//************ Pool Stuff ************************
var msxmlNames = ['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
function XHRPool(){
	this.pool = [];
	this.maxSize = 5;

	this.init = function (){
		for(var i =0 ;i< this.maxSize ;i++){
			this.pool.push(this.makeNewXHR());
		}
		
	}

	 this.makeNewXHR=function(){
		 try {
			return new XMLHttpRequest();
	    } catch(e) {}
	    for (var i=0;i < msxmlNames.length; i++) {
			try {
				return new ActiveXObject(msxmlNames[i]);
			} catch (e) {}
		}
	}

	this.getXHR=function(){
		if(this.pool.length > 0){
			return this.pool.pop();
		}
		else{
			return this.makeNewXHR();
		}

	}

	this.returnXHR=function(xhr){
		if(this.pool.length >= this.maxSize){
		
			delete xhr;
		}
		else{
		
			this.pool.push(xhr);
//			this.pool.reverse();
		}
				
	}
}

//*********** End Pool Stuff *************************
var xhrPool = new XHRPool();
xhrPool.init();

//************** Utility functions *******************
function abort(){
	//httpr.abort();
}

function urlEncode(queryString) {
    s = queryString;
    s = s.replace(/amp;/g, "*am*")
    s = s.replace(/&/g, "*am*");
    s = s.replace(/=/g, "*eq*");
    s = s.replace(/\+/g, "*pl*");
    s = s.replace(/\%/g, "*pg*");
    return s;
}

function urlDecode(queryString) {
    s = queryString;
    s = s.replace("*am*", /&/g);
    s = s.replace("*eq*", /=/g);
    s = s.replace("*pl*", /\+/g);
    s = s.replace("*pl*", /\+/g);
    s = s.replace("&lt;", '<');
    s = s.replace("&gt;", '>');
    return s;
}
// ************* End Utiliy functions ****************

// ************* Ajax Functions **********************
var ERROR_AJAX_DISCONNECTION_MSG = "Experiencing problems connecting to the Postalz Server,please retry the last action(if any).";
var ERROR_AJAX_SERVER_UNAVAILABLE_MSG = "Could not connect to the Postalz Server, please reload the page";
var ERROR_AJAX_SERVER_ERROR_MSG = "The server encountered an unexpected error ... we have recorded this error and shall fix this soon.Please try viewing another card.";
var ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG = "Oops we could not load this data from the server ... we have recorded this error and shall fix this soon.Please try viewing another card.";
var ERROR_AJAX_UNKNOWN_ERROR_MSG = "The server encountered an unexpected error ... we have recorded this error and shall fix this soon.Please try viewing another card.";

var DEBUG_ERROR_AJAX_DISCONNECTION_MSG = "Internet Connection issues , slow connection or packet drops";
var DEBUG_ERROR_AJAX_SERVER_UNAVAILABLE_MSG = "Server closed connection - check for server outage";
var DEBUG_ERROR_AJAX_SERVER_ERROR_MSG = "Exception in JSP code";
var DEBUG_ERROR_AJAX_UNKNOWN_ERROR_MSG = "Unknown status code ";
var DEBUG_ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG = "Page not found";

// Default function when no post Ajax callback function is specified
function noPostAjaxCallBack() {
    //return ajaxResponse;
}


function clearAjaxResponse() {
    ajaxResponse = "";
}

function log(logMsg) {
	// If there is an error abt logAjax.js then we dont do anything
	// or else its an infinite loop
	if(logMsg.indexOf("logAjax.jsp")< -1){
		postData("/jsp/zimo/logAjax.jsp","logMsg=" + logMsg,null,true);
	}

}
function ajaxErrors(pMsg){
	
	if(Dialog != null){
		var dlgId = "err "+new Date().getTime();
		var xx = Dialog.info(pMsg, {className: "alphacube", showProgress: false,width:500,height:100,id:dlgId});
		 setTimeout(function(){ closeAjaxInfo(dlgId)},3000);
	}
	else{
		alert(pMsg);
		closeAjaxInfo();
	}

}

function closeAjaxInfo(pDlgId){
	Windows.close(pDlgId);
	cleanup();
}
// ************* End Ajax Functions ******************

// ************* Client functions ********************

function fetchData(targetUrl, callbackFn, async) {
	try{
		var postAjax = function() {	};

		var httpr=xhrPool.getXHR();

		if (callbackFn == null) {
			postAjax = noPostAjaxCallBack;
		}
		else {
			postAjax = callbackFn;
		}
		
		if (async == null) {
			async = true;
		}
		//async=true;
		async=true; //Should never be synchronous!!!! Put this here to override a sync call
		if(httpr!=null) {
			// Make each req a new 1
			// Ajax request get cached by IE
			var ajaxianDate = new Date();
			var ajaxianTime = ajaxianDate.getTime();
			var noCacheStr = "&nocache=" + ajaxianTime;
			if ((targetUrl.indexOf("?")) == -1) {
				noCacheStr = "?nocache=" + ajaxianTime+"&user=guest";
			}
			
			httpr.open('GET', targetUrl + noCacheStr, async);
			
			
			if(httpr.overrideMimeType)
			{httpr.overrideMimeType("text/plain; charset=ISO-8859-1");}
//			if(callbackFn != null){
				httpr.onreadystatechange = function() {
					if (httpr.readyState == 4) {
						var status = 0;
						try
						{
							status = httpr.status;
						}
						catch (e)
						{
							log(targetUrl + " - " + e);
						}
						if (status == 200) {
							var data = httpr.responseText;

							if (data.indexOf("Exception Information") > -1) {
							 ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
							 // If there is an exception in logAjax.jsp - then it leads to a loop
								 if(targetUrl.indexOf("logAjax.jsp") < 0){
									log(targetUrl + " - " + DEBUG_ERROR_AJAX_SERVER_ERROR_MSG + " - "+data.trim());
								}
							 }
							else {
								 
								 postAjax(data);
							     xhrPool.returnXHR(httpr);
							}
						}
						else if(status == 404){ // page not found
							ajaxErrors(ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG);
							log(targetUrl + " - " + DEBUG_ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG + " - " +httpr.responseText);
//							xhrPool.returnXHR(httpr);
						}
						else if((status == 12030)||(status == 12031)||(status == 12029)){ // disocnnection error
							ajaxErrors(ERROR_AJAX_DISCONNECTION_MSG);
//							xhrPool.returnXHR(httpr);
						}
						else if(status == 12152){ // connection closed by server
							ajaxErrors(ERROR_AJAX_SERVER_UNAVAILABLE_MSG);
							log(targetUrl + " - " + DrrEBUG_ERROR_AJAX_SERVER_UNAVAILABLE_MSG + " - " +httpr.responseText);
//							xhrPool.returnXHR(httpr);
						}
						else {
							 //ajaxErrors(ERROR_AJAX_UNKNOWN_ERROR_MSG);
							 
							 log(targetUrl +" - "+ DEBUG_ERROR_AJAX_UNKNOWN_ERROR_MSG +", status = "+status +" - " + httpr.responseText);
// 							xhrPool.returnXHR(httpr);
						}
					}// if ready state
				}//ready state change function defn
//			}//if cb not null
/*			else{
				httpr.onreadystatechange = function() { xhrPool.returnXHR(httpr);};
			}*/
			httpr.send(null);
		}
		else {
		//	ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
			log(targetUrl +" - " +"httpr is null in fetchData");
		}
	}catch(ex1){
			log("fetchData  -" + targetUrl+" - "+ ex1);
	}
}

function postData(targetUrl, data, callbackFn, async) {
	try{
		var postAjax = function() {	};

		var httpr=xhrPool.getXHR();
		
		if (callbackFn == null) {
			postAjax = noPostAjaxCallBack;
		}
		else {
			postAjax = callbackFn;
		}
		
		if (async == null) {
			async = true;
		}
		//async=true;
		async=true; //Should never be synchronous!!!! Put this here to override a sync call
		if(httpr!=null) {
			// Make each req a new 1
			// Ajax request get cached by IE
			var ajaxianDate = new Date();
			var ajaxianTime = ajaxianDate.getTime();
			var noCacheStr = "&nocache=" + ajaxianTime;
			if ((targetUrl.indexOf("?")) == -1) {
				noCacheStr = "?nocache=" + ajaxianTime+"&user=guest";
			}
			
			httpr.open('POST', targetUrl + noCacheStr, async);
			
			
			if(httpr.overrideMimeType)
			{httpr.overrideMimeType("text/plain; charset=ISO-8859-1");}
				httpr.onreadystatechange = function() {
				//processData();
					if (httpr.readyState == 4) {
						var status = 0;
						try
						{
							status = httpr.status;
						}
						catch (e)
						{
							log(targetUrl + " - " + e);
						}
						if (status == 200) {
							var data = httpr.responseText;
							if (data.indexOf("Exception Information") > -1) {
							 ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
							 // If there is an exception in logAjax.jsp - then it leads to a loop
								 if(targetUrl.indexOf("logAjax.jsp") < 0){
									log(targetUrl + " - " + DEBUG_ERROR_AJAX_SERVER_ERROR_MSG + " - "+data.trim());
								}
							 }
							else {
								 //ajaxResponse = data;
								 
								 postAjax(data);
	 							xhrPool.returnXHR(httpr);
							}
						}
						else if(status == 404){ // page not found
							ajaxErrors(ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG);
							log(targetUrl + " - " + DEBUG_ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG + " - " +httpr.responseText);
						//	xhrPool.returnXHR(httpr);
						}
						else if((status == 12030)||(status == 12031)||(status == 12029)){ // disocnnection error
							ajaxErrors(ERROR_AJAX_DISCONNECTION_MSG);
						//	xhrPool.returnXHR(httpr);
						}
						else if(status == 12152){ // connection closed by server
							ajaxErrors(ERROR_AJAX_SERVER_UNAVAILABLE_MSG);
							log(targetUrl + " - " + DEBUG_ERROR_AJAX_SERVER_UNAVAILABLE_MSG + " - " +httpr.responseText);
						//	xhrPool.returnXHR(httpr);
						}
						else {
							 //ajaxErrors(ERROR_AJAX_UNKNOWN_ERROR_MSG);
							 
							 log(targetUrl +" - "+ DEBUG_ERROR_AJAX_UNKNOWN_ERROR_MSG +", status = "+status +" - " + httpr.responseText);
 						//	xhrPool.returnXHR(httpr);
						}
					}// if ready state
				}//ready state change function defn
			
			httpr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpr.setRequestHeader("Content-length", data.length);
			httpr.setRequestHeader("Connection", "close");
			httpr.send(data);
		}
		else {
//			ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
			log(targetUrl +" - " +"httpr is null in fetchData");
		}
	}catch(ex1){
			alert("postData  -" +targetUrl + " - " + ex1 );
	}
}

var cacheRegistryKeys = new Array();
var cacheRegistryValues = new Array();

function dataInCache(pTargetUrl){
	// Check if data in cacheRegistry
		var regKeySize = cacheRegistryKeys.length;
		var foundInRegistry = false;
		for(var iCtr=0;iCtr<regKeySize;iCtr=iCtr+1){
			if(cacheRegistryKeys[iCtr] == pTargetUrl){
				foundInRegistry = true;
				break;
			}
		}
		if(foundInRegistry){
			return (cacheRegistryValues[iCtr]);
		}
		else{
			return null;
		}
}

function fetchDataCached(targetUrl, callbackFn, async) {
	try{
		var postAjax = function() {	};

		
		
		if (callbackFn == null) {
			postAjax = noPostAjaxCallBack;
		}
		else {
			postAjax = callbackFn;
		}
	
		if (async == null) {
			async = true;
		}
		//async=true;
		async=true; //Should never be synchronous!!!! Put this here to override a sync call

		var httpr=xhrPool.getXHR();
		if(httpr!=null) {
			// Make each req a new 1
			httpr.open('GET', targetUrl , async);
			
			if(httpr.overrideMimeType)
			{httpr.overrideMimeType("text/plain; charset=ISO-8859-1");}
			
				httpr.onreadystatechange = function() {
				//processData();
					if (httpr.readyState == 4) {
						var status = 0;
						try
						{
							status = httpr.status;
						}
						catch (e)
						{
							log(targetUrl + " - " + e);
						}
						if (status == 200) {
							var data = httpr.responseText;
						//	xhrPool.returnXHR(httpr);
							if (data.indexOf("Exception Information") > -1) {
							 ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
							 // If there is an exception in logAjax.jsp - then it leads to a loop
								 if(targetUrl.indexOf("logAjax.jsp") < 0){
									log(targetUrl + " - " + DEBUG_ERROR_AJAX_SERVER_ERROR_MSG + " - "+data.trim());
								}
							 }
							else {
								 //ajaxResponse = data;
								 //Add data to cache registry
								 
								cacheRegistryKeys.push(targetUrl);
								cacheRegistryValues.push(data);
								 postAjax(data);
	 							xhrPool.returnXHR(httpr);
							}
						}
						else if(status == 404){ // page not found
							ajaxErrors(ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG);
							log(targetUrl + " - " + DEBUG_ERROR_AJAX_DATA_NOT_FOUND_ERROR_MSG + " - " +httpr.responseText);
						//	xhrPool.returnXHR(httpr);
						}
						else if((status == 12030)||(status == 12031)||(status == 12029)){ // disocnnection error
							ajaxErrors(ERROR_AJAX_DISCONNECTION_MSG);
						//	xhrPool.returnXHR(httpr);
						}
						else if(status == 12152){ // connection closed by server
							ajaxErrors(ERROR_AJAX_SERVER_UNAVAILABLE_MSG);
							log(targetUrl + " - " + DEBUG_ERROR_AJAX_SERVER_UNAVAILABLE_MSG + " - " +httpr.responseText);
						//	xhrPool.returnXHR(httpr);
						}
						else {
							  
							 //ajaxErrors(ERROR_AJAX_UNKNOWN_ERROR_MSG);
							 log(targetUrl +" - "+ DEBUG_ERROR_AJAX_UNKNOWN_ERROR_MSG +", status = "+status +" - " + httpr.responseText);
 						//	xhrPool.returnXHR(httpr);
						}
					}// if ready state
				}//ready state change function defn
		
				httpr.send(null);
			
		}
		else {
	//		ajaxErrors(ERROR_AJAX_SERVER_ERROR_MSG);
			log(targetUrl +" - " +"httpr is null in fetchData");
		}
	}catch(ex1){
			alert("fetchDataCached -"+targetUrl +" - "+ex1);
	}
}


// ************* End Client functions ****************

























