//----------------------------------------------------
//---------------------------------------------------- THESE SCRIPTS CAN BE ALTERED AND ADDED TO TO CREATE PREFERRED DESIGN FUNCTIONALITY---
//----------------------------------------------------	alter scimPlot.css BEFORE/RATHER THAN these scripts if possible

//--- VARs used in 'display.js' library, DO NOT REMOVE: SET TO PREFERENCES-----
var designConfig = {
	expandDesign: "true",
	docType: "xml",
	displayStatus: "true",
	editFeatures: "usgstitle"// set to element to append edit bar to, otherwise set to "false"
};

var designConstants = {
	footer:["usgsfooter","footer.html"],
	header:["usgsheader","header.html","header_internal.html"],
	nav:["nav","nav.html"]
}

//--- VARs used in the expandedDisplay function -----
//--- These vars are paths to where content should be placed within the HTML DOM of a specified Object
var displayPaths = {
	//[[ path, [[element it applies to, alternative element to affect]]]
	// When an elements display is set to "NONE", include the catch-all div "<div id="catchTrash"></div>" at the end of the page or else an error will be thrown
	contentPath: [ [".childNodes[1]",[ ["default"] ] ] , ["", [ ["org"],["team"],["team1"],["team2"],["team3"],["team4"],["rsoOrgCharts"],["scrollContainer"],["oc"],["ag"],["fs"],["hr"],["ms"],["safety"],["team"] ] ] ],
	
	archivePath: [ [".childNodes[0].childNodes[1].childNodes[0]", [ ["org","NONE"],["team","NONE"],["team1","NONE"],["team2","NONE"],["team3","NONE"],["team4","NONE"],["rsoOrgCharts", "NONE"],["scrollContainer","NONE"],["oc","NONE"],["ag","NONE"],["fs","NONE"],["hr","NONE"],["ms","NONE"],["safety","NONE"],["team","NONE"],["links","NONE"] ]   ] ],
	
	statusPath: [[".childNodes[0].childNodes[0]", [["org","contact"],["team","NONE"],["team1","NONE"],["team2","NONE"],["team3","NONE"],["team4","NONE"],["rsoOrgCharts", "NONE"],["scrollContainer","archive"],["oc","OCRSservices"],["ag","NONE"],["fs","NONE"],["hr","NONE"],["ms","NONE"],["safety","NONE"],["team","NONE"]] ]],
	
	newItemBtnPath: [[".childNodes[0].childNodes[0]", [["org","contact"],["team","NONE"],["team1","NONE"],["team2","NONE"],["team3","NONE"],["team4","NONE"],["rsoOrgCharts", "NONE"],["scrollContainer","archive"],["oc","NONE"],["ag","NONE"],["fs","NONE"],["hr","NONE"],["ms","NONE"],["safety","NONE"],["team","NONE"]] ]]
};

//--- VARs for VERY specific design features designated in dataModel[1][n][2] -----
//--- expandedDisplay should fire these IF they exist  ---
//var determineDisplay; //-- set by determinDisplay.php
var displaySpecifics = {
	stripWrapper: "stripDivWrapper()",
	buildWrapper: "buildDivWrapper()",
	buildBlueWrapper: "buildBlueDivWrapper()",
	collapseLists: "collapse()",
	appendList: "appendList()"
};
var appendListVar = 0;
//----------------------------------------------------
//---------------------------------------------------- DESIGNATED website file structure variables---
//----------------------------------------------------
if (currentDomain() == "my-beta.usgs.gov") {
	var baseURL = "http://my-beta.usgs.gov/websites/cr/";
	var scimBaseURL = "http://my-beta.usgs.gov/scim/";
	var plotBaseURL = "https://my-beta.usgs.gov/";
} else {
	var baseURL = "http://www.cr.usgs.gov/";
	var scimBaseURL = "https://my.usgs.gov/scim/";
	var plotBaseURL = "https://my.usgs.gov/";
}
//-- included scripts path
var baseFeed = baseURL+"inc/php/data.php?";
var exOnlyFeed = baseURL+"inc/php/dataExOnly.php?";
var createItemScriptURL = baseURL+"inc/php/createItem.php?pagePath=";
//-- template pages
var viewContentURL = baseURL+"viewContent.html";
//-- SCIM specific URLS -- DO NOT ALTER --
var scimEditURL = scimBaseURL+"contentItem/edit/";
var scimCreateURL = scimBaseURL+"contentItem/create?";
//-- Dynamic paths -- DO NOT ALTER --
var currentPage = parent.document.location.href;
var relativePath = makeRelative(baseURL,currentPage);


//----------------------------------------------------
//---------------------------------------------------- DYNAMIC VARIABLE/PATH FUNCTIONS---
//----------------------------------------------------
// gets current location as string
function currentDomain() {
	var strHref = location.href;
	var arrHref = strHref.split("/");
	return arrHref[2].toLowerCase();
}

//makes sure a path does not end with a folder /
function makeRelative(baseURL,currentPage){
	var newPath = 	currentPage.substr(baseURL.length);
	if(newPath.indexOf("/") == newPath.length-1) newPath += "index.html";
	return newPath;
}

//----------------------------------------------------
//---------------------------------------------------- DESIGN FUNCTIONS---
//----------------------------------------------------
//--Function created to allow more design elements UTILIZES displayPaths object -----
function expandedDesign(elementID, designHTML){
	var foundAlternate = false;
	// check for special treatment
	if(storedData[elementID][2].webQuery != "NONE" || storedData[elementID][2].intranetQuery != "NONE"){
		var url= baseURL+"inc/php/determinDisplay.php";
		var dd = xhrRequest();
		dd.open('GET', url, true);
		dd.onreadystatechange = function() {
			if (dd.readyState == 4 && dd.status == 200) {
				determineDisplay = dd.responseText;
				foundAlternate = determineAlternate();
				populateDisplay();
			}
		};
		dd.send(null);
		
		function determineAlternate(){
			if ((determineDisplay == "internal" || determineDisplay == "isUser") && (storedData[elementID][2].intranetQuery != "NONE" && storedData[elementID][2].intranetQuery) && isToggledExternal == "false"){
				eval(storedData[elementID][2].intranetQuery);
				return true;
			} else if (storedData[elementID][2].webQuery && storedData[elementID][2].webQuery != "NONE" && isToggledExternal == "true"){
				eval(storedData[elementID][2].webQuery);
				return true;
			} else if(determineDisplay == "external" && storedData[elementID][2].webQuery && storedData[elementID][2].webQuery != "NONE"){
				eval(storedData[elementID][2].webQuery);
				return true;
			} else if(storedData[elementID][2].plotQuery && storedData[elementID][2].plotQuery != "NONE"){
				eval(storedData[elementID][2].plotQuery);
				return true;
			}else if ((determineDisplay == "internal" || determineDisplay == "isUser") && !storedData[elementID][2].intranetQuery){// if there is no intranet query, then default to webQuery. If want NO internal data, leave Intranet query parameter blank
			if(storedData[elementID][2].webQuery){
				if(storedData[elementID][2].webQuery != "NONE"){
					eval(storedData[elementID][2].webQuery);
					return true;
				}
			}
			}
			
		}
	} else {
		populateDisplay();
	}
	
	function populateDisplay(){
		if(foundAlternate != true){
			//editing feature "add item"
			var theDiv = document.getElementById(elementID);
			
			var foundPathStatus = getDisplayPath(elementID, displayPaths.statusPath);
			var titleNode = designLocate(foundPathStatus);
			
			if(displayPaths.archivePath){
				var foundPathArchive = getDisplayPath(elementID, displayPaths.archivePath);
				var archiveNode = designLocate(foundPathArchive);
				if(!archiveNode){
					alert("Your path is incorrect. Delete all possible text elements in your HTML page and double check childNodes path for "+elementID);	
				}
				var archiveURL = storedData[elementID][1].replace(/=/,"*");
				archiveNode.setAttribute('href',baseURL+"archive.html?title="+titleNode.innerHTML+"&archiveQuery="+archiveURL);
			}
			//theDiv.innerHTML = theDiv.innerHTML + newItemButtonLink;
			if(displayPaths.contentPath){
				var foundPathContent = getDisplayPath(elementID, displayPaths.contentPath);
				var contentNode = designLocate(foundPathContent);
					contentNode.innerHTML = designHTML;
			}
		}
		document.getElementById('catchTrash').innerHTML = "";
	}
	//------ Special functions for displaying alternate designs defined in var displaySpecifics, needs to be contained within expandedDesign
	//------ These functions are to manipulate the string of data AFTER it has been formatted by design.js. This can be viewed as "one last filter"
	function stripDivWrapper(){
		document.getElementById(elementID).innerHTML = designHTML;
	}
	
	function buildDivWrapper(){
          document.getElementById(elementID).childNodes[0].className="tanWidgetHeader";
		  document.getElementById(elementID).childNodes[1].className="tanWidget";

          populateDisplay();
	}
	
	function buildBlueDivWrapper(){
          document.getElementById(elementID).childNodes[0].className="blueWidgetHeader";
		  document.getElementById(elementID).childNodes[1].className="blueWidget";

          populateDisplay();
	}
	
	function collapse(){
		if(displayPaths.contentPath){
			var foundPathContent = getDisplayPath(elementID, displayPaths.contentPath);
			var contentNode = designLocate(foundPathContent);
				contentNode.innerHTML = designHTML;
		}
		prepareLists();
	}

	function appendList(){
		var el = document.getElementById('scrollContainer');
	  	var loading = document.getElementById('loadingDiv');
		if(isToggledExternal == "true"){
			appendListVar++;
		}
		if(appendListVar == 1 && stopLoading == true){
			//el.scrollTo(0,0);
			offSet = 15;
			stopLoading = false;
			appendListVar = 0;
			loading.innerHTML = 'Loading...';
			loadMore();
		} else {
			loading.style.display = 'none';
		  	if(designHTML == ""){
			  	stopLoading = true;
			  	loading.innerHTML = 'All Related Items Loaded';
			  	loading.style.display = '';
			}
			if(appendListVar == 1){
				el.innerHTML = designHTML;
			} else {
				el.innerHTML += designHTML;
			}
		}
	}
}
//------------------------------------------------//
//--- functions that search displayPath object----//
//------------------------------------------------//
function getDisplayPath(elementID, displayPathKey){// this function determins what displayPath to use based on mathching the elementID to an array item
	var foundDisplayPath;
	var theElement = elementID;
	var found = false;
	var c = 0;
	for (c; c < displayPathKey.length; c++){
		if(displayPathKey[c][1]){
			for (var n = 0; n < displayPathKey[c][1].length; n++){
				if(displayPathKey[c][1][n][0] == elementID){
					foundDisplayPath = displayPathKey[c][0];
					if(displayPathKey[c][1][n][1]){
						theElement = displayPathKey[c][1][n][1];
					}
					found = true;
					return ([theElement,foundDisplayPath]);
				} 
			}
		}
	} 
	if(c == displayPathKey.length && found == false){
		foundDisplayPath = displayPathKey[0][0];
		return ([theElement,foundDisplayPath]);
	}
}

function designLocate(path){//--- function that evaluates a childNode path from a string var
	if(path[0] == "NONE"){
		var theDivNode = document.getElementById('catchTrash');
		return theDivNode;
	}else{
		var theDivNode = eval("document.getElementById('"+path[0]+"')"+path[1]);
		return theDivNode;
	}
}
//--- function that adds HTML pages to elements SPECIFIED in designConstants object----
function addDesignConstants(){
	if(!determineDisplay){
		var urlDD=baseURL+"inc/php/determinDisplay.php";
		var dd = xhrRequest();
			dd.open('GET', urlDD, true);
			dd.onreadystatechange = function() {
				if (dd.readyState == 4 && dd.status == 200) {
					determineDisplay = dd.responseText;
					makeCall();
				}
			};
			dd.send(null);
	} else {
		makeCall();
	}
	
	function makeCall(){
		//alert(determineDisplay);
		for (key in designConstants){
			var objectID = designConstants[key][0];
			var url;
			if ((determineDisplay == "internal" || determineDisplay == "isUser") && isToggledExternal != "true" && designConstants[key][2]){// this allows for an internal header to be used
				url=baseURL+"inc/design/"+designConstants[key][2];
				constantsCall(objectID,url)
					function getRef(){
						locationRef = document.getElementById(designConfig.editFeatures);
					}
					var locationRef = document.getElementById(designConfig.editFeatures);
					if(locationRef == null){
							getRef();
					} else {
						//addEditDisplays();// repeat this function since header is cleared and edit stuff is placed in header.
					}
			} else {
				var objectID = designConstants[key][0];
				var url = baseURL+"inc/design/"+designConstants[key][1];	
				constantsCall(objectID,url)
			}
		}
	}
}
//--- utilized ONLY by addDesignConstants()----
//--- breaking up into two functions removes possiblity of new data overriding old and final 'key' being the only populated element
function constantsCall(objectID,url){
	var xhrRec = xhrRequest("html");
		xhrRec.open('GET', url, true);
		xhrRec.onreadystatechange = function() {
		if (xhrRec.readyState == 4 && xhrRec.status == 200) {
			var html = xhrRec.responseText;
			if (objectID == "nav") {
				html = html.replace(/href="/g, 'href="'+baseURL);
			} else if (objectID == "usgsfooter") {
				html = html.replace(/Web Address: /, 'Web Address: '+location.href.substr(0,150));
			} else if (objectID == "usgsheader") {
				html = html.replace(/U.S. Geological Survey - Central Region/, document.title);
			}
			document.getElementById(objectID).innerHTML = html;
			addEditDisplays();//only internal header gets this display so might as well call function here
		} else {
			document.getElementById(objectID).innerHTML = "Gathering Data: "+25 *xhrRec.readyState+"% complete";
		}
	};
	xhrRec.send(null);	
}

// creates an XMLHTTPRequest object
// Included on siteSettings so that it is independent of dataCall for designConstance.
function siteDataRequest(type) {
	var xhrSend;
	if (!type) {
		type = 'text';
	}
	if (window.ActiveXObject) {
		try {
			xhrSend = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xhrSend = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	} else if (window.XMLHttpRequest) {
		xhrSend = new XMLHttpRequest();
		if (xhrSend.overrideMimeType) {
			xhrSend.overrideMimeType('text/' + type);
		}
	}
	return (xhrSend);
}



/* ================================================================ 
This copyright notice must be kept untouched in the stylesheet at 
all times.

The original version of this script and the associated (x)html
is available at http://www.stunicholls.com/menu/pro_drop_1.html
Copyright (c) 2005-2007 Stu Nicholls. All rights reserved.
This script and the associated (x)html may be modified in any 
way to fit your requirements.
=================================================================== */
stuHover = function() {
	var cssRule;
	var newSelector;
	for (var i = 0; i < document.styleSheets.length; i++)
		for (var x = 0; x < document.styleSheets[i].rules.length ; x++)
			{
			cssRule = document.styleSheets[i].rules[x];
			if (cssRule.selectorText.indexOf("LI:hover") != -1)
			{
				 newSelector = cssRule.selectorText.replace(/LI:hover/gi, "LI.iehover");
				document.styleSheets[i].addRule(newSelector , cssRule.style.cssText);
			}
		}
	var getElm = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<getElm.length; i++) {
		getElm[i].onmouseover=function() {
			this.className+=" iehover";
		}
		getElm[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" iehover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", stuHover);