
// global variables
var globalVar = {
    leftNavSelClass: "selected"
}

//Checks if the original string ends with subStr 
function endsWith(original, subStr) {
    var lastIndex = original.lastIndexOf(subStr);
    return (lastIndex != -1) && (lastIndex + subStr.length == original.length);
}

//Add functions that will be executed by window.onload 
function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		} 
	} 
} 

//Returns ONLY the first element of a collection of elements 
//with a specific element tag and class name
function getFirstElementByClassName(elementTag, elementClassName) {
	var elements = document.getElementsByTagName(elementTag);
	for (var i = elements.length-1;i>-1;i--) {
		if ( elements[i].className ){//&& elements[i].className.indexOf(elementClassName) != -1 ) {
			var classNames = elements[i].className.split(" ");
			for (classNameIndex = 0; classNameIndex < classNames.length; classNameIndex++){
				if(classNames[classNameIndex] == elementClassName)
					return elements[i];
			}
		}
	}
	return null;
}

//Pop up a new window with the specified properties
function popup(strUrl, iWidth, iHeight, iLeft, iTop, blnCenter, strName, strScroll, strMenus, strTools, strResize, strLocate)
{
  if ( blnCenter )
  {
    iLeft = (screen.width - iWidth) / 2;
    iTop = (screen.height - iHeight) / 2;
  }
  
  var winprops =  "location=" + strLocate + ",scrollbars=" + strScroll + ",menubar=" + strMenus + ",toolbar=" + strTools + ",resizable=" + strResize + ",left=" + iLeft + ",top=" + iTop + ",width=" + iWidth + ",height=" + iHeight;   

  var popup = window.open(strUrl,strName,winprops);
  popup.focus();
}


/* COOKIE CODE */
//To get a cookie value by name use function:
//returnPopulatedValue(cookieName,attributeName);
//@returns query string and if none the value from the specified cookie (if avialable)
//Note cookie functions other than set and get are expecting name = value pairs and are "&" delimited
var theCookieName = "phoenix_prepop";
function setCookie(cookieName,cookieValue,expires,path,domain,secure){
	var curCookie = cookieName + "=" + escape(cookieValue) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}
function getCookie(cookieName){
	var dc = document.cookie;
	var prefix = cookieName + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1)
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;
	
	var end = dc.indexOf(";", begin);
	if (end == -1) end = dc.length;
	
	var returnVal = unescape( dc.substring( begin + prefix.length, end ) );
	return returnVal;
}
function deleteCookie(cookieName, path, domain){
	var now = new Date();
	fixDate( now ); // fix the bug in Navigator 2.0, Macintosh
	var expired = new Date(now.getTime() - 28 * 24 * 60 * 60 * 1000); // 28 days ago

	if ( getCookie( cookieName ) )
	{
		document.cookie = cookieName + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=" + expired.toGMTString();
	}
}
function fixDate(date){
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) date.setTime(date.getTime() - skew);
}

function returnUrlAttributeValue(attributeName) {
	var pageURL = document.location.href;
	if (pageURL.indexOf('?') != -1) {
		var queryString = pageURL.substring(pageURL.indexOf('?') + 1,pageURL.length);
		var queryStringArray = queryString.split("&");
		for ( var i=0, v=queryStringArray.length; i<v; i++) {
			curItem = queryStringArray[i];
			if (curItem.substring(0,curItem.indexOf("=")).toLowerCase() == attributeName.toLowerCase()) {
				return curItem.substring(curItem.indexOf("=") + 1,curItem.length);
				break;
			}
		}
		return "";
	} else {
		return "";
	}
}
function returnCookieAttributeValue(cookieName,attributeName) {
	var cookieValue = getCookie(cookieName);
	var cookieValueArray = ( cookieValue ) ? cookieValue.split("&") : "";
	for (var i=0, v=cookieValueArray.length; i<v; i++) {
		curItem = cookieValueArray[i];
		if (curItem.substring(0,curItem.indexOf("=")).toLowerCase() == attributeName.toLowerCase()) {
			return curItem.substring(curItem.indexOf("=") + 1,curItem.length);
			break;
		}
	}
	return "";
}
function setCookieValue(cookieName,nameValuePair) {
	var thisCookie = getCookie(cookieName);
	var thisDelimiter = (thisCookie) ? "&" : "";
	if ( thisCookie != null ) {
		var thisName = nameValuePair.substring(0,nameValuePair.indexOf("="));
		if (thisCookie.indexOf(thisName) == -1) {
			setCookie(cookieName,thisCookie + thisDelimiter + nameValuePair,'','/');
		} else {
			var arrCookiePairs = thisCookie.split("&");
			if ( arrCookiePairs.length > 0 ) {
				var strNameToMatch = nameValuePair.split("=")[0];
				var strNewValue = nameValuePair.split("=")[1];
				var strNewCookie = "";
				for (var i=0, j=arrCookiePairs.length; i<j; i++) {
					if ( arrCookiePairs[i].split("=").length > 1 ) {
						var strCurName = arrCookiePairs[i].split("=")[0];
						if ( strCurName == strNameToMatch ) {
							strNewCookie = strNewCookie + strCurName + "=" + strNewValue;
						} else {
							strNewCookie = strNewCookie + arrCookiePairs[i];
						}
						if (i+1 != j) strNewCookie = strNewCookie + "&";
					}
				}
			}
			if ( strNewCookie != "" ) {
				setCookie(cookieName,strNewCookie,'','/');
			}
		}
	}
	else {
		setCookie(cookieName,nameValuePair,'','/');
	}
}
function returnPopulatedValue(cookieName,attributeName,defaultValue) {
	var urlAttributeValue = returnUrlAttributeValue(attributeName);
	if (urlAttributeValue != "") {
		// Get Value From URL
		// Phone Check
		if (attributeName == "CLPhone" && !returnSimplePhoneCheck(urlAttributeValue)) {
			return defaultValue;
		}
		return urlAttributeValue;
	} else {
		// Get Value From Cookie
		strCookieVal = returnCookieAttributeValue(cookieName,attributeName);
		if (strCookieVal == "" && defaultValue) {
			return defaultValue;
		} else {
			return strCookieVal;
		}
	}
}


/* LEFT NAVIGATION */
/* Set Left Navigation Selected Menu base on the a tag html text
* 1) menu - is the first level, required
* 2) subMenu - 2nd level (optional)
*/
var setLeftNav = function(menu, subMenu) {
	if(!menu) return;
	//Adds the .html to the menu if it doesn't have any
	if(!endsWith(menu, ".html")){
		menu += ".html";
	}
	var leftNavDiv = document.getElementById('leftNav');
	var leftNavLinks = leftNavDiv.getElementsByTagName('a');
	for( var linkIndex = 0; linkIndex < leftNavLinks.length; linkIndex++){
		var link = leftNavLinks[linkIndex];
		var linkPath = link.getAttribute('href');
		if((endsWith(linkPath, menu)) || (subMenu && endsWith(linkPath, subMenu))){
			link.className += globalVar.leftNavSelClass;
		}
	}
}


/* HEADER */
//remove header search field text if not changed
var addFieldOnOffEvent = function() {
    var fieldWrapperInput = document.forms['headerSearch'].elements['q'];
    var defaultTxt = fieldWrapperInput.value;
    fieldWrapperInput.onfocus = function() {
        if (defaultTxt == fieldWrapperInput.value)
            fieldWrapperInput.value = "";
    };
    fieldWrapperInput.onblur = function() {
        if (fieldWrapperInput.value == "")
            fieldWrapperInput.value = defaultTxt;
    };

}

/* Module to perform search from header
* @class headerSearch
*/
var headerSearch = function () {
	var searchField, goButton, searchContainer, searchForm;
	var defaultInputValue;
	var messaging = {
		invalidSearchTerm: 'Please enter a valid search term.'
	}		
	
	return {
		/*
		 * headerSearch initialization function
		 * 
		 * What it does:
		 * caches jquery elements for search field,go button, search container and the form, and 
		 * binds the validate search and remove messaging functions to the submit event
		 *
		 */
		init: function () {
			searchForm = document.forms['headerSearch'];
			searchField = searchForm.elements['q'];
			goButton = document.getElementById('searchButton');
			searchContainer = getFirstElementByClassName('div', 'siteSearch');
			defaultInputValue = searchField.value;
			searchForm.onsubmit = function (e) {
				headerSearch.removeMessaging();	
				return headerSearch.validateSearch(e,searchField.value);
			};			
		},
		/*
	     * display messaging on submit
	     * 
	     * What it does:
	     * inserts passed message string into HTML code and then inserts into document
	     * 
	     */
	    displayMessaging: function (messageString, messageStatus) {
	      	var html = '<div class="messaging ' + messageStatus + '">' + messageString + '</div>';
	      	var messageDiv = document.createElement("div");
	      	messageDiv.className = "messaging " + messageStatus;
	      	messageDiv.innerHTML = messageString;
	      	goButton.parentNode.insertBefore(messageDiv, goButton.nextSibling);
	      	searchContainer.style.height = (searchContainer.offsetHeight + 6) + 'px';
	    },  			
		/*
		 * perform search
		 * 
		 * What it does:
		 * makes sure there is a search value and that it doesn't match the default input text. 
		 * if checks fail, displays error messaging and prevent the form submit.
		 * 
		 */
		validateSearch: function (e,searchValue) {
			
			var theEvent = window.event || e;
			if (!searchValue || searchValue === defaultInputValue) {
				headerSearch.displayMessaging(messaging.invalidSearchTerm,'failure');
				
				if(theEvent.preventDefault){
					theEvent.preventDefault();
					return true;
				} else {
					return false;
				}
				
			}
			return true;
			
		},
		/*
	     * remove messaging 
	     * 
	     * What it does:
	     * removes inserted messaging and resizes search box to default height
	     * 
	     */
	    removeMessaging: function () {
			var messagingDiv = getFirstElementByClassName('div', 'messaging');
			if(messagingDiv != null){
				messagingDiv.parentNode.removeChild(messagingDiv);
				searchContainer.style.height = parseInt(searchContainer.style.height.slice(0,-2)) - 6 + 'px';
			}
		}			
	};	
}();

addLoadEvent(addFieldOnOffEvent);
addLoadEvent(headerSearch.init);