function logInConsole(note) {
    if (window.console && window.console.firebug) {
        console.log(note);
    }
}


Event.observe(window, 'load',
    function() { init() }
    );


function init() {
    // Focus to the email field when it is on the page
    if (document.forms.login) {
        if (document.forms.login.username) {
            document.forms.login.username.focus();
            document.forms.login.username.select();
            }
        }
    }

// This is used with any page that wants to add / remove elements within its HTML
var sitewideJSCounter = {};

function addRemoveGeneralSections_Add(sectionNode,counterID,RenameFields,CopyFieldValues) {

    var LastElementPosition = $$("."+sectionNode).length-1;
    var LastNode = $$("."+sectionNode)[LastElementPosition];
    var origNode = $$("."+sectionNode)[0];
    var clone = $(origNode.cloneNode(true));
    
    // deal with duplicate IDs
    var namePair = clone.id.split(/\_\_/);
    
    sitewideJSCounter[counterID]++;
    
    clone.id = namePair[0]+"__"+sitewideJSCounter[counterID];
    clearAndRenameFields(clone, sitewideJSCounter[counterID],RenameFields,CopyFieldValues);
    
    origNode.parentNode.insertBefore(clone, LastNode.nextSibling);
    
    $(clone.id).appear();
    //new Effect.SlideDown(id);
    new Effect.Highlight(clone.id, { startcolor: '#FF6969', endcolor: '#f0f0f0' });
    
    }


//function addRemoveGeneralSections_Remove(sectionNode,node,counterID) {
function addRemoveGeneralSections_Remove(linkNode,toBeRemovedID,counterID,subtractOneOrNot,Message) {
    
    if (confirm(Message)) {
        
        //alert(linkNode.id + " / " + toBeRemovedID);
        Effect.Squish(toBeRemovedID);
        setTimeout(function() { $(toBeRemovedID).remove(); }, 2000)
        
        if (subtractOneOrNot == "Y") {
            sitewideJSCounter[counterID]--;
            }
        }
    
    }




var allowTheWorkingCount;
var allowTheWorkingLoop;
function rebuildProcessing(node,text,count) {

    if (allowTheWorkingLoop) {
        var justDots = "";
             if (count == 1 ) { justDots = "."; count++; }
        else if (count == 2 ) { justDots = ". ."; count++; }
        else if (count == 3 ) { justDots = ". . ."; count++; }
        else if (count == 4 ) { justDots = ". . . ."; count++; }
        else if (count == 5 ) { justDots = ". . . . ."; count++; }
        else { justDots = ""; count = 1; }
    
        $(node).innerHTML = text+justDots;
        setTimeout(function(){rebuildProcessing(node,text,count);},300);
        }
    
    }
function rebuildProcessingKill(messageContainer,message) {
    setAllWrkLoop(0);
    $(messageContainer).innerHTML = message;
    new Effect.Highlight(messageContainer, { startcolor: '#FF6969', endcolor: '#f0f0f0' });
    }
function setAllWrkLoop(TrueOrFalse) {
    allowTheWorkingLoop = TrueOrFalse;
    }




//function addRemoveGeneralSections_Remove(sectionNode,node,counterID) {
function addRemoveContentSections_Remove(linkNode,counterID,subtractOneOrNot,Message) {
    
    if (confirm(Message)) {
        
        var toBeRemovedID = linkNode.id;
        //alert(linkNode.id + " / " + toBeRemovedID);
        toBeRemovedID = toBeRemovedID.replace(/content_Content_remove__/, "content_Content_Section__");
        //alert(linkNode.id + " / " + toBeRemovedID);
        
        Effect.Squish(toBeRemovedID);
        setTimeout(function() { $(toBeRemovedID).remove(); }, 2000)
        
        if (subtractOneOrNot == "Y") {
            sitewideJSCounter[counterID]--;
            }
        }
    
    }

function addRemoveContactSections_Remove(sectionNode,node,counterID) {
    //contact_section_link_a__15
    //contact_section_div_a__15
    
    if ($$("."+sectionNode).length == 1) {
        addRemoveGeneralSections_Add(sectionNode,counterID,"Y","N")
        }
    
    var nameAndNum = node.id.split(/\_\_/);
    var nameAndLet = nameAndNum[0].split(/\_/);
    
    var parentLink = "contact_section_div_"+nameAndLet[nameAndLet.length-1]+"__"+nameAndNum[1];
    
    $(parentLink).remove();
    }

function addRemoveAnySections_Remove(sectionNode,node,counterID,wrapperName) {
    //contact_section_link_a__15
    //contact_section_div_a__15
    
    if ($$("."+sectionNode).length == 1) {
        addRemoveGeneralSections_Add(sectionNode,counterID,"Y","N")
        }
    
    var nameAndNum = node.id.split(/\_\_/);
    var nameAndLet = nameAndNum[0].split(/\_/);
    
    //var parentLink = "contact_section_div_"+nameAndLet[nameAndLet.length-1]+"__"+nameAndNum[1];
    var parentLink = wrapperName+nameAndLet[nameAndLet.length-1]+"__"+nameAndNum[1];
    
    $(parentLink).remove();
    }

function sitewadeCounterEquals(counterID,val) {
    if (typeof val != "undefined") {
        sitewideJSCounter[counterID] = val;
        }
    else {
        if (typeof sitewideJSCounter[counterID] == "undefined") {
            sitewideJSCounter[counterID] = 0;
            }
        return sitewideJSCounter[counterID];
        }
    }


function copyValueToField(dataToCopy,copyToThisNode_ID) {

    $(copyToThisNode_ID).value = dataToCopy;
    
    }


//This is used around the site to toggle the Help links / sections on and off
function toggleHelp(helpNode) {
    
    var nameAndNum = helpNode.id.split(/\_\_/);
    
    if (sitewadeCounterEquals("helpID__"+nameAndNum[1]) == 0) {
        new Effect.Grow("helpID__"+nameAndNum[1], { direction: 'top-left', duration: .3 });
        
        setTimeout(function() {
            new Effect.Highlight("helpID__"+nameAndNum[1], { startcolor: '#FF6969', endcolor: '#f0f0f0' });
            }, 400);
        
        //sitewadeCounterEquals("helpID__"+nameAndNum[1],1);
        toggleHelpCounter(nameAndNum[1],1);
        }
    else {
        //Effect.Squish("helpID__"+nameAndNum[1]);
        Effect.BlindUp("helpID__"+nameAndNum[1], { duration: .3 } );
        
        //sitewadeCounterEquals("helpID__"+nameAndNum[1],0);
        toggleHelpCounter(nameAndNum[1],0);
        }
    
    }

function toggleHelpCounter(ID,OnOrOff) {
    sitewadeCounterEquals("helpID__"+ID,OnOrOff);
    }





// Browser Detection
var isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
var NS4 = (document.layers) ? true : false;
var IEmac = ((document.all)&&(isMac)) ? true : false;
var IE4plus = (document.all) ? true : false;
var IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
var IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
var ver4 = (NS4 || IE4plus) ? true : false;
var NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;


// Body onload utility (supports multiple onload functions)
var gSafeOnload = new Array();
// SafeAddOnload(functionNameWithoutPassedValues);
function SafeAddOnload(f) {
    if (IEmac && IE4) {  // IE 4.5 blows out on testing window.onload
        window.onload = SafeOnload;
        gSafeOnload[gSafeOnload.length] = f;
        }
    else if  (window.onload) {
        if (window.onload != SafeOnload) {
            gSafeOnload[0] = window.onload;
            window.onload = SafeOnload;
            }
        gSafeOnload[gSafeOnload.length] = f;
        }
    else
        window.onload = f;
    }
function SafeOnload() {
    for (var i=0;i<gSafeOnload.length;i++)
        gSafeOnload[i]();
    }





// include a file from js scripts dir
var web_root="";
//        include_dom('forms.js');
function include_dom (script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    //js.setAttribute('src', web_root + '/js/' + script_filename);
    js.setAttribute('src', web_root + '' + script_filename);
    html_doc.appendChild(js);
    return false;
}




function my_toggle(id) {
    if (document.getElementById) {
        with (document.getElementById(id).style) {
            if (display == "none") {
                display = "block";
            }else if(display == "block") {
                display = "none";
            }else if (display == "") {
                display = "block";
            }
        }
    }
}


function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=300,height=150,left=200,top=200');");
    }



//** Tab Content script- � Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
//** Last updated: Nov 8th, 06

var enabletabpersistence=0 //enable tab persistence via session only cookies, so selected tab is remembered?

////NO NEED TO EDIT BELOW////////////////////////
var tabbedContentWrapperIDs=new Object()

function expandcontent(linkobj){
    var ulid=linkobj.parentNode.parentNode.id //id of UL element
    var ullist=document.getElementById(ulid).getElementsByTagName("li") //get list of LIs corresponding to the tab contents
    for (var i=0; i<ullist.length; i++){
        ullist[i].className=""  //deselect all tabs
        if (typeof tabbedContentWrapperIDs[ulid][i]!="undefined") //if tab content within this array index exists (exception: More tabs than there are tab contents)
            document.getElementById(tabbedContentWrapperIDs[ulid][i]).style.display="none" //hide all tab contents
        }
    linkobj.parentNode.className="selected"  //highlight currently clicked on tab
    document.getElementById(linkobj.getAttribute("rel")).style.display="block" //expand corresponding tab content
    saveselectedtabbedContentWrapperid(ulid, linkobj.getAttribute("rel"))
    }

function expandtab(tabbedContentWrapperid, tabnumber){ //interface for selecting a tab (plus expand corresponding content)
    var thetab=document.getElementById(tabbedContentWrapperid).getElementsByTagName("a")[tabnumber]
    if (thetab.getAttribute("rel"))
        expandcontent(thetab)
    }

function savetabbedContentWrapperids(ulid, relattribute){// save ids of tab content divs
    if (typeof tabbedContentWrapperIDs[ulid]=="undefined") //if this array doesn't exist yet
        tabbedContentWrapperIDs[ulid]=new Array()
    tabbedContentWrapperIDs[ulid][tabbedContentWrapperIDs[ulid].length]=relattribute
    }

function saveselectedtabbedContentWrapperid(ulid, selectedtabid){ //set id of clicked on tab as selected tab id & enter into cookie
    if (enabletabpersistence==1) //if persistence feature turned on
        setCookie(ulid, selectedtabid)
    }

function getullistlinkbyId(ulid, tabbedContentWrapperid){ //returns a tab link based on the ID of the associated tab content
    var ullist=document.getElementById(ulid).getElementsByTagName("li")
    for (var i=0; i<ullist.length; i++){
        if (ullist[i].getElementsByTagName("a")[0].getAttribute("rel")==tabbedContentWrapperid){
            return ullist[i].getElementsByTagName("a")[0]
            break
            }
        }
    }

function initializetabbedContentWrapper(){
    for (var i=0; i<arguments.length; i++){ //loop through passed UL ids
        if (enabletabpersistence==0 && getCookie(arguments[i])!="") //clean up cookie if persist=off
            setCookie(arguments[i], "")
        var clickedontab=getCookie(arguments[i]) //retrieve ID of last clicked on tab from cookie, if any
        var ulobj=document.getElementById(arguments[i])
        var ulist=ulobj.getElementsByTagName("li") //array containing the LI elements within UL
        for (var x=0; x<ulist.length; x++){ //loop through each LI element
            var ulistlink=ulist[x].getElementsByTagName("a")[0]
            if (ulistlink.getAttribute("rel")){
                savetabbedContentWrapperids(arguments[i], ulistlink.getAttribute("rel")) //save id of each tab content as loop runs
                ulistlink.onclick=function(){
                expandcontent(this)
                return false
                }
            if (ulist[x].className=="selected" && clickedontab=="") //if a tab is set to be selected by default
                expandcontent(ulistlink) //auto load currenly selected tab content
                }
            } //end inner for loop
        if (clickedontab!=""){ //if a tab has been previously clicked on per the cookie value
            var culistlink=getullistlinkbyId(arguments[i], clickedontab)
            if (typeof culistlink!="undefined") //if match found between tabbedContentWrapper id and rel attribute value
                expandcontent(culistlink) //auto load currenly selected tab content
            else //else if no match found between tabbedContentWrapper id and rel attribute value (cookie mis-association)
                expandcontent(ulist[0].getElementsByTagName("a")[0]) //just auto load first tab instead
            }
        } //end outer for loop
    }

function getCookie(Name){ 
    var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
    if (document.cookie.match(re)) //if cookie found
    return document.cookie.match(re)[0].split("=")[1] //return its value
    return ""
    }

function setCookie(name, value){
    document.cookie = name+"="+value //cookie value is domain wide (path=/)
    }

















/////// TOOL TIPS

/*
  Simple Tooltip Loader
  by Jeremy Newman <jnewman@codeweavers.com>
 */

// global for the tool tip object
var tooltipObj = false;

// create a new tool tip
function new_tooltip (parent, text) {

    if (tooltipObj && tooltipObj.id != "tooltipObj")
        tooltipObj = document.getElementById("tooltipObj");

    if (!tooltipObj) {
        tooltipObj = document.createElement('DIV');
        tooltipObj.style.position = 'absolute';
        tooltipObj.id = 'tooltipObj';
        tooltipObj.className='tooltip';
        document.body.appendChild(tooltipObj);
    }
    
    tooltipObj.innerHTML = text;

    var leftPos = (tooltip_getLeftPos(parent) + 5);
    var topPos = (tooltip_getTopPos(parent) + parent.offsetHeight + 2);
    
    tooltipObj.style.left = leftPos + 'px';
    tooltipObj.style.top = topPos + 'px';

    tooltipObj.style.display = "block";

    return false;
}

// use an existing tool tip
function open_tooltip (parent, el) {

    tooltipObj = document.getElementById(el);
    tooltipObj.className='tooltip';

    var leftPos = (tooltip_getLeftPos(parent) + 5);
    var topPos = (tooltip_getTopPos(parent) + parent.offsetHeight + 2);
    
    tooltipObj.style.left = leftPos + 'px';
    tooltipObj.style.top = topPos + 'px';

    tooltipObj.style.display = "block";

    return false;
}

// load ajax content into tooltip
function ajax_tooltip (parent, externalFile) {

    if (tooltipObj && tooltipObj.id != "tooltipObj")
        tooltipObj = document.getElementById("tooltipObj");

    if (!tooltipObj) {
        tooltipObj = document.createElement('DIV');
        tooltipObj.style.position = 'absolute';
        tooltipObj.id = 'tooltipObj';
        tooltipObj.className='tooltip';
        document.body.appendChild(tooltipObj);
    }
    
    ajax_loadContent("tooltipObj", externalFile);

    var leftPos = (tooltip_getLeftPos(parent) + 5);
    var topPos = (tooltip_getTopPos(parent) + parent.offsetHeight + 2);
    
    tooltipObj.style.left = leftPos + 'px';
    tooltipObj.style.top = topPos + 'px';

    tooltipObj.style.display = "block";

    return false;
}

// get top position of element
function tooltip_getTopPos(inputObj)
{
    var returnValue = inputObj.offsetTop;
    while ((inputObj = inputObj.offsetParent) != null) {
        if(inputObj.tagName != 'HTML')
            returnValue += inputObj.offsetTop;
    }
    return returnValue;
}

// get left position of element
function tooltip_getLeftPos(inputObj)
{
    var returnValue = inputObj.offsetLeft;
    while((inputObj = inputObj.offsetParent) != null) {
        if (inputObj.tagName!='HTML')
            returnValue += inputObj.offsetLeft;
    }
    return returnValue;
}

// close the tooltip
function close_tooltip () {
    if (tooltipObj)
        tooltipObj.style.display = "none";
}







var dontDeleteValueClass = 'neverDeleteValue';

function clearAndRenameFields ( node, counter, RenameFields, CopyFieldValues ) {
    
    var elements = node.getElementsByTagName('a');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "a");

    var elements = node.getElementsByTagName('div');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "div");

    var elements = node.getElementsByTagName('span');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "span");

    var elements = node.getElementsByTagName('hidden');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "");
    
    var elements = node.getElementsByTagName('input');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "");

    var elements = node.getElementsByTagName('radio');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "");

    var elements = node.getElementsByTagName('textarea');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "");

    var elements = node.getElementsByTagName('select');
    renameFields(elements, counter, RenameFields, CopyFieldValues, "");
    
    // We don't care about TRs and TDs
    //var elements = node.getElementsByTagName('td');
    //renameFields(elements, counter, RenameFields, CopyFieldValues, "td");
    //var elements = node.getElementsByTagName('tr');
    //renameFields(elements, counter, RenameFields, CopyFieldValues, "tr");

    return node;
}

function renameFields (elements, counter, RenameFields, CopyFieldValues, Type) {
    
    //alert(counter)

    // elements            = Array of all the elements of that type that were found
    // counter            = Lets the script know what number to append to the new fields
    // RenameFields        = This is set in clearAndRenameFields
    // CopyFieldValues    = This is set in clearAndRenameFields
    // Type                = Different types (like div or select) may be handled differently.

    if (Type == "div" || Type == "span") {
        for (var i = 0; i < elements.length; i++){
            var curID = elements[i].id;
            if (curID.match(/\w\_\_\d/)) {
            var pair = curID.split(/\_\_/);
            var newName = pair[0] + '__' + counter;
            elements[i].name = newName;
            elements[i].id = newName;
            elements[i].className = elements[i].className.replace(/elementError/, "");
            }
        }    
    } else if (Type == "tr" || Type == "td") { /*Do Nothing*/
    } else {
        for (var i = 0; i < elements.length; i++){
            var compareName = "";
            var curName = elements[i].name;
            var curID = elements[i].name;
            if (curName.length == 0 && curID.length == 0) {
                // we don't have anything to rename, so compareName remains empty
                }
            else if (curName.length == 0 && curID.length > 0) {
                compareName = curID;
                }
            else {
                compareName = curName;
                }
            if (compareName.match(/\w\_\_\d/)) {
                var pair = compareName.split(/\_\_/);
                var newName = pair[0] + '__' + counter;
            } else {
                var newName = compareName + '__';
                newName = newName.replace(/____$/g,'__');
                newName = newName + counter;
                }
            
            if (RenameFields != "N") {
                elements[i].name = newName;
                elements[i].id = newName;
                }

            elements[i].className = elements[i].className.replace(/elementError/, "");
            if (elements[i].className.match(dontDeleteValueClass)) {
                // Skip
                }
            else {
                if (CopyFieldValues == "N" && elements[i].type != "button") {
                    elements[i].value = "";
                    }
                }
            //elements[i].value = newName; // used in debugging. It pushes the new name into the value of the field
        }
    }
}



function selectFirstFormFieldWithinContainer(containerNodeID,actuallyFocusFlag) {
    var containerNode = $(containerNodeID);
    logInConsole("selectFirstFormFieldWithinContainer called");
    if (actuallyFocusFlag) {
        if ($(containerNode).getElementsByTagName('input')[0]) {
            $(containerNode).getElementsByTagName('input')[0].focus();
        }
    }
    
}


// This will selectFirstFormFieldWithinContainer, but
//  with a short delay first.
var SendActuallyFocusFlag = 1;
function delay_SelectFirstFormFieldWithinContainer(containerNode) {
    setTimeout(function() { if (SendActuallyFocusFlag) selectFirstFormFieldWithinContainer(containerNode,SendActuallyFocusFlag); SendActuallyFocusFlag = 0; }, 200);
    setTimeout(function() { SendActuallyFocusFlag = 1; }, 500);
}


