function sendmail() {
	var ilist = $('itemlist').innerHTML;
	ilist = encode(ilist);
	$('mailitemlist').value = ilist;

	var error = '';
	if ($('navn').value == '') {
		error += '(*) Navn\n';
	}	
	if ($('telefon').value == '') {
		error += '(*) Telefon\n';
	}
	if ($('email').value == '') {
		error += '(*) E-mail\n';
	}
	if (error != '') {
		error = 'Du skal udfylde felterne:\n'+error;
		alert(error);
		return false;
	} else {
		$('navn').value = encode($('navn').value);
		$('telefon').value = encode($('telefon').value);
		$('email').value = encode($('email').value);
		$('besked').value = encode($('besked').value);
		
		var form_obj = $('finish_configuration');
		var formvalues = Form.serialize(form_obj);

		$('navn').value = decode($('navn').value);
		$('telefon').value = decode($('telefon').value);
		$('email').value = decode($('email').value);
		$('besked').value = decode($('besked').value);


		sendmail_do(formvalues);
	}
}

function sendmail_do(formvalues_str) {
//	alert(formvalues_str);
//	return false;
	var url = '/includes/plugins/bygselv/bygselv_index.php';
	var pars = 'do=ajax_sendMail&' + formvalues_str;
//	var pars = encode(pars);
//	alert(pars);
	var myAjax = new Ajax.Updater(
		{success: 'mailformresponse'}, 
		url, 
		{
			method: 'post', 
			parameters: pars, 
			asynchronous: false,
			onFailure: reportMailError
	});

	// This call doesn't work in Safari
	myAjax.updateContent();
	new Effect.Highlight('mailformresponse', { duration: 0.5, endcolor: '#eeeeee' });
}

function encode(str) {
	var result = "";
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == " ") result += "+";
		else result += str.charAt(i);
	}
	return escape(result);
}

function decode(str) {
 	var result = str.replace(/\+/g, " ");
	return unescape(result);
}


function reportMailError(request) {
	$('mailformresponse').innerHtml = "Der opstod en fejl og mailen blev ikke afsendt korrekt. Prøv igen og kontakt Aquatec på nummeret herunder hvis fejlen gentages.";
	new Effect.Highlight('mailformresponse', { duration: 0.5, endcolor: '#eeeeee' });
}


function populateItemlist(pid, selectedsets_arr) {
	$('ajax_activity').style.display = '';
	var qstring = '';
	// Convert to query string
	for (var i=0; i < selectedsets_arr.length; i++) {
		qstring += "&selectedset"+i+"="+selectedsets_arr[i];
	}

	var url = '/includes/plugins/bygselv/bygselv_index.php';
	var pars = 'do=ajax_returnItemlist&pool_id=' + pid + qstring;

	var myAjax = new Ajax.Updater(
		'itemlist',
		url, 
		{
		method: 'get', 
		parameters: pars,
		asynchronous: false
	});	
	// This call doesn't work in Safari
	myAjax.updateContent();
	$('ajax_activity').style.display = 'none';
}

function populateSgDiv(sgid, piid, position) {
	var url = '/includes/plugins/bygselv/bygselv_index.php';
	var pars = 'do=ajax_returnSg&sg_id=' + sgid + '&pi_id=' + piid + '&position=' + position;
	var sgDiv = "sg"+sgid;

	var myAjax = new Ajax.Updater(
		sgDiv,
		url, 
		{
		method: 'get', 
		parameters: pars,
		asynchronous: false
	});	
	// This call doesn't work in Safari
	myAjax.updateContent();
	
	// Check if content was loaded
	if ($('sg'+sgid).innerHTML != "") {
		position++;
	}
	return position;
}

// -------------------> Functions to validate sg choices

function validate_sg(sgid) {
	if ($('sg'+sgid).innerHTML != "") { // Only validate if SG contains data
		// Get sg element + title
		var sg = $('sg'+sgid);
		var sgtitle = $('sgtitle_'+sgid).innerHTML;
	
		// Get minmax values
		var sgmin = $('sgmin_'+sgid).value;
		var sgmax = $('sgmax_'+sgid).value;
		if (sgmax == 0) { // Make <= sgmax possible
			sgmax = 999999;
		}

	//	alert ("Validating = "+sgid+"\n MIN: "+sgmin+"\nMAX: "+sgmax);
		
		// Get all input fields
		var sg_inputs = sg.getElementsByTagName('input');
	
		var sg_radios = new Array();
		var sg_checks = new Array();
		var sg_has_checks = false;
		var sg_has_radios = false;
		
		// loop through them
		for (var i=0; i < sg_inputs.length; i++) {
			if (sg_inputs[i].getAttribute("type") == "radio") {
				sg_has_radios = true;
				if (sg_inputs[i].checked) {
					// Save value of all checked radio values in sg_radios
					sg_radios[sg_radios.length] = sg_inputs[i].getAttribute("value");
				}
			}
			if (sg_inputs[i].getAttribute("type") == "checkbox") {
				sg_has_checks = true;
				if (sg_inputs[i].checked) {
					// Save value of all checked checkboxes values in sg_checks
					sg_checks[sg_checks.length] = sg_inputs[i].getAttribute("value");
				}
			}
		}
	
		// So are we checking checkboxes or radios?
		if (sg_has_checks) {
			// Checkboxes
//			alert(sgmin+"/"+sgmax);
			if (sgmin == 0 && sgmax == 0) {
				// Any number of checks allowed
				return true;
			} else if ((sg_checks.length >= sgmin) && (sg_checks.length <= sgmax)) {
				// Number of checks within allowed range
				return true;
			} else {
				// Number of checks OUTSIDE allowed range - output correct errormessage
				if (sgmin == sgmax) {
					// User must select _precisely_ the sgmin/max value number of checks
					var error = "Vælg venligst præcis "+sgmax+" af valgmulighederne i '"+sgtitle+"'";
				} else if ((sgmin == 0) && (sgmax > 0 && sgmax < 999999)) {
					// User must select _up to_ sgmax checks
					var error = "Du har valgt "+sg_checks.length+" valgmulighed(er) i '"+sgtitle+"'. Vælg maksimalt "+sgmax;
				} else if ((sgmin > 0) && (sgmax == 999999)) { 
					// User must select _at least_ sgmin checks
					var error = "Du har valgt "+sg_checks.length+" valgmulighed(er) i '"+sgtitle+"'. Vælg mindst "+sgmin;
				} else if ((sgmin > 0) && (sgmax > 0 && sgmax < 999999)) {
					// User must select within the min max range
					var error = "Du har valgt "+sg_checks.length+" valgmulighed(er) i '"+sgtitle+"'. Vælg mindst "+sgmin+" og maksimalt "+sgmax;
				}
				alert(error);
				return false;	
			}			
		} else if (sg_has_radios) {
			// Radios
			// Get sg_value for radios and check if it holds a value
			var sg_value_radio = $('value_sg'+sgid).value;
			if (sg_value_radio != "") {
				return true;
			} else {
				alert("Vælg venligst en af valgmulighederne i "+sgtitle);
				return false;
			}
		}
	} else {
		return true; // If sg doesn't have content, just return true!
	}
}

// -------------------> Functions to handle shape selection and update of product list
function selected_set(sgid_csid_setnumber) {
	var setid = 'set_'+sgid_csid_setnumber;
	var checkthis = $(setid);
	var checktype = checkthis.getAttribute("type");


	if (checkthis.checked && checktype == "checkbox") { // Already checked
		checkthis.checked = false;
	} else {
		// Check radio or checkbox
		checkthis.checked = true;

		// Set relevant "value_"-fields for radio buttons
		if (checktype == "radio") {
			var sgid = sgid_csid_setnumber.split("_")[0];
			$('value_sg'+sgid).value = sgid_csid_setnumber;
//			alert($('value_sg'+sgid).value);
		}
	}
}

// -------------------> Functions to handle shape selection and update of product list
function selectedShape(shape_id) {
	setChecked('radio_shape_'+shape_id);
	loadProductList(shape_id);
}

function loadProductList(shape_id) {
	var url = '/includes/plugins/bygselv/bygselv_index.php';
	var pars = 'do=ajax_returnProductList&id=' + shape_id;

	var myAjax = new Ajax.Request(
		url, 
		{
		method: 'get', 
		parameters: pars, 
		onComplete: updateProductList
	});
}

function updateProductList(originalRequest)	{
	$('poollist').innerHTML = originalRequest.responseText;
	new Effect.Highlight('poollist', { duration: 0.5, endcolor: '#eeeeee' });
}

// -------------------> Functions to handle pool selection and update of installation list
function selectedPool(pool_id, firing_obj) {
	var fo = $(firing_obj);
	if (fo.tagName == "INPUT") {
		return false;
	}
	var pi_id = $('value_installation').value;
	var pid = $('value_pool').value;
	var doselect = true;
	var doconfirm = true;

	if (!pid) {
		doconfirm = false;
	}
	if (!pi_id) {
		doconfirm = false;
	}

	if (doconfirm) {
		if (!confirm("Er du sikker på at du vil vælge en anden poolmodel? Dine øvrige valg vil blive nulstillet.")) {
			doselect = false;
		}
	}

	if (doselect) {
		setChecked('radio_pool_'+pool_id);
		$('value_pool').value = pool_id;
		loadInstallationsList(pool_id);
	} else {
		setChecked('radio_pool_'+pid);
	}
}

function loadInstallationsList(pool_id) {
	var url = '/includes/plugins/bygselv/bygselv_index.php';
	var pars = 'do=ajax_returnInstallationsList&id=' + pool_id;

	var myAjax = new Ajax.Request(
		url, 
		{
		method: 'get', 
		parameters: pars, 
		onComplete: updateInstallationsList
	});
}

function updateInstallationsList(originalRequest)	{
	$('installationslist').innerHTML = originalRequest.responseText;
	new Effect.Highlight('installationslist', { duration: 0.5, endcolor: '#eeeeee' });
}
// -------------------> Functions to handle pool selection and update of installation list

function selectedInstallation(pi_id, firing_obj) {
	var fo = $(firing_obj);
	if (fo.tagName == "INPUT") {
		return false;
	}

	var doselect = true;
	var doconfirm = true;

	var previously_selected_pi_id = $('value_installation').value;
	if (previously_selected_pi_id == "") {
		doconfirm = false;
	}

	if (doconfirm) {
		if (!confirm("Er du sikker på at du vil vælge en anden installationstype? Dine øvrige valg vil blive nulstillet.")) {
			doselect = false;
		}
	}

	if (doselect) {
		setChecked('radio_installation_'+pi_id);
		$('value_installation').value = pi_id;
		new Effect.Highlight('installationslist', { duration: 0.5, endcolor: '#eeeeee' });
	} else {
		setChecked('radio_installation_'+previously_selected_pi_id);	
	}
}

// ------------------->

function setClass(obj, targetClassName) {
	// For at kompensere for manglende TR:HOVER i CSS...  
	obj.className = targetClassName;
}

function setChecked(checkthisid_str) {
	var obj = document.getElementById(checkthisid_str);
	obj.checked = true;
}

function trinHasContent(trin_id) {
	// Function der checker om et trin har indhold
	// Bruges til at springe over trin uden indhold
	if (trin_id == 1) {
		return true;
	}
	if (trin_id == 2) {
		var sg1c = $('sg1').innerHTML;
		if (sg1c == "") {
			return false;
		} else {
			return true;
		}
	}	
	if (trin_id == 3) {
		var sg2c = $('sg2').innerHTML;
		var sg3c = $('sg3').innerHTML;
		var sg4c = $('sg4').innerHTML;
		if (sg2c == "" && sg3c == "" && sg4c == "") {
			return false;
		} else {
			return true;
		}
	}	
	if (trin_id == 4) {
		var sg5c = $('sg5').innerHTML;
		if (sg5c == "") {
			return false;
		} else {
			return true;
		}
	}	
	if (trin_id == 5) {
		var sg6c = $('sg6').innerHTML;
		var sg7c = $('sg7').innerHTML;
		if (sg6c == "" && sg7c == "") {
			return false;
		} else {
			return true;
		}
	}	
	if (trin_id >= 6) {
		return true;
	}
}

function showstep(btn, showthisdiv_int, direction) {
	// Disable button
	this.disabled=true;
	var ok = true;
	var error = 'Du skal vælge:\n';

	// Skift til trin2 ------------------------------------->
	if (showthisdiv_int == '2') {
 		if (direction == "next") {
			var pi_id = $('value_installation').value;
			var pid = $('value_pool').value;
			// Check for valgt pool
			if (pid == '') {
				ok = false;
				error = error + '(*) Pool model:\n'
			}
			// Check for valgt installation
			if (pi_id == '') {
				ok = false;
				error = error + '(*) Installationstype:\n'
			}

			if (ok) {
				var loaded_piid = $('loaded_piid').value;
				if ((loaded_piid == '') || (loaded_piid != pi_id)) { 
					// Hvis PI_ID ikke er sat eller hvis det er ændret ifht tidligere loadet
	
	
					// Check for safari
					var detect = navigator.userAgent.toLowerCase();
					var is_safari = detect.indexOf("safari");
					if (is_safari > -1) {
						alert("Pool designeren virker desværre ikke med Apples Safari browser. Vi arbejder på sagen. Brug i stedet den glimrende Firefox browser, som kan hentes gratis på www.getfirefox.com");
						return false;
					}
	
					// HER SKAL DER SKE POPULERING AF DIV PÅ efterfølgende trin afhængig af PI_ID
					var nextposition = 4;
					nextposition = populateSgDiv(1, pi_id, nextposition);
					nextposition = populateSgDiv(2, pi_id, nextposition);
					nextposition = populateSgDiv(3, pi_id, nextposition);
					nextposition = populateSgDiv(4, pi_id, nextposition);
					nextposition = populateSgDiv(5, pi_id, nextposition);
					nextposition = populateSgDiv(6, pi_id, nextposition);
					nextposition = populateSgDiv(7, pi_id, nextposition);
					$('ajax_activity').style.display = 'none';

					// Save loaded piid for future reference
				}
				showstep_switch(showthisdiv_int, direction);
			} else {
				alert(error);
			}
		} else {
			showstep_switch(showthisdiv_int, direction);
		}
	} else if (showthisdiv_int == '3') {
 		if (direction == "next") {
			if (validate_sg(1)) {
				showstep_switch(showthisdiv_int, direction);
			}
		} else {
			showstep_switch(showthisdiv_int, direction);
		}
	} else if (showthisdiv_int == '4') {
 		if (direction == "next") {
			if (validate_sg(2) && validate_sg(3) && validate_sg(4)) {
				showstep_switch(showthisdiv_int, direction);
			}
		} else {
			showstep_switch(showthisdiv_int, direction);
		}
	} else if (showthisdiv_int == '5') {
 		if (direction == "next") {
			if (validate_sg(5)) {
				showstep_switch(showthisdiv_int, direction);
			}
		} else {
			showstep_switch(showthisdiv_int, direction);
		}
	} else if (showthisdiv_int == '6') {
 		if (direction == "next") {
			if (validate_sg(6) && validate_sg(7)) {


				// Pool configuration finished. Now do calculations...
	
				// Set up array to hold selected SGs
				var sgs = new Array();
				
				// Get all inputs in the config form
				var cform = $('productselectorform');
				var cinputs = cform.getElementsByTagName('input');
				
				// Trawl for checked values
				for (var i=0; i < cinputs.length; i++) {
					var itype = cinputs[i].getAttribute("type");
					if (itype == "hidden") {
						var cid = cinputs[i].id;
						if (cid.indexOf("value_sg") > -1) {
							// hiddens that include the string "value_sg"
							sgs[sgs.length] = cinputs[i].value;
						}
					} else if (itype == "checkbox") {
						if (cinputs[i].checked) {
							var name = "sel_"+sgs.length;
							sgs[sgs.length] = cinputs[i].value;
						}				
					}
				}
				var pid = $('value_pool').value;
				populateItemlist(pid, sgs);
				
				showstep_switch(showthisdiv_int, direction);
			} else {
				showstep_switch(showthisdiv_int, direction);
			}
		}
	} else {
		showstep_switch(showthisdiv_int, direction);
	}
	// Re-enable button
	this.disabled=false;
}

function showstep_switch(showthisdiv_int, direction) {

	if (trinHasContent(showthisdiv_int)) {
		// Hide all steps
		var show_str = 'trin' + showthisdiv_int;
		$('trin1').style.display = 'none';
		$('trin2').style.display = 'none';
		$('trin3').style.display = 'none';
		$('trin4').style.display = 'none';
		$('trin5').style.display = 'none';
		$('trin6').style.display = 'none';
		
		// Show relevant step
		$(show_str).style.display = 'block';
	} else {
		if (direction == "next") {
			showthisdiv_int++;
		} else {
			showthisdiv_int--;
		}
		showstep(showthisdiv_int, direction);
	}
}