//Allow you to add multiple events to the onload event handler
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 - 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;
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( hasClass(els[i], searchClass) ) {
			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;
}

//Makes creating arrays easier and shorter
function makeArray() {
     for (i = 0; i<makeArray.arguments.length; i++)
          this[i + 1] = makeArray.arguments[i];
}

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;
}

//END GENERAL FUNCTIONS

//Makes link elements with class 'popup' open in a new browser window
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"));
		return false;
	  }
	}
  }
}
addLoadEvent(doPopups);

//Brings associated form field into focus when the text within a label is clicked (and makes the field blank)
function focusLabels() {
	if (!document.getElementsByTagName) return false;
	var labels = document.getElementsByTagName("label");
	for (var i=0; i<labels.length; i++) {
		if (!labels[i].getAttribute("for")) continue;
		labels[i].onclick = function() {
			var id = this.getAttribute("for");
			if (!document.getElementById(id)) return false;
			var element = document.getElementById(id);
			element.focus();
		}
	}
}
addLoadEvent(focusLabels);

//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" || element.type == "checkbox" || element.type == "radio") 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;
	}
}

//Adds form checking to email submission forms - places error msg in a div with id="formError"
//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("formError")){;
     if (status == true) { //only highlight this error if all other errors resolved first
      replaceText("formError","p","class","errmsg","An invalid email address was given.  Please re-enter your email address.");
						var errBox = document.getElementById("formError");
					 errBox.style.display = "block";
						addClass(errBox, "error");
					 addClass(errBox, "box");
      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("formError")){
     replaceText("formError","p","class","errmsg","Sorry. Fields marked with an asterisk are required.  Please complete these.");
					var errBox = document.getElementById("formError");
					errBox.style.display = "block";
					addClass(errBox, "error");
					addClass(errBox, "box");
     var elmtID = ""+element.id+"";
     var elmt = document.getElementById(elmtID);
     addClass(elmt,"error");
     status = false;
    }
    else {
     alert("You have not filled in the required fields.");
     return false;
    }
   }
  }
 }
 return status;
}

//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);
		thisform.onsubmit = function() {
			return validateForm(this);
		}
	}
}
addLoadEvent(prepareForms);



/* automatically prepend graphics to relevant links */

/* Grabs all non-image links from the page and calls checkLinks() */
function linkPreview(){
	var links = document.getElementsByTagName("a");

	for (i=0; i<links.length; i++){
		var currentLink = links[i];
		var	images = currentLink.getElementsByTagName("img");
		
	 	// Check if the link is an image. We don't want icons next to images.
		if (images.length == 0){
			var linkHref = currentLink.href;
			checkLinks(linkHref, currentLink)
		}
	}
}

/* Checks if the link goes to an external file (ie. .doc, .pdf) or to an external url and calls append(). Also automatically opens external links in new window Parameters: 	The href of the link | the <a> object */
function checkLinks(linkHref, currentLink){
	
	var linkHrefParts = linkHref.split(".");
	// extension is the last element in the LinkSplit array
	var extension = linkHrefParts[linkHrefParts.length - 1];
	// In some browsers there is a "/" placed after the link. removes the "/"
	extension = extension.replace("/","");
	
	if( extension in { doc:1, pdf:1, ppt:1, txt:1, xls:1, zip:1 } ){
		append(currentLink, extension );
	}
	
	if (linkHref.substr(0,7) != 'mailto:') {
	 if (linkHref.substr(0,13) != location.href.substring(0,13)) {
		  append(currentLink, 'ext' );
	   currentLink.onclick = function() {
		    window.open(this.getAttribute("href"));
		    return false;
		  }
	  }
	}
}

/* Creates a span after the object passed in and sets the class to the link type. Parameters: 	<a> object | external link type */
function append(currentLink, extension){
	var span = document.createElement('span');
	span.innerHTML = "&nbsp;";
	currentLink.parentNode.insertBefore(span,currentLink);
	span.className = extension;
}
addLoadEvent(linkPreview);

/*init jquery image rotator for homepage */

function initRotator() {
  $('.logos1').cycle({
  fx:    'fade',
  speed:  3000,
		random: 1,
		delay: -25000,
		timeout: 25000
  });
		
		$('.logos2').cycle({
  fx:    'fade',
  speed:  3000,
		random: 1,
		delay: -20000,
		timeout: 25000
  });
				
		$('.logos3').cycle({
  fx:    'fade',
  speed:  3000,
		random: 1,
		delay: -15000,
		timeout: 25000
  });
				
		$('.logos4').cycle({
  fx:    'fade',
  speed:  3000,
		random: 1,
		delay: -10000,
		timeout: 25000
  });
				
		$('.logos5').cycle({
  fx:    'fade',
  speed:  3000,
		random: 1,
		delay: -5000,
		timeout: 25000
  });	
}
addLoadEvent(initRotator);