//[ Constants for Message Box ] --------------------------------------------------------------------------------------
var CONST_BUTTON_OKONLY				= 0;
var CONST_BUTTON_CANCELONLY			= 1;
var CONST_BUTTON_OKCANCEL			= 2;
var CONST_BUTTON_OKCANCELDELETE		= 3;
var CONST_BUTTON_ABORTRETRYCANCEL	= 4;
var CONST_BUTTON_RETRYCANCEL		= 5;
var CONST_BUTTON_INFORMATION		= 6;
var CONST_BUTTON_ERROR				= 7;

var CONST_MESSAGE_OK				= "OK";
var CONST_MESSAGE_CANCEL			= "CANCEL";
var CONST_MESSAGE_DELETE			= "DELETE";
var CONST_MESSAGE_RETRY				= "RETRY";
var CONST_MESSAGE_ABORT				= "ABORT";
//[ End of constants for Message Box ] --------------------------------------------------------------------------------------
var DialogWindow	= null;
var SessionExpired	= false;
var oPopup			= null;
var ModalDialogWindow_Default	= "center:yes;help:no;resizable:yes;status:no;scroll:yes;toolbar:no;";

//Common.js merge
var CallInitialize = false;
var IsPageEdited   = false;
var placeHolder;
var request;
var encrypted;
var firstPageLoad	= true;
var ClientMessages	= null;
var popupReturned	= false;

var agent			= navigator.userAgent.toLowerCase();
var majorVersion	= parseInt(navigator.appVersion);
var minorVersion	= parseFloat(navigator.appVersion);

var isIE6plus		= agent.indexOf("msie") > -1 && majorVersion != 3 && majorVersion != 5 && minorVersion != .5;
var isMozillas		= agent.indexOf("firefox") > -1;

function stripTags(str)
{
    var pat = /\<.*?\>/g
    str = str.replace(pat,"");
    return str;
}
//### general request builder
function buildRequest(url, async, data)
{
    var r;

    if (window.XMLHttpRequest)
    {
        r = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        r = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (r)
    {
        r.open("POST", url, async);
        r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        r.setRequestHeader("Content-length", data ? data.length : 0);
        r.setRequestHeader('Referer', document.location);
    }
    return r;
}

//### Exception explorer
function reportException(e, target)
{
    for(var i in e)
    {
        $(target).innerHTML += "<br>"+ i + "="+eval("e."+i);
    }
}

Array.prototype.contains = function(searchVal) { 
    var str = this.join(';');
    str += ';';
    return str.indexOf(searchVal+";") > -1;
}

//######### trim() function for JavaScript
String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, '');
};

//######### endsWith()
String.prototype.endsWith = function(str)
{
	return this.lastIndexOf(str) == this.length - str.length;
};

//######### startsWith()
String.prototype.startsWith = function(str)
{
	return this.substring(0,str.length) == str;
};

//######### equals()
String.prototype.equals = function(str)
{
	return this == str;
};

function isNullOrEmpty(s)
{
    if(!s) return true;
    var copy;
    if(typeof(s) != "String")
        copy = s.toString().trim();
    else
        copy = s.trim();
    return copy == "";
}

//### generic get functionality
function $(sender)
{
    return document.getElementById(sender);
}

var exSortKey,
    exSortType,
    exOrder,
    exDataType;
    
//##### Returns transformed XSL in the form of HTML element
function transformXsl(xsl, async, target, xmlDocument, targetDocument, sortKey, sortType, sortOrder, dataType, startTime, endDataTime ,refresh)
{
    var searchXSL;
	var startTime	= startTime || new Date().getTime(), 
		endDataTime	= endDataTime || 0, 
		endTime;
	//return;
	if (window.XSLTProcessor) 
	{
		if(!searchXSL || refresh) 
		{
			searchXSL 			= document.implementation.createDocument("", "", null);
			searchXSL.async		= async;
			searchXSL.load(xsl);
		}
		if(sortKey && sortType)
		{
		    exSortKey   = sortKey;
		    exSortType  = sortType;
		    searchXSL.selectNodes("//*[@order]")[sortType].setAttribute("select",sortKey);
			var order   = searchXSL.selectNodes("//*/@order")[sortType];
			
			order.nodeValue = sortOrder ? sortOrder : (order.nodeValue == "ascending") ? "descending" : "ascending";
			exOrder     = order.nodeValue;
			xmlDocument.documentElement.setAttribute("sort",sortKey);
			xmlDocument.documentElement.setAttribute("order",order.nodeValue);
            xmlDocument.documentElement.setAttribute("data-type",dataType);

			searchXSL.selectSingleNode("//*[@data-type]").setAttribute("data-type",dataType);
			
        }
		
		endDataTime			= new Date().getTime();
		var xsltProcessor	= new XSLTProcessor();
		xsltProcessor.importStylesheet(searchXSL);
		var transformed		= xsltProcessor.transformToFragment(xmlDocument, (targetDocument || document));
		target.innerHTML	= ""; 
		target.appendChild(transformed);
	    transformed = null;
		endTime				= new Date().getTime();
	}
	else if(window.ActiveXObject) 
	{
		if(!searchXSL || refresh) 
		{
			searchXSL 		= new ActiveXObject("Microsoft.XMLDOM");
			searchXSL.async = async;
			searchXSL.load(xsl);
		}
		
		if(sortKey && sortType)
		{
			exSortKey   = sortKey;
		    exSortType  = sortType;
			searchXSL.selectNodes("//*[@order]")[sortType].setAttribute("select",sortKey);
			var order   = searchXSL.selectNodes("//*/@order")[sortType];
			order.nodeValue = sortOrder ? sortOrder : (order.nodeValue == "ascending") ? "descending" : "ascending";
			exOrder     = order.nodeValue;
			xmlDocument.documentElement.setAttribute("sort",sortKey);
			xmlDocument.documentElement.setAttribute("order",order.nodeValue);
            xmlDocument.documentElement.setAttribute("data-type",dataType);
			
			searchXSL.selectSingleNode("//*[@data-type]").setAttribute("data-type",dataType);
        }
	 
	    endDataTime			= new Date().getTime();
		target.innerHTML	= xmlDocument.transformNode(searchXSL); 
		endTime				= new Date().getTime();
	}
	xmlDocument = null;
	searchXSL   = null;
	//recordMetrics($("spnTimeTaken"), startTime, endDataTime, endTime);
	//return target;
}

function ImageSwap(obj)
{
	if (obj.mouseoverimage)
	{
		var imageSource = obj.src
		obj.src = obj.mouseoverimage;
		//store the original image source so the image can be swapped back
		obj.mouseoverimage = imageSource;
	}
	
}

function click_element(t)
{
    if (t)
    {
        if (typeof(t.fireEvent) != "undefined")
        {
            var e = document.createEventObject();
            e.srcElement = t;
            e.type = "click";
            t.fireEvent("onclick", e);
        }
        else if (typeof(t.dispatchEvent) != "undefined")
        {
            var e = document.createEvent("MouseEvents");
            e.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, t);
            t.dispatchEvent(e);
        }
    }
}

function create_document(b)
{
    var d = document.implementation.createDocument ? document.implementation.createDocument('', '', null) : new ActiveXObject("Msxml2.Domdocument.3.0");
    if (d)
    {
        d.async = b;
    }
    return d;
}

function create_popup()
{
    var popup;

    if (window.createPopup)
    {
        popup = window.createPopup();
    }
    else
    {
        popup = document.createElement('div');

        popup.content = document.createElement('div');
        popup.hidden = document.createElement('input');
        popup.hidden.type = "hidden";

        popup.appendChild(popup.content);
        popup.appendChild(popup.hidden);

        popup.addEventListener("click", function(e) { e.cancelBubble = true; }, false);
        popup.style.position = "absolute";

        popup.hide = function()
        {
            // cannot use 'this'
            if (popup.parentNode)
            {
                popup.parentNode.removeChild(popup);
                document.removeEventListener("click", popup.hide, false);
            }
        }
        popup.show = function(x, y, w, h, owner)
        {
            if (!this.parentNode)
            {
                document.addEventListener("click", popup.hide, false);
                owner.appendChild(this);
            }
            this.hidden.focus();
            this.style.left = x;
            this.style.height = h;
            this.style.top = y;
            this.style.width = w;
        }
    }
    return popup;
}

function each_node(xml, xpath, f, v)
{
    if (xml && typeof(f) == "function")
    {
        var d = xml.ownerDocument ? xml.ownerDocument : xml;

        if (typeof(d.evaluate) == "function")
        {
            var nodes = d.evaluate(xpath, xml, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            if (nodes)
            {
                for (var i = 0; i < nodes.snapshotLength; i++)
                {
                    v = f(nodes.snapshotItem(i), v);
                }
            }
        }
        else
        {
            var nodes = xml.selectNodes(xpath);
            if (nodes)
            {
                for (var i = 0; i < nodes.length; i++)
                {
                    v = f(nodes[i], v);
                }
            }
        }
    }
    return v;
}

// cover each frame in document with transparent layer
// used in implementation of modal dialogs in firefox
function enable(doc, flag)
{
    if (doc)
    {
        if (doc.body.tagName == "FRAMESET")
        {
            var frames = doc.getElementsByTagName("FRAME");
            for (var i = 0; i < frames.length; i++)
            {
                var frame = frames[i];
                if (frame)
                {
                    if (flag)
                    {
                        frame.scrolling = frame.scrolling_saved;
                    }
                    else
                    {
                        frame.scrolling_saved = frame.scrolling;
                        frame.scrolling = "no";
                    }
                    enable(frame.contentDocument, flag);
                }
            }
        }
        else
        {
            if (flag)
            {
                if (doc.mask)
                {
                    doc.mask.style.display = "none";
                    doc.onkeypress = null;
                }
            }
            else
            {
                if (!doc.mask)
                {
                    var mask = doc.createElement('div');
                    mask.style.backgroundColor = "transparent";
                    mask.style.height = "100%";
                    mask.style.left = "0px";
                    mask.style.position = "fixed";
                    mask.style.top = "0px";
                    mask.style.width = "100%";
                    doc.body.appendChild(mask);
                    doc.mask = mask;
                }
                doc.mask.style.display = "block";
                doc.onkeypress = function(e) { return e.keyCode != 9; }
            }
        }
    }
}

function find_message(name, defval)
{
    var f = window.top.TopFrame;
    var m = f ? f.window.document.getElementById("Messages") : null;
    return get_attribute(m, name, defval);
}

function find_node(xml, xpath)
{
    return each_node(xml, xpath, function (n, v) { return v ? v : n; }, null);
}

function form_request(url, async, data)
{
    var r;

    if (window.XMLHttpRequest)
    {
        r = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        r = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (r)
    {
        r.open("POST", url, async);
        r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        r.setRequestHeader("Content-length", data ? data.length : 0);
        r.setRequestHeader('Referer', document.location);
    }
    return r;
}

function get_attribute(e, name, f)
{
    var a = e ? e.getAttribute(name) : null;
    return a != null ? a : (typeof(f) == "function" ? f() : f);
}

function get_eventkey(e)
{
    if (!e)
    {
        e = window.event;
    }
    return e ? (e.keyCode ? e.keyCode : e.charCode) : null;
}

function get_eventtarget(e)
{
    if (!e)
    {
        e = window.event;
    }
    return e ? (e.srcElement ? e.srcElement : e.target) : null;
}

function get_text(e)
{
    return e ? (e.innerText != null ? e.innerText : e.textContent) : null;
}

// in mozilla xml island will have "rawdata" attribute sent from server
// create xml document from this attribute and attach it to xml island
// needed for firefox compatibility
function get_xml_island(e, f)
{
    if (e && !e.xmldoc && typeof(e.documentElement) == "undefined")
    {
        var p = new DOMParser();
        e.xmldoc = p.parseFromString(get_attribute(e, "rawdata", f), "text/xml");
    }
    return e && e.xmldoc ? e.xmldoc : e;
}

function set_text(e, s)
{
    if (e)
    {
        if (e.innerText != null)
        {
            e.innerText = s;
        }
        else
        {
            e.textContent = s;
        }
    }
}

function show_modal(url, w, h, f)
{
    try
    {
        if (window.showModalDialog)
        {
            var r = window.showModalDialog(url, window, "dialogHeight:" + h + "px;dialogWidth:" + w + "px;status:no;" + ModalDialogWindow_Default);
            if (typeof(f) == "function")
            {
                f(r);
            }
        }
        else
        {
            if (!window.popup)
            {
                var interval = function()
                {
                    if (!window.popup || window.popup.closed)
                    {
                        window.clearInterval(window.interval);
                        enable(window.top.document, true);

                        if (typeof(f) == "function")
                        {
                            f(window.returnValue);
                        }
                        window.popup = null;
                        window.returnValue = null;
                    }
                }
                window.onbeforeunload = function()
                {
                    if (window.popup)
                    {
                        window.popup.close();
                        window.popup = null;
                    }
                }
                enable(window.top.document, false);
                window.popup = window.open(url, "popup", "height=" + h + ",width=" + w + ",dialog=yes,modal=yes,scrollbars=yes");
                window.interval = window.setInterval(interval, 1000);
            }
            else
            {
                window.popup.focus();
            }
        }
    }
    catch (e)
    {
        alert(e);
    }
}

function size_to_content(iframe)
{
    if (iframe && iframe.tagName == "IFRAME" && iframe.contentWindow)
    {
        var s = document.createElement("span");

        s.innerHTML = iframe.contentWindow.document.body.innerHTML;
        s.style.position = "absolute";
        s.style.visibility = "hidden";

        document.body.appendChild(s);
        iframe.style.height = s.scrollHeight;
        iframe.style.width = s.scrollWidth;
        document.body.removeChild(s);
    }
}

function toggle_display(id)
{
    var e = $(id);
    if (e)
    {
        e.style.display = e.style.display == "none" ? "" : "none";
    }
}

function formatThousands(val,sep,dec)
{
	var T='', S=val.toString(), L, C, j;
	var spl=S.split(dec);
	var e;
	S = spl[0];
	L=S.length-1;
	if(spl.length > 1)
		e = spl[1];
	for (j=0; j<=L; j++)
	{
		T += C = S.charAt(j);
		if ((j < L) && ((L-j) % 3 == 0) && (C != '-') && parseFloat(S) >= 1000) 
			T += sep;
	}
	if(T.substr(T.length-1,T.length) == sep)
		T = T.substr(0,T.length - 1);
	return T + (e && spl.length > 1 ? dec + e : "");
}

//### encoding to pass client side XML data to server
function encodeForXml(sender)
{
	sender = sender.replace(/\</g,changeParam("<")).replace(/\>/g,changeParam(">"));
	return sender.replace(/\;/g,changeParam(";")).replace(/\:/g,changeParam(":")).replace(/\&/g,changeParam("&")).replace(/\"/g,changeParam("\"")).replace(/\'/g,changeParam("\'"));
}

//##### Custom round function to round to specified decimal places
function round(num,decimals)
{
    decimals = decimals ? decimals : 2;
    return Math.round(num*Math.pow(10,decimals))/Math.pow(10,decimals);
}

//########### to save memory leaks, call yourClosure.virtual(sender)
Function.prototype.virtual = function(sender)
{
	if(!window.objects)
	{
		objects		= [];
		functions	= [];
	}
	var func = this;

	var fId = func.fId;
	if(!fId)
		functions[fId = func.fId = functions.length] = func;
	
	var oId = sender.oId;

	if(!oId)
		objects[oId = sender.oId = objects.length] = sender;

	if(!sender.closures)
		sender.closures = []

	var closure = sender.closures[fId]; 
	
	if(closure) //if a combination exists return that
		return closure;

	sender = func = null;

	return objects[oId].closures[fId] = function() { //instantiate the closure for sender/object that has the event
		return functions[fId].apply(objects[oId],arguments); //call apply to emulate usage of "this" as the object instead of function
	}
}

function Logger() 
{
    this.mouseLeftStart =
    this.mouseTopStart =
    this.mouseLeftEnd =
    this.mouseTopEnd =
    this.senderObj  =
    this.senderOldVal =
    this.senderNewVal =
    this.startTime  = 
    this.resource   =
    this.querystring=    
    this.endTime    =    
    this.objectType  = 
    this.controlType  = 
    this.source  = 
    this.timeTaken  = 
    this.req        = null;
    
    this.exception = function(sender){
        //log something (todo)
    }.virtual(this);
    
    this.prepare = function(e,sender)
    {
    
        if($("debug") == null || $("debug").value.toLowerCase().equals("false") ) 
        {
            return;
        }
         
       
            try {
                this.resource           = location.pathname;
                this.mouseLeftStart     = e ? e.x || e.pageX : 0;
                this.mouseTopStart      = e ? e.y || e.pageY : 0;
                this.eventType          = e ? e.type : "load";
                this.source             = agent.indexOf("msie") > -1 ? agent.split(";")[1].toUpperCase() : agent.split(" ")[9];
                this.objectType         = sender ? sender.tagName || sender.nodeName : "generic";
                this.senderObj          = sender ? (sender.id ? sender.id : "unidentified") : 'unavailable';
                this.senderOldVal       = sender ? (sender.value || sender.innerText || (sender.options ? sender.selectedIndex : "unavailable")) : "unavailable";
                this.startTime          = new Date().getTime();//.toGMTString();
            }catch(ex){
                status = 'Debug: Problem preparing the trace, '+ ex.message;
            }
        
    }.virtual(this);
               
    this.entry = function(e,sender)
    {
        if($("debug") == null || $("debug").value.toLowerCase().equals("false") ) 
        {
            return;
        }
         
            
            try {
                //alert(getProperties(sender));
                this.mouseLeftEnd   = e ? e.x || e.pageX : 0;
                this.mouseTopEnd    = e ? e.x || e.pageX : 0;
                this.querystring    = changeParam(location.search); //encode for transport
                this.endTime        = new Date().getTime();
                this.senderNewVal   = sender ? (sender.value || sender.innerText || (sender.options ? sender.selectedIndex : "unavailable")) : "unavailable";
                if(sender && sender.options)
                    this.senderNewVal = sender.selectedIndex;
                    
                this.timeTaken      = this.endTime - this.startTime;
                
                //build POST params for the handler
                var params = ""
                for(var i in this)
                {
                    var typ = typeof(eval('this.'+i));
                    if( typ != "function" && typ != "object")
                        params += i + "=" + eval('this.'+i) + "&"
                }
                
                this.req                        = buildRequest("Handlers/Instrumentor.ashx",true,params);
                this.req.onreadystatechange     = this.completion;
                this.req.send(params);
            }
            catch(x){
                status = 'Debug: Error recording trace, '+x.message;
            }
            
    }.virtual(this);
    
    this.completion = function()
    {
        if (this.req.readyState == 4 && this.req.status == 200)
			{
				var status_code;
				var status_text;
				try
				{
					status_code = this.req.status;
					status_text = this.req.statusText;
				}
				catch(e) {
				    //reportException(e);
				}
				if (status_code == 200 && this.req.responseText && this.req.responseText.indexOf("Error.aspx") == -1)
				{
				    if(this.req.responseXML)
				    {
				        retrieved = this.req.responseXML;
				        try
				        {
				            status = 'Debug: completed recording using Log object # ' + this.oId;
				        }catch(e){
				            //reportException(e);
				        }
				    }
		        }
		        else
		        {
		            //req = null;
		        }
		 } 
    }.virtual(this);
}

Function.prototype.invoke = function(e, callback) //event object,  plus other arguments
{
    var Log = new Logger();
    var sender     = _(e);
    Log.prepare(e,sender);
    
    //custom logic to insert log object in the call
    var args = new Array();
    for(var i = 0; i< arguments.length;i++)
    {
        if(i == 2)
            args.push(Log);
            
        args.push(arguments[i])
    }
        
    try 
    {
        this.apply(sender,args); //real function call
        if(!callback) 
        {
            Log.entry(e,sender,arguments);
        }
        //else log entry in the asynchronous callback
    }
    catch(exception){ //that could occur in 'apply'
      alert(exception.message);
      Log.entry(e, sender, arguments); //completed or not
      Log.exception(sender);
      //log exception on server side using XMLHTTP and/or display a generic message to user
    }
    //alert("In Wrapper function; Logging ends here");
}

function getProperties(e)
{ 
    var str;
    for(var i in e)
        str += (eval("e." + i)+"<< "+i+"\n")
    return str;
}

function _(e)
{
    var eventSender;
    
    try
    {
        eventSender = e ? (e.srcElement || e.target) ? (e.srcElement || e.target) : e : null;
    }
    catch(e)
    {
        eventSender = null;
    }
    
    return eventSender;
}

/*document.onclick = function(){
    if(isIE6plus)
        if(!event.srcElement.onclick || !event.srcElement.onchange); //alert(event.srcElement.id);
            //track stuff for this kind of element
}*/

//##################Encode
var keyStr		= "ABCDEFGHIJKLMNOP" +
                "QRSTUVWXYZabcdef" +
                "ghijklmnopqrstuv" +
                "wxyz0123456789+/" +
                "=";

var objResizeBar	  = null;
var Col2Resize		  = null;
var StartIndex		  = null;
var EndIndex		  = null;
var Size2Set		  = null;

var ResizeThreshold   = 8;
var EdgeThreshold     = 8;
var SizeThreshold     = 20;

//Function to return the table header when header table is being hovered
function GetTableHeader(objReference)
{
    var oElement = objReference;
    while (oElement && oElement.tagName != null && oElement.tagName != "BODY")
    {
        if ((oElement.tagName.toUpperCase() == "TH") || (oElement.tagName.toUpperCase() == "TD"))
        {
            return oElement;
        }
        oElement = oElement.parentElement;
    }
    return null;
}

var sourceSeparator = find_message("CurrentSeparator", ",");
var targetSeparator = find_message("USEnglishSeparator", ".");

function recordChangedState(e)
{
    if (e && e.style.display != "none" && 0 <= e.selectedIndex && e.selectedIndex < e.options.length)
    {
        var es = e.getElementsByTagName("input");
        var h = es && es.length > 0 ? es[0] : null;
        if (h)
        {
            h.value = e.options[e.selectedIndex].text;
        }
    }
}

function safeCheckStates(e, state, province, radio)
{
    if (e && 0 <= e.selectedIndex && e.selectedIndex < e.options.length)
    {
        checkStates(e.options[e.selectedIndex].value, state, province, radio);
    }
}

//########### Returns the querystring of URL
function getQueryString(collection, delimiter, from)
{
	var args = new Object();
	var pairs = collection.substr(from).split(delimiter);

	for (var i = 0; i < pairs.length; i++)
	{
	
		var pos = pairs[i].indexOf('=');
		if (pos >= 0)
		{
            var p = pairs[i];
			args[p.substring(0, pos)] = unescape(p.substring(pos + 1));
		}
	}
	return args;
}

function uncheckAllIfSelected(sender,allCheckBox)
{
	if(!sender.checked)
	{
		$(allCheckBox).checked = false;
		sender.parentNode.parentNode.style.backgroundColor = "white"
	}
	else
		sender.parentNode.parentNode.style.backgroundColor = "lightgrey"
}

//##### build an xsl request object
function buildXsl(xsl,async)
{
	var sampleXSL;

	if (window.XSLTProcessor)
	{
		sampleXSL		= document.implementation.createDocument("", "", null);
		sampleXSL.async = async;
		sampleXSL.load(xsl);
	}
	else if(window.ActiveXObject)
	{
		sampleXSL		= new ActiveXObject("Microsoft.XMLDOM");
		sampleXSL.async = async;
		sampleXSL.load(xsl);
	}
	return sampleXSL;
}

//##################### Remove input-hidden elements recursively from given element
function removeRecursively(sourceElement, noDeep, onlyBasic)
{
	try
	{
		var children = sourceElement.childNodes;
		var restricted = false;
		
		for(var counter=0;counter<children.length;counter++)
		{
			if(children[counter].nodeName.toLowerCase() == "input" && children[counter].attributes.getNamedItem("type").nodeValue == "hidden")
			{
				if(!onlyBasic || children[counter].parentNode.parentNode.id != "trDataRow")
				{
					sourceElement.removeChild(children[counter]);
				}
			}
			if(!noDeep && children[counter].childNodes.length>0)
			{
				removeRecursively(children[counter], noDeep, onlyBasic);
			}
		}
	}catch(x){} //ignore because some objects might not have these properties	
}

//##################### Disable elements recursively from given element
function changeRecursively(sourceElement, disable, noDeep, onlyBasic)
{
	try
	{
		var children = sourceElement.childNodes;
		var restricted = false;
		
		for(var counter=0;counter<children.length;counter++)
		{
			children[counter].enabled   = !disable;
			children[counter].disabled  = disable;
			
			if(!noDeep && children[counter].childNodes.length>0)
			{
				removeRecursively(children[counter], noDeep, onlyBasic);
			}
		}
	}catch(x){} //ignore because some objects might not have these properties	
}


function stripGroupSeperators(expression, type)
{
    switch (type)
    {
    case "Integer":
    case "Double":
    case "Long":
    case "Float":
    case "Money":
        var s = find_message("GroupSeparator", null);
        if (s != null && s.charCodeAt(0) != 160)
        {
            return expression.replace(eval("/[" + s + "]+/g"), "");
        }
        break;
    }
    return expression;
}

function checkValidity(filterExpression, dataType, dateFormat)
{
	var isValid			= false;
	var numberPattern	= eval("/^\\-?\\d+(\\"+sourceSeparator+"\\d*)?$/");

	switch (dataType)
	{
	case "Integer":
	case "Double":
	case "Long":
	case "Float":
	case "Money":
		filterExpression	= stripGroupSeperators(filterExpression,dataType);
		filterExpression	= filterExpression.replace(/^\s+/g, '').replace(/\s+$/g, '');//removing leading and trailing spaces
		isValid				= numberPattern.test(filterExpression);

		if(isValid)
		{
			filterExpression	= filterExpression.replace(sourceSeparator,targetSeparator);
			isValid				= !isNaN(filterExpression);
		}
		break;

	case "Date":
	case "DateTime":
	case "MonthDate":
		isValid				= isDate(filterExpression,dateFormat);
		break;

	case "String":
		isValid = true;
		break;
	}
	return isValid;
}

function focusInIt(sender)
{
	try { 
		var elems = sender.getElementsByTagName("input");
		for(i=0; i < elems.length; i++)
		{
			if (elems[i].getAttribute("TYPE").toLowerCase() == "text")
			{
				elems[i].focus();
				break;
			}
		}
	}catch(x){}
}
//###### Select the row
function selectItself(senderRow)
{
	with (senderRow.parentNode)
	{
		for (var i = 3; i < rows.length; i++)
		{
			if (rows[i].className == "GridRow")
			{
				rows[i].style.backgroundColor = "white";
			}
		}
	}
	senderRow.style.backgroundColor = "lightgrey";
}

//###### select all checks
function checkAllInClientGrid(e,targetTable)
{
	var rows	= $(targetTable).rows;
	var srcEl	= get_eventtarget(e);
	
	for (var i = 0; i < rows.length; i++)
	{
		var item = rows[i].firstChild.firstChild;
		
		if ((rows[i].className == "GridRow")
		&& (item)
		&& (item.tagName == "INPUT"))
		{
			item.checked	= srcEl.checked;
			if (rows[i].className == "GridRow")
				rows[i].style.backgroundColor = item.checked ? "lightgrey" : "white";
		}
	}
}

//###### Adjust columns in the client grid (not being used)
function adjustColumns(dataRow,headingRow)
{
	for(var i=0;i<dataRow.childNodes.length;i++)headingRow.childNodes[i].width = (dataRow.childNodes[i].width);
}
//######################################
function appendZero(source)
{
	if(source.value.charAt(0) == '.')
		source.value = "0" + source.value;
}

//This Method allows only numeric and decimal entries for a given input of type text
// called on keypress keycode -> event.keyCode, digitsOnly -> false
function isValidKeyPress(e, digitsOnly)
{
	var keyCode = typeof(e) == "object" ? get_eventkey(e) : e;

	return (((keyCode > 47) && (keyCode < 58))
			|| ((!digitsOnly) && ((keyCode == 45/* - */) || (keyCode == 46/* . */) || (keyCode == 43/* + */) || (keyCode == 44/* , */) || (keyCode >= 37 && keyCode <=40) || (keyCode == 8) || keyCode == 9)));
}

function SetFocusToFirstTextBox()
{
	try
	{
		var elems = document.forms[0].getElementsByTagName("input");
		for(i=0; i < elems.length; i++){
			if ((elems[i].getAttribute("TYPE") == "text") && (elems[i].disabled == false))
			{
				elems[i].focus();
				break;
			}
		}
	}
	catch(ex)
	{
	}
}

function checkEnter(e)
{
    if(get_eventkey(e) == 13)
    {
        if(e.tagName == "INPUT" && e.getAttribute("type") == "text")
        return false;
    }
}

function PressButtonOnEnter(e, target)
{
    if (!e)
    {
        e = window.event;
    }
	if (get_eventkey(e) == 13)
	{
		target.click();
		e.cancelBubble = true;
		return false;
	}
}

function CheckRadio(obj, radio_all, radio_specific, prefix, count)
{
	if (obj.checked)
	{
		$(radio_specific).checked = true;
	}
	else
	{
		var b = true;
		for (var i = 0; i < count; i++)
		{
			if ($(prefix + i).checked)
			{
				b = false;
				break;
			}
		}
		$(radio_all).checked = b;
	}
}

//Sets a page change
function TrackChange(object) {
	IsPageEdited = true;
}

//Resets a page change
function ResetPageChange() {
	IsPageEdited = false;
}

function GetChangeFlag()
{
     return IsPageEdited;
}

function SetChangeFlag(NewFlag)
{
IsPageEdited = NewFlag ;

}

//Function to check if a page has been edited.
function ValidatePageChange()
{
    var messages = window.top.TopFrame.MessageControl;
    return !IsPageEdited || messages == null || confirm(messages.getAttribute("UnsavedWork"));
}

//Function to check if a page has been edited. This function is used by the CustomButton class.
//If the user cancel the confirmation box, we do not need to return.
function ValidatePageChangeForButton() {
	
	var Success = ValidatePageChange();
	if (Success) {
		createCookie("nav", "true" ,1);
	}
	return Success;
}

//Core Functions.
//Function to show the message box.
//Input Arguments:
//		DialogType : Determines the type of dialog displayed. Select from the constants above.
//		MessageText: Text to displayed in the dialog box.
function ShowMessage1(DialogType, MessageText, IsDebug)
{
	var MsgPageURL = GetApplicationPath() + "Message.aspx?MessageType=";
	IsDebug = IsDebug ? IsDebug : "false";
	var ReturnVal;
    show_modal(MsgPageURL + DialogType + "&MessageString=" + MessageText + "&Debug=" + IsDebug, 400, 210, function (b) { ReturnVal = b; });
	return ReturnVal;
}

//Function to encode the xml characters
//XMLString  - String to encode
//IgnoreApos - If set to true will ignore encoding apostrophe
function XMLEncode(XMLString, IgnoreApos)
{
	var AposReg = /'/g
	var LtReg	= /</g
	var GtReg   = />/g
	var AmpReg = /&/g
	
	XMLString = XMLString.replace(AmpReg,  "&amp;");
	XMLString = XMLString.replace(LtReg,   "&lt;");
	XMLString = XMLString.replace(GtReg,   "&gt;");	
	
	if(!IgnoreApos){
		XMLString = XMLString.replace(AposReg, "&apos;");
	}
	return XMLString;
}

//############## Cookies (to go in corefunctions)
function getCookieVal (offset) {
         var endstr = document.cookie.indexOf (";", offset);
            if (endstr == -1)
            endstr = document.cookie.length;
         return unescape(document.cookie.substring(offset, endstr));
         }

//################################################
function getRealCookie (name) {
	var start = document.cookie.toLowerCase().indexOf(name.toLowerCase() + "=");
	
	if (start == -1)
		return null;
	
	var end = document.cookie.indexOf( ";", start);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(start + name.length +1, end));
}
     
//#### new func
function GetCookie(name)
{
	return getCookie(name);
}

//#### actual functionality / base support
function getCookie(name)
{
	var realCookie = getRealCookie("ckyWWE");
	if(realCookie)	{
		realCookie += "&";  //appending an '&' at the end
		var indStart = realCookie.toLowerCase().indexOf(name.toLowerCase()+"=")
		if(indStart > -1)
		{
			var indEnd		= realCookie.indexOf("&",indStart);
			var cookieValue	= unescape(realCookie.substring(indStart + name.length+1, indEnd));
			return(decodeBase64(cookieValue));
		}
		else
			return getRealCookie(name);
	}
	else
		return getRealCookie(name);
}

//####################################################
function removeRealCookie(name)
{
	createRealCookie(name,"", (-1*24*60*60*1000));
	document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//####################################################
function removeCookie(name)
{
	var realCookie = getRealCookie("ckyWWE");
	if(realCookie)
	{	
		realCookie += "&";
		var indStart	= realCookie.toLowerCase().indexOf(name.toLowerCase()+"=")
		var indEnd		= realCookie.indexOf("&",indStart);
		
		if(indStart > -1 && indEnd > -1)
		{
			var toBlow		= realCookie.substring(indStart + name.length+1, indEnd)
			realCookie	= realCookie.replace(name+"="+toBlow+"&", "");
	
			if(realCookie.endsWith("&"))
			{
				realCookie = realCookie.substring(0, realCookie.length - 1);
			}
			createRealCookie("ckyWWE",realCookie);
		}
	}
}

//########
function createRealCookie(name,value,milliseconds)
{
    var expires = "";
	if (milliseconds) {
		var date = new Date();
	    date.setTime(date.getTime()+(milliseconds));
		expires = "; expires=" + date.toGMTString();
	} else {
		expires = "";
	}

	var cookieString	= name+"="+value+expires+"; path=/";
	document.cookie		= cookieString;
}
//####################################################
function createCookie(name,value,days)
{
	var realCookie = getRealCookie("ckyWWE");
	if(!realCookie)
	{
		createRealCookie("ckyWWE",""); //init
		realCookie = "";
	}else{
		realCookie += "&";
	}

	var indStart = realCookie.toLowerCase().indexOf(name.toLowerCase()+"=")
	if(indStart > -1)
	{
		var indEnd		= realCookie.indexOf("&",indStart);
		var cookieValue	= unescape(realCookie.substring(indStart + name.length+1, indEnd));
		realCookie		= realCookie.replace(name+"="+cookieValue, name+"="+changeParam(value));
	}
	else
	{
		realCookie		+= name+"="+changeParam(value)+"&"
	}
	
	if(realCookie.endsWith("&"))
	{
		realCookie = realCookie.substring(0, realCookie.length - 1);
	}
	
	if(realCookie.length > 1 && realCookie.startsWith("&"))
	{
		realCookie = realCookie.substring(1, realCookie.length);
	}
	
	createRealCookie("ckyWWE",realCookie);
}

/*************************************************************************************************
 Function to show a popup on the screen
**************************************************************************************************/
function Popup(x, y, width, height, target, innerHTML){
	oPopup	= window.createPopup();
	var oPopupBody		= oPopup.document.body;
	oPopupBody.sender	= target.id;
	oPopupBody.style.backgroundColor = "#CCCCCC";
	oPopupBody.innerHTML = innerHTML;
	oPopup.show(x, y, width, height, target);
}

/**********************************************************************
Function to set select a value in a drop down list
**********************************************************************/
function ddlSelect(ddl, value)
{
	if (value)
	{
		for (var n = 0; n < ddl.options.length; n++)
		{
			if (ddl.options[n].value == value)
			{
				ddl.options[n].selected = true;
				break;
			}
		}
	}
}

var CallFocus = true;

function getSelectedValue(select, defaultValue)
{
	if (typeof(select) == "string")
		select = document.getElementById(select);

	if ((select)
	&& (select.options)
	&& (select.selectedIndex >= 0))
		return select.options[select.selectedIndex].value;
	else
	if (defaultValue)
		return defaultValue;
	else
		return "";
}

function getSelectedText(select, defaultValue)
{
	if (typeof(select) == "string")
		select = $(select);

	if ((select)
	&& (select.options)
	&& (select.selectedIndex >= 0))
		return select.options[select.selectedIndex].text;
	else 
	if (defaultValue)
		return defaultValue;
	else
		return "";
}

//######### New encode/decode
function urlDecode(str)
{
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}

function urlEncode(str)
{
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++)
{
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str)
{
    base64Str = str ? str.toString() : null;
    base64Count = 0;
}

function readBase64()
{
    if (!base64Str || base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}

function changeParam(str)
{
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT)
    {
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT)
        {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT)
            {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            }
            else
            {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        }
        else
        {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;

        if (lineCount >= 76)
        {
            result += ('\n');
            lineCount = 0;
        }
    }
    return result.replace(/\+/g, "@");
}

function readReverseBase64()
{
    if (base64Str)
    {
        while (base64Count < base64Str.length)
        {
            var nextCharacter = base64Str.charAt(base64Count);
            base64Count++;

            if (reverseBase64Chars[nextCharacter])
            {
                return reverseBase64Chars[nextCharacter];
            }
            if (nextCharacter == 'A')
            {
                return 0;
            }
        }
    }
    return END_OF_INPUT;
}

function ntos(n)
{
    n = n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str)
{
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}

var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
function toHex(n)
{
    var result = '';
    var start = true;
    for (var i=32; i>0;)
    {
        i-=4;
        var digit = (n>>i) & 0xf;
        if (!start || digit != 0){
            start = false;
            result += digitArray[digit];
        }
    }
    return result == '' ? '0' : result;
}

function pad(str, len, pad)
{
    var result = str;
    for (var i = str.length; i < len; i++)
    {
        result = pad + result;
    }
    return result;
}

function encodeHex(str)
{
    var result = "";
    for (var i = 0; i < str.length; i++)
    {
        result += pad(toHex(str.charCodeAt(i)&0xff),2,'0');
    }
    return result;
}

function decodeHex(str)
{
    str = str.replace(new RegExp("s/[^0-9a-zA-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i = 0; i < str.length; i++)
    {
        nextchar += str.charAt(i);
        if (nextchar.length == 2)
        {
            result += ntos(eval('0x'+nextchar));
            nextchar = "";
        }
    }
    return result;
}

function setCookie(name, value)
{
	createCookie(name,value);
}

//Function used to redirect the menu tabs in P4P create mode
function RedirectMenuURL(URL)
{
	if(ValidatePageChange())
	{
		document.location.href = URL;
	}
}

function getAttribute(e, s)
{
    return get_attribute(e, s, "");
}

function getElementValue(object, defaultValue)
{
	if (typeof(object) == "string")
		object = $(object);

	if (object && object.value)
		return object.value;
	else
	if (defaultValue)
		return defaultValue;
	else
		return "";
}
function LoadDropDown(id, type, prop, ddFilter)
{
    
     var selected = "",ddId=id + "_DD";
     var arr = new Array(type.length);
     var cookieVal = (ddFilter) ? ddFilter[ddId] : (location.href.toLowerCase().indexOf("interactivecalendar.aspx") > -1) ? getCookie(ddId+"CAL") : getCookie(ddId);
     
     for (var i=0; i<type.length; i++)
     {
          if (((cookieVal == null) && (type[i].getAttribute("selected") != null)) || (type[i].getAttribute("id") == cookieVal)) 
            selected = "selected='selected'";
            
           arr[i] = "<OPTION value='" + type[i].getAttribute("id") + "' " + selected + " >" + type[i].getAttribute("val")  + "</OPTION>";
            selected = "";
     }

     if(id=="ProductFamily" || id=="ProductVersion" || id=="ProductEdition")
     {
        prop += " class='pdd'";
     }
     $(id).innerHTML = "<select id='" + id + "_DD' " + prop + " >" + arr.join() + "</select>"
}

function fixMNPLinks()
{
    var tblMNP = $("mnpMenuTop");
    
    var anchors = tblMNP.getElementsByTagName("A");
    
    for(var i=2;i<anchors.length;i++)
    {
        var href = anchors[i].getAttribute("href");
        anchors[i].setAttribute("href","javascript:void(0);");
        anchors[i].setAttribute("onclick",href);
        anchors[i].onclick = href;
    }
}

var container;
var newDivArray = new Array();
function ClearContainer(idStr)
{
    window.clearTimeout(container);
    var c = "";
    
       for (var i=0; i <= newDivArray.length; i++)
       {
         value = newDivArray.pop();
         
         c = $(value);
         if (c!= null)
         {
            c.style.display = "block";
            c.style.display = "none";
         }
       }
}


function ShowMapDetailPopUp()
{
    map = window.open("map.aspx", "map", "width=600,height=600,scrollbar=false");
    map.focus();
}

function showHideProfile(target, sender)
{
    if(target.style.display.equals("none"))
    {
        $("Profile_shp").src = "resources/images/minus_my.gif";
        target.style.display =  "block";
    }
    else
    {
        $("Profile_shp").src = "resources/images/plus_my.gif";
        target.style.display =  "none";
    }
}

function showHideBilling(target, img, sender)
{
    if(target.style.display.equals("none"))
    {
        img.src = "resources/images/minus_my.gif";
        target.style.display =  "block";
    }
    else
    {
        img.src = "resources/images/plus_my.gif";
        target.style.display =  "none";
    }
}

function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
   function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }