/* GENERIC */

//Allow you to add multiple events to the onload event handler - props to simon willison
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

//get elements by class name - props to dustin diaz
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

//Determine if a class is present on a target element
function hasClass(target, classValue) {
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
    
	if (target.className.match(pattern)) {
    	return true;
    } 
    
	return false;
}

//Remove a class from a target element
function removeClass(target, classValue) {
    var removedClass = target.className;
    var pattern = new RegExp("(^| )" + classValue + "( |$)");
	
    removedClass = removedClass.replace(pattern, "$1");
    removedClass = removedClass.replace(/ $/, "");
    target.className = removedClass;

    return true;
}

//Add a class to a target element
function addClass(target, classValue) {
    if (!hasClass(target, classValue)) {
        if (target.className == "") {
            target.className = classValue;
        }
        else {
            target.className += " " + classValue;
        }
    }
    return true;
}

/*SPECIFIC SITE */

/*Makes secondary popup nav work in IE*/
function sfHover() {
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	if(itsAllGood){
		var sfEls = document.getElementById("nav1").getElementsByTagName("li");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}
addLoadEvent(sfHover);

//Makes link elements with class 'popup' open in a new browser window of fixed spec
function doPopups() {
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  for (var i=0; i < links.length; i++) {
	if (links[i].className.match("popup")) {
	  links[i].onclick = function() {
		window.open(this.getAttribute("href"), '_blank', 'resizable=1,location=0,statusbar=0,menubar=0,toolbar=0,directories=0,status=0,scrollbars=1,width=770,height=468');
		return false;
	  }
	  
	}
  }
}
addLoadEvent(doPopups);

/*Makes bg PN Opacity work in IE*/
var bgsleight = function() {
  function fnLoadPngs() {
    var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
    var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
    for (var i = document.all.length - 1, obj = null; (obj = document.all[i]); i--) {
      if (itsAllGood && obj.currentStyle.backgroundImage.match(/\.png/i) != null) {
        fnFixPng(obj);
        obj.attachEvent("onpropertychange", fnPropertyChanged);
      }
    }
  }

  function fnPropertyChanged() {
    if (window.event.propertyName == "style.backgroundImage") {
      var el = window.event.srcElement;
      if (!el.currentStyle.backgroundImage.match(/x\.gif/i)) {
        var bg = el.currentStyle.backgroundImage;
        var src = bg.substring(5,bg.length-2);
        el.filters.item(0).src = src;
        el.style.backgroundImage = "url(x.gif)";
      }
    }
  }

  function fnFixPng(obj) {
    var bg = obj.currentStyle.backgroundImage;
    var src = bg.substring(5,bg.length-2);
    obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
    obj.style.backgroundImage = "url(x.gif)";
  }

  return {
    init: function() {
      if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
        addLoadEvent(fnLoadPngs);
      }		
    }
  }
}();
bgsleight.init();

/*Form Enhancements*/

//Creates default placeholder text, which disappears and reappears automatically
function resetFields(whichform) {
	for (var i=0; i<whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if (element.type == "reset"||element.type == "submit") continue;
		if (!element.defaultValue) continue;
		element.onfocus = function() {
			if (this.value == this.defaultValue) {
				this.value = "";
			}
		}
		element.onblur = function() {
			if (this.value == "") {
				this.value = this.defaultValue;
			}
		}
	}
}



//Determines whether the input field has been completed, based on whether the default still exists
function isFilled(field) {
	if (field.value.length < 1 || field.value == field.defaultValue) {
		return false;
	} else {
		return true;
	}
}

//Determines whether the email field has been completed correctly, based on the existence of certain characters
function isEmail(field) {
	if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1)
	{
		return false;
	} else {
		return true;
	}
}

function replaceText(dest,element,att,value,text){
	/*LOCATE DESTINATION IN HTML*/
	var textDest = document.getElementById(dest);
	/*remove old text (if an existing child node already exists)*/ 
	if (textDest.childNodes[0]) {
		textDest.removeChild(textDest.childNodes[0]);
	}
	/*MAKE NEW HTML DATA*/
	var newelmt = document.createElement(element);
	var newtext = document.createTextNode(text);
	newelmt.appendChild(newtext);
	newelmt.setAttribute(att,value);
	/*OUTPUT NEW HTML DATA TO DETINATION*/
	textDest.appendChild(newelmt); //append
	return false;
}

//Adds form checking to email submission forms - places error msg in a div with id="formErr"
//Draws upon the previous two functions to validate all form fields, based on whether the class "required" or "email" is present
function validateForm(whichform) {
	var status = true;
	for (var i=0; i<whichform.elements.length; i++) {
		var element = whichform.elements[i];
		if (hasClass(element,"email")) {
			if (!isEmail(element)) {
				if (document.getElementById("formErr")){;
					if (status == true) { //only highlight this error if all other errors resolved first
						replaceText("formErr","p","class","errmsg","An invalid email address was given.  Please re-enter your email address.");
						var elmtID = ""+element.id+"";
						var elmt = document.getElementById(elmtID);
						addClass(elmt,"error");
					}
					
					status = false;
				}
				else {
					alert("Please enter a valid e-mail address.");
					return false;
				}
			}
		}
		if (hasClass(element,"required")) {	//or can use:  if(element.className.indexOf("required") != -1)
			if (!isFilled(element)) {
				if (document.getElementById("formErr")){
					replaceText("formErr","p","class","errmsg","Fields marked with an asterisk are required fields.  Please complete these fields.");
					var elmtID = ""+element.id+"";
					var elmt = document.getElementById(elmtID);
					addClass(elmt,"error");
					status = false;
				}
				else {
					alert("You have not filled in the required field '"+element.id+"'.");
					return false;
				}
			}
		}
	}
	return status;
}

//clears the error message boxes once focused on again.
function prepareClearErrors(whichform) {
  if (!document.getElementsByTagName) return false;
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i < inputs.length; i++) {
	if (inputs[i].className.match("required")) {
	  inputs[i].onblur = function() {
		if (isFilled(this)) {
			//alert ("test");
			removeClass(this,'error');
		}
		return false;
	  }
	}
  }
}

//The function to prepare the previous form enhancements for each form on a page
function prepareForms() {
	for (var i=0; i<document.forms.length; i++) {
		var thisform = document.forms[i];
		resetFields(thisform);
		prepareClearErrors(thisform);
		thisform.onsubmit = function() {
			return validateForm(this);
		}
	}
}
addLoadEvent(prepareForms);

//forces a low z-index on the specials board link for a few moments onload to let the specials sticker go past it
function lowZ() {
		
		if (document.getElementById("navspecial")){
				setTimeout('document.getElementById("navspecial").style.zIndex="100"',1500);
		}		
}

addLoadEvent(lowZ);


