﻿var _xmlHttp;

function parseBoolean(s)
{
    if (!s) 
        return false;
    
    s = s.toString().toLowerCase();
    
    return s == "true" || s == "yes" || parseInt(s) > 0;
}

function fireEvent(element, event)
{   
    if (document.createEventObject){
        // dispatch for IE
        //var evt = document.createEventObject();
        //return element.fireEvent('on' + event,evt)
        return element.fireEvent('on' + event);
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

function queryString(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

function URLEncode(toEncode)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = toEncode;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(toDecode)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = toDecode;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

function remoteCommand() 
{              
	try 
	{    // Firefox, Opera 8.0+, Safari    
		_xmlHttp = new XMLHttpRequest();    
    }
    catch ( e ) 
    {   // Internet Explorer    
		try 
		{    
			_xmlHttp=new ActiveXObject( "Msxml2.XMLHTTP" );
		}
		catch ( e ) 
		{      
			try 
			{        
				_xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP" );
			}
			catch ( e ) 
			{        
				alert( "Your browser does not support AJAX!" );
				return ( false );
			}      
		}    
	}  
}   
function CreateLocalXMLDocumentObject(xmlData)
{   
    var xmlDoc; 
    
    try //Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlData);
    }
    catch(e)
    {
        try //Firefox, Mozilla, Opera, etc. 
        {
            var objDOMParser = new DOMParser();   
            
            Node.prototype.__defineGetter__("xml", _Node_getXML);
            Node.prototype.__defineGetter__("text", function () 
            {              
                return this.nodeValue; 
            });             
            Node.prototype.__defineSetter__("text", function (v) 
            {                        
                var cDataSection = this;
                
                if (cDataSection != null && (cDataSection.nodeType == 4))
                {   
                    cDataSection.nodeValue = v;
                }
                else
                {
                    var newcDataSectionNode = this.ownerDocument.createCDATASection(v);
                    this.parentNode.appendChild(newcDataSectionNode);
                }
            });
            Node.prototype.selectSingleNode = function(xpath) 
            {
                var doc = this;
                if (doc.nodeType != 9) 
                    doc = doc.ownerDocument;
			    
			    if (doc.nsResolver == null) 
			        doc.nsResolver = function(prefix) { return(null); };
			
			    var node = doc.evaluate(xpath, this, doc.nsResolver, XPathResult.ANY_UNORDERED_NODE_TYPE, null);
			
			    if (node != null) 
			        node = node.singleNodeValue;
            	
            	return(node);
            };

            if (document.implementation.hasFeature("XPath", "3.0") )
            {  
                XMLDocument.prototype.selectNodes = function (cXPathString, xNode)  
                {     
                    if(!xNode ) 
                    { 
                        xNode = this; 
                    }      
                    
                    var oNSResolver = this.createNSResolver(this.documentElement)
                    var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
                    var aResult = [];     
                    
                    for( var i = 0; i < aItems.snapshotLength; i++)     
                    {        
                        aResult[i] = aItems.snapshotItem(i);     
                    }     
                    
                    return aResult;  
                }  
                // prototying the Element  
                
                Element.prototype.selectNodes = function(cXPathString)  
                {     
                    if (this.ownerDocument.selectNodes)     
                    {        
                        return this.ownerDocument.selectNodes(cXPathString, this);    
                    }     
                    else{throw "For XML Elements Only";}  
                 }
            }
                     
            xmlDoc = objDOMParser.parseFromString(xmlData, "text/xml");                    
        }   
        catch(e)
        {
            alert(e.message);
        }     
    }
    
    return xmlDoc;
}
function CreateXMLDocumentObject(xmlData)
{   
    try //Internet Explorer
    {
        _xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        _xmlDoc.async = "false";
        _xmlDoc.loadXML(xmlData);
    }
    catch(e)
    {
        try //Firefox, Mozilla, Opera, etc. 
        {
            var objDOMParser = new DOMParser();   
            
            Node.prototype.__defineGetter__("xml", _Node_getXML);
            Node.prototype.__defineGetter__("text", function () 
            { 
                return this.nodeValue; 
            });             
            Node.prototype.__defineSetter__("text", function (v) 
            {                         
                var cDataSection = this;
                
                if (cDataSection != null && (cDataSection.nodeType == 4))
                {   
                    cDataSection.nodeValue = v;
                }
                else
                {
                    var newcDataSectionNode = this.ownerDocument.createCDATASection(v);
                    this.parentNode.appendChild(newcDataSectionNode);
                }
            });
            Node.prototype.selectSingleNode = function(xpath) 
            {
                var doc = this;
                if (doc.nodeType != 9) 
                    doc = doc.ownerDocument;
			    
			    if (doc.nsResolver == null) 
			        doc.nsResolver = function(prefix) { return(null); };
			
			    var node = doc.evaluate(xpath, this, doc.nsResolver, XPathResult.ANY_UNORDERED_NODE_TYPE, null);
			
			    if (node != null) 
			        node = node.singleNodeValue;
            	
            	return(node);
            };

            if (document.implementation.hasFeature("XPath", "3.0") )
            {  
                XMLDocument.prototype.selectNodes = function (cXPathString, xNode)  
                {     
                    if(!xNode ) 
                    { 
                        xNode = this; 
                    }      
                    
                    var oNSResolver = this.createNSResolver(this.documentElement)
                    var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
                    var aResult = [];     
                    
                    for( var i = 0; i < aItems.snapshotLength; i++)     
                    {        
                        aResult[i] = aItems.snapshotItem(i);     
                    }     
                    
                    return aResult;  
                }  
                // prototying the Element  
                
                Element.prototype.selectNodes = function(cXPathString)  
                {     
                    if (this.ownerDocument.selectNodes)     
                    {        
                        return this.ownerDocument.selectNodes(cXPathString, this);    
                    }     
                    else{throw "For XML Elements Only";}  
                 }
            }
                     
            _xmlDoc = objDOMParser.parseFromString(xmlData, "text/xml");                    
        }   
        catch(e)
        {
            alert(e.message);
        }     
    }
}
function _Node_getText()
{
    var text = "";
	
	for (var i = 0; i < this.childNodes.length; i++) 
	{
	    if (this.childNodes[i].hasChildNodes()) 
	    {
		    text += this.childNodes[i].text;
		} 
		else 
		{
			text += (this.childNodes[i].nodeValue != null) ? this.childNodes[i].nodeValue:"";
		}
	}
	return text;
}
function _Node_getXML() 
{   
    //create a new XMLSerializer
    var objXMLSerializer = new XMLSerializer;
    
    //get the XML string
    var strXML = objXMLSerializer.serializeToString(this);
    
    //return the XML string
    return strXML;
}

function CreateRemoveNode(id, oid, oid1, oid2, ds)
{
    if (_xmlDoc)
    {
        //Add to Remove section if this is an existing item
        var xmlNode = _xmlDoc.createElement(id);
        
        //Set id of record to remove
        xmlNode.setAttribute("id", oid); 
        
        //Set object id 1 (0 = new record)
        if (oid1 == null) 
            xmlNode.setAttribute("oid1", "0");         
        else 
            xmlNode.setAttribute("oid1", oid1); 
            
        //Set object id 2 (0 = new record)
        if (oid2 == null) 
            xmlNode.setAttribute("oid2", "0");         
        else 
            xmlNode.setAttribute("oid2", oid2);         
        
        //Set data source - defines where the element came from    
        if (ds == null) 
            xmlNode.setAttribute("ds", ""); 
        else 
            xmlNode.setAttribute("ds", ds);
            
        return xmlNode;
    }
    
    return null;
}
function RemoveFromXmlDirect(id, oid, oid1, oid2, ds)
{
    var dataXml = document.getElementById("dataXml");
    
    CreateXMLDocumentObject(dataXml.value);
    
    //Get all the nodes that match this id
    var existingNodes = _xmlDoc.documentElement.selectNodes("input/" + id);
    
    //Remove from input and get the id for the record
    //For new records the id will be 0 
    if (existingNodes.length != 0)
    {
        //Loop through and remove all nodes
        for (var i=0; i<existingNodes.length; i++)
        {
            var existingNode = existingNodes[i];
            oid = existingNode.attributes.getNamedItem("id").text;
            existingNode.parentNode.removeChild(existingNode);         
           
            //We don't want to remove record type 0 since it was 
            //never in the database
            if (oid != "0")
            {
                var xmlNode = CreateRemoveNode(id, oid, oid1, oid2, ds);
                
                if (xmlNode)
                    _xmlDoc.documentElement.selectSingleNode("remove").appendChild(xmlNode);
            }
        }
    }
    //If not found in input then we may just want to remove this node if the oid is not 0
    else if (oid != 0)
    {
        var xmlNode = CreateRemoveNode(id, oid, oid1, oid2, ds);
              
        if (xmlNode)
            _xmlDoc.documentElement.selectSingleNode("remove").appendChild(xmlNode);
    }
    
    dataXml.value = _xmlDoc.xml;
    
    //alert(dataXml.value);
}
function RemoveDataSourceFromXml(ds)
{
    var dataXml = document.getElementById("dataXml");
    
    CreateXMLDocumentObject(dataXml.value);
    
    //Get all the nodes that match this id
    var existingNodes = _xmlDoc.documentElement.selectNodes("input/*[@ds='" + ds + "']");
    var existingNodes2 = _xmlDoc.documentElement.selectNodes("remove/*[@ds='" + ds + "']");

    if (existingNodes.length != 0)
    {
        //Loop through and remove all nodes
        for (var i=0; i<existingNodes.length; i++)
        {    
            var existingNode = existingNodes[i];
            existingNode.parentNode.removeChild(existingNode);  
        }
    }
    
    if (existingNodes2.length != 0)
    {
        //Loop through and remove all nodes
        for (var i=0; i<existingNodes2.length; i++)
        {    
            var existingNode2 = existingNodes2[i];
            existingNode2.parentNode.removeChild(existingNode2);  
        }
    }
    
    dataXml.value = _xmlDoc.xml;
    
    //alert(dataXml.value);
}
function RemoveFromXml(id)
{
    var element = document.getElementById(id);
    var oid = element.getAttribute("oid");
    
    var oid1 = "0";
    try { oid1 = element.getAttribute("oid1"); } catch (e) { oid1 = "0" }    
    
    var oid2 = "0";
    try { oid2 = element.getAttribute("oid2"); } catch (e) { oid2 = "0" }
    
    var ds = "";
    try { ds = element.getAttribute("ds"); } catch (e) { ds = "" }
       
    RemoveFromXmlDirect(id, oid, oid1, oid2, ds);
}
function doLogin()
{
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    if (username != "" && password != "")
    {
        remoteCommand();
    
        var url = window.location.href + "?u=" + username + "&p=" + password; 
    
        _xmlHttp.onreadystatechange = ProcessLogin; 
        _xmlHttp.open('GET', url, true); 
        _xmlHttp.send(null);
    }
    else
        alert ("Missing login information");
}
function AddToXmlDirect(id, controlType, oid, oid1, oid2, ds, value, text, checked, lookfor, mc)
{   
    if (lookfor == null || lookfor == "")
        lookfor = id; 
        
    var targetNode;
    var dataXml = document.getElementById("dataXml");
       
    CreateXMLDocumentObject(dataXml.value);
    
    //Find existing node to update based on data source
    targetNode = _xmlDoc.documentElement.selectSingleNode("input/" + lookfor + "[@ds='" + ds + "']");

    //Create new node and append it ----------------------------------------------
    if (targetNode == null)
    {
        var xmlNode = _xmlDoc.createElement(lookfor);
                                                         
        switch (controlType)
        {
            case "dropdown": 
                var newCDATA = _xmlDoc.createCDATASection(value); 
                xmlNode.appendChild(newCDATA);
                xmlNode.setAttribute("text", text);
                break;
            case "checkbox":
                var newCDATA = null; 
                
                if (checked)
                    newCDATA = _xmlDoc.createCDATASection("1");
                else 
                    newCDATA = _xmlDoc.createCDATASection("0");
                    
                xmlNode.appendChild(newCDATA);
                break;  
            default:  
                var newCDATA = _xmlDoc.createCDATASection(value);      
                xmlNode.appendChild(newCDATA);
                break;
        }
        
        //targetNode = xmlNode;        
        _xmlDoc.documentElement.selectSingleNode("input").appendChild(xmlNode);
        targetNode = xmlNode;
    }

    //Set all the attributes ====================================================================
    //Set object id (0 = new record)
    if (oid == null) 
        targetNode.setAttribute("id", "0");         
    else 
        targetNode.setAttribute("id", oid); 
        
    //Set object id 1 (0 = new record)
    if (oid1 == null) 
        targetNode.setAttribute("oid1", "0");         
    else 
        targetNode.setAttribute("oid1", oid1); 
        
    //Set object id 2 (0 = new record)
    if (oid2 == null) 
        targetNode.setAttribute("oid2", "0");         
    else 
        targetNode.setAttribute("oid2", oid2);             
                    
    //Set data source - defines where the element came from    
    if (ds == null)
        targetNode.setAttribute("ds", ""); 
    else 
        targetNode.setAttribute("ds", ds);  
                     
    //Set control type - defines what kind of control this is
    if (controlType == null) 
        targetNode.setAttribute("ct", ""); 
    else 
        targetNode.setAttribute("ct", controlType);    
        
    if (mc == null) 
        targetNode.setAttribute("mc", ""); 
    else 
        targetNode.setAttribute("mc", mc);
    //Set all the attributes ====================================================================
 
    //Create new node and append it ----------------------------------------------    

    //Add data value to existing and new node ------------------------------------
    if (targetNode != null)
    {
        switch (controlType)
        {  
            case "checkbox" : 
                if (checked)
                    targetNode.firstChild.text = "1";
                else
                    targetNode.firstChild.text = "0";
                break;      
            case "dropdown" : 
                targetNode.firstChild.text = value;
                targetNode.setAttribute("text", text);
                break;
            default:         
                targetNode.firstChild.text = value;
                break;
        }
    }
    //Add data value to existing and new node ------------------------------------
    
    dataXml.value = _xmlDoc.xml;
    
    //alert(dataXml.value);
}

function AddToXml(id)
{   
    var lookfor = id;
    var element = document.getElementById(id);        
    var oid = element.getAttribute("oid");
    
    var oid1 = "0";
    try { oid1 = element.getAttribute("oid1"); } catch (e) { oid1 = "0" }    
    
    var oid2 = "0";
    try { oid2 = element.getAttribute("oid2"); } catch (e) { oid2 = "0" }
    
	var mc = ""; 
	try { mc = element.getAttribute("mc"); } catch (e) { mc = "" }
    
    var ds = element.getAttribute("ds");
    var controlType = element.getAttribute("ct");
    var value = "";
    var text = "";
    var checked = false;
    
    switch (controlType)
    {
        case "dropdown": 
            value = element.options[element.selectedIndex].value;
            text = element.options[element.selectedIndex].text;
            break;
        case "checkbox":
            checked = element.checked;
            break;
        case "checkboxgroup":   
            lookfor = element.name;
            value = element.value;
            break;
        default:  
            value = element.value;
            break;
    }
    
    AddToXmlDirect(id, controlType, oid, oid1, oid2, ds, value, text, checked, lookfor, mc);
}
function ProcessLogin()
{
    if (_xmlHttp.readyState == 4) 
    { 
        if (_xmlHttp.status == 200 && _xmlHttp.responseText == "sucess") 
        {
            window.location.reload();
        }
    }
}
