/***************************************************************
 **            Ajax Framework        	                      **
 **                                                           **
 **         Author:   Pasquale Di Stasio                      **
 **         E-Mail:   info@pasqualedistasio.com               **
 **       Web-Site:   www.pasqualedistasio.com                **
 **                                                           **
 **           Date:   2006-09-27                              **
 **        Version:   1.0                                     **
 ***************************************************************/


XMLHTTP = function(url) {
	if (url == "") {
		alert("URL is not defined");
	}
	this.server_url = url;
	this.debug = false;
	this.cache = false

	this.isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
	this.isMozilla = (navigator.userAgent.indexOf("Gecko") >= 0);

	this.req = null;
	this.mode="";
	this.queue_in_process = 0;
	this.debug_index = 0;
	this.loading = false;	

	this.getXMLHTTP = function() {
		if (window.XMLHttpRequest) {
			this.req = new XMLHttpRequest();
		} else if (window.ActiveXObject){
			try {this.req = new ActiveXObject("Msxml2.XMLHTTP");} 
			catch (e) {try {this.req = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}}
		} else {
			if(this.debug == true) {
				this.showDebug("FATAL ERROR: Could not create XMLHTTPRequest Object!");	
			}
			return false;
		}
		return this.req;
	}


	this.call = function(queryVars, method, currCallback, headers, currMode) {
		if(this.queue_in_process > 0) {
			return false;
		}
		if(!this.getXMLHTTP()) {
			return false;
		}
		if(currMode.toLowerCase() == "xml") {
			this.mode="XML";
			if (this.req.overrideMimeType) this.req.overrideMimeType("text/xml");
		}
		this.queue_in_process = 1;
		this.req.onreadystatechange = this.responseHandler;
		if (!this.cache) {
			var rnd = Math.random();
			full_url = this.server_url + "?" + "_nocache=" + rnd;
			if (method == "GET" && queryVars != "") {
				full_url += "&" + queryVars;
			}
		} else {
			full_url = (method == "POST") ? this.server_url : this.server_url + '?' + queryVars;
		}
		
		if(this.debug == true) {
			this.showDebug("Server Page: "+this.server_url+"<br />HTTP Method: "+method+"<br />Cache: "+this.cache+"<br />Vars: "+queryVars+"<br />Full URL: "+full_url);
		}
		this.req.open(method, full_url, true);
		if(headers){
			var str_headers = "Setting Custom Header:<br>"
			for(var i in headers) {
				if(i != "") {
					try {
						this.req.setRequestHeader(i, headers[i]);
						if(this.debug == true) {
							str_headers += " &nbsp; " + i + ": " +headers[i]+"<br>";
						}
					} catch(e) {}
				}
			}
			if(this.debug == true) {
				this.showDebug(str_headers);
			}
		}
		this.callback = currCallback;
		if(method == 'POST') {
			this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			this.req.send(queryVars);
		} else {
			this.req.send(null);
		}
	}

	this.responseHandler = function() {
		if(ajaxObj.req && ajaxObj.queue_in_process > 0) {
			try {
				if (!ajaxObj.loading) ajaxObj.loader();
				if (ajaxObj.req.readyState != 4) return;
				if (ajaxObj.debug == true) {
					var str = ajaxObj.req.responseText.replace(/(\<)/gi, '&lt;');
					str = str.replace(/(\>)/gi, '&gt;');
					ajaxObj.showDebug("HTTP Server Response:<br/> "+str);
				}
				ajaxObj.queue_in_process = 0;
				ajaxObj.clearLoader();
				if (ajaxObj.req.status != 200) {
					ajaxObj.net_down();
					return false;
				} else if(ajaxObj.mode == "XML") {
					if (document.implementation && document.implementation.createDocument) {
						response = ajaxObj.req.responseXML;
					} else if (window.ActiveXObject) {
						if(document.getElementById('_formjAjaxDocumentXML')){
							document.body.removeChild(document.getElementById('_formjAjaxDocumentXML'));
						}
						var xmlDoc = document.createElement('xml');
						xmlDoc.setAttribute('innerHTML', ajaxObj.req.responseText);
						xmlDoc.setAttribute('id','_formjAjaxDocumentXML');
						document.body.appendChild(xmlDoc);
						response = document.getElementById('_formjAjaxDocumentXML');
					}
					ajaxObj.callback(response);
				} else {
					response = ajaxObj.req.responseText.split("<!===SEPARATOR===!>");
					ajaxObj.callback(response);
				}
				return true;
			} catch(e) {}
		}
	}

	this.net_down = function(status) {
		if(status == 'disable') {
			var msg = 'A network issue has disabled network connections for this page. Please reload this page';
		} else {
			var msg = 'A network issue has occurred which canceled your last request';
		}
		try {
			boxWidth = 340;
			topPosition = parseInt(document.body.scrollTop) + ((document.body.clientHeight - 200) / 2)
			leftPosition = parseInt(document.body.scrollLeft) + ((document.body.clientWidth - boxWidth) / 2)
			if (document.getElementById("ajax_div_notification")) {
				document.getElementById("ajax_div_notification").style.left = leftPosition + "px";
				document.getElementById("ajax_div_notification").style.top = topPosition + "px";
			} else{
				var notif_div = '<span id="ajax_notif_msg"></span><br /><br /><input type="button" value="  OK  " onclick="document.getElementById(\'ajax_div_notification\').style.display=\'none\';" />';
				var div_down = document.createElement('div');
				div_down.id = "ajax_div_notification";
				div_down.style.textAlign = "center";
				div_down.style.padding = "20px 20px 20px 20px";
				div_down.style.position = "absolute";
				div_down.style.top = topPosition + "px";
				div_down.style.left = leftPosition + "px";
				div_down.style.width = boxWidth + "px";
				div_down.style.border = "1px dotted #333333";
				div_down.style.backgroundColor = "#F7F7F7";
				div_down.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
				div_down.style.fontSize = "12px";
				div_down.innerHTML = notif_div;
				document.body.appendChild(div_down);			
			}
			document.getElementById('ajax_notif_msg').innerHTML = msg;
			document.getElementById('ajax_div_notification').style.display = "block";
		} catch(e) { 
			alert(msg);
		}
	}


	this.loader = function(){
		this.loading = true;
		sTop = parseInt(document.body.scrollTop);
		sLeft = parseInt(document.body.scrollLeft);
		topPosition = sTop + ((document.body.clientHeight - 164) / 2)
		leftPosition = sLeft + ((document.body.clientWidth - 199) / 2)
		bodyW = document.body.scrollWidth;
		bodyH = document.body.scrollHeight;
		if (document.getElementById("ajax_container_loader")) {
			document.getElementById("ajax_container_loader").style.width = bodyW + "px";
			document.getElementById("ajax_container_loader").style.height = bodyH + "px";
			document.getElementById("ajax_img_loader").style.top = topPosition + "px";
			document.getElementById("ajax_img_loader").style.left = leftPosition + "px";
		} else{
			var notif_div = '<div id="ajax_img_loader" style="position:absolute; top:'+topPosition+'px; left:'+leftPosition+'px; z-index:99; color:#333333; font-size:18px;" align="center"><b>LOADING...</b></div>';
			var div_loader = document.createElement('div');
			div_loader.id = "ajax_container_loader";
			div_loader.style.position = "absolute";
			div_loader.style.top = "0px";
			div_loader.style.left = "0px";
			div_loader.style.width = bodyW + "px";
			div_loader.style.height = bodyH + "px";
			div_loader.style.backgroundImage = "url(bg_loader.gif)";
			div_loader.style.zIndex = "98";
			div_loader.innerHTML = notif_div;
			document.body.appendChild(div_loader);
		}
		if (this.isIE) {
			this.disableElement("SELECT", true);
		}
		document.getElementById('ajax_container_loader').style.display = "block";
	}

	this.clearLoader = function() {
		document.getElementById('ajax_container_loader').style.display = 'none';
		if (this.isIE) {
			this.disableElement("SELECT", false);
		}
		this.loading = false;
	}

	this.disableElement = function(tagName, val) {
		for (i=0; i<document.all.tags(tagName).length; i++) {
			obj = document.all.tags(tagName)[i];
			if (!obj) continue;
			obj.disabled = val;
		}
	}

	this.showDebug = function(msg){
		if (this.debug != true) return;
		try {
			boxWidth = 600;
			topPosition = 10;
			leftPosition = 80;
			if (document.getElementById("ajax_div_debug")) {
				document.getElementById("ajax_div_debug").style.left = leftPosition + "px";
				document.getElementById("ajax_div_debug").style.top = topPosition + "px";
			} else{
				notif_div = '<span id="ajax_debug_msg"></span><br /><input type="button" value="  OK  " onclick="document.getElementById(\'ajax_div_debug\').style.display=\'none\';" />';
				var div_debug = document.createElement('div');
				div_debug.id = "ajax_div_debug";
				div_debug.style.padding = "10px 10px 10px 10px";
				div_debug.style.position = "absolute";
				div_debug.style.top = topPosition + "px";
				div_debug.style.left = leftPosition + "px";
				div_debug.style.width = boxWidth + "px";
				div_debug.style.border = "1px dotted #333333";
				div_debug.style.backgroundColor = "#BBCFB5";
				div_debug.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
				div_debug.style.fontSize = "12px";
				div_debug.innerHTML = notif_div;
				document.body.appendChild(div_debug);			
			}
			document.getElementById('ajax_debug_msg').innerHTML += "<b>--" + ++this.debug_index + "-----------------------------------</b><br />" + msg + "<hr />";
			document.getElementById('ajax_div_debug').style.display = "block";
		} catch(e) {
			alert(msg);
		}
	}
}

