var popupWin = false; //see openRemoteWindow()



function getCSS(cssId,cssName) 
{
	var cssValue = "UNKNOWN";
	if(document.getElementById || document.all)
	{
		if(document.getElementById)
		{
			idStyle = document.getElementById(cssId).style;
			cssValue = idStyle[cssName];
		}
		else if(document.all)
		{
			cssValue = document.all[cssId].style[cssName];
		}
	}
	return(cssValue);
}


function setCSS(cssId,cssName,cssValue)
{
	if(document.getElementById || document.all)
	{
		if(document.getElementById)
		{
			idStyle = document.getElementById(cssId).style;
			idStyle[cssName] = cssValue;
		}
		else if(document.all)
		{
			document.all[cssId].style[cssName] = cssValue;
		}
	}
}


function setClass(cssId,newClass)
{
//	alert("cssId: "+cssId+"\nnewClass: "+newClass);
	if(document.getElementById || document.all)
	{
		if(document.getElementById)
		{
			idStyle = document.getElementById(cssId);
//			alert("idStyle: "+idStyle);
			
			if(idStyle != null)
			{
//				alert("ID: " + cssId + "\nClass: " + newClass + "\nidStyle: " + idStyle);
				idStyle.className = newClass;
			}
		}
		else if(document.all)
		{
			document.all[cssId].className = newClass;
		}
	}
}


/*
function getClass(cssId) 
{
 var cssValue = "UNKNOWN";
 if(document.getElementById || document.all)
 {
  if(document.getElementById)
  {
   idStyle = document.getElementById(cssId);
   cssValue = idStyle.className;
  }
  else if(document.all)
  {
   cssValue = document.all[cssId].className;
  }
 }
 return(cssValue);
}
*/

/******************
 * Menu Functions *
 ******************/


function menuOver(menuID,menuClass)
{
	//setClass(menuID,"menuitemover");
	setClass(menuID,menuClass);
}

function menuOut(menuID,menuClass)
{
	//setClass(menuID,"menuitem");
	setClass(menuID,menuClass);
}


/******************
 * Box Functions  *
 ******************/

function boxOver(menuID) 
{
	setClass(menuID,"boxover");
}

function boxOut(menuID)
{
	setClass(menuID,"box");
}

function boxTog(menuID)
{
	if(getClass(menuID) == 'box')
	{
		setClass('boxover');
	}
	else
	{
		setClass('box');
	}
}

/*****************************
 * Image Swapping Functions  *
 *****************************/

function imgSwap(imgName,imgPath)
{
	document.images[imgName].src = imgPath;
}

function imgArticleCtrlsOver(ctrlType,imgName)
{
	if(ctrlType=='approve')
		imgSwap(imgName,ICON_ADMIN_UNAPPROVEOVER_URL);
	else if(ctrlType=='unapprove')
		imgSwap(imgName,ICON_ADMIN_APPROVEOVER_URL);
}

function imgArticleCtrlsOut(ctrlType,imgName)
{
	if(ctrlType=='approve')
		imgSwap(imgName,ICON_ADMIN_APPROVE_URL);
	else if(ctrlType=='unapprove')
		imgSwap(imgName,ICON_ADMIN_UNAPPROVE_URL);
}

/******************
 * Miscellaneous  *
 ******************/


function visSwap(cssID)
{
	if(getCSS(cssID,'visibility') == 'hidden')
	{
		setCSS(cssID,'visibility','visible');
	}
	else
	{
		setCSS(cssID,'visibility','hidden');
	}
}


function setAction(form,val)
{
	form.action.value=val;
}

function setField(form,fieldName,val)
{
	form[fieldName].value=val;
}


function openRemoteWindow(thePage,winName,winOpts)
{
	//self.name = "parentWindow"; 
	self.name = winName;
	
	//outerHeight=' + screen.availHeight + ',outerWidth=' + screen.availWidth
	if(!winOpts || winOpts == "")
		winOpts = "scrollbars=yes,resizable=yes,width=600,height=400,left=0,top=0";
	
	popupWin = window.open(thePage, "popupWin", winOpts);
}

function openRemoteViewer(thePage,winName,winOpts)
{
	//This function will open a new window intended as a low-key viewing window.
	// It shouldn't have all the navigation options that a normal browser window has.
	// It's intended for help files and quick viewing of small groups of information
	
}

// addLoadEvent: checks whether any other functions have already been added to the
//               body's onLoad function list
// addLoadEvent courtesy of Simon Willison:
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload =
			function()
			{
				if(oldonload)	oldonload();
				func();
			};
	}
}


// addUnloadEvent: checks whether any other functions have already been added to the
//                 body's onUnload function list
// addUnloadEvent built off of addLoadEvent, courtesy of Simon Willison
function addUnloadEvent(func)
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function')
	{
		window.onunload = func;
	}
	else
	{
		window.onunload =
			function()
			{
				if(oldonunload)	oldonunload();
				func();
			};
	}
}

/***********************
 * DIV showing/hiding  *
 ***********************/

function toggleDiv(a)
{

	if (document.getElementById)
	{
		if(document.getElementById(a).style.display == '')
			document.getElementById(a).style.display = 'none';
		else
			document.getElementById(a).style.display = '';
	}
	else if (document.all)
	{
		if(document.all[a].style.visibility == 'hidden')
			document.all[a].style.visibility = 'visible';
		else
			document.all[a].style.visibility = 'hidden';
	}
	else if (document.layers)
	{
		if(document.layers[a].visibility == 'hide')
			document.layers[a].visibility == 'show';
		else
			document.layers[a].visibility == 'hide';
	}

/*
	if (document.getElementById(a).style.display =='')
		document.getElementById(a).style.display = 'none';
	else
		document.getElementById(a).style.display='';
*/

/*
	if (document.all[a].style.display =='')
		document.all[a].style.display = 'none';
	else
		document.all[a].style.display='';
*/
}


/**
 * hideDiv
 * showDiv
 *
 *  These 2 functions will set the class for the div to be (only) 'hidediv'
 *   or 'showdiv', which is fine if you don't have any other classes set
 *   on the object.  If you do have other classes set that you don't want
 *   to lose, then see hideDivCSS & showDivCSS below
 *
 */
function hideDiv(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'hide';
	}
	else
		setClass(a,'hidediv');
}

function showDiv(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'show';
	}
	else
		setClass(a,'showdiv');
}


/**
 * hideDivCSS
 * showDivCSS
 * showOneDivCSS
 *
 *  These 2 functions will only modify the display attribute for the div.
 *   hideDiv() & showDiv() actually set the class, which can remove any other
 *   class info that you might have wanted to keep. This method circumvents
 *   that problem by only changing styles, and leaving the classes alone.
 *
 */
function hideDivCSS(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'hide';
	}
	else
		setCSS(a,'display','none');
}

function showDivCSS(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'show';
	}
	else
		setCSS(a,'display','block');
}


function showOneDivCSS(arrname, curdiv)
{
	for(i=0;i<arrname.length;i++)
	{
		//alert("SHOW\ncurdiv: "+curdiv+"\narr: "+arrname[i]);
		if(arrname[i] == curdiv)
		{
			showDivCSS(arrname[i]);
		}
		else
		{
			hideDivCSS(arrname[i]);
		}
	}
}

/**
 * showOnlyOne
 *  Given a JS object, hide all direct DIV descendents except the one specified by showID
 */
function showOnlyOne(containingObj,showID)
{
	//Only work with direct descendants of the containing object
	var arr = containingObj.childNodes;
	
	//Loop through all direct descendants, hiding all but the one specified
	for(var i=0;i<arr.length;i++)
	{
		//Only show/hide DIV's
		if(arr[i].tagName && arr[i].tagName.toLowerCase() == 'div')
			if(arr[i].id == showID)
				arr[i].className = arr[i].className.replace('hidediv', 'showdiv');
			else
				arr[i].className = arr[i].className.replace('showdiv', 'hidediv');
	}
}

// See /search.php for an example of usage.
//  Useful in conjunction with showOneDivCSS for expanding
//  only one div (and thus showing all but the one div that
//  should remain hidden...
function showAllButOneDivCSS(arrname, curdiv)
{
	for(i=0;i<arrname.length;i++)
	{
		//alert("HIDE\ncurdiv: "+curdiv+"\narr: "+arrname[i]);
		if(arrname[i] != curdiv)
		{
			showDivCSS(arrname[i]);
		}
		else
		{
			hideDivCSS(arrname[i]);
		}
	}
}


function hideSpan(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'hide';
	}
	else
		setClass(a,'hidespan');
}

function showSpan(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'show';
	}
	else
		setClass(a,'showspan');
}

function showOneDiv(arrname, curdiv)
{
	for(i=0;i<arrname.length;i++)
	{
		if(arrname[i] == curdiv)
		{
			if(errors)
			{
				errors.value="show: "+arrname[i]+"\n"+errors.value;
			}
			showDiv(arrname[i]);
		}
		else
		{
			if(errors)
			{
				errors.value="hide: "+arrname[i]+"\n"+errors.value;
			}
			hideDiv(arrname[i]);
		}
	}
}



/***********************
 * Top Nav Bar Classes *
 ***********************/


var topNavTimer;
var topNavTimeout = 1000;
var visDivs = new Array(0);

// Used b/c I can't seem to pass an array using the setTimeout function
var theNavArr;

// Options:
//  false: menu is not showing
//  "topnav_cat{$i}": name of the menu currently showing
var topNavState    = false;

///////////////////////////
// Top Nav Bar Functions //
///////////////////////////

function hideTopNav(a)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'hide';
	}
	else
		setClass(a,'topnav_cat-hide');
}

function showTopNav(a,extraClasses)
{
	if (document.layers)
	{
		document.layers[a].visibility == 'show';
	}
	else
		setClass(a,'topnav_cat-show '+extraClasses);
}



function showOneTopNav(topNavArr,curNav,extraClasses)
{
	stopTopNavTimer();
	// Flattens multi-dimensional array into 1-D array
	topNavArr = new Array().concat(topNavArr);
	for(i=0;i<topNavArr.length;i++)
	{
		if(topNavArr[i] == curNav)
		{
			showTopNav(topNavArr[i],extraClasses);
			visDivs.push(topNavArr[i]);
			topNavState = topNavArr[i];
		}
		else
		{
			hideTopNav(topNavArr[i]);
		}
	}
}

function closeVisDivs()
{
	for(i=0;i<visDivs.length;i++)
	{
		hideTopNav(visDivs.pop());
	}
}

/**
 * Relies on theNavArr, set in closeTopNav()
 * DO NOT CALL DIRECTLY!!!
 **/
function hideAllTopNav()
{
	for(i=0;i<theNavArr.length;i++)
	{
		hideTopNav(theNavArr[i]);
	}
	topNavState = false;
}

function closeTopNav(myTopNavArr)
{
	clearTimeout(topNavTimer);
	// Flattens multi-dimensional array into 1-D array
	theNavArr = new Array().concat(myTopNavArr);
	topNavTimer = setTimeout("hideAllTopNav();",topNavTimeout);
}

function closeTopNavNOW(myTopNavArr)
{
	clearTimeout(topNavTimer);
	// Flattens multi-dimensional array into 1-D array
	theNavArr = new Array().concat(myTopNavArr);
	hideAllTopNav();
}

function stopTopNavTimer()
{
	clearTimeout(topNavTimer);
}


//
// Position-finding code Matthew found
//
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	return curleft;
}

//
// Position-finding code Matthew found
//
function findPosY(obj)
{
	var curtop = 0;
	var printstring = '';
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			printstring += ' element ' + obj.tagName + ' has ' + obj.offsetTop;
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	
	return curtop;
}


////////////////////////////////////
// Top Nav Bar SUB MENU Functions //
////////////////////////////////////





/*****************************************************************************
 * Event Property
 *  Description
 *  
 * event.data
 *  Used by the onDragDrop event. Returns an array of URL's of dropped objects.
 *  
 * event.height
 *  Stores the height of the window or frame containing the object connected with the event.
 *  
 * event.modifiers
 *  Returns a string listing any modifier keys that were held down during a key or mouse event.
 *  The modifier key values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK and META_MASK.
 *  
 * event.pageX
 * event.pageY
 *  These properties hold the X and Y pixel coordinates of the cursor relative to the page,
 *  at the time of the event.
 *  
 * event.screenX
 * event.screenY
 *  These properties hold the X and Y pixel coordinates of the cursor relative to the page,
 *  at the time of the event.
 *  
 * event.target
 *  Returns a string representing the object that initiated the event.
 *  
 * event.type
 *  Returns a string representing the type of the event (keypress, click, etc).
 *  
 * event.which
 *  Returns a number representing the mouse button that was pressed (1=left, 2=middle, 3=right)
 *  or the ASCII code of the key that was pressed.
 *  
 * event.width
 *  Stores the width of the window or frame containing the object connected with the event.
 *  
 * event.x
 * event.y
 *  These properties hold the X and Y pixel coordinates of the cursor relative to the layer connected
 *  with the event or, for the onResize event, the width and height of the object after it was resized.
 *  (You can also use event.layerX and event.layerY, which do the same thing.)
 *  
 * 
 * So...
 *  leftEdgeOfObject = event.pageX - event.x ?????
 *****************************************************************************/

/*********************
 * User Preferences  *
 *********************/

//Used to set the states of the Delete/Move Up/Move Down buttons on the User Preferences
// page: /members/user_prefs.php
function setButtonStates(deleteButton,upButton,downButton,formLength,formSelectedIndex)
{
	if(formSelectedIndex == -1)
	{
		deleteButton.disabled = true;
		upButton.disabled = true;
		downButton.disabled = true;
	}
	else if (formSelectedIndex == 0)
	{
		deleteButton.disabled = false;
		upButton.disabled = true;
		downButton.disabled = false;
	}
	else if (formSelectedIndex == (formLength-1))
	{
		deleteButton.disabled = false;
		upButton.disabled = false;
		downButton.disabled = true;
	}
	else
	{
		deleteButton.disabled = false;
		upButton.disabled = false;
		downButton.disabled = false;
	}
}

function setFocus(whichField)
{
	//whichField comes in the form of: 'document.edit_article.edit_article[title]'
	eval(whichField + ".focus();");
	//whichField.focus();
}


// Lifted from http://javascript.internet.com/forms/disable-submit.html
function disableSubmit(theForm)
{
	if (document.all || document.getElementById)
	{
		for (i = 0; i < theForm.length; i++)
		{
			var tempobj = theForm.elements[i];
			if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
				tempobj.disabled = true;
		}
		return true;
	}
   return true;
}

function suppressEnter(myfield,e)
{
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	
	if(keycode == 10 || keycode == 13) //LF or CR
	{
		return false;
	}
	else
	   return true;
}

function isControlChar(keycode)
{
	if(keycode == 8) //Backspace
		return true;
	if(keycode == 9) //Horizontal Tab
		return true;
	if(keycode == 11) //Vertical Tab
		return true;
	if(keycode == 14) //Shift Out
		return true;
	if(keycode == 15) //Shift In
		return true;
	if(keycode == 127) //Delete
		return true;
	
	return false;
}

function isInt(e)
{
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	
	// Check for integer values
	if(keycode>=48 && keycode<=57)
		return true;
	
	if(isControlChar(keycode))
		return true;
	
	return false;
}

function isDigit(num)
{
	var string="1234567890";
	if(string.indexOf(num)!=-1)
		return true;
	else
		return false;
}

/***********************************************************/
//
// Check or uncheck all 'checkbox' form elements
//  - Must be called from within the <form>...</form> tags
//  - See findContainingForm(elem) function if calling from a non-form element
//    (e.g. an <a href...> tag within a form)
//  - Use the 
//
function setAllCheckBoxes(form, checkBool)
{
	//if(form.nodeName != 'FORM' || !form.elements.length)
	//	return false;
	
	//Verify that we can find the containing form
	if(!(form = findContainingForm(form)))
		return false;
	
	//Check or uncheck all 'checkbox' form elements
	for(i=0;i<form.elements.length;i++)
		if(form.elements[i].type == 'checkbox')
			form.elements[i].checked = checkBool;
	
	return true;
}
/***********************************************************/


//
// Check or uncheck all 'checkbox' form elements within an element defined by an ID (FORM, DIV, etc)
//  - copied from AIMS project scripts (/projects/aims/include)
//
function setAllCheckBoxesNEW(elemID, checkBool)
{
	var popupObj = document.getElementById(elemID);           // Single element (FORM, DIV, etc)
	var forminputs = popupObj.getElementsByTagName('input');  // Array of INPUT elements inside element
	
	//Check or uncheck all 'checkbox' form elements
	 for(i=0; i<forminputs.length; i++)
		if(forminputs[i].type == 'checkbox')
			forminputs[i].checked = checkBool;
	
	return true;
}


function setAllCheckBoxesByFormName(formName, checkBool)
{
	if(!document.forms[formName])
		return;
	
	return setAllCheckBoxes(document.forms[formName], checkBool);
}

//
//Recursively looks up the stack of nodes to find a form.
//  If one exists, it is returned
//  Otherwise, FALSE is returned
//
function findContainingForm(elem)
{
	if(elem.nodeName == 'FORM')
	{
		//This node is a form
		return(elem);
	}
	else if(elem.parentNode)
	{
		//This node is not a form, but parent node may be
		return findContainingForm(elem.parentNode);
	}
	else
	{
		//This node is not a form and doesn't have a parent node. There is no containing form
		return false;
	}
}

function toggleInputs(theForm,checkBoxName,inputsArray)
{
	errors = theForm.errors;
	errors.value = "";
	if (document.all || document.getElementById)
	{
		for (i = 0; i < inputsArray.length; i++)
		{
//			alert(inputsArray[i]);
			var tempObj = eval("theForm['"+inputsArray[i]+"']");
			var checkObj = eval("theForm['"+checkBoxName+"']");
			//When clicked, it'll still be checked/unchecked,
			// so it's backwards from what would be expected
			if(checkObj.checked)
				//tempObj.disabled = false;
				disableRadioGroup(tempObj);
			else
				//tempObj.disabled = true;
				enableRadioGroup(tempObj)
		}
		return true;
	}
   return true;
}

var errors;

function disableRadioGroup (radioGroup)
{
//	if (!radioGroup.disabled)
//	{
		if(radioGroup.value)
			errors.value = "enabling: " + radioGroup.value + "\n" + errors.value;
		else
			errors.value = "enabling: <attribute not defined> \n" + errors.value;
//		radioGroup.disabled = true;
		if (document.all || document.getElementById)
		{
			if (!radioGroup.length)
				radioGroup.disabled = true;
			else
			{
				errors.value = "radioGroupLen: " + radioGroup.length + "\n" + errors.value;
				for (var b = 0; b < radioGroup.length; b++)
				{
					errors.value = "radio: " + radioGroup[b].value + "\n" + errors.value;
					radioGroup[b].disabled = true;
				}
			}
		}
//	}
}

function enableRadioGroup (radioGroup)
{
//	if (radioGroup.disabled)
//	{
		if(radioGroup.value)
			errors.value = "disabling: " + radioGroup.value + "\n" + errors.value;
		else
			errors.value = "disabling: <attribute not defined> \n" + errors.value;
//		radioGroup.disabled = false;
		if (document.all || document.getElementById)
		{
			if (!radioGroup.length)
				radioGroup.disabled = false;
			else
			{
				errors.value = "radioGroupLen: " + radioGroup.length + "\n" + errors.value;
				for (var b = 0; b < radioGroup.length; b++)
				{
					errors.value = "radio: " + radioGroup[b].value + "\n" + errors.value;
					radioGroup[b].disabled = false;
				}
			}
		}
//	}
}


/*****************
 * Online Store  *
 *****************/

//In testing, not actually in use
//Decided to go with form updates instead
function UpdatePrice(form, priceFieldID, unitPrice, numUnits)
{
	alert("form: "+form+"\npriceFieldID: "+priceFieldID+"\nunitPrice: "+unitPrice+"\nnumUnits: "+numUnits);
	form.getElementByID(priceFieldID).value = '3'; // unitPrice * numUnits;
}


//Simple way of toggling the expand/collapse image when expanding/collapsing a div
// The header div passes in a reference to itself when clicked on.  We then toggle
// its class, which is where the image is defined, as a background
function toggleHeader(obj)
{
	if(obj.className.indexOf("togglerHeaderExpanded") >= 0)
		obj.className = obj.className.replace('togglerHeaderExpanded', 'togglerHeaderCollapsed');
	else
		obj.className = obj.className.replace('togglerHeaderCollapsed', 'togglerHeaderExpanded');
}
