escape = encodeURIComponent;
unescape = decodeURIComponent;

var kMainFrameName = "worksite_mainframe"
var k2K = 2000
var IMAN_DATA_DELIMITOR = "{}";
var RESULT_DATA_DELIMITOR = "{:}";

var reAmp = new RegExp();
reAmp.compile("&", "g");

var reApos = new RegExp();
reApos.compile('\'', 'g');

var reQuot = new RegExp();
reQuot.compile('\"', 'g');

var reLt = new RegExp();
reLt.compile('<', 'g');

var reGt = new RegExp();
reGt.compile('>', 'g');

var reSlash = new RegExp();
reSlash.compile('\\\\', 'g');

var reSpace = new RegExp();
reSpace.compile('\\s', 'g');

function javaString(str) {
	// This add's backslashes to any single || double quotes
	if ( str ) 
	{
		str = str.replace(reSpace, " ")
		str = str.replace(reSlash, "\\\\")
		str = str.replace(reApos, "\\\'")
		str = str.replace(reQuot, "\\\"")

		return str
	} 
	else 
	{
		return ''
	}
}


function javaStringX2(str)
{
	return javaString(javaString(str));
}
	
function htmlString(str) 
{
	// This HTML escapes the string
	if ( str ) 
	{
		str = str.replace(reAmp, "&amp;")
		str = str.replace(reApos, "&#39;")
		str = str.replace(reQuot, "&quot;")
		str = str.replace(reLt, "&lt;")
		str = str.replace(reGt, "&gt;")

		return str
	} 
	else 
	{
		return ''
	}
}

function htmlDeString(str) {
	// This HTML unescapes the string

	if ( str ) 
	{
		str = str.replace(/&#39;/gi, "\'")
		str = str.replace(/&quot;/gi, "\"")
		str = str.replace(/&lt;/gi, "<")
		str = str.replace(/&gt;/gi, ">")
		str = str.replace(/&amp;/gi, "&")
		return str
	} 
	else 
	{
		return ''
	}
}

function rTrim(str) 
{ 
	if ( str )
	{
		return str.replace(/\s+$/, "");
	}
	else
	{
		return '';
	}
} 

function lTrim(str) 
{
	if ( str )
	{
		return str.replace(/^\s+/, "") 
	}
	else
	{
		return '';
	}
} 

function trim(str) 
{
	return rTrim(lTrim(str));
} 

function getURLParam(url, param) 
{
	// This extracts a named param
	
	var index = url.indexOf(param + "=")
	if (index >= 0) 
	{
		var start
		if (index == 0) 
		{
			start = param.length + 1
		} 
		else 
		{
			var priorChar = url.charAt(index-1)
			if (priorChar == '&' || priorChar == '?') 
			{
				start = index + param.length + 1
			}
		}
		
		if (start) 
		{
			var end = url.indexOf("&", start)
			if (end < 0) 
			{
				end = url.length
			}
			return unescape(url.slice(start, end));
		}
	}
	
	return '';
}

function setURLParam(url, param, value)
{
	// This sets a named param
	
	var index = url.indexOf("?" + param + "=")
	if (index < 0) 
	{
		index = url.indexOf("&" + param + "=")
	}

	if (index >= 0) 
	{
		var start = index + 1
		var end = url.indexOf("&", start)
		if (end < 0) 
		{
			if ( value )
			{
				url = url.slice(0, start) + param + "=" + value
			}
			else
			{
				url = url.slice(0, start - 1)
			}
		}
		else
		{
			if ( value )
			{
				url = url.slice(0, start) + param + "=" + value + url.slice(end)
			}
			else
			{
				url = url.slice(0, start) + url.slice(end - 1)
			}
		}
	} 
	else if ( value )
	{
		url = appendURLParam(url, param, value)
	}
	
	return url
}

function appendURLParam(url, param, value) {
	if (url.indexOf("?") < 0) {
		url = url + "?"
		} else {
		url =  url + "&"
	}
	url += param + "=" + value
	
	return url
}
	
function getParam(name) {
	var query = window.location.search
	var arg = name + "="
	var alen = arg.length
	var qlen = query.length
	var i = query.indexOf("?") + 1
	while (i < qlen) {
		var j = i + alen
		if (query.substring(i, j) == arg) {
			var cEnd = query.indexOf("&",j)
			if (cEnd == -1) {
				cEnd = query.length
			}
			return unescape(query.substring(j, cEnd))
		} else {
			i = query.indexOf("&", i) + 1
			if (i == 0) break;
		}
	}
	return ""
}


function getCookie(name, item) {
	var arg = name.toUpperCase() + "="
	var alen = arg.length
	var clen = document.cookie.length
	var i = 0
	while (i < clen) {
		var j = i + alen
		if (document.cookie.substring(i, j).toUpperCase() == arg) {
			var cEnd = document.cookie.indexOf(";",j)
			if (cEnd == -1) {
				cEnd = document.cookie.length
			}
			var cookie = document.cookie.substring(j, cEnd)
			if (item != null) { // Find item
				arg = item.toUpperCase() + "="
				alen = arg.length
				clen = cookie.length
				i = 0
				while (i < clen) {
					j = i + alen
					if (cookie.substring(i, j).toUpperCase() == arg) {
						cEnd = cookie.indexOf("&",j)
						if (cEnd == -1) {
							cEnd = cookie.length
						}
						cookie = cookie.substring(j, cEnd)
						return unescape(cookie)
					} else {
						i = cookie.indexOf("&", i) + 1
						if (i == 0) return ""
					}
				}	
			}
			return unescape(cookie)
		} else {
			i = document.cookie.indexOf(" ", i) + 1
			if (i == 0) break;
		}
	}
	return ""
}

function setCookie(name, value, expireDays,path) {
	var pair = name + "=" + value
	if (expireDays) {
		var expires = new Date()
		var expTime = expires.getTime() + (expireDays * 86400000)
		expires.setTime(expTime)
		pair += "; expires=" + expires.toGMTString()
	}
	if (path) {
		pair += "; path=" + path
	} else {
		pair += "; path=" + "/"
	}
	document.cookie = pair
}

function deleteCookie(cookieName) {
		var now = new Date()
		now.setTime (now.getTime() - 1)
		var cookieValue = getCookie (cookieName)
		document.cookie = cookieName + "=" + cookieValue + "; expires=" + now.toGMTString()
}

function getVersionString()
{
	return getLocStrByLID(417, 'Version') + ' ' + productVersion + ' (' + productBuild + ')';
}

function restoreOffset() {
	var name = window.name + "Offset"
	var offset = getCookie(name)
	if ( offset && window.scrollTo ) {
		var offsets = offset.split(",")
		window.scrollTo(offsets[0], offsets[1])
		setCookie(name, "", 0)
	}	
}

function appendRedirectToURL(url) {
	//This function will append the redirect from the page object (complete with tabid).
	var isMainWindow = isHomeLink(url)
	url = virtualPath() + setURLParam(url, "redirect", escape(window.page.getRedirect()))
	if(isMainWindow) {
		window.location = url
	} else	{
		openDialogWindow(url)
	}
}

//Check the length of "str" with "size".If greater, then trim "str" to "size".
function checkLength(str,size) {
	if(str.length > size)	
		str = str.substring(0,size) + "..."	
	return str
}

function centralize(Sr, Pl, Pw, Dw) {
	return Math.max(0, Math.min(Sr - Dw, (Math.max(0, Pl) + Math.min(Sr, Pl + Pw) - Dw) / 2))
}

// BrowserInfo object
function Browser() {
/*
	Properties:
		isIE:	is Internet Explorer;
		isNS6:	is Netscape 6 and above;
		isNS4:  is Netscape 4.x;
		isNav:	is Netscape browser;
		isMac:	is Macintosh machine;
		isWin:  is Windows machine;
		isIE5:  is Internet Explorer 5.0*;
		isIE55: is Internet Explorer 5.5;
*/	
	 this.isIE	= (document.all)? true : false
	 this.isNS6 = (document.implementation && document.implementation.createDocument) ? true : false
	 this.isNS4 = (navigator.userAgent.toUpperCase().indexOf("MOZILLA/4.79") > -1) || (navigator.userAgent.toUpperCase().indexOf("MOZILLA/4.8") > -1)
	 this.isNav = this.isNS6 || this.isNS4
	 this.isMac = (navigator.userAgent.indexOf("Macintosh") > -1)
	 this.isWin = !this.isMac	 
	 this.isIE5 = (navigator.userAgent.indexOf("MSIE 5.0") > -1)
	 this.isIE55 = (navigator.userAgent.indexOf("MSIE 5.5") > -1)
}

window.disposeAdvise = function window_disposeAdvise(funcObj) 
{
	YAHOO.util.Event.addListener(window, "unload", typeof(funcObj) == "function" ? funcObj : function() { eval(funcObj) });
}

window.onloadAdvise = function window_onloadAdvise(funcObj) 
{
	YAHOO.util.Event.addListener(window, "load", typeof(funcObj) == "function" ? funcObj : function() { eval(funcObj) });
}

function worksiteInitCss() 
{
	var bd = document.body || document.getElementsByTagName('body')[0];
	if( ! bd )
	{ 
		return false; 
	}
	var cls = 
		YAHOO.env.ua.ie ? ("ext-ie " + (YAHOO.env.ua.ie <= 6 ? 'ext-ie6' : (YAHOO.env.ua.ie <= 7 ? 'ext-ie7' : '')))
		: YAHOO.env.ua.gecko ? "ext-gecko"
		: YAHOO.env.ua.opera ? "ext-opera"
		: YAHOO.env.ua.webkit ? "ext-safari" 
		: YAHOO.env.ua.air ? "ext-air" 
		: "";

	bd.className += " " + cls;
	return true;
};

if( ! worksiteInitCss() )
{
	window.onloadAdvise(worksiteInitCss);
}

g_browser = new Browser()

function virtualRoot() 
{
	if ( ! virtualRootCache ) 
	{
		virtualRootCache = prependIPSURL(getCookie("virtualRoot"))
	}
	return virtualRootCache
}
var virtualRootCache = ""

function virtualPath() 
{
	if ( ! virtualPathCache ) 
	{
		virtualPathCache = prependIPSURL(getCookie("virtualPath"))
	}
	return virtualPathCache
}
var virtualPathCache = ""

function getThemeRoot()
{
	if ( ! themeRootCache ) 
	{
		themeRootCache = virtualPath() + "/themes/" + getCookie("themeRoot");
	}
	return themeRootCache
}
var themeRootCache = ""

//This function is only useful for iPlanet gateway.
function prependIPSURL(str) 
{
	var add_ipsURL_to_iman = str;
	return add_ipsURL_to_iman;
}

function getRelativeImageURL(imgSrc) 
{
	var imageName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1).toLowerCase();
	return '../images/' + imageName;
}

function worksiteDialogCallBack(returnObject)
{
	if ( window.document.body )
	{
		window.document.body.className += ' worksite-portal-reload';
	}
	window.location = returnObject && returnObject.url ? returnObject.url : page.getRedirect();
}

function closeDialogWindow(returnObject)
{		
	// [NT-4782] Blank window remains open when the user opens the EVENT LINK received through the NOTIFICATION and saves the changes made to the event.
	var opener;
	try
	{
		opener = window.opener;
		var l = opener.location;
	}
	catch(ex)
	{
		opener = null;
	}

	if (opener)
	{
	    var windowClosed = false;
	    if (typeof (returnObject) != "undefined")
	    {
	        if (returnObject.fullrefresh == true)
	        {
	            opener.name == kMainFrameName ? opener.parent.location.reload(true) : opener.location.reload(true);
	            windowClosed = true;
	            window.close();
	        }
	        else if (returnObject.fromError == true)
	        // check for flag from ReportError in the return object
	        {
	            windowClosed = true;
	            window.close();
	        }
	    }

	    if (!windowClosed && typeof (opener.worksiteDialogCallBack) != "undefined")
	    {
	        opener.worksiteDialogCallBack(returnObject);
	        window.close();
	    }
	}
	// [NT-4782] Blank window remains open when the user opens the EVENT LINK received through the NOTIFICATION and saves the changes made to the event.
	else if (window.name == kMainFrameName && typeof (window.worksiteDialogCallBack) != "undefined")
	{
	    window.worksiteDialogCallBack(returnObject);
	    return true;
	}
	// [no bug #] When coming from an external GetDoc link (e.g., one sent via email), we were trying to close window instead of redirecting to portal
	else if (typeof (window.worksiteDialogCallBack) != "undefined" && returnObject)
	{
	    window.worksiteDialogCallBack(returnObject);
	    return true;
	}
	else
	{
	    window.close();
	}
	
}

function objArrayToMultiOpStr(objArray)
{
	//This function will create a multi-op string from an array of objects that can be sent to the server for multi-op processing.
	var nrtidStr = '';
	
	for (i=0; i < objArray.length; i++)
	{
		nrtidStr += objArray[i].nrtid + kMultiOpSeparator;
	}
	
	return nrtidStr ? nrtidStr.substring(0,(nrtidStr.length-1)) : "";
}

/********************************************************************/
/******************** Client To Asp Code ****************************/
/********************************************************************/

if ( ! window.XMLHttpRequest ) 
{
    window.XMLHttpRequest = function()
                            {
                                return new ActiveXObject("MSXML2.XMLHTTP");
                            }
}
 
function clientToAsp() 
{
	var domObj = new Object();	
		
	//Note: We had added following variable to make sure every request is unique,because XMLHTTP caches similar requests : SJ
	domObj.globalIndex = (new Date()).valueOf()
	domObj.hasError = false;
	domObj.errorMessage = "";
	
	domObj.getData = clientToAsp_getData
	domObj.clearError = clientToAsp_clearError
	domObj.isAccessGranted = clientToAsp_isAccessGranted
	domObj.putData = clientToAsp_putData 
	domObj.checkResult = clientToAsp_checkResult	
	domObj.getDataByPost = clientToAsp_getDataByPost
	domObj.parseResult = clientToAsp_parseResult
	
	return domObj;
}
 function clientToAsp_getData(url, callback) 
 {
 	this.clearError();
 	
 	url = htmlDeString(url);
	url = setURLParam(url, "xmlFormat", "1")
	url = setURLParam(url, "globleindex", this.globalIndex++)

	var requestObj = new XMLHttpRequest();
	
	//if url is pointing to an xml directly, we may need create an ASP
	//file to handle it.

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	var async = false;
	if ( typeof(callback) == 'function' )
	{
		var it = this;
		requestObj.onreadystatechange = function() 
										{ 
											if ( requestObj.readyState == 4 /*COMPLETED*/ )
											{
												callback(it, it.parseResult(requestObj));
												requestObj = it = callback = url = null;
											}
										};
		async = true;
	}
	requestObj.open("GET", url, async);
	requestObj.send(null);

	return async ? null : this.parseResult(requestObj);
}

function clientToAsp_clearError() 
{ 
	this.hasError = false; 
	this.errorMessage = "";
}

function clientToAsp_isAccessGranted() 
{ 
	return true;
}
	
function clientToAsp_putData(url) 
{
 	this.clearError();
	url = setURLParam(url, "xmlFormat", "1")
	url = setURLParam(url, "globleindex", this.globalIndex++)

	var requestObj = new XMLHttpRequest();

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	requestObj.open("GET", url, true)
	requestObj.send(null)
}
	
function clientToAsp_checkResult(result) 
{
	if ( result )
	{
		var indexError = result.indexOf(IMAN_DATA_DELIMITOR)
		if (indexError > 0) 
		{
			this.hasError = result.substring(0,indexError).toUpperCase() == "ERROR:";
		}
		if (this.hasError) 
		{
			this.errorMessage = result.substring(indexError + IMAN_DATA_DELIMITOR.length);
		}
	}
}
	
function clientToAsp_getDataByPost(url, body, callback) 
{
 	this.clearError();
	body += (body ? "&" : '') + "xmlFormat=1"

	var requestObj = new XMLHttpRequest();

	if(url.length > k2K) 
	{
		this.hasError = true;
		this.errorMessage = getLocStrByLID(1155, "Please reduce the number of selected items");
		return
	}

	var async = false;
	if ( typeof(callback) == 'function' )
	{
		var it = this;
		requestObj.onreadystatechange = function() 
										{ 
											if ( requestObj.readyState == 4 /*COMPLETED*/ )
											{
												callback(it, it.parseResult(requestObj));
												requestObj = it = callback = url = body = null;
											}
										};
		async = true;
	}

	requestObj.open("POST", url, async)
	requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	requestObj.send(body)

	return async ? null : this.parseResult(requestObj);
}

function clientToAsp_parseResult(requestObj)
{
    var result = '';
    var responseXML = requestObj.responseXML;
    
	if ( responseXML && responseXML.documentElement && responseXML.documentElement.nodeName != "parsererror")
	{
		var rootNode = responseXML.documentElement;
		if ( rootNode.nodeName == 'data' )
		{
			// FF needs textContent, IE needs text
			result = rootNode.textContent ? rootNode.textContent : rootNode.text;
			this.checkResult(result);
		}
		else
		{
			result = rootNode.ownerDocument;
		}
	}
	else
	{
		result = requestObj.responseText;
		this.checkResult(result);
	}
	return result;
}

/********************************************************************/
/******************** End Client To Asp Code ************************/
/********************************************************************/

var worksiteBrowserCheck = function()
{
	try
	{
		deleteCookie("checkCookies");
		setCookie("checkCookies", "true");

		var cookiesEnabled = getCookie("checkCookies") === "true";
	}
	catch(e)
	{
	}
	
	try
	{
		var ajax = new XMLHttpRequest();
		var ajaxEnabled = ajax && true;
	}
	catch(e)
	{
	}

	return (
	{
		cookies: cookiesEnabled || false,
		ajax: ajaxEnabled || false,
		ok: cookiesEnabled && ajaxEnabled || false
	});	
	
	
}();
