/* COPYRIGHT INFORMATION All pages within a SITE are the property of DTE Energy or its Affiliate, unless other ownership is 
indicated. All information and content including any software programs available on or through a SITE is protected by copyright. A 
user is permitted to download information from a SITE which, by its nature or context, is to be copied in order to use SITE-related 
services. A user is permitted to download information from a SITE for private personal use. A user is prohibited from modifying, copying, 
distributing, transmitting, displaying, publishing, selling, licensing, creating derivative works or using any Content available on or 
through a SITE for any commercial or public purpose unless the user has the prior written permission of DTE Energy or its Affiliate. 
*/

/* Global variables */
var refSearch = "http://idevsearch.dteenergy.com";
var secureBaseURL;
var unsecureBaseURL;
var args = getArgs();
var wasLastFieldValid = true;
var fieldToValidate = "";

/* NOTE google search is currently not being used */
function makeGoogleSearchDiv()
{
	document.write('<div id="searchArea">');
		document.write('<form name="googleSearch" method="get" action="' + refSearch + '/search" onsubmit="return checkSearchForm()">');
			document.write('Search:');
			document.write('<input name="q" type="text" size="12" maxlength="256" value=""></input>');
			document.write('<input src="/images/goButton.gif" type="image" name="submit" border="0" align="top"></input>');
			document.write('<input type="hidden" name="site" value="default_collection"></input>');
			document.write('<input type="hidden" name="access" value="p"></input>');
			document.write('<input type="hidden" name="ud" value="1"></input>');
			document.write('<input type="hidden" name="sort" value="date:D:L:d1"></input>');
			document.write('<input type="hidden" name="output" value="xml_no_dtd"></input>');
			document.write('<input type="hidden" name="oe" value="UTF-8"></input>');
			document.write('<input type="hidden" name="ie" value="UTF-8"></input>');
			document.write('<input type="hidden" name="client" value="default_frontend"></input>');
			document.write('<input type="hidden" name="proxystylesheet" value="default_frontend"></input>');
			document.write('<input type="hidden" name="numgm" value="5"></input>');
		document.write('</form>');
	document.write('</div>');
}

/**********************************************************************
   Begin bread crumb and left nav menu section 
   **NOTE** breadcrumbs are currently not used on this site.
   If they are going to be used, the left nav structure will need to utilize the nav.js file
   and this is a fair re-factoring effort.
***********************************************************************/

// The following 6 steps are  used to create the bread crumbs at the top of relevant pages within the Energy Services Site
	// 1.  Find which page the user is on and identify the corresponding unique ID in menu.js 
		winLocation = window.document.URL.toString();
		//alert(winLocation);

	// 2.  Re-write above variable to string so we can compare to items in menu.js (not sure why we must do this, but it only works this way)
		var windowLocation = "";
		for(var f=0; f < winLocation.length; f++)
		{
			windowLocation = windowLocation+winLocation.charAt(f);
		}

	// 3.  If the document path does not include a document name assume it is index.html
		var winLength=winLocation.length-1;
		if(windowLocation.charAt(winLength)=="/")
		{
			windowLocation = windowLocation+"index.html";
		}
		//alert(windowLocation);

	// 4.  Locate document in menu.js and identify corresponding unique ID
		menuLocation=-1;
		//alert(menuLocation);
		for(var b=0; b < localNav.length; b++)
		{
			var tmpLocalNav = localNav[b].split('|','onsitePopupBottomBorder');
		
		  //find row in menu.js table that matches page
		  tmpNbr = windowLocation.indexOf(tmpLocalNav[2]);
			//alert(b+" : "+tmpLocalNav[2]+", "+tmpNbr);
			if((windowLocation.indexOf(tmpLocalNav[2])!=-1))
			{
				windowLocation = tmpLocalNav[0];
				menuLocation = b;
				//alert("found");
				//current locations unique ID is now windowLocation
			}
		}

	// 5.  If unique ID is multi-tier, convert to array for future use
		var menuStyle = windowLocation.split('_','onsitePopupBottomBorder');
		var parentMenu = menuStyle[0];
		for(var b=1; b < menuStyle.length-1; b++){
			parentMenu += "_" + menuStyle[b];
		}
		var menuNumber = menuStyle[0];
		var menuTier = menuStyle.length;

	// 6.  Create and display the bread crumbs
		function makeBreadCrumbs()
		{
			//alert("menuLocation " + menuLocation);
			if(menuLocation!=-1){
		  	document.write('<a href="',sitePath,'" target="_top">', bcHomeLink,'</a>','onsitePopupBottomBorder');
		  	var currentPage = localNav[menuLocation].split('|','onsitePopupBottomBorder');
		  	var tmpCString = menuStyle[0];
		  	for(var c=0; c < (menuTier-1); c++){
		  		for(var b=0; b < localNav.length; b++){
		  			var tmpCrumb = localNav[b].split('|','onsitePopupBottomBorder');
		  			if(tmpCrumb[0]==tmpCString){
		          tmpCrumb[1] = tmpCrumb[1].replace(/&nbsp;/gi,"");	//change		
		    			document.write(' > <a href="',tmpCrumb[2],'" target="_top">',tmpCrumb[1],'</a>','onsitePopupBottomBorder');
		  			}
		  		}
		  		tmpCString = tmpCString+"_"+menuStyle[c+1];
		  	}
		  	currentPage[1] = currentPage[1].replace(/&nbsp;/gi,"");  //change
		    document.write(' > ',currentPage[1]);
			}
		}

/**********************************************************************
   End bread crumb and left nav menu section
***********************************************************************/

/* 
   Some AJAX functions that will allow us to store the reference to the complimentary secured URL prefix 
   in a single place - namely a .html file - that can be acessed both by the browser at runtime via a simple
   AJAX call or a server side include in the case where value of the variable is needed from within an html or 
   server side evaluation.
*/

function getSecuredUnsecuredURLPrefix(securedUnsecured)
{
	var xmlHttpReq = false;
	
	// ref to html file on server that contains ref to base URL of secured portion of site
	var strURL;
	
	if(securedUnsecured == 'secured')
	{
		strURL = "/includes/refDTEEnergyServicesSecured.html";
	}
	else
	{
		strURL = "/includes/refDTEEnergyServicesUnsecured.html";
	}
	
	// find the base url of this page
	var urlIndex = windowLocation.indexOf("//");
	var urlPart1 = windowLocation.substring(0, urlIndex + 2);
	var urlPartTemp = windowLocation.substring(urlIndex + 2, windowLocation.length);
	var urlPart2 = urlPartTemp.substring(0, urlPartTemp.indexOf("/"));
	var urlBase = urlPart1 + urlPart2;
	
	var responseStr;
	
    // Mozilla/Safari
    if (window.XMLHttpRequest)
	{
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
	{
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttpReq.open('POST', strURL, true);
    xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpReq.onreadystatechange = function()
	{
        if (xmlHttpReq.readyState == 4)
		{
			if(securedUnsecured == 'secured')
			{
				secureBaseURL = xmlHttpReq.responseText;
			}
			else
			{
				unsecureBaseURL = xmlHttpReq.responseText;
			}
        }
    }
	
    xmlHttpReq.send(urlBase + strURL);
}

// validate Email address on contact Us input form
function isEmailValid(emailForm, idOfTagForErrorMessageInsert)
{
	var eMailValidationMessage = "";
    var Temp     = document.emailForm.email;
    var AtSym    = Temp.value.indexOf('@');
    var Period   = Temp.value.lastIndexOf('.');
    var Space    = Temp.value.indexOf(' ');
    var Length   = Temp.value.length - 1;   // Array is from 0 to length-1
    
    if ((AtSym < 1) ||                     // '@' cannot be in first position
	    (Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
		(Period == Length ) ||             // Must be atleast one valid char after '.'
		(Space  != -1) ||				   // No empty spaces permitted
		(Length < 4))
       {
		  eMailValidationMessage = "<span class='validationMessage'>The E-mail address you entered '<b>" + 
			  (document.getElementById('email')).value + "'</b> is either blank or not formatted correctly.</span><br />";
		  document.emailForm.email.value = (document.getElementById('email')).value;
		  document.getElementById('email').focus();
		  document.getElementById('email').select();
       }

	return eMailValidationMessage;
}

// This function specifically validates the "contact us" form
function validateForm(formName, errorMessageElement)
{
	var fullErrorMessage = "";
	var errorStringPrefix = "Please provide a value for : ";
	var requiredFields = getElementsByClassName(document, "*", "requiredField");
	var eMailValidationMessage = "";
	var returnVal = true;
	
	// clear any previous validation messages
	var parentElem = document.getElementById('contactUsContent');
	var childElem = document.getElementById('validationErrorMessage');
	if (childElem != null)
	{
		parentElem.removeChild(childElem);
	}

	for(var i=0; i < requiredFields.length; i++)
	{
		oElement = requiredFields[i];
		if (oElement.name.indexOf('email') > -1)
		{
			// NOTE: the parameter 'email' is the name of the input field used to hold the email 
			// address on the HTML form that is being validated
			eMailValidationMessage = isEmailValid(formName, errorMessageElement);
		}
		else
		{
			if(oElement.value.length < 1)
			{
				fullErrorMessage += "<span class='validationMessage'>" + errorStringPrefix + oElement.name + "</span> <br/>";
				if (returnVal == true)
				{
					returnVal = false;
				}
			}
		}
	}
	
	if (returnVal == true && eMailValidationMessage.length > 0)
	{
		returnVal = false;
	}
	
	insertValidationMessage(eMailValidationMessage + fullErrorMessage);
	return returnVal;
}

// Helper function for inserting error message for validation
function insertValidationMessage(validationMessage)
{
	var elementToInsertAfter = document.getElementById('contactUsContent');
	var newDiv = document.createElement('div');
	var divIdName = 'validationErrorMessage';
	var targetElem = document.getElementById('contactUsFieldSet');
	newDiv.setAttribute('id',divIdName);
	newDiv.innerHTML = validationMessage;
	elementToInsertAfter.insertBefore(newDiv, targetElem);
}

// define global var that is the html filename of current page
var currentPageHTMLFileName = "";

if (windowLocation.indexOf('?') > 0)
{
	currentPageHTMLFileName = windowLocation.substring(windowLocation.lastIndexOf('/') + 1, windowLocation.indexOf('?'));
}
else
{
	currentPageHTMLFileName = windowLocation.substring(windowLocation.lastIndexOf('/') + 1, windowLocation.length);
}

// This simple function will facilitate the display of all customers by unhiding the allLineOfBusinessCustomers 
// div tag and removing the right hand col from the DOM on a given LOB html file.  This function will also
// determine the heading of the page content based on the URL of the page the user is on
// *NOTE : not currently called, however, left in case it is required again
function showAllLOBCustomers()
{
	subsectionAllCustomersHeaderText = getSubsectionTextByCurrentPage();
	//alert(subsectionAllCustomersHeaderText);
	var priorityCustomerList = document.getElementById("priorityLineOfBusinessCustomers");
	var allCustomers = document.getElementById("allLineOfBusinessCustomers");
	var lobContentAreaBody = document.getElementById("contentAreaBody");
	lobContentAreaBody.className="allCustomers";
 	lobContentAreaBody.innerHTML = "<div id=\"lobAllCustomersPageHeader\">" + subsectionAllCustomersHeaderText + 
									" Customers </div>" + allCustomers.innerHTML;
 	(document.getElementById("contentArea")).removeChild(document.getElementById("contentAreaRightCol"));
}

function showAllProjects()
{
	window.location = "/aboutUs/projectMap.html";
}

// This function returns the text of the left nav LOB subsection link determined by the current page
function getSubsectionTextByCurrentPage()
{
	var sideNavAnchorElems = getElementsByClassName(document.getElementById("sideNavigation"), "a", "");
	var sideNavAnchorTarget;
	var targetIndex;

	for (i=0; i<sideNavAnchorElems.length; i++)
	{
		var sideNavInnerHTML = sideNavAnchorElems[i].innerHTML;
		var sideNavText = sideNavInnerHTML.substring(sideNavInnerHTML.indexOf('>') + 1, sideNavInnerHTML.length)
		
		sideNavAnchorTarget = sideNavAnchorElems[i].href;
		targetIndex = sideNavAnchorTarget.indexOf(currentPageHTMLFileName);
		if (targetIndex >= 0)
		{
			return sideNavText
		}
	}
}

// Function for toggling the display of a submenu, given the div id of that contains the submenu items.
function toggleSubMenu(subMenuDivId)
{
	var subMenuDiv = document.getElementById(subMenuDivId);
	var arrowImage = getSubSectionArrowImageRef(subMenuDivId);
	
	//alert("inside toggleSubMenu and " + subMenuDiv.id + "'s display style is : " + subMenuDiv.style.display);
	if (subMenuDiv.style.display == '' || subMenuDiv.style.display == 'none')
	{
		arrowImage.setAttribute('src','/images/arrowDown.gif');
		subMenuDiv.style.display = "block";
	}
	else
	{
		arrowImage.setAttribute('src','/images/arrow.gif');
		subMenuDiv.style.display = "";
	}
	//alert("after" + subMenuDiv.style.display);
}

// helper function to retrieve a reference to the correct arrow image
function getSubSectionArrowImageRef(subMenuDivId)
{
	var arrowImages = getElementsByClassName(document, 
						"img", "sideNavArrow");

	for (k=0; k<arrowImages.length; k++)
	{
		if (arrowImages[k].parentNode.id.toUpperCase() == (subMenuDivId + "HeaderLink").toUpperCase())
		{
			//alert(arrowImages[k]);
			return arrowImages[k];
		}
	}
}

// This function will act as a main "router" to facilitate side navigation and coordination of 
// subsection body content stylings with this side navigation.  This function will be called from 
// the body tag's onload attribute for every page of the site and should not grow too large.  It 
// should only apply css classes to specific divs NOT specific stylings to specific divs
// for performance and maintainability reasons.  In doing this, the detailed stylings are still 
// maintained in the css file, whereas this function simply maps the subsection stylings to the 
// appropriate div tags
function energyServicesMain() 
{
 	//alert("currentPage : " + currentPageHTMLFileName);
	//alert(window.location);
	//alert("aboutUs URL param value : " + getURLParamValue('aboutUsDisplay'));
	//alert("business Lines URL param value : " + getURLParamValue('businessLinesDisplay'));
	//alert("careers URL param value : " + getURLParamValue('careersDisplay'));

	getSecuredUnsecuredURLPrefix('secured');
	getSecuredUnsecuredURLPrefix('unsecured');

	maintainStateOfLeftNav();
	setWindowTitleAndPageTitleToLeftNavClickedLinkText(currentPageHTMLFileName);
	
	if (currentPageHTMLFileName == 'index.html')
	{
		document.getElementById("homeHeaderLink").style.display = "none";
	}
	
	switch(currentPageHTMLFileName)
	{
		case 'lobOnSite.html':
		{
			setSubsectionStyleClasses('onsiteLeftNavAndLOBHeader','onsiteLOBRightColBorder',
										'onsiteLOBLink','onsiteLOBPopupBottomBorder','onsitePopupBottomBorder');
			break;
		}
		case 'lobPetCoke.html':
		{
			setSubsectionStyleClasses('petcokeLeftNavAndLOBHeader','petcokeLOBRightColBorder',
										'petcokeLOBLink','petcokeLOBPopupBottomBorder');
			break;
		}
		case 'lobPulpPaper.html':
		{
			setSubsectionStyleClasses('pulpPaperLeftNavAndLOBHeader','pulpPaperLOBRightColBorder',
										'pulpPaperLOBLink','pulpPaperLOBPopupBottomBorder');
			break;
		}
		case 'lobSteel.html':
		{
			setSubsectionStyleClasses('steelLeftNavAndLOBHeader','steelLOBRightColBorder',
										'steelLOBLink','steelLOBPopupBottomBorder');
			break;
		}
		case 'lobPowerAndRenewables.html':
		{
			setSubsectionStyleClasses('powerAndRenewablesLeftNavAndLOBHeader','powerAndRenewablesLOBRightColBorder',
										'powerAndRenewablesLOBLink','powerAndRenewablesLOBPopupBottomBorder');
			break;
		}
		case 'lobLandingPage.html':
		{
			toggleSubMenu('businessLines');
			break;
		}
		case 'aboutUs.html':
		{
			toggleSubMenu('aboutUs');
			break;
		}
		case 'executiveContactUs.html':
		{
			var emailToAddress = args.emailTo;
			var emailForm = document.getElementById('recipient');
				emailForm.setAttribute("value", emailToAddress + "@dteenergy.com");
		}
/* 		case 'careers.html':
		{
			toggleSubMenu('careers');
			break;
		}
		case 'googleSearch.html':
		{
			document.getElementById('searchArea').style.display = 'none';
		}
 */}
}

// intercepts left nav link targets and redirects to correct page passing parameters to maintain state 
// of expanded left nav subsections
function leftNavController(target)
{
	var newTarget;

	if(target.indexOf("?") > 0)
	{
		newTarget = target  + "&businessLinesDisplay=" + document.getElementById('businessLines').style.display;
	}
	else
	{
		newTarget = target  + "?businessLinesDisplay=" + document.getElementById('businessLines').style.display;
	}

	newTarget += "&aboutUsDisplay=" + document.getElementById('aboutUs').style.display + 
						   "&careersDisplay=" + document.getElementById('careers').style.display;
	
	if (target.indexOf('ontactUs') > 0)
	{
 		newTarget = secureBaseURL + newTarget;
	}
	else
	{
		newTarget = unsecureBaseURL + newTarget;
	}

	window.location = newTarget;
}

// sets the window title and the pageTitle equal to the text of the left nav link, if one is found
// that has the current page as a target, otherwise sets the pageTitle and window title to the value
// entered via the document generic template otherwise leaves it blank.
function setWindowTitleAndPageTitleToLeftNavClickedLinkText(currentPageHTMLFileName)
{
	var leftNavText = getSubsectionTextByCurrentPage();
	var contentAreaBodyDiv = document.getElementById('contentAreaBody');
	var pageTitle;

	if (currentPageHTMLFileName.indexOf('PulpAndPaper') >= 0)
	{
		// handle ampersand in Pulp & Paper as special case b/c & renders as &amp; in window title otherwise
		document.title = "DTE Energy Services - Pulp & Paper";
		pageTitle = "Pulp & Paper";
	}
	else if (currentPageHTMLFileName.indexOf('index.html') >= 0)
	{
		// handle home page left nav as special case b/c we don't want to sync page title and window title in this case
		document.title = "DTE Energy Services";
		pageTitle = "DTE Energy Services";
	}
	else if (currentPageHTMLFileName.indexOf('googleSearch.html') >= 0)
	{
		document.title = "DTE Energy Services - Search Results";
	}
	else if (leftNavText != null && leftNavText.length > 0)
	{
		document.title = "DTE Energy Services - " + leftNavText;
		pageTitle = leftNavText;
	}
	else
	{
		// last attempt is to assume that a title was specified when content created in Web Publisher
		document.title = document.getElementById('energyServicesTitle').innerHTML;
		pageTitle = document.title;
	}
	
	insertPageTitle(pageTitle);
}

// inserts the page title into the body of the page
function insertPageTitle (pageTitle)
{
	var contentAreaBodyDiv = document.getElementById('contentAreaBody');
	var pageTitleDiv = document.createElement("div");
	
	pageTitleDiv.setAttribute("id", "pageTitle");
	pageTitleDiv.innerHTML = pageTitle;
	
	if (contentAreaBodyDiv != null && pageTitle.length > 0)
	{
		contentAreaBodyDiv.insertBefore(pageTitleDiv, contentAreaBodyDiv.childNodes[0]);
	}
}

function getArgs(){
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for (var i=0; i<pairs.length; i++)
	{
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value=pairs[i].substring(pos+1);
		args[argname]=unescape(value);
	}
	return args;
}

function maintainStateOfLeftNav()
{
	if (currentPageHTMLFileName != 'index.html')
	{	
    var subSection = "";
    var leftNavStateMap = new Object();
  
    leftNavStateMap.aboutUs = args.aboutUsDisplay;
    leftNavStateMap.businessLines = args.businessLinesDisplay;
    leftNavStateMap.careers = args.careersDisplay;
  
    for (subSection in leftNavStateMap)
    {
      //alert(subSection + "'s display.style from URL = <" + getURLParamValue(subSection + "Display") + ">");
      //alert(subSection + "'s display.style in leftNavMap = <" + leftNavStateMap[subSection] + ">");
      var subMenuDiv = document.getElementById(subSection);
      var arrowImage = getSubSectionArrowImageRef(subSection);
      //alert(leftNavStateMap[subSection]);
      if (leftNavStateMap[subSection] == 'block')
      {
        arrowImage.setAttribute('src','/images/arrowDown.gif');
      }
      else
      {
        arrowImage.setAttribute('src','/images/arrow.gif');
      }
      document.getElementById(subSection).style.display = leftNavStateMap[subSection];
    }
  }
}

// Helper function to set the classes of the subsections
function setSubsectionStyleClasses(lobHeaderClassName, lobPriorityCustDivClassName, 
									lobPopupCustLinkClassName, lobPopupBottomBorderClassName) 
{
	var lobHeadDiv = document.getElementById("priorityLineOfBusinessCustomersHeading");
	var lobPriorityCustomersDiv = document.getElementById("priorityLineOfBusinessCustomers");
	var sideNavDivs = getElementsByClassName(document, "div", lobHeaderClassName + " contextNavigationLink");
	var sideNavAnchors = sideNavDivs[0].getElementsByTagName("a");
	var customerPopupLinkDivs = getElementsByClassName(document, "div", "customerPopupLink");
	var popupBodyDivs = getElementsByClassName(document, "div", "popupBody");

	lobHeadDiv.className = lobHeaderClassName;
	lobPriorityCustomersDiv.className = lobPriorityCustDivClassName;
	
    for (var i=0; i < customerPopupLinkDivs.length; i++)
    {
         customerPopupLinkDivs[i].className = lobPopupCustLinkClassName + " " + customerPopupLinkDivs[i].className;
	}

    for (var j=0; j < popupBodyDivs.length; j++)
    {
         popupBodyDivs[j].className = popupBodyDivs[j].className + " " + lobPopupBottomBorderClassName;
	}

}

// Utility function to retrieve all elements within an element and tag scope with a specified class name
function getElementsByClassName(oElement, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElement.all)? oElement.all : oElement.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++)
	{
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className))
		{
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function next_focus(formName, elementName, elementLength, nextElement) {
        if(document.forms[formName].elements[elementName].value.length == elementLength)
                document.forms[formName].elements[nextElement].focus()
        return true
}