// ADD IMAGE SWAP -------------------------------------------------
// adds a JS mouse over swap to all image inputs and image links
// in the document with '_off' or '_on' as the last bit of the
// filename before the extension
function AddSwap() {
//    declare variables
    var    inputs,
        hyperlinks,
        numElements,
        childImages,
        numImages,
        i,
        j;
//    test for DOM Methods and get all input elements
    if(    (typeof document.getElementById != 'undefined') &&
        (typeof document.getElementsByTagName != 'undefined') &&
        (inputs = document.getElementsByTagName('input')) &&
        (hyperlinks = document.getElementsByTagName('a'))
        ) {
//        loop through the inputs
        numElements = inputs.length;
        for (i = 0; i < numElements; i++) {
//            find the ones that are of type 'image'
            if (inputs[i].type.toLowerCase() == 'image') {
//                pass image inputs to the function that adds the swap
                this.makeSwap(inputs[i]);
            }
        }
//        loop through the anchors
        numElements = hyperlinks.length;
        for (i = 0; i < numElements; i++) {
//            find the ones that have image children
            childImages = hyperlinks[i].getElementsByTagName('img');
            numImages = childImages.length;
            if (numImages > 0) {
//                pass the images to the function that adds the swap
                for (j = 0; j < numImages; j++) {
                    this.makeSwap(childImages[j]);
                }
            }
        }
        addUnloadHandler(this.cleanUp);
        return true;
    }
    return false;
}
AddSwap.prototype.makeSwap = function (el) {
    if ((typeof el.src == 'string') && (el.src.indexOf('_off.') != -1)) {
//        if the image name contains 'off' set the src of off state img to the current
//        src and swap the 'off' with 'on' to get the src for the on state
        el.offImg = new Image();
        el.offImg.src = el.src;
        el.onImg = new Image();
        el.onImg.src = el.src.replace(/_off\./,'_on.');
    } else if ((typeof el.src == 'string') && (el.src.indexOf('_on.') != -1)) {
//        otherwise, if the image name contains 'on' set the src of on state img to the
//        current src and swap the 'on' with 'ooff' to get the src for the on state
        el.offImg = new Image();
        el.offImg.src = el.src;
        el.onImg = new Image();
        el.onImg.src = el.src.replace(/_on\./,'_off.');
//    if neither of the state slugs is present, return false
    } else return false;
//    add mouseover and mouseout functions
    el.onmouseover = function() { this.src = this.onImg.src; return true; }
    el.onmouseout = function() { this.src = this.offImg.src; return true; }
    return true
}
AddSwap.prototype.cleanUp = function () {
    var    inputs = document.getElementsByTagName('input'),
        hyperlinks = document.getElementsByTagName('a'),
        numElements = inputs.length,
        childImages,
        numImages,
        i,
        j;
//    loop through the inputs
    for (i = 0; i < numElements; i++) {
//        find the ones that are of type 'image'
        if (inputs[i].type.toLowerCase() == 'image') {
//            remove handlers & expandos
            inputs[i].offImg = null;
            inputs[i].onImg = null;
            inputs[i].onmouseover = null;
            inputs[i].onmouseout = null;
        }
    }
//    loop through the anchors
    numElements = hyperlinks.length;
    for (i = 0; i < numElements; i++) {
//        find the ones that have image children
        childImages = hyperlinks[i].getElementsByTagName('img');
        numImages = childImages.length;
        if (numImages > 0) {
//            pass the images to the function that adds the swap
            for (j = 0; j < numImages; j++) {
                childImages[j].offImg = null;
                childImages[j].onImg = null;
                childImages[j].onmouseover = null;
                childImages[j].onmouseout = null;
            }
        }
    }
    return true;
}
addLoadHandler(function() { return new AddSwap();});


// UTILITIES ======================================================


function attachEventListener(target, eventType, functionRef, capture) {
    if (typeof target.addEventListener != "undefined") {
        target.addEventListener(eventType, functionRef, capture);
    } else if (typeof target.attachEvent != "undefined") {
        target.attachEvent("on" + eventType, functionRef);
    } else {
        eventType = "on" + eventType;
        if (typeof target[eventType] == "function") {
            var oldListener = target[eventType];
            target[eventType] = function() {
                oldListener();
                return functionRef();
            }
        } else {
            target[eventType] = functionRef;
        }
    }
    return true;
}

function detachEventListener(target, eventType, functionRef, capture) {
    if (typeof target.removeEventListener != "undefined") {
        target.removeEventListener(eventType, functionRef, capture);
    } else if (typeof target.detachEvent != "undefined") {
        target.detachEvent("on" + eventType, functionRef);
    } else {
        target["on" + eventType] = null;
    }
    return true;
}

function getEventTarget(event) {
    var targetElement = null;
    if (typeof event.target != "undefined") {
        targetElement = event.target;
    } else {
        targetElement = event.srcElement;
    }
    while (targetElement.nodeType == 3 && targetElement.parentNode != null) {
        targetElement = targetElement.parentNode;
    }
    return targetElement;
}

function stopDefaultAction(event) {
    event.returnValue = false;
    if (typeof event.preventDefault != "undefined") {
        event.preventDefault();
    }
    return true;
}

/*    ADD LOAD HANDLER -----------------------------------------------
    allows adding more than one function to the onload event
    based on Simon Willison's discussion of closures at:
    http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*/
function addLoadHandler(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
/*    ADD ONUNLOAD HANDLER -------------------------------------------
    allows adding more than one function to the window's onlunload
    event based on Simon Willison's closure demo
*/
function addUnloadHandler(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != 'function') {
        window.onunload = function() {
            func();
            window.onload = null;
            window.onunload = null;
        }
    } else {
        window.onunload = function() {
            func();
            oldonunload();
        }
    }
}

/*    ADD HANDLER ----------------------------------------------------
    http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*/
function addHandler(obj,evt,func) {
    var oldhandler = obj[evt];
    if (typeof obj[evt] != 'function') {
        obj[evt] = func;
    } else {
        obj[evt] = function() {
            oldhandler();
            func();
        }
    }
}

/*    GET ATTR -------------------------------------------------------
    gets an attribute value; works around the IE class/className,
    for/htmlfor & camel-case debacles

    PARAMETERS
    - o = object; HTML element on which the attribute resides
    - a = string; attribute name

    REQUIRED SCRIPTS
    - translateAttrName; utility to translate from standard to
      MS-specific attribute names

    LIMITATIONS
    - may not have exhaustive list of case-sensitive attributes
*/
function getAttr(o,a) {
    var attr;
//    if the.getAttributeNode method exists, use it
    if (o.getAttributeNode) return (attr = o.getAttributeNode(a))?attr.nodeValue:'';
//    otherwise, try getAttribute with translation
    else if (o.getAttribute) return o.getAttribute(translateAttrName(a));
//    if all else fails, try just accessing it as a property
    else return o[a];
}

/*    SET ATTR -------------------------------------------------------
    sets an attribute value; works around the IE class/className,
    for/htmlfor & camel-case debacles

    PARAMETERS
    - o = object; HTML element on which the attribute resides
    - a = string; attribute name
    - v = string; attribute value

    REQUIRED SCRIPTS
    - translateAttrName; utility to translate from standard to
      MS-specific attribute names

    LIMITATIONS
    - may not have exhaustive list of case-sensitive attributes
*/
function setAttr(o,a,v) {
    var attr;
//    if the getAttributeNode method exists, use it
    if (o.getAttributeNode) {
//        if the attribute already exists, we can just set the nodeValue and have done
        if (attr = o.getAttributeNode(a)) return attr.nodeValue = v;
//        otherwise...
        else {
//            create a new attribute
            attr = document.createAttribute(a);
//            set it's nodeValue
            attr.nodeValue = v;
//            and finally add it to the element
            return o.setAttributeNode(attr);
        }
//    if there's no getAttribute node, try using setAttribute with IE translation
    } else if (o.setAttribute) return o.setAttribute(translateAttrName(a),v);
//    and if all else fails, just set it as a property
    else return o[a] = v;
}

/*    TRANSLATE ATTR NAME --------------------------------------------
    translatest from standard to IE-specific attribute names

    PARAMETERS
    - n = string; attribute name

    LIMITATIONS
    - may not have exhaustive list of case-sensitive attributes
*/
function translateAttrName(n) {
    switch(n) {
        case 'class'        :    return 'className';
        case 'for'            :    return 'htmlFor';
        case 'accesskey'    :    return 'accessKey';
        case 'colspan'        :    return 'colSpan';
        case 'rowspan'        :    return 'rowSpan';
        case 'maxlength'    :    return 'maxLength';
        case 'usemap'        :    return 'useMap';
        default                :    return n;
    }
}


/*
    JavaScript CSS Class Manipulator
    http://onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html

    This example function takes four parameters:

    a
        defines the action you want the function to perform.
    o
        the object in question.
    c1
        the name of the first class
    c2
        the name of the second class

    Possible actions are:

    swap
        replaces class c1 with class c2 in object o.
    add
        adds class c1 to the object o.
    remove
        removes class c1 from the object o.
    check
        test if class c1 is already applied to object o and returns true or false.

*/
function jscss(a, o, c1, c2) {

    if (!o){
        return;
    }
    
    switch (a){
        
        case 'swap':
            o.className = !jscss('check', o, c1) ? o.className.replace(c2,c1) : o.className.replace(c1, c2);
            break;

        case 'add':
            if (!jscss('check', o, c1)) {
                o.className += o.className ? ' '+c1 : c1;
            }
            break;

        case 'remove':
            var rep = o.className.match(' '+c1) ? ' '+c1 : c1;
            o.className = o.className.replace(rep,'');
            break;

        case 'check':
            return new RegExp('\\b'+c1+'\\b').test(o.className);
            break;

    } // end switch

}

/**
 * Get Cookie
 *
 * Taken from 'The JavaScript Anthology' [2006]; breaks down the current
 * document cookie string and parses it for a particular cookie name.
 *
 * Last modified: 2007-11-07 {pf}
 */

function getCookie(searchName) {

    var cookies = document.cookie.split(';');

    for (var i = 0, cookie; cookie = cookies[i]; i++) {

        var cookieCrumbs = cookie.split('=');
        var cookieName = cookieCrumbs[0];
        var cookieValue = cookieCrumbs[1];

        if (cookieName == searchName) {
            return cookieValue;
        }

    }

    return false;

}

/**
 * Set Cookie
 *
 * Updates the current document's cookie string; automatically set to
 * expire in 1 year's time.
 *
 * Last modified: 2007-11-07 {pf}
 */

function setCookie(name, value) {

    //  Normalise cookie string
    var newCookie = name + '=' + value;

    //  Array of month names
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    var today = new Date();
    var expiryYear = today.getFullYear() + 1;
    var expiryDate = new Date(months[today.getUTCMonth()] + ' ' + today.getDate() + ', ' + expiryYear);
    var expiryStr = expiryDate.toGMTString();

    newCookie += ';expires=' + expiryStr;

    document.cookie = newCookie;

    return newCookie;

}


/**
 * "getElementsByClassName"
 * http://www.snook.ca/archives/javascript/your_favourite_1/
 *
 * Finds all elements with a specific class, within a parent ('node'),
 * and returns them in an array.
 *
 * NOTE: Improved structure, regexp and readability. {pf}
 *
 * Last modified: 2006-11-22 {pf}
 */

function getElementsByClassName(classname, node) {

    var a = [];
    var re = new RegExp('(^| )' + classname + '( |$)');
    var els = node.getElementsByTagName("*");

    for (var i = 0, j = els.length; i < j; i++) {
        if (re.test(els[i].className)) {
            a.push(els[i]);
        }
    }

    return a;

}


/**
 * Validate Field [jQuery]
 *
 * Intelligently checks a form field to make sure either a selection has
 * been made or a value entered (as appropriate to the field type).
 *
 * Last modified: 2008-12-02 {pf}
 *
 */

function validateField(field) {
    
    var set = false;
    
    switch ( field.attr('type') ) {
        
        case 'select':
        case 'select-one':
            if ( !field.val() ) {
                return false;
            }
            break;
        
        case 'checkbox':
        case 'radio':
            if ( field.hasClass('requiredGroup') ) {
                var groupChecked = false;
                var fieldset = $(field).parents('fieldset')[0];
                $('input.requiredGroup', fieldset).each ( function() {
                    if ( $(this).attr('checked') ) {
                        groupChecked = true;
                    }
                });
                return groupChecked;
            }
            else if ( !field.attr('checked') ) {
                return false;
            }
            break;
        
        case 'password':
            // not currently testing or comparing passwords in JS, so treated as...
        default: // text
            if ( field.hasClass('validateEmail') ) {
                var emailPattern = new RegExp(/^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
                if ( field.val().match(emailPattern) === null ) {
                    return false;
                }
            }
            else if ( !field.val() ) {
                return false;
            }
        
    }
    
    return true;
    
}


/**
 * Look Up Label
 *
 * A relatively simple function that finds the label for the current
 * form element.
 *
 * Last modified: 2006-11-22 {pf}
 */

function lookUpLabel(field, form) {
    
    var htmlLabels = form.getElementsByTagName('label');
    
    for (var l = 0, htmlLabel; htmlLabel = htmlLabels[l]; l++) {
        if (getAttr(htmlLabel, 'for') == field.id) {
            return htmlLabel;
        }
    }
    
    return null;
    
}


/**
 * Get Parent By ClassName
 *
 * Last modified: 2008-01-31 {pf}
 */

function getParentByClassName(child, cssClass) {
    
    var parent = child.parentNode;
    
    if (parent.className == cssClass) {
        return parent;
    }
    
    return getParentByClassName(parent, cssClass);
    
}


/**
 * Check Requireds [jQuery]
 *
 * Alerts the user to any 'required' inputs, in the target form, which
 * have not been completed.
 *
 * Last modified: 2008-12-01 {pf}
 */
function checkRequireds(thisForm) {
    
    //  Hide server-side-generated "email already registered" warning (if shown)
    if ( $('div.emailWarning').length!= -1 && $('div.emailWarning').length > 0 ) {
        $('div.emailWarning').remove();
    }
    
    var validated = false;
    
    //  Failure counter
    var failed = 0;
    
    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required', thisForm).each( function () {
        
        var fieldValid = validateField($(this));
        
        if ( !fieldValid ) {
            
            failed++;
            
            //  Highlight error
            if ( $(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio' ) {
                $(this).parent().addClass('error');
            }
            else if ( !$(this).parent().hasClass('error') ) {
                $(this).wrap('<div class="error"></div>');
            }
            
        }
        else {
            
            //  Remove error highlight (if present)
            $(this).parent().removeClass('error');
            
        }
        
    });
    
    if (failed > 0) {
        
        if ( $('div.requiredWarning', thisForm).length < 1 ) {
            //  Requires 'reqWarn' HTML string (compiled in head of actual HTML document)
            thisForm.prepend(reqWarn);
        }
        
        //$(window).scrollTo($('div.requiredWarning:first', thisForm));
        
    }
    else if (failed == 0) {
        
        validated = true;
        
    }
    
    return validated;
    
}

/**
 * Find Requireds [jQuery]
 *
 * Automatically scans the page for forms, then adds an 'onsubmit'
 * function to any forms which contain input elements classed as
 * 'required'.
 *
 * Last modified: 2009-12-18 {dn}
 */

function findRequireds() {
    
    $('.formWrapper').each( function() {
        var thisForm = $(this);
        if ( $(':input.required', thisForm) ) {
            $(':submit', thisForm).click( function() {
                return checkRequireds(thisForm);
            });
            
            $(':image', thisForm).removeAttr("onclick");
            
            $(':image', thisForm).click( function() {
                return checkRequireds(thisForm);
            });
        }
    });

}

// Bind form validation when DOM ready [uses jQuery]
$(document).ready( function() {
    if ($(':input.required') != null && $(':input.required').length > 0 ) {
        findRequireds();
    }
});


/**
 * Simple Show/Hide
 *
 * Modifies an element's DOM CSS attributes to show or hide that
 * element.
 *
 * Last modified: 2007-11-06 {pf}
 */

function showHide(element) {

    if (element.style.display != 'none') {
        element.style.display = 'none';
    }
    else if (element.style.display != 'block') {
        element.style.display = 'block';
    }

}


/**
 * Check Filter
 *
 * Checks to see if a filter cookie has been set for the current page
 * and sdjusts the display accordingly.
 *
 * Last modified: 2008-01-28 {pf}
 */

function checkFilter() {

    //  Only run function if element present in current document
    if(document.getElementById('filter')) {
        
        var filterShowHide = document.getElementById('filterShowHide');
        
        //  Update filter hint globals
        var hintTextElement = filterShowHide.firstChild;
        var hintTextPrefix = hintTextElement.nodeValue;
        
        if(getCookie('filter')) {
            if(getCookie('filter') == 'none') {
                //  Trigger hiding of filter body
                showHideFilterBody();
            }
        }
        
        //  Update link presentation to include arrow background, etc.
        showHideFilter();
        
    }
    else {
        
        return false;
        
    }
    
}

/**
 *  Disabled on 2008-01-28; not in current spec.
 */
/* addLoadHandler(
    function() {
        checkFilter();
        return true;
    }
); */


/**
 * Show/Hide Filter Body
 *
 * Last modified: 2008-01-28 {pf}
 */

function showHideFilterBody() {
    
    //  Get prerequisite elements
    var filterShowHide = document.getElementById('filterShowHide');
    var filterBody = document.getElementById('filterBody');
    
    //  Images (indicates state)
    var bgSrcHide = 'url(../img/filter_bg_arrow_hide.gif)';
    var bgSrcShow = 'url(../img/filter_bg_arrow_show.gif)';
    
    showHide(filterBody);
    
    switch(filterBody.style.display) {
        
        case 'none':
            filterShowHide.style.backgroundImage = bgSrcShow;
            setCookie('filter', filterBody.style.display);
            break;
        
        default:
            filterShowHide.style.backgroundImage = bgSrcHide;
            setCookie('filter', 'block');
        
    }
    
}

/**
 * Show/Hide Filter
 *
 * Allows you to show or hide the in-page tag filter.
 *
 * Last modified: 2007-11-06 {pf}
 */

function showHideFilter() {

    var filter = document.getElementById('filter');
    var filterShowHide = document.getElementById('filterShowHide');

    //  Change link when JavaScript enabled
    setAttr(filterShowHide, 'class', 'showHide');
    setAttr(filterShowHide, 'title', 'Show/hide the filter');

    //  Removing default highlight box on focus
    filterShowHide.onfocus = function() {
        this.blur();
    }

    //  Bind new function and break hyperlink behaviour
    filterShowHide.onclick = function() {
        showHideFilterBody();
        return false;
    }

}


/**
 * JavaScript Pop-up Window
 *
 * Intelligently finds and attaches pop-up window function to classed links.
 *
 * Last modified: 2008-03-26 {pf}
 */

function jsPopup() {
    
    if ($("a.jsPopup")) {
        
        var settings = 'left=64, top=48, width=640, height=480, menubar=0, toolbar=0, location=0, scrollbars=1, status=0, resizable=1';
        
        $("a.jsPopup").each( function() {
            
            var href = $(this).attr("href");
            
            if ($(this).attr("id")) {
                var id = $(this).attr("id");
            }
            else {
                var popUpNow = new Date();
                var id = (popUpNow.getFullYear().toString() + popUpNow.getMonth().toString() + popUpNow.getDate().toString() + popUpNow.getHours().toString() + popUpNow.getMinutes().toString() + popUpNow.getMilliseconds().toString());
            }
            
            //alert(id);
            
            if ($(this).attr("rel")) {
                
                switch ($(this).attr("rel")) {
                    
                    case 'map':
                        if (screen.availWidth <= 1024) {
                            settings = 'left=0, top=0, width=1014, height=608, menubar=0, toolbar=0, location=0, scrollbars=1, status=0, resizable=0';
                        }
                        else {
                            settings = 'left=64, top=48, width=1024, height=768, menubar=0, toolbar=0, location=0, scrollbars=1, status=0, resizable=0';
                        }
                        break;
                    
                }
                
            }
            
            $(this).click( function() {
                var newWindow = window.open(href, id, settings);
                return false; // prevents default action
            });
            
        });
        
    }
    
}


// Bind pop-ups when DOM ready [uses jQuery]
$(document).ready( function() {
    if ($('a.jsPopup') != null && $('a.jsPopup').length > 0 ) {
        jsPopup();
    }
});


/**
 *  Clear Form Links
 *
 *  Clear a form's values using a link inside the form. This is a hack
 *  around very poor outsourced markup that can't be substituted for a
 *  proper reset button at the moment. [uses jQuery]
 *
 *  Last modified: 2008-09-17 {pf}
 */

function bindClearForm() {
    
    if ($("input.clearForm") != null) {
        $("input.clearForm").each( function() {
            
            var clearBtn = $(this);
            var form = clearBtn.parents("form");
            
            clearBtn.click( function() {
                
                $(':input', form).each( function() {
                    //  *Don't* empty the value of form buttons (it removes the actual button text!)
                    if ( $(this).attr('type') != 'submit' && $(this).attr('type') != 'reset' && $(this).attr('type') != 'button' ) {
                        //  Also, checkboxes and radios must have any selections nullified
                        if ( $(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio' ) {
                            $(this).attr('checked', false);
                        }
                        //  ...otherwise just wipe text fields and set dropdowns to null
                        else {
                            $(this).val('');
                        }
                    }
                    //  Remove 'error' highlight (if applied)
                    if ( $(this).hasClass('error') ) {
                        $(this).removeClass('error');
                    }
                });
                
                //  Mop up any remaining 'error' class attributions
                $('.error', form).each( function() {
                    $(this).removeClass('error');
                });
                
                //  Remove any required warnings in the current form
                $('.requiredWarning', form).remove();
                
                return false; //prevent default action
                
            });
            
        });
    }
}

// Bind form clearing links when DOM ready [uses jQuery]
$(document).ready( function() {
    bindClearForm();
});


/**
 *  jQuery Form Reset (originally by Mike Alsup)
 *  http://www.learningjquery.com/2007/08/clearing-form-data
 */

function resetForm(form) {

    // iterate over all of the inputs for the form
    // element that was passed in
    $(':input', form).each(function() {
        
        var type = this.type;
        var tag = this.tagName.toLowerCase(); // normalize case
        
        // it's ok to reset the value attr of text inputs,
        // password inputs, and textareas
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = "";
        // checkboxes and radios need to have their checked state cleared
        // but should *not* have their 'value' changed
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        // select elements need to have their 'selectedIndex' property set to -1
        // (this works for both single and multiple select elements)
        else if (tag == 'select')
            this.selectedIndex = -1;
        
    });
    
}


/**
 *  jQuery Overlabel [mod]
 *  Slightly modified version of Scott Sauyet's 'Overlabel' technique:
 *  http://scott.sauyet.com/thoughts/archives/2007/03/31/overlabel-with-jquery/
 *  Last modified: 2009-02-13 {pf}
 */

function loginLabels() {
    
    if ($("#loginControls label") != null) {
        $("#loginControls label").each(function(){
            
            var label = $(this);
            
            $("#"+(this.htmlFor || label.attr('for') || "ID-NOT-FOUND"))
                .focus(function(){ label.css("text-indent", "-1000px"); })
                .blur(function(){ this.value || label.css("text-indent", "0px"); })
                .trigger("focus").trigger("blur")
                .length && label.addClass("overlabel-apply");
            
            //  Handle pre-population by browsers
            if ( $("#"+(this.htmlFor || label.attr('for') || "ID-NOT-FOUND")).val().length > 0 ) {
                $(this).css("text-indent", "-1000px");
            }
            
        });
    }
}

// Bind login labels when DOM ready [uses jQuery]
$(document).ready( function() {
    loginLabels();
});


/**
 *  jQuery 'Confirm Reset' Dialogue [jQuery]
 *  Binds a standard JavaScript confirmation dialogue to all form
 *  'reset' buttons, warning the user of what is about to happen and
 *  asking them to either 'OK' or 'Cancel' the action.
 *  Last modified: 2009-01-08 {pf}
 */

function guardResets() {
    
    $("input[type=reset]").each( function() {
        
        $(this).click( function() {
            return confirm(resetWarn);
        });
        
    });
    
}

// Bind guard resets when DOM ready [uses jQuery]
$(document).ready( function() {
    if ($("input[type=reset]") != null && $("input[type=reset]").length > 0) {
        guardResets();
    }
});


//  Image Zooming
//  Uses the jQuery Lightbox v0.5 plugin, albeit heavily butchered:
//  http://leandrovieira.com/projects/jquery/lightbox/
//  Last modified: 2009-01-11 {dn}
$(function() {
    $zoom = $('a.zoom');
    
    if ($zoom != null && $zoom.length) {
        addZoomIcon();
        $('a.zoom').lightBox();
    }
});

//  Complimentary interface function, which overlays an assistive icon
//  to zoomable images/links
function addZoomIcon() {
    $('a.zoom').each( function() {
        $(this).append('<span class="indicator">+</span>');
    });
}


//  Logo Hovers (for homepage)
//  Cheaply splits the SRC URL for the product logos on hover and
//  temporarily adds in the hover URL instead.
//  Last modified: 2009-12-21 {pf}
function logoHovers() {
    if ($('ul#productLogos li') != null && $('ul#productLogos li').length >= 1) {
        $('ul#productLogos li a img').each( function() {
            var logoDefault = $(this).attr('src');
            var logoURLParts = logoDefault.split('.');
            var logoHover = logoURLParts[0] + '_hover.' + logoURLParts[1];
            $(this).hover(
                function() {
                    $(this).attr('src', logoHover);
                },
                function() {
                    $(this).attr('src', logoDefault);
                }
            );
        });
    }
}


//  Bind logo hovers on Homepage
$(function() {
    logoHovers();
});


// Homepage accordion
(function($) {
    $(document).ready(function() {
        if($("#product-accordion").length > 0)
        {
            $("#product-accordion").accordion({
                    event: "mouseover"
            });
            $("#product-accordion h2").each(function(i) {
                $(this).next().addClass('content-' + i);
            });
            $("#product-accordion ul").each(function() {
                $(this).addClass('items-' + $('li', this).size());
            });
            $("#product-accordion li").each(function() {
                var src = $('img', this).attr('src');
                $(this).hover(function() {
                    $('img', this).attr('src', src.replace(/\.ashx/, '') + '-hover.ashx');
                }, function () {
                    $('img', this).attr('src', src);
                });
            });
        };
    });
})(jQuery);


// Hero slider 
(function($) {
    $(document).ready(function() {
        
        if($('#hero-slider').length > 0) {
            
            var isPlaying = true;
            var pagerWidth = 0;
            var interval = 5000;
            
            if($('#hero-interval').length > 0) {
				
                interval = $('#hero-interval').val();
            }
			if(!interval) {
                interval = 5000;
            }
            var heroSliderOptions = {
                controls: false,
                auto: true,
                pause: interval,
                easing: 'easeOutQuint',
                onNextSlide: function(slideIndex) {
                    $('.thumb-wrap').removeClass('active');
                    $('.thumb-wrap').eq(slideIndex).addClass('active');
                }
            };
            
            var heroSlider = $('#hero-slider').bxSlider(heroSliderOptions);
                    
            //set correct pager width for centering;
            $('.thumb-wrap').each(function() {
                pagerWidth += $(this).outerWidth(true);
            });
            $('#hero-pager').width(pagerWidth);
            
            //set first as active
            $('.thumb-wrap:first-child').addClass('active');
            
            //play/stop
            $('#heroPlayToggle').click(function() {
                if(isPlaying) {
                    isPlaying = false;
                    heroSlider.stopShow();
                    $(this).addClass('pause');
                }
                else {
                    isPlaying = true;
                    heroSlider.startShow(heroSliderOptions);
                    $(this).removeClass('pause');
                }
                return false;
            });
            
            //thumbnail pager
            $('.thumb-wrap').click(function() {
                var i = $('.thumb-wrap').index(this);
                heroSlider.goToSlide(i);
                $('.thumb-wrap').removeClass('active');
                $(this).addClass('active');
                
                if(isPlaying)
                {
                    heroSlider.startShow(); 
                }
            });
            
            if($.browser.msie && $.browser.version.slice(0,3) == "6.0") {
                $('.hero-heading').each(function() {
                    var text = $(this).text();
                    $(this).replaceWith('<h2 class="hero-heading">' + text + '</h2>');
                    
                });
            };
        };
    });
})(jQuery);
