function focusFirstElement(formVar) {
	for(i=0; i < formVar.elements.length; i++) {
    	el = formVar.elements[i];
		if(el.type == 'text' || el.type == 'textarea') {
			el.focus();
			break;
		}
	}
}

//waarde in url vervangen met regex
function addUrlParam(param,value) {
	loc = document.location.toString();
	loc = loc.replace(new RegExp(param + "\=.*?(&|$)"),"");

	//& op einde van de string
	if(loc.substr(loc.length - 1) == '&') {
		loc = loc.substr(0,loc.length - 1);
	}	

	loc += "&" + param + "=" + value;
	document.location = loc;
}

function round(num,rlength) {
	return Math.round(num *Math.pow(10,rlength))/Math.pow(10,rlength);
}

function popupFCK(name) {
	window.open('fckfullscreenedit.php?id='+name,'_blank','fullscreen=yes');
}

function formChanged() { }

function formatPrice(input) {
    num = roundNumber(Number(input.value)).toString();

	if(num < 0) {
		input.style.color = 'red';
	}
	else {
		input.style.color = 'black';
	}

    idx = num.indexOf('.');
    if(idx == -1) {
        num += ".00";
    }
    else if(idx != (num.length - 3)) {
        len = num.length-1;
        for(i = idx; i < len; i++) {
            num += "0";
        }
    }
    input.value = num;
}

function commaToPoint(input) {
	if(input.value.indexOf(',')>-1) {
		input.value=input.value.replace(/\,/,'.');
	}

	if(input.value.match(/[^\-\d\.]/)) {
		input.value = input.value.replace(/[^\-\d\.]/,'');
	}
}

function isDefined(ckVar) {
	var DEFINED_V=true;
	function handleError() {
		DEFINED_V=false;
		return true;
	}

	var oldOnError=window.onerror;
	window.onerror=handleError;
	try {
		eval(ckVar);
	}

	catch (e) {
		DEFINED_V=false;
	}
	window.onerror=oldOnError;
	return DEFINED_V;
}

function roundNumber(num) {
	var rlength = 2; // The number of decimal places to round to
	return Math.round(num *Math.pow(10,rlength))/Math.pow(10,rlength);
}

function ROUND(num,rlength) {
	return Math.round(num *Math.pow(10,rlength))/Math.pow(10,rlength);
}


var currentPoppedUpInput;
var currentPoppedUpInputDisplay;

function textfieldPopup(input,input_display,size) {
    currentPoppedUpInput = input;
    currentPoppedUpInputDisplay = input_display;

    window.open('textfieldedit.php?id=' + input.id + '&size=' + size,'_textpopup','width=700,height=440,statusbar=yes,status=yes');
}

function isHTML(str) {
    return str.match(/<.*?>/);
}

/*function htmlToText(str) {
    return str.replace(/<\S[^>]*>/g,' ');
}*/

function truncate(str,len) {
    if(str.length > len) {
        str = str.substring(0,len);
        str += '..';
    }
    return str;
}

function handleDayKey(input,e,id) {
	key = getKeyCode(e);

	if(input.value.match(/[^\d]/)) {
		input.value = input.value.replace(/[^\d]/,'');
	}

	val = Number(input.value);
	if(val > 31) {
		input.value='31';
	}

 	if(asciiIsNumber(key) && (input.value.length == 2)) {
 		try {
			document.getElementById(input.id.replace(/_day$/,'') + '_month').focus();
		}
		catch(e) { }
	}
}

function handleMonthKey(input,e,id) {
	source = getEventSource(e);

	if(source != input)
		return;

	key = getKeyCode(e);

	if(input.value.match(/[^\d]/)) {
		input.value = input.value.replace(/[^\d]/,'');
	}

	val = Number(input.value);
	if(val > 12) {
		input.value='12';
	}

	if(asciiIsNumber(key) && (input.value.length == 2)) {
		try {
			document.getElementById(input.id.replace(/_month$/,'') +'_year').focus();
		}
		catch(e) { }
	}
}

function handleYearKey(input) {
	val = input.value;
	if(val.match(/[^\d]/)) {
		input.value = val.replace(/[^\d]/,'');
	}
}

function handleYearBlur(input) {
	val = Number(input.value);
	if((input.value.length < 3) && (val > 0)) {
		d = new Date;
		fullYear = '' + d.getFullYear();
		century = Number(fullYear.substr(0,2));
		year = Number(fullYear.substr(2));

		if(val < (year + 10)) {
			input.value = '' + century + padLeft(input.value,2,'0');
		}
		else {
			input.value = '' + (century-1) + padLeft(input.value,2,'0');
		}
	}
	storeDate(input);
}

function validDate(input) {
	base_id = input.id.replace(/_[^_]+$/,'');

	if(	(year = document.getElementById(base_id + '_year').value).length
		&&
		(month = document.getElementById(base_id + '_month').value).length
		&&
		(day = document.getElementById(base_id + '_day').value).length) {

		valid = isValidDate(year,month,day);

		if(!valid) {
			registerInvalidDate(base_id);
		}
		else {
			clearInvalidDate(base_id);
		}

		color = valid?'black':'white';
		bg = valid?'white':'red';
	}
	else {
		clearInvalidDate(base_id);
		color = 'black';
		bg = 'white';
	}

	document.getElementById(base_id + '_year').style.color = color;
	document.getElementById(base_id + '_year').style.background = bg;

	document.getElementById(base_id + '_month').style.color = color;
	document.getElementById(base_id + '_month').style.background = bg;

	document.getElementById(base_id + '_day').style.color = color;
	document.getElementById(base_id + '_day').style.background = bg;
}

function isValidDate(y, m, d) {
    with (new Date(y, (m-1), d)) {
        return ((Number(getFullYear()) == Number(y)) && (Number(getMonth()) == Number(m-1)) && (Number(getDate()) == Number(d)));
    }
}

function isValidDateStr(str) {
	if(!str) {
		return false;
	}

	if(typeof(str).toLowerCase() != 'string') {
		return false;
	}

	prts = str.split('-');
	if(prts.length != 3) {
	    return false;
	}

	return isValidDate(prts[0],prts[1],prts[2]);
}

function padLeft(str,length,character) {
	if(str.length >= length)
		return str;

	while(str.length < length) {
		str = character + str;
	}
	return str;
}

function storeDate(input) {
	store_id = input.id.replace(/_[^_]+$/,'');

	val = getDateFromId(store_id);

	if(!isValidDateStr(val)) {
		val = '';
	}

	document.getElementById(store_id).value = val;

	return val;
}

function getDateFromId(id) {
	val =
		document.getElementById(id + '_year').value +
		'-' +
		document.getElementById(id + '_month').value +
		'-' +
		document.getElementById(id + '_day').value;

	return val;
}

function asciiIsNumber(code) {
	return ((code >= 96 && code <= 105) || (code >= 48 && code <= 57));
}

function getKeyCode(e) {
	if(document.all) {
		return e.keyCode;
	}
	else {
		return e.which;
	}
}

function getEventSource(e) {
	if(document.all) {
		return e.srcElement;
	}
	else {
		return e.target;
	}
}

function funcname(f) {
	var s = f.toString().match(/function (\w*)/)[1];
	if ((s == null) || (s.length==0)) return "anonymous";
	return s;
}

function printstacktrace() {
	var s = "";
	for (var a = arguments.caller; a !=null; a = a.caller) {
		s += "->"+funcname(a.callee) + "\n";
		if (a.caller == a) {s+="*"; break;}
	}
	return s;
}

function checkDateInterval(name) {
	startdate = getDateFromId(name+'_start');
	alert(startdate);
}

function addDaysToDateStr(datestr,days) {
	prts = datestr.split('-');

	if(isValidDate(prts[0],prts[1],prts[2])) {
		d = new Date(prts[0],(prts[1]-1),prts[2]);
		d.setDate(d.getDate() + days);
		return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
	}
	else {
		return false;
	}
}

function validateForm(form) {
	if(hasInvalidDates()) {
		return false;
	}
	else {
		return true;
	}
}

var invalidDates = new Object();

function registerInvalidDate(id) {
	invalidDates[id] = true;
}

function clearInvalidDate(id) {
	invalidDates[id] = false;
}

function hasInvalidDates() {
	for(var id in invalidDates) {
		if(invalidDates[id] == true) {
			try {
				document.getElementById(id+'_day').focus();
			}
			catch(e) { }
			return true;
		}
	}
	return false;
}

function dateStrDifference(start,end) {
	prts = start.split('-');
	startdate = new Date(prts[0], prts[1] - 1, prts[2]);

	prts = end.split('-');

	enddate = new Date(prts[0], prts[1] - 1, prts[2]);

	secs = enddate.getTime() - startdate.getTime();
	return Math.floor(secs / (3600 * 24 * 1000)) + 1;
}

function pressedEnter(e) {
	if(document.all) {
		return handleKeyPressIE(e);
	}
	else {
		return handleKeyPressOther(e);
	}
}

function getKeyCode(e) {
	if(document.all) {
		return e.keyCode;
	}
	else {
		return e.which;
	}
}

function handleKeyPressIE(e) {
	if(e.keyCode == 13) {
		return true;
	}
	return false;
}

function handleKeyPressOther(e) {
	if(e.which == 13) {
		return true;
	}
	return false;
}


function popWindow(url) {
	window.open(url,'_blank','width=800,height=600,resizable=yes,scrollbars=yes');
}

function showModalPopup(url, title) {
	var win = new Window({
		title: title,
		width:800, 
		height:600, 
		destroyOnClose: true, 
		recenterAuto:false,
		showEffect: Element.show,
		hideEffect: Element.hide,
		url: url,
		minimizable: false,
		maximizable: false,
		resizable: false,
		draggable: false
	});
	
	win.showCenter(true);
}

function debugWindow(content){
	var win = window.open('about:blank','_debugger','width=800,height=600,resizable=yes,scrollbars=yes');
	win.document.write('<pre>'+content+'</pre>');
}

function blankIfNull(str) {
	return str ? str : '';
}

var HTMLUtil = {
	putOptionsInSelect: function(select, options, clearfirst) {
		if(clearfirst == undefined) {
			clearfirst = true;
		}
		
		if(clearfirst) {
			select.options.length = 0;
		}
		
		for(var i = 0; i < options.length; i++) {
			select.options[select.options.length] = options[i];
		}
	}
}

var FormChangedWarning = {
	register: function(form, changeCallback) {
		$A(form.elements).each(function(field) {
			if(field.tagName.toLowerCase() == 'fieldset') {
				return;
			}
			
			new Form.Element.EventObserver(field, function(element) {
				if(changeCallback != undefined) {
					changeCallback();
				}
				else {
					FormChangedWarning.setDirty();
				}
			});
		});
		
		Event.observe(form,'submit',function() {
			window.onbeforeunload = function() { };
		});
	} ,
			
	setDirty: function() {
		$$('input.submitbutton').each(function(node) {
			node.style.color = 'blue';
		});
		
		window.onbeforeunload = function() {
			return "Als u de pagina nu verlaat, gaan uw wijzigingen verloren! Toch Doorgaan?";
		}
	}
}

var FormChangedWarningAgenda = {
	register: function(form, changeCallback) {
		$A(form.elements).each(function(field) {
			
			if(field.tagName.toLowerCase() != 'button' && field.tagName.toLowerCase() != 'fieldset') {				
				new Form.Element.EventObserver(field, function(element) {
					if(changeCallback != undefined) {
						changeCallback();
					}
					else {
						FormChangedWarningAgenda.setDirty();
					}
				});
			}
		});
		
		Event.observe(form,'submit',function() {
			window.onbeforeunload = function() { };
		});				
	} ,
			
	setDirty: function() {
		$$('input.submitbutton').each(function(node) {
			node.style.color = 'blue';
			node.style.fontWeight = 'bold';
		});
		
		window.onbeforeunload = function() {
			return "U hebt uw agendapunt nog niet opgeslagen. Controleer ook of u uw vereniging hebt aangeduid bij 'Organisator'. Klik op 'Cancel' om terug te keren en eerst op te slaan alvorens een locatie aan te maken. Indien u klikt op OK, wordt uw productie niet opgeslagen!";
		}
	}
}


var Emailer = {
	register: function(input) {
		var link = $a(
			{href: 'javascript:void(null)'},
			$img({src:"images/message.gif", style: "vertical-align: middle"})
		);
		
		link.onclick = function() {
			if(input.value) {
				link.href = "mailto: "+ input.value;
				return true;
			}
			else {
				alert("Vul eerst een e-mail adres in!")
				return false;
			}
		};
		
		input.parentNode.appendChild(link);
	}
}

var InputUrlClicker = {
	register: function(input) {
		var link = $a(
			{href: 'javascript:void(null)', target: '_blank'},
			$img({src:"images/external.png", style: "vertical-align: middle"})
		);
		
		input.parentNode.appendChild(link);
		

		var onInputChange = function() {
			url = input.value;
			
			if(url) {
				if(!url.match(/^http/)) {
					url = "http://" + url;
				}
				
				link.onclick = function() { return true; };
				link.href = url;
			}
			else {
				link.onclick = function() {
					alert("Geef eerst het adres van de website in!");
					return false;
				}
			}
		}		
		
		Event.observe(input,'change',onInputChange);
		onInputChange();

	}	
}

var FormEnterListener = {
	overrideEnter: function(form, handler, excludeElements) {
		var elements = [];
		if(excludeElements == undefined) {
			excludeElements = [];
		}
		
		$A(form.getElementsByTagName('input')).each(function(node,index) {
			if(!excludeElements.contains(node) && node.className != 'autocomplete-text-input') {
				handleInputEnter(node,handler);
			}
		});
	}
}

function handleInputEnter(input, handler) {
	Event.observe(input,'keydown',function(event) {
		
		if(event.which == 13) {
			handler(event);
		}
	});
}

function array_push(array, value) {
	array[array.length] = value;
}


Event.observe(window,'load',function() {
	$$('form.please-wait-on-submit').each(function(form) {
		form.observe('submit',function() {
			form.getElementsBySelector('input[type=submit]').each(function(input){
				input.value = "Even geduld...";
			});
		});
	});
});