/* (c) Business objects 2004.  All rights reserved. */

var BROWSER_INTERNET_EXPLORER = ( window.navigator.userAgent.toLowerCase().indexOf('msie') != -1);
var BROWSER_SAFARI = ( window.navigator.userAgent.toLowerCase().indexOf('applewebkit') != -1);
var BROWSER_GECKO = ( window.navigator.userAgent.toLowerCase().indexOf('gecko') != -1) && (!BROWSER_SAFARI);

var IE_CLOSE_SCREEN_LEFT = 10004; // IE magic number for closing browser window.
var IE_CLOSE_MIN_SCREEN_LEFT = -32000; // IE magic number for closing browser window while minimized.

var DEFAULT_NAV_WIDTH = "200";

function getRpUrl()
{
	var hplus = getHeaderPlus();
	return hplus.rpUrl;
}

function getHeaderPlus() {
	if (isNetscape70() || BROWSER_GECKO) return top;
	return findFrame('headerPlusFrame');
}
function getDataFrame() {
	if (isNetscape70() || BROWSER_GECKO) return findFrame('dataWrapperFrame');
	return findFrame('dataFrame');
}

function getGlobals() {
	var variables = getHeaderPlus();
	if(variables != null)
		return variables.globals;
	return null;
}

function empty() {
  return '';
}

function findElementById(Id) {
	var mywin = window;
	try {
		while (mywin != mywin.parent && mywin.parent && mywin.parent.document) {
			mywin = mywin.parent;
		}
	} catch (ex) {
		// stop at the current frame, if mywin.parent.document returns access denied error.
		// This happens when the parent frame has a different URL context than the current frame.
	}
	var f = mywin.document.getElementById(Id);
	if (f != null) return f;
	
	for (var i = 0; i < mywin.length; i++) {
		f = findElementHelper(mywin.frames[i], Id);
		if (f != null) return f;
	}
	return null;
}
function findElementHelper(frame, Id) {
	// frames with certain plugins (word, excel) will cause a js error because the frame document doesn't exist
	if ((typeof(frame.document)).toLowerCase() == "unknown") return null;

	var f = null;
	try {
		f = frame.document.getElementById(Id);		
	} catch(ex) {
		// Ignore this frame if we can't access it.  NS will return "Permission denied to get property
		// HTMLDocument.getElementById" on some frames (eg: external hyperlink page)
	}
	
	if (f != null) return f;
	
	for (var i = 0; i < frame.length; i++) {
		f = findElementHelper(frame.frames[i], Id);
		if (f != null) return f;
	}
	return null;
}
function findFrame(frame) {
	var f = findElementById(frame);
	if (f) {
		// safari lies and tries to identify itself as Mozilla/Gecko..
		// however, it sets its vendor to Apple 
		if (isSafari()) 
			return f;
		return f.contentWindow;
	}

		return null;
}

function showListing(webAppDir, querystr) {
	resetLastActionId();
	if (webAppDir == undefined) {
		webAppDir = "";
	}
	
	if( querystr == undefined ) {
		querystr = "";
	}

	// discovery - append iscontentSearch=true if is search
	var g = getGlobals();
	if( undefined != g && g.showSearch
		&& g.lastWorkspacePage.indexOf( "isContentSearch=true" ) > -1  
		&& -1 == querystr.indexOf( "isContentSearch=true" ) ) {
		if( "" == querystr ) 
			querystr += "?";
		else
			querystr += "&";
		querystr += "isContentSearch=true";
	}
	
	showInWorkspace(webAppDir + "listingenvelope.aspx" + querystr);
}

function showInWorkspaceWithHeaderTitle (url, title, preserveActionId, id)
{
	if (id != undefined)
		showInWorkspace(url, preserveActionId, id);
	else
		showInWorkspace(url, preserveActionId);
		
	setWorkspaceHeaderTitle(title);

	var workspaceHeader = findFrame('workspaceHeaderFrame'); 
	if(workspaceHeader && workspaceHeader.displayNewWindowButton)
		workspaceHeader.displayNewWindowButton(); 
}

function replaceContext( url, context, lowercaseApproot ) {
    if( context && (context.length > 0 ) ) {
        var startIndex = url.toLowerCase().lastIndexOf(lowercaseApproot);
        if( startIndex > -1 )
            url = context + url.substring( startIndex );
    }
    return url;
}

function showInWorkspace(url, preserveActionId, id, context, lowercaseApproot) {
    url = replaceContext( url, context, lowercaseApproot );
	setWorkspaceHeaderTitle("");
	if (!preserveActionId) {
		resetLastActionId();
	}

	if (id != -1) {
	    if (id != undefined) {
			updateRightFrame(id, context, lowercaseApproot);
		} else {
			updateRightFrame(0, context, lowercaseApproot);
	    }
	}
	
    if (url.match("FullClient_") && !url.match ("rpUrl=")) 
    {
	   var rpUrl = getRpUrl();
    		if (rpUrl) {		
    			url = addQueryStrSep(url) + "rpUrl="+ rpUrl;
		}
    }

	if (url) {		
		// need to work around some safari behavior when finding frame "workspaceFrame"
	 	if(isSafari() && 'workspaceFrame' == window.name) {
	 		document.location.href = url;
	 		return;
		}
		
		var wkspace = findFrame('workspaceFrame');
		if (wkspace && ((typeof(wkspace.document)).toLowerCase() != "unknown")) {
			if( isSafari() ) {
				wkspace.src = url;		// for navigation in safari (current frame is not workspace)
			} else {
				wkspace.document.location.href = url;
			}
		} else {
			var wsenvFrame = findFrame('workspaceEnvelopeFrame');
			if (wsenvFrame) {
			    var loc = "";
				if (lowercaseApproot && lowercaseApproot.toLowerCase() == "/applications" )
				{
    				loc = "../workspaceenvelope.aspx?workspaceUrl=" + "." + lowercaseApproot + "/" +_URIEncode(url);
				}
				else
				{
    				loc = "workspaceenvelope.aspx?workspaceUrl=" + _URIEncode(url);
				}    
			

				wsenvFrame.location.href = loc;
			} else {
				document.location.href = url;
			}
		}
	}
}
function showLastWorkspace(defaultUrl) {
	var g = getGlobals();
	if(g == null)
		return;

	var url = "home.aspx";
	if (defaultUrl && (defaultUrl.length > 0)) {
		url = defaultUrl;
	}
	if (g.lastWorkspacePage) {
		url = g.lastWorkspacePage;
		restoreLastActionId();
	}
	else resetLastActionId();
	showInWorkspace(url, true);
}
function saveWorkspace(urlToSave) {
	if (urlToSave.length == 0) return;

	var g = getGlobals();
	if(g == null)
		return;

	g.lastWorkspacePage = urlToSave;
	saveLastActionId();
}

function showInListing(url) {
	if (url) {
		var listingframe = findFrame('listingframe');
		if (listingframe) listingframe.document.location.href = url;
		else showInWorkspace(url);
	}
}

function showNoAccess (webAppDir) {
	var wkspace = findFrame('workspaceFrame');
	if (wkspace)		
		wkspace.document.location = webAppDir + "noAccess.aspx";
	else
		document.location = webAppDir + "noAccess.aspx";
}

function isChecked(ID)
{
	var inputItems = document.getElementsByTagName("input"); 
	if(inputItems == null) return false; 
	for(var i = 0; i < inputItems.length; i++)
	{
		var lowerCaseID = inputItems[i].id.toLowerCase(); 
		if(inputItems[i].checked && lowerCaseID.indexOf(ID.toLowerCase()) >= 0)
		return true; 
	}
	return false; 
}

function showDiscussions (id, webAppDir) {
	var g = getGlobals(); 
	if(g == null)
		return;

	var frame = findFrame("supplementalBodyFrame");

	if (arguments.length > 0) {
		g.discussions_id = id;
	}
	
	var urlPrefix = "";
	if (arguments.length > 1 && webAppDir.length > 0)	
		urlPrefix = webAppDir + "/";
		
	if (g.supplementalFrameShown) {
		var url = urlPrefix + "discussions/desktop/discussions.aspx?objectId=";
    	if (g.discussions_id) {
	    	url += g.discussions_id;
		}
		else {
			url += "0";
		}
		if (isSafari()) frame.src = url;
		else frame.location.href = url;
	}
}

//This function is to fix the bug in IE/XP where in full screen mode all toolbars are hidden (Can't close window)
function ieFixWindowProps(windowProps){
    if (windowProps.indexOf('fullscreen') > -1){
      var newFullScreenString = "left=0,top=0,width=" + (screen.width-10) + ",height=" + (screen.height-70);
      var fullIndex = windowProps.indexOf('fullscreen');
      if (windowProps.indexOf(',', fullIndex) > -1){
        windowProps = windowProps.substring(0, fullIndex - 1) + newFullScreenString
                      + windowProps.substring(windowProps.indexOf(',', fullIndex));
      }else{
        windowProps = windowProps.substring(0, fullIndex - 1) + newFullScreenString;
      }
    }
    return windowProps;
}

function resetLastActionId() {
	var g = getGlobals();
	if(g != null)
		g.lastActionId = null;
}
function setLastActionId(id) {
	var g = getGlobals();
	if(g != null)
		g.lastActionId = id;
}
function getLastActionId() {
	var g = getGlobals();
	if (g != null && g.lastActionId) return String(g.lastActionId);
	else return null;
}
function saveLastActionId() {
	var g = getGlobals();
	if(g != null)
		g.savedLastActionId = g.lastActionId;
}
function restoreLastActionId() {
	var g = getGlobals();
	if(g != null)
		g.lastActionId = g.savedLastActionId;
}

function addQueryStrSep(url)
{
    if (url.length == 0)
        return "?";

    if (-1 == url.indexOf('?'))
    {
        return url + "?";
    }
    else
    {
        if ('&' != url.charAt(url.length - 1))
            return url + "&";
        else
            return url;
    }
}
function gotoAction(url, id, viewInPortal, windowName, windowProps, webAppDir)
{ 

	var g = getGlobals();
	if(g != null)
	{
		g.lastUrl = url; 
		g.lastWindowName = windowName + id; 
		g.lastWindowProps = windowProps; 
	}
	
	if (BROWSER_GECKO && url.indexOf("Dashboard/dashboard_") != -1)
    {
		setLastActionId(id);
		if (!windowName)
			windowName = "iv";
		if (!windowProps)
			windowProps = "fullscreen=yes,location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes";
		window.open(url, windowName, ieFixWindowProps(windowProps));
		return;
    }
	
    
	var wkspace = findFrame('workspaceFrame');
    if (!wkspace)
    {
        // If we are not in an InfoView subframe.
        if (viewInPortal && !(isNetscape70() && windowName))
            window.top.location.href = url;
        else
            window.open(url, windowName, ieFixWindowProps(windowProps));
    }
    else
    {
	    setLastActionId(id);
	    if (viewInPortal && !(isNetscape70() && windowName)) {
		    showDiscussions(id, webAppDir);
		    showInWorkspace(url, true, id);
	    } else {
		    window.open(url, windowName, ieFixWindowProps(windowProps));
	    }
	}
	return;
}

function toggleNav (bShow)
{
	// do nothing for netscape 7.0 since it refreshes the whole page
	if (isNetscape70())
		return;

	if (bShow != undefined)
	{
		toggleNavBase(bShow);
	}
	else
	{
		toggleNavBase();
		var g = getGlobals();
		if(g == null)
			return;
		bShow = g.navFrameShown;
	}
	setPanelStateForRestoredWorkspace ('nav', bShow);
}


function toggleNavBase(bShow)
{
	var g = getGlobals();
	if(g == null)
		return;
		
	// do nothing for netscape 7.0 since it refreshes the whole page
	if (isNetscape70())
		return;

	if (bShow != undefined)
		g.navFrameShown = bShow;
	else
		g.navFrameShown = !g.navFrameShown;

	var navWorkFrame = findFrame('navWorkFrame');
	var fs = navWorkFrame.document.getElementById('navWorkFrameSet');
	var frame = navWorkFrame.document.getElementById('navigationFrame');

	var navFrameCol = fs.cols.substr(0, fs.cols.indexOf(','));
    var restOfCols = fs.cols.substr(fs.cols.indexOf(','));

    //Make sure the centre frame is always *
    restOfCols = restOfCols.replace(/,.*,/, ",*,");

	if (g.navFrameShown)
	{
		frame.noResize=false;
		if (g.navCols)
            fs.cols = g.navCols + restOfCols;
		else
			fs.cols = DEFAULT_NAV_WIDTH + restOfCols;		
	}
	else
	{
		// save the last state
		if (navFrameCol != "0")
			g.navCols = navFrameCol;
		fs.cols="0" + restOfCols;
		frame.noResize=true;
	}
	
	if(g.btnNav != null)
		g.btnNav.check(g.navFrameShown, false); 

}

function toggleSupplemental (bShow)
{
	// do nothing for netscape 7.0 since it refreshes the whole page
	if (isNetscape70())
		return;

	toggleSupplementalBase(bShow);
	setPanelStateForRestoredWorkspace ('discuss', bShow);
}

function toggleSupplementalBase(bShow)
{
	var suppFrame = findFrame('supplementalFrame');
	if (suppFrame && suppFrame.toggleSupplementalBase) {
		suppFrame.toggleSupplementalBase(bShow);
	}
}

function toggleFoldersCategories(bShowFolders, id)
{
	var navHeaderFrame = findFrame('navigationHeaderFrame');
	if (navHeaderFrame) {
		var g = getGlobals();
		if (bShowFolders) {
			g.nav_folderId = id;
			navHeaderFrame.displayFolders();
		} else {
			g.nav_categoryId = id;
			navHeaderFrame.displayCategories();
		}
	}
}

function setSearch(isSearch, searchType, searchText) {
	var g = getGlobals();
	if(g == null)
		return;

	g.listing_issearch = isSearch;
	g.listing_searchtype = searchType;
	g.listing_searchtext = searchText;
	g.listing_advancedsearch = "";
}

function refreshListing() {
	var listingframe = findFrame('listingframe');
	if (listingframe && listingframe.doSubmit) {
		listingframe.doSubmit();
	} else {
		showListing();
	}
}

function selectNavNodeAndDisplay(bShowFolders, id, webAppDir) {
	toggleFoldersCategories(bShowFolders, id);
	var g = getGlobals();
	if (g == null)
		return;
		
	g.nav_selectednode = id;
	g.listing_parentid = id;
	g.listing_advancedsearch = "";
	showListing(webAppDir);
}

function selectParentNavNode() {
	var navBodyFrame = findFrame('navigationBodyFrame');
	navBodyFrame.selectParentNavNode();
}

function refreshEntireNavTree(){
	var navBodyFrame = findFrame('navigationBodyFrame');
	navBodyFrame.refreshEntireNavTree();
}

function refreshSelectedNavNode() {
	var navBodyFrame = findFrame('navigationBodyFrame');
	navBodyFrame.refreshNavNode();
}

function expandSelectedNavNode() {
	var navBodyFrame = findFrame('navigationBodyFrame');
	navBodyFrame.expandNavNode();
}

function refreshSelectedNavNodeChildren() {
	var navBodyFrame = findFrame('navigationBodyFrame');
	navBodyFrame.refreshNavNodeChildren();
}

function setWorkspaceHeaderTitle(title) {
	var headerFrame = findFrame('workspaceHeaderFrame');
	if (headerFrame && headerFrame.setTitle) {
		headerFrame.setTitle(title);
	}
	var g = getGlobals();
	if(g != null)
		g.workspaceHeaderTitle = title;
}

function panelButtonHover(id, newImg) {
	var img = document.getElementById(id);
	if (img && img.src) {
		img.src = newImg.src;
	}
}

// Id map for menu items
function createIdMap (theArray)
{
	var map = new Object();
	for (var i = 0; i < theArray.length; i++)
	{
		map[theArray[i].id] = i;
	}
	return map;
}

//  -comma separated lists-
// input is (probably) a hidden input
// item is a string
// only adds items not already in the list
function addToCSList(input, item)
{
	if (input.value.length > 0) {
		var oldvalue = "," + input.value + ",";
		if (oldvalue.indexOf("," + item + ",") == -1) {
			input.value += "," + item;
		}
	} else {
		input.value = item;
	}
}
function removeFromCSList(input, item)
{
	var items = input.value.split(",");
	var i;
	input.value = "";
	for (i = 0; i < items.length; i++) {
		if (items[i] != item && items[i] != "") {
			addToCSList(input, items[i]);
		}
	}
}

function _URIEncode(s)
{
   if( (typeof(encodeURIComponent)).toLowerCase() == "function" ) {
      //escape behaves differently in IE and Netscape; besides it's been deprecated and removed from the standard.
	  //Therefore use encodeURIComponent when we can.
	  return encodeURIComponent(s);
   } else {
	   //for Safari, which does not support encodeURIComponent;
	  var tmp = escape(s);
      // encode "+", since escape will not do it for us...
      return tmp.replace(/\+/g, "%2b");
   }
}

function _HtmlEncode (s)
{
	es = s.replace(/\&/g,"&amp;");
	es = es.replace(/\</g,"&lt;");
	es = es.replace(/\>/g,"&gt;");
	es = es.replace(/\'/g,"&apos;");
	es = es.replace(/\"/g,"&quot;");
	return es;
}

function getJSDate(calendarName)
{
	var dateString = document.getElementById(calendarName + "_dateHidden").value; 
	var dateArray = dateString.split("."); 
	var hour = document.getElementById(calendarName + "_hoursDropDownList").selectedIndex; 
	var min = document.getElementById(calendarName + "_minutesDropDownList").selectedIndex; 
	var AMorPM = document.getElementById(calendarName + "_ampmDropDownList");
	if(AMorPM) {
		hour += 1; 
		if(AMorPM.selectedIndex == 0 && hour == 12) hour = 0;  
		if(AMorPM.selectedIndex == 1 && hour != 12) hour = hour + 12;  
	}
	var date = new Date(dateArray[0], dateArray[1] -1, dateArray[2], hour, min, 0); 
	return date;
}
		
function goHistory(id)
{
	var mywin = window;
	mywin = mywin.parent;

	var historyPage = "report_history.aspx?id=";
	historyPage += id;
	setLastActionId(id);
	showInWorkspace(historyPage, true);
}

function isNetscape70() {
	return (navigator.product == "Gecko" && navigator.userAgent.indexOf("Netscape/7") != -1);
}

function isSafari() {
	return navigator.vendor == "Apple Computer, Inc.";
}

function netscapeOnScroll() {
	// Netscape 7.x has issues with scrolling where vertical lines appear when scrolling down
	// this seems to fix the problem...  
	self.document.bgColor = self.document.bgColor;
}

if (isNetscape70()) {
	self.window.onscroll = netscapeOnScroll;
}

function toggleRightFrame(bShow)
{
	if (bShow != undefined)
	{
		toggleRightFrameBase(bShow);
	}
	else
	{
		toggleRightFrameBase();
		var g = getGlobals();
		if(g == null)
			return;		
    	bShow = g.rightFrameShown;
	}
	setPanelStateForRestoredWorkspace ('right', bShow);
}

function toggleRightFrameBase(bShow)
{
	var g = getGlobals();
	if(g == null)
		return;

    var frame = findFrame('rightFrame');
    if (frame == null) {
        return;
    }

	if (g.rightFrameShown == undefined)
		g.rightFrameShown = false;

	if (bShow != undefined)
		g.rightFrameShown = bShow;
	else
		g.rightFrameShown = !g.rightFrameShown;
		
	var navWorkFrame = findFrame('navWorkFrame');
	var fs = navWorkFrame.document.getElementById('navWorkFrameSet');
	var rf = navWorkFrame.document.getElementById('rightFrame');
    var rightCols = fs.cols.substr(fs.cols.lastIndexOf(',') + 1);
    var restOfCols = fs.cols.substr(0, fs.cols.lastIndexOf(',') + 1);

    //Make sure the centre frame is always *
    restOfCols = restOfCols.replace(/,.*,/, ",*,");

    if (g.rightFrameShown) {
        if(g.rightFrame == undefined)
        	g.rightFrame = DEFAULT_NAV_WIDTH;
        fs.cols = restOfCols + g.rightFrame;
        rf.noResize = false;
    } else {
        rf.noResize = true;
        g.rightFrame = rightCols;
        fs.cols = restOfCols + "0";
    }
   	if (g.rightFrameShown)
   		updateRightFrame(-1);
}

function updateRightFrame(id, context, lowercaseApproot)
{
    var frame = findFrame('rightFrame');
    if (frame == null)
    	return;

    var g = getGlobals();
    if(g == null)
	return;
	
	if (id == undefined)
		g.rightFrameRequestedId = 0;
	else if (id != -1)
		g.rightFrameRequestedId = id;
		
	if (!g.rightFrameShown)
		return;

    if (g.rightFrameRequestedId != g.rightFrameCurrentId || g.rightFrameUrlChanged) {
    	g.rightFrameCurrentId = g.rightFrameRequestedId;
    	g.rightFrameUrlChanged = false;
		var loc = frame.location.toString();
		if(loc.indexOf(g.rightUrl) > -1){
		var url = loc.substring(0,loc.indexOf('?'));
		frame.location = url + "?repID=" + g.rightFrameCurrentId + "&LOCALE=" + g.rightLocale;
		}
		else{
			frame.location = g.rightUrl + "?repID=" + g.rightFrameCurrentId + "&LOCALE=" + g.rightLocale;
		}
		
    }

}

function opendocumentCallback(id) {
    showDiscussions(id, "../../");
    updateRightFrame(id);
}

function ignoreErrors() {
	return true;
}

function isWindowClosing()
{
	// Determine if window is closing according to browser type.
	// NOTE: Currently no official way in javascript to determine if window is closing.
	if (BROWSER_INTERNET_EXPLORER) {
		if (window.screenLeft == IE_CLOSE_SCREEN_LEFT) return true;
		if (window.screenLeft == IE_CLOSE_MIN_SCREEN_LEFT) return true;
	}
	else if (BROWSER_GECKO || BROWSER_SAFARI)
	{
		// TODO: Figure out how to check for Netscape and/or Safari.
	}
	
	return false;
}

function setPanelStateForRestoredWorkspace (panelId, isShown)
{
	var wsHeaderFrame = findFrame('workspaceHeaderFrame');
	if (wsHeaderFrame && wsHeaderFrame.setPanelStateForRestoredWorkspaceImpl)
			wsHeaderFrame.setPanelStateForRestoredWorkspaceImpl (panelId, isShown);
}

// Encodes delimiters "=" and ","
// Identical to codebehind function
function encodeDelimiters (s)
{
	es = s.replace(/\|/g,"*|");
	es = es.replace(/\&/g,"*||");
	es = es.replace(/\=/g,"*|||");
	es = es.replace(/\,/g,"*||||");
	return es;
}

// Decodes strings previously encoded with encodeDelimiters()
// Identical to codebehind function
function decodeDelimiters (es)
{
	s = es.replace(/\*\|\|\|\|/g,",");
	s = s.replace(/\*\|\|\|/g,"=");
	s = s.replace(/\*\|\|/g,"&");
	s = s.replace(/\*\|/g,"|");
	return s;
}

function moveListBoxItems (fromListBox, toListBox, moveAll)
{
	// Iterate forward thru "fromListBox", copying to "toListBox"
	for (count = 0; count < fromListBox.options.length; ++count)
	{
		var currentItem = fromListBox.options[count];
		if (moveAll || currentItem.selected)
		{
			var option = new Option (currentItem.text, currentItem.value, false, false);
			toListBox.options[toListBox.options.length] = option;
		}
	}

	// Iterate backwards thru "fromListBox", removing copied items
	for (count = fromListBox.options.length -1;  count >= 0; --count)
	{
		if (moveAll || fromListBox.options[count].selected)
			fromListBox.options[count] = null;
	}
}
// ADAPT00597903  
// http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/activating_activex.asp
function writeActiveX(activeXParams)
{
	document.writeln(activeXParams);
}

