if (!Array.prototype.push) {
  Array.prototype.push = function(obj) {
    this[this.length] = obj;
  }
}
function domcheck()
{
	// check if dom is recognized, if not return false;
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	if (!document.getElementsByTagName) return false;
}
function $(id)
{
	return document.getElementById(id);
}

var chosendomains = [];
// step 1 - when 'check' in step 1 is clicked, get the domains and create the tables
function submitstep1()
{
	var domainform = $("domaincheck");
	if (!domainform) return false;
	domainform.onsubmit = function () { return domaincheck();}
}

function domaincheck()
{
	var domain = document.getElementById("newdomain").value.toLowerCase();
	var count = 0;
	if (domain != '')
	{
		var domainarray = domain.split(/[,;\/+\s]+/);
		for (var i=0, dlength = domainarray.length; i<dlength; i++)
		{
			var result = domainarray[i].split(".");

			if (!result[0].match(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/i)) {
				alert('De ingevoerde domeinnaam '+domainarray[i]+' is niet geldig!');
			}
			else if (result[0].length > 62) { alert('De ingevoerde domeinnaam '+domainarray[i]+' is te lang, deze kan maximaal uit 62 karakters bestaan!'); return false; }
			else if (result[0].length < 2) { alert('De ingevoerde domeinnaam '+domainarray[i]+' is te kort, deze moet minimaal 2 karakters zijn!'); return false; }
			else {
				for (var j in chosendomains) {
					if (chosendomains[j] == result[0]) count++;
				}
				if (count == 0) {
					var target = "domaincheck";
					if (typeof tlds == 'undefined') return true;
					step1tldtable(result,target);
					chosendomains.push(result[0]);
				}
			}
		}
		document.getElementById("newdomain").value = '';
	}
	return false;
}

// step 1
function startstep1()
{
	var step1 = $('domaintables');
	if (!step1) return false;

	var alltables = step1.getElementsByTagName('table');
	for (var i=0, tblength = alltables.length; i<tblength; i++) {
		if (alltables[i].className == 'domain') {
			// remember domain
			chosendomains.push(alltables[i].id);

			// check all
			var row = Construct.node('tr', [
				Construct.node('td', {className:'domaintd'}, [
					Construct.node('input', {type:'checkbox', id:'checkalltlds'+alltables[i].id})
				]),
				Construct.node('td', {colSpan:'3',className:'domaintd'}, [
					Construct.node('label', {htmlFor:'checkalltlds'+alltables[i].id}, 'Kies alle')
				])
			]);
			var tablebody = alltables[i].firstChild;
			while (tablebody.nextSibling && tablebody.tagName != 'tbody') {
				tablebody = tablebody.nextSibling;
			}
			tablebody.insertBefore(row, tablebody.firstChild);

			var checkall = $('checkalltlds'+alltables[i].id);
			checkall.onclick = function() {
				var table = get_parent(this, 'table');
				var domain = table.id;
				var checkboxes = table.getElementsByTagName('input');
				for (m=0, clength = checkboxes.length; m<clength; m++) {
					if (checkboxes[m].id.indexOf(domain) != -1) {
						checkboxes[m].checked = (this.checked) ? 'checked' : '';
					}
				}
			}
		}
	}
}

// step 1 - create a table for each chosen domain
function step1tldtable(result,target)
{
	var k;
	var domain = result[0];
	var extension = result[1];
	if (!extension) {
		var extension = '';
	}

	// create the table
	var element = 
	Construct.node('table', {className:'domain', id:domain}, [
		Construct.node('thead', [
			Construct.node('tr', [
				Construct.node('th', {colSpan:'3',className:'domain'}, 'Extensie(s) voor ', [Construct.node('strong', {className:'domain'}, domain)]),
				Construct.node('th', [Construct.node('a', {href:domain,className:'delete-product',id:domain},
					[Construct.node('img', {src:'/layout/custom/dev_bestelwizard/delete.gif'})])
				])
			])
		]),
		Construct.node('tbody', {id:domain+"_tbody"}, [
			Construct.node('tr', [
				Construct.node('td', {className:'domaintd'}, [
					Construct.node('input', {type:'checkbox', id:'checkalltlds'+domain})
				]),
				Construct.node('td', {colSpan:'3',className:'domaintd'}, [
					Construct.node('label', {htmlFor:'checkalltlds'+domain}, 'Kies alle')
				])
			])
		])
	]);
	$('domaintables').appendChild(element);

	// remove a domaintable
	var as = document.getElementsByTagName('a');
	for(i=0, alength = as.length; i < alength; i++) {
		if (as[i].className == 'delete-product') {
			as[i].onclick = function() { arrayremove(chosendomains, this.id); remove(this, 'table', 'dit domein'); return false; };
		}
	}
	// create the tld rows
	for (k in tlds)
	{
		if ((extension != '') && (tlds[k].tld == extension)) {
			var checked = 'checked';
		}
		else {
			checked = '';
		}
		var star = (tlds[k].paymentperiod == "24") ? "*" : "";
		var row = Construct.node('tr', [
			Construct.node('td', {className:'domaintd'}, [
				Construct.node('input', {type:'checkbox', id:domain+"."+tlds[k].tld, name:'domein[stap1]['+domain+']['+tlds[k].tld+']', value:tlds[k].tld, checked:checked})
			]),
			Construct.node('td', {className:'domaintd'}, [
					Construct.node('label', {htmlFor:domain+"."+tlds[k].tld}, domain+"."+tlds[k].tld)
			]),
			Construct.node('td', {className:'price'}, '\u20AC ' + geld(tlds[k].price)),
			Construct.node('td', {className:'domaintd', id:domain + '_status_' + tlds[k].tld},
			[
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/onbekend.gif', alt:'Onbekend', title:'Onbekend'})
			])
		]);

		$(domain+'_tbody').appendChild(row);
		if (checked) {
			$(domain+"."+tlds[k].tld).checked = true;
		}
	}
	// get the status of the checked box and display message when status is taken
	var boxes = document.getElementsByTagName('input');
	var action = '';
	for(var j=0, blength = boxes.length; j<blength; j++) {
		var type = boxes[j].getAttribute("type");
		if (type == 'checkbox' && boxes[j].id.indexOf('checkalltlds') != -1) {
			boxes[j].onclick = function() {
				var table = get_parent(this, 'table');
				var domain = table.id;
				var checkboxes = table.getElementsByTagName('input');
				for (m=0, clength = checkboxes.length; m<clength; m++) {
					if (checkboxes[m].id.indexOf(domain) != -1) {
						checkboxes[m].checked = (this.checked) ? 'checked' : '';
					}
				}
			}
		}
		else if (type == 'checkbox' && boxes[j].id.indexOf('checkalltlds') == -1) {
			boxes[j].onclick = function() {
				if (this.checked) {
					var split = this.id.split('.');
					domain = split[0];
					tld = split[1];
					var status = $(domain+"_status_"+tld).className;
					if (status) {
						status == 'bezet' ? action = confirm('Het domein '+domain+('.')+tld+' is bezet. U kunt alleen een bestelling plaatsen als het domein daadwerkelijk van u is!') : '';
						(status == 'vrij' || status == 'domaintd' || status == 'fout' || action) ? '' : this.checked = false;
					}
				}
			}
		}
	}
	loadContent("/executables/test.inc.php/" + domain);

	// if an error is displayed, remove it
	var domaincheck = $('domaincheck');
	var ps = domaincheck.getElementsByTagName('p');
	for (var l=0, plength = ps.length; l<plength; l++) {
		if (ps[l].className.indexOf('error') != -1) ps[l].parentNode.removeChild(ps[l]);
	}
	return false;
}

// step 1 - remove a php table
function removetable()
{
	var div = document.getElementById("domaintables");
	if (div) {
		var tables = div.getElementsByTagName("a");
		for (var i=0, tlength = tables.length; i < tlength; i++) {
			if (tables[i].className == 'delete-product') {
				tables[i].onclick = function() { arrayremove('chosendomains', this.id); remove(this, 'table', 'dit domein'); return false; }
			}
		}
	}
}

function remove(el, parent, element, row)
{
	var confirmed = confirm_deleting(element);
	if (!confirmed) return false;
	if (row) remove_sibling(row);
	el = get_parent(el, parent);
	el.parentNode.removeChild(el);
	return true;
}

function confirm_deleting(element)
{
	confirmed = confirm('Weet u zeker dat u '+element+' wilt verwijderen?');
	return confirmed;
}

/* Get status with php from all the tld's. Create an image for each status and disable checkboxes if status is taken */
var timer = 0;
function getStatus(tld, content, domeinnaam) {
	var cont = parent.window.document;

	timer++;
	
	var statusCell = cont.getElementById(domeinnaam + '_status_' + tld);
	statusCell.parentNode.className = "statuscell";

	if (statusCell.childNodes[0]) {
		statusCell.removeChild(statusCell.childNodes[0]);
	}

	var a = cont.createElement('a');
	var img = cont.createElement('img');
	img.setAttribute('src', content);
	
	if (content == "exists") { 
		statusCell.className = "bezet";
		img.setAttribute('alt', 'Bezet');
		img.setAttribute('title', 'Bezet');
		img.setAttribute('src', '/layout/custom/dev_bestelwizard/bezet.gif');
		a.setAttribute('href', '/whois.php?domain=' + domeinnaam + '&tld=' + tld);
		a.setAttribute('target', '_blank');
	}
	if (content == "free") { 
		statusCell.className = "vrij";
		img.setAttribute('alt', 'Beschikbaar');
		img.setAttribute('title', 'Vrij');
		img.setAttribute('src', '/layout/custom/dev_bestelwizard/vrij.gif');
	}

	if (content == "error" || content == "invalid") {
		statusCell.className = "fout";
		img.setAttribute('alt', 'Fout');
		img.setAttribute('title', 'Fout');
		img.setAttribute('src', '/layout/custom/dev_bestelwizard/fout.gif');
	}

	if (content == "exists") {
		a.appendChild(img);
		statusCell.appendChild(a);
	}
	else {
		statusCell.appendChild(img);
	}

	var hidden = cont.createElement('input');
	hidden.setAttribute("type", 'hidden');
	hidden.setAttribute("id", 'statusses'+domeinnaam+'.'+tld);
	hidden.setAttribute("name", 'statusses['+domeinnaam+'.'+tld+']');
	hidden.setAttribute("value", content);
	
	statusCell.appendChild(hidden);
}

/* create an iframe for interaction with the server */
function loadContent(src) {
	var style = 'width: 1px; height: 1px; border: 0px;';

	frame = document.createElement('iframe');
	frame.src = src;
	frame.id = 'blaat';
	frame.setAttribute('style', style);

	document.getElementById('hidden_status').appendChild(frame);
}

// step 1 - create the legenda for the domein statusses
function legenda()
{
	var domaindiv = $('domaintables');
	var legenda =
	Construct.node('table', {cellSpacing:0, id:'legenda'}, [
		Construct.node('thead', [
			Construct.node('tr', [
				Construct.node('th', 'Vrij'),
				Construct.node('th', 'Bezet'),
				Construct.node('th', 'Fout'),
				Construct.node('th', 'Onbekend')
			])
		]),
		Construct.node('tbody', [
			Construct.node('tr', [
				Construct.node('td', [
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/vrij.gif', alt:'Vrij', title:'Domein beschikbaar'})
				]),
				Construct.node('td', [
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/bezet.gif', alt:'Bezet', title:'Domeinnaam is al bezet'})
				]),
				Construct.node('td', [
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/fout.gif', alt:'Fout', title:'Er ging iets mis bij het controleren van het domein'})
				]),
				Construct.node('td', [
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/onbekend.gif', alt:'Onbekend', title:'Geen status bekend'})
				])
			])
		])
	]);
	domaindiv.parentNode.insertBefore(legenda, domaindiv);
}

// step 1 - construct the form ending
function createformend()
{
	var check = $('domaincheck');
	if (!check) return false;
	var buttn = $("stap1verder");
	var step = $('stap');
	var bottomdiv = $("bottom");
	if (!buttn) {
		if (!bottomdiv) {
			var frm = Construct.node('form', {method:'post', action:'stap1' , id:'domains'}, [
				Construct.node('div', {id:'domaintables'}),
				Construct.node('div', {id:'bottom'})
			]);
			step.appendChild(frm);
			bottomdiv = $("bottom");
		}

		var submitfunc = function() {submitdomains() && $('domains').submit()};
		var formend2 = Construct.node('p', {className:'rights'}, 'Aan bovenstaande gegevens kunnen geen rechten worden ontleend.');
		var formend3 = Construct.node('p', {className:"kleiner"}, 'De prijzen van een domeinextensie zijn per jaar en zijn exclusief 19% BTW');
		var formend4 = Construct.node('p', {id:'submits'}, [
			Construct.node('input', {name:'send-wizardstap2', type:'hidden', value:'Verder'}),
			Construct.node('input', {type:'submit', className:'button verder', onclick:submitfunc, id:'stap1verder', value:'Verder'})
		]);

		bottomdiv.appendChild(formend2);
		bottomdiv.appendChild(formend3);
		bottomdiv.appendChild(formend4);
	}
	legenda();
}

// step 1 - submit to step 2
function submittostep2()
{
	var step1 = $('domaincheck');
	if (!step1) return false;
	var frm = $("domains");
	frm.onsubmit = function() { return submitdomains(); }
}

function submitdomains()
{
	var step1 = $('domaincheck');
	if (!step1) return false;
	var domaintables = $('domaintables');
	var domains = 0;
	var tables = domaintables.getElementsByTagName("table");
	if (tables)
	{
		for (var i=0, tlength = tables.length; i<tlength; i++)
		{
			if (tables[i].className == 'domain')
			{
				var inputs = tables[i].getElementsByTagName("input");
				for (var j=0, ilength = inputs.length; j<ilength; j++)
				{
					if (inputs[j].getAttribute("type") == 'checkbox') {
						if (inputs[j].checked) domains++;
					}
				}
			}
		}
	}
	
	if (domains == 0)
	{
		var checkdomain = $('checkdomain');
		var parent = checkdomain.parentNode;
		var domainmelding = Construct.node('p', {className:'error'}, 'Om verder te kunnen moet u een domein en een extensie kiezen.');
		step1.insertBefore(domainmelding, parent);
		return false;
	}

	return true;
}

// step 2 - hide product legenda and save changes button - set select.used for used php selects
function startstep2()
{
	var step2 = $('stap2');
	if (!step2) return false;
	var legenda = $('diensten_legenda');
	legenda.className = "structural";
	
	// create removebutton
	var remove_legenda = Construct.node('a', {className:'remove-legenda'});
	var remove_image = Construct.node('img', {src:'/layout/custom/dev_bestelwizard/delete.gif'});
	remove_legenda.appendChild(remove_image);

	var h4 = legenda.getElementsByTagName('h4');
	h4[0].appendChild(remove_legenda);

	var savestep2 = $('opslaan');
	savestep2.parentNode.removeChild(savestep2);
	var i; var tds; var j; var select; var h; var tblength; var tlength; var tdslength;
	
	var tablebuttons = step2.getElementsByTagName('a');
	for (h=0, tblength = tablebuttons.length; h<tblength; h++) {
		if (tablebuttons[h].className == 'delete-table') {
			tablebuttons[h].onclick = function () { remove(this, 'table', 'dit domein'); check_tables(step2); return false;}
		}
	}

	var tbody = step2.getElementsByTagName('tbody');
	for (i=0, tlength = tbody.length; i<tlength; i++) {
		tds = tbody[i].getElementsByTagName('td');
		for (j=0, tdslength = tds.length; j<tdslength; j++) {
			if (tds[j].className == 'product') {
				select = tds[j].getElementsByTagName('select');
				if (select[0].value != '-1') select[0].used = true;
			}
		}
	}
	// create a div for the error notices
	var step = $('stap');
	var errordiv = Construct.node('div', {id:'foutmeldingen'});
	var choice = $('pakketkeuze');
	step.insertBefore(errordiv, choice);
}

function check_tables(step2)
{
	var tables = step2.getElementsByTagName('table');
	var i, tablecount = 0; var tlength;

	for (i=0, tlength = tables.length; i<tlength; i++) {
		if (tables[i].className.indexOf('keuzeoverzicht') != -1) tablecount++;
	}
	if (tablecount == 0) {
		var errordiv = $('foutmeldingen');
		var notice = Construct.node('p', {className:'warn'}, 'Er zijn geen domeinen meer geselecteerd. Ga terug naar stap 1 om opnieuw te beginnen.');
		errordiv.appendChild(notice);
	}
}

// step 2 - submit to step 2
function showlegenda()
{
	var step2 = $('stap2');
	if (!step2) return false;
	var legenda = $('diensten_legenda');
	var tbody = step2.getElementsByTagName('tbody');

	for (var i=0, tlength = tbody.length; i<tlength; i++)
	{
		var domain = tbody[i].id;
		var choicefield = $('choice'+domain);
		choicefield.appendChild(
			Construct.node('span', [
				Construct.node('a', {className:'info'}, [
					Construct.node('img', {src:'/layout/custom/dev_bestelwizard/info.gif', alt:'Keuze informatie', title:'Keuze informatie'})
				])
			])
		);
	}
	var as = document.getElementsByTagName('a');
	for(var j=0, alength = as.length; j < alength; j++) {
		if (as[j].className == 'info') {
			as[j].onclick = function() {
				var table = get_parent(this, 'tbody');
				var tabledomain = table.id;
				var tablelegenda = $('diensten_legenda_'+tabledomain);
				if (tablelegenda) {
					tablelegenda.className = (tablelegenda.className == "structural") ? "diensten kleiner" : "structural";
				} else {
					var legendaclone = legenda.cloneNode(true);
					legendaclone.id = 'diensten_legenda_'+tabledomain;
					this.parentNode.appendChild(legendaclone);
					legendaclone.className = "diensten kleiner";
					var legenda_as = legendaclone.getElementsByTagName('a');
					for (var a=0, lalength = legenda_as.length; a<lalength; a++) {
						if (legenda_as[a].className == 'remove-legenda') {
							legenda_as[a].onclick = function () {
								var parent = get_parent(this, 'div');
								parent.className = "structural";
							}
						}
					}
				}
			}
		}
	}
}

// step 2 - add a new select row to a domaintable
function selectonclick()
{
	var step2 = $('stap2');
	if (!step2)	return false;
	var i; var j; var tds; var select; var tlength; var tdlength; var domain;

	var tbody = step2.getElementsByTagName("tbody");
	for(i=0, tlength = tbody.length; i<tlength; i++) {
		domain = tbody[i].id;
		tds = tbody[i].getElementsByTagName('td');
		for (j=0, tdlength = tds.length; j<tdlength; j++) {
			if (tds[j].className == 'product') {
				select = tds[j].getElementsByTagName("select")[0];
				select.onchange = function() { change_product_select(this); }
			}
			else if (tds[j].className == 'aantal') {
				select = tds[j].getElementsByTagName("select")[0];
				if (select) select.onchange = function() { change_price(this); calculation(domain); }
			}
			else if (tds[j].className == 'contractperiode') {
				select = tds[j].getElementsByTagName("select")[0];
				if (select) select.onchange = function() { change_contractperiodrow(this); calculation(domain); }
			}
			else if (tds[j].className == 'betaalperiode') {
				select = tds[j].getElementsByTagName("select")[0];
				if (select) select.onchange = function() { change_paymentperiodrow(this); calculation(domain); }
			}
		}
	}
}

// step 2 - a product is chosen from the select
function change_product_select(select) 
{
	if (select.value == -1) return false;
	
	var relations;
	var tbody = get_parent(select, 'tbody');
	var domain = tbody.id;
	var tablerow = get_parent(select, 'tr');
	if (!select.used) {	
		select.used = true;
		relations = update_package_row(tablerow, domain, select, false);
		if (select.firstChild.value == -1) {
			select.removeChild(select.firstChild);
		}
	}
	else {
		relations = update_package_row(tablerow, domain, select, true);
	}
	var x; var count = 0;
	for (x in relations) { count++;}
	if (count>0) {
		create_package_row(tbody, domain, relations, false);
	}
}

// step 2 - get the products that can be used in a new productselect
function get_relations(select)
{
	var products = {};
	for (var j = 0, slength = select.options.length; j < slength; j++) {
		if (select.options[j].value == -1) continue;
		products[select.options[j].value] = select.options[j].value;
	}
	for (var k = 0, rlength = relation[select.value].length; k < rlength; k++) {
		delete products[relation[select.value][k]];
	}
	return products;
}

// step 2 - create a new package row 
function create_package_row(table, domain, products, selectedid)
{
	var select = Construct.node('select', {className:'select', name:'domein[' + domain + '][pakketten][new]'}, [
		Construct.node('option', {value:'-1'}, 'Selecteer')
	]);
	select.onchange = function() { change_product_select(this); };

	for (var p in products) {
		select.appendChild(Construct.node('option', {value:product[p].id}, product[p].product));
	}

	var a = Construct.node('a', {href:domain,className:'delete-product'}, 'Verwijder');

	var tablerow = Construct.node('tr', {className:'pakket'}, [
		Construct.node('td', {className:'product'}, [
			select
		]),
		Construct.node('td', {className:'aantal'}),
		Construct.node('td', {className:'contractperiode'}),
		Construct.node('td', {className:'betaalperiode'}),
		Construct.node('td', {className:'prijs'}),
		Construct.node('td', {className:'period'}),
		Construct.node('td', [
			a
		])
	]);
	a.onclick = function() {
		var row = get_parent(this, 'tr');
		remove_step2_tablerow(this, row, table, domain, products, selectedid);
		calculation(domain);
		return false;
	}
	table.appendChild(tablerow);
}

// step 2 - remove a row and its siblings then recalculate and create a new row
function remove_step2_tablerow(button, row, table, domain, products, id)
{
	var confirmed = remove(button, 'tr', 'dit pakket', row);
	if (confirmed) {
		calculation(domain);
		create_package_row(table, domain, products, id);
	}
}

// step 2 - update the row when a package is changed
function update_package_row(row, domain, select, delete_siblings)
{
	var id = select.value;
	var classname;
	var amountrow;
	var relations;
	var months = document.createTextNode('');
	var classes = ['aantal', 'contractperiode', 'betaalperiode', 'prijs', 'period'];
	if (select.used) {
		// remove children of tds with class aantal, contractperiode, betaalperiode en prijs
		var tds = row.getElementsByTagName('td');
		for (var i=0, tlength = tds.length; i<tlength; i++) {
			for (classname in classes) {
				if (tds[i].className == classes[classname]) {
					while (tds[i].firstChild) {
						tds[i].removeChild(tds[i].firstChild);
					}
				}
			}
		}
		if (row.nextSibling) {
			if (row.nextSibling.className == 'extrainfo') {
				row.parentNode.removeChild(row.nextSibling);}
		}
	}
	// update the row
	var per;
	var j;
	(product[id].priceperiod == 1) ? per = 'p/m' : per = 'p/j';
	var amount = product[id].price / (product[id].priceperiod == 1 ? 1 : 12);
	var price = document.createTextNode('\u20AC'+geld(amount));

	if (parseFloat(product[id].quantitymax) > parseFloat(product[id].quantitydefault)) {
		amountrow = Construct.node('select', {name:'domein[' + domain + '][pakketten][' + id + '][aantal]'});
		var dcount = product[id].quantitydefault;
		var amountarray = [];
		amountarray.push('0');
		while (parseFloat(dcount) <= parseFloat(product[id].quantitymax)) {
			 amountarray.push(dcount);
			 dcount = parseFloat(dcount) + parseFloat(product[id].quantitystep);
		}
		amountarray.splice(0,1);
		create_dropdown(amountarray, amountrow);
		amountrow.onchange = function() { change_price(this); calculation(domain); };
	}
	else {
		amountrow = Construct.node('input', {type:'text',size:'3', name:'domein['+domain+'][pakketten]['+id+'][aantal]', value:product[id].quantitydefault, disabled:'disabled'});
	}
	
	var hidden = Construct.node('input', {type:'hidden', name:'domein[' + domain + '][pakketten][' + id + '][0]', value:id});
	
	var contractperiodrow = Construct.node('select', {id:'contractperiode', name:'domein[' + domain + '][pakketten][' + id + '][contractperiode]'});
	contractperiodrow.onchange = function() { change_contractperiodrow(this); calculation(domain); }
	cdisabled = selectrow(product[id].contractperiod, contractperiodrow);
	
	var paymentperiodrow = Construct.node('select', {id:'betaalperiode', name:'domein[' + domain + '][pakketten][' + id + '][betaalperiode]'});
	paymentperiodrow.onchange = function() { change_paymentperiodrow(this); calculation(domain); }
	bdisabled = selectrow(product[id].paymentperiod, paymentperiodrow);

	var a = 
	Construct.node('a', {href:domain,className:'delete-product'}, 'Verwijder');
	a.onclick = function() {
		relations = {};
		for (x in product) { relations[x] = x; }
		var table = get_parent(row, 'tbody');
		remove_step2_tablerow(this, row, table, domain, relations, id);
		return false;
	}

	var inforow = create_extrainfo(row, domain, id);

	var tds = row.getElementsByTagName("td");
	for (var l=0, tdlength = tds.length; l<tdlength; l++) {
		if (tds[l].className == 'aantal') {
			tds[l].appendChild(amountrow);
		}
		if (tds[l].className == 'contractperiode') {
			tds[l].appendChild(contractperiodrow);
			tds[l].appendChild(months);
			if (cdisabled == 'disabled') contractperiodrow.setAttribute('disabled', "disabled");
		}
		if (tds[l].className == 'betaalperiode')	{
			tds[l].appendChild(paymentperiodrow);
			tds[l].appendChild(months);
			if (bdisabled == 'disabled') paymentperiodrow.setAttribute('disabled', "disabled");
		}
		if (tds[l].className == 'prijs') {
			tds[l].appendChild(price);
			tds[l].appendChild(hidden);
		}
		if (tds[l].className == 'period') {
			tds[l].appendChild(document.createTextNode('p/m'));
		}
		if (tds[l].className == 'delete-product') {
			tag = tds[l].getElementsByTagName('a');
			if (!tag[0]) tds[l].appendChild(a);
		}
	}
	// relations ophalen voor eventueel nieuwe row
	relations = get_relations(select);
	if (delete_siblings) { // remove all siblings after the new extrainforow/row
		remove_sibling((inforow ? inforow : row), relations);
	}
	calculation(domain);
	return relations;
}

// step 2 - when the contractperiodrow changes make sure paymentperiodrow isn't higer
function change_contractperiodrow(select)
{
	var parent = select.parentNode.parentNode;
	var rows = parent.getElementsByTagName('td');
	var rl = rows.length;
	for (i=0; i<rl; i++)
	{
		if (rows[i].className == 'betaalperiode')
		{
			var paymentperiodrow = rows[i];
		}
	}
	var selects = paymentperiodrow.getElementsByTagName('select');
	var paymentselect = selects[0];
	if (parseFloat(paymentselect.value) > parseFloat(select.value)) { 
		paymentselect.value = select.value;
	}
}

// step 2 - contractperiod not smaller then paymentperiod
function change_paymentperiodrow(select)
{
	var parent = select.parentNode.parentNode;
	var rows = parent.getElementsByTagName('td');
	var rl = rows.length;
	for (i=0; i<rl; i++)
	{
		if (rows[i].className == 'contractperiode')
		{
			var contractperiodrow = rows[i];
		}
	}
	var selects = contractperiodrow.getElementsByTagName('select');
	var contractselect = selects[0];
	if (parseFloat(contractselect.value) < parseFloat(select.value)) { 
		contractselect.value = select.value;
	}
}

// step 2 - changes the price for products with a varying amount
function change_price(amountdropdown)
{
	var amount = parseFloat(amountdropdown.value);
	var parent = get_parent(amountdropdown, 'tr');
	var tds = parent.getElementsByTagName('td');
	for (var i=0, tdlength = tds.length; i<tdlength; i++) {
		if (tds[i].className == 'product') {
			var select = tds[i].getElementsByTagName('select');
			var id = select[0].value;
		}
		if (tds[i].className == 'prijs') {
			if (tds[i].firstChild.nodeType == 3) {
				tds[i].removeChild(tds[i].firstChild);
				var productprice = parseFloat(product[id].price)*100;
				var price = Math.round(productprice * amount)/100;
				var pricetext = document.createTextNode('\u20AC'+geld(price));
				tds[i].insertBefore(pricetext, tds[i].lastChild);
			}
		}
	}
}

// step 2 - creates an extra inforow with productchoices (inputs or radios)
function create_extrainfo(row, domain, id)
{
	// loop through choicesets
	var i;
	var count = 0;
	var title;
	var p;
	var j;
	var td = Construct.node('td', {colSpan:'7'});
	var choices;
	var label, radio;
	
	for (i in choicesets) {
		if (choicesets[i].productid == id) {
			if (choicesets[i].choiceset == 'f') { //create text input
				p = Construct.node('p');
				p.id = domain+'.'+choicesets[i].id;
				label = Construct.node('label', {htmlFor:domain+choicesets[i].id}, choicesets[i].title + ':');
				p.appendChild(label);
				p.appendChild(Construct.node('input', {type:'text', name:'domein[' + domain + '][pakketten][' + id + '][keuzeset]['+choicesets[i].id+']', id:domain+choicesets[i].id}));
				td.appendChild(p);
				count++;
			}
			else { //create radio(s)
				title = Construct.node('span', {className:'label'}, choicesets[i].title + ':');
				p = Construct.node('p');
				p.id = domain+'.'+choicesets[i].id;
				p.appendChild(title);
				choices = choicesets[i].choices.split(';');
				var firstradio = 0;
				for (j in choices) {
					try {
						var rchecked = (firstradio == 0) ? 'checked="checked" ' : '' ;
						radio = document.createElement('<input type="radio" name="domein[' + domain + '][pakketten][' + id + '][keuzeset][' + choicesets[i].id + ']" value="' + choices[j] + '" id="' + domain+choices[j] + '" ' + rchecked + '/>');
					}
					catch (e) {
						radio = Construct.node('input', {type:'radio', name:'domein[' + domain + '][pakketten][' + id + '][keuzeset]['+choicesets[i].id+']', value:choices[j], id:domain+choices[j]});
						if (firstradio == 0) radio.checked = true;
					}
					var txt = document.createTextNode(choices[j]);
					label = Construct.node('label', {className:'radio',htmlFor:domain+choices[j]});
					label.appendChild(radio);
					label.appendChild(txt);
					p.appendChild(label);
					firstradio++;
				}
				td.appendChild(p);
				count++;
			}
		}
	}
	// insert before row.nextSibling
	if (count > 0) {
		var extrainforow =	Construct.node('tr', {className:'extrainfo'}, [
			td
		]);
		row.parentNode.insertBefore(extrainforow, row.nextSibling);
	}
	return extrainforow;
}

function selectrow(select, appendrow)
{
	select = select.split(",");
	for (var k=0, slength = select.length; k<slength; k++) {
		if (k==select.length-1) var sselected = '"selected"';
		if (select.length==1) var sdisabled = "disabled";
		var row = Construct.node('option', {value:select[k], selected:sselected}, select[k] + ' maanden');
		appendrow.appendChild(row);
	}
	return sdisabled;
}

// step 2 - when ordertype is changed, recalculate prices
function ordertype()
{
	var step2 = $('stap2');
	if (!step2) return false;
	var inputs = step2.getElementsByTagName("input");
	var h; var ilength;
	for (h=0, ilength = inputs.length; h<ilength; h++) {
		if (inputs[h].getAttribute("type") == "radio") {
			inputs[h].onclick = function () {
				var tbody = get_parent(this, 'tbody');
				/*
				var tfoot = $('prices_'+tbody.id);
				var trs = tfoot.getElementsByTagName('tr');
				for (var m=0, trslength = trs.length; m<trslength; m++) {
					if (trs[m].className.indexOf("domainprice") != -1) {
						trs[m].className = (this.id == tbody.id+".extra_diensten") ? "domainprice structural" : "domainprice";
					}
				}
				*/
				calculation(tbody.id);
			}
		}
	}
}

// step 2 - calculate the discount 
function calculate_discount(id, contractperiod, type) 
{
	var hosting = [1,2,3,4,6,7,8];
	var j;
	for (j in hosting) {
		if (hosting[j] == id && contractperiod == 12) {
			var discount = (type == 'tld') ? 14.95 : (type == 'hosting') ? parseFloat(product[id].price) * parseFloat(3) : '' ;
		}
	}
	if (discount) return discount;
}

function get_ordertype(tbody)
{
	if (!tbody) return false;
	var tr = tbody.getElementsByTagName('tr');
	var i; var trlength = tr.length; var h; var ilength;
	for (i=0; i<trlength; i++){
		if (tr[i].className.indexOf('ordertype') != -1) {
			var inputs = tr[i].getElementsByTagName("input");
			for (h=0, ilength = inputs.length; h<ilength; h++) {
				if (inputs[h].checked) {
					var ordertype = inputs[h].id;
				}
			}
			return ordertype;
		}
	}
}

// step 2 - calculate the prices for a domain table
function calculation(domain)
{
	var tbody = $(domain);
	var tldprice;
	var quarterprice = 0;
	var yearprice = 0;
	var discountamount = 0;
	var ordertype = get_ordertype(tbody);
	if (ordertype == domain+".extra_diensten") {
		var m;
		tldprice = 0;
	}
	else {
		var m;
		var split = domain.split('.');
		var tld = split[1];
		for (m in tlds) {
			if (tlds[m].tld == tld) {
				tldprice = tlds[m].price;
			}
		}
	}
	var products = [];
	
	var k; var tds; var i; var value; var amountdrop; var amountinput; var amount; 
	var paymentdrop; var paymentp; var contractdrop; var contractp; var price; var subtotal; var discount; var monthprice; 
	var q; var domainpricetds; var trslength; var tdslength;

	if (ordertype != domain+".verhuizen") {
		vprice = 0;
	}
	else {
		vprice = 14.95;
	}

	var trs = tbody.getElementsByTagName("tr");
	for (k=0, trslength = trs.length; k<trslength; k++)
	{
		if (trs[k].className.indexOf("pakket") != -1)
		{
			tds = trs[k].getElementsByTagName("td");
			for (i=0, tdslength = tds.length; i<tdslength; i++)
			{
				if (tds[i].className == "product") {
					value = tds[i].getElementsByTagName("select")[0].value;
					products.push(value);
				}
				if (value != -1) {
					price = product[value].price;
					if (tds[i].className.indexOf("aantal") != -1) {
						amountdrop = tds[i].getElementsByTagName('select')[0];
						amountinput = tds[i].getElementsByTagName('input');
						amount = amountdrop ? parseFloat(amountdrop.value) : parseFloat(amountinput[0].value);
					}
					if (tds[i].className.indexOf("betaalperiode") != -1) {
						paymentdrop = tds[i].getElementsByTagName('select');
						paymentp = paymentdrop[0].value;
					}
					if (tds[i].className.indexOf("contractperiode") != -1) {
						contractdrop = tds[i].getElementsByTagName('select');
						contractp = contractdrop[0].value;
					}
				}
			}
			
			if (specialoffers[value]) { // calculate discount
				if ((specialoffers[value].mincontract == contractp || specialoffers[value].mincontract > contractp) && (specialoffers[value].minpayment == paymentp || specialoffers[value].minpayment > paymentp))
				{
					var datum = new Date();
					var today = new Date();
					var startdate = specialoffers[value].startdate.split(",");
					var enddate = specialoffers[value].enddate.split(",");
					var newstartdate = datum.setFullYear(startdate[0],startdate[1],startdate[2]);
					var newenddate = datum.setFullYear(enddate[0],enddate[1],enddate[2]);

					if (((newstartdate < today) || (startdate[0] == '1970')) && ((newenddate > today) || (enddate[0] == '1970')))
					{
						// is de datum tussen de start en einddatum?
						if (specialoffers[value].discountmonths) {
							if (parseFloat(specialoffers[value].discountmonths) < parseFloat(paymentp)) {
								if (product[value].priceperiod == "1") {
									monthprice = parseFloat(product[value].price);
								}
								else if (product[value].priceperiod == "12") {
									monthprice = parseFloat(product[value].price) / parseFloat(12);
								}
								discount = parseFloat(monthprice) * parseFloat(specialoffers[value].discountmonths);
							}
						}
						if (specialoffers[value].offerprice != "" && specialoffers[value].offerprice != 0) {
							discount = parseFloat(specialoffers[value].offerprice);
						}
					}
				}
			}
			// verhuiskosten
			if (vprice != 0) {
				for (var i=0; i<products.length; i++) {
					if (product[products[i]] && product[products[i]].notransfercosts) {
						vprice = 0;
						break;
					}
				}
			}

			if (value == -1) continue;
			if (product[value].priceperiod == "12") {
				subtotal = parseFloat(amount) * parseFloat(price);
			} else {
				subtotal = parseFloat(amount) * (parseFloat(paymentp) * parseFloat(price));
			}
			var hostingdiscount = '';
			hostingdiscount = calculate_discount(value, contractp, 'hosting');
			if (discount) subtotal = parseFloat(subtotal) - parseFloat(discount);
			if (hostingdiscount) discountamount = discountamount + parseFloat(hostingdiscount);
			if (paymentp == 3) {
				quarterprice = parseFloat(quarterprice) + parseFloat(subtotal);
			} else if (paymentp == 12) {
				yearprice = parseFloat(yearprice) + parseFloat(subtotal);
			}
			if (!tlddiscount) var tlddiscount = calculate_discount(value, contractp, 'tld');
		}
	}
	if (tlddiscount && (parseFloat(tldprice) > parseFloat(0))) tldprice = parseFloat(tldprice) - parseFloat(tlddiscount);
	yearprice = parseFloat(yearprice) + parseFloat(tldprice);
	if (ordertype == domain+".verhuizen" && vprice == 0) {
		vprice = 'gratis';
	}
	// display the prices at the bottom of the table
	var tfoot = $('prices_'+tbody.id);
	var trs = tfoot.getElementsByTagName('tr');
	for (var m=0, tl = trs.length; m<tl; m++) {
		if (trs[m].className == "yprices") {
			var tds = trs[m].getElementsByTagName('td');
			for (var p=0, tlh = tds.length; p<tlh; p++) {
				if (tds[p].className == "txt") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(yearprice) > parseFloat(0)) {
						var yearrow = document.createTextNode('Te betalen per jaar:');
						tds[p].appendChild(yearrow);
					}
				}
				else if (tds[p].className == "prijzen") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(yearprice) > parseFloat(0)) {
						var yearrow = document.createTextNode('\u20AC' + geld(yearprice));
						tds[p].appendChild(yearrow);
					}
				}
			}
		}
		else if (trs[m].className == "qprices") {
			var tds = trs[m].getElementsByTagName('td');
			for (var p=0, tlh = tds.length; p<tlh; p++) {
				if (tds[p].className == "txt") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(quarterprice) > parseFloat(0)) {
						var quarterrow = document.createTextNode('Te betalen per kwartaal:');
						tds[p].appendChild(quarterrow);
					}
				}
				else if (tds[p].className == "prijzen") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(quarterprice) > parseFloat(0)) {
						var quarterrow = document.createTextNode('\u20AC' + geld(quarterprice));
						tds[p].appendChild(quarterrow);
					}
				}
			}
		}
		else if (trs[m].className == "vprices") {
			var tds = trs[m].getElementsByTagName('td');
			for (var p=0, tlh = tds.length; p<tlh; p++) {
				if (tds[p].className == "txt") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(vprice) > parseFloat(0)) {
						var transferrow = document.createTextNode('Eenmalig:');
						tds[p].appendChild(transferrow);
					}
				}
				else if (tds[p].className == "prijzen") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(vprice) > parseFloat(0)) {
						var transferrow = document.createTextNode('\u20AC' + geld(vprice));
						tds[p].appendChild(transferrow);
					}
				}
			}
		}
		else if (trs[m].className == "discount") {
			var tds = trs[m].getElementsByTagName('td');
			for (var p=0, tlh = tds.length; p<tlh; p++) {
				if (tds[p].className == "txt") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(discountamount) > parseFloat(0)) {
						var discountrow = document.createTextNode('Korting 1e jaar:');
						tds[p].appendChild(discountrow);
					}
				}
				else if (tds[p].className == "prijzen") {
					while (tds[p].firstChild) {
						tds[p].removeChild(tds[p].firstChild);
					}
					if (parseFloat(discountamount) > parseFloat(0)) {
						var discountrow = document.createTextNode('\u20AC' + geld(discountamount));
						tds[p].appendChild(discountrow);
					}
				}
			}
		}
		else if (trs[m].className.indexOf("domainprice") != -1) {
			trs[m].className = ordertype == domain+".extra_diensten" ? 'domainprice empty' : 'domainprice';
			var td;
			domainpricetds = trs[m].getElementsByTagName('td');
			for (var q=0, dtl = domainpricetds.length; q<dtl; q++)
			{
				td = domainpricetds[q];
				if (ordertype == domain+".extra_diensten") {
					while (td.firstChild) {
						td.removeChild(td.firstChild);
					}
				} else {
					if (td.className == 'domeinprijs') {
						if (parseFloat(tldprice) == 0) {
							create_tldtext(td, 'gratis');
						} else {
							create_tldtext(td, '\u20AC' + geld(tldprice));
						}
					} else if (td.className == 'betaaltermijn') {
							create_tldtext(td, '12 maanden');
					} else if (td.className == 'txt') {
							create_tldtext(td, '.' + tld + ' domeinregistratie');
					} else if (td.className == 'period' && parseFloat(tldprice) != 0) {
							create_tldtext(td, 'p/j');
					}
				}
			}
		}
		else if (trs[m].className.indexOf("transferprice") != -1) {
			trs[m].className = vprice == 0 ? 'transferprice empty' : 'transferprice';
			var td;
			domainpricetds = trs[m].getElementsByTagName('td');
			for (var q=0, dtl = domainpricetds.length; q<dtl; q++)
			{
				td = domainpricetds[q];
				if (vprice == 0) {
					while (td.firstChild) {
						td.removeChild(td.firstChild);
					}
				} else {
					if (td.className == 'domeinprijs') {
						create_tldtext(td, vprice == 'gratis' ? vprice : '\u20AC' + geld(tldprice));
					} else if (td.className == 'betaaltermijn') {
							create_tldtext(td, 'eenmalig');
					} else if (td.className == 'txt') {
							create_tldtext(td, 'Verhuizen domein');
					}
				}
			}
		}
	}
}

// step 2 - create textnode with tldprice
function create_tldtext(td, text)
{
	while (td.firstChild) {
		td.removeChild(td.firstChild);
	}
	var tldtext = document.createTextNode(text);
	td.appendChild(tldtext);
}

// stap 2 - check input on submit to step 3
function submittostep3()
{
	var stap2 = $('stap2');
	if (!stap2) return false;
	var submit = $('send-wizardstap3');
	var notices;
	submit.onclick = function() { notices = submitstep2(stap2); if (notices == false) return false; }
}

function submitstep2(stap2)
{
	var products, selects, productrows, i, j, tds, k, productselect, contractperiodselect, paymentperiodselect, paragraph, l, choicesetid, m, checked, choices, tl, pl, tdl;
	var step = $('stap');
	clear_step2_notices(step);
	var notice = 0;
	var tbody = stap2.getElementsByTagName("tbody");
	for (i=0, tl = tbody.length; i<tl; i++)
	{
		domain = tbody[i].id;
		products = 0;
		productrows = tbody[i].getElementsByTagName('tr');
		for (j=0, pl = productrows.length; j<pl; j++)
		{
			if (productrows[j].className == "pakket") {
				tds = productrows[j].getElementsByTagName('td');
				for (k=0, tdl = tds.length; k<tdl; k++) {
					if (tds[k].className == "product") {
						productselect = tds[k].getElementsByTagName("select");
						if (productselect[0].value != '-1') {
							products++;
						} else continue;
					}
					if (tds[k].className == "contractperiode") {
						contractperiodselect = tds[k].getElementsByTagName("select");
					}
					if (tds[k].className == "betaalperiode") {
						paymentperiodselect = tds[k].getElementsByTagName("select");
					}
				}
				if (contractperiodselect[0]) {
					if (parseFloat(contractperiodselect[0].value) < parseFloat(paymentperiodselect[0].value)) {
						notice = step2notice(productrows[j], 'De betaalperiode kan niet hoger zijn dan de contractperiode.', notice);
					}
				}
			}
			if (productrows[j].className == "extrainfo") {
				notice = check_choicesets(productrows[j], notice);
			}
			if (productrows[j].className == 'ordertype') ordertyperow = productrows[j];
		}
		var ordertype = get_ordertype(tbody[i]);
		if (!ordertype) notice = step2notice(ordertyperow, 'Wilt u het domein '+domain+' verhuizen of uitbreiden met extra diensten?', notice);
		if (products == 0 && (ordertype == domain+'.extra_diensten')) {
			notice = step2notice(tbody[i], 'U hebt nog niet overal een pakket geselecteerd.', notice);
		}
	}
	if (notice > 0) return false;
}

function clear_step2_notices(step) 
{
	// find the error notices, and clear it
	var errordiv = $('foutmeldingen');
	while (errordiv.firstChild) errordiv.removeChild(errordiv.firstChild);

	// clear all error classes
	remove_errorclass(step, 'tr');
	remove_errorclass(step, 'table');
}

function remove_errorclass(step, element)
{
	var els = step.getElementsByTagName(element);
	var j, el;
	for (j=0, el = els.length; j<el; j++) {
		if (els[j].className.indexOf('error') != -1) {
			var errorclass = els[j].className;
			els[j].className = errorclass.replace(' error', '');
		}
	}
}

function step2notice(row, text, notice) 
{
	var errordiv = $('foutmeldingen');
	if (row) row.className += ' error';
	var noticetext = Construct.node('p', {className:'warn'}, text);
	errordiv.appendChild(noticetext);
	notice++;
	return notice;
}

// step 2 - check if required choicesets have a value
function check_choicesets(row, notice) 
{
	paragraph = row.getElementsByTagName('p');
	var l, pl, m, cl;
	for (l=0, pl = paragraph.length; l<pl; l++) {
		choicesetid = paragraph[l].id.split('.');
		if (choicesets[choicesetid[2]].required == "t") {
			choices = paragraph[l].getElementsByTagName('input');
			if (choicesets[choicesetid[2]].choiceset == "f") {
				if (choices[0].value == '') { notice = step2notice(row, 'U moet nog enkele keuzes maken.', notice); }
				else { notice = validate_choiceset(choices[0].value, choicesets[choicesetid[2]].validationtype, row, notice); }
			} else {
				checked = 0;
				for (m=0, cl = choices.length; m<cl; m++) {
					if (choices[m].checked) checked++;
				}
				if (checked == 0) notice = step2notice(row, 'U moet nog enkele keuzes maken.', notice);
			}
		}
	}
	return notice;
}

function validate_choiceset(input, validationtype, row, notice)
{
	if (validationtype == 'e-mail') {
		var at = input.indexOf("@");
		var dot = input.indexOf(".");
		if ((input.length<10) || (at == -1) || (dot == -1)) { notice = step2notice(row, 'Het ingevulde e-mailadres voldoet niet aan het formaat naam@domein.extensie', notice); }
	}
	if (validationtype == 'website') {
		//
	}
	return notice;
}

// step 3 - create a new personal data form
function frm()
{
	var step3 = $('stap3');
	if (!step3) {
		var changeaccount = $('changeaccount');
		if (!changeaccount) return false;
	}

	var factuur = $('factuur');
	if (!factuur)
	{
		var persoonsgegevens = $('persoonsgegevens');

		// maak een checkbox aan
		var checkbox1 = Construct.node('p', [
			Construct.node('label', {htmlFor:'admincheck'}, [
				Construct.node('input', {
					type:'checkbox',
					className:'checkbox',
					name:'admincheck',
					id:'admincheck',
					onclick:checkcontacts,
					checked:$('Administratief_contactfirstnameinitials').value != ''
				}),
				document.createTextNode(' Afwijkend administratief contact')
			])
		]);
		var checkbox2 = Construct.node('p', [
			Construct.node('label', {htmlFor:'factuurcheck'}, [
				Construct.node('input', {
					type:'checkbox',
					className:'checkbox',
					name:'factuurcheck',
					id:'factuurcheck',
					onclick:checkcontacts,
					checked:$('Factuurgegevensfirstnameinitials').value != ''
				}),
				document.createTextNode(' Afwijkend factuuradres')
			])
		]);
		var checkbox3 = Construct.node('p', [
			Construct.node('label', {htmlFor:'techcheck'}, [
				Construct.node('input', {
					type:'checkbox',
					className:'checkbox',
					name:'techcheck',
					id:'techcheck',
					onclick:checkcontacts,
					checked:$('Technisch_contactfirstnameinitials').value != ''
				}),
				document.createTextNode(' Afwijkend technisch contact')
			])
		]);

		var fieldset = persoonsgegevens.getElementsByTagName('fieldset')[0];
		fieldset.appendChild(checkbox1);
		fieldset.appendChild(checkbox2);
		fieldset.appendChild(checkbox3);

		checkcontacts();
	}
}

function checkcontacts()
{
	$('Administratief_contact').style.display = $('admincheck').checked ? 'block' : 'none';
	$('Factuurgegevens').style.display = $('factuurcheck').checked ? 'block' : 'none';
	$('Technisch_contact').style.display = $('techcheck').checked ? 'block' : 'none';
}

// step 3 - show or hide a second personal information form
function login_account()
{
	var step3 = $('stap3');
	if (!step3) return false;

	var persg = $('persoonsgegevens');
	var errordiv = Construct.node('div', {id:'foutmeldingen'});
	step3.insertBefore(errordiv,persg);

	var login_mini = $('login_mini');
	if (!login_mini) return false;
	if (login_mini.className != 'fout') login_mini.className = 'structural';

	var account = $('account');
	account.className = 'structural';

	var p = Construct.node('p');
	p.appendChild(document.createTextNode('Heeft u een account? '));
	var a1 = Construct.node('a', {href:'', className:'login'}, 'Log in');
	a1.onclick = function() 
	{
		var jslogin = $('login_mini');
		if (jslogin) {
			jslogin.className = (jslogin.className == 'structural') ? '' : 'structural';
		}
		return false;
	}
	p.appendChild(a1);

	p.appendChild(Construct.node('br'));
	p.appendChild(document.createTextNode('Heeft u nog geen account? '));
	var a2 = Construct.node('a', {href:'', className:'account'}, 'Meld u hier aan *');
	a2.onclick = function() 
	{
		var jsaccount = $('account');
		if (jsaccount) {
			jsaccount.className = (jsaccount.className == 'structural') ? '' : 'structural';
		}
		return false;
	}
	p.appendChild(a2);

	var step = $('stap');
	step.insertBefore(p,login_mini);
}

// step 3 - add copy button
function step3copy()
{
	var step3 = $('stap3');
	if (!step3) return false;

	var formfields = [
		'company',
		'firstnameinitials',
		'nameextra',
		'lastname',
		'street',
		'number',
		'extension',
		'address2',
		'zipcode',
		'place',
		'country',
		'phonenumber',
		'email'
	];

	var contacts = ['Administratief_contact', 'Factuurgegevens', 'Technisch_contact'];
	for (n in contacts) {
		var b = Construct.node('button', {name:'copyformdata', id:'copyformdata'}, [ document.createTextNode('Kopieer') ])
		try {
			// ie doesn't know type button...
			b.type = 'button';
		}
		catch (e) {}
		b.onclick = function () {
			var target = this.parentNode.parentNode.id;
			var source = this.parentNode.getElementsByTagName('select')[0].value;
			if (!source) return;

			for (i in formfields) {
				$(target+formfields[i]).value = $(source+formfields[i]).value;
			}
			$(target+'male').checked = $(source+'male').checked;
			$(target+'female').checked = $(source+'female').checked;
			var elements = $(target).getElementsByTagName('label');
			for (i in elements) {
				if (elements[i].className) {
					elements[i].className = elements[i].className.replace(/ ?error/, '');
				}
			}
			var elemnts = $(target).getElementsByTagName('input');
			for (i in elemnts) {
				if (elemnts[i].className) {
					elemnts[i].className = elemnts[i].className.replace(/ ?error/, '');
				}
			}
			return false;
		};
		var s = Construct.node('select', [
			Construct.node('option', {value:'Domeinhouder'}, [ document.createTextNode('Domeinhouder') ]),
			Construct.node('option', {value:'Administratief_contact'}, [ document.createTextNode('Administratief contact') ]),
			Construct.node('option', {value:'Factuurgegevens'}, [ document.createTextNode('Factuurgegevens') ]),
			Construct.node('option', {value:'Technisch_contact'}, [ document.createTextNode('Technisch contact') ])
		]);
		var children = s.getElementsByTagName('option');
		for (c in children) {
			if (children[c] && children[c].value == contacts[n]) {
				s.removeChild(children[c]);
			}
		}
		var par = Construct.node('p', {className:'copybutton'}, [ document.createTextNode('Kopieer gegevens van: ') ]);
		par.appendChild(s);
		par.appendChild(b);

		$(contacts[n]).appendChild(par);
	}
}

// step 3 - check the personal data form input
function step3forms()
{
	var step3 = $('stap3');
	if (!step3) return false;
	var submit = $('send-wizardstap4');
	var notices;
	//step3.onsubmit = function() { notices = submitstep3(step3); if (notices) return false; }
	submit.onclick = function() { notices = submitstep3(step3); if (notices) return false; }
}

function submitstep3(step3)
{
	clearform(); // clear old notices first
	var amount = 0;
	var persg = $('persoonsgegevens');
	var errordiv = $('foutmeldingen');

	var br, text;
	var notices = [];
	var domainnotices = checkform("Domeinhouder");
	if (domainnotices.length > 0) { amount++; notices = notices.concat(domainnotices); }
	
	var checks = ['admincheck', 'factuurcheck', 'techcheck'];
	var checkforms = ['Administratief_contact', 'Factuurgegevens', 'Technisch_contact'];
	for (i in checks) {
		var item = $(checks[i]);
		if (item.checked) {
			var itemnotices = checkform(checkforms[i]);
			if (itemnotices.length > 0) { amount++; notices = notices.concat(itemnotices); }
		}
	}
	if (notices.length > 0) {
		var notice = Construct.node('p', {className:'warn'});
		var noticetext = document.createTextNode('Controleer uw gegevens bij de aangegeven velden:');
		notice.appendChild(noticetext);

		var i, nl;

		for (i=0, nl = notices.length; i<nl; i++) {
			br = Construct.node('br');
			notice.appendChild(br);
			text = document.createTextNode(notices[i]);
			notice.appendChild(text);
		}
		errordiv.appendChild(notice);
	}
	
	var meerderjarig = $("meerderjarig");
	var minderjarig = $("minderjarig");
	if (!meerderjarig.checked && !minderjarig.checked) {
		var agreement = Construct.node('p', {className:'warn'}, 'Geef aan of u meer- of minderjarig bent.');
		errordiv.appendChild(agreement);
		meerderjarig.parentNode.className += ' error';
		minderjarig.parentNode.className += ' error';
		amount++;
	}

	var agreed = $("voorwaarden");
	if (!agreed.checked) {
		var agreement = Construct.node('p', {className:'warn'}, 'U dient akkoord te gaan met de voorwaarden.');
		errordiv.appendChild(agreement);
		agreed.parentNode.className += ' error';
		amount++;
	}

	var accountemail = $("username");
	if (accountemail && accountemail.value != "")
	{
		var account = $("account");
		var password = $("password");
		var password_again = $("password_again");
		if (password.value && password_again.value)
		{
			if (password.value != password_again.value)
			{
				var accountnotice = Construct.node('p', {className:'warn'}, 'U hebt twee verschillende wachtwoorden ingevuld.');
				errordiv.appendChild(accountnotice);
				amount++;
			}
		}
		else
		{
			var accountnotice = Construct.node('p', {className:'warn'}, 'U dient bij het aanmaken van een account uw wachtwoord twee keer in te voeren.');
			errordiv.appendChild(accountnotice);
			amount++;
		}
	}

	var els = persg.getElementsByTagName('input');
	for (i in els) {
		els[i].onkeypress = noerror;
		els[i].onchange = noerror;
	}

	if (amount > 0) return amount;
}

function noerror()
{
	this.className = this.className.replace(/ ?error/, '');
	var elements = this.parentNode.parentNode.getElementsByTagName('label');
	for (i in elements) {
		if (elements[i].className) {
			elements[i].className = elements[i].className.replace(/ ?error/, '');
		}
	}
}

// step 3 - start function clearform
function clearform()
{
	var step3 = $('stap3');
	//clear domeinhouder en factuurhouder forms
	var type = new Array("Domeinhouder", "Factuurgegevens");
	
	var j, tl, k, fl;

	for (j=0, tl = type.length; j<tl; j++)
	{
		var fields = new Array(type[j] + 'firstnameinitials', type[j] + 'lastname', type[j] + 'street', type[j] + 'extension', type[j] + 'zipcode', type[j] + 'place', type[j] + 'country', type[j] + 'phonenumber', type[j] + 'email');
	
		for (k=0, fl = fields.length; k<fl; k++)
		{
			var attr = $(fields[k]);
			if (attr) {
				if (attr.className.indexOf('error') != -1) { 
					var errorclass = attr.className; attr.className = errorclass.replace('error', '');
				}
			}
		}
		var numberattr = $(type[j]+'number');
		if (numberattr.className.indexOf('error') != -1) { 
			var errorclass = numberattr.className; numberattr.className = errorclass.replace('error', '');	}
	}
	// find the error notices, and clear it
	var errordiv = $('foutmeldingen');
	while (errordiv.firstChild) errordiv.removeChild(errordiv.firstChild);
}

// start function checkform
function checkform(type)
{
	var noticetext = [];
	var amount = 0;
	var fields = new Array(type + 'firstnameinitials', type + 'lastname', type + 'street', type + 'zipcode', type + 'place', type + 'country', type + 'phonenumber', type + 'email');

	var i, fl;
	
	for (i=0, fl = fields.length; i<fl; i++)
	{
		var attr = $(fields[i]);
		if (attr.value.length == 0) {
			attr.className += ' error';
			amount++;
		}
	}
	if (amount != 0) { noticetext.push('De aangegeven velden mogen niet leeggelaten worden.'); }

	var man = $(type + "male");
	var woman = $(type + "female");
	if (!man.checked && !woman.checked) { 
		noticetext.push('U moet een geslacht kiezen.');
		man.parentNode.className += ' error';
		woman.parentNode.className += ' error';
	}

	var number = $(type + "number");
	if ((number.value != "") && isNaN(number.value)) {
		noticetext.push('Uw huisnummer moet een getal zijn.');
		number.className += ' error';
	}

	var email = $(type + "email");
	var at = email.value.indexOf("@");
	var dot = email.value.indexOf(".");
	if (email.value != "")
	{
		if ((email.value.length<10) || (at == -1) || (dot == -1)) { 
			noticetext.push('Uw e-mailadres voldoet niet aan het formaat naam@domein.extensie');
			email.className += ' error';
		}
	}
	return noticetext;
}

function geld(geld) {
	var euros = Math.floor(geld) + '';
	var test = geld - euros;
	var centen = Math.round((geld - euros) * 100) + '';
	while (centen.length < 2) centen  += '0';
	return euros.concat(',', centen);
}

function addEvent(obj, type, fn) {
    if (obj.attachEvent) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn](window.event);}
        obj.attachEvent('on'+type, obj[type+fn]);
    } else {
        obj.addEventListener(type, fn, false);
    }
}

function removeEvent(obj, type, fn) {
    if (obj.detachEvent) {
        obj.detachEvent('on'+type, obj[type+fn]);
        obj[type+fn] = null;
    } else {
        obj.removeEventListener(type, fn, false);
    }
}

function arrayremove(array, element) {
	var a;
	for (a in array) {
		if (array[a] == element) delete array[a];
	}
}
function remove_sibling(el, relations) {
	var row;
	while (el.nextSibling) {
		row = el.nextSibling;
		if (relations && row.className == 'pakket' && row.firstChild.firstChild) {
			if (relations[row.firstChild.firstChild.value]) {
				if (row.nextSibling && row.nextSibling.className == 'extrainfo') {
					el = row.nextSibling;
				}
				else {
					el = row;
				}
			}
			else {
				row.parentNode.removeChild(row);
			}
		}
		else {
			row.parentNode.removeChild(row);
		}
	}
}

function create_dropdown(array, append){
	var j, al;
	for (j=0, al = array.length; j<al; j++) {
		row = Construct.node('option', {value:j+1, innerHTML:array[j]});
		append.appendChild(row);
	}
}

// loop until parentnode is the given element
function get_parent(element, parent)
{
	while(element.nodeName.toLowerCase() != parent && element.parentNode) {
		element = element.parentNode;
	}
	return element;
}

/* Lowercase the input and trim the leading and trailing whitespaces from it. */
function trim(domain) {
	var reg = domain;
	reg = reg.replace(/^\s+/, '');
	reg = reg.replace(/\s+$/, '');
	
	return reg.toLowerCase();
}

//addEvent(window, "load", domcheck);

addEvent(window, "load", startstep1);
addEvent(window, "load", removetable);
addEvent(window, "load", submitstep1);
addEvent(window, "load", createformend);

addEvent(window, "load", submittostep2);
addEvent(window, "load", startstep2);
addEvent(window, "load", showlegenda);
addEvent(window, "load", ordertype);
addEvent(window, "load", selectonclick);
addEvent(window, "load", submittostep3);
addEvent(window, "load", step3copy);

addEvent(window, "load", frm);
addEvent(window, "load", login_account);
addEvent(window, "load", step3forms);
