﻿//<!--
/************
This file is part of Genwi JS Lib.
All Rights Reserved.

Desc: AJAX lib.
      Ajax object creates the request and process response.
      Returns a Response Object to call back listner(s).

Sample Use: 
var oAjax = new Ajax('req name', 'req url', 'req method', 'array of listners');
oAjax.setListner('callBackFunction');

callBackFunction will be called after response is received
and process.

************/

var oXmlHttp = null, bReqInProg = false;

function Ajax (pName, pUrl, pIsGet, pListners)
{
	this.name = pName;
	this.sUrl = pUrl;
	this.sMethod = pIsGet ? "GET" : "POST";
	this.sPostData = null;
	this.bShowProgress = false;
	this.sShowProgressId = null;
	this.sProgressHtml = '<img src="' + _GL.getBaseUrl() + 'images/loader_small.gif" border="0" />';
	this.bAsync = true;
	this.iResponseType = 0;
	this.bResponseReady = false;
	this.aListners = pListners;

	this.RESPONSE_JS = 0;
	this.RESPONSE_HTML = 1;
	this.RESPONSE_TEXT = 2;
	this.RESPONSE_JSON = 3;
	
	this.setListner = function(pCallback)
	{
		this.aListners[this.aListners.length] = pCallback;
	}

    this.showProgress = function(pShow)
    {
        var e = _GL.getUIElem(this.sShowProgressId);
        if (e)
            e.innerHTML = pShow ? this.sProgressHtml : '';
    }
    
	this.send = function()
	{
		if (typeof(window.XMLHttpRequest) != "undefined")
			oXmlHttp = new XMLHttpRequest();
		else if (typeof(ActiveXObject) != "undefined")
		{
			var lib = "Microsoft.XMLHTTP";
			oXmlHttp = new ActiveXObject(lib);
		}
		else
		{
			alert("XML HTTP not supported");
			return;
		}

        if (this.bShowProgress)
            this.showProgress(true);
            
		oXmlHttp.open(this.sMethod, this.sUrl, this.bAsync);
		if (this.sMethod == 'POST')
			oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		
		var req = this;
		oXmlHttp.onreadystatechange = function ()
		{
			req.processResquest(oXmlHttp);
		}
		
		oXmlHttp.send(this.sPostData);
	}

	this.processResquest = function(pHttp)
	{
		if (pHttp.readyState == 4) 
		{
			//status 200 = OK
			if (this.bShowProgress)
                this.showProgress(false);
           
            this.bShowProgress = false;
            this.sShowProgressId = null;

			var st = pHttp.status;
			if (st == 200) 
			{
				var oResp = new AjaxResponse(this);
				oResp.sResponseText = "" + pHttp.responseText;
				oResp.oResponseXml = pHttp.responseXML;
				oResp.sHeaderText = "" + pHttp.getAllResponseHeaders();
				oResp.process();
				oResp.notify();
			}
			else
			{
				var msg = "Error: " + pHttp.statusText;
				
				if (st == 404)
					msg = "Invalid URL: '" + this.sUrl + "' [System Error: " +  pHttp.statusText + "]";
			
				alert(msg);
			}
			pHttp = null;
			oXmlHTTP = null;
			bReqInprogress = false;
		}
	}
}

function AjaxResponse (pParent)
{
	this.parent = pParent;
	this.sResponseText = null;
	this.oResponseXml = null;
	this.sHeaderText = null;
	this.oData = null;
	this.oJSON = null

	this.process = function()
	{
		var s = this.sResponseText, p = this.parent;
		if (s.length > 0)
		{
		    if (p.iResponseType == p.RESPONSE_JSON)
			{
				try
				{
					this.oJSON = eval('(' + s + ')');
				}
				catch(e)
				{ //Exception for malformed response.
				}
			}
			
			if (p.iResponseType == p.RESPONSE_JS)
				eval(s);
			
			if (s.hasAny("<html", "<body", "<script", "<?xml "))
				p.iResponseType = p.RESPONSE_HTML;
				
			p.bResponseReady = true;
		}
		//else
			//alert("Empty response")
			
	}

	this.notify = function()
	{
		var p = this.parent, aL = p.aListners, l = aL.length;
		for (var i=0; i<l; i++)
		    eval(aL[i] + '(this)');
	}
}

function XmlHelper()
{
    // Xml helpers
	this.getValue = function (pXml, pXPath)
	{
		var aX = pXPath.split('/');
		var nd = this.getNodeByXpath(pXml, pXPath),rv;
		rv = nd ? this.getNodeValue(nd) : '';
		return rv;
	}
	
	this.getNode = function (pXml, pName, pIndex)
	{
		var nodes = pXml.getElementsByTagName(pName);
		
		if (nodes)
		{
			if (pIndex >= 0)
			{
				if (nodes.length >= pIndex)
					return nodes[pIndex];
			}
			else
			{
				if (nodes[0])
					return nodes[0];
			}
		}
		
		return null;
	}
	
	this.getNodes = function (pXml, pName)
	{
		return pXml.getElementsByTagName(pName);
	}
	
	this.getNodeByXpath = function (pXml, pXPath)
	{
		var aX = pXPath.split('/');
		
		var nd = null, idx, nm = '';
		for (var i=0; i<aX.length; i++)
		{
			idx = 0;
			nm = aX[i];
			if (nm.indexOf(']') == nm.length - 1)
			{
				idx = nm.substr(nm.indexOf('[')+1, nm.indexOf(']')- nm.indexOf('[')-1);
				nm = nm.substr(0, nm.indexOf('['));
			}
			nd = this.getNode( (nd == null)?pXml:nd, nm, parseInt(idx));
			if (nd == null)
				break;
		}
		
		return nd;
	}
	
	this.getNodeValue = function (pNode)
	{
		var rv, pn = pNode;
		if (pn.childNodes.length > 1)
			rv = pn.childNodes[1].nodeValue;
		else
			rv = pn.firstChild ? pn.firstChild.nodeValue : null;

		return rv;
		
		// pNode.text and textContent doesn't work for safari.
		//return (typeof(pNode.text) == 'undefined')?pNode.textContent:pNode.text;
	}

	this.getAttribValue = function (pXml, pXPath, pId)
	{
		var nd = this.getNodeByXpath(pXml, pXPath);
		if (nd)
		{
			var aA = nd.attributes;
			for (var i=0; i<aA.length; i++)
			{
				if (aA[i].name == pId)
					return aA[i].value;
			}
		}
		return "";
	}

}

var oXmlHelper = new XmlHelper();

//-->