// SpryMenuBar.js - version 0.12 - Spry Pre-Release 1.6.1
//
// Copyright (c) 2006. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

/*******************************************************************************

 SpryMenuBar.js
 This file handles the JavaScript for Spry Menu Bar.  You should have no need
 to edit this file.  Some highlights of the MenuBar object is that timers are
 used to keep submenus from showing up until the user has hovered over the parent
 menu item for some time, as well as a timer for when they leave a submenu to keep
 showing that submenu until the timer fires.

 *******************************************************************************/

var Spry; if (!Spry) Spry = {}; if (!Spry.Widget) Spry.Widget = {};
/**********************************************************************************/ 
/* These following functions deal with the showing and hiding of the dropdown box */
/* This code is based heavily off of the spry assets code                         */
/**********************************************************************************/
function setupBox(){

	var top = document.getElementById('top');
	var box = document.getElementById('dropDown');
//	top.onmouseover=initShow;
//	top.onmouseout=initClose;
//	box.onmouseover=initShow;
//	box.onmouseout=initClose;
	addEventListener(top, 'mouseover', initShow, false);
	addEventListener(top, 'mouseout', initClose, false);
	addEventListener(box, 'mouseover', initShow, false);
	addEventListener(box, 'mouseout', initClose, false);
	addEventListener(box, 'click', initShow, false);
	if(document.getElementById('clientInfo')){
		var info = document.getElementById('clientInfo');
		addEventListener(info, 'click', clientInfo, false);
	}

	top.onclick=initContent;
}
// addEventListener for Menu Bar
// attach an event to a tag without creating obtrusive HTML code
addEventListener = function(element, eventType, handler, capture)
{
	try
	{
		if (element.addEventListener)
		{
			element.addEventListener(eventType, handler, capture);
		}
		else if (element.attachEvent)
		{
			element.attachEvent('on' + eventType, handler);
		}
	}
	catch (e) {}
};


function showDiv(){
	var top = document.getElementById('top');
	var ret = getPosition(top);
	//alert(ret.x);
	//alert(ret.y);
	var box = document.getElementById('dropDown');
	clearTimeout(box.closetime);
	box.style.left=ret.x+'px';
	box.style.top=ret.y +top.offsetHeight+'px';
	setHover('top');
	//document.getElementById('sample').innerHTML = box.style.left+', '+box.style.top+' from '+ret.tk;
}

function setHover(id){
	var top = document.getElementById('top');
	top.className='hover';
}

function clearHover(id){
	var top = document.getElementById('top');
	top.className='';
}
function show(){
	var box = document.getElementById('dropDown');
	clearTimeout(box.closetime);
	showDiv();
}

function initShow(){
	var box = document.getElementById('dropDown');
	if(!(/^\s*$/.test(box.innerHTML))){
		clearTimeout(box.closetime);
		box.showtime = setTimeout("showDiv()",40);
		//showDiv();
	}else{
		setHover('top');
	}
		
}

function initClose(){
	var box = document.getElementById('dropDown');
	if(!(/^\s*$/.test(box.innerHTML))){
		clearTimeout(box.showtime);
		box.closetime = setTimeout("hideDiv()", 400);
		//hideDiv();
	}else{
		clearHover('top');
	}
}
function topClick(){
	var box = document.getElementById('top');
	if (box.className == "hover"){
		hideDiv();
	}else{
		showDiv();
	}
}

function initContent(){
	//var script = document.createElement('script');
	//script.src = 'genSystemList.cgi';
	//script.type = "text/javascript";
	//document.getElementsByTagName('head')[0].appendChild(script);
	document.getElementById('top').onclick=topClick;
	showDiv();
	var xhReq = new XMLHttpRequest();
	xhReq.open("POST", "genSystemList.cgi", false);
	xhReq.send(null);
	var box = document.getElementById('dropDown');
	box.innerHTML = xhReq.responseText;
	setupTree('tree1', 'a');
	setupTree('tree1', 'p');
	if(document.getElementById('mobileFlag').value == 1){
		document.getElementById('tree1').parentNode.style.maxHeight = 'none';
	}
}

function hideDiv(){
	var box = document.getElementById('dropDown');
	clearTimeout(box.showntime);
	box.style.left = '-1000em';
	clearHover('top');
}


function getPosition(el, doc)
{
	doc = doc || document;
	if (typeof(el) == 'string') {
		el = doc.getElementById(el);
	}

	if (!el) {
		return false;
	}

	//if (el.parentNode === null || Spry.Widget.MenuBar.getStyleProp(el, 'display') == 'none') {
		//element must be visible to have a box
	//	return false;
	//}

	var ret = {x:0, y:0};
	var parent = null;
	var box;

	var obj = el;
	if (obj.offsetParent){
		do {
			ret.x += obj.offsetLeft;
			ret.y += obj.offsetTop;
		}while (obj = obj.offsetParent);
	}else if (el.getBoundingClientRect) { // IE
		box = el.getBoundingClientRect();
		var scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
		var scrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft;
		ret.x = box.left + scrollLeft;
		ret.y = box.top + scrollTop;
	} else if (doc.getBoxObjectFor) { // gecko
		box = doc.getBoxObjectFor(el);
		ret.x = box.x;
		ret.y = box.y;
	} else { // safari/opera
		ret.x = el.offsetLeft;
		ret.y = el.offsetTop;
		parent = el.offsetParent;
		if (parent != el) {
			while (parent) {
				ret.x += parent.offsetLeft;
				ret.y += parent.offsetTop;
				parent = parent.offsetParent;
			}
		}
		// opera & (safari absolute) incorrectly account for body offsetTop
		//if (Spry.is.opera || Spry.is.safari && Spry.Widget.MenuBar.getStyleProp(el, 'position') == 'absolute')
		//	ret.y -= doc.body.offsetTop;
	}
	//if (el.parentNode)
	//		parent = el.parentNode;
	//else
	//	parent = null;
	//if (parent.nodeName){
	//	var cas = parent.nodeName.toUpperCase();
	//	while (parent && cas != 'BODY' && cas != 'HTML') {
	//		cas = parent.nodeName.toUpperCase();
	//		ret.x -= parent.scrollLeft;
	//		ret.y -= parent.scrollTop;
	//		if (parent.parentNode)
	//			parent = parent.parentNode;
	//		else
	//			parent = null;
	//	}
	//}
	return ret;
};


/**********************************************************************************/ 
/* These following functions deal with the expanding and hiding of the tree nodes */
/**********************************************************************************/

function setupTree(tree, tag){
	var tree = document.getElementById(tree);
	var nodes = tree.getElementsByTagName(tag);
	var id = document.getElementById('systemID').value;
	for(var i=0;i<nodes.length;i+=1){
		if(id == nodes[i].id){setSelect(nodes[i], 'systemChoice', 'systemID');}
		//check if the parent li does not have a next child li, then you know it is an end
		var isEnd = checkEndNode(nodes[i])
		if(hasUlSib(nodes[i], 'noe', 'syslistMemory')){
			nodes[i].onclick=showHideSubShort;
			nodes[i].ondblclick=clicksubmitSelector;
			if(!inList('syslistMemory', getSysId(nodes[i]) ) ){ 
				if(isEnd){
					addClass(nodes[i],'closedEnd');
				}else{
					addClass(nodes[i],'closed');
				}
			}else{
				if(isEnd){
					addClass(nodes[i],'expandedEnd');
				}else{
					addClass(nodes[i],'expanded');
				}
			}
			//if we know that this node is an end, make it so the child ul does not have background lines
			//also add the class closedEnd instead of closed
		}else{
			nodes[i].onclick=setSelectItem;
			nodes[i].ondblclick=clicksubmitSelector;
			//nodes[i].style.paddingLeft='16px';
			if(isEnd){addClass(nodes[i], 'bulletEnd');}
			//add the class bulletEnd
		}
	}
	setClientInfoDisplay();
	
}

function checkEndNode(element){
	parentLi = element.parentNode;
	while(parentLi = parentLi.nextSibling){
		if(parentLi.tagName == 'LI'){return false;}
	}
	return true;
}

function hasUlSib(element, display, list){
	var sib = element.parentNode.childNodes;
	for (var i=0;i<sib.length;i+=1){
		if(sib[i].tagName=='UL' && sib[i].className!="extras"){
			if(inList(list, getSysId(element) ) ){ 
				sib[i].style.display='block'; 
			}else{
				sib[i].style.display='none'; 
			}
			if(checkEndNode(element)){sib[i].style.backgroundImage='none';}
			return true;
		}
	}
	return false;
}



function setSelectItem(){
	setSelect(this, 'systemChoice', 'systemID');
}

function setSelect(current, idselector, idider){
	var selClass='selected';
	
	// if the current does not have an ID, look through the children untill you find one that does have an ID
	// This makes the Entity Links page work
	var info = current;
	if(current.id == ""){
		var curChildren = current.childNodes;
		for(var k=0; k<curChildren.length; k+=1){
			if (curChildren[k].id){info=curChildren[k];}
		}
	}
	var selector = document.getElementById(idselector);
	selector.value = info.innerHTML;
	if(document.getElementById(idselector+'Display')){
		var selectorDisplay = document.getElementById(idselector+'Display');
		selectorDisplay.innerHTML = selector.value;
	}
	var ider = document.getElementById(idider);
	ider.value = info.id.replace(/id/, '');
		
	var oldselect = document.getElementsByTagName(current.tagName);
	for(var i=0; i<oldselect.length; i+=1){
		removeClass(oldselect[i],selClass);
	}
	addClass(current,selClass);
	if(idselector == 'systemChoice'){
		setClientInfoDisplay();
	}
}

function setClientInfoDisplay(){
	var selectorDisplay = document.getElementById('systemChoiceDisplay');
	if( isClient(document.getElementById('systemID').value) ){
		document.getElementById('clientInfo').style.display='block';
		selectorDisplay.style.width = '138px';
	}else{
		document.getElementById('clientInfo').style.display='none';
		selectorDisplay.style.width = '160px';
	}
}

function clientInfo(e){
	//Stop the event from propogating
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	//Open Client Window
	var loc = document.getElementById('systemID').value;
	var req = '';
	var newwin = window.open('ClientInfoWin.cgi?loc='+loc, '_blank', 
	'scrollbars=yes,toolbar=0,location=0,menubar=0,directories=0,status=0,copyhistory=0,width=320,height=320,channelmode=no,resizable=yes,top=100,left=100');
	newwin.focus();
}

function showHideSubShort(){
//	showHideSub(this.parentNode.childNodes[0], 'systemChoice', 'systemID', 'syslistMemory');
//	showHideSub(this.parentNode.childNodes[1], 'systemChoice', 'systemID', 'syslistMemory');
	showHideSub(this, 'systemChoice', 'systemID', 'syslistMemory');
}

function clicksubmitSelector(){
	clearSelection();
	var button = document.getElementById('sysChange');
	button.click();
}
	
function submitSelector(){
	clearSelection();
	var button = document.getElementById('sysChange');
	//alert(button.onclick);
	if(button.onclick){
		return forceClient();
	}else{
		//submitForm();
		//button.click();
		return true;
	}
	//alert(button.onmousedown);
}

function forceClient(){
	var sysID = document.getElementById('systemID').value;
	if(isClient(sysID)){
		return true;
	}else{
		alert('Selected entity is not a client. Please select a client.');
		return false;
	}
}

function isClient(sysID){
	if(document.getElementById(sysID)){
		var selected = document.getElementById(sysID);
		var classx = selected.className;
		if(/^\s*selected\s*$/.test(classx)  || /bulletEnd/.test(classx) || /^\s*$/.test(classx) ){
			return true;
		}else{	return false;}
	}
}

function submitForm(){
	var fname = document.getElementsByTagName('FORM')[0].name;
	eval('document.'+fname+'.submit()');
}

function showHideSub(current, idselector, idider, list){
	var children = current.parentNode.childNodes;
	var sublist;

	for(var i=0; i<children.length;i+=1){
		if(children[i].tagName == 'UL' && !sublist){
			sublist = children[i];
		}
	}
	if(sublist){
		var sysID = getSysId(current);
		var classes = current.className;
		if(/.*expanded.*/.test(classes)){
			sublist.style.display='none';
			addClass(current,'closed');
			removeClass(current,'expanded');
			// Remove the sysID from the expanded list
			removeFromList(list, sysID);
		}else{
			sublist.style.display='block';
			addClass(current,'expanded');
			removeClass(current,'closed');
			// Add the sysID to the expanded list
			addToList(list, sysID);
		}
	}
	setSelect(current, idselector, idider);
	
}

//modify these so that it will keep the end property if the node has already been established as an end
function removeClass(element, oldC){
	var classes = element.className;
	if(/End/.test(classes) && (oldC == 'closed' || oldC == 'expanded') ){
		oldC = oldC+'End';	
	}
	var re = new RegExp('\\s*'+oldC+'\\s*');
	classes = classes.replace(re, ' ');
	classes = classes.replace(/^\s+|\s+$/g, '') 
	element.className=classes;

}

function addClass(element, newC){
	var styles = element.className;
	if(/End/.test(styles) && (newC == 'closed' || newC == 'expanded') ){
		newC = newC+'End';	
	}
	element.className = styles+' '+newC;	
	element.className = element.className.replace(/^\s+|\s+$/g, '') 
}

//following 3 functions are used for tracking which nodes are open or not
function removeFromList(listID, element){
	var re = new RegExp('#_'+element+'_', 'g');
	var list = getList(listID);
	setList(listID, list.replace(re, '') );
	//alert(list.value+':removed '+element);
}
function addToList(listID, element){
	var list = getList(listID);
	if(!inList(listID, element)){
		var arry = list.split('#');
		arry.push('_'+element+'_');
		setList(listID, arry.join('#') );
	//	alert(list.value+':added '+element);
	//}else{
	//	alert('did nothing');
	}
}
function inList(listID, element){
	var re = new RegExp('#_'+element+'_', 'g');
	return re.test(getList(listID));
}

function getList(listID){
	if (listID == 'syslistMemory'){
		return readCookie('listMem');
	}else{
		var list = document.getElementById(listID);
		return list.value;
	}
}

function setList(listID, val){
	if (listID == 'syslistMemory'){
		createCookie('listMem',val,'');
	}else{
		var list = document.getElementById(listID);
		list.value = val;
	}
}

function getSysId(current){
	var info = current;
	if(current.id == ""){
		var curChildren = current.childNodes;
		for(var k=0; k<curChildren.length; k+=1){
			if (curChildren[k].id){info=curChildren[k];}
		}
	}
	return info.id.replace(/id/, '');
}


// following 3 functions deal with cookies, from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return ""; //The origional script returned null, but that was rough on the other code.
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function clearSelection(){
	var sel ;
	if(document.selection && document.selection.empty){
		document.selection.empty() ;
	} else if(window.getSelection) {
		sel=window.getSelection();
		if(sel && sel.removeAllRanges){
			sel.removeAllRanges() ;
		}
	}
	return;
}

