/* ----------------------------------------------------------------------------------------------
	Begin Pipeline Specific Scripts

	These scripts are specific to the actual Pipeline tab pages. 
   ---------------------------------------------------------------------------------------------- */

//----------------  Begin Constants ------------------
LOGIN_DIV	   ="LoginDiv";
LOGIN_IFRAME   ="LoginIFrame";
TARGET_DIV	   ="TargetDiv";
TARGET_IFRAME  ="TargetIFrame";
//NS_FRAME_MIN_WIDTH  	= 795;
//NS_FRAME_MIN_HEIGHT 	= 538;
NS_FRAME_MIN_WIDTH  	= 800;
NS_FRAME_MIN_HEIGHT 	= 600;
CUSTOMER_ACTIVITIES_DIV = "CustomerActivitiesMenu";
APPLET_URL              = "pipelineApplet.asp?rtba=%1";
LOGIN_URL               = "login.asp?pipe=%1";
ANON_URL				= "loginanon.asp?pipe=%1";
FRAME_NAME              = "_menu";
AUTHENTICATION_COOKIE   = "Authenticated";
BANNER_LOGO_DIV  		= "bannerLogo";

_pipe  = "";
_htmlBuf="";
_localAuth="";  
_lastSelection=null;
_appletTimedOut=false;

//----------------  End Constants ------------------

// This is here to handle situations where we have been launced as an individual frame.
// The main code is in default.asp and is there for the MS Death Patch.
function canAuthenticate() {
	return true;
}

// Try to find a parent object.  If we are standalone, get our opener.  Otherwise, get our parent
function getParentObj() {
	var parentObj = parent;
	if( parentObj == null || parentObj == this )
		parentObj = window.opener;
	return parentObj;
}

//if authenticated, open the Link System Access tab
function loadLinkAccess() {
	if (isAuthenticated()) {
		var prvpipe=getPipeId();
		openPipeNoFocus(null, "Security", "Link System Access"); //force Link System Access when the first pipe is authenticated
		return true;
	}

	return false;
	

	
}
// Open up Link System Access via Login 
function openPipeNoFocus(event, aPipe, aLabel) {
	if (this == parent) {
		return true;
	}
	else {
		var pipe     = aPipe;
		var tabLabel = aLabel;
		parent.openPipeNoFocus(event, aPipe, aLabel)
		return false;
	}
}
// If we have been authenticated, then return true.  Otherwise
// Try to find either our parent or our opener and see if they have been authenticated
function getAuthentication() {

	return getCookie(AUTHENTICATION_COOKIE);
}

function isAuthenticated() {
		return getAuthentication() != null
}
function setAuthenticated(aVal) {
	try {

		if (parent.userAuthenticated==undefined) {
			// noop
		}
		else {
			parent.userAuthenticated();
		}
	}
	catch(ex){	// Eat it, If we are standalone, we don't care
	}

	if( getAuthentication() != null )
		return;

	document.cookie=AUTHENTICATION_COOKIE+'='+aVal;
}

// Hide any visible pages so the home page can become visible again
function showHomePage() {
	document.getElementById( TARGET_DIV ).style.display="none";
	document.getElementById( LOGIN_DIV ).style.display="none";
	return false;
}

// Get pipeline Id
function getPipeId() {
	if( _pipe != null && _pipe.length > 0 )
		return _pipe;
	
	// MS XP Patch
	var s = window.location.toString();
	var idx1 = s.indexOf("pipe=");
	var idx2 = s.indexOf("&", idx1);
	if( idx1 > -1 ) {
		if( idx2 > -1 ) 
			_pipe = s.substring(idx1+5, idx2) ;
		else
			_pipe = s.substring(idx1+5 );
	}
	
	if( _pipe == null || _pipe.length==0 )
		alert("PipelineScripts.getPipeId() returned NULL");
		
	return _pipe;
}

// When Login is clicked, show Login div.
function login(autoConnect) {

	if( autoConnect == null )
		autoConnect = true;
		
	document.getElementById( TARGET_DIV ).style.display="none";
	document.getElementById( LOGIN_DIV ).style.display="block";

	var div = document.getElementById( LOGIN_DIV );
	var logFrame = div.getElementsByTagName("IFRAME")[0];

	var loginUrl = logFrame.getAttribute("_src");
	
	if( loginUrl == null || loginUrl == "")
		if ("ANONSECURITY" == getPipeId()) {
			loginUrl = ANON_URL.replace("%1", getPipeId() );
		} else {
			loginUrl = LOGIN_URL.replace("%1", getPipeId() );
		}
	var thisUrl = document.location.toString();
	var idx = thisUrl.indexOf("?");
	if ( idx > -1 )
		thisUrl = thisUrl.substr(idx+1);

	logFrame.src = loginUrl + "&" + thisUrl;

	// Bug in Netscape with IFRAMES.  Hardcode to a specific width
	if( document.all == null ) {
		logFrame.width=NS_FRAME_MIN_WIDTH;
		logFrame.height=NS_FRAME_MIN_HEIGHT;
	}

	// append parms from LoginUrl
	if( autoConnect && isAuthenticated() ) {
		var obj = document.getElementById( CUSTOMER_ACTIVITIES_DIV );
		if( obj != null )
			obj.innerHTML = "<p><font color=white>Connecting...</font></p>";
	
		var theUrl = APPLET_URL;
		theUrl = theUrl.replace("%1", getAuthentication());
		theUrl = theUrl + "&" + loginUrl.substr(loginUrl.indexOf("?")+1);
		logFrame.src = theUrl  + "&" + thisUrl;

	}
	div.src = div.src;
	
	//Kludge for Netscape.  By replacing "whatnew" iframe with an empty page
	//Netscape will paint the applet correctly
	var obj = getIFrameNamed("whatsnew")
	if( obj != null )
		obj.location.replace("EmptyFrame.asp");
	
	return false;	//override I.E. event handling
}


// Return an IFRAME named
function getIFrameNamed(aName) {
	var iframes = document.getElementsByTagName("IFRAME");
	
	for( var idx = 0; idx < iframes.length; idx++ ) {
		if( iframes[idx].id == aName ) {
			if ( document.frames != null ) {	// I.E. 
				return document.frames(idx)
			}
			else {	// N.S.
				return this.window.frames[idx]
			}
		}
	}
}

// Helper for N.S. vs I.E. differences
function getMenuItems() {
	return getIFrameNamed(LOGIN_IFRAME).getMenuItems();
}

function setConnecting() {
	var obj = document.getElementById( CUSTOMER_ACTIVITIES_DIV );
	if( obj != null )
		obj.innerHTML = "<p><font color=white>Connecting...</font></p>";

	
}
// Called from applet
function appletLoaded(authStr) {
	//if( ! isAuthenticated() )    took out so anonymous security applet could draw menu
	//	return;

	var theMenuItems = getMenuItems();

	if( theMenuItems == null || theMenuItems.length == 0 ) {
		setTimeout( "appletLoaded()", 500);
		return;
	}

	loadMenuFromXML(theMenuItems);
}

// Given an XML document, create the menu
function loadMenuFromXML(theMenuItems) {	
	var xmlDoc = XmlDocument.create();
	xmlDoc.loadXML(theMenuItems);

	buildMenu(xmlDoc.documentElement, null);
	
	var obj = document.getElementById( CUSTOMER_ACTIVITIES_DIV);
	if( obj != null )
		obj.innerHTML = _htmlBuf;
	_htmlBuf = "";
}

// Jeff G.  2003-04-09. 
// Given an XML document and the menu node, create the menu
function loadMenuNodeFromXML(menuNode, theMenuItems) {	
    //displayXML(theMenuItems);
	var xmlDoc = XmlDocument.create();
	xmlDoc.loadXML(theMenuItems);

	buildMenu(xmlDoc.documentElement, null);

	document.getElementById( menuNode ).innerHTML = _htmlBuf;
	_htmlBuf = "";
}

// Jeff G.  2003-04-29. 
// Given an XML document, create the menu and return the HTML.
function getMenuHTMLFromXML(theMenuItems) {	
    //displayXML(theMenuItems);
	var xmlDoc = XmlDocument.create();
	xmlDoc.loadXML(theMenuItems);

	buildMenu(xmlDoc.documentElement, null);
	return _htmlBuf;
	_htmlBuf = "";
}

// Build Menu HTML from XML document
function buildMenu( xmlNode, nodeInfo ) {
	for( var idx=0; idx<xmlNode.childNodes.length; idx++ ) {
		var curNode = xmlNode.childNodes[idx];

		if( curNode.nodeName.toLowerCase() == "item" ) {
			nodeInfo = new Object();
			nodeInfo.tool_tip="";		//default value
			
			buildMenu(curNode, nodeInfo);

			_htmlBuf += "\n";
			if( nodeInfo.type.toLowerCase() =="folder" ) {
				_htmlBuf += "<p class='nodeClosed'><a href='javascript:void(0);' onClick='return nodeClicked(event);' onmouseover='disposeAppletPopup();' LEVEL=" + nodeInfo.indent;
				_htmlBuf += " _subMenu="+nodeInfo.sub_menu_name + ">" ;
				_htmlBuf += nodeInfo.name + "</a></p>";

				_htmlBuf += "\n<span class='subnavNode' ID=" + nodeInfo.sub_menu_name + ">";

				buildMenu(nodeInfo.sub_items, null);

				_htmlBuf += "\n</span>";
			}
			else if (nodeInfo.type.toLowerCase() =="appletitem"){
				_htmlBuf += "\n<p><a href='javascript:void(0);' onClick='return appletItemClicked(event);'  onmouseover='disposeAppletPopup();' " + FRAME_NAME + "='" + nodeInfo.name + "' title='" + nodeInfo.tool_tip + "'>" + nodeInfo.title + "</a></p>";
			}
			else if (nodeInfo.type.toLowerCase() == "wei-htmlitem"){
                	// Jeff G. 2003-04-09.  Build the URL for WEI items.
				if (nodeInfo.url.substr(1, 4) != "http") {
				// tgenglish 2006-09-13 Will not mesh with new environment configuration code
           			srcUrl = readURL("cfg/BCOUURL.txt");
        		} 
        		else {
          			srcUrl = "";
        		}
				var destUrl = srcUrl + nodeInfo.url.replace("+", "&");

				_htmlBuf += "\n<p><a href='" + destUrl + "' target='" + "TargetFrame" + "' onClick='htmlItemClicked(event);' title='" + nodeInfo.tool_tip + "'>" + nodeInfo.name + "</a></p>";
			}
			else if (nodeInfo.type.toLowerCase() =="htmlitem"){
				
				var destUrl = nodeInfo.url;
				var lTarget = nodeInfo.target;
				if ( lTarget == null )
					lTarget = "TargetFrame";

				destUrl = appendRequiredParms(destUrl);

				_htmlBuf += "\n<p><a href='" + destUrl + "' target='" + lTarget ;
				if( lTarget != "TargetFrame" )
				 	_htmlBuf += "' onClick='htmlItemClicked(event, null, true);'"
				else
				 	_htmlBuf += "' onClick='htmlItemClicked(event);'"
				_htmlBuf += " onmouseover='disposeAppletPopup();'  title='" + nodeInfo.tool_tip + "'>" + nodeInfo.name + "</a></p>";
			}
			else if (nodeInfo.type.toLowerCase() =="erroritem"){
				_htmlBuf += "\n<p><a href='javascript:void(0);' onClick='return login();'><font color=yellow>" + nodeInfo.name + "  Click to Retry</font>" + "</a></p>";
			}
			else
				alert("buildMenu() - don't know how to handle xmlNode.type=" + nodeInfo.type );
		}
		else if( curNode.nodeName.toLowerCase() == "name" ){
			nodeInfo.name=curNode.firstChild.nodeValue;
		}
		else if( curNode.nodeName.toLowerCase() == "title" ){
			nodeInfo.title=curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "type" ) {
			nodeInfo.type=curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "indent" ) {
			nodeInfo.indent=curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "sub-menu-name" ) {
			nodeInfo.sub_menu_name=curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "url" ) {
			nodeInfo.url=curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "sub-items" ) {
			nodeInfo.sub_items = curNode;
		}
		else if ( curNode.nodeName.toLowerCase() == "tooltip" ) {
			nodeInfo.tool_tip = curNode.firstChild.nodeValue;
		}
		else if ( curNode.nodeName.toLowerCase() == "target" ) {
				nodeInfo.target = curNode.firstChild.nodeValue;
		}
	}

	return;
}

function getEventSrc(event) {
	try {
		var eventSrc = event.srcElement;
		if( eventSrc == null ) {	//if N.S.
			eventSrc = event.target;
			if( eventSrc.nodeType == 3 ) {
				eventSrc = eventSrc.parentNode;
			}
		}
		return eventSrc;
	}
	catch(exception) {
		return null;
	}
}
// Expand or contract a menu node.
function nodeClicked(event, isAuthRequired ) {
	var eventSrc = getEventSrc(event);
	if( isAuthRequired && !isAuthenticated()) {
		login();
	}

	var oId  = eventSrc.getAttribute("_subMenu");
	var node = document.getElementById(oId);

	if( node.style.display == "block" ) {
		node.style.display = "none";
		eventSrc.parentNode.className="nodeClosed";
	}
	else {
		node.style.display = "block";
		eventSrc.parentNode.className="nodeOpen";


		var objs  = document.getElementsByTagName("a");
		var lvl = eventSrc.getAttribute("LEVEL");

		for( var idx=0; idx<objs.length; idx++ ) {
			if( objs[idx].getAttribute("LEVEL") == lvl && objs[idx].getAttribute("_subMenu") != oId ) {
				var theNode = document.getElementById( objs[idx].getAttribute("_subMenu"));
				theNode.style.display = "none";
				objs[idx].parentNode.className = "nodeClosed";
			}
		}
	}

	// Stop Browser event processing
	return false;
}

// Whenever an Applet menu item is clicked, show the applet and run the item
// Event "e" may be null.  If so, we should have been passed an "aFrame" and "parms"
function appletItemClicked(e, aFrame, parms) {
	var curFrame = getIFrameNamed(LOGIN_IFRAME).getCurrentFrame();
	var newFrame = "";
	
	if( e != null ) {
		var eventSrc = getEventSrc(e);
		newFrame = eventSrc.getAttribute( FRAME_NAME );
		if( _lastSelection != null )
			_lastSelection.className = "";
		_lastSelection = eventSrc;
		eventSrc.className="itemClicked";
	}
	else {
		newFrame = aFrame;
	}

	getIFrameNamed(LOGIN_IFRAME).processMenuEvent(newFrame, parms);

	htmlPageClosed();
	// Stop browser event processing
	return false;
}

// Whenever an Html link is clicked, we want to show the "Target" div and hide the applet
// This is called immediately before the browser replaces the URL for the TargetDiv with
// whatever item the user has selected
function htmlItemClicked(e, aUrl, showInNewFrame)  {
	if( showInNewFrame != null && showInNewFrame == true ) {
		if( aUrl != null )
			window.open( aUrl, _blank );
		return;
	}
	
	try {
		if ( ! getIFrameNamed(LOGIN_IFRAME).closeFrame() )
			return false;
	}
	catch( e ) {
	}

	var div = document.getElementById( TARGET_DIV );
	if(aUrl != null ) {
		if( aUrl.indexOf("MethodInvokerUrl") == -1 ) {
			aUrl = appendRequiredParms(aUrl);
		}
		getIFrameNamed( TARGET_IFRAME ).location.replace( aUrl );
	}

	var iframes = div.getElementsByTagName("IFRAME");
	// Bug in Netscape with IFRAMES.  Hardcode to a specific width
	if( document.all == null ) {
		for( var idx=0; idx<iframes.length; idx++) {
			iframes[idx].width=NS_FRAME_MIN_WIDTH;
			iframes[idx].height=NS_FRAME_MIN_HEIGHT;
		}
	}
	document.getElementById( LOGIN_DIV ).style.display="none";
	document.getElementById( TARGET_DIV ).style.display="block";
	
	if( e != null ) {
		var eventSrc = getEventSrc(e);
		if( eventSrc != null ) {
			if( _lastSelection != null )
				_lastSelection.className = "";
			_lastSelection = eventSrc;
			eventSrc.className="itemClicked";
		}
	}
	
	return false;
}

// Append MethodInvokerUrl parm to any URL that needs to communicate back to us
function appendRequiredParms(aUrl) {
	var thisUrl = window.location.toString();
	thisUrl = thisUrl.substr(0, thisUrl.lastIndexOf("/"));
	thisUrl += "/MethodInvoker.asp"
	thisUrl = "MethodInvokerUrl=" + thisUrl;

	if( aUrl.indexOf("?" ) > -1 )
		aUrl += "&" + thisUrl;
	else
		aUrl += "?" + thisUrl;
		
	return aUrl;
}

// Called from HomePages to show Realtime reports
function openWindow(varUrl,intToolbar,intLoc,intScroll,intResize,varWin) {
	var viewit=varUrl;
	var winopt="toolbar="+intToolbar+",location="+intLoc+",scrollbars="+intScroll+",resizable="+intResize+",menubar=1";
	
	 window.open(viewit,varWin,winopt);
	return false;	
}

// Called from HomePages to show Gas Quality reports at max screen size
function openWindowWide(varUrl,intToolbar,intLoc,intScroll,intResize,varWin) {
	var viewit=varUrl;
	wid = screen.availWidth -10;
	hei = screen.availHeight -50;
	top1 = 0;
	left1 = 0;


	var winopt="toolbar="+intToolbar+",status=1,location="+intLoc+",scrollbars="+intScroll+",resizable="+intResize+",menubar=0,width="+wid+",height="+hei+",top="+top1+",left="+left1;
	var winname= window.open(viewit,varWin,winopt,width= hei,height= hei);
    winname.focus();
	return false;

}


// Called from MethodInvoker.asp whenever navigating from "Realtime" screens
// Will hide their page and show our applet
function htmlPageClosed() {
	document.getElementById( TARGET_DIV ).style.display="none";
	getIFrameNamed( TARGET_IFRAME ).location.replace( "common/LoadingMessage.asp" );
	document.getElementById( LOGIN_DIV ).style.display="block";
	
	// override I.E. event handling
	return false;
}

function showError( aMsg ) {
	alert(aMsg);
	return false;
}


// When we are "shown", handle any special processing here.
function refreshDisplay() {
	if( _appletTimedOut ) {
	    htmlPageClosed();
	    _appletTimedOut=false;
	}
}

function appletTimedOut() {
	_appletTimedOut = true;
}


// This will be called from the page "MethodInvoker.asp" whenever we come from
// the "Realtime" screens to open an applet page.
function openAppletFrame( parms ) {
	var FRAME_NAME = "FRAMENAME=";
	var NUM_PARMS  = "NUMPARMS=";
	var frameName;
	var numParms;
	var idx1;
	var idx2;
	idx1=parms.toUpperCase().indexOf(FRAME_NAME);
	if( idx1 < 0 )
		return showError( "PipelineScripts.openFrame():  FrameName was not specified" );
	idx2=parms.indexOf("&", idx1);
	if( idx2 < 0 )
		return showError( "PipelineScripts.openFrame():  Unable to deterime FrameName" );
	
	frameName = parms.substring(idx1+FRAME_NAME.length,idx2);

	parms = parms.substr(idx2);	
	idx1=parms.toUpperCase().indexOf(NUM_PARMS);
	if( idx1 < 0 )
		return showError( "PipelineScripts.openFrame():  NumParms was not specified" );
	
	htmlPageClosed();
	
	appletItemClicked( null, frameName, parms );
}

function showAlert( aTitle, aMsg, aPipe ) {
	if( document.getElementById(BANNER_LOGO_DIV) != null )
		alert(aMsg);
	else
		parent.showAlert(aTitle, aMsg, aPipe );
}
// End Pipeline Specific Scripts 


/************************
 * We need to make the Iframe bigger if its "contents" are bigger than
 * the default size.  We run through this method until all the contents are
 * downloaded, then reset the page size as needed
 *************************/ 
function setTabPageSizeBasedOnContent() {
	// If netscape, bail out.  We have not been able to determine the size of the N.S. document
	if( document.all == null ) 	{
		return;
	}
		
	// If the document is not loaded or the heights have not been computed, wait for 200 ms and
	// try again.
	if( document.readyState != "complete" || document.body.scrollHeight == 0) {
		setTimeout( "setTabPageSizeBasedOnContent()", 200 );
		return;
	}
	
	// Grab min height for IFRAME.  If we don't have a frame element, we were 
	// opened as a separate browser session, so ignore this block.  If we do,
	// then verify that we don't have more data in our page than the "_minHeight".
	// If we do, adjust that _minHeight value to accomodate the size of the page
	if( window.frameElement != null ) {
		var minH = new Number(window.frameElement.getAttribute("_minHeight" ));
		
		// If it is less than the actual size of the document,
		// reset attributes and resize frame
		if( minH < document.body.scrollHeight ) {
			window.frameElement.setAttribute("_minHeight", document.body.scrollHeight );
			window.frameElement.style.height=document.body.scrollHeight + "px";
		}
	}
}
// Called when a pipeline home page is opened for the first time
// If we were not passed in a pipe, then we were probably bookmarked.
// Redirect to the same page and grab the pipe from the name of the Home Page
function initTabPage(aPipe) {
	_pipe = aPipe;
	setTabPageSizeBasedOnContent();

	if( aPipe == null || aPipe.length == 0 ) {
		var url = window.location.toString();
		var pg  = url.substr(url.lastIndexOf("/")+1);
		var pAbr = pg.substring(0, pg.toUpperCase().indexOf("HOME.ASP"))
		
		if( url.indexOf("?") > -1 )
			window.location.replace(url + "&pipe=" + pAbr + "&mode=1");
		else
			window.location.replace(url + "?pipe=" + pAbr + "&mode=1");
	}
	if (parent._autoLogin != undefined && parent._autoLogin.indexOf(aPipe) != -1) {
		login();
	}	
}

// If the applet is running, dispose of the Navlist Popup
function disposeAppletPopup() {
	getIFrameNamed(LOGIN_IFRAME).disposeAppletPopup();
}

// Every time the TargetIframe is loaded, we need to tickle the applet, if its loaded
// so that the user does not time out.
function targetContentLoaded() {
	try {
		getIFrameNamed(LOGIN_IFRAME).tickleApplet();
	}
	catch(ex) {
		// eat it
	}
}