var _ajxBusy = false;
var _abortTimeout = 0;
//var _abortTimeout2 = 0;
var ajXRqst = null;

function createXMLHTTP()
{
	if (ajXRqst == null)
	{
		try { ajXRqst =  new ActiveXObject("Msxml2.XMLHTTP.6.0"); return ajXRqst; } catch(e) {}
		try { ajXRqst =  new ActiveXObject("Msxml2.XMLHTTP.3.0"); return ajXRqst; } catch(e) {}
		try { ajXRqst =  new ActiveXObject("Msxml2.XMLHTTP"); return ajXRqst; } catch(e) {}
		try { ajXRqst =  new ActiveXObject("Microsoft.XMLHTTP"); return ajXRqst; } catch(e) {}
		return false;
	}
	
	return ajXRqst;
}

// if animate is passed and is NOT NULL, loading will be shown (default behaviour)
// if noerror is passed and is NOT NULL, alter will be shown (default behaviour)
function requestXmlHttp(url, id, frm, animate, noerror)
{
	if (_ajxBusy)
	{
		t = setTimeout(function() {requestXmlHttp(url, id, frm);},100);
		return false;
	}
	
	rid = http_request.length;
	http_reqids[rid] = id;

	var str = "";
	var urlFields = url.split("?");
	if(urlFields.length > 0)
		str = urlFields[1] + "&";
	
	if(frm)
		str += getParameterString(frm);
	
	
	// To avoid cache problem
	str += "r=" + Math.random();
	str += "&DIV_ID=" + id;
	url = urlFields[0];

    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest)
	{
        http_request[rid] = new XMLHttpRequest();
		if (http_request[rid].overrideMimeType) 
			http_request[rid].overrideMimeType('text/xml'); 
    }
	else if (window.ActiveXObject)	// branch for IE/Windows ActiveX version
	{
        _isWModIE = true;
        http_request[rid] = createXMLHTTP();
	}
	
	if(http_request[rid])
	{
		if (animate == null && typeof statusBarLoad == "function")
			statusBarLoad();
		_ajxBusy = true;
		//statusBarLoad();
		http_request[rid].open("POST", "wdg.php?" + url, true);
		http_request[rid].onreadystatechange = function() { processReqChange(id); };
		
		// Set Header with each word started with capital letters because MAC converts it to such and other browsers send as is
		// certain languages need this
		http_request[rid].setRequestHeader("hl_i-Header", "request");
		// these two are set so that server knows which items requested xml
		
		http_request[rid].setRequestHeader("hl_i-Fid", rid);
		
		//  DONOT change the next statement else POST WON'T Work
		http_request[rid].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//_httpReqMod.setRequestHeader("Content-length", str.length);
		http_request[rid].setRequestHeader("Connection", "close");
		
		http_request[rid].send(str);
		_abortTimeout = setTimeout(function(animate, noerror)
		{ 
			if (http_request[rid].readyState > 2)
			{
				if (animate == null && typeof statusBarPrgUpdate == "function")
					statusBarPrgUpdate();
				return true;
			}
			
			http_request[rid] = null;
			_ajxBusy = false;
			if (noerror == null)
				alert("The service is temporarily unavailable. Please try again.");
			if (animate == null && typeof statusBarUnload == "function")
				statusBarUnload(); 
		}, 20*1000);
		
		/*_abortTimeout2 = setTimeout(function()
		{
			_abortTimeout2 = 0;
			if (http_request[rid].readyState == 1)
				return true;
		}, 2000);*/
	}
	else
	{
		if (noerror == null)
			loadModuleHandler("The requested operation failed. Please try again", id);
	}
	return true;
}

/* url passed to this function will be called without any modifications */
function requestXmlHttp2(url, id, frm, animate, noerror)
{
	if (_ajxBusy)
	{
		t = setTimeout(function() {requestXmlHttp2(url, id, frm);},100);
		return false;
	}
	
	rid = http_request.length;
	http_reqids[rid] = id;

	var str = "";

	if(frm)
		str += getParameterString(frm);
	
	
	// To avoid cache problem
	str += "r=" + Math.random();
	str += "&DIV_ID=" + id;

    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest)
	{
        http_request[rid] = new XMLHttpRequest();
		if (http_request[rid].overrideMimeType) 
			http_request[rid].overrideMimeType('text/xml'); 
    }
	else if (window.ActiveXObject)	// branch for IE/Windows ActiveX version
	{
        _isWModIE = true;
        http_request[rid] = createXMLHTTP();
	}
	
	if(http_request[rid])
	{
		if (animate == null && typeof statusBarLoad == "function")
			statusBarLoad();
		_ajxBusy = true;
		//statusBarLoad();
		alert(url);
		http_request[rid].open("POST", url, true);
		http_request[rid].onreadystatechange = function() { processReqChange(id); };
		
		// Set Header with each word started with capital letters because MAC converts it to such and other browsers send as is
		// certain languages need this
		http_request[rid].setRequestHeader("hl_i-Header", "request");
		// these two are set so that server knows which items requested xml
		
		http_request[rid].setRequestHeader("hl_i-Fid", rid);
		
		//  DONOT change the next statement else POST WON'T Work
		http_request[rid].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//_httpReqMod.setRequestHeader("Content-length", str.length);
		http_request[rid].setRequestHeader("Connection", "close");
		
		http_request[rid].send(str);
		_abortTimeout = setTimeout(function(animate, noerror)
		{ 
			if (http_request[rid].readyState > 2)
			{
				if (animate == null && typeof statusBarPrgUpdate == "function")
					statusBarPrgUpdate();
				return true;
			}
			
			http_request[rid] = null;
			_ajxBusy = false;
			if (noerror == null)
				alert("The service is temporarily unavailable. Please try again.");
			if (animate == null && typeof statusBarUnload == "function")
				statusBarUnload(); 
		}, 20*1000);
		
		/*_abortTimeout2 = setTimeout(function()
		{
			_abortTimeout2 = 0;
			if (http_request[rid].readyState == 1)
				return true;
		}, 2000);*/
	}
	else
	{
		if (noerror == null)
			loadModuleHandler("The requested operation failed. Please try again", id);
	}
	return true;
}

function processReqChange(id)
{
	hr = null;
	for(i=http_reqids.length-1; i>= 0; i--)
	{
		if (http_reqids[i] == id)
		{
			hr = http_request[i];
			break;
		}
	}
	
	if (hr && hr.readyState == 4)
	{
		//clearTimeout(_abortTimeout2);
		clearTimeout(_abortTimeout);
		_ajxBusy = false;
        if (hr.status == 200)
		{
			if (hr.getResponseHeader('content-type').indexOf("XML") != -1 || hr.getResponseHeader('content-type').indexOf("xml") != -1)
			{
				var xml = hr.responseXML;
				
				if (xml.getElementsByTagName("SCRIPTFILES")[0])
					for(iloop = xml.getElementsByTagName("SCRIPTFILES").length-1; iloop>=0; iloop--)
						dynRequestExec(xml.getElementsByTagName("SCRIPTFILES")[iloop].firstChild.nodeValue, i, id);
				else
					loadContantsScript(i, id);
			}
			else
				loadModuleHandler(hr.responseText, id); 
		}
		else
		{
			alert("!! The service is temporarily unavailable.\nErrorcode "+hr.status+"\n"+hr.responseText, id);
			if (typeof statusBarUnload == "function")
				statusBarUnload();
		}
		
	}
}

function requestDynForm(frm, divid)
{
	if(divid == null)
	{
		if(document.getElementById(frm).div != null)
			divid = document.getElementById(frm).div.value;
		else
			divid = "screenContent";
	}
	
	requestXmlHttp('', divid, frm);
}


function loadContantsScript(requestId, id)
{
	hr = http_request[requestId];
	if(hr)
	{
		var xml = hr.responseXML;
		if (xml.getElementsByTagName("DIVID")[0])
			id = xml.getElementsByTagName("DIVID")[0].firstChild.nodeValue;
		else
			id = 'WDG_MAIN'; // the default place to show the screen
		
		if (xml.getElementsByTagName("CONTENTS")[0])
			loadModuleHandler(unescape(xml.getElementsByTagName("CONTENTS")[0].firstChild.nodeValue), id);
		if (xml.getElementsByTagName("SCRIPT")[0])
			loadScriptHandler(xml.getElementsByTagName("SCRIPT")[0].firstChild.nodeValue);
	}
	delete(hr);
	//statusBarUnload();
}

function loadScriptHandler(scriptText)
{
	if(scriptText != "")
	{
		var html_doc = document.getElementsByTagName('head').item(0);
		if(document.getElementById('mainscripttag'))
			html_doc.removeChild(document.getElementById('mainscripttag'));
		
		scriptTag = document.createElement("SCRIPT");
		scriptTag.text = scriptText;
		scriptTag.defer = true;
		scriptTag.id = 'mainscripttag';
		html_doc.appendChild(scriptTag);
	}
}

// User information module 
function loadModuleHandler(text, id)
{
	if (typeof statusBarUnload == "function")
		statusBarUnload();
	
	if (id == "WDG_NONE") // means that we donot have to show the output of this div
		return;
	
	divId = document.getElementById(id);
	

	if (divId)
		divId.innerHTML = text;
	else
		alert("The page failed to load due to technical issues.\nPlease report this problem and we will try to fix it as soon as possible.");
	divId.style.display = "block";
}

// This function will generate a string from all the form variables 
function getParameterString(frm)
{
	tfrm = document.getElementById(frm);
	var str = "";
	var count = tfrm.elements.length;
	
	for (var iLoop = 0; iLoop < count; iLoop++)
	{
		elementName = tfrm.elements[iLoop].name;
		// send value of items check box or radio if selected
		if ((tfrm.elements[iLoop].type == "radio") || (tfrm.elements[iLoop].type == "checkbox"))
			if (!tfrm.elements[iLoop].checked)
				continue;
		
		
		if ((tfrm.elements[iLoop].type == "button") || (tfrm.elements[iLoop].type == "submit"))	
			elementValue = document.getElementById("selected_"+ frm +"_" + elementName).value;
		else
			elementValue = tfrm.elements[iLoop].value;
		
		if(elementValue == "")
			continue;	
		
		str += elementName + "=" + encodeURLString(elementValue) + "&" ;
	}
	
	return str;
}

function encodeURLString(str) 
{
	return escape(str).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
}

var http_request = new Array();
var http_reqids = new Array();
var _isWModIE = false;

var jsLodingCount = 0;
function dynRequestExec(url, requestId, id)
{
	var jsId = 'jsInclude_'+ url.replace(".", "");
	
	var html_doc = document.getElementsByTagName('head').item(0); 
	if(document.getElementById(jsId))
		html_doc.removeChild(document.getElementById(jsId));
	
    var js = document.createElement('script'); 
    js.language = 'javascript'; 
    js.type ='text/javascript'; 
    js.src =  url; 
	js.id = jsId;
    js.defer = true; 
	
	if(id != "")
	{		
		if(++jsLodingCount < 1)
			jsLodingCount = 1;
		if(document.all)
		{
			if(js.readyState)
			{
				js.onreadystatechange = function(){if(js.readyState == "loaded" || js.readyState == "complete"){if(--jsLodingCount==0){loadContantsScript(requestId, id);}}};
				html_doc.appendChild(js);
			}
			else
			{
				html_doc.appendChild(js);
				if(--jsLodingCount==0){loadContantsScript(requestId, id);};
			}
		}
		else
		{
			js.onload = function(){if(--jsLodingCount==0){loadContantsScript(requestId, id);}};
			html_doc.appendChild(js);
		}
	}
	else
		html_doc.appendChild(js);
}