document.observe('dom:loaded',function(){
	// zoekveld
	var zoekVeld = $('zoekTerm');
	zoekVeld.addClassName('inactief').setAttribute('value',$('zoeken').down('label').innerHTML);
	zoekVeld.observe('focus',function(){
		if(zoekVeld.hasClassName('inactief')){
			zoekVeld.removeClassName('inactief');
			zoekVeld.setValue('');
		}
	});
	zoekVeld.observe('blur',function(){
		if($F(zoekVeld).length==0){	
			zoekVeld.addClassName('inactief').setValue($('zoeken').down('label').innerHTML);
		}
	});

	// image switcher	
	if($('kind')){
		var rand = Math.ceil(Math.random()*3);
		$('kind').setStyle({'background':'url(site/images/startpagina-kinderen/'+rand+'.png)'});
	}
	if($('kind')){
		$('kind').setAttribute('title','Klik om de afbeelding van het kind te wijzigen.');
		$('kind').observe('click',function(){
			new Effect.Fade($('kind'),{
				duration:0.5,
				afterFinish: function(){
					var rand = Math.ceil(Math.random()*3);
					$('kind').setStyle({'background':'url(site/images/startpagina-kinderen/'+rand+'.png)'});
					new Effect.Appear($('kind'),{duration:0.5});
				}
			});
		});
	}
	
	// contentpagina
	if($('kindKlein')){
		var rand = Math.ceil(Math.random()*3);
		$('kindKlein').setStyle({'background':'url(site/images/content-kinderen/'+rand+'.png)'});
	}
	
	// de twee kaartjes
	/*$('kaartje-dab').observe('mouseover',function(){
		new Effect.Shake($('kaartje-dab'),{distance:3,duration:0.4});
	});
	$('kaartje-rec').observe('mouseover',function(){
		new Effect.Shake($('kaartje-rec'),{distance:3,duration:0.4});
	});*/

	// Switch naar CMS linksbovenin?
	var checkUrl = 'check.php?c='+window.location;
	new Ajax.Request(checkUrl, { 
		method: 'get', 
		onSuccess: function(transport){
			var json = transport.responseText.evalJSON(true);
			// CMS
			if(json.cms == 1){				
				// laad een extra css- en js-bestand
				LazyLoader.load('site/styles/cms.css');
				LazyLoader.load('site/js/cms.js', function(){
				   laadCMSfrontend();
				});
			}
		}
	});
});

/* Zoek een ID */
function get_id(id) {
	// geef van een naam als lijst_cat_2882 alleen het nummer 2882 terug
	var ar = id.split("_");
	return ar[ar.length-1];
}

/* Sla een formulier op */
function ajaxSubmit(fID){
	var qs = Form.serialize(fID);
	alert(qs);
}

/* Pagina printen */
function printPagina(){
	if(window.print){
		window.print();	
	}
}

/* Rot 13 - encode email */
function email_decode(a,s){
	var email = Rot13.convert(s);	
	a.href = 'mailto:'+email;
}

/* Tooltips */
// laat een tooltip zien
function showTooltip(a,tooltip){
	var tt = $(tooltip);
	
	// positie
	var hoogte = tt.getHeight() - 15;
	tt.style.top = '-'+Math.round(hoogte/2)+'px';
	
	// laten sluiten bij onclick
	tt.onclick = function(){
		new Effect.Fade(this,{duration:0.3});
	}
	
	// alle andere elementen sluiten
	var tts = $$('.tooltip');
	tts.each(function(t){
		if(t.id != tt.id){
			new Effect.Fade(t,{duration:0.3});
		}
	});
	new Effect.toggle(tt,'appear',{duration:0.3});
}

/* ### FORMULIEREN ### */
/* Laat een hint bij een veld zien */
var hintDocumentOffset = true;
function showHint(field){
	// alle andere hints verwijderen
	
	// verwijder alle hints
	var hints = $$('.hint');
	hints.each(function(h){
		Element.hide(h);
	});
	
	// veld actief maken (lijnkleur anders)
	Element.addClassName(field,"form_actief");

	// elements
	var hint = $(field.id+"_hint");
	Element.show(hint);
	var parent = field.offsetParent;
	var top = parent.offsetTop;
	// hoogte van veld en hint?
	var field_height = Element.getHeight(field);
	var hint_height = Element.getHeight(hint);
	
	// nu corigeren voor hoogtes
	if(hintDocumentOffset){
		var newx = Math.round(top + (field_height / 2) - (hint_height / 2) + 4);
	}else{
		var newx = Math.round((field_height / 2) - (hint_height / 2) + 4);
	}

	// plaatsen 
	hint.style.top = newx+"px";
}

/* Verberg deze hint weer */
function removeHint(field){
	Element.removeClassName(field,"form_actief");
	
	// hint weghalen
	var hint = $(field.id+"_hint");
	Element.hide(hint);
}

/* Highlight een veld */
function formAddHighlight(field){
	Element.addClassName(field,"form_actief");	
}

/* Onthighlight een veld */
function formAddHighlight(field){
	Element.removeClassName(field,"form_actief");	
}

/* inline valideren */
function formInlineValidate(veld,verplicht,type){
	var fout = false;	
	var id = veld.id;
	var value = veld.value;
	var mess = '';
	
	// verwijder alle hints
	var hints = $A(document.getElementsByClassName('hint'));
	hints.each(function(hint){
		Element.hide(hint);
	});
		
	// Type checken (wie weet is het een checkbox oid)
	var veldtype = veld.getAttribute('type');
	if(veldtype == 'checkbox'){
		/* Het is een checkbox */
		id = id.replace('[]','');
		
		var inputs = $A(document.getElementsByClassName('checkbox'));
		var res = inputs.any(function(input){
			if(input.id.indexOf(id)!=-1){
				// deze heeft het goede id
				return(input.checked);
			}
		});
		fout = !res;
		if(fout){
			mess = 'U dient in ieder geval één van de opties te selecteren.';	
		}
	}else{
		/* Het is een standaard string */
		// whitespace weghalen
		value = value.strip();
		
		// lang genoeg?
		if(value.length==0){
			if(verplicht){
				fout = true;
				mess = 'Dit veld is verplicht.';
			}
		}else{
			// check voor bepaalde types
			
			// email
			if(type == 'email'){
				fout = !formCheckEmail(value);
				if(fout){
					mess = 'Dit e-mail adres is niet correct opgemaakt.';
				}
			}
			
			// postcode
			if(type == 'postcode'){
				value = value.replace(' ','');
				value = value.toUpperCase();
				fout = !formCheckPostcode(value);
				if(fout){
					mess = 'Deze postcode is niet in een vorm als 1234AB.';
				}else{
					veld.value = value;
				}
			}
			
			// telefoon
			if(type == 'telefoon'){
				//value = value.replace(' ','');
				//value = value.toUpperCase();
				fout = !formCheckTelefoon(value);
				if(fout){
					mess = 'Dit telefoonnummer is niet juist.';
				}else{
					veld.value = value;
				}
			}
			
			// datum
			if(type == 'datum'){
				fout = !formCheckDatum(value);
				if(fout){			
					mess = 'Voer een geldige datum in.';
				}else{
					veld.value = value;
				}
			}	
			
			// sofinummer
			if(type == 'sofinummer'){
				fout = !formCheckSofinummer(value);
				if(fout){
					mess = 'Deze waarde is niet geldig.';
				}
			}
		}
	}
	
	// fouten kenbaar maken
	var validate = $('inline_validate_'+id);
	if(fout){
		validate.removeClassName('form_inline_validate_ok');	
		validate.addClassName('form_inline_validate_fout');		
		
		// boodschap tonen
		if(mess.length > 0){
			var hint = veld.id+'_hint';
			Element.update(hint,'<p>'+mess+'</p>');
			showHint(veld);
		}
	}else{
		validate.removeClassName('form_inline_validate_fout');				
		validate.addClassName('form_inline_validate_ok');	
	}
}

/* Checkfuncties voor formulier */
function formCheckEmail(value){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var res = filter.test(value);
	return res;
}

function formCheckPostcode(value){
	var filter = /^[1-8]{1}[0-9]{3}[A-Z]{2}$/;
	var res = filter.exec(value);
	return res;
}

function formCheckTelefoon(value){
	var filter = /([0]{1}[6]{1}[-s]*[1-9]{1}[s]*([0-9]{1}[s]*){7})|([0]{1}[1-9]{1}[0-9]{1}[0-9]{1}[-s]*[1-9]{1}[s]*([0-9]{1}[s]*){5})|([0]{1}[1-9]{1}[0-9]{1}[-s]*[1-9]{1}[s]*([0-9]{1}[s]*){6})/;
	var res = filter.exec(value);
	return res;
}

function formCheckDatum(value){
	//var filter = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
	//var res = filter.exec(value);
	var spl = value.split('-');
	var fout = false;
	if(spl.length == 3){
		var dag = spl[0];
		var maand = spl[1];
		var jaar = spl[2];
		if(!formCheckNummer(dag) || parseFloat(dag) < 1 || parseFloat(dag) > 31){
			fout = true;
		}		
		if(!formCheckNummer(maand) || parseFloat(maand) < 1 || parseFloat(maand) > 12){
			fout = true;
		}
		if(!formCheckNummer(jaar) || parseFloat(jaar) < 1900 || parseFloat(jaar) > 2100 || jaar.length < 4){
			fout = true;
		}	
	}else{
		fout = true;	
	}
	return !fout;
}

function formCheckNummer(value){
	if (isNaN(parseFloat(value))){
		return false;
	}else{
		return true;	
	}
}

function formCheckSofinummer(value){
	// verwijder alle tekens die geen cijfers zijn
	value = value.replace(/\D/, "");
		
	// loop door de 9 cijfers met de 11 proef formule
	var som = 0;
	for (i=1; i<10; i++) {
		som += value.charAt(i-1) * (10-i);
	} 
	
	// geef resultaat van check terug
	return (som % 11==0 && value.length == 9);
}

/* Popupvensters */
/* open een popup */
var popUpWin=0;

function popUpWindow(URLStr, left, top, width, height){
  if(popUpWin){
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

/* Prototype uitbreiden met functie om radiobuttons te snappen */
function $RF(el, radioGroup) {
	if($(el).type == 'radio') {
		var el = $(el).form;
		var radioGroup = $(el).name;
	} else if ($(el).tagName.toLowerCase() != 'form') {
		return false;
	}
	return $F($(el).getInputs('radio', radioGroup).find(
		function(re) {return re.checked;}
	));
}

// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}
 
 
 
/** 
*  Script lazy loader 0.5
*  Copyright (c) 2008 Bob Matsuoka
*
*  This program is free software; you can redistribute it and/or
*  modify it under the terms of the GNU General Public License
*  as published by the Free Software Foundation; either version 2
*  of the License, or (at your option) any later version.
*/
 
var LazyLoader = {}; //namespace
LazyLoader.timer = {};  // contains timers for scripts
LazyLoader.scripts = [];  // contains called script references
LazyLoader.load = function(url, callback) {
        // handle object or path
        var classname = null;
        var properties = null;
        try {
                // make sure we only load once
                if ($A(LazyLoader.scripts).indexOf(url) == -1) {
                		// javascript of css?
                		var css = url.indexOf('.css') != -1;
                		
                        // note that we loaded already
                        LazyLoader.scripts.push(url);
                        
                        if(!css){
                        	// JS
	                        var script = document.createElement("script");
	                        script.src = url;
	                        script.type = "text/javascript";
						}else{
							// CSS
							var script = document.createElement('link');
							script.href = url;
							script.type = "text/css";
							script.rel = "stylesheet";
							script.media = "screen";
						}
                        $$("head")[0].appendChild(script);  // add script/css tag to head element
                       
                        // was a callback requested
                        if (callback) {    
                                // test for onreadystatechange to trigger callback
                                script.onreadystatechange = function () {
                                        if (script.readyState == 'loaded' || script.readyState == 'complete') {
                                                callback();
                                        }
                                }                            
                                // test for onload to trigger callback
                                script.onload = function () {
                                        callback();
                                        return;
                                }
                                // safari doesn't support either onload or readystate, create a timer
                                // only way to do this in safari
                                if ((Prototype.Browser.WebKit && !navigator.userAgent.match(/Version\/3/)) || Prototype.Browser.Opera) { // sniff
                                        LazyLoader.timer[url] = setInterval(function() {
                                                if (/loaded|complete/.test(document.readyState)) {
                                                        clearInterval(LazyLoader.timer[url]);
                                                        callback(); // call the callback handler
                                                }
                                        }, 10);
                                }
                        }
                } else {
                        if (callback) { callback(); }
                }
        } catch (e) {
                alert(e);
        }
}
