// Javascript Library - Copyright Make IT Work (http://www.makeitwork.be)
// Usage: <SCRIPT  language="javascript" src="scriptlib.js">

// JScode cleaned with http://www.jslint.com

// Define javascript variable for jquery form validation
var jquery_validate_errorimage = "<img src='http://www.makeitwork.be/_skeleton/_makeitwork/lib-pics/icon-oknot12x12.gif' alt='OK' width='12' height='12' align='absmiddle'>&nbsp;";

// Set page title
function changeTitle(title)
{
	document.title = title;
}

// Returns file extension e.g. jpg
function getFileExtension(filename)
{
	return (/[.]/.exec(filename.toLowerCase())) ? /[^.]+$/.exec(filename.toLowerCase()) : undefined;
}

// Check if string is member of array
function in_array(needle, haystack)
{
  for (var values in haystack) 
  {
    if (haystack[values] == needle) { return true; }
  }
  return false; 
} 

// Returns to the "returnpage" after x seconds
function timedReturn(rpage,secs)
{	
	//Usage: 
	//if (isset($returnpage)) echo "<script>timedReturn('$returnpage',3000)</ script>";
    //else echo "<p><button onclick='window.close()'>Close</button>";							
	document.write("<p><img src=\"_makeitwork/lib-pics/icon-info16x16.gif\" alt=\"rotate\" align=\"absmiddle\" width=\"16\" height=\"16\">This page will automatically close in "+ (secs / 1000) +" seconds...</p>");
	document.write("<p><button onclick=window.open('"+rpage+"','_self');><img src='/_makeitwork/lib-pics/progressbar-loading-roundgrey1.gif' alt='rotate' align='absmiddle' width='12' height='12'>Close Now</button></p>");
	var t=setTimeout("window.open('"+rpage+"', '_self');",secs);
}

// Closes the page after x seconds
function timedClose(secs)
{
	document.write("<p><img src=\"/_makeitwork/lib-pics/icon-info16x16.gif\" alt=\"rotate\" align=\"absmiddle\" width=\"16\" height=\"16\">This page will automatically close in "+ (secs / 1000) +" seconds...</p>");
	document.write("<p><button onclick=window.close();><img src='/_makeitwork/lib-pics/progressbar-loading-roundgrey1.gif' alt='rotate' align='absmiddle' width='12' height='12'>Close Now</button></p>");
	var t=setTimeout('window.close();',secs);
}

// The left() function doesn't exist, so we'll just create one...
function Left(str, n)
{
	if (n <= 0) { return ""; }
	else if (n > String(str).length) { return str; }
	else { return String(str).substring(0,n); }
}

// The right() function doesn't exist, so we'll just create one...
function Right(str, n)
{
    if (n <= 0) { return ""; }
    else
	{
		if (n > String(str).length) { return str; }	
		else
		{
			var iLen = String(str).length;
			return String(str).substring(iLen, iLen - n);
		}
	}
}

// The replace() function doesn't exist, so we'll just create one...
function replace( str, from, to )
{
    var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}

// The Perfect pop-up :-) =================================================================================================

// Here's how you would call it:
// <a href="me.jpg" onclick="return popImage(this.href,'Site author');">link</a>

//really not important (the first two should be small for Opera's sake)
PositionX = 10;
PositionY = 10;
defaultWidth  = 600;
defaultHeight = 400;

//kinda important
var AutoClose = true;

//don't touch
function popImage(imageURL,imageTitle)
{
  var imgWin = window.open('','_blank','scrollbars=no,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
  if( !imgWin ) { return true; } //popup blockers should not cause errors
  imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
    'function resizeWinTo() {\n'+
    'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
    'var oH = document.images[0].height, oW = document.images[0].width;\n'+
    'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
    'window.doneAlready = true;\n'+ //for Safari and Opera
    'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
    'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
    'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
    'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
    'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
    'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
    'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
    'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
    'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
    'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
    '}\n'+
    '<\/script>'+
    '<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
    (document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
    '<img src="'+imageURL+'" alt="Loading image ..." title="" onload="resizeWinTo();">'+
    (document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
  imgWin.document.close();
  if(imgWin.focus) { imgWin.focus(); }
  return false;
}

// Pop-up window with picture
function ShowPicture(fotonaam, fhoogte, fbreedte, src, naam)
{
	naam=fotonaam;
	len=naam.length;
	naam=replace(replace(Left(naam,naam.length - 4),"-"," "),"_"," ");
	margin = 180; // margin you need for the menu + your OS menu bar
	reshoogte = screen.height; // user resolution height
	resbreedte = screen.width; // user resolution width
	if (fhoogte > (reshoogte-margin))
	{ hoogte = reshoogte-margin; breedte = (fbreedte/fhoogte)*hoogte; }
	else { hoogte = fhoogte; breedte = fbreedte; } // if the resolution is way bigger than the pic size
	// alle parameters doorgeven aan de windowNavigator, navigatie info
	strUrl = "windowNavigator.php?fotonaam=" + fotonaam + "&src=" + src + "&breedte=" + breedte + "&hoogte=" + hoogte + "&naam=" + naam;
	foto = window.open(strUrl,'','menubar=no,toolbar=no');
	foto.resizeTo(breedte+15,hoogte+margin-50); // count 50 pixels for the OS menu bar
}

// Pop-up window
function open_me(url,w,h,name)
{
	w=w+17; h=h+17;
	window.open(url,name,'location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=0,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Pop-up window with scroll bar
function open_me_scroll(url,w,h,name)
{
	w=w+17; h=h+17;
	window.open(url,name,'location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=1,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Pop-up window 2 with scroll bar
function open_me2(url,w,h)
{
	w=w+17; h=h+17;
	window.open(url,'popwin2','location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=0,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Pop-up window 2 with scroll bar
function open_me_scroll2(url,w,h)
{
	w=w+17; h=h+17;
	window.open(url,'popwin2','location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=1,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Pop-up window 3 with scroll bar
function open_me3(url,w,h)
{
	w=w+17; h=h+17;
	window.open(url,'popwin3','location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=0,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Pop-up window 3 with scroll bar
function open_me_scroll3(url,w,h)
{
	w=w+17; h=h+17;
	window.open(url,'popwin3','location=0,resizable=0,status=0,titlebar=0,directories=0,toolbar=0,menubar=0,scrollbars=1,status=0,width='+w+',height='+h+',screenX='+(screen.width - w)/2+',screenY='+(screen.height - h)/2+',top='+(screen.height - h)/2+',left='+(screen.width - w)/2);
}

// Limit the size of a textarea

// HTML code needed:
// <form name="form1">
// <textarea name="textfield" onkeydown="textCounter(textfield,form1.remLen,100);"
// onkeyup="textCounter(form1.textfield,form1.remLen,100);">Hello</textarea>
// <input name="remLen" type="text" value="100" size="3" maxlength="3" readonly="readonly"> remaining chars...
// </form>

function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit)
	{
		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	}
	else
	{
		// otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length;
	}
}

// needed for age calculator
function y2k(number)
{
	return (number < 1000) ? number + 1900 : number;
}


// Age calculator
// HTML code needed: 
// Stef is <script>calculate(17,9,1970)</ script> oud...
function calculate(day,month,year)
{		
	var today = new Date();
	var thisYear = y2k(today.getYear());
	var thisMonth = today.getMonth()+1;
	var thisDay = today.getDate();
	var yearsold = thisYear - year, monthsold = 0, daysold = 0, string = '';

    if (thisMonth >= month) { monthsold = thisMonth - month; }
    else { yearsold--; monthsold = thisMonth + 12 - month; }

    if (thisDay >= day) { daysold = thisDay - day; }
    else {
        if (monthsold > 0) { monthsold--; }
        else { yearsold--; monthsold+=11; }
        daysold = thisDay + 31 - day;
    }

    if (yearsold > 0)
	{
		// toon dan enkel maanden & dagen
		string = yearsold + ' jaar';	
	}
	else
	{
		// anders enkel jaren
		if (monthsold > 0) { string += monthsold + ' maand '; }
		if (daysold > 0)
		{
			string += ' en ' + daysold + ' dag';
			if (daysold > 1) { string += 'en'; }
		}
	}
	document.write(string);
}

// For decent pop-up and tooltips, use pure CSS: /_makeitwork/style.css
// Usage: This is <a class="info" href="javascript:void(null);">some text<div>This is the tooltip</div></a> which you have.

// Pop-up Divs
function toggleDiv(id,flagit)
{
	if (flagit=="1")
	{
		if (document.layers) { document.layers[id].display = ""; }
		else
		{
			if (document.all) { document.all[id].style.display = ""; }
			else { if (document.getElementById) { document.getElementById(id).style.display = ""; } }
		}
	}
	else
		if (flagit=="0")
		{
			if (document.layers) { document.layers[id].display = "none"; }
			else
			{
				if (document.all) { document.all[id].style.display = "none"; }
				else { if (document.getElementById) { document.getElementById(id).style.display = "none"; } }
			}
	}
}

// Toggle visibility of element
function toggleVis(obj)
{
	var el = document.getElementById(obj);
	if (el.style.display != 'none') { el.style.display = 'none'; }
	else { el.style.display = ''; }
}

// Expand/collapse a DIV
// HTML code needed:
// <div id="hiddentext" style="display:none;">
// This is hidden text</div>
// <br /><a href="javascript:void(null);" onclick="expand('hiddentext', this);">
// <img src="/lib-pics/icon-sq-plus.gif" border="0" align="absmiddle"></a></a>
function expand(thistag, tag)
{
	styleObj=document.getElementById(thistag).style;
	if (styleObj.display=='none')
	{
		styleObj.display='';
		tag.innerHTML = "<img src='/_makeitwork/lib-pics/button-shrink-blue.gif' align=absmiddle border=0>";
	}
	else
	{
		styleObj.display='none';
		tag.innerHTML = "<img src='/_makeitwork/lib-pics/button-grow-blue.gif' align=absmiddle border=0>";
	}
}

// Richt Text Editor
// depends on other RTE scripts

function RTEsubmitForm(fieldname)
{
	if (fieldname == 'all')
	{
		alert('Update *all* RTE fields');
		updateRTEs();	
	}
	else
	{
		alert('Update RTE field ' + fieldname);
		updateRTE(fieldname);
	}
	return true;
}

// Delete button with confirmation question
function DeleteWithConfirmation(deletepage_url,field_name,field_value,messagetext)
{
	if (confirm(messagetext)==1)
	{
		location.href = eval('\"'+deletepage_url+'?'+field_name+'='+field_value+'\"');
	}
}

// Delete button with confirmation question - quick version
function DeleteWithConfirmationQuick(deletepage_url,messagetext)
{
	if (confirm(messagetext)==1)
	{
		location.href = eval('\"'+deletepage_url+'\"');
	}
}

// Trim left
function ltrim(str)
{
	return str.replace(/^\s+/, '');
}

// Trim right
function rtrim(str)
{
	return str.replace(/\s+$/, '');
}

// Trim left and right
function alltrim(str)
{
	return str.replace(/^\s+|\s+$/g, '');
}

// Strip double spaces
function filterDubbeleSpaties(str)
{
	return str.replace(/\s\s+/,' ');
}

// Filter lidwoorden uit string (bvb groepsnaam)
function filterLidwoorden(sText)
{
	var reBadWords = /^ |^LES |^DE |^THE |^HET |^EEN /gi;
	return filterDubbeleSpaties(alltrim(sText.replace(reBadWords, function (sMatch) {return sMatch.replace(/./g, ""); })));
}

// Check if a variable is set. Usage: if(checkVar(yy)){do something}
function checkVar(what)
{
	return Boolean(typeof what != 'undefined' && what);
}

// Set a cookie
function Set_Cookie( 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" : "" );
}

// Get a cookie
function Get_Cookie(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;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) { return null; }
}

// Calculate window's width and heigth
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' )
{
	//Non-IE
	myWidth = window.innerWidth;
	myHeight = window.innerHeight;
}
else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
{
	//IE 6+ in 'standards compliant mode'
	myWidth = document.documentElement.clientWidth;
	myHeight = document.documentElement.clientHeight;
}
else if (document.body && (document.body.clientWidth || document.body.clientHeight))
{
	//IE 4 compatible
	myWidth = document.body.clientWidth;
	myHeight = document.body.clientHeight;	
}

// Email spam blocker ( http://www.myvasco.com/msb )
// Usage: <a href="javascript:msb('your generated code')">mailto:list[AT SIGN]themission[DOT]be?subject=subscribe</a>
function ch1(x) {var yy=2;var z=0;var xx="";for(var y=0;y<x.length;y++){z=x.charCodeAt(y);xx+=String.fromCharCode(z-yy);}return xx;}function msb(x) {location.href=ch1(x);}

// Press Enter key to submit form
function checkEnter(e)
{ //e is event object passed from function invocation
	var characterCode; //literal character code will be stored in this variable
	
	if (e && e.which)
	{
		//if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else
	{
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	
	if(characterCode == 13)
	{
		//if generated character code is equal to ascii 13 (if enter key)
		document.forms[0].submit(); //submit the form
		return false;
	}
	else {return true; }
}

function IsEmpty(aTextField)
{
	if ((aTextField.value.length == 0) || (aTextField.value == null)) { return true; }
	else { return false; }
}

// TAB BAR
// Example:
//<div class="tabContainer">
//  <a href="#" title="Tab01" id="tab01tab" class="tabMedOn" onclick="klikTab('tab01');return false;">Activiteiten</a>
//  <a href="#" title="Tab02" id="tab02tab" class="tabMedOff" onclick="klikTab('tab02');return false;">Adressen</a>
//  <a href="#" title="Tab03" id="tab03tab" class="tabMedOff" onclick="klikTab('tab03');return false;">Bestanden</a>
//  <!--<a href="#" title="Tab04" id="tab04tab" class="tabMedOff" klikTab('tab04');return false;">Links</a>-->
//  <!--<a href="#" title="Tab05" id="tab05tab" class="tabMedOff" klikTab('tab05');return false;">Links</a>-->
//  <div class="clear"></div>
//</div>
// and at the bottom:auto
//<script language="javascript1.2" type="application/javascript">
//	// This part makse sure the last previously opened tab is loaded
//	if (document.getElementById(Get_Cookie('miwtab'))) klikTab(Get_Cookie('miwtab'));
//< /script>


function klikTab(tabnr)
{
	//alert ("Tab "+tabnr+" clicked");
	Set_Cookie("miwtab", tabnr);
	
	for (i=1;i<=9;i++)
	{		
		//alert ("tab0"+i+" =?= "+tabnr);
		if ("tab0"+i == tabnr)
		{			
			if (document.getElementById("tab0"+i)) toggleDiv("tab0"+i,1);
			if (document.getElementById("tab0"+i+'tab')) document.getElementById("tab0"+i+'tab').className='tabMedOn';
		}
		else
		{
			if (document.getElementById("tab0"+i)) toggleDiv("tab0"+i,0);
			if (document.getElementById("tab0"+i+'tab')) document.getElementById("tab0"+i+'tab').className='tabMedOff';
		}		
	}
}

// Dreamweaver function
function MM_findObj(n, d)
{ //v4.01
	var p,i,x;
	if (!d) { d=document; }
	if((p=n.indexOf("?"))>0&&parent.frames.length)
	{
		d=parent.frames[n.substring(p+1)].document;
		n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) { x=d.all[n]; }
	for (i=0;!x&&i<d.forms.length;i++) { x=d.forms[i][n]; }
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) { x=MM_findObj(n,d.layers[i].document); }
	if(!x && d.getElementById) { x=d.getElementById(n); }
	return x;
}

// Dreamweaver function
function MM_validateForm()
{ //v4.0
	var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
	for (i=0; i<(args.length-2); i+=3){ test=args[i+2]; val=MM_findObj(args[i]);
	if (val) { nm=val.name; if ((val=val.value)!="") {
		if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
			if (p<1 || p==(val.length-1)) { errors+='- "'+nm+'" moet een geldig e-mail adres zijn.\n'; }
		} else if (test!='R') { num = parseFloat(val);
			if (isNaN(val)) { errors+='- "'+nm+'" moet een nummer zijn.\n'; }
			if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
				min=test.substring(8,p); max=test.substring(p+1);
			if (num<min || max<num) { errors+='- "'+nm+'" moet een nummer tussen '+min+' en '+max+' zijn.\n'; }
		} } } else if (test.charAt(0) == 'R') { errors += '- "'+nm+'" is een verplicht veld.\n'; } }
	} if (errors) { alert('Corrigeer de volgende fouten:\n\n'+errors+'\n\n'); }
	document.MM_returnValue = (errors == '');
}

// Dreamweaver function
function MM_preloadImages()
{ //v3.0
	var d=document;
	if(d.images)
	{
		if(!d.MM_p) { d.MM_p=new Array(); }
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
		for(i=0; i<a.length; i++)
		{
			if (a[i].indexOf("#")!==0)
			{
				d.MM_p[j]=new Image();
				d.MM_p[j++].src=a[i];
			}
		}
	}
}

// Dreamweaver function
function MM_swapImgRestore()
{ //v3.0
	var i,x,a=document.MM_sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) { x.src=x.oSrc; }
}

// Dreamweaver function
function MM_swapImage()
{ //v3.0
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr=new Array();
	for(i=0;i<(a.length-2);i+=3)
	{
		if ((x=MM_findObj(a[i]))!=null) { document.MM_sr[j++]=x; if(!x.oSrc) { x.oSrc=x.src; } x.src=a[i+2]; }
	}
}

// Dreamweaver function
function MM_reloadPage(init)
{ //reloads the window if Nav4 resized
	if (init==true)
	{
		with (navigator)
		{
			if ((appName=="Netscape")&&(parseInt(appVersion)==4))
			{
				document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
			}
		}
	}
	else
	{
		if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) { location.reload(); }
	}
}

// Dreamweaver function
function MM_jumpMenu(targ,selObj,restore)
{
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}