//--------------------
// page URL variables
//--------------------

// the full URL of the page being called
var fullURL = location.href;
// the URL of the page being called without the domain and the querystring
var loc=location.pathname;
// the loc is split to get the file path and file name
var pathElements = loc.split("/");
// if there is no page name, the default is index.html
var fileName = (pathElements[(pathElements.length-1)] == "") ? 'index.html' : pathElements[(pathElements.length-1)];
// the filePath is the loc without the fileName
var filePath = loc.replace(fileName, "");
var queryString = '';
// assign a querystring value if theer is one
if (fullURL.indexOf('?') != -1){
	pathElements = fullURL.split("?");
	queryString = pathElements[1];
}

var fullPath = location.href;
var fullPathElements = fullPath.split("/");
var serverProtocol = fullPathElements[0];
var serverName = fullPathElements[2];
var protocolAndHost = serverProtocol + "//" + serverName;
var isSecureProtocol= (serverProtocol.indexOf('https') !=-1)?true:false;

var onCMS = (serverName.indexOf('cms') !=-1) || (serverName.indexOf('cms') !=-1)?true:false;
var onDev = (serverName.indexOf('extcdev') !=-1) || (serverName.indexOf('he2lxweb-4') !=-1)?true:false;
var onStaging = (serverName.indexOf('extcstage') !=-1) || (serverName.indexOf('he2lxweb-5') !=-1)?true:false;
var onProduction = (onCMS == false) && (onDev == false) && (onStaging == false)?true:false;

// domino pages requires that this variable exist
var IMGPath ="/images";


//--------------------
// object storing information for an element matching the URL
//--------------------

function arrayElement(url, name, level, position, parents, matchFound, matchType) {
	this.url = url;
	this.name = name;
	this.level = level;
	this.position = position;
	this.parents = parents;
	this.matchFound = matchFound;
	this.matchType = matchType;
}

var parentArray=new Array();
var matchedElement = new arrayElement('', '', '', '', parentArray, false, '');


//--------------------
// navLink object: leftnav links are an array of objects
//--------------------

function navLink(id,name,url,level,environment,subItemNum) {
    this.id=id;
    this.name=name;
    this.url=url;
    this.level=level;
    this.environment=environment;
    this.subItemNum=subItemNum;
}


/*-----[ FUNCTION isFullyQualifiedURL ]---------------*/

function isFullyQualifiedURL(urlString){
    var booleanValue =(urlString.indexOf('http://') !=-1) || (urlString.indexOf('https://') !=-1) || (urlString.indexOf('mailto:') !=-1)?true:false;
    return booleanValue;
}// end function


/*-----[ FUNCTION isLastArrayItem ]---------------*/

function isLastArrayItem(arrayIndex){
  if (navArray){
    var arrayLength = navArray.length;
    if ((arrayIndex+1) == arrayLength){
      return true;
    } else {
      return false;
    }
  }
}// end function


//--------------------
// leftNav function
//--------------------

function displaySecondaryNavigation(navigationArray){
	
	//--------------------
	// page URL variables
	//--------------------
	
	// the full URL of the page being called
	var fullURL = location.href;
	// the URL of the page being called without the domain and the querystring
	var loc=location.pathname;
	// the loc is split to get the file path and file name
	var pathElements = loc.split("/");
	// if there is no page name, the default is index.html
	var fileName = (pathElements[(pathElements.length-1)] == "") ? 'index.html' : pathElements[(pathElements.length-1)];
	// the filePath is the loc without the fileName
	var filePath = loc.replace(fileName, "");
	var queryString = '';
	// assign a querystring value if theer is one
	if (fullURL.indexOf('?') != -1){
		pathElements = fullURL.split("?");
		queryString = pathElements[1];
	}
	// domino pages requires that this variable exist
	var IMGPath ="/images";
/*
PSEUDOCODE

LOGIC Portion

loop through array ends when a match is found
	for each item:
		identify the level
		if the level is 0:
			store the id in an array in the 0 position and overwrite any older values
		if the level is 1:
			store the id in an array in the 1 position and overwrite any older values
		if the level is 2:
			store the id in an array in the 2 position and overwrite any older values	
		see if there's a match
			try a full URL match
			try a file path, file name, and querystring match
			try a file path and file name match
			try just a path match
			if there is a match
				grab its ID and grab its level
				

DISPLAY Portion

if first item in array:
	write <ul>
for each item:
	check to see if it matches the parent IDs of the matched item
	if it does:
		assign the css var to be class="on"
	if it doesn't:
		assign the css var to be empty
	check to see if there is a next item
	if there is:
		is a level up, a level down, or same level
		if next item is a level up:
			write <li><a href="link">Title</a></li>
			write </ul>
			write </li>
		if next item is a level down:
			write <li><a href="link">Title</a>
			write <ul>
		if next item is the same level:
			write <li><a href="link">Title</a></li>
	if there isn't:
			write <li><a href="link">Title</a></li>
			write </ul>
*/


	//--------------------
	// loop through leftnav array and try to find a match
	//--------------------
	
	function findMatch (urlString, matchType){
		var elementId = '';
		var elementName = '';
		var elementURL = '';
		var elementLevel = '';
		
		var lastCharPos;
		
	
		for (var i=(navigationArray.length - 1); i > 0 ; i--){
			elementId = navigationArray[i].id;
			elementName = navigationArray[i].name;
			elementURL = navigationArray[i].url;
			elementLevel = navigationArray[i].level;

			lastCharPos = elementId.length - 1;
	
			//--------------------
			// for a file path, name, and querystring match to occur:
			//  the string has to equal the elementId precisely
			//  no other match can be found yet
			//  the filetype must be a  path, name, and querystring match and not be a level 4 item
			//--------------------
			if(elementId == urlString && matchedElement.matchFound == false && matchType == 'file path, name, and querystring' && elementLevel != 4){
				matchedElement.id = elementId;
				matchedElement.url = elementURL;
				matchedElement.name = elementName;
				matchedElement.level = elementLevel;
				matchedElement.position = i;
				matchedElement.matchFound = true;
				matchedElement.matchType = matchType;
				
				// convert level value to integer
				matchedElement.level = parseInt(matchedElement.level);
			} 
			//--------------------
			// for a file path and name match to occur:
			//  the string has to equal the elementId precisely
			//  no other match can be found yet
			//  the filetype must be a  path and name match and not be a level 4 item
			//--------------------
			else if(elementId == urlString && matchedElement.matchFound == false && matchType == 'file path and name' && elementLevel != 4){
				matchedElement.id = elementId;
				matchedElement.url = elementURL;
				matchedElement.name = elementName;
				matchedElement.level = elementLevel;
				matchedElement.position = i;
				matchedElement.matchFound = true;
				matchedElement.matchType = matchType;
				
				// convert level value to integer
				matchedElement.level = parseInt(matchedElement.level);
			} 
			//--------------------
			// for a part of file path and name match to occur:
			//  the string has to contain the elementId
			//  no other match can be found yet
			//  the filetype must be a part of path and name match and not be a level 4 item
			//--------------------
			else if(elementId.charAt(lastCharPos) != '/' && urlString.indexOf(elementId)!= -1 && matchedElement.matchFound == false && matchType == 'part of file path and name' && elementLevel == 4){
				matchedElement.id = elementId;
				matchedElement.url = elementURL;
				matchedElement.name = elementName;
				matchedElement.level = elementLevel;
				matchedElement.position = i;
				matchedElement.matchFound = true;
				matchedElement.matchType = matchType;
				
				// convert level value to integer
				matchedElement.level = parseInt(matchedElement.level);
			} 
			//--------------------
			// for a seciondary match to occur:
			//  the file path has to contain some of the elementId
			//  no other match can be found yet
			//  the filetype must be a file path match and must be a level 4 item
			//--------------------		
			else if (urlString.indexOf(elementId)!= -1 && matchedElement.matchFound == false && matchType == 'file path' && elementLevel == 4) {
				matchedElement.id = elementId;
				matchedElement.url = elementURL;
				matchedElement.name = elementName;
				matchedElement.level = elementLevel;
				matchedElement.position = i;
				matchedElement.matchFound = true;
				matchedElement.matchType = matchType;
				
				// convert level value to integer
				matchedElement.level = parseInt(matchedElement.level);
			}
		}
	}
	
	function levelShouldBeDisplayed (currentPosition, currentDisplayValue, elementLevel, displayLevel){
		
		//--------------------
		// for a level to be displayed:
		//  the string has to meet the elementId
		//  no other match can be found yet
		//  the filetype cannot be a file path match unless it is a level 4 item
		//  it has to be immediately after the matching element and is a level lower than the matching element 
		//--------------------
	
		if (currentDisplayValue == false){
			if (matchedElement.parents.length > (displayLevel - 1) ){
				if (currentPosition == matchedElement.parents[(displayLevel - 1)].position){
					return true;
				} 
			// if position is match position, set all displays to true so that children links can be displayed
			} else if (currentPosition == matchedElement.position) {
					return true;
			}
		// anytime the element level goes down, return false
		} else if ( (currentDisplayValue == true) && (elementLevel < displayLevel) ) {
			return false;
		// anytime the element level is 2 greater then the match level, return false
		} else if ( (currentDisplayValue == true) && (displayLevel == (matchedElement.level + 2)) ) {
			
			// debug code 
			// document.write(elementLevel + ', ' + (matchedElement.level + 1) + ', ');
			
			return false;
		} else {
			return true;
		}
		
		return false;
	}
	
	function linkShouldBeDisplayed (elementLevel, displayLevel1, displayLevel2, displayLevel3){
		if( (elementLevel == 0) || (elementLevel == 1  && displayLevel1 == true) || (elementLevel == 2 && displayLevel2 == true)  || (elementLevel == 3 && displayLevel3 == true) ){
			return true;
		} else {
			return false;
		}
	}
	
	function getNextElementLevel (linkPosition, displayLevel1, displayLevel2, displayLevel3){
		var elementLevel = navigationArray[linkPosition].level;
		elementLevel = parseInt(elementLevel);
		var nextElementLevel = 0;
		var nextElementEnvironment = "";
	
		// if the element is the last one in the array, set it to 0
		if ((linkPosition + 1) == navigationArray.length){
			return nextElementLevel;
		} else {
			for (var i=linkPosition; i < (navigationArray.length - 1); i++){
				nextElementLevel = navigationArray[i + 1].level;
				nextElementLevel = parseInt(nextElementLevel);
				nextElementEnvironment = navigationArray[i + 1].environment;
				
				//**********
				// If environment value is "qa" but we're not on dev or staging, skip this iteration
				// If environment value is "d" but we're not on dev, skip this iteration
				// If environment value is "s" but we're not on staging, skip this iteration
				// If environment value is "p" but we're not on production, skip this iteration
				//**********
				if(nextElementEnvironment){
					nextElementEnvironment = nextElementEnvironment.toLowerCase();
					if (((nextElementEnvironment == 'qa' && !onDev) && (nextElementEnvironment == 'qa' && !onStaging)) || (nextElementEnvironment == 'd' && !onDev) || (nextElementEnvironment == 's' && !onStaging) || (nextElementEnvironment == 'p' && !onProduction)){
						continue;
					}
				}

				if( linkShouldBeDisplayed (nextElementLevel, displayLevel1, displayLevel2, displayLevel3) == true ){
					
					// debug code 
					//document.write('crrElPos:' + nextElementLevel + ',nextElPos: ' + (i+1) + ',nextEl: ' + nextElementLevel + '</br>');
					//document.write('Dis1:' + displayLevel1 + ',Dis2: ' + displayLevel2 + ',Dis3: ' + displayLevel3 + '</br>');
					
					return nextElementLevel;
				}
			}
		}
		
		return elementLevel;
	}	
	

	//--------------------
	// try to match progressively less strict url string types until a match is found:
	//  try a full URL match
	//  try a file path, file name, and querystring match
	//  try a file path and file name match
	//  try just a path match
	//--------------------
	
	var urlString = fullURL;
	
	findMatch(urlString, 'full URL');
	
	if (matchedElement.matchFound == false){
		urlString = filePath + fileName + '?' + queryString;
		findMatch(urlString, 'file path, name, and querystring');
	}
	if (matchedElement.matchFound == false){
		urlString = filePath + fileName;
		findMatch(urlString, 'file path and name');
	}
	if (matchedElement.matchFound == false){
		urlString = filePath + fileName;
		findMatch(urlString, 'part of file path and name');
	}
	if (matchedElement.matchFound == false){
		urlString = filePath;
		findMatch(urlString, 'file path');
	}		


	//--------------------
	// if there is a match find its parents
	// 	in the case of a level 4 match, the first non-level 4 item sets the value for the current level
	//--------------------
	
	if (matchedElement.matchFound == true){
		var currentLevel = matchedElement.level;

		// if there's a level 4 match, the first non-level 4 item sets the value for the current level
		if (currentLevel == 4){
			for (var i=matchedElement.position; i >= 0; i--){
				if (navigationArray[i].level < currentLevel){
					currentLevel = parseInt(navigationArray[i].level);
					break;
				}
			}		
		}
		
		// incremented by 1 for the logic below
		currentLevel = currentLevel + 1;

		for (var i=matchedElement.position; i >= 0; i--){
			if (navigationArray[i].level < currentLevel){
				currentLevel = currentLevel - 1;
				//test matchedElement.parents[currentLevel] = i;
				matchedElement.parents[currentLevel] = new arrayElement(navigationArray[i].id, navigationArray[i].name, currentLevel, i, '', true, '');
				// debug code 
				//document.write(matchedElement.position + ', ' + currentLevel + '<br />');
			}
		}
		
	}

	
	//--------------------
	// debug write to browser
	//--------------------

	/*

	document.write('<strong>PATH INFORMATION</strong><br />');
	document.write('fullPath: ' + fullPath + '<br />');
	document.write('fullPathElements: ' + fullPathElements + '<br />');
	document.write('serverProtocol: ' + serverProtocol + '<br />');
	document.write('serverName: ' + serverName + '<br />');
	document.write('protocolAndHost: ' + protocolAndHost + '<br />');
	document.write('isSecureProtocol: ' + isSecureProtocol + '<br />');

	document.write('<strong>ENVIRONMENT INFORMATION</strong><br />');
	document.write('onCMS: ' + onCMS + '<br />');
	document.write('onDev: ' + onDev + '<br />');
	document.write('onStaging: ' + onStaging + '<br />');
	document.write('onProduction: ' + onProduction + '<br />');

	document.write('<strong>MATCH INFORMATION</strong><br />');
	document.write(fullURL + '<br />');
	document.write(filePath + '<br />');
	document.write(fileName + '<br />');
	document.write(queryString + '<br />');

	document.write('matchedElement URL =' + matchedElement.url + '<br />');
	document.write('matchedElement level =' + matchedElement.level + '<br />');
	document.write('matchedElement.position =' + matchedElement.position + '<br />');
	document.write('matchedElement parents =' + matchedElement.parents + '<br />');
	document.write('matchedElement number of parents =' + matchedElement.parents.length + '<br />');
	document.write('matchedElement matchFound =' + matchedElement.matchFound + '<br />');
	document.write('matchedElement matchType =' + matchedElement.matchType + '<br />');	

	document.write('<br />');

	document.write('<strong>PARENT INFORMATION</strong><br />');
	document.write('matchedElement number of parents =' + matchedElement.parents.length + '<br />');	
	if (matchedElement.parents.length != 0){
		for (var i=0; i < matchedElement.parents.length; i++){
			document.write('parents # ' + i + ':' + matchedElement.parents[i].url + '<br />');
			document.write('parents # ' + i + ':' + matchedElement.parents[i].name + '<br />');	
			document.write('parents # ' + i + ':' + matchedElement.parents[i].level + '<br />');
			document.write('parents # ' + i + ':' + matchedElement.parents[i].position + '<br />');
		}
	}
	
	document.write('<br />');

	for (var i=0; i < navigationArray.length; i++){
		document.write(navigationArray[i].id + '<br />');
	}
	*/
	

	var numberOfParents = matchedElement.parents.length;
	var currentParent = 0;
	
	var elementURL = '';
	var elementName = '';
	var elementLevel = 0;
	var elementEnvironment = '';
	var isLastElement = false;
	var isNextLastElement = false;
	
	var appendedDomain = '';
	
	var nextPosition = 0;
	var nextElementLevel;
	
	var displayLevel1 = false;
	var displayLevel2 = false;
	var displayLevel3 = false;
	
	var cssString = '';

	// leftnav div
	document.write('<div id="secondaryNavigation">');
	// start nav list
	document.write('<ul id="secondaryNavigationList">');
	

	//--------------------
	// loop through array and display list items
	//--------------------
	
	
	for (var i=0; i < navigationArray.length; i++){

		//document.write(i + ' of ' + navigationArray.length  + ', ');
	
		elementURL = navigationArray[i].url;
		elementName = navigationArray[i].name;
		elementLevel = navigationArray[i].level;
		elementEnvironment = navigationArray[i].environment;
		isLastElement = (i == (navigationArray.length - 1)) ? true : false;
		isNextLastElement = (i == (navigationArray.length - 2)) ? true : false;
		
		appendedDomain = ''; /* set default to empty for each nav item */

		//**********
		// If environment value is "qa" but we're not on dev or staging, skip this iteration
		// If environment value is "d" but we're not on dev, skip this iteration
		// If environment value is "s" but we're not on staging, skip this iteration
		// If environment value is "p" but we're not on production, skip this iteration
		//**********
		if(elementEnvironment){
			elementEnvironment = elementEnvironment.toLowerCase();
			if (((elementEnvironment == 'qa' && !onDev) && (elementEnvironment == 'qa' && !onStaging)) || (elementEnvironment == 'd' && !onDev) || (elementEnvironment == 's' && !onStaging) || (elementEnvironment == 'p' && !onProduction)){
				continue;
			}
		}	
		// debug code
		//document.write(i + ', ' + elementLevel + ','+ elementName + ',' + isNextLastElement +'<br>');
		//document.write(navigationArray.length + '<br>');

		
		//**********
		// Append protocol and host to url if current page is secured
		// Appends www.freddiemac.com if host is not recognized /* site-specific */
		//**********
		
		if (!isFullyQualifiedURL(elementURL)){
			if (isSecureProtocol){
				appendedDomain ="http://www.freddiemac.com"; /* site-specific */
				elementURL = appendedDomain + elementURL;
			} else if (!onCMS && !onDev && !onStaging){
				appendedDomain ="http://www.freddiemac.com"; /* site-specific */
				elementURL = appendedDomain + elementURL;
			}
		}		
		
		//--------------------
		// if there is a parent at the currentParent level
		//   if current position matches current parent position or the current position matches the matched element position
		//     increment parent array item
		//     turn on link class for this element
		//--------------------

		cssString = '';
		
		if (matchedElement.parents[currentParent]){
			if ( (i == matchedElement.parents[currentParent].position) || (i == matchedElement.position) ){

				if ((currentParent == 0) && (i == matchedElement.parents[currentParent].position)){
					cssString = 'class = "on';
				} 
				
				// level 1 links that are expanded have a different appearance and so must be assigned an "expanded" class
				else if 
				(
				((currentParent == 1) && (i == matchedElement.parents[currentParent].position))
				){
					cssString = 'class = "expanded';					
				}
				else if ((matchedElement.level == 4 ) && (currentParent == matchedElement.parents.length - 1))
				{
					cssString = 'class = "expanded';					
				}	
				
				currentParent = currentParent + 1;
			}
		}
		
		if ( (matchedElement.level != 4 ) && (i == matchedElement.position) ){
			cssString = 'class = "on';
		}
		
		if (i==0){
			cssString += ' firstNavLink"';
		} else if (cssString != '') {
			cssString += '"';
		}
		 
		//--------------------
		// determine if level 1, 2 and 3 links should be displayed
		//   displayLevel should be set and level links should be displayed if
		//   	parents.length is greater than level
		//		shouldDisplayLevel is true
		//			it's activated once the second parent is hit and it's deactivated once the current level is greater than the current level + 2
		//--------------------
		
		displayLevel1 = levelShouldBeDisplayed(i, displayLevel1, elementLevel, 1);
		displayLevel2 = levelShouldBeDisplayed(i, displayLevel2, elementLevel, 2);
		displayLevel3 = levelShouldBeDisplayed(i, displayLevel3, elementLevel, 3);
			



		// display link:
		// if it's level 0 or 1
		// if it's level 2 and displayLevel2 == true
		// if it's level 3 and displayLevel3 == true
		
		// debug code
		// var displayVar = linkShouldBeDisplayed (elementLevel, displayLevel1, displayLevel2, displayLevel3);
		// document.write(displayLevel1 + ', ' + displayLevel2 + ', ' + displayLevel3 + ', ' + displayVar + '<br />');
		

		if ( linkShouldBeDisplayed (elementLevel, displayLevel1, displayLevel2, displayLevel3) ){
		
		
			// get the next element level that will be displayed
			nextElementLevel = getNextElementLevel(i, displayLevel1, displayLevel2, displayLevel3);
			
			// debug code
			// document.write('::' + i + ' of ' + navigationArray.length + ',' + elementLevel + ', ' + nextElementLevel + '<br />');
			
		
			//--------------------		
			// if next item is a level up:
			//	write <li><a href="link">Title</a></li>
			//	write </ul>
			//	write </li>
			//--------------------
	
			if (nextElementLevel < elementLevel){
				// debug
				//document.write('<a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a>');
			
				document.write('<li><a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a></li>');
				
				for (var j=nextElementLevel; j < (elementLevel); j++){
					document.write('</ul></li>');
				}

			}
			
			
			//--------------------		
			// if next item is a level down:
			//	write <li><a href="link">Title</a>
			//	write <ul>
			//--------------------
	
			if (nextElementLevel > elementLevel){
				// debug
				//document.write('<a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a>');


				document.write('<li><a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a><ul>');
			}	
			
						
			//--------------------		
			// if next item is the same level:
			// write <li><a href="link">Title</a></li>
			//--------------------
	
			if (nextElementLevel == elementLevel){
				// debug
				//document.write('<a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a>');

				document.write('<li><a href="' + elementURL + '" ' + cssString + '>' + elementName + '</a></li>');
			}
			
			// debug code
			//document.write('<br/>----------------------------------------------DISPLAY ' + i + '<br />');
				
		}	
	}
	
	// debug code
	// document.write('<br />');
	
/*
for each item:
	check to see if it matches the parent IDs of the matched item
	if it does:
		assign the css var to be class="on"
	if it doesn't:
		assign the css var to be empty
	check to see if there is a next item
	if there is:
		is a level up, a level down, or same level
		if next item is a level up:
			write <li><a href="link">Title</a></li>
			write </ul>
			write </li>
		if next item is a level down:
			write <li><a href="link">Title</a>
			write <ul>
		if next item is the same level:
			write <li><a href="link">Title</a></li>
	if there isn't:
			write <li><a href="link">Title</a></li>
			write </ul>
			
	don't display:
		level 4 elements
		level 3 elements whose siblings aren't the found item
		
	do display:
		level 3 elements where the position is greater than the parent 
*/
	

	// close nav list
	document.write('</ul>');
	// close leftnav div
	document.write('</div>');

}


function displayGoToNavigation(matchedElement){

	var backToString = '';
	var backToURL = '';
	var backToName = '';
/* 
Pre 2007 Navigation - comment back in for visual flip
*/
/*
	document.write('<span class="breadcrumbs">');
	
	if (matchedElement.url != ''){
		if (matchedElement.level == 4){
			backToURL = matchedElement.parents[(matchedElement.parents.length - 1)].url;
			backToName = matchedElement.parents[(matchedElement.parents.length - 1)].name;
			document.write('<a href="' + backToURL + '">Go to ' + backToName + '</a>');
		} else if (matchedElement.level != 4 && matchedElement.matchType == 'file path'){
			backToURL = matchedElement.url;
			backToName = matchedElement.name;
			document.write('<a href="' + backToURL + '">Go to ' + backToName + '</a>');
		}
	}
	document.write('&nbsp;</span>');
*/
}
