/*
-----------------------------------------------
Ajax class

By Rodesigned 2008

Version         1.0
-----------------------------------------------
*/
var AjaxParameters = null;
var AjaxPeriodicalResponseInterval = [];
var AjaxActiveRequests = [];

function getXmlHttp(requestType) {
	requestType = (requestType !== undefined ? requestType : '');
	var xmlHttp = null;
	try {xmlHttp = new XMLHttpRequest();}
	catch (e) {
		try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e) {
			try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
			catch (e) {xmlHttp = false;}
		}
	}
    if (xmlHttp.overrideMimeType) {xmlHttp.overrideMimeType('text/'+requestType);}
    return xmlHttp;
}

if (!window.execScript) {
	window.execScript = function(script) {setTimeout(script, 0);};
}

function Ajax() {

	this.responseText = null; // de responseText of responseXML value, alleen als 'this.response' true is
	this.lastRequest = null; // alert(Ajax.lastRequest.properties.url); Hiermee kan de laatste aanroep nogmaals gedaan worden, indien nodig

}

function AjaxFramework() {

	AjaxParameters = [];

	this.container  = null; // id van de layer
	this.url		= null; // op te roepen url
	this.request	= null; // mee te geven parameters aan de url
	this.response	= false; // wel of geen response (resultaat in JS var), true, false/null
	this.method		= 'get';// get of post
	this.onSuccess	= null; // naam van functie outgevoerd door eval(), bij succes
	this.onFailure	= null; // naam van functie outgevoerd door eval(), bij een error
	this.onLoading	= null; // script dat uitgevoerd moet worden, of functie aanroepen bij readyState 2 (loading)
	this.onLoaded	= null; // script dat uitgevoerd moet worden, of functie aanroepen bij readyState 3 (loaded)
	this.evalJs		= true; // <script> blocks uitvoeren in de opgevraagde url
	this.form		= null; // naam van formulier waarvan parameters meegesturu meoten worden
	this.encoding	= 'UTF-8'; // encoding, UTF-8, ISO, etc
	this.preventCache = false; // wel of geen gecachte gegevens op laten halen (uit browser)
	this.requestType = 'html'; // type request, html, xml, plain
	this.showLoading = false; // wel of geen 'loading' laten zien in de container, kan eventueel flikkering geven
	this.responseText = null; // de responseText of responseXML value, alleen als 'this.response' true is
	this.proxy		= null; // als er een proxy opgegevens is, wordt url via deze proxy opgevraagd (url laden via php of asp pagina)
	this.formRequest = null;

	AjaxParameters.push(this);
	AjaxParameters = AjaxParameters[0];
}

Ajax.prototype.Updater = function(container,url,request,parameters) {
	this.Request(container,url,request,parameters,false);
};

Ajax.prototype.Response = function(url,request,parameters) {
	this.Request(null,url,request,parameters,true);
};

Ajax.prototype.PeriodicalResponse = function(url,request,parameters) {
	Ajax.Response(url,request,parameters);
	AjaxPeriodicalResponseInterval[url] = setInterval(function() {Ajax.Response(url,request,parameters);},Math.round(parameters.interval*1000));
};

Ajax.prototype.Request = function(container,url,request,parameters,response) {

	var AjaxFw = new AjaxFramework();
	AjaxFw.container		= container;
	AjaxFw.url				= url;
	AjaxFw.request			= (request !== undefined && request !== '' ? '?'+request.replace("'","\'") : '');
	AjaxFw.response			= (response === true ? true : false);
	if (parameters !== undefined) {
		AjaxFw.response			= (response === true && parameters.response !== undefined? true : AjaxFw.response);
		AjaxFw.method			= (parameters.method !== undefined ? parameters.method : AjaxFw.method);
		AjaxFw.onSuccess		= (parameters.onSuccess !== undefined ? parameters.onSuccess : AjaxFw.onSuccess);
		AjaxFw.onFailure		= (parameters.onFailure !== undefined ? parameters.onFailure : AjaxFw.onFailure);
		AjaxFw.onLoading		= (parameters.onLoading !== undefined ? parameters.onLoading : AjaxFw.onLoading);
		AjaxFw.onLoaded			= (parameters.onLoaded !== undefined ? parameters.onLoaded : AjaxFw.onLoaded);
		AjaxFw.evalJs			= (parameters.evalJs !== undefined ? parameters.evalJs : AjaxFw.evalJs);
		AjaxFw.form				= (parameters.form !== undefined ? parameters.form : AjaxFw.form);
		AjaxFw.encoding			= (parameters.encoding !== undefined ? parameters.encoding : AjaxFw.encoding);
		AjaxFw.preventCache		= (parameters.preventCache !== undefined ? parameters.preventCache : AjaxFw.preventCache);
		AjaxFw.requestType		= (parameters.requestType !== undefined ? parameters.requestType : AjaxFw.requestType);
		AjaxFw.showLoading		= (parameters.showLoading !== undefined ? parameters.showLoading : AjaxFw.showLoading);
	}
	AjaxFw.Execute();

};

// eval() uit scope halen zodat een eventueel lek geen toegang geeft tot andere vars
function AjaxExecuteEval(script) {
	eval(script);
	script = null;
}

function AjaxExecuteFunction(xhr,script) {
	if (script.toString().match('function') !== null) {
		var f = script;
		f(xhr);
		script = null;
	}
	else {
		AjaxExecuteEval(script);
	}
}

AjaxFramework.prototype.Execute = function() {

    // Wordt reguest al uitgevoerd, dan niet uitvoeren. Anders wel en registreren
    var currentRequest = this.method.toString().toUpperCase()+'#'+this.url+''+this.request;
    if (AjaxActiveRequests.inArray(currentRequest,AjaxActiveRequests)) {
        return false;
    }
    var AjaxActiveRequestsNum = (AjaxActiveRequests.length === 0) ? 0 : AjaxActiveRequests.length;
    AjaxActiveRequests[AjaxActiveRequestsNum] = currentRequest;

	Ajax.lastRequest = {properties: this};

	if (this.form !== null) {
		this.buildFormRequest();
		// Nu het formulier uitschakelen (submit disable)
		this.statusFormSubmit(this,'disabled');
	}

	var xhr = getXmlHttp(this.requestType);
	var _this		= this;
    

	xhr.open(this.method.toString().toUpperCase(), this.url+''+this.request, true);
	xhr.onreadystatechange = function() {

		switch(xhr.readyState) {
			case 0:
				break;
			case 1:
				if (_this.onLoading !== null) {AjaxExecuteFunction(xhr,_this.onLoading);}
				break;
			case 2:
				if (_this.onLoaded !== null) {AjaxExecuteFunction(xhr,_this.onLoaded);}
				break;
			case 3:
				break;
			case 4:
				if (xhr.status == 200) {
					if (_this.container !== null && _this.response === false) {
						if (document.getElementById(_this.container) === null) {
							alert('Requested container/layer ('+_this.container+') could not be found');
						}
						else {
							document.getElementById(_this.container).innerHTML = xhr.responseText;
							if (_this.evalJs === true) {
								var re = /<script(\s[^>]*)?>([\s\S]*?)<\/script>/gi, match;
								while (match = re.exec(xhr.responseText)) {window.execScript(match[2], 'javascript');}
							}
						}
					}
					if (_this.response === true) {Ajax.responseText = xhr.responseText;}
					if (_this.onSuccess !== null) {
						AjaxExecuteFunction(xhr,_this.onSuccess);
					}
					xhr = null;
				}
				else if (xhr.status == 404) {
					if (_this.onFailure !== null) {AjaxExecuteFunction(xhr,_this.onFailure);}
					xhr = null;
				}

				if (_this.form !== null) {
					_this.statusFormSubmit(_this,'');
				}
				break;
		}

	};

	if (this.method.toString().toUpperCase() == 'POST') {
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		if (this.formRequest === null) {
			this.formRequest = '&_=';
		}
    }

	if (this.preventCache === true) {
    	xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		xhr.setRequestHeader("Cache-Control", "no-cache");
	}
	xhr.send(this.formRequest);

    delete AjaxActiveRequests[AjaxActiveRequestsNum];
    AjaxActiveRequests.pop(AjaxActiveRequestsNum);
    //alert(AjaxActiveRequests.length);

};


AjaxFramework.prototype.buildFormRequest = function() {

	if (this.form !== null && document.getElementById(this.form) !== null) {
		//var request = '?';
		var pairs = [];
		var ename = null;
		var value = null;
		with (document.getElementById(this.form)) {
			for (var i=0; i < elements.length; i++) {
				ename = (elements[i].name !== undefined && elements[i].name != '' ? elements[i].name : elements[i].id);
				value = elements[i].value;
					 
				if (elements[i].type != 'checkbox' || (elements[i].type == 'checkbox' && elements[i].checked)) {
	
					if (elements[i].type == 'select-multiple') {
						for (var n=0; n < elements[i].options.length; n++) {
							if (elements[i].options[n].selected) {pairs.push(ename + "=" + encodeURIComponent(elements[i].options[n].value));}
						}
					}
					else if (elements[i].type == 'radio') {
						if (elements[i].checked) {pairs.push(ename + "=" + encodeURIComponent(value));}
					}
					else {pairs.push(ename + "=" + encodeURIComponent(value));}
				}
			}
			ename = null;
			value = null;
		}
		AjaxParameters.formRequest = pairs.join("&");
		pairs = null;
	}

};


AjaxFramework.prototype.statusFormSubmit = function(objThis,status) {

	if (document.getElementById(objThis.form) !== null) {

		var elements = document.getElementById(objThis.form).getElementsByTagName('input');
		for(var i = 0;i<elements.length;i++) {
			//if (elements[i].type == 'submit' || elements[i].type == 'reset') {
				elements[i].disabled = status;
			//}
		}

	}

	return true;

}

var Ajax = new Ajax();