var ie =		(navigator.appName.indexOf('Explorer')>-1);
var isIE  =		(navigator.appVersion.indexOf("MSIE") != -1);
var isWin =		(navigator.appVersion.toLowerCase().indexOf("win") != -1);
var isOpera =	(navigator.userAgent.indexOf("Opera") != -1);
var isWebkit =	(navigator.userAgent.toLowerCase().indexOf("webkit") != -1);


var popupWnd = false;
var popupReturnValue = '';
var popupOnElem = '';
var popupArg = '';




// Dynamicly load Css and/or Javascript files.

rx_DynamicFileLoad = function() {};
rx_DynamicFileLoad.loading = false;
rx_DynamicFileLoad.loadlist = [];
rx_DynamicFileLoad.filelist = "";
rx_DynamicFileLoad.triggers = {};

rx_DynamicFileLoad.Add = function(filename, filetype) {
	if (rx_DynamicFileLoad.filelist.indexOf("["+filename+"]") != -1) return false;
	rx_DynamicFileLoad.filelist += ",[" + filename + "]"; //List of files added in the form "[filename1],[filename2],etc"
	rx_DynamicFileLoad.loadlist.push({"filename" : filename, "filetype" : filetype});
	if(!rx_DynamicFileLoad.loading) {
		rx_DynamicFileLoad.loading = true;
		rx_DynamicFileLoad.Load();
	}
	return true;
};

rx_DynamicFileLoad.Load = function() {
	var e = rx_DynamicFileLoad.loadlist.shift();
	rx_DynamicFileLoad.trigger("LoadingFile", e);
	if (e['filetype'] == "js") { //if filename is a external JavaScript file
		var fileref = document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", e['filename']);

	} else if (e['filetype'] == "css") { //if filename is an external CSS file
		var fileref = document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", e['filename']);
	}

	if (isIE) {
		var t = rx_DynamicFileLoad.simpleClosure(rx_DynamicFileLoad.__onAsyncLoadIE,null, fileref);
		fileref.attachEvent("onreadystatechange", t);
	} else {
		var t = rx_DynamicFileLoad.simpleClosure(rx_DynamicFileLoad.__onAsyncLoad, null, null);
		fileref.addEventListener("load", t, true);
	}

	var a=document.getElementsByTagName("HEAD");
	if(!a || a.length == 0) {
		a=[document.createElement("HEAD")];
		document.documentElement.appendChild(a[0]);
	}
	a[0].appendChild(fileref);
	return true;
};
rx_DynamicFileLoad.simpleClosure = function(a,o) {
	var e=[];
	for(var t=2; t<arguments.length; ++t) e.push(arguments[t]);
	return function() {
		var s=[];
		for(var n=0; n<arguments.length; ++n) s.push(arguments[n]);
		return a.apply(o||this,e.concat(s));
	}
};

rx_DynamicFileLoad.__onAsyncLoadIE = function(e) {
	if(e.readyState=="loaded") rx_DynamicFileLoad.__onAsyncLoad()
};
rx_DynamicFileLoad.__onAsyncLoad = function() {
	if(rx_DynamicFileLoad.loadlist.length) {
		rx_DynamicFileLoad.Load();
	}
	if(!rx_DynamicFileLoad.loadlist.length) {
		rx_DynamicFileLoad.loading = false;
		rx_DynamicFileLoad.trigger("Loaded", null);
		rx_DynamicFileLoad.triggers = {};
	}
};
rx_DynamicFileLoad.bind = function(event, callback) {
	if(typeof(rx_DynamicFileLoad.triggers[event]) == 'undefined') rx_DynamicFileLoad.triggers[event] = new Array();
	rx_DynamicFileLoad.triggers[event].push(callback);
};
rx_DynamicFileLoad.trigger = function(event, params) {
	if(typeof(rx_DynamicFileLoad.triggers[event]) != 'undefined') {
		for(var i=0; i<rx_DynamicFileLoad.triggers[event].length; i++) rx_DynamicFileLoad.triggers[event][i](params);
	}
};

function rx_gotfocus() {
	window.onfocus = '';
}

function rx_wopen(url,features,setvalelem) {
	popupOnElem = setvalelem;
	popupArg = (typeof(popupOnElem) == 'object') ? popupOnElem.value : '';
	if (window.showModalDialog) {
		popupReturnValue = window.showModalDialog(url,popupArg,features);
		if (popupReturnValue != undefined) popupOnElem.value = popupReturnValue;
		//popupWnd = window.open(url,'popupWnd',features);
		//if(!popupWnd.opener) popupWnd.opener = self;
		//popupWnd.focus();
		//window.onfocus = rx_gotfocus;
	} else {
		popupWnd = window.open(url,'popupWnd',features);
		popupWnd.focus();
		window.onfocus = rx_gotfocus;
	}
}

function rx_wopen2(url,features,setvalelem) {
	popupOnElem = setvalelem;
	popupArg = (typeof(popupOnElem) == 'object') ? popupOnElem.value : '';
	popupWnd = window.open(url,'popupWnd',features);
	if(!popupWnd.opener) popupWnd.opener = self;
	popupWnd.focus();
	window.onfocus = rx_gotfocus;
}

function rx_wopen3(url,target,features,setvalelem) {
	popupOnElem = setvalelem;
	popupArg = (typeof(popupOnElem) == 'object') ? popupOnElem.value : '';
	popupWnd = window.open(url,target,features);
	popupWnd.focus();
	window.onfocus = rx_gotfocus;
}

function setborderkonq(tblid) {
	var tbl = document.getElementById(tblid);
	var r,c,i,x;
	for (r=0;r<tbl.rows.length;r++) {
		for(c=0;c<tbl.rows[r].cells.length;c++){
			if (tbl.rows[r].cells[c].innerHTML == '') {
				if (tbl.rows[r].cells[c].style.overflow != 'visible') tbl.rows[r].cells[c].style.overflow = 'visible';
			} else {
				if (tbl.rows[r].cells[c].style.overflow != 'hidden') tbl.rows[r].cells[c].style.overflow = 'hidden';
			}
		}
	}

}

function windowWidth() {
	if(!window.opera && document.documentElement && document.documentElement.clientWidth)
	return document.documentElement.clientWidth;
	else if(document.body && document.body.clientWidth)
	return document.body.clientWidth;
	else if(window.innerWidth) {
		return (document.width>window.innerWidth) ? window.innerWidth-16 : window.innerWidth;
	}
	return 0;
}

function windowHeight() {
	if(!window.opera && document.documentElement && document.documentElement.clientHeight)
	return document.documentElement.clientHeight;
	else if(document.body && document.body.clientHeight)
	return document.body.clientHeight;
	else if(window.innerHeight) {
		return (document.height>window.innerHeight) ? window.innerHeight-=16 : window.innerHeight;
	}
	return 0;
}

function elementGetY (obj) {
	var y = 0;
	var o = obj;
	while (obj.offsetParent) {
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return y;
}


function sprintf() {
	if (!arguments || arguments.length < 1 || !RegExp) 	{
		return;
	}
	
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;     
	// '
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str)) {
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];

		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			
			
			var pad = '';
			if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			else if (pPad) pad = pPad;
			var justifyRight = true;
			if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
			if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
			if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			//alert(a[0] + " leftpart:"  + leftpart + " pad:" +  pPad + " jus:" + pJustify + " minlen:"  + pMinLength + " prec:" + pPrecision + " type:" + pType + " value:" + param + " precision:" + precision);
			var subst = param;
			if (pType == 'b') subst = parseInt(param).toString(2);
			else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			else if (pType == 'u') subst = Math.abs(param);
			else if (pType == 'f') {
				if (precision > -1) {
					if (param == 0) {
						subst = '0'+'00000'.substring(0,precision);
					} else {
						subst = Math.round(parseFloat(param) * Math.pow(10, precision)) + '';
					}
			  		subst = '' + Math.round(subst / Math.pow(10, precision)) + '.' + subst.substring(subst.length - precision,subst.length);
				} else {
					subst = parseFloat(param);
				}
			} else if (pType == 'o') subst = parseInt(param).toString(8);
			else if (pType == 's') subst = param;
			else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}

function getCssRule(seltext) {
	var stylesheets = document.styleSheets;
	var s,r;
	var sheetrules,currule,curstate;
	for (s=0;s<stylesheets.length;s++) {
		//if (stylesheets[s].href != '' && stylesheets[s].href != location.href) continue;
		sheetrules = stylesheets[s].cssRules ? stylesheets[s].cssRules : stylesheets[s].rules;
		for (r=0;r<sheetrules.length;r++) {
			currule = sheetrules[r];
			if (currule.selectorText.toLowerCase() == seltext) {
				return currule;
			}
		}
	}
	return false;
}

function chgCssRule(rule,k,v) {
        var r = getCssRule(rule);
        if (r) eval('r.style.' + k + '= v;');
}

//Voor flash
var flash_plugin;
function GetSwfVer(){
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		var flashObj;
		if ((flashObj=navigator.plugins["Shockwave Flash 2.0"]) || (flashObj=navigator.plugins["Shockwave Flash"])) return parseInt(flashObj.description.split(" ")[2]);
	} else if ( isIE && isWin && !isOpera ) {
		var axo,e;
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			return parseInt(axo.GetVariable("$version").split(" ")[1]);
		} catch (e) {}
	}
	return 0;
}
function checkFlash(swf_version,no_flash_url) {
	if (flash_plugin) return true;
	if (no_flash_url && location.href.indexOf(no_flash_url)>-1) return false;
	flash_plugin = GetSwfVer() >= swf_version;
	if ( !flash_plugin && no_flash_url) location.href=no_flash_url;
	return flash_plugin;
}
function gettag(name) {
	var attr='';var j=0;var ref,i;
	while(ref=arguments[++j]) for (var i in ref) attr+=' '+i+'="'+ref[i]+'"';
	return '<'+name+attr+'>\n';
}
function getflash(url,paramsref,dim,swf_version,no_flash_url,only_embed) {
	if (swf_version && !checkFlash(swf_version,no_flash_url)) return '';
	if (only_embed == 'detect') only_embed=!(isIE && isWin && !isOpera);
	if (only_embed) return getflashembed(url,paramsref,dim,swf_version);
	if (only_embed==null) {
		var id = paramsref.id ? paramsref.id : paramsref.name;
		var name = paramsref.name ? paramsref.name : id;
		delete( paramsref.id );
		paramsref.name = name;
		var embed = getflashembed(url,paramsref,dim,swf_version);
		delete(paramsref.name);
		paramsref.id = id;
		return getflashobject(url,paramsref,dim,swf_version,embed,true);
	}
	return getflashobject(url,paramsref,dim,swf_version);
}
function writeflash(url,paramsref,dim,swf_versionswf_version,no_flash_url,only_embed) {
	var str=getflash(url,paramsref,dim,swf_versionswf_version,no_flash_url,only_embed);
	document.writeln(str);
}
function getflashembed(url,paramsref,dim,swf_version) {
	var attr={src:url,TYPE:"application/x-shockwave-flash",PLUGINSPAGE:"http://www.macromedia.com/go/getflashplayer"};
	var emb=gettag('embed',attr,dim,paramsref)+gettag('/embed');
	return emb;
}
function getflashobject(url,paramsref,dim,swf_version,content,both) {
	if (content==null) content='';
	var attr;
	if (isIE || both) {
		attr={id:"hp_video_obj",classid:'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',codebase:'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+swf_version+',0,0,0'};
	} else {
		attr={id:"hp_video_obj",TYPE:"application/x-shockwave-flash",data: url};
	}
	if (paramsref.id) attr.id=paramsref.id;
	if (paramsref.name) attr.name=paramsref.name;
	var obj=gettag('object',attr,dim);
	obj+=gettag('param',{name: 'movie',value:url});
	for (var i in paramsref) {
		if (i=='name' || i=='id') continue;
		obj+=gettag('param',{name: i,value:paramsref[i]});
	}
	return obj+content+gettag('/object');
}

function rx_sizeToContent() {
	var isMSIE = (navigator.appName == "Microsoft Internet Explorer");
	var isOpera = (navigator.userAgent.indexOf("Opera") != -1);
	var aX,aY,nX,nY;
//	if (isOpera)
	//return;

	if (!window.sizeToContent) {
		var xelm = document.documentElement;
		try {window.resizeTo(xelm.scrollWidth, xelm.scrollHeight);} catch (e) {}
		var dx = xelm.scrollWidth - xelm.clientWidth + 10;
		var dy = xelm.scrollHeight - xelm.clientHeight + 4;
		try {window.resizeBy(dx, dy);} catch (e) {}
		aX = window.opener.document.documentElement.clientWidth;
		aY = window.opener.document.documentElement.clientHeight;
		
		nX = Math.max(0,parseInt(((aX - xelm.clientWidth) / 2))) + Math.max(0,window.opener.screenLeft - window.screenLeft);
		nY = Math.max(0,parseInt(((aY - xelm.clientHeight) / 2))) +  + Math.max(0,window.opener.screenTop - window.screenTop);
		window.moveBy(nX,nY);
	} else {
		
		try {window.resizeTo(400, 250);} catch (e) {}
		window.scrollBy(1000, 1000);

		if (window.scrollX > 0 || window.scrollY > 0) {
			window.resizeBy(window.innerWidth * 2, window.innerHeight * 2);
			window.sizeToContent();
		}
			//window.resizeBy(16, 16);
		window.scrollTo(0, 0);
		var tX = window.opener.screenX;
		var tY = window.opener.screenY;
		aX = window.opener.innerWidth;
		aY = window.opener.innerHeight;
		if (aX < window.innerWidth) aX = window.innerWidth+2;
		if (aY < window.innerHeight) aY =  window.innerHeight+2;
		nX = parseInt((tX + aX - window.innerWidth) / 2);
		nY = parseInt((tY + aY - window.innerHeight) / 2);
		window.moveBy(nX-window.screenX,nY-window.screenY);
	}
}

function rx_utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var tmp_arr = [], i = ac = c1 = c2 = c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function rx_utf8_encode ( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function rx_base64_encode( data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['atob'] == 'function') {
    //    return atob(data);
    //}

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];

	if (data == "") return "";

    data = rx_utf8_encode(data);

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
	return enc;
}

function rx_base64_decode( data,json ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['btoa'] == 'function') {
//        return btoa(data);
  //  }

    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];

    data += '';
	if (data == "") return "";

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    dec =  rx_utf8_decode(dec);

	if (json && (typeof(dec) == "object" || (typeof(dec) == "string" && dec.charAt(0) == '{' && dec.charAt(dec.length-1) == '}'))) {
		eval("dec = " + dec);
	} 

	return dec;

}
// Deze wordt gebruikt voor de datepicker. Als s en e zijn de id's van de input-fields. Als alleen s gezet, doet hij alleen een parse om format te checken. 
function chkdates(format,s,e,warn) {
	s = $('#'+s);
	var sv = s.attr('value');
	if (e) {
		e = $('#'+e);
		var ev = e.attr('value');
	}
	var svd,evd;
	try {
		svd = $.datepicker.parseDate(format, sv);
		if (e) {
			evd = $.datepicker.parseDate(format, ev);
			if ( svd && evd && svd > evd) {
				e.attr('value',sv);
				if ( warn ) alert( warn );
			}
			e.datepicker('option', 'minDate', svd );
		}
	} catch(err) {
		alert(err);
		return;
	}
}
