//returns the correct object based on browser object detection
window.createXmlHttpRequest = function()
{
	var request = null;

	if (window.XMLHttpRequest)
	{
		request = new XMLHttpRequest();
	}
	else if (typeof(ActiveXObject != "undefined"))
	{
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}

	return request;
}

function SiteMap(sourceFilePath, sourceFileName)
{
	//if no path is provided, default to current directory
	if (!sourceFilePath) sourceFilePath = "./";
	
	//if no source file name is provided, default to sitemap.xml
	if (!sourceFileName) sourceFileName = "sitemap.xml";

	var sitemap = null;
	
	//for DOM capable browsers, create a new DOM document object and implement the selectNodes and selectSingleNode methods for it
	if (document.implementation && document.implementation.createDocument)
	{
		sitemap = document.implementation.createDocument("","", null);

		//given an xpath and an optional starting node object, find nodes matching the xPath
		Document.prototype.selectNodes = function(xPath, startNode)
		{
			if (!startNode) startNode = this;

			var xPathResult = this.evaluate(xPath, startNode, this.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
			
			var foundNodes = new Array();

			while (node = xPathResult.iterateNext())
			{
				foundNodes.push(node);
			}

			return foundNodes;
		};

		//given an xPath and an optional starting node object, find a single node matching the xPath (or the first element of the nodeList to which it evaluates)
		Document.prototype.selectSingleNode = function(xPath, startNode)
		{
			if (!startNode) startNode = this;
			
			var foundNode = null;
			
			var selectedNodes = this.selectNodes(xPath, startNode);

			if (selectedNodes.length > 0)
			{
				foundNode = selectedNodes[0];
			}
			
			return foundNode;
		};
		

		Document.prototype.loadXML = function(s)
		{
			//parse the string to a new doc
			var parser = new DOMParser();
			var doc2 = parser.parseFromString(s, "text/xml");
			
			// remove all initial children
			while (this.hasChildNodes())
			{
				this.removeChild(this.lastChild);
			}
		
			// insert and import nodes
			for (var i = 0; i < doc2.childNodes.length; i++)
			{
				this.appendChild(this.importNode(doc2.childNodes[i], true));
			}
		}

		
		//add support for the DOMParser if not present
		if (typeof(window.DOMParser) == "undefined")
		{
		   DOMParser = function () {}
		        
		   DOMParser.prototype.parseFromString = function (str, contentType)
		   {
		      if (typeof ActiveXObject != "undefined")
		      {
		         var d = new ActiveXObject("MSXML.DomDocument");
		         d.loadXML(str);
		         return d;
		      }
		      else if (typeof XMLHttpRequest != "undefined")
		      {
		         var req = new XMLHttpRequest;
		         req.open("GET", "data:" + (contentType || "application/xml") +
		                         ";charset=utf-8," + encodeURIComponent(str), false);
		         if (req.overrideMimeType)
		         {
		            req.overrideMimeType(contentType);
		         }
		         
		         req.send(null);
		         return req.responseXML;
		      }
		   }
		}
	}
	else if (window.ActiveXObject) //MS IE
	{
		sitemap = new ActiveXObject("Microsoft.XMLDOM");
	}
	else
	{
		alert("To use this page you need a browser capable of loading XML documents. Microsoft Internet Explorer 5 or greater or Netscape Navigator 6.2 are recommended.");
		return;
	}

	var xmlhttp = window.createXmlHttpRequest();
	xmlhttp.open("GET", sourceFilePath + sourceFileName, false);
	xmlhttp.send(null);

	sitemap.loadXML(xmlhttp.responseText);

	this.sourceXML = sitemap; //store the XML for reuse

	this.currentLocation = "";
	this.pathToCurrentLocation = new Array();
	this.useDirNameAsPageName = false;
	this.currentPageNode = null;
	
	this.getCurrentLocation(); //extract the path to this page from the URL
	this.getNodeFromCurrentLocation(); //use that path as a key to look up this page's node in the XML file
	this.getPathToCurrentLocation(); //build an array of the parent nodes representing the steps to get to this page
}


//returns the name of the page at the third level of the path to the current page
SiteMap.prototype.getPageHeader = function()
{
	var header = "";
	
	if (this.pathToCurrentLocation.length > 1)
	{
		header = this.pathToCurrentLocation[2].longName;
	}

	return header;
}


//extract the path from the site root to the current page from the URL
SiteMap.prototype.getCurrentLocation = function()
{
	var currentLocation = location.pathname.toString();

	//fix the pathname for use when previewing from TeamSite
	if (currentLocation.indexOf("STAGING") != -1)
	{
		currentLocation = currentLocation.split("/iw-mount/default/main/sfn/sfnonline/STAGING/docs/");
		currentLocation = currentLocation[1];		
	}
	else if (currentLocation.indexOf("WORKAREA") != -1)
	{
		currentLocation = currentLocation.split("/iw-mount/default/main/sfn/sfnonline/WORKAREA/updates/docs/");
		currentLocation = currentLocation[1];	
	}
	/*
	else if (currentLocation.indexOf("") != -1)
	{
		currentLocation = currentLocation.split("/");
		currentLocation = currentLocation[1];
	}
	*/

	this.currentLocation = currentLocation;
}


//returns an array of SiteMapNode objects representing the siblings of the current page in the sitemap file
SiteMap.prototype.getCurrentLevel = function()
{
	var currentLevel = null;
	
	if (this.currentPageNode != null)
	{
		currentLevel = this.getLevelFromNode(this.currentPageNode);
	}
	
	return currentLevel;
}


//given a DOM node from the sitemap file, returns an array of SiteMapNode objects representing its immediate child nodes in the sitemap file
SiteMap.prototype.getLevelFromNode = function(parentNode)
{
	var currentLevel = new Array();

	if (parentNode != null && parentNode.hasChildNodes())
	{
		var siblings = parentNode.childNodes;

		//create a new SiteMapNode object for each child of the provided node and add them to the returned array
		for (var i = 0; i < siblings.length; i++)
		{
			if (siblings[i].nodeType != 3)
			{
				currentLevel.push(new SiteMapNode(siblings[i].getAttribute("longName"), siblings[i].getAttribute("href"), siblings[i].nodeName, siblings[i], siblings[i].getAttribute("hideInNav")));
			}
		}
	}
	
	return currentLevel;
}


//given a numeric depth, returns an array of SiteMapNode objects representing the nodes at that depth
SiteMap.prototype.getLevelFromCurrentPath = function(depth)
{
	var level = null;
	
	if (this.pathToCurrentLocation.length >= depth)
	{
		var levelParent = this.pathToCurrentLocation[depth].sourceNode;

		level = this.getLevelFromNode(levelParent);
	}
	
	return level;
}


//returns the depth of the current page in the sitemap
SiteMap.prototype.getCurrentPageDepth = function()
{
	return this.pathToCurrentLocation.length - 1;
}


//treats the path to this page extracted from the URL as an XPath used to find the current page's node in the sitemap file
SiteMap.prototype.getNodeFromCurrentLocation = function()
{
	//create default page name for cases where we've only got the implicit index.html or index.htm in the URL
	if (this.currentLocation.indexOf(".html") == -1 || 
		this.currentLocation.indexOf("index.html") != -1 || 
		this.currentLocation.indexOf("index.htm") != -1)
	{
		if (this.currentLocation.indexOf(".html") == -1)
		{
			this.currentLocation += "index.html";	
		}
	
		this.useDirNameAsPageName = true;
	}

	//split the page name on the period and take the base name as the current node name
	this.currentLocation = this.currentLocation.split(".")[0];

	//find the node in the sitemap corresponding to the path of the current page
	this.currentPageNode = this.sourceXML.selectSingleNode("/docs/" + this.currentLocation);
}


//build the array representation of the path from this page to the root
SiteMap.prototype.getPathToCurrentLocation = function()
{
	this.getAncestry(this.currentPageNode);
	this.pathToCurrentLocation.reverse(); //the path is build in order back from the page - fix to start from top
}


//recursively seek up the tree from the current page
SiteMap.prototype.getAncestry = function(node)
{
	if (node && node.parentNode != null)
	{
		var currentItem = new SiteMapNode(node.getAttribute("longName"), node.getAttribute("href"), node.nodeName, node, node.getAttribute("hideInNav"));
		this.pathToCurrentLocation.push(currentItem)

		if (node.parentNode.nodeType != 9)
		{
			this.getAncestry(node.parentNode); //nodeType 9 is the Document node
		}
	}
}


//used to get the name attribute from a given node
SiteMap.prototype.getPageName = function(node)
{
	return node.getAttribute("longName");
}


//used to get the long name of the current page
SiteMap.prototype.getCurrentPageName = function()
{
	return this.getPageName(this.currentPageNode);
}


//value object which holds data about a particular node in the sitemap
function SiteMapNode(longName, href, pathSegment, sourceNode, hideInNav)
{
	this.longName = longName || "";
	this.href = href || "";
	this.pathSegment = pathSegment || "";
	this.sourceNode = sourceNode || null;
	this.hideInNav = hideInNav || null;
}


function Breadcrumb(trail, pageStartsFromTab, siteMap, separator)
{
	this.trail = trail || new Array();
	this.pageStartsFromTab = pageStartsFromTab || false;
	//this.siteMap = siteMap || new SiteMap("/Kristen/");
	this.siteMap = siteMap || new SiteMap("/assets/sitemap/");
	this.separator = separator || '<img src="/assets/images/careers/red_arrow.gif" border="0" class="RedArrowAlign">';
	this.outputHTML = "";
}


Breadcrumb.prototype.getPath = function(currentSegmentNumber)
{
	var pathToParent = "/";
	
	for (var i = 1; i <= currentSegmentNumber; i++)
	{
		pathToParent += this.trail[i].pathSegment + "/";
	}

	return pathToParent;
}


Breadcrumb.prototype.show = function()
{
	if (this.siteMap == null)
	{
		document.write("Unable to open the sitemap file.");
		return false;
	}

	this.trail = this.siteMap.pathToCurrentLocation;

	if (this.trail.length > 0)
	{
		this.buildHTML();
		document.write(this.outputHTML);
	}
	else
	{
		document.write("This page does not have an entry in the sitemap file.");
	}
	
	return true;
}


Breadcrumb.prototype.buildHTML = function()
{  
	var classNameNormal = "";
	var classNameBold = "";
	var separatorImagePath = "";
	var separatorClassName = "";
	
	var sectionName = this.trail[1].pathSegment;

	
	switch (sectionName)
	{
	  	case "career": 
		
			classNameNormal = "TextBreadCrumbRed";
			classNameBold = "TextBreadCrumbRedBold";
			separatorImagePath = "/assets/images/careers/red_arrow.gif";
			separatorClassName = "RedArrowAlign";
			
			break;
		
		case "customer":
		
			classNameNormal = "TextBreadCrumbGreen";
			classNameBold = "TextBreadCrumbGreenBold";
			separatorImagePath = "/assets/images/customers/green_arrow.gif";
			separatorClassName = "GreenArrowAlign";
			
			break;
		
		default:
		
			classNameNormal = "TextBreadCrumbBlue";
			classNameBold = "TextBreadCrumbBlueBold";
			separatorImagePath = "/assets/images/blue_arrow.gif";
			separatorClassName = "BlueArrowAlign";
			
			break;
	} 
	
	var separator = '<img src="' + separatorImagePath +'" border="0" class="' + separatorClassName + '">';
	
	for (var i = 0; i < this.trail.length-1; i++)
	{	
		//for every entry after the first, add the separator between levels
		if (i > 0)
		{
			this.outputHTML += separator;
		}
		
		//this will be true if there's no explicit page name
		if (this.siteMap.useDirNameAsPageName == true && (i == this.trail.length-2))
		{
			this.outputHTML += '<span class="' + classNameBold + '">'  + this.trail[i].longName; + '</span>';
			break;
		}
		else
		{
			//if there's an href specified in the XML file, use it otherwise, build the path to this point
			var path = (this.trail[i].href != "") ? this.trail[i].href : this.getPath(i);
			
			//add this segment to the HTML that is output to the screen
			this.outputHTML += '<a class="' + classNameNormal + '" href="' + path + '">' + this.trail[i].longName + '</a>';		
		}
	}

	if (this.siteMap.useDirNameAsPageName == false)
	{
		this.outputHTML += separator + '<span class="' + classNameBold + '">' + this.siteMap.getCurrentPageName() + '</span>';	
	}
}


function configurePage() 
{ 
	if (document.getElementById("header"))
	{
		document.getElementById("header").innerHTML = breadcrumb.siteMap.getPageHeader();
	}
	
	if (document.getElementById("horizontalNav"))
	{
		document.getElementById("horizontalNav").innerHTML = getHorizontalNav();
	}

	//create the menus for Career and Customer
	createDropDownMenus();
	
	if (breadcrumb.trail.length > 0)
	{
		var sectionName = breadcrumb.trail[1].pathSegment;
		
		if (sectionName == "career")
		{
			document.images["careers"].src = "/assets/images/Careers_Nav_In.gif";
		}
		else if (sectionName == "customer")
		{
			document.images["customers"].src = "/assets/images/Customers_Nav_In.gif";
		}
	}
}


function getHorizontalNav()
{
	var horizontalNavHTML = "";
	
	//get the path to this page up to the trailing slash - the page name itself is added below
	var currentLocation = breadcrumb.getPath(breadcrumb.siteMap.getCurrentPageDepth() - 1);

	//gets an array of SiteMapNode objects representing the current level in the sitemap
	var thirdLevelNav = breadcrumb.siteMap.getLevelFromCurrentPath(2);

	//if there's anything at this level
	if (thirdLevelNav != null)
	{
		//then loop through the items, creating menu options for them
		for (var i = 0; i < thirdLevelNav.length; i++)
		{
			//but don't output items for which hideInNav is true in the XML file
			if (thirdLevelNav[i].hideInNav == "true")
			{
				continue;
			}
			
			//build HTML for link for this item		
			horizontalNavHTML += '<a href="' + currentLocation + thirdLevelNav[i].pathSegment + '.html">' + thirdLevelNav[i].longName + '</a>';
			
			//for all but the final item, add a separator
			if (i != thirdLevelNav.length - 1)
			{ 
				horizontalNavHTML += '<span class="SubNavSeperator"> | </span>';
			}
		}
	}
	
	return horizontalNavHTML;
}


function createDropDownMenus() 
{
	//don't create the menus if they already exist  
	if (window.mm_menu_0206162835_0)
	{
		return;
	}
	
	//create a new Menu object with style information
	window.mm_menu_0206162835_0 = new Menu("root", 214, 21, "Verdana, Arial, Helvetica, sans-serif", 11, "#A23833", "#FFFFFF", "#F7EEEE", "#A23833", "left", "middle", 5, 0, 500, -5, 7, true, true, true, 0, false, true);
	
	//get a reference to the sitemap XML file
	var sourceXML = breadcrumb.siteMap.sourceXML;
	
	//then get the career node
	var careerNode = sourceXML.getElementsByTagName("career")[0];
	
	//and use it to get whatever immediate children it has
	var careerNav = breadcrumb.siteMap.getLevelFromNode(careerNode);
	
	//add a menu item for each child
	for (var i = 0; i < careerNav.length; i++)
	{
		//but only if it's not hidden using the hideInNav attribute in the XML file
		if (careerNav[i].hideInNav == "true")
		{
			continue;
		}
	
		//for now this assumes pointing at a directory
		mm_menu_0206162835_0.addMenuItem(careerNav[i].longName, "location='/career/" + careerNav[i].pathSegment + "/'");
	}
	
	//now set properties for the menu
	mm_menu_0206162835_0.hideOnMouseOut = true;
	mm_menu_0206162835_0.bgColor = '#F3CFCE';
	mm_menu_0206162835_0.menuBorder = 1;
	mm_menu_0206162835_0.menuLiteBgColor = '#F3CFCE';
	mm_menu_0206162835_0.menuBorderBgColor = '#430400';
	
	window.mm_menu_0206170926_0 = new Menu("root", 156, 21, "Verdana, Arial, Helvetica, sans-serif", 11, "#8EA22D", "#FFFFFF", "#F4F8E6", "#8EA22D", "left", "middle", 5, 0, 500, -5, 7, true, true, true, 0, false, true);
	
	var customerNode = sourceXML.getElementsByTagName("customer")[0];
	var customerNav = breadcrumb.siteMap.getLevelFromNode(customerNode);
	
	//add items to the Customer menu
	for (var j = 0; j < customerNav.length; j++)
	{
		//but only if they're not supposed to be hidden
		if (customerNav[j].hideInNav == "true")
		{
			continue;
		}

		//for now this assumes pointing at a directory
		mm_menu_0206170926_0.addMenuItem(customerNav[j].longName, "location='/customer/" + customerNav[j].pathSegment + "/'");
	}
	
	//now set properties for the menu
	mm_menu_0206170926_0.hideOnMouseOut = true;
	mm_menu_0206170926_0.bgColor = '#F3F7E6';
	mm_menu_0206170926_0.menuBorder = 1;
	mm_menu_0206170926_0.menuLiteBgColor = '#F3F7E6';
	mm_menu_0206170926_0.menuBorderBgColor = '#586325';
	
	mm_menu_0206170926_0.writeMenus();
}
