/*
 * Company		: Opzet V.O.F..
 * Programmer	: Guus Sprokkereef
 * 				: Rob Burgers
 * Email		: guus@opzet.nl
 * 
 * Date			: 07-03-2007
 * Version		: 1.1.1
 * 
 * History:
 * 07-05-2008	: RB - Added function checkBurgerservicenummer()
 */

/* ============================================================================================================
 * 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(guusf@opzet.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>
 * 
 * getFormDate(yearField, monthField, dayField)
 *		- returns a valid date or false
 *		- fields are form-objects
 *		- example: getFormDate(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)
 * 
 * moveSelectOption(orgID,destID,hiddenID,bSort)
 * 
 * moveAllSelectOptions(orgID,destID,hiddenID,bSort)
 * 
 * ============================================================================================================
 */

/*
 * 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 (.)
	 * 
	 */

	// Downloaded from http://www.icann.org/registries/top-level-domains.htm
	var domStr = "ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw";
	
	// unofficial tld 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 checkbox
	var f = document.getElementById(i);
	f.checked = !f.checked;

}

function getFormDate(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.toUpperCase()=="TEXT")
	{
		by = yearField.value;
	} else {
		var by = yearField[yearField.selectedIndex].value;
	}

	if (monthField.type.toUpperCase()=="TEXT")
	{
		var bm = eval(monthField.value-1);
	} else {
		var bm = eval(monthField[monthField.selectedIndex].value-1);
	}
	if (dayField.type.toUpperCase()=="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 getFormDate(yearField, monthField, dayField)!=false;
}

function checkRadio(radioGroup)
{
	// Return true if one of the radiobuttons is checked
	if (radioGroup.length>0)
	{
		for (var 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(string,oldString,newString)
{
	var n = string.split(oldString);

	if (!checkChar(string,oldString))
	{
		string = "";
		for (i=0;i<n.length ;i++)
		{
			string += n[i];
			if (i+1<n.length)
			{
				string += newString;
			}
		}
	}
	return string;
}

/*
 * 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" || loFormItem.type.toUpperCase()=="FILE")
            {
                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]+$/;
	var r = /^[\-]?[0-9]*[\.|\,]?[0-9]+$/; // supports negative numbers
	return r.test(str);
	//return true;
}

/*
 * Test for the Dutch 'Burgerservicenummer'
 * Valid if:
 * value is exactly 9 characters in length
 * value is numeric
 * value complies with a derivate of the 'elfproef' test (see http://nl.wikipedia.org/wiki/Burgerservicenummer)
 * 
 * Rob Burgers
 * 07-05-2008
 */
function checkBurgerservicenummer(f)
{
	str = document.getElementById(f).value;
	
	count = 9;
	if ( ( str.length == count ) )
	{
		elfproef = ( 9*str.charAt(0) + 8*str.charAt(1) + 7*str.charAt(2) + 6*str.charAt(3) + 5*str.charAt(4) + 4*str.charAt(5) + 3*str.charAt(6) + 2*str.charAt(7) + (-1*str.charAt(8)) );
		if (elfproef % 11 == 0) { return true; }
	}
	return false;
}

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: array without the value
 */
function removeFromArray(a,v)
{
	var i = 0;
	var na = new Array();

	for (i=0;i<a.length;i++)
	{
		if (a[i]!=v)
		{
			na[na.length] = a[i];
		}
	}
	return na;
}

/*
 * 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;
}

// keep for backward compatibility
function formatCurrency(str)
{
	return formatDecimal(str,2);
}

function formatDecimal(str,dec)
{
	var a;
	var i, j;
	var ret = "";
	ret = str.toString();
	if (ret.indexOf(".")==-1)
	{
		a = "";
		while(a.length < dec)
		{
			a = a + "0";
		}
		ret = ret+"."+a;
	} else {
		j = "";
		while (j.length<dec)
		{
			j = j + "0";
		}
		j = parseInt("1"+j);
		i = parseFloat(str);
		i = (Math.round(i*j)/j).toString();

		a = i.split(".");

		while (a[1].length<dec)
		{
			a[1] = a[1]+"0";
		}
		ret = a[0]+"."+a[1];
	}
	return ret;
}

function getStripPath(s)
{
	var str = s;
	var bSlash = s.indexOf("/")>=0;
	var bBackslash = s.indexOf("\\")>=0;
	if (bSlash)
	{
		str = s.substring(s.lastIndexOf("/")+1,s.length);
	}
	if (bBackslash)
	{
		str = s.substring(s.lastIndexOf("\\")+1,s.length);
	}
	return str;
}

/*
 * parameter orgID	: id of the selectBox with the selected option to move
 * parameter destID	: id of the selectBox where the option should go to
 */
function moveSelectOption(orgID,destID,hiddenID,bSort)
{
	var inbox = document.getElementById(orgID)
	var tobox = document.getElementById(destID);
	
	//alert(inbox.selected);
	if (inbox.selectedIndex!=-1)
	{
		while (inbox.selectedIndex!=-1)
		{		
			tobox.options[tobox.options.length] = new Option(inbox.options[inbox.selectedIndex].text,inbox.options[inbox.selectedIndex].value);
			inbox.options[inbox.selectedIndex] = null;
		}
	} else {
		alert("Selecteer een optie om te verplaatsen");
	}
	if (bSort) {sortOptions(tobox);}
	updateHiddenField(hiddenID);
}

/*
 * parameter orgID	: id of the selectBox with the selected option to move
 */
function moveSelectOptionUp(orgID,hiddenID)
{
	try
	{
		var select = document.getElementById(orgID);
		swapOptions(select, select.selectedIndex, select.selectedIndex-1);
		updateHiddenField(hiddenID);
	}
	catch(e)
	{
		//alert(e);
	}
}

/*
 * parameter orgID	: id of the selectBox with the selected option to move
 */
function moveSelectOptionDown(orgID,hiddenID)
{
	try
	{
		var select = document.getElementById(orgID);
		swapOptions(select, select.selectedIndex, select.selectedIndex+1);
		updateHiddenField(hiddenID);
	}
	catch(e)
	{
		//alert(e);
	}
}

/*
 * parameter obj : The target <select multiple>
 * parameter i   : selectedIndex to swap ...
 * paramerer j   : ... with this selectedIndex
 */
function swapOptions(obj,i,j)
{
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
}

/*
 * parameter orgID	: id of the selectBox with the selected option to move
 * parameter destID	: id of the selectBox where the option should go to
 */
function moveAllSelectOptions(orgID,destID,hiddenID,bSort)
{
	var inbox = document.getElementById(orgID);
	var tobox = document.getElementById(destID);
	
	//alert(inbox.selected);
	while (inbox.options.length>0)
	{		
		tobox.options[tobox.options.length] = new Option(inbox.options[0].text,inbox.options[0].value);
		inbox.options[0] = null;
	}
	if (bSort) {sortOptions(tobox);}
	updateHiddenField(hiddenID);
}
// internal sort-function for options of selectbox
function sortOptions(o)
{
	var a = new Array();
	var i;
	for (i=0;i<o.options.length;i++)
	{
		a[a.length] = new Array(o.options[i].text,o.options[i].value);
	}
	a.sort();
	for (i=0;i<o.options.length;i++)
	{
		o.options[i].text = a[i][0];
		o.options[i].value = a[i][1];
	}
}

// internal function for options of selectbox
function updateHiddenField(id)
{
	var optionsBox = document.getElementById(id+"_active");
	var hiddenBox = document.getElementById(id);
	var str = "";

	hiddenBox.value = "";
	var i;
	for (i=0;i<optionsBox.options.length;i++)
	{

		if (str.length>0)
		{
			str += ",";
		}
		str += optionsBox.options[i].value;
	}
	hiddenBox.value = str;
}

function imageBrowser(c,f,t)
{
	var w = 610;
	var h = 500;
	
	var url = '/admin/main.php?e=' + c + '&view=browser&field=' + f + '&target=' + t;

	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',toolbar=no,location=no,status=no,menubar=no,resizable=yes,dependent=no'
	win=window.open(url,'imageBrowser',settings)
	if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function deletePreview(f)
{
	// clear hidden text field
	document.getElementById(f).value = '';
	
	// remove preview
	var img = document.getElementById('preview_' + f);
	img.src = '';
	img.style.display = 'none';
	
	// remove trashbin
	var bin = document.getElementById('trash_' + f);
	bin.style.display = 'none';
	
	// display 'kies' button
	var btn = document.getElementById('new_' + f);
	btn.style.display = 'inline';
}


function fileBrowser(c,f,t)
{
	var w = 620;
	var h = 500;
	
	var url = '/admin/main.php?e=' + c + '&view=browser&field=' + f + '&target=' + t;

	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,toolbar=no,location=no,status=no,menubar=no,resizable=yes,dependent=no'
	win=window.open(url,'fileBrowser',settings)
	if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function selectFile(f,id,name)
{
	// set hidden text field
	document.getElementById(f).value = id;
	
	// show preview
	var field = document.getElementById('preview_' + f);
	field.innerHTML = name;

/*	
	// remove trashbin
	var bin = document.getElementById('trash_' + f);
	bin.style.display = 'inline';
		
	// display 'kies' button
	var btn = document.getElementById('new_' + f);
	btn.style.display = 'none';
*/
}
function selectImage(f,id,name)
{
	// set hidden text field
	document.getElementById(f).value = id;
	
	// show preview
	var img = document.getElementById('preview_' + f);
	img.src = name;
	img.style.display = 'inline';
	
	// remove trashbin
	var bin = document.getElementById('trash_' + f);
	bin.style.display = 'inline';
		
	// display 'kies' button
	var btn = document.getElementById('new_' + f);
	btn.style.display = 'none';
}



