/**
 * Helper function that trims whitespace from beginning and end of a string
 *
 * @author:  Matthew Rasnake  http://www.powercreative.com/
 * @param:   str              a string
 */
function trim(str) {
   return str.replace(/^\s*|\s*$/g,"");
}

function offsitePopup(url) {
    var offsitePopup = window.open(url, 'offSiteWindow',
         'width=1000,height=700,scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes,location=yes');
    if (typeof offsitePopup == 'object') {
        offsitePopup.focus();
    }
    return false;
}

widthReg  = /^w([0-9]+)$/;
heightReg = /^h([0-9]+)$/;
foundClass = "";

sfHover = function() {
	var sfEls = document.getElementById("NavBar").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"), "");
		}
	}
}


function globalOnLoad() {
	//suckerfish hover for IE6, etc
    //
	var IE6 = (document.all && document.getElementById)?true:false;
	if (IE6) { sfHover(); }


    // Assign link events
    anchors = document.getElementsByTagName("a");
    inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (FM.checkForClass(inputs[i],"eraseReplace")) {
            inputs[i].onfocus = function() {eraseReplace(this);}
            inputs[i].onblur = function() {eraseReplace(this);}
        }
    }
    for (var i = 0; i < anchors.length; i++) {
        /*
        if (FM.checkForClass(anchors[i],"ToggleMenu")) {
            FM.toggleClass(anchors[i],"ToggleMenu");
            anchors[i].onmouseover = function() { togglePopMenu(trim(this.className)); return false; }
        }
        */

        if (FM.checkForClass(anchors[i],"ImagePop"))  foundClass = "ImagePop";
        if (FM.checkForClass(anchors[i],"Popup"))     foundClass = "Popup";
        if (FM.checkForClass(anchors[i],"PDF")) {
            anchors[i].onclick = function() { PDFPopup(this.href); return false; }
        }
        if (FM.checkForClass(anchors[i],"Offsite")) {
            anchors[i].onclick = function() { offsitePopup(this.href); return false; }
        }
        if (FM.checkForClass(anchors[i],"Footnote")) {
            if (!anchors[i].href.indexOf("OpenFootnotes(")) {
                anchors[i].onclick = function() { CSSOpenFootnotes(this.href); return false; }
            }
        }
        if (FM.checkForClass(anchors[i],"Definition")) {
            anchors[i].onclick = function() { CSSDefinitionPopup(this.href); return false; }
        }
        if (FM.checkForClass(anchors[i],"EnlargePhoto")) {
            anchors[i].onclick = function() { EnlargePhoto(this.href.substr(this.href.lastIndexOf("/")+1)); return false; }
        }
        if (FM.checkForClass(anchors[i],"CloseButton")) {
            anchors[i].onclick = function() { self.close(); return false; }
        }
        if (FM.checkForClass(anchors[i],"PrintButton")) {
            anchors[i].onclick = function() { self.print(); return false; }
        }
        if (foundClass != "") {
            // width & height should be specified by class names that begin with a 'w' or an 'h'
            // popup class names should be, e.g.: class="Popup w400 h320"
            if (foundClass=="ImagePop") {
                anchors[i].onclick = function () { NewImagePopup(this); return false; };
            } else {
                anchors[i].onclick = function() { popupWindow(this); return false; };
            }
        }
        foundClass = "";
    }
    // Run page onLoad function, if it exists
    if (typeof onLoad != 'undefined') {
        onLoad();
    }
}

// Every page should execute the global onload function
window.onload = globalOnLoad;


/////////////////////////////
// Miscellaneous Functions //

var replace = new Array();
function eraseReplace(obj) {
    if (!replace[obj.name]) replace[obj.name] = obj.value;
    if (obj.value == replace[obj.name]) {
        obj.value = "";
    } else if (obj.value == "") {
        obj.value = replace[obj.name];
    }
}

// END Miscellaneous Functions //
/////////////////////////////////

////////////////////////////
// Popup Window Functions //

// A general-purpose popup window function
function popupWindow(trigger) {
    FM.toggleClass(trigger,"Popup");
    aClass = trigger.className.split(" ");
    width = 700;
    height = 550;
    for (var j = 0; j < aClass.length; j++) {
        if (aClass[j].search(widthReg) >= 0)  { width = aClass[j].substr(1); }
        if (aClass[j].search(heightReg) >= 0) { height = aClass[j].substr(1); }
    }
    var windowName = 'popup';
    if(arguments.length > 3) {
        windowName = arguments[3];
    }
    var popUp = window.open(trigger.href, windowName, 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes,menubar=no,toolbar=no');
    if (typeof popUp == 'object') { popUp.focus(); }
}

function PopAddImage(toWhat,ID) {
  popup("/admin/add-image.php?to="+toWhat+"&id="+ID,800,600,'foo');
}

/**
 * Displays the specified URL in a new window with all menus, tools, and scrollbars
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   url             URL to display in the popup window
 * @param   width           (Optional) The width of the new popup window
 * @param   height          (Optional) The height of the new popup window
 * @param   windowName      (Optional) The name of the window
 */
function popup(url, width, height, windowName)
{
    // Default to a 700 x 500 window
    width = (!isNaN(width) ? width + '' : '700');
    height = (!isNaN(height) ? height + '' : '500');
    windowName = (windowName == undefined || windowName == '' ? 'popup' : windowName);

    // Create it
    var popUp = window.open(url, windowName, 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes,location=yes');

    // Bring it to the front
    if (typeof popUp == 'object') { popUp.focus(); }

    return false;
}  // popup()

// END Popup Window Functions //
////////////////////////////////

////////////////////////////////
// Field Validation Functions //

// This function is used to make sure that required form fields have values.
//    Field_Name: name of a form field in the form of document.form_name.form_field_name that will be validated.
//    Error_Message: this is the alert error message that will be displayed to the user.
function Has_Value(Field_Name, Error_Message) {
	var text;

	text = Field_Name.value;

	while(text.search(/\s/) > -1) {
        text = text.replace(/\s/, "");
    }

    if(text == 0) {
        alert(Error_Message);
        Field_Name.focus();
        return false;
    }
    return true;
}

function validPostal(field) { //validates Zip Code
    popUpMsg = ((arguments[1]>"")&&(arguments[1]!="undefined"))?arguments[1]:"";
    reFull =/^[0-9]{5}-[0-9]{4}/;                                                         //regular expression matching US Zip+4
    reZip =/^[0-9]{5}$/;                                                                  //regular expression matching US Zip
    reCan =/^[abceghj-np-tvxyABCEGHJ-NPRSTVXY]\d[abceghj-nprstvwxyzABCEGHJ-NPRSTVWXYZ]( )?\d[abceghj-nprstvwxyzABCEGHJ-NPRSTVWXYZ]\d$/    //regular expression matching Canadian Postal Code
    if ((field.value.search(reFull) == -1)&& (field.value.search(reZip) == -1) && (field.value.search(reCan) == -1)) cleaned = false;
    else cleaned = true;
    if(!cleaned) {
        field.onchange = function () { validPostal(field,popUpMsg) };                            //set field to recall this fn onChange
        showMsg("Please enter a valid US or Canadian postal code.",field,popUpMsg);              //show user the Error
        retVal = retVal && cleaned;
    } else {
        noError(field,popUpMsg);                                                                 //unset Error indicators
        retVal = true;
    }
    return retVal;
}

function validEmail(field) {                                                                //validates Email
    popUpMsg = ((arguments[1]>"")&&(arguments[1]!="undefined"))?arguments[1]:"";
    //re =/^\w+((-\w+)|(\.\w+)|(\+\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9][A-Za-z0-9]+$/;
    re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(field.value.search(re) == -1) {                                                      //if not valid
        field.onchange = function () { validEmail(field,popUpMsg) };                        //set field to recall this fn onChange
        showMsg("Please enter a valid email address.",field,popUpMsg);                      //show user the Error
        retVal = false;
    } else {
        retVal = true;
        noError(field,popUpMsg);                                                            //unset Error indicators
    }
    return retVal;
}

function hasValue(field,fDesc) {
    popUpMsg = ((arguments[2]>"")&&(arguments[2]!="undefined"))?arguments[2]:"";
    if (field.value>"") {
        noError(field,popUpMsg);                                                                 //unset Error indicators
    } else {
        field.onchange = function () { hasValue(field,fDesc,popUpMsg) };                         //set field to recall this fn onChange
        showMsg("Please enter a "+fDesc+".",field,popUpMsg);                                     //show user the Error
        retVal = false;
    }
    return retVal;
}

function showMsg(msg,field) {                                                             //shows user form Error
  popUpMsg = ((arguments[2]>"")&&(arguments[2]!="undefined"))?arguments[2]:"";
  if ((!field.oBGC)&&(field.style.backgroundColor!="pink")) field.oBGC = field.style.backgroundColor;  //save field bG color
  field.style.backgroundColor = "pink";                                                   //set field Error bG color
  if (popUpMsg) {
    alert(msg);                                                                           //alert message text
  } else {
    errSpan = eval("document.getElementById('"+field.name+"_error')");
    errSpan.innerHTML = "<br/>"+msg;
  }
  field.focus();                                                                          //put focus on offending field
  return;
}

function noError(field,popUpMsg) {                                                        //unset Error indicators
  if (field.style.backgroundColor == "pink") field.style.backgroundColor = field.oBGC;    //reset field bG color
  if (!popUpMsg) {
    errSpan = eval("document.getElementById('"+field.name+"_error')");                    //get error Span
    errSpan.innerHTML = ""                                                                //empty it
  }
}

// END Field Validation Functions //
////////////////////////////////////


///////////////////////////////
// Dan's FluidMind functions //

// Make sure the "FM" namespace object exists
if (typeof FM != 'object') {
    FM = new Object();
}

/**
 * Checks a given class attribute for the presence of a given class
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     The name of the CSS class to check for
 */
FM.checkForClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }
    if (element.className == '') {
        return false;
    } else {
        return new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }
}


/**
 * Adds a class to an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to add the class to
 * @param   nameOfClass     Class name to add
 * @see     checkForClass
 */
FM.addClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (!FM.checkForClass(element, nameOfClass)) {
        element.className += (element.className ? ' ' : '') + nameOfClass;
        return true;
    } else {
        return false;
    }
}


/**
 * Removes a class from an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     Class name to remove
 * @see     checkForClass
 */
FM.removeClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        element.className = element.className.replace(
            (element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),
            '');
        return true;
    } else {
        return false;
    }
}


/**
 * Replaces a class with another if the class is present
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   class1          Class name to replace
 * @param   class2          Class name to replace it with
 * @see     checkForClass
 * @see     addClass
 * @see     removeClass
 */
FM.replaceClass = function(element, class1, class2) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, class1)) {
        FM.removeClass(element, class1);
        FM.addClass(element, class2);
        return true;
    } else {
        return false;
    }
}


/**
 * Toggles the specified class on and off
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to toggle the class of
 * @param   nameOfClass     Class name to toggle
 * @see     checkForclass
 * @see     addClass
 * @see     removeClass
 */
FM.toggleClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        FM.removeClass(element, nameOfClass);
    } else {
        FM.addClass(element, nameOfClass);
    }

    return true;
}
// Dan's FluidMind functions //
///////////////////////////////
