var useSecurePostSecret = true;
window.addEvent('domready', 
	function() {
		
		if (!useSecurePostSecret)
		{
			return;
		}

		var series = "";
		var ac = readCookie('auth');
		if (ac == null) ac = readCookie('com.quantia.user');
		if (ac != null)
		{
			var pieces = ac.split('___');
			if (pieces.length > 1)
			{
				plsplt = pieces[1];
				series = plsplt.split('_')[0];
			}
		}
		if (series != "")
		{
			var now = new Date().realGetTime();
			var postSecretRefresh = readCookie('postSecretRefresh');
			var securePostSecretClientTimestamp = now;
			if (postSecretRefresh != null)
			{
				var pieces = postSecretRefresh.split(',');
				if (pieces.length > 1)
				{
					securePostSecretClientTimestamp = Number(pieces[0]);
					securePostSecretExpires = Number(pieces[1]);
					if (securePostSecretClientTimestamp + securePostSecretExpires < now)
					{
						securePostSecretClientTimestamp = now;
					}
				}
			}
		    var s = document.createElement('script');
		    s.src = 'https://' + QSettings._secureDomain + '/getSecurePostSecret?s=' + series + "&t=" + securePostSecretClientTimestamp;
		    document.getElementsByTagName('head')[0].appendChild(s);
		}
		else
		{
			secureTimeDelta = 0;
			createCookie('postSecretRefresh', '', -1);
		}
});

var HTTP = {};

HTTP._factories = [
    function() { return new XMLHttpRequest();},
	function() { return new ActiveXObject("Msxml2.XMLHTTP");},
	function() { return new ActiveXObject("Microsoft.XMLHTTP");}
];

HTTP._factory = null;
HTTP._requestList = new Array();

window.addEvent('unload',function(){
	if (HTTP._requestList != null)
	{
		HTTP.cleanUpRequests();
	}
});

HTTP.createRequest = function() 
{
	var request  = null;

	if (HTTP._factory == null) 
	{
		for (var i=0; i < HTTP._factories.length; i++)
		{
			try
			{
				var factory = HTTP._factories[i];
				request = factory();
				if (request != null  && request != undefined)
				{
					HTTP._factory = factory;
					break;
				}
			}
			catch(e)
			{

			}
		}
	}
	else 
	{
		request  = HTTP._factory();
	}
	
	if (request != null)
	{
		if (HTTP._requestList != null)
		{
			HTTP._requestList.push(request);
		}
		return(request);
	}
	else
	{
	    //alert("Error creating request object!");
		return(null);
	}
};

HTTP.cleanUpRequests = function()
{
	for (var i = 0; i < HTTP._requestList.length; i++)
	{
		try
		{
			HTTP._requestList[i].onreadystatechange = null;
			cleanUp(HTTP._requestList[i]);
		}
		catch (e)
		{
			return;
		}
	}
}

HTTP.getSynchronous = function(url)
{
	var request = HTTP.createRequest();
    request.open("GET", url, false);
    // Encode the properties of the values object and send them as
    // the body of the request.
	request.setRequestHeader('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
    request.send(null);
    return request.responseText;
};

HTTP.getXml = function(url,callback, errorCallback) 
{
	var request = HTTP.createRequest();
	request.onreadystatechange = function()
	{
		try 
		{
			if(request.readyState == 4)
			{
				if ((request.status == 200 || request.status == 0))
				{
					if(request.responseXml == undefined || request.responseXml == null)
					{ 
						callback(XML.CreateDocument(request.responseText),request.responseText);		
					}else
					{
						callback(request.responseXML,request.responseText);		
					}
					request = null;
				}
				else if (request.status == 304) // NOT MODIfIED? pretend it is empty
				{
					callback(XML.CreateDocument("<notModified></notModified>"), "<notModified></notModified>");
				}
				else
				{
					if (errorCallback != null)
						errorCallback(request.status);
				}
			}
		}
		catch (e)
		{
			if (errorCallback != null)
				errorCallback(e);
		}
	};
	try
	{
		request.onerror = function()
		{
			if (errorCallback != null)
				errorCallback();
		};
	} catch(e) {}
	request.open("GET",url,true);
	request.setRequestHeader('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
	var f = request.send(null);
};

HTTP.getText= function(url,callback) 
{
	var request = HTTP.createRequest();
	request.onreadystatechange = function()
	{
		if(request != null && request.readyState == 4 && (request.status == 200 || request.status == 0))
		{
		    if(callback != null)
    			callback(request.responseText);		

			request = null;
		}
	};
	request.open("GET",url,true);
	request.setRequestHeader('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
	request.send(null);
};

HTTP.resolveHtmlValues= function(html, strDataformID, callback) 
{
	var tmpHtml = html;
	var url = QSettings.BuildUrlCmd("gethtmlvoucherparams")+ "&df=" + strDataformID;
	
	var request = HTTP.createRequest();
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200)
		{
			var resp = request.responseText;
			if(resp == null)
				return;
			var names = resp.split(',');
			for(var i = 0;  i < names.length; i++)
			{
				var name = names[i].split('=');
				if(name[0] == 'pname')
				{
					tmpHtml = tmpHtml.replace("{$%patient_name%$}", name[1]);
				}
				else if(name[0] == 'dname')
				{
					tmpHtml = tmpHtml.replace("{$%ref_by_doctor_name%$}", name[1]);
				}
			}
			request = null;
			callback(tmpHtml);
		}
	};
	request.open("GET",url,true);
	request.setRequestHeader('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
	request.send(null);
	
};


/**
 * Send an HTTP POST request to the specified URL, using the names and values
 * of the properties of the values object as the body of the request.
 * Parse the server's response according to its content type and pass
 * the resulting value to the callback function.  If an HTTP error occurs,
 * call the specified errorHandler function, or pass null to the callback
 * if no error handler is specified.
 **/
HTTP.post = function(url, strPostInfo, callback, errorHandler) {
    //alert(strPostInfo);
    var request = HTTP.createRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                callback(request.responseText);

				request = null;
            }
            else {
                if (errorHandler) errorHandler(request.status,
                                               request.statusText);
                else callback(null);

				request = null;
            }
        }
    };

    request.open("POST", url);
    // This header tells the server how to interpret the body of the request
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
   	if (!HTTP.addSecurityHeaders(request, url, strPostInfo))
   	{
   		if (typeof errorhandler == 'undefined')
   			errorhandler = null;
   	    
		setTimeout(function() {HTTP.post(url, strPostInfo, callback, errorhandler);}, 500);
		return;
	}

    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(strPostInfo);
};

HTTP.postAsXml = function(url, strPostInfo, callback, errorHandler) {
    //alert(strPostInfo);
    var request = HTTP.createRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                callback(request.responseText);

				request = null;
            }
            else {
                if (errorHandler) errorHandler(request.status,
                                               request.statusText);
                else callback(null);

				request = null;
            }
        }
    };

    request.open("POST", url);
    // This header tells the server how to interpret the body of the request
    request.setRequestHeader("Content-Type",
                             "text/xml");
    if (!HTTP.addSecurityHeaders(request, url, strPostInfo))
    {
    	if (typeof errorhandler == 'undefined')
    		errorhandler = null;
    	
		setTimeout(function() {HTTP.post(url, strPostInfo, callback, errorhandler);}, 500);
		return;
    }

    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(strPostInfo);
};


HTTP.postXmlSynchronous = function(url, strPostInfo) {
    //alert(strPostInfo);
    var request = HTTP.createRequest();
    request.open("POST", url, false);
    // This header tells the server how to interpret the body of the request
    request.setRequestHeader("Content-Type",
                             "text/xml");
    if (!HTTP.addSecurityHeaders(request, url, strPostInfo))
    {
    	return '';
    }

    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(strPostInfo);
    return request.responseText;
};

HTTP.postSynchronous = function(url, strPostInfo) {
    //alert(strPostInfo);
    var request = HTTP.createRequest();
    request.open("POST", url, false);
    // This header tells the server how to interpret the body of the request
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
    if (!HTTP.addSecurityHeaders(request, url, strPostInfo))
    {
    	return '';
    }
    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(strPostInfo);
    return request.responseText;
};

HTTP.hasSecureSecret = function()
{
	if (typeof secureTimeDelta == 'undefined' || secureTimeDelta == 0)
		return false;
	return true;
};

HTTP.usingNewSecurePost = function()
{
	var c = readCookie("auth");
	if (c != null) return true;
};

// returns status = true if ok, false if retry would be required
HTTP.addSecurityHeaders = function(request, url, strPostInfo)
{
	if (url.indexOf("https:") > -1)
	{
		return true;
	}

	var usingNewSecurePost = HTTP.usingNewSecurePost();
	if (!HTTP.hasSecureSecret())
	{
		if (usingNewSecurePost)
		{
			return false;
		}
		return true;
	}
	if (!usingNewSecurePost)
		LoginCredentials.ConvertOldToNewCookie();
	
	var now = new Date().realGetTime();
	var currentServerTime = now + secureTimeDelta;
	
	// Take off the last 5 digits (of the time as a string)
	// as a way of reliably dividing by 100,000
	// use that "metric minute" as the time on the server, too, 
	// to give us +/- a few hundred seconds of clock drift every hour
	 
	var currentServerMinutes = "" + currentServerTime;
	var len = currentServerMinutes.length;
	currentServerMinutes = currentServerMinutes.substr(0, len - 5);
	var strSecret = securePostSecret + currentServerMinutes;
	var hashedSecret = SHA1(strSecret);
	var stringToHash = trim(strPostInfo) + securePostSecret;
	var hashedSignature = SHA1(stringToHash);
	request.setRequestHeader("x-quantia-post", hashedSecret);
	request.setRequestHeader("x-quantia-stime", currentServerMinutes);
	request.setRequestHeader("x-quantia-signature", hashedSignature);
	return true;
};

var XML = {};
XML.CreateDocument = function(strXml)
{
	try
	{
		return (new DOMParser()).parseFromString(strXml, "text/xml");	
	}
	catch(e)
	{
	}
	try
	{
		var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.loadXML(strXml);
		return xmlDoc;
	}
	catch(e)
	{

	}

		/*
	if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("", "", null);

	}
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = tmp;
 	}
	else
	{
		alert('Your browser can\'t handle this script');
		return;
	}
	alert("123");
	xmlDoc.loadXML(request.responseText);
	alert("124");	*/
};

XML.MakeSureDocumentIsNormalized = function(xmlDoc)
{
    if (window.gecko) 
    {
        if ((xmlDoc != null) && (xmlDoc.hasBeenNormalized != true))
        {
            xmlDoc.hasBeenNormalized = true;
            xmlDoc.normalize();
        }
    }
}

XML.GetElementsByTagNameOneLevel = function(xmlElem, strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    if (xmlElem["childNodes"] != null)
    {
		var results = new Array();
		var j = 0;
        var childCount = xmlElem.childNodes.length;
        for (var i = 0; i < childCount; ++i)
        {
            var child = xmlElem.childNodes[i];
            if (child.nodeName == strValue)
            {
                results[j++] = child;
            }
        }
        return results;
    }
    return null;
}

XML.GetElementByTagNameOneLevel = function(xmlElem, strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    if (xmlElem["childNodes"] != null)
    {
        var childCount = xmlElem.childNodes.length;
        for (var i = 0; i < childCount; ++i)
        {
            var child = xmlElem.childNodes[i];
            if (child.nodeName == strValue)
            {
                return child;
            }
        }
    }
    return null;
}

XML.FindAndFillValueOneLevel = function(xmlElem,strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        if(strValue == null)
        {
            tmp = xmlElem;
        } else
        {
			var tmp = null;
			for (var i = 0; i < xmlElem.childNodes.length; i++)
			{
				if (xmlElem.childNodes[i].nodeName == strValue)
				{
					tmp = xmlElem.childNodes[i];
					break;
				}
			}
        }
        if(tmp != null)
        {   
			var result = "";
			for (var i = 0; i < tmp.childNodes.length; i++)
			{
				if (tmp.childNodes[i].nodeType == 3) // if it's a text node
				{
					result += tmp.childNodes[i].nodeValue;
				}
			}
			return result;
        }
    }catch(e)
    {
    } 
    return "";
};

XML.FindAndFillValue = function(xmlElem,strValue,unescapeText)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        if(strValue == null)
        {
            tmp = xmlElem;
        } else
        {
            var tmp = XML.GetFirstElementByTagName(xmlElem,strValue);
        }
        if(tmp != null)
        {   
			var result = "";
			for (var i = 0; i < tmp.childNodes.length; i++)
			{
				if ((tmp.childNodes[i].nodeType == 3) || // if it's a text node
				    (tmp.childNodes[i].nodeType == 4)) // or it's a CDATA node
				{
					result += tmp.childNodes[i].nodeValue;
				}
			}
			
			if (unescapeText == true)
			{
				return unescape(result);
			}
			return result;
        }
    }catch(e)
    {
    } 
    return "";
};
XML.SetNodeValue = function(xmlElem,strValue)
{
    var tmp2 = xmlElem.childNodes[0];
    tmp2.nodeValue = strValue;
};
XML.FindAndFillValueInt = function(xmlElem,strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var strRes = XML.FindAndFillValue(xmlElem,strValue);
        if(strRes.length>0)
            return parseInt(strRes,10);
    }catch(e)
    {
    } 
    return -1;
};
XML.FindAndFillValueFloat = function(xmlElem,strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var strRes = XML.FindAndFillValue(xmlElem,strValue);
        if(strRes.length>0)
            return parseFloat(strRes);
    }catch(e)
    {
    }         
    return -1.0;
};
XML.FindAndFillValueBool = function(xmlElem,strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var strRes = XML.FindAndFillValue(xmlElem,strValue);
        if(strRes == "true")
            return true;
        if(strRes == "false")
            return false;
    }catch(e)
    {
    }         
    return null;
};
XML.HasElementByTagName = function(xmlElem,strValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var tmp = XML.GetFirstElementByTagName(xmlElem,strValue);
        if(tmp != null)
            return true;
    }catch(e)
    {
    }       
    return false;
};

XML.GetAttributeFromTag = function(xmlElem,strTagName,strAttributeName,defaultValue)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        //given an XML node/element, finds the tag within the node,
        //then finds the specified attribute of that tag
        //eg. if you want to find value from qpoint, strTagName = qpoint,
        //strAttributeName = value;
        //<qpoint value="3.5" qp_edts="" qp_id="1" /> 
        var tmp = XML.GetFirstElementByTagName(xmlElem,strTagName);
        if(tmp != null)
        {   
            var tmp2 = tmp.getAttribute(strAttributeName);
            if(tmp2 != null)
            {
                return tmp2;
            }
        }      
    }catch(e)
    {
    } 
	if (defaultValue == null)
	{
		defaultValue = "";
	}
    return defaultValue;
};

XML.GetFirstElementByTagName = function(xmlElem,strTagName)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var elemList = XML.GetElementsByTagName(xmlElem,strTagName);
        if(elemList != null)
            return elemList[0];
    }catch(e)
    {
    } 
    return null;
};
XML.GetFirstElementByTagNameOneLevel = function(xmlElem,strTagName)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);

    try
    {
        var elemList = XML.GetElementsByTagName(xmlElem,strTagName);
        if (elemList != null)
		{
			for (var i = 0; i < elemList.length; i++)
			{
				if (elemList[i].parentNode == xmlElem)
				{
            		return elemList[i];
				}
			}
		}
    }catch(e)
    {
    } 
    return null;
};
XML.GetElementsByTagName = function(xmlElem,strTagName)
{
    XML.MakeSureDocumentIsNormalized(xmlElem);
    
    try
    {
        var elemList = xmlElem.getElementsByTagName(strTagName);
        if(elemList != null && elemList.length >0)
            return elemList;
    }catch(e)
    {
    } 
    return null;
};
XML.Serialize = function(node)
{
    if(typeof XMLSerializer != "undefined")
        return (new XMLSerializer()).serializeToString(node);
    else if (node.xml) return node.xml;
    else alert("XML.Serialize is not supported or can't serialize " + node);
};
XML.StripCDataFromText = function(strCDataText)
{
    var idxStart = strCDataText.indexOf("<![CDATA[")+9;
    var idxEnd = strCDataText.indexOf("]]>");
    return strCDataText.substring(idxStart,idxEnd);
};
XML.CreateCDataNode = function(xmlDoc, strText)
{
	return xmlDoc.createCDATASection(strText.replace(/]]>/g, "..."));	
};

XML._escapesBadCharacters = null;
XML.CreateTextNode= function(xmlDoc, strText)
{
    if (XML._escapesBadCharacters == null)
    {
        var xmlDoc = XML.CreateDocument("<x></x>");
        var yElem = xmlDoc.createElement("y");
        yElem.appendChild(xmlDoc.createTextNode("<"));
        xmlDoc.documentElement.appendChild(yElem);
        XML._escapesBadCharacters = (XML.Serialize(xmlDoc).indexOf("<x><y>&lt;</y></x>") > -1);
    }
    if (!XML._escapesBadCharacters)
    {
        strText = XML.RemoveBadXMLCharacters(strText);
    }
    return xmlDoc.createTextNode(strText);
};
XML.RemoveBadXMLCharacters = function(strText)
{
    strText = strText.replace(/&/g, "&amp;");
    strText = strText.replace(/</g, "&lt;");  
    strText = strText.replace(/>/g, "&gt;");
    return strText;
};


var DOM = {};
DOM.ClearChildren = function(xmlElem)
{
    if(xmlElem == null || xmlElem == false)
        return;
    while(xmlElem.hasChildNodes()) 
    {
        var fc = xmlElem.firstChild;
        xmlElem .removeChild(fc);      
    } 
};
DOM.RemoveFromDOM = function(xmlElem)
{
    if(xmlElem == null || xmlElem == false)
        return;
    var parent = xmlElem.parentNode;
    parent.removeChild(xmlElem);
};
DOM.SetVisible = function(domElem, bVisible, /*optional*/widthHeightStyle)
{
    domElem.style.visibility = bVisible ? "visible" : "hidden";
    if(widthHeightStyle != undefined)
    {
        domElem.style.width = widthHeightStyle;
        domElem.style.height = widthHeightStyle;
    }
};

//gets XML, either from XML Data Island, or From Server
DOM.GetXml = function(url, funcCallback)
{
 	var xmlIsland = DOM.GetXmlDataIsland();
 	if(xmlIsland != null)
 	    funcCallback(xmlIsland);
 	else
 	    HTTP.getXml(url, funcCallback);   
};

DOM.GetXmlDataIsland = function(strName)
{
	if ($(strName) != null)
	{
		var value = $(strName).innerHTML;
				
		value = value.replace(/^\s+/,"").replace(/&nbsp;/g, " ");
		
		// safari treats "&" different than other browsers... messes up parsing if we don't do this
		if ((navigator.userAgent.toLowerCase().indexOf("safari") != -1) && (navigator.userAgent.toLowerCase().indexOf("chrome") == -1))
		{
			value = value.replace(/&/g, "&amp;");
		}
		else
		{
			value = value.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
		}
		
		value = value.replace(/QQltQQ/g, "&lt;").replace(/QQgtQQ/g, "&gt;").replace(/QQquotQQ/g, "&quot;");
				
		var result = XML.CreateDocument(value); 
		
		return result;
	}
	
    try {
	  if(strName == undefined)
	  	strName = 'embeddedXmlData';
      if(window[strName])
      {
        if(window[strName] != undefined && window[strName].length>0)
        {
            var doc =  XML.CreateDocument(window[strName]);
            window[strName] = '';
            return doc;
        }
      }
    }catch(e){};
/*    var xmlData = document.getElementById("xmlData");
    if(xmlData == null)
	return null;
    if(xmlData.XMLDocument != undefined)
        var xmlDoc = xmlData.XMLDocument;
    else
    {
        var strXml = xmlData.innerHTML;
        xmlDoc = XML.CreateDocument(strXml);
    }
    return xmlDoc;
 */  
 	return null;
    //var xmlDoc = document.getElementById("xmlData").XMLDocument;// all("testXML").XMLDocument;
};
/* -- doesn't work in IE6
DOM.GetFirstChildElemByName = function(currentNode,strName)
{
    if(currentNode.nodeType != 1)
    {
        return null;
    }
    var res = XML.GetElementsByTagName(currentNode
    if(XML.GetElementsByTagName(current
    if(currentNode.getAttribute('name') == strName)
        return currentNode;
    for(var i=0;i<currentNode.childNodes.length;i++)
    {
        var res= DOM.GetFirstChildElemByName(currentNode.childNodes[i],strName);
        if(res != null)
            return res;
    };
    return null;
};*/

DOM.ConvertAllLinksToOpenInNewWindow = function(parentNode)
{
    function openInNewWindow() { 
        // Change "_blank" to something like "newWindow" to load all links in the same new window 
        var newWindow = window.open(this.getAttribute('href'), '_blank'); 
        newWindow.focus(); 
        return false; 
    } 

    if(parentNode == null)
        parentNode = document;
    var links = $(parentNode).getElements('a'); // get all anchors within parentNode
    
    for (var i = 0; i < links.length; i++) { 
        var link = $(links[i]);
        if(link.quantiaLink != true && link.onclick == 'undefined') 
            link.onclick = openInNewWindow; 
    } 
};


var DocumentUtils= {};
DocumentUtils.CreateALink = function(strLinkLocation,strInnerText,bNewWindow,windowArguments)
{
  //  function openInNewWindow() { 
  //      alert('here');
  //      return false; 
  //  } 
    //',width=960,height=665, resizable=no, scrollbars=no,location=yes,toolbar=no,status=no,menubar=no, left=20, top=20'
	var newElt = new Element('a');
	newElt.quantiaLink = true;
	newElt.href = strLinkLocation;
	if(bNewWindow)
    	newElt.onclick = function() {var win=window.open(strLinkLocation, "_blank",windowArguments);win.focus();return false;};
	newElt.appendChild(document.createTextNode(strInnerText));
	return(newElt);
	/*
    var link = document.createElement('a');//new Element('a');
    link.href = strLinkLocation;
    if(bNewWindow == true)
    {
        link.onclick = 
             function()
            {
                var win=window.open(strLinkLocation, "_blank",'width=960,height=665, resizable=no, scrollbars=no,location=yes,toolbar=no,status=no,menubar=no, left=20, top=20');
                win.focus();
                return false;
            };;
    }
         

    link.innerHTML = strInnerText;
    return link;*/
};

