
/* ============================================================================================================
 * Standard-scripts for the checking and processing of forms
 * 
 * autoTab(input,len,e)
 *		- tabs to the next formitem when the number of characters is typed
 *		- example: <input type="text" onKeyUp="return autoTab(this, 2, event);">
 * 
 * checkEmail(adres)
 *		- returns true when the adres is a valid e-mail
 *		  address
 *		- example: emailCheck(g.sprokkereef@faceworks.nl)
 * 
 * toggleChexbox(idStr)
 *		- checks or unchecks the checkbox with the id idStr
 *		- depricated
 *		- use: <input id="myIdentifier" type="checkbox" name="mybox" value="true"><label for="myIdentifier">I like spam</label>
 * 
 * getDate(yearField, monthField, dayField)
 *		- returns a valid date or false
 *		- fields are form-objects
 *		- example: getDate(document.forms['update']['gebjaar'],document.forms['update']['gebmaand'],document.forms['update']['gebdag'])
 *		- fields may be a input-text or select form-element
 * 
 * checkDate(yearField, monthField, dayField)
 *		- returns true if the date is valid
 *		- fields are form-objects
 *		- example: checkDate(document.forms['update']['gebjaar'],document.forms['update']['gebmaand'],document.forms['update']['gebdag'])
 *		- fields may be a input-text or select form-element
 * 
 * checkRadio(radioGroup)
 *		- returns true if one of the radiobuttons of a group is checked 
 *		- example: checkRadio(document.forms['update']['sex']))
 *
 * hasLength(loFormItem,min,max)
 *		- returns true if the value of the formitem has the right length
 *		- the max parameter is optional
 *		- example: hasLength(document.forms['update']['name'],4,20) //langer dan 3, korter dan 21 tekens
 *		- example: hasLength(document.forms['update']['name'],4)    //minimaal 4 tekens lang
 *
 * getRadio(radioGroup)
 *		- returns the value if one of the radiobuttons of a group is checked else it returns an empty string
 *		- example: checkRadio(document.forms['update']['sex']))
 * 
 * checkChar(string,char)
 *		- returns true if the string contains one or more characters char.
 * 
 * replaceChar(string,oldString,newString)
 *		- replace characters or strings in a string with another string
 * 
 * checkPostcode(string)
 *		- returns true if the string contains a valid dutch postalcode
 *		- a postcode is valid when it contains 4 numeric characters and two characters eg. 1234 AB or 1234AB
 * 
 * checkPhone(string,no_of_digits)
 *		- returns true if the string contains a minimum of the defined number of numbers
 * 
 * hasInput(loFormItem)
 *      - returns true if the parameter formitem has had input
 *
 * getInput(loFormItem)
 *      - returns the value of a formitem
 *
 * checkNumeric(string)
 *		- returns true if the parameter is a numeric value, 
 *		  the value can be integer or decimal (decimal point)
 * 
 * 
 * addToArray(a,v)
 * 
 * existsInArray(a,v)
 * 
 * ============================================================================================================
 */


/*
 * autoTab
 */
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) 
{
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode))
	{
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
	}

	// functions for autotab
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
		found = true;
		else
		index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
		if (input.form[i] == input)index = i;
		else i++;
		return index;
	}
	return true;
}

/*
 * Controleer of een tekst is opgemaakt volgens 
 * het patroon van een e-mail adres
 */
function checkEmail(str)
{	
	/*
	 * Regels voor controle van e-mail adressen
	 * 
	 * Het adres moet beginnen met tenminste 1 teken voor de apenstaart (@)
	 *
	 * Een punt (.) en koppelteken (-) mogen niet naast elkaar staan en ook 
	 * niet naast de apenstaart (@)
	 * 
	 * Er moet 1 apenstaart (@) in het adres staan
	 * 
	 * Er moeten tenminste twee tekens na de apenstaart (@) staan
	 * 
	 * Het adres moet eindigen op een gekwalificeerde TLD (Top Level Domain)
	 * vooraf gegaan door een punt (.)
	 * 
	 */

	var domStr = "";
	// Well known official top level domains
	domStr += "com|edu|gov|int|mil|net|org|arpa|nato|info|aero|biz|coop|museum|name|pro|";
	// Alphabetically split top level domains
	domStr += "ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|";
	domStr += "ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|";
	domStr += "ca|cc|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|";
	domStr += "de|dj|dk|dm|do|dz|";
	domStr += "ec|ee|eg|eh|er|es|et|eu|";
	domStr += "fi|fj|fk|fm|fo|fr|fx|";
	domStr += "ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|";
	domStr += "hk|hm|hn|hr|ht|hu|";
	domStr += "id|ie|il|in|io|iq|ir|is|it|";
	domStr += "jm|jo|jp|";
	domStr += "ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|";
	domStr += "la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|";
	domStr += "ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|";
	domStr += "na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|";
	domStr += "om|";
	domStr += "pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|";
	domStr += "qa|";
	domStr += "re|ro|ru|rw|";
	domStr += "sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|";
	domStr += "tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|";
	domStr += "ua|ug|uk|um|us|uy|uz|";
	domStr += "va|vc|ve|vg|vi|vn|vu|";
	domStr += "wf|ws|";
	domStr += "ye|yt|yu|";
	domStr += "za|zm|zr|zw|";
	// custom domains for testing purposes
	domStr += "local";	    

	var re = new RegExp("^[A-Z0-9_]+([\.-]?[A-Z0-9_])*@([A-Z0-9_-]{2,}[\.]{1})+("+ domStr +")$","i");
	
	return re.test(str);
}

/*
 * keep this for backward compatibility
 */
function emailCheck(str)
{
	return checkEmail(str);
}

/*
 * Checkbox wordt aangevinkt of uitgevinkt afhankelijk van zijn status
 */
function toggleCheckbox(i) {
	// i = ID van de chekbox
	var f = document.getElementById(i);
	f.checked = !f.checked;

}

function getDate(yearField, monthField, dayField)
{
	/*
	 * Returns a valid date constructed by three 
	 * form fields or false when there is something wrong
	 * 
	 * The fields can either be text or selectboxes.
	 * 
	 */
	if (yearField.type=="text")
	{
		by = yearField.value;
	} else {
		var by = yearField[yearField.selectedIndex].value;
	}

	if (monthField.type=="text")
	{
		var bm = eval(monthField.value-1);
	} else {
		var bm = eval(monthField[monthField.selectedIndex].value-1);
	}
	if (dayField.type=="text")
	{
		var bd = dayField.value;
	} else {
		var bd = dayField[dayField.selectedIndex].value;
	}
	
	// check if all values are numeric
	r = /^[0-9]+$/;
	if (r.test(by) && r.test(bm) && r.test(bd))
	{
		// construct a new date with the values of the form
		var bDate = new Date(by,bm,bd);
		
		/* to check if the date is an existing date 
		 * the day of the constructed date is compared
		 * to the day of the selectbox
		 */
		if (bDate.getDate()==bd) {
			return bDate;
		} else {
			return false;
		}
	} else {
		return false;
	}
	return false;
}	

function checkDate(yearField, monthField, dayField)
{
	/* 
	 * Use this function to validate the date entered in a 
	 * form by calling this function with the three date fields
	 * of the form.
	 * 
	 * Returns true if there is a valid date.
	 * 
	 * Guus Sprokkereef
	 * 19-06-2003
	 */
	 return getDate(yearField, monthField, dayField)!=false;
}

function checkRadio(radioGroup)
{
	// Return true if one of the radiobuttons is checked
	if (radioGroup.length>0)
	{
		for (i=0;i<radioGroup.length; i++)
		{
 			if (radioGroup[i].checked)
			{
				return true;
			}
		}
	} else {
		alert("checkRadio: wrong formfield sent to function.");
	}
    return false;
}

function checkChar(s,c)
{
	var n = s.split(c);
	return n.length = 0;
}

function replaceChar(str,oldString,newString)
{
	str = new String(str);
	var n = str.split(oldString);

	if (!checkChar(str,oldString))
	{
		str = "";
		for (i=0;i<n.length ;i++)
		{
			str += n[i];
			if (i+1<n.length)
			{
				str += newString;
			}
		}
	}
	return str;
}

/*
 * Return true als een postcode voldoet aan de 
 * Nederlandse samenstelling voor een postcode
 */
function checkPostcode(str)
{
	reg = /^[0-9]{4} ?[A-Z]{2}$/i; 
	return reg.test(str);
}

/*
 * Return true if the input has had input (a radio was selected, text has been entered etc.)
 * throw in the formitem itself, not it's value
 *
 * !!! Only input type="text",input type="checkbox", input type="radio", select and textarea 
 * !!! have been implemented so far.
 *
 */
function hasInput(loFormItem)
{
    if (loFormItem)
    {
        if (loFormItem.type)
        {
            if (loFormItem.type.toUpperCase()=="TEXT" || loFormItem.type.toUpperCase()=="TEXTAREA" || loFormItem.type.toUpperCase()=="HIDDEN")
            {
                if (loFormItem.value&&loFormItem.value.length>=1)
                {
                    return true;
                }
            } else if (loFormItem.nodeName.toUpperCase() == "SELECT")
            {
                switch (loFormItem.selectedIndex)
                {
                    case -1:
                        return false;
                    case 0:
                        if (loFormItem.options[loFormItem.selectedIndex].value)
                        {
                            return true;
                        }
                        break;
                    default:
                        return true;            
                }
            }
        } else 
        {
            return checkRadio(loFormItem);
        }
    }
    return false;
}

/*
 * Check de lengte van invoer
 */
function hasLength(loFormItem,min,max)
{
	var s = getInput(loFormItem).length;
	if (max>0)
	{
		return s>=min && s<=max;
	} else {
		return s>=min;
	}	
}

/*
 * Return true if the input has had input (a radio was selected, text has been entered etc.)
 * throw in the formitem itself, not it's value
 *
 * !!! Only input type="text", input type="hidden", input type="checkbox", input type="radio", select and textarea 
 * !!! have been implemented so far.
 *
 */
function getInput(loFormItem)
{
    if (loFormItem)
    {
        if (loFormItem.type)
        {
            if (loFormItem.type.toUpperCase()=="TEXT" || loFormItem.type.toUpperCase()=="TEXTAREA" || loFormItem.type.toUpperCase()=="PASSWORD" || loFormItem.type.toUpperCase()=="HIDDEN")
            {
                if (loFormItem.value&&loFormItem.value.length>=1)
                {
                    return loFormItem.value;
                } else {
					return "";
				}
            } else if (loFormItem.nodeName.toUpperCase() == "SELECT")
            {
                switch (loFormItem.selectedIndex)
                {
                    case -1:
                        return "";
						break;
                    case 0:
                        if (loFormItem.options[loFormItem.selectedIndex].value)
                        {
                            return loFormItem.options[loFormItem.selectedIndex].value;
                        }
                        break;
                    default:
                        return loFormItem.options[loFormItem.selectedIndex].value;            
                }
            }
        } else 
        {
            return checkRadio(loFormItem);
        }
    }
    return "";
}

/*
 * Geef de waarde van de radio-groep
 */
function getRadio(radioGroup)
{
	// Return true if one of the radiobuttons is checked
	if (radioGroup.length>0)
	{
		for (i=0;i<radioGroup.length; i++)
		{
 			if (radioGroup[i].checked)
			{
				return radioGroup[i].value;
			}
		}
	} else {
		alert("checkRadio: wrong formfield sent to function.");
	}
    return "";
}

/*
 * Return true if the string contains a minimum of the defined number of numbers
 * 
 * Guus Sprokkereef
 * 03-05-2004
 */
function checkPhone(str,no)
{
	var i=0;
	var n=0;

	for (i=0;i<str.length;i++)
	{
		if (checkNumeric(str.substring(i,i+1)))
		{
			n++;
		}
	}
	return n>=no;
}

/* 
 * Return true if the string is a numeric or decimal value
 * 
 * Guus Sprokkereef
 * 14-04-2004
 */
function checkNumeric(str)
{
	var r = /^[0-9]*[\.]?[0-9]+$/;
	return r.test(str);
}

function sqlDate(d,db)
{
	// functie nog aanpassen voor andere database dan Access
	// datum omzetten naar datum voor sql
	var s = "";
	if (db)
	{
		if (db.toLowerCase()=="access")
		{
			s = "#"+eval(d.getMonth()+1)+"/"+d.getDate()+"/"+d.getYear()+"#";
		} else if (db.toLowerCase()=="sql")
		{
			s = "'"+eval(d.getMonth()+1)+"/"+d.getDate()+"/"+d.getYear()+"'";
		}
	} else {
		alert("verkeerd of geen database type opgegeven.\ngebruik: sqlDate([date],[access|sql]);");
	}
	return s;
}

/*
 * parameter a: array with values
 * parameter v: value to be checked in the array
 * 
 * return: array with including the value
 */
function addToArray(a,v)
{
	var b = existsInArray(a,v);
	var i = 0;

	if (!b)
	{
		a[a.length] = v;
	}
	return a;
}

/*
 * parameter a: array with values
 * parameter v: value to be checked in the array
 * 
 * return: true if the value exists in the array
 */
function existsInArray(a,v)
{
	var b = false;
	var i = 0;

	for (i=0;i<a.length;i++)
	{
		if (a[i]==v)
		{
			b = true;
		}
	}
	return b;
}

