// 29-05-2010
// Changelog
// - Added transformTextarea
// - Added divToTextarea
/**


 * Short notation of getting the element.
 * 
 * @param id 			The element ID.
 * 
 * @return				The element.
 **/
function $(id) {
	var element = (typeof(id)=='object'?id:document.getElementById(id));
//	alert(element);
//	alert(id);
	if ((element == null)||(element.nodeName=='#text')){
	//	alert('Element = null : '+id);
		return null;
//		return DummyElement; // return a dummy so the page will process normally if you use chainability
	}
	if (element.defined != undefined)	return element;

	
	element._debug = function(elem,newWindow,maxDepth) {
		if (maxDepth==0) {
			newWindow.document.write(String(elem));
			return null;
		}
		newWindow.document.write("<table cellpadding=1 cellspacing=1><style>td{font : normal normal 11px/13px Verdana, Arial, sans-serif;}</style>");
		var a = new Array();
		for (var j in elem) {
			a[a.length] = j;
		}
		a.sort();
		
		for (var i = 0; i < a.length; i++) {
			var key = new String(a[i]);
			if ((key != "debug")&&(key !="_debug")) {
				try {
					var h = new String(elem[key]);
					
					h = h.replaceAll('<script>','');
					h = h.replaceAll('</script>','');
					h = h.replaceAll('</script>','');
					h = h.replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('\n','<br>');
					
					newWindow.document.write("<tr><td valign=top>" + key + "</td><td valign=top bgcolor=#EEEEEE NOWRAP><pre>");
					if (typeof(elem[key])=="object"){
						if ((key!="debug")&&(key!="_debug"))
							this._debug(elem[key],newWindow,maxDepth-1);
					}else{
	  				newWindow.document.write(h);
					}
					
  				newWindow.document.write("</pre></td></tr>");
				} catch(err) {
					newWindow.document.write("<tr><td valign=top>" + key + "</td><td valign=top bgcolor=red NOWRAP><pre>" + err.description + "</pre></td></tr>");
				}
			}
		}	
		
		newWindow.document.write("</table>");
	}
	element.debug = function() {
		var keys     = ((arguments[0]!=null)&&(arguments[0]!="")?String(arguments[0]).split('.'):"");
		var maxDepth = arguments[1] || 3;
		var elem = this;
		if (keys!=""){
			for (var i=0;i<keys.length;i++){
				elem = elem[keys[i]];
			}
		}
		var newWindow = window.open("", "", "resizable=yes,scrollbars=yes,toolbar=0,status=1,menubar=no,width=800,height=600");
		newWindow.document.open("text/html");
		this._debug(elem,newWindow,maxDepth);
		newWindow.document.close();
	}

	element.mouseEvent = new Object();
	element.defined   = true;
	return element;
}
/**
 * retrieve the scroll top position
 **/
function scrollTop(){
	if (document.documentElement && !document.documentElement.scrollTop){
		return document.documentElement.scrollTop
	}else if (document.documentElement && document.documentElement.scrollTop){
		return document.documentElement.scrollTop
	}	else if (document.body && document.body.scrollTop){
		return body.scrollTop
	}
}


var getChildnodes = new function( ){
	this.elem = null;
	this.childnodes = new Array();
	this.error = null;
	this.errorOwner = new Array();
	
	this.clear = function(){
		this.childnodes = new Array();
		this.elem       = null;
		this.error      = null;
		this.errorOwner = new Array();
	}
	this.parse = function( parent ){
		this.clear();
		this.elem = $(parent);
		this._getChildren( this.elem );
		return this.childnodes;
//		alert(this.childnodes);
	}
	this._getChildren = function( currentElement ){
		if (currentElement==null) return false;
		if (currentElement.children.length>0)
			for (var i=0;i<currentElement.children.length;i++){
				if (currentElement.children[i].id!=''){
					switch (currentElement.children[i].tagName){
						case 'INPUT':
							this.childnodes[this.childnodes.length] = currentElement.children[i];
						break;
						case 'SELECT':
							this.childnodes[this.childnodes.length] = currentElement.children[i];
						break;
						case 'TEXTAREA':
							if (currentElement.children[i].style.visibility=='hidden'){ // Prolly a CKEditor TODO: Check if this aint giving bugs, hmm tfta check !
								if ( currentElement.children[i].tfta != undefined){
									currentElement.children[i].innerHTML = tftaGetContent(currentElement.children[i].tfta);
//									alert(currentElement.children[i].value);
								}
									
							}
							this.childnodes[this.childnodes.length] = currentElement.children[i];
						break;
					}
					if ((currentElement.children[i].name != currentElement.children[i].id)&&(currentElement.children[i].name=='MANDATORY')){
						if (currentElement.children[i].value.trim()==''){
							this.error = 'MANDATORY';
							currentElement.children[i].onclick = function (){this.style.backgroundColor = '#FFFFFF';}
							this.errorOwner[this.errorOwner.length] = currentElement.children[i];
						}
					}
					
				}
				this._getChildren( currentElement.children[i] );
				
			}
	}
	this.getPostString = function(){
		var str   = '';
		var value = '';
		if (this.childnodes.length>0){
			for (var i=0;i<this.childnodes.length;i++){
				value = '';
				switch (this.childnodes[i].type.toUpperCase()){
					case 'CHECKBOX':
						value = (this.childnodes[i].checked==false?0:1);
						break;
					default:
						value = escape(this.childnodes[i].value.split('\n').join('<br/>'));
						break;
				}
				str +='&' + this.childnodes[i].id + '=' + value;
			}
		}
		return str;
	}
}

var eventHandler = new function(){


	this.attic        = Array();
	this.handle = function(elem,handleValue,ownerValue,waitelem,callBack){
		this.attic[ this.getFreeIndex() ] = new Attic(elem,handleValue,ownerValue,waitelem,callBack);
	}
	this.post = function( elem,parent,handleValue,waitelem,callBack ){
		if ($(elem)==null) return false;
		getChildnodes.parse( parent );
		if (getChildnodes.error!=null){
			switch(getChildnodes.error){
				case 'MANDATORY':
					alert('Je hebt niet alle velden goed ingevuld.');
					for (var i=0;i<getChildnodes.errorOwner.length;i++){
						getChildnodes.errorOwner[i].style.backgroundColor = '#FFEEEE';
					}
				break;
			}
		}else{
			this.attic[ this.getFreeIndex() ] = new AtticPost( elem, getChildnodes.getPostString() ,handleValue,waitelem,callBack);
		}
		
		
	}
	
	this.getFreeIndex = function(){
		index = 0;
		for (var i=0;i<this.attic.length;i++){
			if (this.attic[i].active==false){
				index = i;
				break;
			}
			index = i+1;
		}
		return index;
	}
	

}



function AtticPost( elem, str, handleValue, waitelem,callBack ){
	this.waitelem = $(waitelem);
	this.elem     = $(elem);
	this.active   = true;
	this.callBack = callBack;
	this.handleValue = handleValue;
	this.xmlHttp = getXmlHttp();
	if (this.waitelem!=null)
		this.waitelem.style.visibility = 'visible';
	
	str = '&handleValue='+this.handleValue + str;
	this.xmlHttp.owner = this;
	this.xmlHttp.open("POST", window.hostname+'eventHandler.php', true);
	this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	// Add a ready state handler to the XML HTTP object:
	this.xmlHttp.onreadystatechange = function( ){
		if (this.readyState == 4){
	        if(this.status == 200) {
	        	if (this.owner.elem!=null)
					this.owner.elem.innerHTML = this.responseText;
	        	if (this.owner.callBack!=null){
					if (typeof(this.owner.callBack)=='string'){
					}else{
						this.owner.callBack(this.owner.elem,this.responseText)
					}
	        	}
	        	
				if (this.owner.waitelem!=null)
					this.owner.waitelem.style.visibility = 'hidden';
	        	
	        	this.owner.active = false;
	        }	
		}
	}
	
	// Send the request:
	this.xmlHttp.send(str);	
	
}

function getInputChildren( elem ){
	if (elem.children.length>0)
		return elem.children;
}

function getXmlHttp(){
	var xmlHttp = null;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
//	alert(xmlHttp.parentNode);
//	xmlHttp.id = 'as';
//	xmlHttp.owner = '';
	return xmlHttp;
}

function Attic(elem,handleValue,ownerValue,waitelem,callBack){
	this.active      = true;
	this.elem        = $(elem);
	this.handleValue = handleValue;
	this.ownerValue  = ownerValue;
	this.waitelem    = $(waitelem);
	this.callBack    = callBack;
	if (this.waitelem!=null)
		this.waitelem.style.visibility = 'visible';
//	if ((this.waitelem!=null)&&(this.waitelem.style.visibility=='visible')) return false;
	this.xmlHttp = getXmlHttp();
//	alert(this.xmlHttp.parent);
	this.xmlHttp.open("GET", window.hostname+'eventHandler.php?handleValue='+this.handleValue+'&ownerValue='+this.ownerValue, true);
//	alert('wel');
//	debug(this.xmlHttp);
//	alert('a');
	this.xmlHttp.owner = this;
	
	// Add a ready state handler to the XML HTTP object:
	
	this.xmlHttp.onreadystatechange = function(){
	//	alert(this.readyState);
		if (this.readyState == 4){
			if (this.owner.elem!=null)
				this.owner.elem.innerHTML = this.responseText;
			if (this.owner.callBack!=null){
				if (typeof(this.owner.callBack)=='string'){
//					eval(this.owner.callBack+'('+this.owner.elem+','+this.responseText+');');
					eval(this.owner.callBack+'(this.owner.elem,this.responseText);');
				}else{
					this.owner.callBack(this.owner.elem,this.responseText);
				}	
			}
				
			if (this.owner.waitelem!=null)
				this.owner.waitelem.style.visibility = 'hidden';
			this.owner.active = false;
		}
	}
	
	// Send the request:
	this.xmlHttp.send(null);	
	
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function debug( elem ){
	
	var raam = window.open('','mywindow','width=800,height=600');
	alert(raam.document);
	raam.document.write(' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"	"http://www.w3.org/TR/html4/strict.dtd">	<html>	  <head></head><body><table style="width:100%">');
	for (property in elem){
		raam.document.write('<tr><td>'+property+'</td><td>'+elem[property]+'</td></tr>');
//		alert(property);
	}
	raam.document.write('</body></html>');
	
}



function setCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ){
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ){
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ){
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){
		return null;
	}
}
// TODO: make this chainable
function showElem( elem,e ){
	e = e || window.event;
	elem = $(elem);
	elem.style.top  = ((e.clientY + scrollTop())+10)+'px';
	elem.style.display = 'block';
	elem.style.left = (((e.clientX) -10)-elem.offsetWidth) + 'px';
}
// TODO: make this chainable
function hideElem( elem ){
	$(elem).style.display = 'none';
}

function getRadiogroupValue( id ){
	
}

var inputCorrection = new function(){
	
	this.email = function( elem ){
		if (elem==null) return false;
		var value = elem.value;
		if (value.trim().length==0) return false;
		// remove the spaces...wicked people
		value = value.split(' ').join('');
		// split it to check if it is an email address
		if ((value.split('@').length==2)&&(value.split('@')[1].split('.').length>1)){
			elem.value = value;
			return true;
		}else
			return false;
	}
	
	this.date = function( elem ){ // dd-mm-yyyy
		if (elem==null) return false;
		if (elem.value.trim().length==0) return false; 
		// Remove all the spaces
		var value = elem.value.split(' ').join('');
		var date  = new Array();
		if (value.split('-').length==3){ // Correct date seperated with dashes
			date = value.split('-');
			if (date[2].length==2)
				date[2] = (date[2]>30?'19':'20')+date[2];
				
		}else if(value.length==8){       // Date written out without the dashes
			date[0] = value.substr(0,2);
			date[1] = value.substr(2,2);
			date[2] = value.substr(4,4);
		}else if(value.length==6){       // date written out as 121281
			date[0] = value.substr(0,2);
			date[1] = value.substr(2,2);
			date[2] = (value.substr(4,2)>30?'19':'20')+value.substr(4,2);
		}else{
			return false;
		}
		if ((date[0]>31)||(date[1]>12)||(date[0]<1)||(date[1]<1)||(date[2]<1930)){
			return false;
		}else{
			elem.value = date[0]+'-'+date[1]+'-'+date[2];
			return true;
		}
	}
	this.firstName = function( elem ){
		if (elem==null) return false;
		var value = elem.value;
		if (value.trim().length==0) return false;
		// make the word lowercase and upper only the first letter
		value = value.toUpperCase().substr(0,1) + value.toLowerCase().substr(1,value.length-1);
		elem.value = value;
		return true;

	}
	this.lastName = function( elem ){
		if (elem==null) return false;
		var value = elem.value;
		elem.value = value.toLowerCase();
		return true;
		// TODO: dingetjes hier met tussenvoegesel enzo
		/*
		var tussenVoegsel = '';
		if (value.split(' ')==2){ // tussen voegsel
			tussenVoegsel = value.split(' ')[0].toLowerCase();
		}
		if (value.trim().length==0) return false;
		// make the word lowercase and upper only the first letter
		value = value.toUpperCase().substr(0,1) + value.toLowerCase().substr(1,value.length-1);
		elem.value = value;
		return true;
		*/
	}
	
	this.dutchPostalCode = function( elem ){ //@TODO: Make the postal code check improved
		if (elem==null) return false;
		var value = elem.value.split(' ').join('');
		if (value.length!=6) return false;
		var firstFour = value.substr(0,4);
		var lastTwo   = value.substr(4,2);
		if ( isNaN(firstFour) ) return false;
		elem.value = firstFour + ' ' + lastTwo.toUpperCase();
		return true;
		
	}
	this.city = function( elem ){
		if (elem==null) return false;
		var value = elem.value;
		if (value.trim().length==0) return false;
		elem.value = value.toUpperCase().substr(0,1) + value.toLowerCase().substr(1,value.length-1);
		return true;
	}
	this.streetWithNumber = function( elem ){
		if (elem==null) return false;
		var value = elem.value;
		if (value.trim().length==0) return false;
		elem.value = value.toUpperCase().substr(0,1) + value.toLowerCase().substr(1,value.length-1);
		return true;
	}
};
var tfta = 0;
var tftaEditor = new Array();

function transformTextarea( textareaid ){
	var ta = $(textareaid);
	tftaEditor[tfta] = CKEDITOR.replace( $(textareaid),{filebrowserBrowseUrl : 'includes/ckfinder/ckfinder.php',height:ta.style.height,width:ta.style.width,enterMode:2,shiftEnterMode:1}); 
	CKFinder.SetupCKEditor( tftaEditor[tfta], 'includes/ckfinder/' ) ;
	ta.tfta = tfta;
	tfta++;
}
function tftaGetContent( id ){
	return tftaEditor[id].getData();	
}


function divToTextarea( parent, saveKey ){
	var ta = document.createElement('textarea');
	var button = document.createElement('div');
//	$(parent).oldclick = $(parent).onclick;
//	$(parent).onclick = function(){};
	
	
	button.innerHTML = '<input type=button value="Opslaan" onclick="eventHandler.handle(\''+parent+'\',\''+saveKey+'\',$(\'TA'+parent+'\').value.split(\'\\n\').join(\'<br/>\'),null,null);resetDiv(\''+parent+'\');  if (window.event){window.event.cancelBubble = true;}else{event.stopPropagation();}" >';
	button.id = 'TB'+parent;
	button.type = 'button';
	button.value = 'Opslaan';
	ta.id = 'TA'+parent;

	parent = $(parent);
	ta.style.width = parent.offsetWidth+'px';
	ta.style.height = parent.offsetHeight+'px';
	ta.style.fontSize = '11px';
	ta.style.fontFamily = 'Verdana';
	ta.innerHTML = parent.innerHTML.split('<br>').join('\n');
	ta.onclick = function(e){
		if (window.event){window.event.cancelBubble = true;}else{e.stopPropagation();}
	}
	parent.innerHTML = '';
	parent.appendChild( ta );
	parent.appendChild( button );
//	parent.parentNode.insertBefore(ta,parent);
	//parent.parentNode.insertBefore(button,parent);
	//parent.style.visibility = 'hidden';
	//parent.style.display = 'none';
	//$('TB'+parent).onclick = '';
//	document.body.insertBefore(ta,parent);
//	alert(parent.offsetWidth);
}

function resetDiv( parent ){
	if ($('TA'+parent)==null) return;
	var t = $('TA'+parent).innerHTML;
//	$(parent).innerHTML = t.split('\n').join('<br>');
//	$(parent).onclick = $(parent).oldclick;
//	alert($('TA'+parent).innerHTML);
}

 
