/* DF functions */
var DF = new function(){};

DF.namespace = function(s){
	var names = s.split('.');
	var curNs = DF;
	for (var i = names.length > 0 && names[0] == "DF" ? 1 : 0; i < names.length; i++){
		if (!curNs[names[i]]) curNs[names[i]] = new function(){};
		curNs = curNs[names[i]];
	}
};

DF.$ = function(el){
	if (DF.Dom.isEl(el)) return el;
	if (!DF.string.isNullOrEmpty(el)) return document.getElementById(el);
	return null;
};
$ = DF.$; // alias

DF.isSafari = navigator.userAgent.search(/safari/i) > -1;
DF.isIE = !!(document.all);
	
DF.namespace('DF.array');

DF.array.isArray = function(o){
	if (DF.isSafari)
		return (typeof(o)).toLowerCase() == 'object' && o.length && o.pop && o.push;
	else
		return o.constructor && o.constructor.toString().indexOf('Array') > -1;
}

DF.array.applyFunction = function(array, func, params){
	if (DF.array.isArray(array)){
		for (var i = 0; i < array.length; i++){
			func(array[i], params);
		}
	}else{
		func(array, params);
	}
};

DF.array.listToArray = function(list){
	var a = new Array();
	for (var i = 0; i < list.length; i++){
		a.push(list[i]);
	}
	return a;
};

DF.namespace('DF.string');

DF.string.endsWith = function(src, sub){
	return src.lastIndexOf(sub) == src.length - sub.length;
};

DF.string.isNullOrEmpty = function(str){
	return (typeof(str)).toLowerCase() != 'string' || str.length == 0;
};

DF.namespace('DF.Dom');

DF.Dom.isEl = function(el){
	return !!(el.nodeType && el.tagName);
};

DF.Dom.getAllElements = function(rootEl, els){
	els = els || [];
	rootEl = $(rootEl) || document.body;
	for (var i = 0; i < rootEl.childNodes.length; i++){
		var child = rootEl.childNodes[i];
		if (DF.Dom.isEl(child)){
			els.push(child);
			DF.Dom.getAllElements(child, els);
		}
	}
	return els;
};

DF.Dom.getElementsByClassName = function(className, tagName, rootEl){
	var els = [];
	if (!DF.string.isNullOrEmpty(className)){
		rootEl = $(rootEl) || document;
		var searchEls = DF.string.isNullOrEmpty(tagName) ? DF.Dom.getAllElements() : rootEl.getElementsByTagName(tagName);
		for (var i = 0; i < searchEls.length; i++){
			var el = searchEls[i];
			if (DF.Dom.hasClass(el, className))
				els.push(el);
		}
	}
	return els;
};

DF.Dom.addClass = function(el, className){
	DF.array.applyFunction(el, function(el){
		el = $(el);
		if (!DF.string.isNullOrEmpty(className) && !DF.Dom.hasClass(el, className))
			el.className += ' ' + className;
	});
};

DF.Dom.removeClass = function(el, className){
	DF.array.applyFunction(el, function(el){
		el = $(el);
		if (!DF.string.isNullOrEmpty(className)){
		
			var r = new RegExp('(?:^|[ ]+)'+className+'(?:$|[ ]+)');
			el.className = el.className.replace(r, '');
		}
	});
};

DF.Dom.hasClass = function(el, className){
	if (!DF.string.isNullOrEmpty(className)){
		el = $(el);
		var classes = el.className.split(' ');
		for (var i = 0; i < classes.length; i++){
			if (classes[i] == className)
				return true;
		}
	}
	return false;
};

DF.Dom.setStyle = function(el, style, value){
	if (el && !DF.string.isNullOrEmpty(style)){
		DF.array.applyFunction(el, function(el, arg){
			el = $(el);
			el.style[arg.style] = arg.value;
		}, {'style':style, 'value':value});
	}
};

DF.Dom.removeAttribute = function(el, attr){
	DF.array.applyFunction(el, function(el, attr){ // el array
		DF.array.applyFunction(attr, function(attr, el){ // attr array
			$(el).removeAttribute(attr);
		}, el);
	}, attr);
};

DF.Dom.removeEl = function(el){
	DF.array.applyFunction(el, function(el){
		el = $(el);
		if (el.parentNode) el.parentNode.removeChild(el);
	});
};

DF.Dom.prependEl = function(child, parent){
	child = $(child);
	parent = $(parent);

	if (parent.childNodes.length > 0)
		parent.insertBefore(child, parent.childNodes[0]);
	else
		parent.appendChild(child);
};

DF.Dom.getXY = function(el){
	var xy = [0,0];
	el = $(el);
	while (el && el != document){
		xy[0] += el.offsetLeft;
		xy[1] += el.offsetTop;
		el = el.offsetParent;
	}
	return xy;
}

DF.namespace('DF.events');

DF.events.addOnLoadFunction = function(func)
{
	var oldOnLoad = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldOnLoad();
			func();
		}
	}
};

DF.namespace('DF.Validation');

DF.Validation.validateEmail = function(efield, required)
{
	if (required == false && efield.value == "") {
		return "";
	}
	
	if (efield.value.match(/^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$/) == null)
		return "Invalid E-mail Address.\n";

	return "";
};

DF.Validation.ValidatePhone = function(pfield, required)
{
	if (required == false && pfield.value == "") {
		return "";
	}
	
	var pvalue = pfield.value;
	rePhoneNumber = new RegExp(/^\(?\d{3}\)?[-., ]*\d{3}[-., ]*\d{4}$/);

	if (!pvalue.match(rePhoneNumber)) {
		return "Please enter a 10 digit phone number (ex. 555-555-1234)\n";
	}
	
	return "";
};

/*
	5 digit Zip code validation.
	return "" if the zip is in the correct format, error message otherwise. 
*/
DF.Validation.ValidateZIPCode = function(zfield, required)
{
	if (required == false && zfield.value == "") {
		return "";
	}

	if (zfield.value.search(/^\d{5}$/) != 0) {
		return "Please enter a valid 5-digit ZIP Code.\n";
	}
	return "";
};

DF.Validation.FormRequired = function(field)
{
	if (field.type=="checkbox" || field.type=="radio") {
		if (!field.checked){
			return field.name + " is a required field.\n";
		}
	} else if (field[0] && (field[0].type=="checkbox" || field[0].type=="radio")) {
		var check = false;
		var name = field[0].name;
		for (var i=0; i<field.length; i++) {
			if (field[i].checked) {
				check = true;
			}
		}
		if (!check) {
			var msg;
			if (field.type=="checkbox"){
				msg = "Please choose at least one option from ";
			}
			else {
				msg = "Please choose an option from ";
			}
			return msg + name + "\n";
		}
	} else if (field.type=="select-one" || field.type=="select-multiple") {
		if (field.options[field.selectedIndex].value=="")
			return field.name + " is a required field.\n";
	} else {
		if (field.length == 0 || field.value == "") {
			return field.name+" is a required field.\n";
		}
	}
	return "";
};

DF.Validation.equalToField = function (field, otherField, required) {
	if (field.value !== otherField.value) {
		return field.id + " must have the same value as " + otherField.id + ".\n";
	}
	
	return "";
};

DF.Validation.limit = function(field, chars) {
       if (field.value.length > chars) {
              field.value = field.value.substr(0, chars);
              alert('You are only allowed to enter '+chars+' characters in the '+field.name+' field!');
       }
};

//Backward compatible alias
ValidateEmail = DF.Validation.validateEmail;
ValidatePhone =  DF.Validation.ValidatePhone;
ValidateZIPCode = DF.Validation.ValidateZIPCode;
FormRequired = DF.Validation.FormRequired;
limit = DF.Validation.limit;


DF.namespace('DF.Util.Cookies');
DF.Util.Cookies.getCookie = function(key1,key2) {       

	var sCookie = new String(document.cookie);
	//alert(sCookie)
	if(key1 != null)
	{
		var aCList = sCookie.split('; ');
		for(var i = 0;i < aCList.length;i++)
		{
			sCookie = aCList[i];
			var oReg = new RegExp("(^"+key1+"=)(.*)","ig");
			var aResult = oReg.exec(sCookie);
			if(aResult != null)
			{
				sCookie = RegExp.$2;
				if(key2 != null)
				{
					aCList = sCookie.split("&");
					for(var i = 0;i < aCList.length;i++)
					{
						sCookie = aCList[i];
						var oReg = new RegExp("(^"+key2+"=)(.*)","ig");
						var aResult = oReg.exec(sCookie);;
						if(aResult != null)
						{
							sCookie = unescape(RegExp.$2);
							break;
						}else {
							sCookie = false;
						}
					}
				}
				break;
			} else {
				sCookie = false;
			}
		}
	}
	return sCookie;
};


/* End DF Functions */

/* Menus */
DF.namespace('DF.EE.menu');
EE = DF.EE; // alias

EE.menu.topMenuHtml = [];

(function(){ // EE.menu scope
	
	var timerId, topMenus = new Array();
	
	function init(){
	    var menulist = $('hd-menu-list');
        if(menulist){       
	        var menus = menulist.getElementsByTagName('li');
	        for(var i = 0; i < menus.length; i++){
                var m = new EE.menu.TopMenu(menus[i]);                
                topMenus.push(m);
            }
		}
	};
	DF.events.addOnLoadFunction(init);
	
	EE.menu.hideAll = function(){
		DF.array.applyFunction(topMenus, function(topMenu){
			topMenu.hideDropDown();
		});
	};
	
	EE.menu.writeDropDown = function(i){
		if (EE.menu.topMenuHtml.length > i)
			document.write(EE.menu.topMenuHtml[i]);
	};
	
	EE.menu.TopMenu = function(el){
		var dropDown, dropDownItems = new Array();
		
		dropDown = el.getElementsByTagName('ul')[0];
				
		if (dropDown) 
		{
			dropDownItems = DF.array.listToArray(dropDown.getElementsByTagName('li'));
		}
				
		this.el = $(el);
				
		var me = this;
		this.el.onmouseover = function() {onMouseOver.call(me);};
		this.el.onmouseout = function() {onMouseOut.call(me);};
		
		function onMouseOver(e){
			if (timerId) clearTimeout(timerId);
			EE.menu.hideAll();
			this.showDropDown();
		}
		
		function onMouseOut(e){
			if (timerId) clearTimeout(timerId);
			timerId = setTimeout('EE.menu.hideAll()', 600);
		}
		
		// Frame workaround for IE. Sends top level menu behind dropdown on side of expansion.
		function HideSiblings(el, direction)
		{
			var CurNode = $(el);
			var CurIndex, FirstNeighbor, NextNeighbor;
			var TempListItems = $('hd-menu-list').getElementsByTagName('li');										
									
			// Array of top level menu items
			var TopLevel = [];
			for(var i=0; i< TempListItems.length; i++)
			{
				if(TempListItems[i].parentNode.id == 'hd-menu-list')
				{
					TopLevel.push(TempListItems[i]);
				}
			}
			
			for(var i=0; i < TopLevel.length; i++)
			{	
				if (CurNode == TopLevel[i])
				{	
					CurIndex = i;
					FirstNeighbor = CurIndex + 1;
					NextNeighbor = CurIndex + 2;					
				}				
				if (direction == "right" && CurIndex < TopLevel.length)
				{					
					if (DF.isIE)
					{	
						TopLevel[FirstNeighbor].style.zIndex = 1;
						if (NextNeighbor < TopLevel.length)
							TopLevel[NextNeighbor].style.zIndex = 1;
					}
				}
				else { // Works fine going left - natural z order.
				}
			}		
		}
		
		// Frames workaround. Restore top menu neighbors for IE.	
		function ShowSiblings(el)
		{
			var CurNode = $(el);
			var TempListItems = $('hd-menu-list').getElementsByTagName('li');										
												
			// Array of top level menu items
			var TopLevel = [];
			for(var i=0; i< TempListItems.length; i++)
			{
				if(TempListItems[i].parentNode.id == 'hd-menu-list')
				{
					TopLevel.push(TempListItems[i]);
				}
			}
			
			for(var i=0; i< TopLevel.length; i++)
			{				
				// Restore top-level items for IE. Firefox uses the CSS.
				if (DF.isIE)
				{
					TopLevel[i].style.zIndex = 0;
				}
			}
		}	
				
		function SetWidth(width)		{
			var w = width + 1 + 'px';
			DF.Dom.setStyle(dropDown, 'width', w);
			if (DF.isIE) DF.Dom.setStyle(dropDownItems, 'width', '100%');					
			DF.Dom.setStyle(dropDown, 'overflow', 'hidden');
		}
		
		// Frames workaround. Display dropdown on side with more room.
		function GotoBiggerSide(RoomRight, RoomLeft, width)	{
			var AdjRight = width - 2;
			var AdjLeft = width - 1;
			
			if (RoomRight > RoomLeft)
			{
				DF.Dom.setStyle(dropDown, 'right', 'auto');
				DF.Dom.setStyle(dropDown, 'left', AdjLeft);
			}
			else
			{
				DF.Dom.setStyle(dropDown, 'left', 'auto');
				DF.Dom.setStyle(dropDown, 'right', AdjRight);
			}
			DF.Dom.setStyle(dropDown, 'borderRight', 'solid 1px #8f8f8f');
		}		
				
		this.showDropDown = function(){
			if (dropDown){
				DF.Dom.setStyle(dropDown, 'display', '');	// Prevents scrollbar from wide, non-displayed menu items.
			
				// min width match parent
				if (this.el.offsetWidth + 1 > dropDown.offsetWidth){
					var w = this.el.offsetWidth + 1 + 'px'; // + offset for border
										
					DF.Dom.setStyle(dropDown, 'width', w);					
				}				
				if (DF.isIE) DF.Dom.setStyle(dropDownItems, 'width', '100%');
				
				var menuEl = $('hd-menu');					
				
				// avail height down to bottom of b/g image
				var HtBelow = 124;
				var HtTotal = 210;
				
				// dropdown ht, width, left edge
				var dH = dropDown.offsetHeight;
				var dW = dropDown.offsetWidth;
												
				// left edge top menu item
				var MenuPos = DF.Dom.getXY(this.el)[0];
				
				// width of top menu item
				var MenuWidth = this.el.offsetWidth
				var MenuWidthAdjLeft = MenuWidth - 1;
				var MenuWidthAdjRight = MenuWidth - 1 ;
				
				// initial room on right and left, from left edge
				var RoomOnRight = 955 - MenuPos + 20;
				var RoomOnLeft = MenuPos;
				
				// room after moving over (less width of top item)
				var NetRoomOnRight = RoomOnRight - MenuWidth;
				var NetRoomOnLeft = RoomOnLeft - 20;
				// max room, either side
				var NetRoom = (NetRoomOnLeft > NetRoomOnRight) ? NetRoomOnLeft : NetRoomOnRight;
		
				// Right align dropdowns that would extend beyond right edge
				if (DF.Dom.getXY(dropDown)[0] + dropDown.offsetWidth > DF.Dom.getXY(menuEl)[0] + menuEl.offsetWidth){
					
					// too wide for either side
					if (dW > NetRoomOnRight && dW > NetRoomOnLeft)
					{
						// reduce width to max available
						SetWidth(NetRoom);
						
						// go to bigger side 
						GotoBiggerSide(NetRoomOnRight, NetRoomOnLeft, MenuWidth);
					}
					else
					{
						DF.Dom.setStyle(dropDown, 'left', 'auto');
						DF.Dom.setStyle(dropDown, 'right', '-2px');
					}
				}								
				
				/*
					Workaround for framed site. 
					Shift dropdown to the side when taller than area below. 
					Pick side with GotoBiggerSide().
					Test for frames by height since top frame is 229 px max.					
				*/
				//if (dH > HtBelow && document.body.scrollHeight < 270)
				if (parent.frames.length > 0)
				{
					if (dH > HtBelow )
					{		
						// add top border when moved over.
						DF.Dom.setStyle(dropDown, 'borderTop', 'solid 1px #8f8f8f');
						
						// start at bottom of available area
						DF.Dom.setStyle(dropDown, 'bottom', '-101px');
												
						// too wide for either side
						if (dW > NetRoomOnRight && dW > NetRoomOnLeft)
						{	
							// reduce width to max available
							SetWidth(NetRoom);						
							// go to bigger side 
							GotoBiggerSide(NetRoomOnRight, NetRoomOnLeft, MenuWidth);
							
						}
						// more room on right
						else if (NetRoomOnRight > NetRoomOnLeft)		
						{
								DF.Dom.setStyle(dropDown, 'right', 'auto');
								DF.Dom.setStyle(dropDown, 'left', MenuWidthAdjLeft);							
								
								HideSiblings(el, "right");	//Move items on right below the dropdown so they don't show through.
						}
						// more room on left
						else											
						{
								DF.Dom.setStyle(dropDown, 'left', 'auto');
								DF.Dom.setStyle(dropDown, 'right', MenuWidthAdjRight);							
						}
						
						// when taller than total height, display from top down rather than bottom up (cut off bottom items).
						if (dH > HtTotal)
						{
							DF.Dom.setStyle(dropDown, 'bottom', '');
							DF.Dom.setStyle(dropDown, 'top', '-70px');
						}
					}
				} 	
				DF.Dom.setStyle(dropDown, 'visibility', 'visible');		
			}
		};
		
		this.hideDropDown = function(){
			DF.Dom.setStyle(dropDown, 'display', 'none');
			DF.Dom.setStyle(dropDown, 'left', '');
			DF.Dom.setStyle(dropDown, 'right', '');
			DF.Dom.setStyle(dropDown, 'width', '');
			DF.Dom.setStyle(dropDown, 'visibility', '');
			
			// Restore the top menu
			var menuEl = $('hd-menu-list');						
			ShowSiblings(menuEl); 
		};
	};
})();


(function(){ 	
	function init(){
		var loginBtn = $('loginBtn');
		var logoutBtn = $('logoutBtn');

		if(loginBtn)
		{
			var loginCookie = DF.Util.Cookies.getCookie("LoggedIn");
			if (loginCookie === "True")
			{
				DF.Dom.addClass(loginBtn, 'hide');
				DF.Dom.removeClass(logoutBtn, 'hide');
			}
			else
			{
				DF.Dom.addClass(logoutBtn, 'hide');
				DF.Dom.removeClass(loginBtn, 'hide');
			}
		}
	};
	DF.events.addOnLoadFunction(init);
})();


