﻿/* Title: ajaxlib.js*/
// AJAXLib v. 1.0
// author: Jacek Karaszewski, http://www.karaszewski.com/tools/ajaxlib/
// licenced under Creative Commons Attribution 2.5 License

// public
var GnextCallFunc ='';
var GnextCallFuncParam = '';
var GFromFunc = '';
var GCallBack = false;
/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*------------------------------------------------------------
   Function: net.xxx
	 content loader object for cross-browser requests
   
--------------------------------------------------------------    
  Revision History: 
------------------------------------------------------------*/ 
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
method = "POST";
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
  this.parameter = null;
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType ="application/x-www-form-urlencoded";
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader("Content-Type", contentType);
      }
      this.req.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); /* Added 060828 OS to workaround IE cache bug. */
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
      if (httpStatus==200 || httpStatus==0){
      	//resultXML = xmlRequestObj.responseXML
        this.onload.call(this);
      }
      else {
        this.onerror.call(this);
      }
  }
}
net.ContentLoader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}
 
/*------------------------------------------------------------
   Function: doAjax
   Check if a specific tag exist in the XML. If exist return the text
   
   Arguments:
   url - what ajax code to call
   callback - What function to return to
--------------------------------------------------------------    
  Revision History: 
  - NEW 2008-02-08 tlin2: Initial version. 
------------------------------------------------------------*/ 
function doAjax(url, callback) {
  loader = new net.ContentLoader(url,callback);
}
/*------------------------------------------------------------
   Function: commonAjaxResp
   Common ajax response
   
   Arguments:
   url - what ajax code to call
   callback - What function to return to
--------------------------------------------------------------    
  Revision History: 
  - NEW 2008-02-08 tlin2: Initial version. 
------------------------------------------------------------*/ 
function commonAjaxResponse() {
	debug( this.req.responseText);
}
/*------------------------------------------------------------
   Function: getIfExist
   Check if a specific tag exist in the XML. If exist return the text
   
   Arguments:
   resultXML - xml object
   tag - name of tag to check
   num - What number of a specific tag to return
--------------------------------------------------------------    
  Revision History: 
  - NEW 2007-03-15 tlin2: Initial version. 
------------------------------------------------------------*/ 
function getIfExist(resultXML,tag,num)
{

	var aValue= '';
	try {
	 	aValue = resultXML.getElementsByTagName(tag)[num].firstChild.nodeValue ;
	 	//return extremTrim(aValue);
	 	return aValue;
	} catch(ex) {
		debug("getifExist ERRROR + " + ex);
		return "";
 	}
 
}
/*------------------------------------------------------------
   Function: getAttIfExist
   Check if a specific tag exist in the XML. If exist return a attribute
   
   Arguments:
   resultXML - xml object
   tag - name of tag to check
   att - Attribute name
   num - What number of a specific tag to return
--------------------------------------------------------------    
  Revision History: 
  - NEW 2008-02-14 tlin2: Initial version. 
------------------------------------------------------------*/ 
function getAttIfExist(element,att,num)
{
	var attribute= '';
	try {
	 	attribute = element.getAttribute(att);
	 	return attribute;
	} catch(ex) {
		debug("ERRORRRRRRRRR");
		return "";
 	}
 
}
/*------------------------------------------------------------
   Function: extremTrim
   Trim all values not listed i function
   
   Arguments:
   aValue - a string
--------------------------------------------------------------    
  Revision History: 
  - NEW 2007-03-15 tlin2: Initial version. 
------------------------------------------------------------*/ 
function extremTrim(aValue) {
	var eValue="";
	var checkstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
	for(i=0;i<aValue.length;i++) {
		if (checkstr.indexOf(aValue.substr(i,1))!=-1) eValue += aValue.substr(i,1);
	}
	return eValue;
}
/*------------------------------------------------------------
   Function: ajaxGenResponse
   Generic response for all the ajax calls

--------------------------------------------------------------    
  Revision History: 
  - NEW 2007-03-15 tlin2: Initial version. 
------------------------------------------------------------*/ 

function ajaxGenResponse() { 
	try{
		var res = resultXML.getElementsByTagName('resultBool')[0].firstChild.nodeValue ;
	} catch(ex) {
		return false;
	}
	var resCode = '';
	var resText = '';
	if(res!="true") {
		//var resCode = resultXML.getElementsByTagName('resultCode')[0].firstChild.nodeValue ;
		resCode = getIfExist(resultXML, 'resultCode',0);		
		resText = getIfExist(resultXML, 'resultText',0);		
		//alert(resCode + resText);
	} 
	if(GnextCallFunc != ""){
		//debug("res=" + res + " GnextCallFuncParam=" + GnextCallFuncParam + " resCode=" + resCode + " resText=" + resText);
		 GnextCallFunc(GFromFunc, res, GnextCallFuncParam, resCode, resText);
	}
} 
/*------------------------------------------------------------
   Function: loadXMLDoc
   makes a ajax call 

--------------------------------------------------------------    
  Revision History: 
  - NEW 2007-03-15 tlin2: Initial version. 
------------------------------------------------------------*/ 
function loadXMLDoc(url, callFunc, ignoreWhite, fromFunc, nextCallFunc, nextCallFuncParam) {
	GCallBack = false;
	GFromFunc				= fromFunc;
	GnextCallFunc 			= nextCallFunc;
	GnextCallFuncParam 	= nextCallFuncParam;
	stripWS 					= ignoreWhite;
	//debug("fromFunc=" + fromFunc +  " nextCallFunc=" + nextCallFunc + " nextCallFuncParam=" + nextCallFuncParam)
	
	xmlRequestObj = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
	
	if(callFunc != undefined ) {
		functionToCall 		= callFunc;
		xmlRequestObj.onreadystatechange = proccessXML;
		GCallBack = true;
	}
	
	var sendStr = "";
	var urlS= url.split('&');
	for(i=0;i<urlS.length;i++) {
		if(i==0) {
			url = urlS[i];
		} else {
			sendStr += '&' + urlS[i];
		}
	}
	xmlRequestObj.open("POST", url, true);
	xmlRequestObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded") ;
	xmlRequestObj.send(sendStr);
}


// private

function is_ws(nod) {
	return !(/[^\t\n\r ]/.test(nod.data));
}

function findWhiteSpace(node, nodeNo) {
	for (i=0; i<node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType == 3 && is_ws(node.childNodes[i])) {
			nodesToDelete[nodesToDelete.length] = node.childNodes[i]
		}
		if (node.childNodes[i].hasChildNodes()) {
			findWhiteSpace(node.childNodes[i], i);
		}
	}
	node = node.parentNode;
	i = nodeNo;
}

function stripWhiteSpace(node) {
	nodesToDelete = Array();
	findWhiteSpace(node, 0);
	for(i=nodesToDelete.length-1;i>=0;i--) {
		nodeRef = nodesToDelete[i];
		nodeRef.parentNode.removeChild(nodeRef)
	}
}

function proccessXML() {
	if (xmlRequestObj.readyState == 4 && (xmlRequestObj.status == 200 || xmlRequestObj.status == 304)) {
		if(stripWS) {
			stripWhiteSpace(xmlRequestObj.responseXML);
		}
		
		resultXML = xmlRequestObj.responseXML;
		if(GCallBack) functionToCall()
	}
}
//------------------------------------------------------------------
//   executeAjax
//------------------------------------------------------------------
function executeAjax(callback, url, param) {
		//debug("executeAjax " + callback + "-->" + url + "-->" + param);
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
    		req = new XMLHttpRequest();
    		if(GCallBack) req.onreadystatechange = callback;
    		req.open("POST", url, true);
    		req.send(null);
  	} // branch for IE/Windows ActiveX version
  	else if (window.ActiveXObject) {
    		req = new ActiveXObject("Microsoft.XMLHTTP");
    		if (req) {
      			if(GCallBack) req.onreadystatechange = callback;
	      		req.open("POST", url, true);
      			req.send();
    		}
  	}
}
