/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* 2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */
/***********************************************
* Ajax Includes script-  Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

//To include a page, invoke ajaxinclude_once("afile.htm") in the BODY of page
//Included file MUST be from the same domain as the page displaying it.

if (typeof ROOT_URL == 'undefined') ROOT_URL = "http://" + location.hostName + "/";

 function ajaxCreate() {
 	var page_request = false
 	
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
 	
 	return page_request;
}

function noCache(uri){
	return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567)

}

// Execute script code in string
function ajaxScript(str){
	try {
		var re = /<[\s\/]*script\b[^>]*>([^>]*)<\/script>/g;
		var matches = "";
		var match1;
		while (match1 = re.exec(str)) matches = matches + match1[1];
		re = /<[\s\/]*script\b[^>]*>(.*?)<\/script>/g;
		while (match1 = re.exec(str)) matches = matches + match1[1];
		
		var ele = document.createElement("SCRIPT");
		ele.type = 'text/javascript';
		ele.text = matches;
		document.body.appendChild(ele);
		
		//eval(matches);
		return true;
	}catch(e) {
		alert(e.message);
	}
}
// Read content from "path" and assign to "containerobj"."propertyName"
function ajaxRead(path, containerobj, propertyName) {
	var page_request = false

	if (!propertyName) propertyName="innerHTML";
	
	page_request = ajaxCreate();
	
	if (!page_request) return false;
	
	if (containerobj)
		eval("document.getElementById('" + containerobj + "')." + propertyName + " = 'Loading...'");
	
	page_request.onreadystatechange=function(){
		//page_request.readyState == 4 && 
		if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {								
		
		//	document.getElementById(containerobj).innerHTML = page_request.responseText;	
			//alert('sent2');
			if (containerobj){
				eval("document.getElementById('" + containerobj + "')." + propertyName + " = page_request.responseText");	
				
			}
			eval("ajaxScript(page_request.responseText)");
			
		}else if (page_request.readyState == 404 || page_request.readyState == 500) 
				alert("\n The system can not response at the moment. Please try again letter!");
	}
	if (path.indexOf("http:")==-1) 
		path = ROOT_URL + path;
		
	page_request.open('GET', noCache(path), true) //get page asynchronously 
	page_request.send(null)
	
//	if (window.location.href.indexOf("http")==-1 || page_request.status==200)
//		document.write(page_request.responseText)

	return true;
}

function ajaxSendForm(form, page_request, containerobj, propertyName ) {
	if (!page_request)
		page_request = ajaxCreate();	
	if (!page_request) return false;
	
	params = "";
	for(i=0; i < form.elements.length;i++) {
		if (form.elements[i].type == "select-multiple") {
			for(j=0, k=0;j< form.elements[i].length;j++)
				if (form.elements[i].options[j].selected) {
					params+= form.elements[i].name + "=" + form.elements[i].options[j].value + "&";
					k++;
				}
		}else if (form.elements[i].type == "checkbox" || form.elements[i].type == "radio") {
			if (form.elements[i].checked) 
				params += form.elements[i].name + "=" +  encodeURIComponent(form.elements[i].value) + "&";	
			//else
		}else
			params += form.elements[i].name + "=" +  encodeURIComponent(form.elements[i].value) + "&";		
	}	
		
	
	//alert(form.action);
	//alert(params);

	if (containerobj) {
		page_request.onreadystatechange=function(){

			if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {								
			
				if (!propertyName) propertyName="innerHTML";
				
				eval("document.getElementById('" + containerobj + "')." + propertyName + " = page_request.responseText");	
				
			}else if (page_request.readyState == 404 || page_request.readyState == 500) 
					alert("\n The system can not response at the moment. Please try again letter!");
		}
	}
  	page_request.open(form.method,form.action,true);		

	page_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');	

	page_request.send(params);
	
	return page_request;
}

function AJAX(sfile) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "GET";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;	//true ; false; optional
  		this.element = null;
		this.elementObj = null;
		this.requestFile = sfile;
		this.vars = new Object();
		this.responseStatus = new Array(2);
		this.response = '';
		
		if (sfile) {
			i = sfile.indexOf(this.queryStringSeparator);
			if (i != -1) {
				this.requestFile = sfile.substr(0, i);
				this.URLString = sfile.substr(i+1);
			}
		}
		
		this.inform = false;
		this.informObj = null;
		this.message = "Loading....";
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { alert ('Error: ' + this.responseStatus[0] + ": " + this.responseStatus[1]); };
		this.onFail = function() { };
		
		this.onFinish = function() { }; // Function to run after finish getting data
		this.turnonMessage = function() {
									if (this.inform) {
										if (!this.informObj) {
											var ele = document.createElement("SPAN");
											
											ele.innerHTML = this.message;
											ele.style.zIndex = 1000;
											ele.style.position = "absolute";
											ele.style.padding = "10px";
											ele.style.border = "1px solid red";
											ele.style.backgroundColor="#FFFF80";
											ele.innerHTML = this.message;
											if (!document.body) {
												 document.write('<BODY></BODY>');
											}
											document.body.appendChild(ele);
											this.informObj = ele;
										}
										
										if (this.elementObj) {	// Center of target element
											//alert(this.elementObj.offsetTop + " - " +  this.elementObj.offsetHeight + " - " + this.informObj.offsetHeight);
											this.informObj.style.left = this.elementObj.offsetLeft + this.elementObj.offsetWidth /2 - this.informObj.offsetWidth /2;
											this.informObj.style.top = this.elementObj.offsetTop + this.elementObj.offsetHeight /2 - this.informObj.offsetHeight /2;
										}else {			// Center the screen
											
											this.informObj.style.left = screen.width /2;
											this.informObj.style.top = screen.Height /2;
										}
										
										this.informObj.style.display = 'block';
										
									}
								};
		
		this.turnoffMessage = function() {
									if (this.informObj) {
										this.informObj.style.display = "none";
									}
								};
		this.noCache = function(uri){
									return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567)

								};
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};
	
	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		//this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
					
	}

	this.runResponse = function() {
		try {
			if (this.execute == "optional")
				ajaxScript(this.response);
			else
				eval(this.response);
		}catch (e) {
			alert(e.message + "\n" + this.response);
		}
	}

	this.sendForm = function(form) {
		params = "";
		for(i=0; i < form.elements.length;i++) {
			
			if (form.elements[i].type == "select-multiple") {
				for(j=0, k=0;j< form.elements[i].length;j++)
					if (form.elements[i].options[j].selected) {
						params+= form.elements[i].name + "=" + form.elements[i].options[j].value + "&";
						k++;
					}
			}else if (form.elements[i].type == "checkbox" || form.elements[i].type == "radio") {
				if (form.elements[i].checked) 
					params += form.elements[i].name + "=" +  encodeURIComponent(form.elements[i].value) + "&";	
						//else
			}else
				params += form.elements[i].name + "=" +  encodeURIComponent(form.elements[i].value) + "&";		
		
		}	
		
		
		tmp_method = this.method;
		tmp_requestFile = this.requestFile;
		
		this.method = form.method;
		this.requestFile = form.action;
		//alert(params);
		this.run(params);

		this.method = tmp_method;
		this.requestFile = tmp_requestFile;		
	}
	
	this.run = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			
			if (this.requestFile.indexOf("http:") == -1)
				this.requestFile = ROOT_URL + this.requestFile;
				
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					if (this.URLString)
						totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					else totalurlstring = this.requestFile;
					this.xmlhttp.open(this.method, this.noCache(totalurlstring), true);
				} else {
					this.xmlhttp.open(this.method, this.noCache(this.requestFile), true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}
				
				this.turnonMessage();
				
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							self.turnoffMessage();		// Turn off inform windows
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.turnoffMessage();		// Turn off inform windows
							
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName.toLowerCase();
								
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
									
								}
							}
							
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							
							self.onFinish();	
							break;
					}
				};
				//alert(this.requestFile + ' - ' + this.method + " - " + this.URLString);
				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}
