var curCodeField = new Array();

function updateCodeField(pid, dcid){
	//$('.showonfocus').hide();
	
	
	//alert(pid);
	var cur = "input["+pid+"]["+dcid+"]";
	
	if(curCodeField[pid] != null){
	   //alert(curCodeField[pid]);
    	if(curCodeField[pid] != dcid || dcid == '0'){
    	    if(document.getElementById("input[" + pid + "][" + curCodeField[pid] + "]")){
    		  document.getElementById("input[" + pid + "][" + curCodeField[pid] + "]").style.display = 'none';
    		}
    		if(document.getElementById(cur)){
        	   document.getElementById(cur).style.display = 'block';
        	}
        } 
    } else {
        if(document.getElementById(cur)){
           document.getElementById(cur).style.display = 'block';
        }
    }
    
    curCodeField[pid] = dcid;
}



function showProductGroup(pgid) {
    var url = "ajax/shop_product.php?sid=" + Math.random()+"&pgid=" + pgid;
    //alert(url);
	showOverlay(url);
}

function showProduct(pid) {
	showOverlay("ajax/shop_product.php?pid=" + pid + "&sid=" + Math.random());
}

function showGiftcertificate() {
	showOverlay("ajax/shop_certificate.php?sid=" + Math.random());
}

function inlinecart(id) {
	$.ajax({
		url: "ajax/shop_inlinecart.php?action=inlinecart&start=" + id,
		success: function(data) {
		    
			$("#inlinecart").html(data);
		}
	});
}

function addProduct(form) {
    //alert(form);
    postVars = makePostString(form);
	if(document.getElementById("exclusivecode") != null){
		postVars += "&exclusivecode=" + document.getElementById("exclusivecode").value;
	}
	
	$.ajax({
	    type: "POST",
		url: "ajax/shop_addproduct.php?sid=" + Math.random(),
		data: postVars,
		success: function(data) {
		    if(data == "2"){
				showMessage("De code die u heeft opgegeven is niet geldig");
			} else {
				showOverlay("ajax/shop_cart.php");
				inlinecart();	//updateinlinecart
			}
		}
	});
}

function removeProduct(pid) {
	$.ajax({
		url: "ajax/shop_removeproduct.php?pid=" + pid + "&sid=" + Math.random(),
		success: function(data) {
			showOverlay("ajax/shop_cart.php");
		}
	});
	
	inlinecart();//updateinlinecart
}

function saveCart(form) {
	postVars = makePostString(form);
	
	//var randNr = (Math.random()*parseInt(maxVal)).toFixed(2);
	$.ajax({
		type: "POST",
		url: "ajax/shop_savecart.php?sid=" + Math.random(),
		data: postVars,
		success: function(data) {
			if (data == "1") {
		      	inlinecart();
				showOverlay("ajax/shop_customer.php");
			} else {
				showMessage(data);
			}
		}
	});
}

function updateParticipants(productid, nofParticipants) {
	var checkboxchecked = $('#syllabi_'+productid).is(':checked') ? 1 : 0;

	$.ajax({
		type: "POST",
		url: "ajax/shop_updateparticipants.php?sid=" + Math.random(),
		data: "productid=" + productid + "&nofParticipants=" + nofParticipants+ "&checkboxchecked=" + checkboxchecked,
		success: function(data) {
			showOverlay("ajax/shop_cart.php");
			inlinecart();	//updateinlinecart
 
		}
	});

	
			
}


function shopLogin(email) {

	bool = $("#shoplogin").validationEngine('validate');
	if(bool){
		var password = document.getElementById("password1-password").value;
		showOverlay("ajax/shop_customer.php?action=login&email=" + email + "&password=" + password);
	}
	
}


/*
function shopLogin(email, password, rememberme) {
	$.ajax({
		url: "ajax/login.php?action=login&email=" + email + "&password=" + password + "&rememberme=" + rememberme,
		success: function(data) {
			showMessage(data);
			
			$("#login").html('<a href="javascript:showOverlay(\'ajax/account.php\');">mijn gegevens</a> <span class="white"> | </span><a href="javascript:showOverlay(\'ajax/logout.php\');">uitloggen</a>');
			showOverlay("ajax/shop_customer.php");
		}
	});
}
*/

function addMailAndPassword(){
    //$('#checkuseremail').fadeOut();
	bool = $("#newcustomer").validationEngine('validate');
	if(bool){

		var email = document.getElementById("email").value;

		var passwd = document.getElementById("password1-password").value;
		
		var passwd2 = document.getElementById("password2-password").value;
		if(passwd == ""){
			showMessage("U dient een wachtwoord in te vullen");
			return;
		}
		if(passwd != passwd2){
			showMessage("De door u ingevulde wachtwoorden komen niet met elkaar overeen");
			return;
		}

		if(passwd.length < 6){
			showMessage("Het wachtwoord dient uit minimaal zes karakters te bestaan.");
			return;
		}


		showOverlay('ajax/shop_customer.php?newuser&email='+email+'&passwd='+passwd+'&passwd2='+passwd2);
	}
}

//change by tim 21-12-2010 (button verandert en ajax teruggave aangepast);
function checkUserEmail(){
    //$('#checkuseremail').fadeOut();
	bool = $("#newuser").validationEngine('validate');
	idname = $('#language').val();
	
	if(bool){

		$.ajax({
			type: "POST",
			url: "ajax/checkuseremail.php?sid=" + Math.random(),
			data: "email=" + escape(document.getElementById("email").value),
			success: function(data) {
				
				//alert(eval('(' + data + ')')
				$('#checkuseremail').html('<button type="submit" name="action" class="cartbutton" id="'+idname+'" value="" onclick="javascript:shopLogin(\''+escape(document.getElementById("email").value)+'\')"> </button>');
				$('#replacethis').html(data);
				//document.getElementById("customertbody").prepend = data; oude code van lex
			}
		});
	}
}

function shopLogout() {
	$.ajax({
		url: "ajax/login.php?action=logout",
		success: function() {
			//hideOverlay();
		}
	});
}

var pwsent = false;
function newPassword() {
	if(!pwsent){
		email = $('#email').val();
		if(email != ''){
			pwsent = true;
			$.ajax({
				url: "ajax/resetpassword.php?email=" + email,
				success: function(data) {
					showMessage(data);
				}
			});
		}
	}
}

function resetPassword() {
	email = $('#email').val();
	if(email != ''){
		$.ajax({
			url: "ajax/resetpassword.php?email=" + email,
			success: function(data) {
				showMessage(data);
			}
		});
	}
}
function saveTaferelen(form) {
	postVars = makePostString(form);
	$.ajax({
		type: "POST",
		url: "ajax/shop_updatetaferelen.php",
		data: postVars,
		success: function(data) {
			hideOverlay();
		}
	});
}



function saveCustomer(form) {


	postVars = makePostString(form);
	if(screen.width){
	   postVars += "scrwidth=" + screen.width + "&scrheight=" + screen.height + "&";
	} else {
	   postVars += "scrwidth=" + window.screen.width + "&scrheight=" + window.screen.height + "&";
	}

	if(window.innerWidth){
	   postVars += "winwidth=" + window.innerWidth + "&winheight=" + window.innerHeight + "&";
	} else {
	   postVars += "winwidth=" + window.screen.availWidth + "&winheight=" + window.screen.availHeight + "&";
	}


	
	bool = $("#customer_form").validationEngine('validate');

	

	if(bool){
		$.ajax({
			type: "POST",
			url: "ajax/shop_savecustomer.php",
			data: postVars,
			success: function(data) {
				//alert(data);
				if (data == "1") {
					showOverlay("ajax/shop_payment.php");
				} else if(data == "0"){
				    //taferelen gelukt
					showMessage("Uw gegevens zijn opgenomen in de database");
					shopLogout();
				} else if(data == "4"){
					 //taferelen al geregistreerd voor emailadres
					showMessage("Uw bent al geregistreerd voor taferelen.");
					shopLogout();
				} else if(data == "3"){
					//returnt tegenwoordig 3 als er geen payment nodig is...
					showOverlay("ajax/shop_overview.php");
				} else if(data == "2"){
					showOverlay("ajax/login.php?msg="+escape("Uw e-mailadres is al bij ons bekend. U kunt hieronder inloggen. Daarna kunt u zichzelf aanmelden voor de taferelen")+"&user="+$('#email1').val());
				} else {
					showMessage(data);
					updateOverlaySize();
				}
			}
		});
	}
}

function savePayment(form) {


	bool = ($("#payment_form").validationEngine('validateField', '#agree'));
	bool = !bool;



	var id = $("input[@name=method]:checked").attr('id');
	if(id == '2') {
		bool = $("#payment_form").validationEngine('validate');
	}

	
	if(bool){

		postVars = makePostString(form);
		$.ajax({
			type: "POST",
			url: "ajax/shop_savepayment.php?sid=" + Math.random(),
			data: postVars,
			success: function(data) {
				if (data == "1") {
					showOverlay("ajax/shop_overview.php");
				} else {
					showMessage(data);
				}
			}
		});
	}
	
}

function doWebOrder() {
	document.getElementById('finish').disabled = true;
	var orderId = $("#orderID").val();
	$.ajax({
		url: "ajax/shop_doorder.php?sid=" + Math.random() + "&orderId="+orderId,
		success: function(data) {
			$('.cartbutton').attr("disabled", "true");
			if (data == 1) {
				showOverlay("ajax/shop_finish.php");
			} else if (data == 2) {


				$('#form1').submit();
			} else if (data.substring(0, 9) == "idealurl:") {
			     //alert((data.substring(9, data.length)).replace(/&amp;/g, "&"));

				document.location = (data.substring(9, data.length)).replace(/&amp;/g, "&");
			} else {
				showMessage(data);
				
			}
			inlinecart();
		}
	});
	
}

function addCoupon(){
	var code = document.getElementById("couponcode").value;
	
	postVars = "code="+code+"&sid="+Math.random();
	$.ajax({
		type: "POST",
		url: "ajax/shop_addcoupon.php",
		data: postVars,
		success: function(data) {
			if (data == "1") {
				showOverlay("ajax/shop_payment.php");
			} else {
				showMessage(data);
			}
		}
	});
}

function removeCoupon(couponID){
	postVars = "couponid="+couponID+"&sid="+Math.random();
	$.ajax({
		type: "POST",
		url: "ajax/shop_removecoupon.php",
		data: postVars,
		success: function(data) {
			if (data == "1") {
				showOverlay("ajax/shop_payment.php");
			} else {
				showMessage(data);
			}
		}
	});
}

function makePostString(form) {
	if(form.elements == undefined) {
		return '';
	}

	postVars = "";
	for (var i = 0; i < form.elements.length; i++) {
		value = form.elements[i].value;
		
		// Add to varstring if checked
		if (form.elements[i].type == "radio") {
			if (form.elements[i].checked == true) {
				postVars += form.elements[i].name + "=" + encodeURIComponent(value) + "&";
			}
		} else if (form.elements[i].type == "checkbox") {
			if (form.elements[i].checked == true) {
				postVars += form.elements[i].name + "=" + encodeURIComponent(value) + "&";
			} else {
				postVars += form.elements[i].name + "=&";
			}
		} else {
			postVars += form.elements[i].name + "=" + encodeURIComponent(value) + "&";
		}
	}
	
	return postVars;
}


// Oude shop dingen

function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		//Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function doCRMWebOrder(action, weborderid) {
    var xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	

	//var url = "modules/doCRMOrder.php";
	var url = "inc/crmapi/index.php";
	url = url + "?sid=" + Math.random();
	url = url + "&action=" + action;
	url = url + "&weborderid=" + weborderid;
	
	xmlHttp.onreadystatechange = function() { handleDoCMSOrder(xmlHttp); };
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function handleDoCMSOrder(xmlHttp) { 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
	    document.getElementById("doOrderStatus").innerHTML = xmlHttp.responseText;
	    //update winkelmand
	    inlinecart();
	} else {
		document.getElementById("doOrderStatus").innerHTML = "<p>Bezig met plaatsen van de order in CRM...</p>";
	}
}

function checkNLPostCode(nbs_zip){ // nbs_zip is the value of the postcode field   

    nbs_zip = nbs_zip.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
    nbs_zip = nbs_zip.replace(/\s{2,}/g," "); // replace multiple spaces by one space
    nbs_zip = nbs_zip.replace(/(\d)\s(\d)/g, "$1$2"); // remove spaces between numbers
    nbs_zip = nbs_zip.replace(/(\d)\s(\d)/g, "$1$2"); // remove spaces between numbers again - must be done twice!
    nbs_zip = nbs_zip.replace(/(\D)\s(\D)/g, "$1$2"); // remove spaces between letters
    nbs_zip = nbs_zip.toUpperCase(); // convert letters to uppercase
    
    //added by tim 24-02-2011
    
    //als er geen spatie is ingevoerd moet die worden toegevoegd
    if(nbs_zip.length == 6) {
        nums    = nbs_zip.substr(0,4);
        chars   = nbs_zip.substr(4,3);
        format_zip = nums + ' ' +chars;
    } else {
        format_zip = nbs_zip;
    }
    
    //validates also the case of the letters
    var reg = new RegExp('^(\\d)(\\d)(\\d)(\\d)(\\s+)([A-Z])([A-Z])$');
    var res = reg.exec(format_zip); //test

    if (res != null) {
        //res[0] bevat correct format_zip;
        $('#pc').val(res[0]);
        return true;
    } else {
        //anders iets heel fouts
        showMessage(getLangText('zipcode_not_correct'));//(nbs_zip + " is een ongeldige postcode, een postcode dient als volgt ingevuld te worden: 1111 AA");
        return false;
    }
    
    //end edit by Tim    
}


function getAddress() {
    var xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	//document.getElementById("sn").value = '';
    //document.getElementById("pn").value = '';
	var pc = document.getElementById("pc").value;
	var hn = document.getElementById("hn").value;    
    //var pc.split(' ').join(''); 
    $("#ajaxmsg").hide();
   
  
    if(checkNLPostCode(pc)){
        if(pc != "" && hn != ""){
        
            pc = pc.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
            pc = pc.replace(/\s{2,}/g," "); // replace multiple spaces by one space
            pc = pc.replace(/(\d)\s(\d)/g, "$1$2"); // remove spaces between numbers
            pc = pc.replace(/(\d)\s(\d)/g, "$1$2"); // remove spaces between numbers again - must be done twice!
            pc = pc.replace(/(\D)\s(\D)/g, "$1$2"); // remove spaces between letters
            pc = pc.toUpperCase(); // convert letters to uppercase
        
        
        	var url = "inc/webservices/index.php";
        	url = url + "?sid=" + Math.random();
        	url = url + "&pc=" + pc;
        	url = url + "&hn=" + hn;
        	
        	xmlHttp.onreadystatechange = function() { handleGetAddress(xmlHttp); };
        	xmlHttp.open("GET", url, true);
        	xmlHttp.send(null);
        }
    }
}

function handleGetAddress(xmlHttp) { 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		//alert(xmlHttp.responseText);
	    //document.getElementById("doOrderStatus").innerHTML = xmlHttp.responseText;
	    if(xmlHttp.responseText != "|"){
            var tmp = xmlHttp.responseText.split("|");
    	    document.getElementById("sn").value = tmp[0];
    	    document.getElementById("pn").value = tmp[1];
			document.getElementById("sn").readOnly = true;
			document.getElementById("pn").readOnly = true;
			document.getElementById("sn").style.backgroundColor = "#ccc";
			document.getElementById("pn").style.backgroundColor = "#ccc";
    	} else {
			document.getElementById("sn").readOnly = false;
			document.getElementById("pn").readOnly = false;
			document.getElementById("sn").style.backgroundColor = "#fff";
			document.getElementById("pn").style.backgroundColor = "#fff";
		}
	} else {
		//document.getElementById("doOrderStatus").innerHTML = "<p>Bezig met plaatsen van de order in CRM...</p>";
	}
}

function textCounter(){
	var maxlimit = "150";
	var field = document.getElementById("cert_message");
	var cntfield = document.getElementById("num_chars");
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		cntfield.innerHTML = maxlimit - field.value.length;
	}
}

