var mainfile = (this.location.href.indexOf('menu.php') > 0 ? 'menu.php' : undefined);
function ajaxObject(config){
	var obj = {

		_defaults :  {
			showWaiter 	: true, //laat een bezig gifje zien (default false)
			asynchroon	:	true, //indien false dan bevriest de pagina
			actie				: '', //de actie die php moet afhandelen
			parameters	: '', //De post parameters (bij AIM is dit het form)
			url					: (typeof(applicatieFolder)!='undefined'? applicatieFolder: '')+(typeof(mainfile)!='undefined'?mainfile+'?ajx':'index.php?ajx'), //de te openen url
			waiterImg		: 'images/spinner.gif', //de src van de waiter image
			method			: 'POST', //kan ook GET of AIM  zijn
			onReady 		: '', //	= function(){}
			validReturn : false //	de return type (tekst, xml,  json) moet van dit type zijn anders error weergeven (
		},
		userVars : {},

		init : function(config){
			//set de deault van deze pagina
			this.settings = this._defaults;
			if (typeof(config) == 'object'){
				for (var key in config){
					if (config[key] != null && config[key] != undefined){
						this.settings[key] = config[key];
					}
				}
			}
		},

		//que functies als de request achter elkaar geladen moeten worden
		queue : function (config){

			if (config == undefined) config = new Object;
			if (this.queueList == undefined) this.queueList = new Array();

			this.isqueue = true;
			this.queueList[this.queueList.length]=config; /* voeg actie toe aan lijst*/
			this.startqueue();
		},
		startqueue: function (){
			if(!this.ajaxBusy){
				this.ajaxBusy = true;
				var config = this.queueList.shift();
				this.load(config);
			}
		},


		load : function(config){
			config = (config || {});
			//config set hier parameters die alleen voor dit object gelden
			if (this.settings == undefined){
				//init is niet aangeroepen door user dus diet doen we zelf
				this.init();
			}

			//params maken met combi van settings en mee gegeven config

			for (var key in this.settings){
				if (config[key] == null || config[key] == undefined){
					config[key] = this.settings[key];
				}
			}

			if (config.method == 'AIM'){
				//AIM object bestaat standaard al
				// fake wat ajax dingetjes
				req = new Object();
				req.readyState = 4;
				req.status = 200;
			}else{
				//maak het request
				var req = this._createXMLHTTPObject();
				if (!req){
					alert('De door u gebruikte browser word niet ondersteund');
					return;
				}


				req.open(config.method, config.url, config.asynchroon);
				req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			}
			//waiter?
			if(config.showWaiter){
				this.showWaiter(config);
			}

			var ajaxObj = this;
			var onReadyStateChangeFunc = function (AIMResult) {

				if (req.readyState == 4) {
					//req is klaar
					if (req.status == 200 || req.status == 304){
						//geen error

						//verberg waiter
						if (ajaxObj.waiter){
							ajaxObj.hideWaiter();
						}

						if (config.method == 'AIM'){
							var resultaat = new Object();
							if (AIMResult.type){
								resultaat.type = AIMResult.type;
							}else{
								resultaat.type = 'xml';
							}
							var response = AIMResult;
						}else{
							//get response in juiste formaat
							var resultaat = ajaxObj.getResponse(req);
							var response = resultaat.response;
							//fout afhandeling
							if (config.validReturn && config.validReturn != resultaat.type){
								//type response niet juist
								if ( resultaat.type =='xml' && getXMLValue(response, 'nietToegestaan')){
									//laat het xml niet toegestaan gedeelte hem oppakken
								}else{
									alert(T_laadError);
									return;
								}
							}
						}


						if (typeof(response) == 'object'){
							if (resultaat.type == 'xml'){
								if (response.firstChild.tagName == 'parsererror'){
									//parse error
									alert('XML parse error');
									return;
								}
								var melding;
								if (melding = getXMLValue(response, 'alert')){
									alert(unescape(melding));
								}
								if (getXMLValue(response, 'nietToegestaan')){
									//request is niet toegestaan waarschijnlijk sessie verlopen of back gebrukt dus doe een refresh
									if (parent.document){
										parent.document.location.href = parent.document.location.href;
									}else{
										document.location.href = document.location.href
									}

									return;
								}
								var alertEnStop;
								if (alertEnStop = getXMLValue(response, 'alertEnStop')){
									alert(unescape(alertEnStop));
								}
							}else if (resultaat.type == 'json'){
								if (typeof(response['alert']) != 'undefined'){
									alert(unescape(response['alert']));
								}

								if (typeof(response['nietToegestaan']) != 'undefined'){
									//request is niet toegestaan waarschijnlijk sessie verlopen of back gebrukt dus doe een refresh
									document.location.href = document.location.href;
									return;
								}

								if (typeof(response['alertEnStop']) != 'undefined'){
									alert(unescape(response['alertEnStop']));
									return;
								}
								
								if (config.asynchroon == false && typeof(response['javaUitstapFunctie']) != 'undefined'){
									var javaUitstapResult;
									eval('javaUitstapResult = '+ response['javaUitstapFunctie'] + ';');
									
									//verder gaan met de php functie
									config.parameters += '&'+response['javaUitstapVar']+ '='+javaUitstapResult;
									ajaxObj.load(config);
									
									return;
								}
							}
						}else{
							if (response.indexOf('<b>Parse error</b>') != -1 || response.indexOf('<b>Fatal error</b>') != -1){
								//parse error
								alert(T_laadError);
								return;
							}
						}
						//probeer de onReady func te laden
						if ((typeof(config.onReady) == 'function') || (typeof(ajaxObj.onReady) == 'function')){
							//er is een onRedy func



							if (typeof(config.onReady) == 'function'){
								//de onReady is in de config van dit specifieke request meegegeven
								config.onReady(response, req);
							}else{
								//run de onReady van het object
								ajaxObj.onReady(response, req);
							}
						}

						//moeten we nog door queueen
						if (ajaxObj.isqueue == true){
							ajaxObj.ajaxBusy = false;
							if (ajaxObj.queueList.length > 0)
								ajaxObj.startqueue();
						}
						//mem opschonen
						ajaxObj.req = undefined;
						ajaxObj.params = undefined;

					}else{
						//een http error
						alert('Http error. Code : '+req.status);
						//niet verder queueen
						ajaxObj.queueList = undefined;
						ajaxObj.ajaxBusy = false;
					}
				}
			}
			if (config.method == 'AIM'){
				var AIMcallBackFunctions = new Object();
				AIMcallBackFunctions.onComplete = onReadyStateChangeFunc;
				//config.parameters dient hier de form te zijn
				var form = config.parameters;
				var doen = AIM.submit(form, AIMcallBackFunctions);
				if (doen){
					form.action = config.url+(config.actie != '' ? '&actie='+config.actie : '');
					form.submit();
				}
			}else{
				if (config.asynchroon == true){
					req.onreadystatechange = onReadyStateChangeFunc;
				}
				if (typeof(config.parameters) == 'object'){ //of array
					var parameters = '';
					for (var key in config.parameters){
						parameters += key+'='+config.parameters[key]+'&';
					}
					config.parameters = parameters;
				}
				var postData='actie='+config.actie+'&'+config.parameters;

				req.send(postData);
				if (config.asynchroon == false){
					if (config.showWaiter){
						ajaxObj.hideWaiter();
					}
					onReadyStateChangeFunc();
					var resultaat = ajaxObj.getResponse(req);
					return resultaat.response;
				}
			}
		},

		_createXMLHTTPObject : function(){
			var XMLHttpFactories = [
				function () {return new XMLHttpRequest()},
				function () {return new ActiveXObject("Msxml2.XMLHTTP")},
				function () {return new ActiveXObject("Msxml3.XMLHTTP")},
				function () {return new ActiveXObject("Microsoft.XMLHTTP")}
			];
			var xmlhttp = false;
			for (var i=0;i<XMLHttpFactories.length;i++) {
				try {
					xmlhttp = XMLHttpFactories[i]();
				}
				catch (e) {
					continue;
				}
				break;
			}
			return xmlhttp;
		},

		showWaiter : function(config){
			//maak waiter als deze nog niet bestaat

			if(!this.waiter){
				if (!document.getElementById('ajaxWaiter')){
					this.waiter = document.createElement('IMG');
					this.waiter.src = config.waiterImg;
					this.waiter.id = 'ajaxWaiter'+ Math.random();
					this.waiter.style.position = 'absolute';
					this.waiter.style.zIndex = '1000';
					document.body.appendChild(this.waiter);
				}else{
					this.waiter = document.getElementById('ajaxWaiter');
				}

			}
			//bepaal breedte en hoogte van window
			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;
			}
			//bepaal midden
			var mid = new Object();
			mid.x = (myWidth/2);
			mid.y = (myHeight/2);

			//plaats waiter
			this.waiter.style.top = mid.y+0+'px';
			this.waiter.style.left = mid.x+12+'px';
			this.waiter.style.display = 'block';
		},

		hideWaiter : function(){
			this.waiter.style.display = 'none';
		},

		getResponse : function(req){
			var contentType = req.getResponseHeader('Content-Type');
			var mimeType = contentType.match(/\s*([^;]+)\s*(;|$)/i)[1];
			switch(mimeType.toLowerCase()) {
				case 'text/javascript':
				case 'application/javascript':
				case 'text/html':
				case 'text/plain':
				case 'text/css':
				default:
					var type = 'tekst';
					var response = req.responseText;

				break;
				case 'application/json':
				case 'application/x-json':
					var type = 'json';
					try {
						var response = parseJSON(req.responseText);
					} catch (exception) {
						var response = new Object();
						response.error = true;
						response.responseText = req.responseText;
						alert(T_laadError);
					}


				break;
				case 'text/xml':
				case 'application/xml':
				case 'application/xhtml+xml':
					var type = 'xml';
					var response = req.responseXML;



				break;
			}

			return {type : type, response : response};
		}
	}
	if (config){
		obj.load(config);
	}
	return obj;
};
function getXMLValue(xml, tagName){
	if(!(els=xml.getElementsByTagName(tagName))) return false;
	if(!(els[0])) return false;
	if(!(els[0].firstChild)) return '';
		return els[0].firstChild.nodeValue;
}
function parseJSON(str_json) {
	// Decodes the JSON representation into a PHP value
    //
    // version: 911.718
    // discuss at: http://phpjs.org/functions/json_decode    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      improved by: T.J. Leahy
    // +      improved by: Michael White
    // *        example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');    // *        returns 1: ['e', {pluribus: 'unum'}]
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */

    var json = this.window.JSON;    if (typeof json === 'object' && typeof json.parse === 'function') {
        try {
            return json.parse(str_json);
        } catch(err) {
						/*if (!(err instanceof SyntaxError)) {                throw new Error('Unexpected error type in json_decode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null; */       }
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
		var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
		cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
		// because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
		// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
		if ((/^[\],:{}\s]*$/).
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
					// In the third stage we use the eval function to compile the text into a
					// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
					// in JavaScript: it can begin a block or an object literal. We wrap the text
					// in parens to eliminate the ambiguity.

				// by ultraware euro fix
				text = text.replace(/u0080/g, '€');
				text = text.replace('null', 'undefined');

				j = eval('(' + text + ')');
				return j;
    }
		// If the text is not JSON parseable, then a SyntaxError is thrown.
		throw new SyntaxError('json_decode');
/*
	// http://kevin.vanzonneveld.net
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *     returns 1: ['e', {pluribus: 'unum'}]



    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' +
            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if (/^[\],:{}\s]*$/.
        test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.

				// by ultraware euro fix
				text = text.replace(/u0080/g, '€');

        j = eval('(' + text + ')');

        return j;
    }

    // If the text is not JSON parseable, then a SyntaxError is thrown.
    throw new SyntaxError('json_decode');*/
}

/**
*
*  AJAX IFRAME METHOD (AIM)
*  voorbeeld http://www.webtoolkit.info/ajax-file-upload.html
*
**/

AIM = {

	frame : function(c) {
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		var d, xmlObject;
		if (i.contentDocument) {
				d = i.contentDocument;
		} else if (i.contentWindow) {
				d = i.contentWindow.document;
		} else {
				d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
				return;
		}
		if (typeof(i.onComplete) == 'function') {

			if (d.xmlVersion){
				xmlObject = d;
			}else{
				var xml = d.body.innerHTML;
				xml = xml.split('> <').join('><');
				xml = xml.split('<DIV class=e>').join('');
				xml = xml.split('<DIV class=d>').join('');
				xml = xml.split('<DIV class=c>').join('');
				xml = xml.split('<DIV class=k>').join('');
				xml = xml.split('<SPAN class=b>').join('');
				xml = xml.split('<SPAN class=k>').join('');
				xml = xml.split('<SPAN class=t>').join('');
				xml = xml.split('<SPAN class=tx>').join('');
				xml = xml.split('<SPAN class=m>').join('');
				xml = xml.split('<SPAN class=pi>').join('');
				xml = xml.split('<SPAN class=di>').join('');
				xml = xml.split('<A class=b style="VISIBILITY: hidden" onfocus=h() onclick="return false">-').join('');
				xml = xml.split('</A>').join('');
				xml = xml.split('<SPAN>').join('');
				xml = xml.split('<DIV>').join('');
				xml = xml.split('<PRE>').join('');
				xml = xml.split('</PRE>').join('');
				xml = xml.split('</DIV>').join('');
				xml = xml.split('</SPAN>').join('');
				xml = xml.split('<DIV class=c style="MARGIN-LEFT: 1em; TEXT-INDENT: -2em">').join('');
				xml = xml.split('<DIV style="MARGIN-LEFT: 1em; TEXT-INDENT: -2em">').join('');
				xml = xml.split('<A class=b onfocus=h() onclick="return false" href="#">-').join('');
				xml = xml.split('<SCRIPT>f(clean);</SCRIPT>').join('');
				xml = xml.split('<SPAN class=di id="">').join('');
				xml = xml.split('&gt;').join('>');
				xml = xml.split('&lt;').join('<');
				xml = xml.split(/\r/g).join('');
				xml = xml.split(/\n/g).join('');
				xml = xml.split('&nbsp;').join("");
				xml = xml.replace('&nbsp;', '' );
				xml = xml.split('> <').join('><');
				xml = xml.split('> <').join('><');
				xml = xml.split('<![CDATA[').join('');
				xml = xml.split(']]>').join('');
				xml = xml.split('<?xml version="1.0" encoding="UTF-8" ?>').join('');
				xml = xml.split('<DIV style="TEXT-INDENT: -2em; MARGIN-LEFT: 1em" class=c>').join('');
				xml = xml.split('<A style="VISIBILITY: hidden" class=b onfocus=h() onclick="return false">-').join('');
				xml = xml.split('<DIV style="TEXT-INDENT: -2em; MARGIN-LEFT: 1em">').join('');

				if (window.ActiveXObject){
					xmlObject=new ActiveXObject('Microsoft.XMLDOM');
					xmlObject.async='false';
					xmlObject.loadXML(xml);
				} else {
					var parser=new DOMParser();
					xmlObject=parser.parseFromString(xml,'text/xml');
				}
			}
			//xmlObject.loadXML(xml);
			//alert(d.body.innerHTML);
			//alert(xml);
			if (json = getXMLValue(xmlObject, 'json')){
				var result = parseJSON(json);
				result.type = 'json'
				i.onComplete(result);
			}else{
				i.onComplete(xmlObject);
			}

		}
	}

}
/*EINDE AIM*/
