/*****************************************************\
| UI.js holds the scripts to run the interactive bits |
| of the Woodland intranet                            |
\*****************************************************/

var OldClassName;
/****************************************************************\
| Event handler intended for mouseover effects.
|
| srcElement (optional): the element whose className is changed 
|						 by the function.
| note:	if srcElement is null, the srcElement of the
|		window's event object is used.                           
\****************************************************************/
function HiliteElement(srcElement) {
	var Source = (srcElement != null) ? srcElement : window.event.srcElement;
	OldClassName = Source.className;
	Source.className += "Hilite";

}
function openProductImageAdd() {
	var dd = document.MainForm.dd_ProductImageAdd
	var index = dd.selectedIndex
	var ID = dd.options[index].value
 
	window.open("ProductImageEdit.aspx?ID=" + ID + "&Action=NEW")
}
function openCategoryEdit(id) {
	//var dd = document.MainForm.dd_CategoryEdit
	//var index = dd.selectedIndex
	//var ID = dd.options[index].value
	
	window.open("CategoryEdit.aspx?ID=" + id + "&Action=UPDATE")
	//window.open("Admin/CategoryEdit.aspx?ID=" + id + "&Action=UPDATE")
}

function openProductAdmin()
{
	window.open("ProductAdmin.aspx")
}
function openCategoryAdmin()
{
	window.open("CategoryAdmin.aspx")
}
function openAttributeAdmin()
{
	window.open("AttributeAdmin.aspx")
}
function openFinishAdmin()
{
	window.open("FinishAdmin.aspx")
}

/****************************************************************\
| Resets the className from the one created by HiliteElement
\****************************************************************/
function RestoreElement(srcElement) {
	var Source = (srcElement != null) ? srcElement : window.event.srcElement;
	Source.className = OldClassName
}

/****************************************************************\
| Called by the Infragisitics WebTree's InitializeTree event
\****************************************************************/
var IGNavTree;
function NavigationTree_InitializeTree(treeId) {
	IGNavTree = igtree_getTreeById(treeId);
}
/*********************************************************************\
| Depends on IGNavTree which comes from NavigationTree_InitializeTree
\*********************************************************************/
function ToggleFoldersPane() {
	var hidden = ReadCookie("FoldersHidden");
	(hidden == "true") ? ShowFolders() : HideFolders();
	
	WriteCookie("FoldersHidden", (hidden == "true") ? "false" : "true")
}

/*********************************************************************\
| Hides the Folders section
\*********************************************************************/
function HideFolders() {
//	FoldersCell.style.width = "27px";
//	LeftPane.className = "Collapsed";
//	FoldersCollapser.innerText = ">";
//	IGNavTree.treeElement.style.display = "none";
}
/*********************************************************************\
| Shows the Folders section
\*********************************************************************/
function ShowFolders() {
	//FoldersCell.style.width = "250px";
	//LeftPane.className = "";
	//FoldersCollapser.innerText = "<";
	//IGNavTree.treeElement.style.display = "";
}

/****************************************************************\
| Creates a cookie that expires 1 year from the date 
| on which it was created.                           
\****************************************************************/
function WriteCookie(CookieName, CookieValue) {
	var d;
	var Expires;
	d = new Date();
	Expires = new Date((d.getFullYear() + 1), d.getMonth(), d.getDate());
	document.cookie = CookieName + "=" + CookieValue + "; expires=" + Expires
}
/****************************************************************\
| Parses the cookies collection to find the value    
| specified by CookieName.                           
\****************************************************************/
function ReadCookie(CookieName) {
	var CookieString;
	var DesiredValue;
	CookieString = document.cookie.split(";")
	for (var count = 0; count < CookieString.length - 1; count++) {
		if (CookieString[count].indexOf(CookieName) != -1) {
			DesiredValue = CookieString[count];
			break;
		}
	}
	try {
		DesiredValue = DesiredValue.substr( (DesiredValue.indexOf("=") + 1), ( DesiredValue.length - DesiredValue.indexOf("=") ) );
	}
	catch (e) {
		DesiredValue = "";
	}
	
	return DesiredValue;
}

/****************************************************************\
| Used to mimick the behavior of the CSS2 min-height | min-width |
| properties. Best used in conjunction with dynamic properties.  |
\****************************************************************/
function EnforceMinimum(Value, MinValue) {
	var PropertyValue = (Value > MinValue) ? Value : MinValue;
	return PropertyValue
}

/****************************************************************\
| Used to mimick the behavior of the CSS2 max-height | max-width |
| properties. Best used in conjunction with dynamic properties.  |
\****************************************************************/
function EnforceMaximum(Element, Property, MaxValue) {
	if (Element.readyState != "complete") {return}

	if (Element.currentStyle.Property > MaxValue) {
		Element.style.Property = MaxValue
	}
}

/****************************************************************\
| Handles the OnReadyStateChange event for an image you want	 |
| centered.														 |
|																 |
| Uses clientWidth of the elements with the ID parameters to	 |
| center a given element in a given container.					 |
\****************************************************************/
function CenterIn(ContainerID, ElementID) {

	var Container = document.getElementById(ContainerID);
	var Element = document.getElementById(ElementID);
	
	/********************************************\
	 test for availability of Element data
	\********************************************/
	if (Element.readyState != "complete") {return}
	
	/********************************************\
	 Prevent the container from stretching to fit
	 the demensions of the element
	\********************************************/
	Container.style.position = "relative";
	Element.style.position = "absolute";
	
	/******************************************\
	 Measure width & height of both elements
	\******************************************/
	var ContainerWidth = Container.clientWidth
	var ContainerHeight = Container.clientHeight
	
	var ElementWidth = Element.clientWidth
	var ElementHeight = Element.clientHeight
	
	/********************************************\
	 if the Element is bigger than the container,
	 add some padding to the container to give
	 the appearance of being centered.
	\********************************************/
	if (ContainerWidth > ElementWidth) {
		Element.style.left = ((ContainerWidth - ElementWidth) / 2);
	}
	else {
		Element.style.left = 0;
		Container.style.width = Element.offsetWidth + 5;
	}
	
	if (ContainerHeight > ElementHeight) {
		Element.style.top = ((ContainerHeight - ElementHeight) / 2);
	}
	else {
		Element.style.top = 0;
		Container.style.height = Element.offsetHeight + 5;
	}
	
}
/*********************************************\
| Loads the page at the specified URL into the
| browser.
\*********************************************/
function NavigateTo(url) {
	window.location = url;
}
/*********************************************\
| Displays a message in the status bar.
\*********************************************/
function ShowStatus(Message) {
	window.status = Message;
}
/*********************************************\
| Resets the message in the status bar.
\*********************************************/
function ResetStatus() {
	window.status = "";
}

/*********************************************\
| Adds dynamic behavior to the elements in the
| Elements Array.
\*********************************************/
function InitDynamicInputs(Elements, Values) {
	/***********************************************\
	 Iterate through the Elements array and
	 attatche event handlers and defalut values
	 
	 NOTE:	Each element in Elements must have a 
			value in Values, even if that value is an 
			empty string.
	\***********************************************/
	for (var i = 0; i<Elements.length; i++) {
		var Element = Elements[i];
		if (Element) {
			with (Element) {
				onfocus = ElementFocus;
				onblur = ElementBlur;
				if (value == "") {
					value = Values[i];
				}
			}
		}
	}
}
var ValueIndex;
/***********************************************\
| ElementFocus()								|
|	Erases the default value for an element		|
|	to allow easy entry of desired value.		|
\***********************************************/

function ElementFocus() {
	e = window.event;
	
	// Find element focused on in Elements array
	for (var i=0;i<Elements.length;i++) {
		if (Elements[i] == e.srcElement) {
			ValueIndex = i
		}
	}
	
	// Test for default value. If found, erase.
	if (e.srcElement.value == Values[ValueIndex]) {
		e.srcElement.value = "";
	}
}

/***********************************************\
| ElementBlur()									|
|	Re-inserts default value if no other		|
|	value has been entered.						|
\***********************************************/
function ElementBlur() {
	e = window.event;

	if (e.srcElement.value == '') {
		e.srcElement.value = Values[ValueIndex];
	}
}

/************************************************\
| Toggle( ElementID )
|	For the element found with ElementID, toggles
|	between default and no display.
|
|	Inputs:
|		ElementID (string) [optional] 
|			Element to toggle. Can be either the id, or the element itself
|
|		Toggler (element) [optional]
|			Clickable handle that
|			initiates the toggling
|
|		Subject (string) [optional]
|			Descriptive text to add after 'show'
|			or 'hide'
|
|	Note: Assumes a stack of 17px tall Images,
|		  'Show' image on top
\************************************************/
function Toggle( ElementID, Toggler, Subject ) {
	//var Element = document.getElementById(ElementID);
	var Element = GetElement(ElementID);
	//var Toggler = document.getElementById(TogglerID)
	if (Toggler.nodeName != "element") {
		Toggler = event.srcElement
	}/**/
	
	if (Element == null) {
		// Grab Toggler's next younger sibling
		Element = getYoungerSibling(Toggler)
	}
	
	try {
		var bHidden = Element.style.display == "none";

		if (bHidden) {
			// Show the element
			Element.style.display = '';
			
			Toggler.title = (Subject != '') ? "Hide " + Subject : + "Hide";
			//Toggler.style.backgroundPosition = "0px 17px"
		}
		else {
			// Hide the element
			Element.style.display = 'none';
			
			Toggler.title = (Subject != '') ? "Show " + Subject : + "Show";
			//Toggler.style.backgroundPosition = "0px 0px"
		}
		
	}
	catch (e) {}
}

/*******************************************************\
| getParentByTagName(Element, TagName)
|
|	Inputs:
|		Element(node) [required]:
|			child in search of its ancestor
|
|		TagName(string) [required]:
|			Sets desired type of ancestor
|
|	For Element, walks up the heirarchy to find it's 1st
|	ancestor whose tagName == TagName
\*******************************************************/
function getParentByTagName(Element, TagName) {
	if (typeof Element == 'object') {
		var ElementFound = false;
		
		while (!ElementFound) {
			Element = Element.parentNode;
			
			// Use DOM 1 (core) to test if the current node is the document
			// 'document' element is the end of the line. Parent element not found
			if (Element.nodeType == 9) break;
			
			if (Element.tagName.toLowerCase() == TagName.toLowerCase()) {
				ElementFound = true
				break;
			}
		}
		
		
		return Element
	}
}

/***********************************************\
| getParentByClassName
|	Same as above, but className == ClassName
\***********************************************/
function getParentByClassName(Element, ClassName) {
	if (typeof Element == 'object') {
		var ElementFound = false;

		while (!ElementFound) {
			
			Element = Element.parentNode;
			
			// Use DOM 1 (core) to test if the current node is the document
			// 'document' element is the end of the line. Parent element not found
			if (Element.nodeType == 9) break;//note: setting ElementFound = false would create an infinite loop.
			
			//if (Element.className.toLowerCase() == ClassName.toLowerCase()) {
			if (Element.className.toLowerCase().indexOf(ClassName.toLowerCase()) > -1)
			{
				ElementFound = true
				break;
			}
		}
		
		if (!ElementFound) {
			Element = null;
		}
		
		return Element
	}
}

/***********************************************\
| getYoungerSibling(Element)
|	returns the sibling just below Element
\***********************************************/
function getYoungerSibling(Element) {
	// nodeType 1 is an element node
	if (Element.nodeType == 1) {
		var Parent = Element.parentElement
		var siblings = Parent.childNodes
		
		for (var c = 0; c<siblings.length;c++) {
			if (siblings(c) == Element) {
				return siblings(c+1);
			}
		}
	}
}

/***********************************************\
| TieElementTobutton(Element, ButtonID)
|	Calls the click event for Button when the
|	Enter key is pressed while Element has the
|	focus.
\***********************************************/
function TieElementToButton(Element, ButtonID) {
	// KeyCode 13 corresponds to the Enter key
	if (event.keyCode != 13) return
	var ButtonToClick = document.getElementById(ButtonID);
	ButtonToClick.click()
	event.returnValue = false;
}

function GetElement(Element) {
	if (typeof Element != "object") {
		Element = document.getElementById(Element);
	}
	
	return Element
}

function GetText(Element)
{
	var sText = "";
	if (Element.innerText != null)
	{
		sText = Element.innerText;
	}
	else if (Element.textContent != null)
	{
		sText = Element.textContent;
	}
	
	return sText;
}
function SetText(Element, Text)
{
	if (Element.innerText != null)
	{
		Element.innerText = Text;
	}
	else if (Element.textContent != null)
	{
		Element.textContent = Text;
	}
}

function EncodeEntities(str)
{
	Encode(str);
}

function DecodeEntities(str)
{
	Decode(str);
}

/*
	Encode and Decode
	Searches for a discrete set of tags that are allowed to be entered
	by the user. Any other potentially-dangerous characters will throw
	the exception as expected.
*/
var arrOffendingChars = new Array();
var arrReplacementChars = new Array();

arrOffendingChars[0] = "<br>";
arrReplacementChars[0] = "[br /]";
arrOffendingChars[1] = "<br/>";
arrReplacementChars[1] = "[br /]";
arrOffendingChars[1] = "<br />";
arrReplacementChars[1] = "[br /]";

function Encode(sIn)
{
	for (var i = 0;i<arrOffendingChars.length;i++)
	{
		while (sIn.indexOf(arrOffendingChars[i]) > -1)
		{
			sIn = sIn.replace(arrOffendingChars[i], arrReplacementChars[i]);
		}
	}
	return sIn;
}
function Decode(sIn)
{
	for (var i = 0;i<arrReplacementChars.length;i++)
	{
		while (sIn.indexOf(arrReplacementChars[i]) > -1)
		{
			sIn = sIn.replace(arrReplacementChars[i], arrOffendingChars[i]);
		}
	}
	return sIn;
}





/*
	QueryString object holds query string variables
*/
function QueryString()
{
	var _items = window.location.search.substring(1).split("&");
	this.Items = new Collection();
	for (var i = 0, len = _items.length; i<len; i++)
	{
		var Name = _items[i].split("=")[0];
		var Value = _items[i].split("=")[1];
		
		this.Items[Name] = Value;
	}
}

function Collection()
{
	this.count = function() {
		var i = 0;
		for (var att in this)
		{
			i++
		}
		return i - 1;//dont count the 'count' property
	};
}



/*
	inserts a "$" at the beginning, rounds to two decimal places,
	and from the left, every 3 characters inserts a comma
	
	Psuedo code for comma insertion:
	FormattedNum = return value
	preComma = sNum % 3 = chars from begining before 1st comma
	
	1] if preComma > 0, take sNum.substring(0, preComma) and add that to FomrattedNum
	2] sNum = sNum.substr(preComma), storing the remaining digits in sNum
	3] Then, add a comma.
	4] While sNum.length > 0, repeat steps 5 & 6
	5] Append the next three digits to FormattedNum
	6] sNum = sNum.substr(3), storing the remaining digits in sNum
	7] if sNum.length > 0, append a comma to FormattedNum
*/
function FormatCurrency(sNum)
{
	if (isNaN(sNum))
	{
		return sNum
	}
	else
	{
	    sNum = parseFloat(sNum)
	}
	
	sNum = sNum.toFixed(2)
	//end mid by kevin
	
	sNum = sNum.toString()
	var negative = ""
	if (sNum.indexOf("-") >= 0)
	{
		negative = "-";
		sNum = sNum.substr(1);
	}
	var FormattedNum = ""; //return value
	
	var bDecimal = new Boolean(sNum.indexOf(".") > 0)
	var DecimalPart
	if (bDecimal == false) 
	{
		DecimalPart = ".00"
	}
	else 
	{
		DecimalPart = sNum.substr(sNum.indexOf("."))
		sNum = sNum.substring(0, sNum.indexOf("."))
	}
	if (DecimalPart.length < 2){DecimalPart = DecimalPart + "0"}
	
	var len = sNum.length;
	var preComma = 0; //chars from begining before 1st comma
	if (len > 2)
	{
		preComma = len % 3
	}
	
	var litComma = ","
	
	
	
	if (preComma > 0) 
	{
	/*1*/	FormattedNum = FormattedNum + sNum.substring(0, preComma)
	/*2*/	sNum = sNum.substr(preComma)
	/*3*/	FormattedNum = FormattedNum + litComma;
	}
	
	/*4*/while (sNum.length > 0)
	{
	/*5*/	FormattedNum = FormattedNum + sNum.substring(0, 3)
	/*6*/	sNum = sNum.substr(3);
	/*7*/	FormattedNum = (sNum.length > 0) ? FormattedNum + litComma : FormattedNum;
	}
	
	FormattedNum = negative + "$" + FormattedNum + DecimalPart;
	
	return FormattedNum
}
