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 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);
	$.ajax({
	    type: "POST",
		url: "ajax/shop_addproduct.php?sid=" + Math.random(),
		data: postVars,
		success: function(data) {
		    //alert(data);
			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) {
	$.ajax({
		type: "POST",
		url: "ajax/shop_updateparticipants.php?sid=" + Math.random(),
		data: "productid=" + productid + "&nofParticipants=" + nofParticipants,
		success: function(data) {
			showOverlay("ajax/shop_cart.php");
			inlinecart();	//updateinlinecart
		}
	});
}

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 shopLogout() {
	$.ajax({
		url: "ajax/login.php?action=logout",
		success: function(data) {
			
			$("#login").html('<a href="javascript:showOverlay(\'ajax/login.php\');">login</a><span class="white"> | </span><a href="javascript:showOverlay(\'ajax/account.php\');">registreren</a>');

			//showOverlay("ajax/shop_customer.php"); Uitgecomment omdat het raar is als je uitlogt een registratiepagina krijgt
			
			hideOverlay();
			//showMessage(data);
			
		}
	});
}

function resetPassword() {
	email = $("#email").val();
	if (email == "") {
		showMessage("U dient uw email adres in te vullen zodat wij daar een nieuw wachtwoord naartoe kunnen sturen.");
	} else {
		$.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 + "&";
	}
	
	$.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"){
                showMessage("Uw gegevens zijn opgenomen de database");	
			} 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) {
	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() {
	$.ajax({
		url: "ajax/shop_doorder.php?sid=" + Math.random(),
		success: function(data) {
			$('.cartbutton').attr("disabled", "true");
			if (data == 1) {
				showOverlay("ajax/shop_finish.php");
			} 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 makePostString(form) {
	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
    
    if (!/^[1-9]\d{3}\s[A-Z]{2}$/.test(nbs_zip)) {
        showMessage(nbs_zip + " is een ongeldige postcode, een postcode dient als volgt ingevuld te worden: 1111 AA");
        return false;
    } else {
        return true;
    }
}


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") {
	    //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];
    	}
	} else {
		//document.getElementById("doOrderStatus").innerHTML = "<p>Bezig met plaatsen van de order in CRM...</p>";
	}
}