/*

			JEES PHILIP

 @fileoverview
 This JavaScript file represents the core browser-side functionality
 supplied by Taconite. In general, the tools in this file wrap an instance
 of XMLHttpRequest object and provide utility methods for gather data from
 form elements to be sent to the server as par of an Ajax request.
 */

var taconite_client_version="2.0-rc1";

/**
 Constructor for the AjaxRequest class.

 <br><br>
 Example:

 <br><br>
 var ajaxRequest = new AjaxRequest("YOUR_URL");

 @class The AjaxRequest object wraps an instance of XMLHttpRequest and provides
 facilities for setting functions that are called before a request is made
 and after a request returns. By default, AjaxRequest handles the server
 response by simply calling eval(), passing to it the responseText from
 the XMLHttpRequestObject, of course assuming that the response was
 generated by Taconite on the server side and that running eval() will
 update the web page.<br><br>Example Usage:<br><br>var ajaxRequest = new AjaxRequest("YOUR_URL");
 <br>ajaxRequest.addFormElements("form_element_id_attribute_value-or-form_dom_element");
 <br>ajaxRequest.sendRequest();

 @constructor
 @param {String} a String repesenting the URL to which the Ajax request
 will be sent.
 */
function AjaxRequest(url) {
    /** @private */
    var self = this;

    /** @private */
    var xmlHttp = createXMLHttpRequest();

    /** @private */
    var queryString = "";

    /** @private */
    var requestURL = url;

    /** @private */
    var method = "GET";

    /** @private */
    var preRequest = null;

    /** @private */
    var postRequest = null;

    /** @private */
    var debugResponse = false;

    /** @private */
    var async = true;

    /** @private errorHandler*/
    var errorHandler = null;

  /** @private closeEventFunctions name of the function which perform aftert he close event of the dispalyed poup*/

    var closeEventFunctions = null; // 05122009

	this.setCloseEventFunctions = function(functionNames) {
        closeEventFunctions = functionNames;
    }
	this.getCloseEventFunctions = function() {
        return closeEventFunctions;
    }

    /**
     Return the instance of the XMLHttpRequest object wrapped by this object.
     @return XMLHttpRequest
     */
    this.getXMLHttpRequestObject = function() {
        return xmlHttp;
    }

    /**
     Set the pre-request function. This function will be called prior to
     sending the Ajax request. The pre-request function is passed a reference
     to this object.
     @param {Function} The function to be called prior to sending the Ajax
     request. The function is passed a refernce of this object.
     */
    this.setPreRequest = function(func) {
        preRequest = func;
    }

    /**
     Set the post-request function. This function will be called after the
     response has been received and after eval() has been called using the
     XMLHttpRequest object's responseText. The post-request function is passed
     a reference to this object.
     @param {Function} The function to be called after receiving the Ajax
     response. The function is passed a refernce of this object.
     */
    this.setPostRequest = function(func) {
        postRequest = func;
    }

    /**
     Return the post request function.
     */
    this.getPostRequest = function() {
        return postRequest;
    }

    /**
     Send the Ajax request using the POST method. Use with caution -- some
     browsers do not support the POST method with the XMLHttpRequest object.
     */
    this.setUsePOST = function() {
        method = "POST";
    }

    /**
     Send the Ajax request using the GET method, where parameters are sent
     as a query string appended to the URL. This is the default behavior.
     */
    this.setUseGET = function() {
        method = "GET";
    }

    /**
     Enable client-side debugging.  The server's response will be written
     to a text area appended to the bottom of the page.  If parsing is
     performed on the client side, then the results of the parsing operations
     are shown in their own text areas.
     */
    this.setEchoDebugInfo = function() {
        debugResponse = true;
    }

    /**
     Indicate if debugging is enabled.
     @return boolean
     */
    this.isEchoDebugInfo = function() {
        return debugResponse;
    }

    /**
     Set the query string that will be sent to the server. For GET
     requests, the query string is appended to the URL. For POST
     requests, the query string is sent in the request body. This
     method is useful, for example, if you want to send an XML string
     or JSON string to the server.
     @param {String} qa, the new query string value.
     */
    this.setQueryString = function(qs) {
        queryString = qs;
    }

    /**
     Return the query string.
     @return The query string.
     */
    this.getQueryString = function() {
        return queryString;
    }

    /**
     @param {Boolean} asyncBoolean, set to true if asynchronous request, false synchronous request.
     */
    this.setAsync = function(asyncBoolean){
        async = asyncBoolean;
    }

    /**
     @param {Function} Set the error handler function that is called if the
     server's HTTP response code is something other than 200.
     */
    this.setErrorHandler = function(func){
        errorHandler = func;
    }

    /**
     Add all of the form elements under the specified form to the query
     string to be sent to the server as part of the Ajax request.
     The values are automatically encoded.
     @param form, A form DOM element, or the id attribute of the form element from
     which you wish to accumulate the form values.
     */
    this.addFormElements = function(form) {
        var formElements = new Array();
        if (form != null) {
            if (typeof form == "string") {
                var el = document.getElementById(form);
                if (el != null) {
                    formElements = el.elements;
                }
            } else {
                formElements = form.elements;
            }
        }
        var values = toQueryString(formElements);
        accumulateQueryString(values);
    }

    /** @private */
    function accumulateQueryString(newValues) {
        if(queryString == "") {
            queryString = newValues;
        }
        else {
            queryString = queryString + "&" +  newValues;
        }
    }

    /**
     Add the name/value pair to the query string.
     @param {String} name
     @param {String} value
     */
    this.addNameValuePair = function(name, value) {
        var nameValuePair = name + "=" + encodeURIComponent(value);
        accumulateQueryString(nameValuePair);
    }

    /**
     Same as addNamedFormElements, except it will filter form elements by form's id.
     For example, these are all valid uses:<br>
     <br>ajaxRequest.addNamedFormElements("form-id""element-name-1");
     <br>ajaxRequest.addNamedFormElements("form-id","element-name-1",
     "element-name-2", "element-name-3");
     */
    this.addNamedFormElementsByFormID = function() {
        var elementName = "";
        var namedElements = null;

        for(var i = 1; i < arguments.length; i++) {
            elementName = arguments[i];
            namedElements = document.getElementsByName(elementName);
            var arNamedElements = new Array();
            for(j = 0; j < namedElements.length; j++) {
                if(namedElements[j].form  && namedElements[j].form.getAttribute("id") == arguments[0]){
                    arNamedElements.push(namedElements[j]);
                }
            }
            if(arNamedElements.length > 0){
                elementValues = toQueryString(arNamedElements);
                accumulateQueryString(elementValues);
            }
        }
    }

    /**
     Add the values of the named form elements to the query string to be
     sent to the server as part of the Ajax request. This method takes any
     number of Strings representing the form elements for wish you wish to
     accumulate the values. The Strings must be the value of the element's
     name attribute.<br><br>For example, these are all valid uses:<br>
     <br>ajaxRequest.addNamedFormElements("element-name-1");
     <br>ajaxRequest.addNamedFormElements("element-name-1", "element-name-2", "element-name-3");
     */
    this.addNamedFormElements = function() {
        var elementName = "";
        var namedElements = null;

        for(var i = 0; i < arguments.length; i++) {
            elementName = arguments[i];
            namedElements = document.getElementsByName(elementName);

            elementValues = toQueryString(namedElements);

            accumulateQueryString(elementValues);
        }

    }

    /**
     Add the values of the id'd form elements to the query string to be
     sent to the server as part of the Ajax request. This method takes any
     number of Strings representing the ids of the form elements for wish you wish to
     accumulate the values. The Strings must be the value of the element's
     name attribute.<br><br>For example, these are all valid uses:<br>
     <br>ajaxRequest.addFormElementsById("element-id-1");
     <br>ajaxRequest.addFormElementsById("element-id-1", "element-id-2", "element-id-3");
     */
    this.addFormElementsById = function() {
        var id = "";
        var element = null;
        var elements = new Array();

        for(var h = 0; h < arguments.length; h++) {
            element = document.getElementById(arguments[h]);
            if(element != null) {
                elements[h] = element;
            }
        }

        elementValues = toQueryString(elements);
        accumulateQueryString(elementValues);
    }

    /**
     Send the Ajax request.
     */
    this.sendRequest = function() {
        if(preRequest) {
            preRequest(self);
        }

        var obj = this;
        if(async)
            xmlHttp.onreadystatechange = function () { handleStateChange(self) };

            if(requestURL.indexOf("?") > 0) {
                requestURL = requestURL + "&ts=" + new Date().getTime();
            }
            else {
                requestURL = requestURL + "?ts=" + new Date().getTime();
            }


            try {
                if(method == "GET") {
                    if(queryString.length > 0) {
                        requestURL = requestURL + "&" + queryString;
                    }
                    xmlHttp.open(method, requestURL, async);
                    xmlHttp.send(null);
                }
                else {
                    xmlHttp.open(method, requestURL, async);
                    //Fix a bug in Firefox when posting
                    try {
                        if (xmlHttp.overrideMimeType) {
                            xmlHttp.setRequestHeader("Connection", "close");//set header after open
                        }
                    }
                    catch(e) {
                        // Do nothing
                    }
                    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xmlHttp.send(queryString);
                }
            }
            catch(exception) {
                if(errorHandler) {
                    errorHandler(self, exception);
                }
                else {
                    throw exception;
                }
            }

            if(!async) {  //synchronous request, handle the state change
                handleStateChange(self);
            }

            if(self.isEchoDebugInfo()) {
                echoRequestParams();
            }
    }

    handleStateChange = function(ajaxRequest) {
	   if(ajaxRequest.getXMLHttpRequestObject().readyState != 4) {
            return;
        }
        if(ajaxRequest.getXMLHttpRequestObject().status != 200) {
            errorHandler(self);
            return;
        }
        try {
            var debug = ajaxRequest.isEchoDebugInfo();
            if(debug) {
                echoResponse(ajaxRequest);
            }
             //handle null responseXML
            var nodes = null;
 			if (ajaxRequest.getXMLHttpRequestObject().responseXML != null) {
                nodes = ajaxRequest.getXMLHttpRequestObject().responseXML.documentElement.childNodes;
            }
            else {
                nodes = new Array();
            }
             var parser = new XhtmlToDOMParser();
            var parseInBrowser = "";
            for(var i = 0; i < nodes.length; i++) {
                if(nodes[i].nodeType != 1 || !isTaconiteTag(nodes[i])) {
                    continue;
                }

                parser.parseXhtml(nodes[i]);
            }
        }
        catch(exception) {
            if(errorHandler) {

                errorHandler(self, exception);
            }
            else {
                throw exception;
            }
        }
        finally {
            try {
                if(ajaxRequest.getPostRequest()) {
                    var f = ajaxRequest.getPostRequest();
 					f(ajaxRequest);
                }
            }
            catch(exception) {
                if(errorHandler) {
                    errorHandler(self, exception);
                }
            }
        }
    }

    /** @private */
    function isTaconiteTag(node) {
        return node.tagName.substring(0, 9) == "taconite-";
    }

    /** @private */
    function toQueryString(elements) {
        var node = null;
        var qs = "";
        var name = "";

        var tempString = "";
        for(var i = 0; i < elements.length; i++) {
            tempString = "";
            node = elements[i];

            name = node.getAttribute("name");
            //use id if name is null
            if (!name) {
                name = node.getAttribute("id");
            }
            name = encodeURIComponent(name);

            if(node.tagName.toLowerCase() == "input") {
                if(node.type.toLowerCase() == "radio" || node.type.toLowerCase() == "checkbox") {
                    if(node.checked) {
                        tempString = name + "=" + encodeURIComponent(node.value);
                    }
                }

                if(node.type.toLowerCase() == "text" || node.type.toLowerCase() == "hidden" || node.type.toLowerCase() == "password") {
                    tempString = name + "=" + encodeURIComponent(node.value);
                }
            }
            else if(node.tagName.toLowerCase() == "select") {
                tempString = getSelectedOptions(node);
            }

            else if(node.tagName.toLowerCase() == "textarea") {
                tempString = name + "=" + encodeURIComponent(node.value);
            }

            if(tempString != "") {
                if(qs == "") {
                    qs = tempString;
                }
                else {
                    qs = qs + "&" + tempString;
                }
            }

        }

        return qs;

    }

    /** @private */
    function getSelectedOptions(select) {
        var options = select.options;
        var option = null;
        var qs = "";
        var tempString = "";

        for(var x = 0; x < options.length; x++) {
            tempString = "";
            option = options[x];

            if(option.selected) {
                tempString = encodeURIComponent(select.name) + "=" + encodeURIComponent(option.value);
            }

            if(tempString != "") {
                if(qs == "") {
                    qs = tempString;
                }
                else {
                    qs = qs + "&" + tempString;
                }
            }
        }

        return qs;
    }

    /** @private */
    function echoResponse(ajaxRequest) {
        var echoTextArea = document.getElementById("debugResponse");
        if(echoTextArea == null) {
            echoTextArea = createDebugTextArea("Server Response:", "debugResponse");
        }
        var debugText = ajaxRequest.getXMLHttpRequestObject().status
        + " " + ajaxRequest.getXMLHttpRequestObject().statusText + "\n\n\n";
        echoTextArea.value = debugText + ajaxRequest.getXMLHttpRequestObject().responseText;
    }

    /** @private */
    function echoParsedJavaScript(js) {
        var echoTextArea = document.getElementById("debugParsedJavaScript");
        if(echoTextArea == null) {
            var echoTextArea = createDebugTextArea("Parsed JavaScript (by JavaScript Parser):", "debugParsedJavaScript");
        }
        echoTextArea.value = js;
    }

    /** @private */
    function createDebugTextArea(label, id) {
        echoTextArea = document.createElement("textarea");
        echoTextArea.setAttribute("id", id);
        echoTextArea.setAttribute("rows", "15");
        echoTextArea.setAttribute("style", "width:100%");
        echoTextArea.style.cssText = "width:100%";

        document.getElementsByTagName("body")[0].appendChild(document.createTextNode(label));
        document.getElementsByTagName("body")[0].appendChild(echoTextArea);
        return echoTextArea;
    }


    /** @private */
    function echoRequestParams() {
        var qsTextBox = document.getElementById("qsTextBox");
        if(qsTextBox == null) {
            qsTextBox = createDebugTextBox("Query String:", "qsTextBox");
        }
        qsTextBox.value = queryString;

        var urlTextBox = document.getElementById("urlTextBox");
        if(urlTextBox == null) {
            urlTextBox = createDebugTextBox("URL (Includes query string if GET request):", "urlTextBox");
        }
        urlTextBox.value = requestURL;
    }

    /** @private */
    function createDebugTextBox(label, id) {
        textBox = document.createElement("input");
        textBox.setAttribute("type", "text");
        textBox.setAttribute("id", id);
        textBox.setAttribute("style", "width:100%");
        textBox.style.cssText = "width:100%";

        document.getElementsByTagName("body")[0].appendChild(document.createTextNode(label));
        document.getElementsByTagName("body")[0].appendChild(textBox);
        return textBox;
    }
};

/**
 Create an instance of the XMLHttpRequest object, using the appropriate
 method for the type of browser in which this script is running. For Internet
 Explorer, it's an ActiveX object, for all others it's a native JavaScript
 object.
 @return an instance of the XMLHttpRequest object.
 */
function createXMLHttpRequest() {
    var req = false;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {
                req = false;
            }
        }
    }
    return req;
};

/************************************************************************************************************************/
/************************************************************************************************************************/

// POP UP CREATOR -- Add on

ModalPopup = function (elem,options) {
	try{
		options = options || {};
		var HasBackground = (options.HasBackground!=null)?options.HasBackground:true;
		var BackgroundColor = options.BackgroundColor || '#669299';
		var BackgroundOpacity = options.BackgroundOpacity || 60; // 1-100
		BackgroundOpacity = (BackgroundOpacity > 0) ? BackgroundOpacity : 1;
		var BackgroundOnClick = options.BackgroundOnClick || function(){};
		var BackgroundCursorStyle = options.BackgroundCursorStyle || "default";
		var Zindex = options.Zindex || 90000;
		var AddLeft = options.AddLeft || 0; //in px
		var AddTop = options.AddTop || 0; //in px

		function _Convert(val) {
			if (!val) {return;}
			val = val.replace("px","");
			if (isNaN(val)) {return 0;}
			return parseInt(val);
		}
		var popup = document.getElementById(elem);
		if (!popup) {return;}
		//set the popup layer styles
		var winW = (document.layers||(document.getElementById&&!document.all)) ? window.outerWidth : (document.all ? document.body.clientWidth : 0);
		var winH = window.innerHeight ? window.innerHeight :(document.getBoxObjectFor ? Math.min(document.documentElement.clientHeight, document.body.clientHeight) : ((document.documentElement.clientHeight != 0) ? document.documentElement.clientHeight : (document.body ? document.body.clientHeight : 0)));
		//display the popup layer
		popup.style.display = "block";
		popup.style.visibility = "visible";
		var currentStyle;
		if (popup.currentStyle)	{
			currentStyle = popup.currentStyle;
		}
		else if (window.getComputedStyle) {
			currentStyle = document.defaultView.getComputedStyle(popup, null);
		} else {
			currentStyle = popup.style;
		}


		var elemW = popup.offsetWidth -
			_Convert(currentStyle.marginLeft) -
			_Convert(currentStyle.marginRight) -
			_Convert(currentStyle.borderLeftWidth) -
			_Convert(currentStyle.borderRightWidth);

		var elemH = popup.offsetHeight -
			_Convert(currentStyle.marginTop) -
			_Convert(currentStyle.marginBottom) -
			_Convert(currentStyle.borderTopWidth) -
			_Convert(currentStyle.borderBottomWidth);

		popup.style.position = "absolute";
		popup.style.left = (winW/2 - elemW/2 + AddLeft) + "px";
		popup.style.top = (winH/2 - elemH/2 + AddTop - 10) + "px";
		popup.style.zIndex = Zindex + 1;

		if (HasBackground) {
			if (!ModalPopup._BackgroundDiv) {
				ModalPopup._BackgroundDiv = document.createElement('div');
				ModalPopup._BackgroundDiv.style.display = "none";
				if(document.body.scrollWidth > window.screen.height)
				{
					ModalPopup._BackgroundDiv.style.width = document.body.scrollWidth;
				}else{
					ModalPopup._BackgroundDiv.style.width = "100%";
				}
				ModalPopup._BackgroundDiv.style.position = "absolute";
				ModalPopup._BackgroundDiv.style.top = "0px";
				ModalPopup._BackgroundDiv.style.left = "0px";
				document.body.appendChild(ModalPopup._BackgroundDiv);
			}
			ModalPopup._BackgroundDiv.onclick =  BackgroundOnClick;
			ModalPopup._BackgroundDiv.style.background = BackgroundColor;
			ModalPopup._BackgroundDiv.style.height = document.all ? Math.max(Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.body.scrollHeight)) : (document.body ? document.body.scrollHeight : ((document.documentElement.scrollHeight != 0) ? document.documentElement.scrollHeight : 0)) + "px";
			ModalPopup._BackgroundDiv.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + BackgroundOpacity +")";
			ModalPopup._BackgroundDiv.style.MozOpacity = BackgroundOpacity / 100;
			ModalPopup._BackgroundDiv.style.opacity = BackgroundOpacity / 100;
			ModalPopup._BackgroundDiv.style.zIndex = Zindex;
			ModalPopup._BackgroundDiv.style.cursor = BackgroundCursorStyle;

			//Display the background
			ModalPopup._BackgroundDiv.style.display = "";
		}
	}
	catch(error)
	{
		 alert("["+error.description+"] ModalPopup-AjaxCommonLib.js");
	}
}

ModalPopup.Close = function(id) {
	try{
		if (id) {
			document.getElementById(id).style.display = "none";
			document.getElementById(id).style.visibility = "hidden";
		}
		if  (ModalPopup._BackgroundDiv) {
			ModalPopup._BackgroundDiv.style.display = "none";
		}
	}
	catch(error)
	{
		 alert("["+error.description+"] ModalPopup.Close-AjaxCommonLib.js");
	}
}
/************************************************************************************************************************/
/************************************************************************************************************************/

//QUERY STRING PARSER

/*BGIN*/

function Querystring(qs)
{ // optionally pass a querystring to parse
	this.params = {};

	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
 	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

// split out each name=value pair
	for (var i = 0; i < args.length; i++)
	{
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);

		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;

		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_)
{
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key)
{
	var value = this.params[key];
	return (value != null);
}

/*END*/

/************************************************************************************************************************/
/************************************************************************************************************************/


/* USER DEFINED FUNCTION */

// THIS IS TO SET THE LOADING IMAGE BEFORE THE DATA FETCHES FORM THE SERVER

function displaySuccessMessage(ajaxrequestObject)
{
	try
	{
 		if(document.getElementById("errorMessagePannel") == undefined)
		{
			createDivForPopups();
			ModalPopup("errorMessagePannel");

 		}

  		var responseObj = ajaxrequestObject.getXMLHttpRequestObject();

		var functions = ajaxrequestObject.getCloseEventFunctions();
		var temp ="";
		if(functions == null)
		{
			functions = "void(0);";
		}
		else
		{
			functionArray =functions.split("|");
			for(i=0;i<functionArray.length;++i)
			{
				temp = temp +functionArray[i];
			}

		}
  		document.getElementById("errorMessagePannel").innerHTML =innerHTML ="<table width='100%' class='Display'><tr><td><a href='javascript:closeErrorMessage();"+escape(temp)+"'><B>close</B></></td></tr></table>"
  		document.getElementById("errorMessagePannel").innerHTML = document.getElementById("errorMessagePannel").innerHTML + responseObj.responseText;
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js: displaySuccessMessage()]");
	}
 }

// SET THE LOADING IMMAGE[ DISPLAY THE IMAGE SPECIFIED AT THE CENTER OF THE SCREEN OR IN THE contentPanelName ]

function setLoadingImage(contentPanelName,imagePath)
{	try
	{
		if(document.getElementById(contentPanelName) == undefined)
		{
			createDivForPopups();
			document.getElementById("errorMessagePannel").innerHTML = "<center><font style='font-family:Verdana, Arial, Helvetica,sans-serif;font-size:11px;color:#993366;'><center><br><br><br><br><br><br><img src="+imagePath+"><br>Loading...</font></center>";
			ModalPopup("errorMessagePannel");
			setDivCenter("errorMessagePannel");
		}
		else
		{
			document.getElementById(contentPanelName).innerHTML = "<center><font style='font-family:Verdana, Arial, Helvetica,sans-serif;font-size:11px;color:#993366;'><center><br><br><br><br><br><br><img src="+imagePath+"><br>Loading...</font></center>";
		}
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js: setLoadingImage()]");
	}
}


// SET THE STATUS IMMAGE[ DISPLAY THE IMAGE SPECIFIED AT THE CENTER OF THE SCREEN OR IN THE contentPanelName ]

function setStatusImage(contentPanelName,imagePath,status)
{	try
	{
		if(document.getElementById(contentPanelName) == undefined)
		{
			document.getElementById(contentPanelName).innerHTML = "<center><font style='font-family:Verdana, Arial, Helvetica,sans-serif;font-size:11px;color:#000000;'><center><br><br><br><br><br><br><img src="+imagePath+"><br>"+status+"</font></center>";

		}
		else
		{
			document.getElementById(contentPanelName).innerHTML = "<center><font style='font-family:Verdana, Arial, Helvetica,sans-serif;font-size:11px;color:#000000;'><center><br><br><br><br><br><br><img src="+imagePath+"><br>"+status+"</font></center>";
		}
		ModalPopup(contentPanelName);
		setDivCenter(contentPanelName);
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js: setStatusImage()]");
	}
}

// COMMON ERROR HANDLE FUNCTION

/*function ajaxErrorhandler(ajaxrequestObject,err)
{
	try
	{
		var xmlHttpRequestObject = ajaxrequestObject.getXMLHttpRequestObject();
		var text = xmlHttpRequestObject.responseText;
		if(xmlHttpRequestObject.status==200){
			return
		}
		else
		{
			document.getElementById("errorPageDiv").style.display = "none";
			alert(document.getElementById("errorMessagePannel").offsetWidth);
			if(document.getElementById("errorMessagePannel") != undefined)
			{
				document.getElementById("errorMessagePannel").innerHTML ="<table width='100%' class='Display'><tr><td align='right'><a href='javascript:closeErrorMessage();' style='text-decoration:none;color:red;'>Close</></td></tr></table>"
 				document.getElementById("errorMessagePannel").innerHTML = document.getElementById("errorMessagePannel").innerHTML + text;
				//setTimeout("closeErrorMessage();",7000);
			}
			else
			{
				try
				{
					createDivForPopups()
					errorDiv = document.getElementById("errorMessagePannel");
					errorDiv.innerHTML ="<table width='100%' class='Display'><tr><td><a href='javascript:closeErrorMessage();' style='text-decoration:none;'><B>close</B></></td></tr></table>"
					errorDiv.innerHTML = errorDiv.innerHTML + text;
					ModalPopup("errorMessagePannel")
				//	setTimeout("closeErrorMessage();",7000);

				}
				catch(er)
				{
					document.write(er.description+"[ AjaxCommonLib.js: ajaxErrorhandler()]"+text)
				}

			}

		}
	}
	catch(Er){alert(Er.description+"[-  AjaxCommonLib.js -ajaxErrorhandler() catch 2");}
}
*/
// CREATE DYNAMIC DIV ON THE PAGE

function createDivForPopups()
{
	try
	{
		var errorDiv					= window.document.createElement("div");
		var root						= (document.compatMode == "CSS1Compat"?document.documentElement: document.body);
		errorDiv.id					= "errorMessagePannel";
		errorDiv.style.position			= "absolute";
		errorDiv.style.backgroundColor	= "#FFFFFF";
		errorDiv.style.left				= root.scrollLeft + 200 + "px";
		errorDiv.style.top				= root.scrollTop + 400 + "px";
		errorDiv.style.width			= "700px";
		errorDiv.style.height			="200px";
		errorDiv.className				="Display";
		//errorDiv.style.overflow			="auto"
		window.document.body.appendChild(errorDiv);
		
		setDivCenter(errorDiv.id);
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: createDivForPopups()]")
	}

 }
// CREATE USER DEFIEND DIV ON PAGE

function createDivForPage(divId,className,position,backgroundColor,innerContent,width,height)
{
	try
	{
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
			var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
			
			if(ieversion < 7){
			alert("Please upgrade your browser to Internet Explorer 7 to get this feature. The following page will redirect you to download Explorer 7.");
			 window.open('http://www.microsoft.com/downloads/details.aspx?FamilyId=9AE91EBE-3385-447C-8A30-081805B2F90B&displaylang=en','','toolbar=yes, menubar=yes, scrollbars=yes, resizable=yes, width=1000, height=1000, top=0, left=0');
			 return;
			}
		}		
		var newDiv				= window.document.createElement("div");
		var root					= (document.compatMode == "CSS1Compat"?document.documentElement: document.body);
		newDiv.id					= divId;
		newDiv.style.position		= position;
		newDiv.style.backgroundColor	= backgroundColor;
		//newDiv.style.left			= root.scrollLeft + 200 + "px";
		//newDiv.style.top			= root.scrollTop + 400 + "px";
		newDiv.style.left			= root.scrollLeft + 200 + "px";
		newDiv.style.top			= root.scrollTop + 400 + "px";
	
		newDiv.style.width			= "auto";
		newDiv.style.height			= "auto";
		newDiv.className			= className;
		newDiv.overflow			= "auto";
		window.document.body.appendChild(newDiv);
		document.getElementById(divId).innerHTML = innerContent;
		ModalPopup(divId);
		setDivCenter(newDiv.id);
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: createDivForPopups()]")
	}

 }
 // CLOSE THE USERDEFINED DIV
function closeDiv(divId)
{
	try
	{
		if(document.getElementById(divId) != undefined)
		{
			ModalPopup.Close(divId);
			var removeErrorMessagePannel = document.getElementById(divId);
			window.document.body.removeChild(removeErrorMessagePannel);

		}
		return;
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: closeDiv()]")
	}
} 

function clearDiv(divId){
	try
	{
		var divObj	= document.getElementById(divId);
		if(document.getElementById(divId) != undefined)
		{		
			divObj.innerHTML = "";
			ModalPopup.Close(divId);
		}
		return;
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: clearDiv()]")
	}
}

function clearDivValue(divId){
	try
	{
		var divObj	= document.getElementById(divId);
		if(document.getElementById(divId) != undefined)
		{		
			divObj.innerHTML = "";
		}
		return;
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: clearDiv()]")
	}
}

function toggleAlert(errorDiv,contentPanelName,msgTxt,msgTitle,closeFunction){
	try{
			ModalPopup.Close(contentPanelName);
			document.getElementById(contentPanelName).style.display = "none";
			makeAlertDiv(errorDiv,msgTitle,msgTxt,closeFunction)
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: toggleAlert()]")
	}
}

function alertClose(errorDiv,contentPanelName,focusDiv){
	try{
		clearDiv(errorDiv);
		ModalPopup(contentPanelName);
		setDivCenter(contentPanelName);
		document.getElementById(focusDiv).focus();		
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: alertClose()]")
	}
}

function alertCancel(errorDiv,contentPanelName,statusPanel){
	try{
		clearDiv(errorDiv);
		clearDiv(statusPanel)
		ModalPopup(contentPanelName);
		setDivCenter(contentPanelName);
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: alertCancel()]")
	}
}

function makeDivPopUp(divId){
 	try
	{
		document.getElementById(divId).style.diplay = "block"		
		document.getElementById(divId).style.backgroundColor = "white";
		ModalPopup(divId);
		setDivCenter(divId);
		//window.onscroll = function(){setDivCenter(divId)}
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js :- makeDivPopUp()]");
	}
}

function makeConfirmDiv(contentPanelName,alertTitle,confirmMessage,closeFunction,imagePath,onOkFunction,onCancelFunction,closeFunction){
	try
	{
		makeDivPopUp(contentPanelName);
		var alertPageHTML = "";
		var okImagePath = imagePath + "ok.png";
		var cancelImagePath = imagePath + "cancel.png";
		alertPageHTML = alertPageHTML + "<center>"
		alertPageHTML = alertPageHTML + "<table>"
		alertPageHTML = alertPageHTML + "<tr><td><div style='width:600px'>"
		alertPageHTML = alertPageHTML + "<div class='fancy_close' style='display:block' onClick=javascript:"+closeFunction+"></div>"
		alertPageHTML = alertPageHTML + "<fieldset>"
		alertPageHTML = alertPageHTML + "<legend class='form_text'>"+alertTitle+"</legend>"
		alertPageHTML = alertPageHTML + "<div class='form_text' style='text-align:center'>"+confirmMessage+"</div>"
		alertPageHTML = alertPageHTML + "<div style='text-align:center'>&nbsp;</div>"
		alertPageHTML = alertPageHTML + "<div style='text-align:center'>"
//		alertPageHTML = alertPageHTML + "<span><img src='"+okImagePath+"' title='' onclick="+onOkFunction+"  style='cursor:pointer'></span>"
//		alertPageHTML = alertPageHTML + "<span><img src='"+cancelImagePath+"' title='' onclick="+onCancelFunction+"  style='cursor:pointer'></span>"
		alertPageHTML = alertPageHTML + "<a href=javascript:"+onOkFunction+" style='text-decoration:none;'><img src='"+okImagePath+"' title='' style='cursor:pointer' border='0'></a>"
		alertPageHTML = alertPageHTML + "<a href=javascript:"+onCancelFunction+" style='text-decoration:none;'><img src='"+cancelImagePath+"' title='' style='cursor:pointer' border='0'></a>"
		alertPageHTML = alertPageHTML + "</fieldset>"
		alertPageHTML = alertPageHTML + "</div>"
		alertPageHTML = alertPageHTML + "</td></tr>"
		alertPageHTML = alertPageHTML + "</table>"
		alertPageHTML = alertPageHTML + "</center>"
		document.getElementById(contentPanelName).innerHTML = trim(alertPageHTML);
		document.getElementById(contentPanelName).style.dispaly = "block";
		setDivCenter(contentPanelName);
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js :- makeConfirmDiv()]");
	}	
}

function toggleConfirm(errorDiv,contentPanelName,msgTxt,msgTitle,imagePath,onOkFunction,onCancelFunction,closeFunction){
	try{
			ModalPopup.Close(contentPanelName);
			makeConfirmDiv(errorDiv,msgTitle,msgTxt,closeFunction,imagePath,onOkFunction,onCancelFunction,closeFunction)
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: toggleConfirm()]")
	}
}

function makeAlertDiv(contentPanelName,alertTitle,alertMessage,closeFunction){
	try
	{
		makeDivPopUp(contentPanelName);
		var alertPageHTML = "";
		alertPageHTML = alertPageHTML + "<center>"
		alertPageHTML = alertPageHTML + "<table>"
		alertPageHTML = alertPageHTML + "<tr><td><div style='width:600px'>"
		alertPageHTML = alertPageHTML + "<div class='fancy_close' style='display:block' onClick=javascript:"+closeFunction+"></div>"
		alertPageHTML = alertPageHTML + "<fieldset>"
		alertPageHTML = alertPageHTML + "<legend class='form_text'>"+alertTitle+"</legend>"
		alertPageHTML = alertPageHTML + "<div class='form_text' style='text-align:center'>"+alertMessage+"</div>"
		alertPageHTML = alertPageHTML + "</fieldset>"
		alertPageHTML = alertPageHTML + "</div>"
		alertPageHTML = alertPageHTML + "</td></tr>"
		alertPageHTML = alertPageHTML + "</table>"
		alertPageHTML = alertPageHTML + "</center>"
		document.getElementById(contentPanelName).innerHTML = trim(alertPageHTML);
		document.getElementById(contentPanelName).style.dispaly = "block";
		//var root					= (document.compatMode == "CSS1Compat"?document.documentElement: document.body);
		//document.getElementById(contentPanelName).style.left	= root.scrollLeft + 400 + "px";
		//document.getElementById(contentPanelName).style.top	= root.scrollTop + 250 + "px";
		setDivCenter(contentPanelName);
		//alert(document.getElementById(contentPanelName).innerHTML)
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js :- makeAlertDiv()]");
	}	
}

//function setDivCenter(contentPanelName){
//	document.getElementById(contentPanelName).style.display ="block";
//	var avilWidth = window.screen.availWidth;
//	var avilHeight = window.screen.availHeight;
//	if (window.innerWidth && window.innerHeight){ //if browser supports window.innerWidth and window.innerHeight
//		avilWidth = window.innerWidth;
//		avilHeight = window.innerHeight;
//	}else if (document.all){ //else if browser supports document.all (IE 4+)
//		avilWidth = document.body.clientWidth;
//		avilHeight = window.document.body.clientHeight;		
//	}
//	var divWidth = document.getElementById(contentPanelName).offsetWidth;
//	var divHeight = document.getElementById(contentPanelName).offsetHeight;
//	document.getElementById(contentPanelName).style.left = (avilWidth/2) - (divWidth/2);
//	document.getElementById(contentPanelName).style.top = (avilHeight/2) - (divHeight/2);
//	if (parseFloat(document.getElementById(contentPanelName).style.top)<10)
//	{
//		document.getElementById(contentPanelName).style.top = 10;
//	}
//}

function setDivCenter(contentPanelName){
	document.getElementById(contentPanelName).style.display ="block";
 	var avilWidth = window.screen.availWidth;
	var avilHeight = window.screen.availHeight;
	if (window.innerWidth && window.innerHeight){ //if browser supports window.innerWidth and window.innerHeight
 		avilWidth = window.innerWidth;
		avilHeight = window.innerHeight;
	}else if (document.all){ //else if browser supports document.all (IE 4+)
 		avilWidth = document.body.clientWidth;
		avilHeight = window.document.body.clientHeight;		
	}
	var divWidth = document.getElementById(contentPanelName).offsetWidth;
	var divHeight = document.getElementById(contentPanelName).offsetHeight;
	var root = (document.compatMode == "CSS1Compat"?document.documentElement: document.body);
	
	document.getElementById(contentPanelName).style.left =  root.scrollLeft + (avilWidth/2) - (divWidth/2);
	document.getElementById(contentPanelName).style.top =   root.scrollTop  + (avilHeight/2) - (divHeight/2) ;
 
	if(parseFloat(document.getElementById(contentPanelName).style.top) <= 10)
	{
 		document.getElementById(contentPanelName).style.top =12;
	}
}

function ajaxErrorhandler(ajaxrequestObject,err)
{
	try
	{
		
		var closeFunction  = "";
		var xmlHttpRequestObject = ajaxrequestObject.getXMLHttpRequestObject();
		var text = xmlHttpRequestObject.responseText;
		if(xmlHttpRequestObject.status==200){
			return
		}
		else
		{	
			if (trim(text.toUpperCase()) == "SESSION EXPIRED, LOGIN AGAIN...")
			{
				closeFunction = "closeErrorMessage();logout();"
			}else{
				closeFunction = "closeErrorMessage();"
			}
			
			if(document.getElementById("errorMessagePannel") != undefined)
			{
 				document.getElementById("errorMessagePannel").innerHTML ="<div class='fancy_close' title='Please Click To Close Window' onClick='javascript:"+closeFunction+"'></div><br>";
				document.getElementById("errorMessagePannel").innerHTML = document.getElementById("errorMessagePannel").innerHTML + text;
				//setTimeout("closeErrorMessage();",7000);
			}
			else
			{
				try
				{
					createDivForPopups()
					errorDiv = document.getElementById("errorMessagePannel");
 					errorDiv.innerHTML = "<div class='fancy_close' title='Please Click To Close Window' onClick='closeErrorMessage();'></div><br>";
					errorDiv.innerHTML = errorDiv.innerHTML + text;
					//alert(document.getElementById("errorMessagePannel").offsetWidth);
					ModalPopup("errorMessagePannel");
					setDivCenter("errorMessagePannel");
				//	setTimeout("closeErrorMessage();",7000);

				}
				catch(er)
				{
					document.write(er.description+"[ AjaxCommonLib.js: ajaxErrorhandler()]"+text)
				}

			}

		}
	}
	catch(Er){alert(Er.description+"[-  AjaxCommonLib.js -ajaxErrorhandler() catch 2");}
}
 
// CLOSE THE DYNAMICALLY CREATED DIV

function closeErrorMessage()
{
	try
	{
		if(document.getElementById("errorMessagePannel") != undefined)
		{
			ModalPopup.Close('errorMessagePannel');
			var removeErrorMessagePannel = document.getElementById("errorMessagePannel");
			window.document.body.removeChild(removeErrorMessagePannel);

		}
		return;
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: closeErrorMessage()]")
	}
}

// HANDLE THE RESPONSE OF THE AJAX REQUEST AND
// PLACE THE RESPOSE TEXT IN THE CONTOL SPECIFIED IN THE QUERY STRING AS "ContentPannelName"

function handleLoadContentFrame(obj)
{
	try
	{
		closeErrorMessage();
		var responseObj = obj.getXMLHttpRequestObject();
		var QuertString = obj.getQueryString();
		var QueryStringparser = new Querystring(QuertString); // Query sting parser
 		if(!QueryStringparser.contains("ContentPannelName")) {alert("Content Pannel Name is not defined in the Query String..");return;}
  		var contentFrameID= QueryStringparser.get("ContentPannelName");
		document.getElementById(contentFrameID).innerHTML = responseObj.responseText;
		//setDivCenter(contentFrameID);
 	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js :- handleLoadContentFrame()]");
	}
}
function ajaxErrorhandler4Modal(ajaxrequestObject,err)
{
	try
	{
		var respnseObj = ajaxrequestObject.getXMLHttpRequestObject();
		var text = respnseObj.responseText;
		var queryStr = ajaxrequestObject.getQueryString();
		var QueryStringparser = new Querystring(queryStr); // Query sting parser
 		//if(!QueryStringparser.contains("ContentPanelName")) {alert("Content Pannel Name is not defined in the Query String..");return;}
		//if(!QueryStringparser.contains("ActivePanelName")) {alert("Content Pannel Name is not defined in the Query String..");return;}
  		var contentPanelId = QueryStringparser.get("ContentPanel");
		var errorPanelId = QueryStringparser.get("ErrorPanel");
		var statusPanelId = QueryStringparser.get("StatusPanel");
		
		
		var pramString = "'"+contentPanelId+"','"+errorPanelId+"','"+statusPanelId+"'";
		//alert(pramString);
		var closeFunction = "";
		
		if(respnseObj.status==200){
			return
		}
		else
		{	

			
			//closeFunction = "closeErrorMessage4Modal("+pramString+");";
			//closeFunction="javascript:function(){if(document.getElementById('logOutFlag')){if (document.getElementById('logOutFlag').value == 'Y'){closeErrorMessage4Modal("+pramString+");logout();}else{closeErrorMessage4Modal("+pramString+");}}}"
			//alert(closeFunction);
			closeFunction="closeErrorMessage4Modal("+pramString+");";
			
//			if (trim(text.toUpperCase()) == "SESSION EXPIRED, LOGIN AGAIN...")
//			{
//				closeFunction = "closeErrorMessage4Modal("+pramString+");logout();"
//			}else{
//				closeFunction = "closeErrorMessage4Modal("+pramString+");"
//			}
			
			document.getElementById(contentPanelId).style.display = "none";
			document.getElementById(statusPanelId).style.display = "none";
			if(document.getElementById(errorPanelId) != undefined)
			{
				//document.getElementById(errorPanelId).innerHTML ="<div class='fancy_close' style='text-align:center' title='Please Click To Close Window' onClick=closeErrorMessage4Modal("+pramString+");></div><br>";
				document.getElementById(errorPanelId).innerHTML ="<div class='fancy_close' style='text-align:center' title='Please Click To Close Window' onClick="+closeFunction+"></div><br>";
				document.getElementById(errorPanelId).innerHTML = document.getElementById(errorPanelId).innerHTML + text;
				makeDivPopUp(errorPanelId);
				document.getElementById(errorPanelId).setAttribute("align","center");
				setDivCenter(errorPanelId);
			}
			else
			{
				try
				{
					//createDivForPopups()
					makeDivPopUp(errorPanelId);
					errorDiv = document.getElementById(errorPanelId);
					
 					//errorDiv.innerHTML = "<div class='fancy_close' style='text-align:center' title='Please Click To Close Window' onClick=closeErrorMessage4Modal("+pramString+");></div><br>";
					errorDiv.innerHTML = "<div class='fancy_close' style='text-align:center' title='Please Click To Close Window' onClick="+closeFunction+"></div><br>";				
					errorDiv.innerHTML = errorDiv.innerHTML + text;
					//alert(document.getElementById("errorMessagePannel").offsetWidth);
					document.getElementById(errorPanelId).setAttribute("align","center");
					setDivCenter(errorPanelId);
					//ModalPopup("errorMessagePannel")
					
					//alert(document.getElementById("errorMessagePannel").offsetWidth);
				//	setTimeout("closeErrorMessage();",7000);

				}
				catch(er)
				{
					document.write(er.description+"[ AjaxCommonLib.js: ajaxErrorhandler4Modal()]"+text)
				}

			}
		}
	}
	catch(Er){alert(Er.description+"[-  AjaxCommonLib.js -ajaxErrorhandler4Modal() catch 2");}
}

function closeErrorMessage4Modal(contentPanelId,errorPanelId,statusPanelId){
	try
	{
		if(document.getElementById(statusPanelId) != undefined)
		{
			document.getElementById(statusPanelId).innerHTML = "";
			document.getElementById(statusPanelId).style.display = "none";
		}
		if(document.getElementById('logOutFlag')){
			if (document.getElementById('logOutFlag').value == 'Y'){
				logout();
			}
		}		
		if(document.getElementById(errorPanelId) != undefined)
		{
			document.getElementById(errorPanelId).innerHTML = "";
			ModalPopup.Close(errorPanelId);
		}
		if(document.getElementById(contentPanelId) != undefined)
		{
			makeDivPopUp(contentPanelId);
		}
		return;
	}
	catch(er)
	{
		alert(er.description+"[ AjaxCommonLib.js: closeErrorMessage()]")
	}
}

function gotoAnchor(anchorName){
	try{
		window.location = anchorName;
	}
	catch(Err)
	{
		alert(Err.description+"[ AjaxCommonLib.js :- gotoAnchor()]");
	}	
}


function handleLoadDefault(ajaxObj)
{
	try{
		var responseObj = ajaxObj.getXMLHttpRequestObject();
		var contentPanelName = getAttribute("ContentPanel");
		if (document.getElementById(contentPanelName) != "undefined" || document.getElementById(contentPanelName) != null){
			document.getElementById(contentPanelName).innerHTML = trim(responseObj.responseText);
		}else{
			alert("Content Panel Specified is Found!!!...");
		}
	}
	catch(error)
	{
		alert(error.description+ " AjaxCommonLib.js - handleLoadDefault()");
	}	
}

