//----------------------------------------------------
//---------------------------------------------------- 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: "wlcinav"
};

var designConstants = {
	header:["wlciheader","header.html"],
	nav:["wlcinav","nav.html"],
	footer:["wlcifooter","footer.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 = {
	contentPath: [ [".childNodes[1]",[ ["default"] ] ] , ["", [ ["newItem"],["news"] ] ] ],
	archivePath: [ [".childNodes[0].childNodes[1].childNodes[0]", [ ["didYouKnow","NONE"],["newItem","NONE"],["news","newsHighlights"] ]   ] ],
	statusPath: [[".childNodes[0].childNodes[0]", [["newItem","NONE"],["news","newsHighlights"]]]],
	newItemBtnPath: [[".childNodes[0].childNodes[0]", [["newItem","NONE"],["news","newsHighlights"]]]]
};

//--- 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 = {
	clearMetaData: "clearMetaData()",
	sortDecending: "sortContent('decending')"
};

//----------------------------------------------------
//---------------------------------------------------- DESIGNATED website file structure variables---
//----------------------------------------------------


if (currentDomain() == "my-beta.usgs.gov") {
	var baseURL = "http://my-beta.usgs.gov/websites/wlci/";
	var scimBaseURL = "https://my-beta.usgs.gov/scim/";
} else if (currentDomain() == "my.usgs.gov") {
        var baseURL = "http://my.usgs.gov/websites/wlci/";
        var scimBaseURL = "https://my.usgs.gov/scim/";
} else if (currentDomain() == "www.wlci.gov") {
        var baseURL = "http://www.wlci.gov/";
        var scimBaseURL = "https://my.usgs.gov/scim/";
} else {
	var baseURL = "http://wlci.gov/";
	var scimBaseURL = "https://my.usgs.gov/scim/";
}


//-- 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 || storedData[elementID][2].intranetQuery){
		var url="inc/php/determinDisplay.php";
		var dd = siteDataRequest();
		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" && storedData[elementID][2].intranetQuery && isToggledExternal == "false"){
				eval(storedData[elementID][2].intranetQuery);
				return true;
			} else if (storedData[elementID][2].webQuery && isToggledExternal == "true"){
				eval(storedData[elementID][2].webQuery);
				return true;
			} else if(determineDisplay == "external" && storedData[elementID][2].webQuery){
				eval(storedData[elementID][2].webQuery);
				return true;
			} else if(determineDisplay == "internal" && !storedData[elementID][2].intranetQuery){// if there is no intranet query, then default to webQuery. If want NO internal data, leave Intranet query parameter blank
				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;
			}
		}
	}
	
	//------ Special functions for displaying alternate designs need to be contained within expandedDesign
	function clearMetaData(){
		if(displayPaths.contentPath){
			var foundPathContent = getDisplayPath(elementID, displayPaths.contentPath);
			var contentNode = designLocate(foundPathContent);
			
			var mdata = xhrRequest("html");
			mdata.open('GET', 'inc/php/editDisplay.php', true);
			mdata.onreadystatechange = function() {
				if (mdata.readyState == 4 && mdata.status == 200) {
					var showMdata = mdata.responseText;
							
					if(showMdata ==""){
						var sansMetaData = designHTML.replace(/<div[^>]*class='metaData'[^>]*>(.*?)<\/div>/g,"");
						contentNode.innerHTML = sansMetaData;
					} else {
						contentNode.innerHTML = designHTML;
					}
							
				}
			};
			mdata.send(null);
			
		}
		
	}
	function sortContent(sortOrder){
		var newDesignHTML = [];
		var oldDesignHTML = "";
		//chunkArray = designHTML.split(/\<div\sid\=\'itemID/);
		 chunkArray = designHTML.split("<div id='itemID");
		
		for (var sc = 0; sc < chunkArray.length; sc++) {
			if(chunkArray[sc] == ""){
				chunkArray.splice(sc,1);
			}
			
			chunkArray[sc] = "<div id='itemID" + chunkArray[sc];
			
			indexArray = chunkArray[sc].split(/\./,1);
			var newIndex = indexArray[0].match(/>\d{0,}$/);
			if(newIndex == null){
				oldDesignHTML += chunkArray[sc];
			}else{
				newIndex = newIndex[0].substr(1);
				newDesignHTML[newIndex-1] =chunkArray[sc];
			}
			
			if(sc == chunkArray.length-1){
				if(displayPaths.contentPath){
				var foundPathContent = getDisplayPath(elementID, displayPaths.contentPath);
				var contentNode = designLocate(foundPathContent);
					for (var nd = 0; nd < newDesignHTML.length; nd++) {
						contentNode.innerHTML += newDesignHTML[nd];
					}
					contentNode.innerHTML += oldDesignHTML;
				}
			}
  		}
	}
}
//------------------------------------------------//
//--- 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(){
	var urlDD="inc/php/determinDisplay.php";
	var dd = siteDataRequest();
		dd.open('GET', urlDD, true);
		dd.onreadystatechange = function() {
			if (dd.readyState == 4 && dd.status == 200) {
				determineDisplay = dd.responseText;
				for (key in designConstants){
					var objectID = designConstants[key][0];
					var url;
					if (determineDisplay == "internal" && designConstants[key][2]){
						url=baseURL+"inc/design/"+designConstants[key][2];
						constantsCall(objectID,url)
						addEditDisplays();// repeat this function since header is cleared and edit stuff is placed in header.
					}
				}
			}
		};
		dd.send(null);
	for (key in designConstants){
		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 = siteDataRequest("html");
		xhrRec.open('GET', url, true);
		xhrRec.onreadystatechange = function() {
		if (xhrRec.readyState == 4 && xhrRec.status == 200) {
			var html = xhrRec.responseText;
			if (objectID == "wlcinav") {
				html = html.replace(/href="/g, 'href="'+baseURL);
			} else if (objectID == "wlcifooter") {
				html = html.replace(/Web Address: /, 'Web Address: '+location.href.substr(0,150));
			} else if (objectID == "wlciheader") {
				html = html.replace(/U.S. Geological Survey - Central Region/, document.title);
			}
			document.getElementById(objectID).innerHTML = html;
		} 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 independant 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);
}