/**
 * ajaxKit v 1.0
 * Kit for using Asynchronous JavaScript and XML with XMLHttpRequest
 *
 * Author: Radim Schinko 2007
 * License: Use ajaxKit as you want without no warranty and no permissions!
 *
**/
function ajaxKit(debug) {
	this.xmlhttp = null;
	this.debug = debug;
	this.automaticElementUpdates = new Array();
	this.responseOut = '';
	/**
	 * Reset data and function assigment
	 */
	this.reset = function() {
	  //
		this.requestMethod = "GET";
		this.requestFile = "";
		this.URLString = "";
		this.encodeURIString = false;
		//
    this.element = null;
  	this.elementObj = null;
		//
		this.params = new Object();
		this.paramsSeparator = "&";
		//
		this.responseStatus = new Array(2);
	  //
	  this.onLoading = function() { if(this.debug) alert('AJAX :: Request sent'); }; // Function to execute when response status is loading(1)
		this.onLoaded = function() { if(this.debug) alert('AJAX :: Response loaded'); }; // Function to execute when response status is loaded(2)
		this.onInteractive = function() { if(this.debug) alert('AJAX :: Response prepared'); }; // Function to execute when response status is interactive(3)
		this.onCompletion = function() { if(this.debug) alert('AJAX :: Request proccessed');	}; // Function to execute when response status is completed(4)
		this.onError = function() { if(this.debug) alert('AJAX :: Connection Error!'); }; // Function to execute when response status is loaded(2)
		this.onFail = function() { if(this.debug) alert('AJAX :: Init Failed'); }; // Function to execute when ajax initialization failed
	};
  /**
	 * Ajax initialization
	 */
	this.init = function() {
	  this.reset();
		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.initFailed = true;
			}
		}
	};
  /**
	 * Insert or update parameter for request
	 */
	this.setParam = function(name, value){
		this.params[name] = Array(value, false);
	};
  /**
	 * Encode parameter for request
	 */
	this.encParam = function(name, value, returnvars) {
	  if(value=='' || value==0) return false;
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.params[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
		return true;
	}
  /**
	 * Parse string and set params(encoded optional)
	 */
	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.paramsSeparator);
		regexp = new RegExp(this.paramsSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode) {
				this.encParam(urlVars[0], urlVars[1]);
			} 
			else {
				this.setParam(urlVars[0], urlVars[1]);
			}
		}
	}
  /**
	 * Create URL string from an global URIString and passed custom urlstring
	 */
	this.createURLString = function(urlstring) {
	  // Encoding global URLString
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}
    // Process passed custom urlstring(no encoding)
		if (urlstring) {
			if (this.URLString.length) { // URLString allready defined
				this.URLString += this.paramsSeparator + urlstring; // Add custom urlstring
			} 
			else { 
				this.URLString = urlstring;// Set custom urlstring
			}
		}
		// Prevents caching of URLString
		this.setParam("rndval", new Date().getTime());
    //
		urlstringTemp = new Array();
		for (paramName in this.params) {
		  // Encode params
			if (false==this.params[paramName][1] && true==this.encodeURIString) {
				encodedArr = this.encParam(paramName, this.params[paramName][0], true);
				delete this.params[paramName];
				this.params[encodedArr[0]] = Array(encodedArr[1], true);
				paramName = encodedArr[0];
			}
      // Insert param string
			urlstringTemp[urlstringTemp.length] = paramName + "=" + this.params[paramName][0];
		}
		//
		if (urlstring) {
			this.URLString += this.paramsSeparator + urlstringTemp.join(this.paramsSeparator);
		} 
		else {
			this.URLString += urlstringTemp.join(this.paramsSeparator);
		}
	}
  /**
	 * Run AJAX Request
	 */
	this.runAJAXRequest = function(urlstring) {
	  // Initialization Error
		if (this.initFailed) {
			this.onFail();
		} 
		else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.requestMethod == "GET") { 
					totalurlstring = this.requestFile + "?" + this.URLString; 
					this.xmlhttp.open(this.requestMethod, totalurlstring, true);
				} else { 
					this.xmlhttp.open(this.requestMethod, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				} 
        // Response handling
				this.xmlhttp.onreadystatechange = function() {
				  // Response Status handling
					switch (self.xmlhttp.readyState) {
					  // Waiting for response
						case 1: self.onLoading(); break;
						// Response is loaded
						case 2: self.onLoaded(); break;
						// Response is proccessed
						case 3: self.onInteractive(); break;
						// Response is prepared
						case 4:
							//self.response = self.xmlhttp.responseText;
							self.response = self.stringTrim(self.xmlhttp.responseText);
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.getResponse(self.response);
              // Element content replacement handling (if element is defined)
              //alert(self.elementObj.type);
							if (self.elementObj) {
								self.updateElementContent(self.elementObj);
							} 
							// Completion handling
							if (self.responseStatus[0] == "200") { 
								eval(self.onCompletion);
							} 
							// Error handling
							else {
								self.onError();
							}
              //
							self.URLString = "";
							break;
					}
				};
        // Send request
        // alert(this.requestFile + "?" + this.URLString);
        // alert('Delka requestu: ' + this.URLString.length);
				this.xmlhttp.send(this.URLString);
			}
		}
	};
	/**
	 * Response string whitespaces trim
	 */
	this.stringTrim = function(string) {
	  var i=0;
  	while(i < string.length && string[i] == ' ') {
  	  i++; 
  	}
  	string = string.substring(i, string.length);
	  //
  	var i=string.length -1;
  	while(i > 0 && string[i] == ' ') {
  	  i-=1;	
  	}
  	string = string.substring(0, i+1);
  	//
  	return string;
  }
	/**
	 * Element content update handling
	 */
	this.updateElementContent = function(elementObj) {
	  var elemNodeName = elementObj.nodeName; 
		elemNodeName = elemNodeName.toLowerCase();
		// Element has value
		if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
			elementObj.value = this.response;
		} 
		else {
			elementObj.innerHTML = this.response;
	  }
	};
	/**
	 * Run element update by ajax
	 */
	this.runElementUpdate = function(elementId,url,file,method,onLoadingFunc,onLoadedFunc,onInteractiveFunc,onCompletionFunc) {
	  this.reset();
	  //
	  this.element = elementId;
	  //
	  if(file) this.requestFile = file;
  	if(method) this.requestMethod = method;
	  if(onLoadingFunc) this.onLoading = onLoadingFunc;
	  if(onLoadedFunc) this.onLoaded = onLoadedFunc;
	  if(onInteractiveFunc) this.onInteractive = onInteractiveFunc;
	  if(onCompletionFunc) this.onCompletion = onCompletionFunc; 
	  //
  	this.runAJAXRequest(url);
	};
	/**
	 * Form post handling
	 */
	this.runFormPost = function(formElementId,responseTargetElementId,requestFile,requestMethod) {
	  this.reset();
	  //
	  var form = document.getElementById(formElementId);
	  if(!form) {
	    return false;
	  }
	  // Register all form inputs into parameters array
	  for(var i=0; i < form.elements.length; i++) {
	    switch(form.elements[i].type.toUpperCase()) {
	      case "CHECKBOX" : 
	        //alert(form.elements[i].name);
          if(form.elements[i].checked) {
            this.encParam(form.elements[i].name,1);
          }
          else {
            this.encParam(form.elements[i].name,"");
          }
	        break;
	      case "RADIO" :
	        if(form.elements[i].checked) {
	          this.encParam(form.elements[i].name,form.elements[i].value);
	        }
	        else if(this.params[form.elements[i].name]==undefined) {
	          this.encParam(form.elements[i].name,"");
	        }
	        break;
	      case "SELECT" :
	        this.encParam(form.elements[i].name, form.elements[i].options[form.elements[i].selectedIndex].value);
	        break;
	      case "FILE":  break; // Not supported
	      default: this.encParam(form.elements[i].name,form.elements[i].value);
	    }
	  }
	  //
	  this.requestMethod = requestMethod;
	  this.requestFile = requestFile;
	  this.element = responseTargetElementId;
	  this.runAJAXRequest();
	  //	  
	  return false;
	}	
	/**
	 * Show Pseudo PopUp Box with content loaded by ajax
	 */
	this.showPseudoPopUp = function(urlString,requestFile) {
	  var infoStr = "Pseudo PopUpBox: " + requestFile + "?" +urlString;
	  alert(infoStr);
	  // create an alement
	  var pppHolder = document.getElementById("pseudo_pop_up_box_container");
    //
	  pppHolder.innerHTML = "DEFAULT CONTENT FOR PPP";
	  
	  //
	  return false;
	};
	
	this.getResponse = function(response)
	{
		jeFalse = response;
	}
	
	/**
	 * Show Pseudo PopUp Box with content loaded by ajax
	 */
	this.runElementUpdateReturn = function(elementId,url,file,method,onLoadingFunc,onLoadedFunc,onInteractiveFunc,onCompletionFunc) {
	  this.reset();
	  //
	  this.element = elementId;
	  //
	  if(file) this.requestFile = file;
  	if(method) this.requestMethod = method;
	  if(onLoadingFunc) this.onLoading = onLoadingFunc;
	  if(onLoadedFunc) this.onLoaded = onLoadedFunc;
	  if(onInteractiveFunc) this.onInteractive = onInteractiveFunc;
	  if(onCompletionFunc) this.onCompletion = onCompletionFunc;
	  //
  	this.runAJAXRequest(url);

  	return this.responseOut;
	};
	
	/**
	 * Initialization
	 */
	this.init();
}
//
var ajaxKitVar = new ajaxKit(false);

