// Variables

divs = new Array("Aanvrager","Woonwensen","Financieel");
InkomensEisFactor = 4.5;

// Functions


function checkAutocollection(veld) {
	if (veld.checked == false) {
		removeError("10005",veld)
		showError(ERRORAUTOCOLLECTION,"10005",veld,"nofocus");
	} else {
		removeError("10005",veld)
	}
}



function checkGeneralConditions(veld) {
	if (veld.checked == false) {
		removeError("10011",veld)
		showError(CHECKGENERALCONDITIONS,"10011",veld,"nofocus");
	} else {
		removeError("10011",veld)
	}
}


/*
function checkGeneralConditions(veld) {
	if (veld.value == 'niet_akkoord') {
		removeError("10011",veld)
		showError(CHECKGENERALCONDITIONS,"10011",veld,"nofocus");
	} else if (veld.value == '') {
		showError("","",veld);
	} else {
		removeError("10011",veld)
	}
}
*/


function checkDate(veld) {
	var dateError = false;

	var dateStr = veld.value;

	if (dateStr.length == 0) {
		return;
	}

	var datePats = /^(\d{8})$/;
	var matchArrays = dateStr.match(datePats); // is the format ok?

	if (matchArrays != null) {
		var dateStr = dateStr.substring(0,2) + '-' + dateStr.substring(2,4) + '-' + dateStr.substring(4,8);
	}

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
		removeError("10007",veld);
		showError(ERRORDATE1 + dateStr,"10007",veld,"nofocus");
		var dateError = true;
		return;
	} else {
		day = matchArray[1]; // p@rse date into variables
		month = matchArray[3];
		year = matchArray[5];
		if (day.length == 1) {
			var day = "0" + day;
		}
		if (month.length == 1) {
			var month = "0" + month;
		}
		veld.value = day + '-' + month  + '-' + year;
		removeError("10007",veld);
	}

	if (month < 1 || month > 12) { // check month range
		removeError("10007",veld);
		showError(ERRORDATE2,"10007",veld,"nofocus");
		error = true;
		return;
	}

	if (day < 1 || day > 31) {
		removeError("10007",veld);
		showError(ERRORDATE3,"10007",veld,"nofocus");
		error = true;
		return;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		removeError("10007",veld);
/*		showError(ERRORDATE4.evaluate([month]),"10007",veld,"nofocus"); */
		showError(ERRORDATE4,"10007",veld,"nofocus");
		error = true;
		return;
	}

	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			removeError("10007",veld);
/*			showError(ERRORDATE5.evaluate([year, day]),"10007",veld,"nofocus"); */
			showError(ERRORDATE5,"10007",veld,"nofocus");
			error = true;
			return;
		}
	}

	if (year < 1900) { // check year above 1900
		removeError("10007",veld);
		showError(ERRORDATE6,"10007",veld,"nofocus");
		error = true;
		return;
	}
}


function checkInitials(veld) {
	var initials = veld.value.toUpperCase();
	var re = /[^A-Z]/g
	var initials = initials.replace(re,"");
	var initials = initials.split("");
	var initials = initials.join(".");
	if (initials.length > 0) {
		var initials = initials + '.';
	}
	veld.value = initials;
}


function checkZipcode(veld) {
	var zipcode = veld.value.toUpperCase();
	var re = /[^A-Z0-9]/g
	var zipcode = zipcode.replace(re,"");
	if (zipcode.length == 0) {
		return;
	}
	if (zipcode.length != 6) {
		removeError("10008",veld);
		showError(ERRORZIPCODE,"10008",veld,"nofocus");
		return;
	} else {
		removeError("10008",veld);
	}
	var pnum = zipcode.substring(0,4);
	var pchar = zipcode.substring(4,6);
	if (!pnum.match(/^(\d){4}$/)) {
		removeError("10008",veld);
		showError(ERRORZIPCODE,"10008",veld,"nofocus");
	}
	if (!pchar.match(/^[A-Z]{2}$/)) {
		removeError("10008",veld);
		showError(ERRORZIPCODE,"10008",veld,"nofocus");
	}
	var zipcode = pnum + " " + pchar;
	veld.value = zipcode;
}


function checkEmail(veld){
	var testresults
	var str=veld.value
	if (str.length == 0) {
		return;
	}
	var filter=/^([\w-]+(?:\.[\w-]+)*)@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str))
		testresults=true
	else {
		removeError("10013",veld);
		showError(ERROREMAIL,"10013",veld,"nofocus");
		testresults=false;
	}
	return (testresults)
}


function checkNetnummer(val)
{
   var match=false;
   var myArray= new Array ('010','013','015','020','023','024','026','030','033','035','036','038','040','043','045','046','050','053','055','058','070','071','072','073','074','075','076','077','078','079')
   for (i=0;i<myArray.length;i++)
   {
      if (myArray[i]==val)
      {
         match=true;
      }
   }
   return match;
}


function checkTelephone(veld) {
	var telefoon = veld.value;
	var re = /[^0-9]/g
	var telefoon = telefoon.replace(re,"");
	if (telefoon.length == 0) {
		return;
	}
	if (telefoon.length != 10) {
		removeError("10006",veld);
		showError(ERRORTELEPHONE1,"10006",veld,"nofocus");
		return;
	} else {
		removeError("10006",veld);
	}
	if(/^[1-9]/.test(telefoon)) {
		removeError("10006",veld);
		showError(ERRORTELEPHONE2,"10006",veld,"nofocus");
		return;
	}
	if (checkNetnummer(telefoon.substring(0,3)) == true) {
		veld.value = telefoon.substring(0,3) + "-" + telefoon.substring(3,10);
	} else {
		if(/^06/.test(telefoon)) {
			veld.value = telefoon.substring(0,2) + "-" + telefoon.substring(2,10);
		} else {
			veld.value = telefoon.substring(0,4) + "-" + telefoon.substring(4,10);
		}
	}
}


function trimLeadingZeros(val) {
	while (val.substr(0,1) == '0' && val.length>0) {
		val = val.substr(1,9999);
	}
	return val;
}


function elfProef(veld){
	var veldvalue = stripAlphaChars(veld.value);
	veld.value = trimLeadingZeros(veldvalue);
	var elNameLength  = veld.value.length;
	var total         = 0;
	var bankLength    = 9;
	var result        = false;
	var regex         = new RegExp(/\d{9}$/);

	if (elNameLength == 0) {
		return;
	}

	if (document.registrationform.accounttype.value == 'giro') {
		removeError("10001",veld);
		return;
	}

	if (elNameLength == bankLength) {
		var rekLength = 'ok';
	}

    if ( regex.test(veld.value) ){ // Checked op minimale lengte en cijfers
        for(var i = 0; i < elNameLength; i++){ // Begin elf-proef
            total += parseInt(veld.value.substr(i,1)) * bankLength;
            bankLength--;
        }
        if ( (parseInt(total) % 11) == 0){
        	if (rekLength) {
        		result = true;
        	}
        }
    }

    if (result == false) {
		removeError("10001",veld);
		showError(ERRORELFPROEF,"10001",veld,"nofocus");
    } else {
    	removeError("10001",veld);
    }

}


function checkChildnumber(veld) {
	var kidsError = false;
	var kids = veld.value;

	if (kids.length == 0) {
		return;
	}

	var kidsPats = /^(\d)*$/;
	var kidsmatch = kids.match(kidsPats); // is the format ok?

	if (kidsmatch == null) {
		var kidsError = ERRORCHILDNUMBER1;
	}

	if (kids > 20) {
		var kidsError = ERRORCHILDNUMBER2.evaluate([kids]);
	}

	if (kidsError == false) {
		removeError("10002",veld);
	} else {
		removeError("10002",veld);
		showError(kidsError,"10002",veld,"nofocus");
	}
}


function checkKamers() {
	var min = document.registrationform.requirementroomsmin;
	var max = document.registrationform.requirementroomsmax;
	if (min.value > max.value) {
		removeError("10003",max);
		showError(ERRORKAMERS,"10003",max,"nofocus");
	}
}


function stripAlphaChars(pstrSource)
{
var m_strOut = new String(pstrSource);
    m_sOut = m_strOut.replace(/[^0-9]/g, '');

    return m_sOut;
}


function checkEmptyFieldsTabs(tab) {
	var emptyRF = 0;

	var rfs = '';
	if (tab == 1) {
		var rfs = new Array();
		if (document.registrationform.cohabit.value == 'ja') {
			rfs.push("nationalityperson2","socialsecuritynumberperson2","birthdayperson2","lastnameperson2","initialsperson2","cohabit");
		} else {
			rfs.push("cohabit");
		}
		rfs.push("childnumber","maritalstatus","nationality","socialsecuritynumber","birthday","email","telephone","locality","zipcode","number","street","lastname","initials");
	} else if (tab == 2) {
		var rfs = new Array("requirementleasepricemax","requirementleasepricemin","startdate","requirementfloor","requirementlift","requirementparking","requirementroomsmax","requirementroomsmin","requirementobjecttype","currentlivingcondition");
	} else if (tab == 3) {
		var rfs = new Array("autocollection","generalconditions","income","accountplace","accountnumber","accounttype");
		if (document.registrationform.cohabit.value == 'ja') {
			rfs.push("incomeperson2");
		}
	}

	if (rfs.length != 0) {
		for (j=0;j<rfs.length;j++) {
			x = document.registrationform.elements[rfs[j]];
			if (x.value == '') {
				emptyRF++;
				RFvalue = rfs[j];
				showError("","",x);
			} else {
				removeError("",x);
			}
		}
	}

	if (emptyRF != 0) {
		showError(ERROREMPTYFIELDS,"10004",0);
	}
}


function noPartner() {
	document.getElementById('cohabit').value = 'nee';
	checkCohabit(document.getElementById('cohabit'));
}


function checkCohabit(veld) {
	var reqs = new Array("req1","req2","req3","req4","req5","req6");
	if (veld.value == 'ja') {
		for (j=0;j<reqs.length;j++) {
			document.getElementById(reqs[j]).style.display = '';
		}
		document.getElementById('partnertext1').style.display = 'none';
		document.getElementById('partnertext2').style.display = '';
	} else {
		for (j=0;j<reqs.length;j++) {
			document.getElementById(reqs[j]).style.display = 'none';
		}
		document.getElementById('partnertext1').style.display = '';
		document.getElementById('partnertext2').style.display = 'none';
	}
}


function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}


function checkNumber(veld) {
	var nr = veld.value;

	if (nr.length == 0) {
		removeError("10004",veld);
		showError(ERROREMPTYFIELDS,"10004",veld,"focus");
		return;
	}

	if (nr.match(/^(\d)*$/) == null) {
		showError(ERRORNUMBERS1,"10009",veld,"focus");
	}
}


function checkMultipleNumbers (fields) {
	if (isArray(fields)) {
		for (var i=0; i<fields.length; i++) {
			removeError("", fields[i]);
		}
		for (var i=0; i<fields.length; i++) {
			checkNumber(fields[i]);
		}
	}
}


function checkNumbers(veld, uitleg, markfocus) {
	var nr = veld.value;

	if (nr.length == 0) {
		return;
	}

	if (nr.match(/^(\d)*$/) == null) {
		removeError("10009",veld);
		if (!uitleg) {
			var uitleg = ERRORNUMBERS1;
		}
		if (!markfocus) {
			showError(uitleg,"10009",veld,"nofocus");
		} else {
			showError(uitleg,"10009",veld,"focus");
		}
	} else {
		removeError("10009",veld);
	}
}


function checkLeaseprice() {
	var min = document.registrationform.requirementleasepricemin;
	var max = document.registrationform.requirementleasepricemax;
	if (parseInt(min.value) >= parseInt(max.value)) {
		removeError("10010",max);
		showError(ERRORLEASEPRICE,"10010",max,"nofocus","dontfocus");
	} else {
		if (max.value != '') {
			removeError("10010",max);
		}
	}
}


function checkIncomeSetLeasepriceMax() {
	var ink = document.registrationform.income;
	var max = document.registrationform.requirementleasepricemax;
	if (max.value == '') {
		val = (ink.value / InkomensEisFactor);
		val = (val < 0 ? -1 : 1) * Math.floor(Math.abs(val));
		max.value = val;
	}
}


function checkAccounttype (veld) {
	if (veld.value == 'giro') {
		document.getElementById('accountownerrow').style.display = '';
	} else {
		document.getElementById('accountownerrow').style.display = 'none';
	}
}


function checkAccountowner (veld, act) {
	if (document.registrationform.accounttype.value == 'giro') {
		if (veld.value == '') {
			if (act == 'submit') {
				removeError("10012",veld);
				showError(ERRORACCOUNTOWNER,"10012",veld,"nofocus");
			} else {
				veld.value=ACCOUNTOWNERVALUE;
			}
		} else if (veld.value == ACCOUNTOWNERVALUE) {
			removeError("10012",veld);
			showError(ERRORACCOUNTOWNER,"10012",veld,"nofocus");
		} else {
			removeError("10012",veld);
		}
	}
}

function checkRequirementCity () {
	var city = document.registrationform.requirementcity1;
	if (city.value == 'Plaats') {
		removeError("10014",city);
		showError(ERRORCITY,"10014",city,"nofocus");
	} else {
		removeError("10014",city);
	}
}


function checkRequirementCities (veld, plaats) {
	var place = document.registrationform.elements[plaats];
	if (veld.value != 'Straat' && place.value == 'Plaats') {
		removeError("10015",place,'nocolor');
		showError(ERRORCITIES,"10015",place,"nofocus");
	} else {
		removeError("10015",place,'nocolor');
	}
}


function onFocusEmpty (veld, val) {
	if(veld.value==val) {
		veld.value='';
		bordercolor = Element.getStyle(veld,'border-top-color');
		if (bordercolor == 'rgb(255, 0, 0)' || bordercolor == '#ff0000') {
		} else {
			veld.style.color='#000000';
		}
	}
}


function onBlurFill (veld, val) {
	if(veld.value=='') {
		veld.value=val;
		veld.style.color='#AAAAAA';
	} else {
		removeError('',veld);
	}
}






//
//
//
//
//
//
//
//
//
//
// ALGEMEEN MAKEN (application.js) getBrowserWidth()
//
//
//
//
//
//
//
//
//
//


function getBrowserWidth(){
    if (window.innerWidth){
        return window.innerWidth;}
    else if (document.documentElement && document.documentElement.clientWidth != 0){
        return document.documentElement.clientWidth;    }
    else if (document.body){return document.body.clientWidth;}
        return 0;
}











function showError(tekst, id, veld, nofocus, dontfocus) {
	error = true;
	if (veld) {
		veld.style.border="1px solid #FF0000";
		veld.style.background = "#FFDDDD";
		veld.style.color = "#FF0000";

		if (navigator.appName == "Microsoft Internet Explorer" && nofocus == 'nofocus') {
		} else {
			if (!dontfocus) {
				veld.focus();
			}
		}
	}

	if (tekst) {
		var div = document.getElementById('errormessage');
		div.style.display = '';
		if (id) {
			div.innerHTML += "<div id=\"" + id + "\"><li>" + tekst + "</li></div>";
		} else {
			div.innerHTML += "<div><li>" + tekst + "</li></div>";
		}
	}
}


function removeError(id, veld, nocolor) {
	veld.style.border="1px solid #A4A4A4";
	veld.style.background = "#FFFFFF";
	if (!nocolor) {
		veld.style.color = "#000000";
	}
	if (id) {
		if (document.getElementById(id)) {
			document.getElementById('errormessage').removeChild(document.getElementById(id));
		}
		if (document.getElementById('errormessage').innerHTML == '') {
			document.getElementById('errormessage').style.display = 'none';
		}
	}
}


function hideError() {
	document.getElementById('errormessage').style.display = 'none';
}


function checkTab(tab, nexttab, focusfield) {
	error = false;
	tekst = "";
	document.getElementById('errormessage').innerHTML = "";
	checkEmptyFieldsTabs(tab);
	checkInitials(document.registrationform.initials);
	checkNumbers(document.registrationform.number);
	checkZipcode(document.registrationform.zipcode);
	checkTelephone(document.registrationform.telephone);
	checkEmail(document.registrationform.email);
	checkDate(document.registrationform.birthday);
	checkChildnumber(document.registrationform.childnumber);
	checkCohabit(document.registrationform.cohabit);
	if (document.getElementById('cohabit').value == 'ja') {
		checkDate(document.registrationform.birthdayperson2);
	}
	if (tab >= 2) {
		checkRequirementCity();
		checkRequirementCities(document.registrationform.requirementstreet2, 'requirementcity2');
		checkRequirementCities(document.registrationform.requirementstreet3, 'requirementcity3');
		checkRequirementCities(document.registrationform.requirementstreet4, 'requirementcity4');
		checkRequirementCities(document.registrationform.requirementstreet5, 'requirementcity5');
		checkKamers();
		checkDate(document.registrationform.startdate);
/*		checkNumbers(document.registrationform.requirementleasepricemin, '', 'markfocus');
		checkNumbers(document.registrationform.requirementleasepricemax, '', 'markfocus'); */
		checkMultipleNumbers([document.registrationform.requirementleasepricemin, document.registrationform.requirementleasepricemax]);
		checkLeaseprice();
	}
	if (tab >= 3) {
		checkGeneralConditions(document.registrationform.generalconditions);
		checkAutocollection(document.registrationform.autocollection);
		checkNumbers(document.registrationform.income,ERRORNUMBERS2);
		checkAccountowner(document.registrationform.accountowner,'submit');
		elfProef(document.registrationform.accountnumber);
	}
	if (error == false) {
		hideError();
		tabbar.enableTab(nexttab);tabbar.setTabActive(nexttab);
		if (focusfield) {
			document.registrationform.elements[focusfield].focus();
		}
		return true;
	} else {
		return false;
	}
}


function toggleDiv(div) {
document.getElementById("chkalgvw").style.display = 'block';

	for (i=0;i<divs.length;i++) {
		if (divs[i]==div) {
			document.getElementById(divs[i]).style.display = 'block';
		} else {
			document.getElementById(divs[i]).style.display = 'none';
		}
	}
}


function checkSelects(idn) {

	for (d=idn;d<=divs.length;d++) {
		if (d == idn) {
			var a = d - 1;
			toggleDiv(divs[a]);
			if (navigator.appName != "Microsoft Internet Explorer") {
				switch(idn){
					case '1':
					document.registrationform.initials.focus();
					break;
					case '2':
					document.registrationform.requirementcity1.focus();
					break;
					case '3':
					document.registrationform.accounttype.focus();
					break;
					default:
					alert('default');
				}
			}
		} else {
			tabbar.disableTab(d);
		}
	}
	return true;
}


function submitForm () {
	var show = '';
	if (document.registrationform.cohabit.value == 'ja') {
		var inkomen = parseInt(document.registrationform.income.value) + parseInt(document.registrationform.incomeperson2.value);
	} else {
		var inkomen = document.registrationform.income.value;
	}
	var show = show + "\nInkomenseis factor: " + inkomen / document.registrationform.requirementleasepricemax.value;
	for(i=0; i<document.registrationform.elements.length; i++) 	{
		if (i != 0)
			var show = show + "\n" + document.registrationform.elements[i].name + ": " + document.registrationform.elements[i].value;
	}
//	alert(show);
	document.registrationform.submit();
}

/***************************************
* Textarea limiet
* http://www.Mastercode.nl
* Door: Ted [webmaster[A]mastercode[P]nl
***************************************/
function limiet(veld, maximum, telveld)
{
   if (veld.value.length > maximum)
      veld.value = veld.value.substring(0, maximum);
   else
      document.getElementById(telveld).firstChild.nodeValue = (maximum - veld.value.length);
}
