/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* http://www.twilightuniverse.com/projects/sack */

function xhttp() {	
	this.xmlhttp = null;
	this.httpRoot = (window.httpRoot==undefined) ?'': window.httpRoot;
	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = '';
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = 'index.php';
		this.vars = new Object();
		this.responseStatus = new Array(2);
		this.enableExtURL = false;
		this.async = false;
		this.errors= new Array("Data "+"Error","User "+"error","<b>Fatal "+"error</b>","<b>Parse "+"error</b>","<b>Warning"+"</b>","<b>Catchable fatal "+"error</b>");
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { alert('xhttp error \n '+ this.xmlhttp.status + ' ' + this.xmlhttp.statusText + '\n' + this.xmlhttp.responseText) };
		this.onFail = function() { alert('xhttp failed \n '+ this.xmlhttp.status + ' ' + this.xmlhttp.statusText + '\n' + this.xmlhttp.responseText)};
	};

	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) {
				try{ this.xmlhttp = new ActiveXObject("MSXML3.XMLHTTP") }catch(e3){
  					try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0") }catch(e){
						this.xmlhttp = null;
					}
				}
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
//		if(typeof value =='object' ) value = json_encode(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());
//		if(window.parent._nid)this.setVar("nid", window.parent._nid);
//		else 
		if(window._nid)this.setVar("nid", window._nid);


		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.eval = function() {
		eval(this.response);
	}
	this.ready = function(){

		document.body.style.cursor=""
		this.response = this.xmlhttp.responseText;
	
		this.responseText = this.xmlhttp.responseText;
		this.responseXML = this.xmlhttp.responseXML;
		this.responseStatus[0] = this.xmlhttp.status;
		this.responseStatus[1] = this.xmlhttp.statusText;
		
		if(this.response!==''){
			for (er in this.errors){
				try { if(this.response.toLowerCase().match(this.errors[er].toLowerCase())) {_log(this.errors[er]);showErrorMsg(this.response);break}	 }catch(e){} 				
			}
		}
		
		if (this.execute) {
			this.eval();
		}

		if (this.elementObj) {
			elemNodeName = this.elementObj.nodeName;
			elemNodeName.toLowerCase();
			if (elemNodeName == "input"
			|| elemNodeName == "select"
			|| elemNodeName == "option"
			|| elemNodeName == "textarea") {
				this.elementObj.value = this.response;
			} else {
				this.elementObj.innerHTML = this.response;
			}
			
	    	
			//execute all scripts
			var x = this.elementObj.getElementsByTagName("script"); 
			var x = this.elementObj.getElementsByTagName("script"); 
			for( var i=0; i < x.length; i++) {				
		    	if (!x[i].src) {	
		    		try { eval(x[i].text);
		    		 }catch(e){ }
		    	}
	    	}    	


	    }	
		if (this.responseStatus[0] == "200" || this.responseStatus[1] == "") {
			this.onCompletion();
		} else {
			this.onError();
		}
		this.URLString = "";
	}
	
	this.runAJAX = function(urlstring) {
		
		if(window.masterGet && this.method == "POST") this.setVar("masterGet",window.masterGet);	
		
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				if (this.enableExtURL) {
					enableCrossDomain()
			   }

				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.httpRoot + this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, this.async);
				} else { 
					document.body.style.cursor="wait"
					this.xmlhttp.open(this.method, this.httpRoot + this.requestFile, this.async);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
						this.xmlhttp.setRequestHeader("Cache-control","no-cache" )
//						this.xmlhttp.setRequestHeader("Content-length", this.URLString.length);
						this.xmlhttp.setRequestHeader("Connection", "close");
					} catch (e) {  }
				}

				this.xmlhttp.onreadystatechange = function() { 
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							if(!(browser.mozilla && !self.async)) self.ready();
							break;
					}
				};
			
				if(!this.URLString || this.URLString=='') return;
				try { this.xmlhttp.send(this.URLString);		}catch(e){} 				
				try { this.xmlhttp.readyState==1				 }catch(e){alert('no net')} 

				if(browser.mozilla && !this.async) this.ready()
			}
		}
	};

	this.reset();
	this.createAJAX();
}


function showErrorMsg(fullMsg){

	alert(fullMsg.replace(/<n\l>/gi,'\n'))


}
