
var modsort = new Array( "9", "8", "7", "6", "5", "4", "3", "2", "1" );
var oldreq,zipcode,housenumber,docf;
var street="";
var city="";
var bankgiro="";
var rekcheck=false;
var postcheck=false;

var fldZipcode = "postalCode";
var fldHousenr = "housenumber";
var fldStreet  = "streetname";
var fldCity    = "city";
var fldDelvZipcode = "delv_postalCode";
var fldDelvHousenr = "delv_housenumber";
var fldDelvStreet  = "delv_streetname";
var fldDelvCity    = "delv_city";

var DUTCH_HET = /(land|nummer|adres)$/i;
////////////////////////////////////////////////
var ERROR_INV_EMAIL = "Ongeldig emailadres";
var ERROR_POSTCODE = "De postcode moet vier cijfers en twee letters bevatten";
var ERROR_INV_GIRO = "Het ingevulde gironummer is niet geldig.";
var ERROR_INV_BANK = "Het ingevulde banknummer is niet geldig";
var ERROR_INV_DATE = "De ingevulde datum is niet geldig";
var ERROR_INV_PHONE = "Het ingevulde telefoonnummer is niet geldig";
var ERROR_INV_EMAIL2 = "De twee e-mailadressen moeten hetzelfde zijn";
var ERROR_INV_COND   = "U dient akkoord te gaan met de algemene voorwaarden";
var ERROR_INV_PAYMENT   = "U dient akkoord te gaan met de machtiging";
var ERROR_INV_ALTERNATEDELIVERY = "Het bezorgadres is niet volledig ingevuld";
////////////////////////////////////////////////
var INFO_SOURCE = {'select-one': 'gekozen', 'checkbox': 'aangevinkt', '*': 'ingevuld'};
var ERROR_EMPTY = "verplicht veld";
var ERROR_MANDATORY = "moet nog $ worden";
////////////////////////////////////////////////


var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
var isPC_re = /^\d{4}\ ??\w{2}$/;
var isPhone_re = /^0\d{9}$/;
var isDate_re = /^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}$/;

var dateCheck = {check:isDate_re, err:ERROR_INV_DATE};	


function elem(el) {
  return document.getElementById(el);
};


function setVarField(elm, id) {
	// application defined variable tree VAR_MAP
	var value = "";
	var path = id.split(".");
	var t = VAR_MAP[path[0]];
	var ctrl = document.order[path[0]];
	if (t && ctrl) {
		value = t[getValue(ctrl)][path[1]];
	}
	elm.innerHTML = value || "";
}



function updateVarFields(ctrlName) {
	$(".mceAtomic").each(
	  function() {
		  var id = this.id;
		  var regex = new RegExp("^var:" + (ctrlName || ""));
		  if (regex.test(id)) {
			  setVarField(this, id.replace(/^var:/, ""));
		  }
	  }
	)
}



function initVarListeners() {
	if (typeof(VAR_MAP) == 'undefined') {
		alert("missing definition of VAR_MAP\nUsage: var VAR_MAP = {product:{3:{price:'4,50'},4:{price:'5,25'}}};");
		return;
	}
	for(var ctrl in VAR_MAP) {
		$("input[name="+ ctrl + "]").bind("click change", function(e){
			updateVarFields(this.name);
		})
	}
	updateVarFields();
}


function preselectRadioButtons() {
	var distinctNames = {};
	$("input:radio").each(function() {
		var found = distinctNames[this.name];
		
		if (this.checked) {
			distinctNames[this.name] = this;
		}
		else {
			if (!found)
				distinctNames[this.name] = this;
		}
	});
	
	for (var name in distinctNames) {
		distinctNames[name].checked = true;
	}
}


function checkmod(mod) // modulo 11 A.K.A. Elfproef for dutch bank accounts
{
	var output = 0;
	for (var i = 0; i < 9; i++) { output += ( parseInt(modsort[i]) * parseInt(mod.substr(i, 1)) ); }
	if (output % 11 == 0) return true;
	return false;
};


function bankcheck() // checks bank/giro account
{
	var F = document.forms[0];
	if (!F.account || !F.accountType || (F.paymentMethod && F.paymentMethod[0].checked)) return undefined;
	var str = F.account.value;

	if (F.accountType[0].checked && (str.length != 9 || !checkmod(str)))
	{
		return ERROR_INV_BANK;
	}
	else if (F.accountType[1].checked && !str.match(/^\d{1,8}$/))
	{
		return ERROR_INV_GIRO;
	}

	return undefined;
};

function show_hide_alternateDelivery()
{
	var F = document.forms[0];
	if (!F.alternateDelivery || F.alternateDelivery.value == 'Ja') return undefined;
	
	if (F.alternateDelivery[0].checked) {
		$("#delv_title").parent().hide();
		$("#delv_initials").parent().hide();
		$("#delv_firstname").parent().hide();
		$("#delv_lastnamePrefix").parent().hide();
		$("#delv_lastname").parent().hide();
		$("#delv_postalCode").parent().hide();
		$("#delv_housenumber").parent().hide();
		$("#delv_housenumberSuffix").parent().hide();
		$("#delv_streetname").parent().hide();
		$("#delv_city").parent().hide();
		$("#delv_country").parent().hide();
		$("#delv_phone").parent().hide();
		$("#delv_dateOfBirth").parent().hide();
		$("#delv_email").parent().hide();
	} else {
		$("#delv_title").parent().show();
		$("#delv_initials").parent().show();
		$("#delv_firstname").parent().show();
		$("#delv_lastnamePrefix").parent().show();
		$("#delv_lastname").parent().show();
		$("#delv_postalCode").parent().show();
		$("#delv_housenumber").parent().show();
		$("#delv_housenumberSuffix").parent().show();
		$("#delv_streetname").parent().show();
		$("#delv_city").parent().show();
		$("#delv_country").parent().show();
		$("#delv_phone").parent().show();
		$("#delv_dateOfBirth").parent().show();
		$("#delv_email").parent().show();
	}
	return undefined;
};

function initAlternateDelivery()
{
	var F = document.forms[0];
	if (F.alternateDelivery && F.alternateDelivery.value == 'Ja') return undefined;
	
	$("#delv_title").parent().hide();
	$("#delv_initials").parent().hide();
	$("#delv_firstname").parent().hide();
	$("#delv_lastnamePrefix").parent().hide();
	$("#delv_lastname").parent().hide();
	$("#delv_postalCode").parent().hide();
	$("#delv_housenumber").parent().hide();
	$("#delv_housenumberSuffix").parent().hide();
	$("#delv_streetname").parent().hide();
	$("#delv_city").parent().hide();
	$("#delv_country").parent().hide();
	$("#delv_phone").parent().hide();
	$("#delv_dateOfBirth").parent().hide();
	$("#delv_email").parent().hide();
	
	return undefined;
};

function initDigitaalPlusUpgrade()
{
	var F = document.forms[0];
	if (F.aboId) 
		F.aboId.value = getParameter(unescape(document.location.href.toLowerCase()),'aboid');
	if (F.klantId) 
		F.klantId.value = getParameter(unescape(document.location.href.toLowerCase()),'klantid');
	if (F.hash) 
		F.hash.value = getParameter(unescape(document.location.href.toLowerCase()),'hash');
}

function checkInitials(ctrl) {
	var val = getValue(ctrl);
	var valid = val.match(/[^\.]/);
	if (valid) {
		var parts = val.toUpperCase().split(".");
		var newval = "";
		for (var i = 0; i < parts.length; i++) {
			var subp = parts[i].split("");
			for (var j = 0; j < subp.length; j++) {
				newval += subp[j] + ".";
			}
		}
		ctrl.value = newval;
	}
	return valid ? undefined : "?";
}

function checkEmail2(ctrEmail2) {
	return (!ctrEmail2.form['email'] || ctrEmail2.form['email'].value == ctrEmail2.value) 
		? undefined
		: ERROR_INV_EMAIL2;
}

function checkAlternateDelivery(ctrAlternateDelivery) {
	var F = document.forms[0];
	return (!ctrAlternateDelivery || getValue(ctrAlternateDelivery)=="Nee" || (getValue(ctrAlternateDelivery)=="Ja" && !(F.delv_title.value == 'O') && !empty(F.delv_initials.value) && !empty(F.delv_lastname.value) && !empty(F.delv_postalCode.value) && !empty(F.delv_housenumber.value) && !empty(F.delv_streetname.value) && !empty(F.delv_city.value) && !empty(F.delv_country.value))) 
		? undefined
		: ERROR_INV_ALTERNATEDELIVERY;
}

function checkDate(ctrDate) {
	var isValid = true;
	var today = jQuery.datepicker.formatDate('yy-mm-dd', new Date());

	try{
		jQuery.datepicker.parseDate('dd-mm-yy', getValue(ctrDate));
	}
	catch(error){
		isValid = false;
	}
	if (isValid)
		isValid = getValue(ctrDate).substring(6) > '1900' && getValue(ctrDate).substring(6) + '-' + getValue(ctrDate).substring(3,5)+ '-' + getValue(ctrDate).substring(0,2) < today;  
		
	return isValid
	? undefined
	: ERROR_INV_DATE;

}
function empty(str) {
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if (str==null || str.length==0 || str.search(re) > -1 || str=="") { return true; } else { return false; }
};



function nojs(txt) { // removes possible malicious JS insertion before showing preview pane
  txt.replace(/[\"\'][\s]*javascript:(.*)[\"\']/g, "\"\"");
  txt = txt.replace(/script(.*)/g, "");
  txt = txt.replace(/eval\((.*)\)/g, "");
  return txt;
};



function filterkeys(a, mode){
  var k, e;

  if (a)   {
	  if ("which" in a){ k=(e=a).which}
	  else if("keyCode" in a){k=(e=a).keyCode}
  } 
  else if (window.event)
  {
	if("keyCode" in window.event) {k=(e=window.event).keyCode }
	else if ("which" in window.event) {k=(e=a).which}
  }
  else { return true }

  if (e.altKey || e.ctrlKey || k < 48) return true;

  if (mode == 'zip') { // zipcode : first 4 numeric last two alpha
    if (document.forms[0].postalCode.value.length < 4) { mode = 'num' } else { mode = 'alpha' }
  }

  if (mode == 'delv_zip') { // zipcode : first 4 numeric last two alpha
	    if (document.forms[0].delv_postalCode.value.length < 4) { mode = 'num' } else { mode = 'alpha' }
	  }

  if (k == 8 || k == 9 || k == 46) { // allowed keys : 8 backspace, 9 tab
    return true;
  }

  if ( ((k>47 && k<58) || (k>95 && k<106)) && mode == "num") { // (48-57) numeric
    return true;
  }
  
  if (mode == "date"&&  ((k>47 && k<58) || (k>95 && k<106) || k == 109 || k == 189)) { // (48-57) date
	    return true;
	  }
	  
  if ( ( (k > 64 && k < 91) || (k > 96 && k < 123) ) && mode == "alpha") { // (64-91) lowercase alpha & (96-123) uppercase alpha
    return true;
  }

  if ( ( (k > 47 && k < 58) || (k>95 && k<106) || (k > 64 && k < 91) || (k > 96 && k < 123) || k == 32 ) && mode == "alphaspc") { // spaces & alphanumeric
    return true;
  }

  return false;
};


function filterchars(ctrl, e, mode) {
	
	if (e.which == 0 || e.ctrlKey || e.altKey)
		return;

	if (e.which == 8) return;
	
	
	if (mode == 'zip') { // zipcode : first 4 numeric last two alpha
		if (ctrl.value.length < 4) { mode = 'num' } else { mode = 'alpha' }
	}

	if (mode == 'num' && (e.which < 48 || e.which > 57)) {
		e.preventDefault();
		return;
	}
	
	if (mode == "date" && (e.which < 48 || e.which > 57) && e.which != 45) {
		e.preventDefault();
	    return;
	}
	
	if (mode == 'alpha' && !(e.which >= 65 && e.which <= 90 || e.which >= 97 && e.which <= 122 || e.which == 32)) {
		e.preventDefault();
	    return;
	}
}


function getValue(ctrl) {
	if (ctrl.value) {
		if (ctrl.type == 'checkbox')
			return ctrl.checked ? ctrl.value : "";
		
		return ctrl.value;
	}

	if (ctrl.item) {
		for (var i = 0; i < ctrl.length; i++)
			if (ctrl[i].checked)
				return ctrl[i].value;
	}
	return undefined;
}

var checker = {
	
	mandatory : [], // fields are begin fetched from labels with class=mandatory (see init())
	regexp    : { email:{check:isEmail_re, err:ERROR_INV_EMAIL}, 
				  //email2:{check:isEmail_re, err:ERROR_INV_EMAIL}, 
				  delv_email:{check:isEmail_re, err:ERROR_INV_EMAIL}, 
				  postalCode:{check:isPC_re, err:ERROR_POSTCODE}, 
				  delv_postalCode:{check:isPC_re, err:ERROR_POSTCODE}, 
				  prefDate:dateCheck, 
				  phone:{check:isPhone_re, err:ERROR_INV_PHONE},
				  delv_phone:{check:isPhone_re, err:ERROR_INV_PHONE}				  
		},

	codecheck : { 
		initials: function(c){return checkInitials(c)},
		delv_initials: function(c){return $("#delv_initials").parent().is(":visible") ? checkInitials(c) : undefined },
		account: function(c){return bankcheck()}, 
		email2: function(c){return checkEmail2(c)},
		title: function(c){return $(c).val() == 'O' ? checker.getMandatoryMsg('title') : undefined },
		delv_title: function(c){return ($(c).val() == 'O' && $("#delv_title").parent().is(":visible")) ? checker.getMandatoryMsg('delv_title') : undefined },
		confirm: function(c){return $(c).is(":checked") ? undefined : ERROR_INV_COND  },
		confirmPayment: function(c){return $(c).is(":checked") ? undefined : ERROR_INV_PAYMENT  },
		dateOfBirth: function(c){return checkDate(c)},
		delv_dateOfBirth: function(c){return $("#delv_dateOfBirth").parent().is(":visible") ? checkDate(c) : undefined }
		},

	checkedFormFields: {},

	init : function() {
		var F = document.forms[0];
		var self = this;

		// fetch mandatory fields based on label having mandatory class
		$("label.mandatory").each( function(){
			controlName = this.htmlFor;
			if (F[controlName]) {
				self.mandatory[self.mandatory.length] = controlName;
				self.checkedFormFields[controlName] = true;
			}
		});

		for (f in this.regexp) { if (F[f]) this.checkedFormFields[f] = true }
		for (f in this.codecheck) { if (F[f]) this.checkedFormFields[f] = true }
		
		// from the postback or static page?
		var staticPage = document.location.href.match(/\.html$/);
		this.check(null, true || staticPage);
	},

	checkSubmit: function(e, sendEvent) {
		var allChecked = true; //$("#confirm:checked").length > 0;
		// except all checked fields we have to get the confirmation
		// are all fields checked?
		for (f in this.checkedFormFields) 
			allChecked = allChecked && this.checkedFormFields[f];
		/*
		if (e && !allChecked) {
			e.preventDefault();
			e.stopPropagation();
		}
		*/
		//var $btn = $(":submit"); 
		//$btn.addClass(allChecked ? "enabled" : "disabled").removeClass(allChecked ? "disabled" : "enabled");

		//var btn = $btn[0];
		//btn.disabled = !allChecked;
		//btn.onclick = allChecked ? (function(){return this.disabled = true;}) : (function(){return false});
		//if (allChecked && sendEvent)
			//s.sendFormEvent('s', s.pageName, s.prop17);

		return allChecked;
	},

	check : function (sender, nonVisual) {
		var errors = {};

		var F = document.forms[0];

		// find out if any constraints have been applied to this sender
		var fConstrained = false; 

		for (var i = 0; i < this.mandatory.length; i++) {
			var f = this.mandatory[i];
			var ctrl = F[f];
			if (null == ctrl || (sender && ctrl != sender) || $("#" + f).parent().is(":hidden")) continue;
			var value = getValue(ctrl);
			
			if (empty(value)) {
				errors[f] = ERROR_EMPTY;
			}
			fConstrained = sender != null;
		}

		for (f in this.regexp) {
			if (errors[f]) continue;
			var ctrl = F[f];
			if (null == ctrl || (sender && ctrl != sender)) continue;
			var value = getValue(ctrl);

			if (value != null && !value.match(this.regexp[f].check)) {
				errors[f] = this.regexp[f].err;
			}
			fConstrained = sender != null;
		}

		for (f in this.codecheck) {
			if (errors[f]) continue;
			var ctrl = F[f];
			if (null != ctrl  && (!sender || ctrl == sender)) {
				var err = this.codecheck[f](ctrl);
				if (err) errors[f] = err;
				fConstrained = sender != null;
			}
		}

		var hasErrors = false;
		for (f in errors) {
			this.checkedFormFields[f] = false;
			hasErrors = true;
		}

		var errTags = $("label");
		if (!nonVisual && (!fConstrained && hasErrors))
		{
			var errorHTML = "";
			var errorsGAnalytics = "";

			for (var n = 0; n < errTags.length; n++)
			{
				var f = errTags[n].htmlFor;
				if (f in errors) {
					var err = errors[f];
					if (err == ERROR_EMPTY)
						err = sender == null ? this.getMandatoryMsg(f) : "";

					if (err) {
						errorHTML += (errorHTML ? "<br/>" : "");
						errorHTML += err + ".";
						$(errTags[n]).addClass("error");
						errorsGAnalytics += f + ",";
						continue;
					}
				}	
				$(errTags[n]).removeClass("error");

			}

			if (errorHTML){
				$("#errors").css("display", "block").children("span").html(errorHTML);
			}
			if (errorsGAnalytics){
				_gaq.push(['_trackEvent', 'Form', 'Error', errorsGAnalytics]);
			}
		}


		if (!hasErrors) {
			if (sender) {
				this.checkedFormFields[sender.name] = true;
				errTags.filter("[for=" + sender.id + "]").each(function() {$(this).removeClass("error")});
			}
			else { 
				$("#errors").css("display", "none");
			}
		}

		return hasErrors;
	},


	getTitle: function(id) {
		var html = "";
		if ($("#label_" + id).html() != null) {
			html = $("#label_" + id).html();
		} else {
			html = $("#" + id).parent("div.formelt").children("label").html();
		}
		if (html) {
			html = html.replace(/<.*$/m, "");
			html = html.replace(/^\s+/m, "");
			html = html.replace(/\s+$/m, "");
		}
		return html || '?';
	},

	getMandatoryMsg: function (id) {
		var type = $("#" + id)[0].type;
		var todo = INFO_SOURCE[type] || INFO_SOURCE['*'];
		var title = this.getTitle(id);
		var prefix = DUTCH_HET.test(title) ? 'Het' : 'De';
		return prefix + " " + title.toLowerCase() + " " + ERROR_MANDATORY.replace("$", todo); 
	},

	checkAll: function() { return !this.check() }
};



function update(sender, initial) {
	return checker.check(sender, initial);
};




function initcheck() {
	$(":input").change(function() { $(this).parents("fieldset").find(":input").each(function() { update(this) }) });
//	$("#postalCode").keydown(function(e) { return filterkeys(e, "zip") }).keypress(function(e) { return filterchars(this, e, "zip") });
//	$("#delv_postalCode").keydown(function(e) { return filterkeys(e, "delv_zip") }).keypress(function(e) { return filterchars(this, e, "zip") });
	$("#account,#housenumber,#delv_housenumber,#phone,#delv_phone").keydown(function(e) { return filterkeys(e, "num") }).keypress(function(e) {filterchars(this, e,"num")});
	$("#dateOfBirth,#delv_dateOfBirth,#prefDate").keydown( function(e) { return filterkeys(e, "date") }).keypress(function(e) {filterchars(this, e,"date")});;
	$(":submit").click(function(e) { update(); $('input[type=submit]', this).attr('disabled', 'disabled'); return checker.checkSubmit(e, false) });
	$("form").submit(function(e) { update(); $('input[type=submit]', this).attr('disabled', 'disabled'); return checker.checkSubmit(e, true) });
	//$("#dateOfBirth").click( function(e) {var $this = $(this); if (this.value == "dd-mm-yyyy") this.value = ""});
	$(":input[@name='alternateDelivery']").click( function() { show_hide_alternateDelivery() });

	/*
	// DISABLE hitting the <ENTER> on forms
	$("form").keypress(function(e) { 
		var key = (e.which || e.keyCode); 
		if (key == 13) e.preventDefault();
	});
*/
	$("input:checkbox,input:radio").css("border", "none");
	$("#initials,#delv_initials").css("text-transform", "uppercase");

	checker.init();
	preselectRadioButtons();
	initVarListeners();
	initAlternateDelivery();
	initDigitaalPlusUpgrade();
	update(null, true);
};



function ProcessLR(data) 
{
	data[fldStreet] = data.street;
	data[fldCity] = data.city;

	$("#"+fldStreet+",#"+fldCity)
		.each(function() {
			var $this = $(this);
			this.readOnly = data[this.id] ? true : false;
			this.readOnly ? $this.addClass("disabled") : $this.removeClass("disabled");
			$this.val(data[this.id] || ""); 
			update(this);
		});
		
	if (data.city) {
		var jq = $("#"+fldHousenr).parent().nextAll().children("input").not(".disabled");
		if (jq.length) jq[0].focus();
	}
}

function ProcessDelvLR(data) 
{
	data[fldDelvStreet] = data.street;
	data[fldDelvCity] = data.city;

	$("#"+fldDelvStreet+",#"+fldDelvCity)
		.each(function() {
			var $this = $(this);
			this.readOnly = data[this.id] ? true : false;
			this.readOnly ? $this.addClass("disabled") : $this.removeClass("disabled");
			$this.val(data[this.id] || ""); 
			update(this);
		});
		
	if (data.city) {
		var jq = $("#"+fldDelvHousenr).parent().nextAll().children("input").not(".disabled");
		if (jq.length) jq[0].focus();
	}
}


function LookupAddress(pc, nr)
{
	if (!pc || !nr) return null;
	var re = new RegExp("^(\\d{4})\\s*?(\\w{2})$");
	var match = re.exec(pc);
	if (match == null || !(nr.match(/^\d+$/))) return null;

	var zip = match[1] + match[2];
	var url = "/landers/order/pclookup.do?pc=" + zip + "&nr=" + nr;
	var resp = $.getJSON(url, undefined, ProcessLR);
}

function LookupDelvAddress(pc, nr)
{
	if (!pc || !nr) return null;
	var re = new RegExp("^(\\d{4})\\s*?(\\w{2})$");
	var match = re.exec(pc);
	if (match == null || !(nr.match(/^\d+$/))) return null;

	var zip = match[1] + match[2];
	var url = "/landers/order/pclookup.do?pc=" + zip + "&nr=" + nr;
	var resp = $.getJSON(url, undefined, ProcessDelvLR);
}

function doLookup() {
	var zipcode = document.getElementById(fldZipcode);
	var housenr = document.getElementById(fldHousenr);
	if (zipcode && housenr) {
		LookupAddress(zipcode.value, housenr.value);
	}
}

function doDelvLookup() {
	var zipcode = document.getElementById(fldDelvZipcode);
	var housenr = document.getElementById(fldDelvHousenr);
	if (zipcode && housenr) {
		LookupDelvAddress(zipcode.value, housenr.value);
	}
}

function initPcLookup(pc) {
	if (pc) fldZipcode = pc;
	$("#" + fldZipcode + ", #" + fldHousenr).bind("change", doLookup);
}

function initDelvPcLookup(pc) {
	if (pc) fldDelvZipcode = pc;
	$("#" + fldDelvZipcode + ", #" + fldDelvHousenr).bind("change", doDelvLookup);
}

function getParameter ( queryString, parameterName ) {
	  var parameterName = parameterName + "=";
	  if ( queryString.length > 0 ) {
	    begin = queryString.indexOf ( parameterName );
	    if ( begin != -1 ) {
	      begin += parameterName.length;
	      end = queryString.indexOf ( "&" , begin );
	      if ( end == -1 ) {
	        end = queryString.length
	      }
	      return unescape ( queryString.substring ( begin, end ) );
	    }
	    return "null";
	  }
	}

jQuery(initcheck);

