

function CheckMaxLength (field, maxlength, displayname)
{
	if (field.value.length > maxlength) {
		alert('Het veld ' + displayname + ' heeft een maximale lengte van ' + maxlength + ' karakters');
		
		field.focus();
		return false;
	} else {
		return true;
	}
}


/*
 ####################################################
 autocomplete 
 ####################################################
*/

function matchFieldSelect (field, select, value) 
{
  var property = value ? 'value' : 'text';
  var found = false;
  for (var i = 0; i < select.options.length; i++)
    if ((found = select.options[i][property].indexOf(field.value) == 0))
      break;
  if (found)
    select.selectedIndex = i;
  else
    select.selectedIndex = -1;
  if (field.createTextRange) {
    var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;"
    if (cursorKeys.indexOf(event.keyCode+";") == -1) {
      var r1 = field.createTextRange()
      var oldValue = r1.text;
      var newValue = found ? select.options[i][property] : oldValue;
      if (newValue != field.value) {
        field.value = newValue
        var rNew = field.createTextRange()
        rNew.moveStart('character', oldValue.length) 
        rNew.select()
      }
    }
  }
}

function ShowList(divlist, left, top) 
{
	if (divlist) {
		divlist.style.position = 'absolute';
		divlist.style.visibility = 'visible';
		if (left) divlist.style.left = left;
		if (top) divlist.style.top = top;
	}
}


function HideList(divlist, left, top)
{
	if (divlist) {
		divlist.style.visibility = 'hidden';
		
		if (left) divlist.style.left = left;
		if (top) divlist.style.top = top;
	}
}

function ToggleDiv(clickbutton, elementDIV)
{
	//try to toggle div
	
	bu = document.getElementById('laatsterecordBUTT');
	el = document.getElementById('laatsterecordDIV');
	//alert(bu.basename);
	//alert(el);
	try 
	{
		if (el.style.visibility == 'hidden') {			
			el.style.position   = 'relative';
			timer = setTimeout("el.style.visibility = 'visible'", 1);
			bu.innerText = 'Verberg ' + bu.basename;
		}else {
			el.style.visibility = 'hidden';
			el.style.position   = 'absolute';	
			bu.innerText = 'Toon ' + bu.basename;	
		}
	
	
	} catch(errorObject) {
		// do nothing
		//return true;
		
			
	}

}
/*
 ####################################################
 value checks 
 ####################################################
*/
function CheckField(objName) 
{
	var fieldName = objName;
	// if the field is not enabled we can 
	// assert that all conditions are met
	if (!fieldName) {
	    alert( 'CheckField called with undefined argument' );
	}
	if (fieldName.disabled == true) return true;
	
	// else
	if (IsEntered(fieldName) == false) {
		alert("Niet alle verplichte velden zijn ingevuld.");
		try {
			fieldName.focus();
		} catch(e) {
			//alert('catch error');
		}
		return false;
	} else {
		return true;
   }
}

function IsEntered(objName) 
{
	var fieldName = objName;
	
	if ((fieldName.value) && (fieldName.value !='') && (fieldName.value.length > 0) ) {
		return true
	} else {
		return false;		
	}
}



function HasSelected(theForm, objName) {
	var fieldName = objName;
	
	if (fieldName.value == '') {
		alert ('Niet alle verplichte velden zijn ingevuld.');
		return false;
	} else {
		return true;
	}
}


function VerifyPassword(objPassword1, objPassword2) {
	if (objPassword1.value != objPassword2.value) {
		alert ('De wachtwoorden zijn niet identiek.');
		return false;
	} else {
		return true;
	}
}

function MultiChecked(theForm, formfield) 
{	

	//var theForm = document.forms[0];
	var selName = formfield;
	// get a handle to the object
	var selObject = GetObjectArrayFromName( theForm, selName );
	
	// programmer error?
	if (selObject == null ) {
		alert("Formulierfout: " + selName + "niet gevonden.");
		return false;
	}
	// check at least one checkbox is checked
	checkFlag = false;
	for (i=0, max=selObject.length; i < max; i++) {
		if (selObject[i].checked) checkFlag = true;	
	}
	// halt submit of form if not enough info
	if (!checkFlag) {
		alert("Niet alle verplichte velden zijn ingevuld.");
		return false;
	} else 
	 	return true;
}

function MultiCheckedNoAlert(theForm, formfield) 
{	

	//var theForm = document.forms[0];
	var selName = formfield;
	// get a handle to the object
	var selObject = GetObjectArrayFromName( theForm, selName );
	
	// programmer error?
	if (selObject == null ) {
		alert("Formulierfout: " + selName + "niet gevonden.");
		return false;
	}
	// check at least one checkbox is checked
	checkFlag = false;
	for (i=0, max=selObject.length; i < max; i++) {
		if (selObject[i].checked) checkFlag = true;	
	}
	// halt submit of form if not enough info
	if (!checkFlag) {
		return false;
	} else 
	 	return true;
}


function isNumBetween(n, min, max) {
	return(
		(n >= (min!=null ? min : Number.MIN_VALUE)) &&
		(n <= (max!=null ? max : Number.MAX_VALUE))
	);
}

function CheckYear(objName)
{
	var d = new Date();
	var currentyear = d.getFullYear();
	var fieldName = objName;
	if(fieldName.value.length == 2){
		if (fieldName.value < (currentyear-2000)){
			fieldName.value = "20"+fieldName.value;
		} else {
			fieldName.value = "19"+fieldName.value;
		}
	}


	if(isNumBetween(fieldName.value,currentyear-100,currentyear)){
		return true;
	}else{
		alert("Het geboortejaar klopt niet.")
		return false;
	}

}
function CheckMonth (objName)
{
	var month = objName.value;
		if(month != 0){
		return true;
	}else{
		alert("Kies een geboortemaand.")
		return false;
	}
}

function CheckDay(objName)
{
	var day = objName.value;
	if(isNumBetween(day,1,31)){
		return true;
	}else{
		alert("De geboortedag klopt niet.")
		return false;
	}
}


/*
 ####################################################
 Time and time interval checks
 ####################################################
*/

function UpdateDuration(theForm, loopID) 
{
	if (!loopID) loopID = '';
	eval('var starttime = theForm.starttime'+loopID+'.value;');
	eval('var stoptime  = theForm.stoptime'+loopID+'.value;');
	
	var startminutes = TimeToMinutes(starttime);	
	if(!startminutes)
	{
		//theForm.starttime.focus()
		return false;
	}
	var stopminutes = TimeToMinutes(stoptime);
	if(!stopminutes)
	{
		//theForm.stoptime.focus()
		return false;
	}	
	eval( 'var durationObj = theForm.duration'+loopID+';');
	durationObj.value = '';
	if ( (stopminutes*1) < (startminutes*1) ) 
			stopminutes += 60*24;
	
	var duration = (stopminutes - startminutes);
	
	durationObj.value = MinutesToTime(duration);
	
	return true;

}
function GetCurrentTime()
{
	now = new Date;
	theHour = now.getHours();
	theMinute = now.getMinutes();
		
	if (theMinute<10) theMinute = '0' + theMinute;
	
	return theHour + ':' + theMinute;
}

function HasTime(theField)
{	
	if ((theField.value=='')||IsTime(theField.value)) {		
		return true;
	}else {
		alert("vul de tijd in als HH:MM. Bijvoorbeeld 14:35 of 9:10");
		theField.focus();
		theField.select();
	}
}

function IsTime(theTime)
{		
	if (!theTime) return false	
	var aTime = theTime.split(':');			
	return !(aTime.length!=2 || isNaN(aTime[0]*1) || isNaN(aTime[1]*1) || aTime[0]>23 || aTime[1]>59 );
	
}
function TimeToMinutes(theTime)
{
	// check input
	if (!IsTime(theTime)) return false;	
	// convert HH:MM to Minutes
	var aTime = theTime.split(':');	
	return (aTime[0] * 60) + (aTime[1] * 1);
	
}

function MinutesToTime(theMinutes)
{
	// check input
	if (isNaN(theMinutes)) return false;
		
	var theHour = Math.floor((theMinutes*1)/60);
	var theMinute = (theMinutes*1)%60;
	
	if (theMinute<10) theMinute = '0' + theMinute;
		
	theTime = theHour + ':' + theMinute;
		
	return theTime;
}

/*
 need special javascript code to reach object handle 
 because of incompatibility between javascript and php
 when we want a multiple selection.
*/
function GetObjectArrayFromName(theForm, theObjectName ) {
	var theObjectArray = Array();
	a = 0;
	// go through each form element looking for the name
	for (var i=0,max=theForm.elements.length;i<max;i++) {
		if ( theForm.elements[i].name == theObjectName ) {
			// found it, add object to array
			theObjectArray[a] = theForm.elements[i];
			a++;
		}
   	}
	if (theObjectArray.length > 0) 
		return theObjectArray
	else
   	   return null;
}

function GetObjectFromName(theForm, theObjectName ) {
	
	// go through each form element looking for the name
	for (var i=0;i<theForm.elements.length;i++) {
		if ( theForm.elements[i].name == theObjectName ) {
			// found it, add object to array
			return theForm.elements[i];			
		}
   	}
	// object not found
   	return null;
}
/*
 ##################################################
 multirow form functions
 ##################################################
*/

function ToggleForcelink(chkboxislink) {
    
    var ff = document.getElementById('frmforcelink');
    var fs = document.getElementById('frmsjabloon')
    
    if (ff && fs) {
        
        if (chkboxislink.checked) {
            ff.disabled = false;
            fs.disabled = true;
            fs.style.border='1px solid #eee';
            
        } else {
            ff.disabled = true;
            fs.disabled = false;
            fs.style.border='';

        }//endif
        
    }//endif
}

function IsPostcode(objName) { 
    if (objName.value == '') {
        // if not set then valid postcode
        return true;
    } else if(3==3){
		objName.value = objName.value.toUpperCase();
		
		var regvalue = '^([1-9]{1}[0-9]{3})[\\s]{0,}([A-Z]{2})'; 
		
    	var reg = new RegExp( regvalue, "ig" ); 
    	if (result = reg.test(objName.value)) {
    		objName.value = RegExp.$1 + ' ' + RegExp.$2;
    		return true;
    	} else {
    		alert('Ongeldige postcode ');
    		objName.focus();
    		objName.select();
    		return false;
    	}
    	
	} else { 
		// Browser does not support JavaScript 1.2
	    return true; 
	}
} 

function IsValidEmail(objName) {
	var fieldName = objName;
	if (fieldName.value != '' && EmailCheck(fieldName.value) == false) {
		alert("Email adres is niet geldig.");
		fieldName.focus();
		return false;
	} else {
		return true;
	}
}
function EmailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
    // user is not valid
    	//alert("The username doesn't seem to be valid.")
    	return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
   		host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
    	// this is an IP address
	  	for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
	        	//alert("Destination IP address is invalid!")
				return false
	    	}
    	}
    	return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
	    return false
	}

	/* domain name seems valid, but now make sure that it ends in a
		four-letter word (like info)
	   	three-letter word (like com, edu, gov) or a two-letter word,
	   	representing country (uk, nl), and that there's a hostname preceding 
	   	the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
   		it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
    	domArr[domArr.length-1].length>5) {
   		// the address must end in a two letter or three letter word or four letter word.
   		//alert("The address must end in a three-letter domain, or two letter country.")
   		return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
   		var errStr="This address is missing a hostname!"
   		//alert(errStr)
   		return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}

function IsChecked(objName) {
	var fieldName = objName;
	if (IsRadioChecked(fieldName)){		
		return true;
	} else {
		if (fieldName.name == 'agreement'){
			alert("U moet nog accoord gaan met de voorwaarden.");
		}else{
			alert("Niet alle verplichte velden zijn ingevuld.");
		}
		//fieldName.focus();
		return false;		
	}	
	
}

function IsRadioChecked(objName) {
	var fieldName = objName;
	var imax = objName.length;	
	if (!imax) return objName.checked;
	var isChecked = false;
	for (i=0;i<imax;i++) {
		isChecked = (isChecked || fieldName[i].checked );
	}
	return isChecked;
	
}


function IsValidDate(Day,Mn,Yr){
    var DateVal = Mn + "/" + Day + "/" + Yr;
    var dt = new Date(DateVal);

    if(dt.getDate()!=Day){
        return(false);
        }
    else if(dt.getMonth()!=Mn-1){
    //this is for the purpose JavaScript starts the month from 0
        return(false);
        }
    else if(dt.getFullYear()!=Yr){
        return(false);
        }
        
    return(true);
}


function check_extension(filename) {
  var re = /\..+$/;
  var ext = filename.match(re);
  if (allowedExtensions[ext]) {
    return true;
  } else {
    return false;
  }
}

function htmlEncode(value){ 
  return $('<div/>').text(value).html(); 
} 

function htmlDecode(value){ 
  return $('<div/>').html(value).text(); 
}

