// Start Document Ready Calls
$(document).ready(function () {

    //Cufon Font Replacement
    Cufon.replace('.cufon');

    //ColorBox Lightbox
    $(".enlarge").colorbox();

    /**********************************/
    //		Equal Heights Calls
    /**********************************/
    equalHeight($(".equal"));
    //equalHeight($(".equalCols"));

    //Mega Dropdown Menu
    var SelfLocation = window.location.href.split('?');
    switch (SelfLocation[1]) {
        case "justify_right":
            jQuery(".megamenu").megamenu({ 'justify': 'right' });
            break;
        case "justify_left":
        default:
            jQuery(".megamenu").megamenu();
    }


    //Home Page Banner Slider
    $('#bannerHome').nivoSlider({
        effect: 'fade', //Specify sets like: 'fold,fade,sliceDown'
        //slices:15,
        animSpeed: 500, //Slide transition speed
        pauseTime: 7000,
        startSlide: 0, //Set starting Slide (0 index)
        directionNav: true, //Next & Prev
        directionNavHide: true, //Only show on hover
        controlNav: true, //1,2,3...
        controlNavThumbs: false, //Use thumbnails for Control Nav
        controlNavThumbsFromRel: false, //Use image rel for thumbs
        controlNavThumbsSearch: '.jpg', //Replace this with...
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
        keyboardNav: false, //Use left & right arrows
        pauseOnHover: true, //Stop animation while hovering
        manualAdvance: false, //Force manual transitions
        captionOpacity: 0.8, //Universal caption opacity
        beforeChange: function () { },
        afterChange: function () { },
        slideshowEnd: function () { } //Triggers after all slides have been shown
    });

    //Channel Page Banner Slider
    $('#bannerChannel').nivoSlider({
        effect: 'fade', //Specify sets like: 'fold,fade,sliceDown'
        //slices:15,
        animSpeed: 500, //Slide transition speed
        pauseTime: 3000,
        startSlide: 0, //Set starting Slide (0 index)
        directionNav: true, //Next & Prev
        directionNavHide: true, //Only show on hover
        controlNav: true, //1,2,3...
        controlNavThumbs: false, //Use thumbnails for Control Nav
        controlNavThumbsFromRel: false, //Use image rel for thumbs
        controlNavThumbsSearch: '.jpg', //Replace this with...
        controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
        keyboardNav: false, //Use left & right arrows
        pauseOnHover: true, //Stop animation while hovering
        manualAdvance: false, //Force manual transitions
        captionOpacity: 0.8, //Universal caption opacity
        beforeChange: function () { },
        afterChange: function () { },
        slideshowEnd: function () { } //Triggers after all slides have been shown
    });

    // Tabs - SiteWide
    var tab = $('div.tabs > div');
    tab.hide().filter(':first').show();

    $('div.tabs ul.tab a').click(function () {
        tab.hide();
        tab.filter(this.hash).show();
        $('div.tabs ul.tab a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();


});
// End Document Ready Calls

/////////////////////////////////////////////
/////////////////////////////////////////////

//jQuery Equal Heights
function equalHeight(group) {
    tallest = 0;
    group.each(function () {
        thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

//Tabs JavaScript
$(function () {
    $('.tab-set').tabs();
    $("a.openTab").click(function () {
        $('.tab-set').tabs('select', this.hash);
        return false;
    });
});

/////////////////////////////////////////////
// jQuery MegaMenu Plugin - GeekTantra     //
// Author URI: http://www.geektantra.com   //
/////////////////////////////////////////////
var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

jQuery.fn.megamenu = function (options) {
    options = jQuery.extend({
        activate_action: "mouseover",
        deactivate_action: "mouseleave",
        show_method: "slideDown",
        hide_method: "slideUp",
        justify: "left",
        enable_js_shadow: true,
        shadow_size: 3,
        mm_timeout: 250
    }, options);
    var $megamenu_object = this;
    if (options.activate_action == "click") options.mm_timeout = 0;
    $megamenu_object.children("li").each(function () {
        jQuery(this).addClass("mm-item");
        jQuery(".mm-item").css({ 'float': options.justify });

        jQuery(this).find("div:first").addClass("mm-item-content");
        jQuery(this).find("a:first").addClass("mm-item-link");
        var $mm_item_content = jQuery(this).find(".mm-item-content");
        var $mm_item_link = jQuery(this).find(".mm-item-link");
        $mm_item_content.hide();

        jQuery(document).bind("click", function () {
            jQuery(".mm-item-content").hide();
            jQuery(".mm-item-link").removeClass("mm-item-link-hover");
        });
        jQuery(this).bind("click", function (e) {
            e.stopPropagation();
        });
        $mm_item_content.wrapInner('<div class="mm-content-base"></div>');
        if (options.enable_js_shadow == true) {
            $mm_item_content.append('<div class="mm-js-shadow"></div>');
        }
        var $mm_timer = 0;
        // Activation Method Starts
        jQuery(this).bind(options.activate_action, function (e) {
            e.stopPropagation();
            var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
            var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
            clearTimeout($mm_timer);
            $mm_timer = setTimeout(function () { //Emulate HoverIntent
                mm_item_link_obj.addClass("mm-item-link-hover");
                mm_item_content_obj.css({
                    'top': ($mm_item_link.offset().top + $mm_item_link.outerHeight()) - 1 + "px",
                    'left': ($mm_item_link.offset().left) - 5 + 'px'
                })

                if (options.justify == "left") {
                    var mm_object_right_end = $megamenu_object.offset().left + $megamenu_object.outerWidth();
                    // Coordinates of the right end of the megamenu object
                    var mm_content_right_end = $mm_item_link.offset().left + $mm_item_content.outerWidth() - 5;
                    // Coordinates of the right end of the megamenu content
                    if (mm_content_right_end >= mm_object_right_end) { // Menu content exceeding the outer box
                        mm_item_content_obj.css({
                            'left': ($mm_item_link.offset().left - (mm_content_right_end - mm_object_right_end)) - 2 + 'px'
                        }); // Limit megamenu inside the outer box
                    }
                } else if (options.justify == "right") {
                    var mm_object_left_end = $megamenu_object.offset().left;
                    // Coordinates of the left end of the megamenu object
                    var mm_content_left_end = $mm_item_link.offset().left - mm_item_content_obj.outerWidth() +
                                    $mm_item_link.outerWidth() + 5;
                    // Coordinates of the left end of the megamenu content
                    if (mm_content_left_end <= mm_object_left_end) { // Menu content exceeding the outer box
                        mm_item_content_obj.css({
                            'left': mm_object_left_end + 2 + 'px'
                        }); // Limit megamenu inside the outer box
                    } else {
                        mm_item_content_obj.css({
                            'left': mm_content_left_end + 'px'
                        }); // Limit megamenu inside the outer box
                    }
                }
                if (options.enable_js_shadow == true) {
                    mm_item_content_obj.find(".mm-js-shadow").height(mm_item_content_obj.height());
                    mm_item_content_obj.find(".mm-js-shadow").width(mm_item_content_obj.width());
                    mm_item_content_obj.find(".mm-js-shadow").css({
                        'top': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
                        'left': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
                        'opacity': 0.5
                    });
                }
                switch (options.show_method) {
                    case "simple":
                        mm_item_content_obj.show();
                        break;
                    case "slideDown":
                        mm_item_content_obj.height("auto");
                        mm_item_content_obj.slideDown('fast');
                        break;
                    case "fadeIn":
                        mm_item_content_obj.fadeTo('fast', 1);
                        break;
                    default:
                        mm_item_content_obj.each(options.show_method);
                        break;
                }
            }, options.mm_timeout);
        });
        // Activation Method Ends
        // Deactivation Method Starts
        jQuery(this).bind(options.deactivate_action, function (e) {
            e.stopPropagation();
            clearTimeout($mm_timer);
            var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
            var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
            //      mm_item_content_obj.stop();
            switch (options.hide_method) {
                case "simple":
                    mm_item_content_obj.hide();
                    mm_item_link_obj.removeClass("mm-item-link-hover");
                    break;
                case "slideUp":
                    mm_item_content_obj.slideUp('fast', function () {
                        mm_item_link_obj.removeClass("mm-item-link-hover");
                    });
                    break;
                case "fadeOut":
                    mm_item_content_obj.fadeOut('fast', function () {
                        mm_item_link_obj.removeClass("mm-item-link-hover");
                    });
                    break;
                default:
                    mm_item_content_obj.each(options.hide_method);
                    mm_item_link_obj.removeClass("mm-item-link-hover");
                    break;
            }
            if (mm_item_content_obj.length < 1) mm_item_link_obj.removeClass("mm-item-link-hover");
        });
        //    Deactivation Method Ends
    });
    this.find(">li:last").after('<li class="clear-fix"></li>');
    this.show();
};

/////////////////////////////////////////////
// AnyLink Dropdown Menu                   //
/////////////////////////////////////////////

if (typeof dd_domreadycheck == "undefined") //global variable to detect if DOM is ready
    var dd_domreadycheck = false

var anylinkcssmenu = {

    menusmap: {},
    preloadimages: [],
    effects: { delayhide: 200, shadow: { enabled: true, opacity: 0.3, depth: [5, 5] }, fade: { enabled: true, duration: 500} }, //customize menu effects

    dimensions: {},

    getoffset: function (what, offsettype) {
        return (what.offsetParent) ? what[offsettype] + this.getoffset(what.offsetParent, offsettype) : what[offsettype]
    },

    getoffsetof: function (el) {
        el._offsets = { left: this.getoffset(el, "offsetLeft"), top: this.getoffset(el, "offsetTop"), h: el.offsetHeight }
    },

    getdimensions: function (menu) {
        this.dimensions = { anchorw: menu.anchorobj.offsetWidth, anchorh: menu.anchorobj.offsetHeight,
            docwidth: (window.innerWidth || this.standardbody.clientWidth) - 20,
            docheight: (window.innerHeight || this.standardbody.clientHeight) - 15,
            docscrollx: window.pageXOffset || this.standardbody.scrollLeft,
            docscrolly: window.pageYOffset || this.standardbody.scrollTop
        }
        if (!this.dimensions.dropmenuw) {
            this.dimensions.dropmenuw = menu.dropmenu.offsetWidth
            this.dimensions.dropmenuh = menu.dropmenu.offsetHeight
        }
    },

    isContained: function (m, e) {
        var e = window.event || e
        var c = e.relatedTarget || ((e.type == "mouseover") ? e.fromElement : e.toElement)
        while (c && c != m) try { c = c.parentNode } catch (e) { c = m }
        if (c == m)
            return true
        else
            return false
    },

    setopacity: function (el, value) {
        el.style.opacity = value
        if (typeof el.style.opacity != "string") { //if it's not a string (ie: number instead), it means property not supported
            el.style.MozOpacity = value
            if (el.filters) {
                el.style.filter = "progid:DXImageTransform.Microsoft.alpha(opacity=" + value * 100 + ")"
            }
        }
    },

    showmenu: function (menuid) {
        var menu = anylinkcssmenu.menusmap[menuid]
        clearTimeout(menu.hidetimer)
        this.getoffsetof(menu.anchorobj)
        this.getdimensions(menu)
        var posx = menu.anchorobj._offsets.left + (menu.orientation == "lr" ? this.dimensions.anchorw : 0) //base x pos
        var posy = menu.anchorobj._offsets.top + this.dimensions.anchorh - (menu.orientation == "lr" ? this.dimensions.anchorh : 0)//base y pos
        if (posx + this.dimensions.dropmenuw + this.effects.shadow.depth[0] > this.dimensions.docscrollx + this.dimensions.docwidth) { //drop left instead?
            posx = posx - this.dimensions.dropmenuw + (menu.orientation == "lr" ? -this.dimensions.anchorw : this.dimensions.anchorw)
        }
        if (posy + this.dimensions.dropmenuh > this.dimensions.docscrolly + this.dimensions.docheight) {  //drop up instead?
            posy = Math.max(posy - this.dimensions.dropmenuh - (menu.orientation == "lr" ? -this.dimensions.anchorh : this.dimensions.anchorh), this.dimensions.docscrolly) //position above anchor or window's top edge
        }
        if (this.effects.fade.enabled) {
            this.setopacity(menu.dropmenu, 0) //set opacity to 0 so menu appears hidden initially
            if (this.effects.shadow.enabled)
                this.setopacity(menu.shadow, 0) //set opacity to 0 so shadow appears hidden initially
        }
        menu.dropmenu.setcss({ left: posx + 'px', top: posy + 'px', visibility: 'visible' })
        if (this.effects.shadow.enabled)
            menu.shadow.setcss({ left: posx + anylinkcssmenu.effects.shadow.depth[0] + 'px', top: posy + anylinkcssmenu.effects.shadow.depth[1] + 'px', visibility: 'visible' })
        if (this.effects.fade.enabled) {
            clearInterval(menu.animatetimer)
            menu.curanimatedegree = 0
            menu.starttime = new Date().getTime() //get time just before animation is run
            menu.animatetimer = setInterval(function () { anylinkcssmenu.revealmenu(menuid) }, 20)
        }
    },

    revealmenu: function (menuid) {
        var menu = anylinkcssmenu.menusmap[menuid]
        var elapsed = new Date().getTime() - menu.starttime //get time animation has run
        if (elapsed < this.effects.fade.duration) {
            this.setopacity(menu.dropmenu, menu.curanimatedegree)
            if (this.effects.shadow.enabled)
                this.setopacity(menu.shadow, menu.curanimatedegree * this.effects.shadow.opacity)
        }
        else {
            clearInterval(menu.animatetimer)
            this.setopacity(menu.dropmenu, 1)
            menu.dropmenu.style.filter = ""
        }
        menu.curanimatedegree = (1 - Math.cos((elapsed / this.effects.fade.duration) * Math.PI)) / 2
    },

    setcss: function (param) {
        for (prop in param) {
            this.style[prop] = param[prop]
        }
    },

    setcssclass: function (el, targetclass, action) {
        var needle = new RegExp("(^|\\s+)" + targetclass + "($|\\s+)", "ig")
        if (action == "check")
            return needle.test(el.className)
        else if (action == "remove")
            el.className = el.className.replace(needle, "")
        else if (action == "add" && !needle.test(el.className))
            el.className += " " + targetclass
    },

    hidemenu: function (menuid) {
        var menu = anylinkcssmenu.menusmap[menuid]
        clearInterval(menu.animatetimer)
        menu.dropmenu.setcss({ visibility: 'hidden', left: 0, top: 0 })
        menu.shadow.setcss({ visibility: 'hidden', left: 0, top: 0 })
    },

    getElementsByClass: function (targetclass) {
        if (document.querySelectorAll)
            return document.querySelectorAll("." + targetclass)
        else {
            var classnameRE = new RegExp("(^|\\s+)" + targetclass + "($|\\s+)", "i") //regular expression to screen for classname
            var pieces = []
            var alltags = document.all ? document.all : document.getElementsByTagName("*")
            for (var i = 0; i < alltags.length; i++) {
                if (typeof alltags[i].className == "string" && alltags[i].className.search(classnameRE) != -1)
                    pieces[pieces.length] = alltags[i]
            }
            return pieces
        }
    },

    addEvent: function (targetarr, functionref, tasktype) {
        if (targetarr.length > 0) {
            var target = targetarr.shift()
            if (target.addEventListener)
                target.addEventListener(tasktype, functionref, false)
            else if (target.attachEvent)
                target.attachEvent('on' + tasktype, function () { return functionref.call(target, window.event) })
            this.addEvent(targetarr, functionref, tasktype)
        }
    },

    domready: function (functionref) { //based on code from the jQuery library
        if (dd_domreadycheck) {
            functionref()
            return
        }
        // Mozilla, Opera and webkit nightlies currently support this event
        if (document.addEventListener) {
            // Use the handy event callback
            document.addEventListener("DOMContentLoaded", function () {
                document.removeEventListener("DOMContentLoaded", arguments.callee, false)
                functionref();
                dd_domreadycheck = true
            }, false)
        }
        else if (document.attachEvent) {
            // If IE and not an iframe
            // continually check to see if the document is ready
            if (document.documentElement.doScroll && window == window.top) (function () {
                if (dd_domreadycheck) return
                try {
                    // If IE is used, use the trick by Diego Perini
                    // http://javascript.nwbox.com/IEContentLoaded/
                    document.documentElement.doScroll("left")
                } catch (error) {
                    setTimeout(arguments.callee, 0)
                    return;
                }
                //and execute any waiting functions
                functionref();
                dd_domreadycheck = true
            })();
        }
        if (document.attachEvent && parent.length > 0) //account for page being in IFRAME, in which above doesn't fire in IE
            this.addEvent([window], function () { functionref() }, "load");
    },

    addState: function (anchorobj, state) {
        if (anchorobj.getAttribute('data-image')) {
            var imgobj = (anchorobj.tagName == "IMG") ? anchorobj : anchorobj.getElementsByTagName('img')[0]
            if (imgobj) {
                imgobj.src = (state == "add") ? anchorobj.getAttribute('data-overimage') : anchorobj.getAttribute('data-image')
            }
        }
        else
            anylinkcssmenu.setcssclass(anchorobj, "selectedanchor", state)
    },


    setupmenu: function (targetclass, anchorobj, pos) {
        this.standardbody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body
        var relattr = anchorobj.getAttribute("rel")
        var dropmenuid = relattr.replace(/\[(\w+)\]/, '')
        var menu = this.menusmap[targetclass + pos] = {
            id: targetclass + pos,
            anchorobj: anchorobj,
            dropmenu: document.getElementById(dropmenuid),
            revealtype: (relattr.length != dropmenuid.length && RegExp.$1 == "click") ? "click" : "mouseover",
            orientation: anchorobj.getAttribute("rev") == "lr" ? "lr" : "ud",
            shadow: document.createElement("div")
        }
        menu.anchorobj._internalID = targetclass + pos
        menu.anchorobj._isanchor = true
        menu.dropmenu._internalID = targetclass + pos
        menu.shadow._internalID = targetclass + pos
        menu.shadow.className = "anylinkshadow"
        document.body.appendChild(menu.dropmenu) //move drop down div to end of page
        document.body.appendChild(menu.shadow)
        menu.dropmenu.setcss = this.setcss
        menu.shadow.setcss = this.setcss
        menu.shadow.setcss({ width: menu.dropmenu.offsetWidth + "px", height: menu.dropmenu.offsetHeight + "px" })
        this.setopacity(menu.shadow, this.effects.shadow.opacity)
        this.addEvent([menu.anchorobj, menu.dropmenu, menu.shadow], function (e) { //MOUSEOVER event for anchor, dropmenu, shadow
            var menu = anylinkcssmenu.menusmap[this._internalID]
            if (this._isanchor && menu.revealtype == "mouseover" && !anylinkcssmenu.isContained(this, e)) { //event for anchor
                anylinkcssmenu.showmenu(menu.id)
                anylinkcssmenu.addState(this, "add")
            }
            else if (typeof this._isanchor == "undefined") { //event for drop down menu and shadow
                clearTimeout(menu.hidetimer)
            }
        }, "mouseover")
        this.addEvent([menu.anchorobj, menu.dropmenu, menu.shadow], function (e) { //MOUSEOUT event for anchor, dropmenu, shadow
            if (!anylinkcssmenu.isContained(this, e)) {
                var menu = anylinkcssmenu.menusmap[this._internalID]
                menu.hidetimer = setTimeout(function () {
                    anylinkcssmenu.addState(menu.anchorobj, "remove")
                    anylinkcssmenu.hidemenu(menu.id)
                }, anylinkcssmenu.effects.delayhide)
            }
        }, "mouseout")
        this.addEvent([menu.anchorobj, menu.dropmenu], function (e) { //CLICK event for anchor, dropmenu
            var menu = anylinkcssmenu.menusmap[this._internalID]
            if (this._isanchor && menu.revealtype == "click") {
                if (menu.dropmenu.style.visibility == "visible")
                    anylinkcssmenu.hidemenu(menu.id)
                else {
                    anylinkcssmenu.addState(this, "add")
                    anylinkcssmenu.showmenu(menu.id)
                }
                if (e.preventDefault)
                    e.preventDefault()
                return false
            }
            else
                menu.hidetimer = setTimeout(function () { anylinkcssmenu.hidemenu(menu.id) }, anylinkcssmenu.effects.delayhide)
        }, "click")
    },

    init: function (targetclass) {
        this.domready(function () { anylinkcssmenu.trueinit(targetclass) })
    },

    trueinit: function (targetclass) {
        var anchors = this.getElementsByClass(targetclass)
        var preloadimages = this.preloadimages
        for (var i = 0; i < anchors.length; i++) {
            if (anchors[i].getAttribute('data-image')) { //preload anchor image?
                preloadimages[preloadimages.length] = new Image()
                preloadimages[preloadimages.length - 1].src = anchors[i].getAttribute('data-image')
            }
            if (anchors[i].getAttribute('data-overimage')) { //preload anchor image?
                preloadimages[preloadimages.length] = new Image()
                preloadimages[preloadimages.length - 1].src = anchors[i].getAttribute('data-overimage')
            }
            this.setupmenu(targetclass, anchors[i], i)
        }
    }

}

//AnyLink Initialize
anylinkcssmenu.init("anchorclass")

/////////////////////////////////////////////
// Accordion (Multiple Sliders)            //
/////////////////////////////////////////////
var ddaccordion = {

    contentclassname: {}, //object to store corresponding contentclass name based on headerclass

    expandone: function (headerclass, selected) { //PUBLIC function to expand a particular header
        this.toggleone(headerclass, selected, "expand")
    },

    collapseone: function (headerclass, selected) { //PUBLIC function to collapse a particular header
        this.toggleone(headerclass, selected, "collapse")
    },

    expandall: function (headerclass) { //PUBLIC function to expand all headers based on their shared CSS classname
        var $ = jQuery
        var $headers = $('.' + headerclass)
        $('.' + this.contentclassname[headerclass] + ':hidden').each(function () {
            $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
        })
    },

    collapseall: function (headerclass) { //PUBLIC function to collapse all headers based on their shared CSS classname
        var $ = jQuery
        var $headers = $('.' + headerclass)
        $('.' + this.contentclassname[headerclass] + ':visible').each(function () {
            $headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
        })
    },

    toggleone: function (headerclass, selected, optstate) { //PUBLIC function to expand/ collapse a particular header
        var $ = jQuery
        var $targetHeader = $('.' + headerclass).eq(selected)
        var $subcontent = $('.' + this.contentclassname[headerclass]).eq(selected)
        if (typeof optstate == "undefined" || optstate == "expand" && $subcontent.is(":hidden") || optstate == "collapse" && $subcontent.is(":visible"))
            $targetHeader.trigger("evt_accordion")
    },

    expandit: function ($targetHeader, $targetContent, config, useractivated, directclick) {
        this.transformHeader($targetHeader, config, "expand")
        $targetContent.slideDown(config.animatespeed, function () {
            config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
            if (config.postreveal == "gotourl" && directclick) { //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
                var targetLink = ($targetHeader.is("a")) ? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
                if (targetLink) //if this header is a link
                    setTimeout(function () { location = targetLink.href }, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
            }
        })
    },

    collapseit: function ($targetHeader, $targetContent, config, isuseractivated) {
        this.transformHeader($targetHeader, config, "collapse")
        $targetContent.slideUp(config.animatespeed, function () { config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated) })
    },

    transformHeader: function ($targetHeader, config, state) {
        $targetHeader.addClass((state == "expand") ? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
        .removeClass((state == "expand") ? config.cssclass.collapse : config.cssclass.expand)
        if (config.htmlsetting.location == 'src') { //Change header image (assuming header is an image)?
            $targetHeader = ($targetHeader.is("img")) ? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
            $targetHeader.attr('src', (state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
        }
        else if (config.htmlsetting.location == "prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
            $targetHeader.find('.accordprefix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
        else if (config.htmlsetting.location == "suffix")
            $targetHeader.find('.accordsuffix').html((state == "expand") ? config.htmlsetting.expand : config.htmlsetting.collapse)
    },

    urlparamselect: function (headerclass) {
        var result = window.location.search.match(new RegExp(headerclass + "=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
        if (result != null)
            result = RegExp.$1.split(',')
        return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
    },

    getCookie: function (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 null
    },

    setCookie: function (name, value) {
        document.cookie = name + "=" + value + "; path=/"
    },

    init: function (config) {
        document.write('<style type="text/css">\n')
        document.write('.' + config.contentclass + '{display: none}\n') //generate CSS to hide contents
        document.write('<\/style>')
        jQuery(document).ready(function ($) {
            ddaccordion.urlparamselect(config.headerclass)
            var persistedheaders = ddaccordion.getCookie(config.headerclass)
            ddaccordion.contentclassname[config.headerclass] = config.contentclass //remember contentclass name based on headerclass
            config.cssclass = { collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
            config.revealtype = config.revealtype || "click"
            config.revealtype = config.revealtype.replace(/mouseover/i, "mouseenter")
            if (config.revealtype == "clickgo") {
                config.postreveal = "gotourl" //remember added action
                config.revealtype = "click" //overwrite revealtype to "click" keyword
            }
            if (typeof config.togglehtml == "undefined")
                config.htmlsetting = { location: "none" }
            else
                config.htmlsetting = { location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
            config.oninit = (typeof config.oninit == "undefined") ? function () { } : config.oninit //attach custom "oninit" event handler
            config.onopenclose = (typeof config.onopenclose == "undefined") ? function () { } : config.onopenclose //attach custom "onopenclose" event handler
            var lastexpanded = {} //object to hold reference to last expanded header and content (jquery objects)
            var expandedindices = ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders != null) ? persistedheaders : config.defaultexpanded)
            if (typeof expandedindices == 'string') //test for string value (exception is config.defaultexpanded, which is an array)
                expandedindices = expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
            var $subcontents = $('.' + config["contentclass"])
            if (expandedindices.length == 1 && expandedindices[0] == "-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
                expandedindices = []
            if (config["collapseprev"] && expandedindices.length > 1) //only allow one content open?
                expandedindices = [expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
            if (config["onemustopen"] && expandedindices.length == 0) //if at least one content should be open at all times and none are, open 1st header
                expandedindices = [0]
            $('.' + config["headerclass"]).each(function (index) { //loop through all headers
                if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html() != "") { //add a SPAN element to header depending on user setting and if header is a container tag
                    $('<span class="accordprefix"></span>').prependTo(this)
                    $('<span class="accordsuffix"></span>').appendTo(this)
                }
                $(this).attr('headerindex', index + 'h') //store position of this header relative to its peers
                $subcontents.eq(index).attr('contentindex', index + 'c') //store position of this content relative to its peers
                var $subcontent = $subcontents.eq(index)
                var needle = (typeof expandedindices[0] == "number") ? index : index + '' //check for data type within expandedindices array- index should match that type
                if (jQuery.inArray(needle, expandedindices) != -1) { //check for headers that should be expanded automatically (convert index to string first)
                    if (config.animatedefault == false)
                        $subcontent.show()
                    ddaccordion.expandit($(this), $subcontent, config, false) //Last param sets 'isuseractivated' parameter
                    lastexpanded = { $header: $(this), $content: $subcontent }
                }  //end check
                else {
                    $subcontent.hide()
                    config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
                    ddaccordion.transformHeader($(this), config, "collapse")
                }
            })
            $('.' + config["headerclass"]).bind("evt_accordion", function (e, isdirectclick) { //assign custom event handler that expands/ contacts a header
                var $subcontent = $subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
                if ($subcontent.css('display') == "none") {
                    ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
                    if (config["collapseprev"] && lastexpanded.$header && $(this).get(0) != lastexpanded.$header.get(0)) { //collapse previous content?
                        ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
                    }
                    lastexpanded = { $header: $(this), $content: $subcontent }
                }
                else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0) != lastexpanded.$header.get(0)) {
                    ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
                }
            })
            $('.' + config["headerclass"]).bind(config.revealtype, function () {
                if (config.revealtype == "mouseenter") {
                    clearTimeout(config.revealdelay)
                    var headerindex = parseInt($(this).attr("headerindex"))
                    config.revealdelay = setTimeout(function () { ddaccordion.expandone(config["headerclass"], headerindex) }, config.mouseoverdelay || 0)
                }
                else {
                    $(this).trigger("evt_accordion", [true])
                    return false //cancel default click behavior
                }
            })
            $('.' + config["headerclass"]).bind("mouseleave", function () {
                clearTimeout(config.revealdelay)
            })
            config.oninit($('.' + config["headerclass"]).get(), expandedindices)
            $(window).bind('unload', function () { //clean up and persist on page unload
                $('.' + config["headerclass"]).unbind()
                var expandedindices = []
                $('.' + config["contentclass"] + ":visible").each(function (index) { //get indices of expanded headers
                    expandedindices.push($(this).attr('contentindex'))
                })
                if (config.persiststate == true && $('.' + config["headerclass"]).length > 0) { //persist state?
                    expandedindices = (expandedindices.length == 0) ? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
                    ddaccordion.setCookie(config.headerclass, expandedindices)
                }
            })
        })
    }
}

/////////////////////////////////////////////
// Accordion (Expand/Collapse)             //
/////////////////////////////////////////////
ddaccordion.init({
    headerclass: "trigger", //Shared CSS class name of headers group
    contentclass: "triggerContent", //Shared CSS class name of contents group
    revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
    mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
    collapseprev: false, //Collapse previous content (so only one open at any time)? true/false 
    defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
    onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
    animatedefault: false, //Should contents open by default be animated into view?
    persiststate: false, //persist state of opened contents within browser session?
    toggleclass: ["closedlanguage", "openlanguage"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
    //togglehtml: ["prefix", "<img src='http://i13.tinypic.com/80mxwlz.gif' style='width:13px; height:13px' /> ", "<img src='http://i18.tinypic.com/6tpc4td.gif' style='width:13px; height:13px' /> "], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
    animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
    oninit: function (expandedindices) { //custom code to run when headers have initalized
        //do nothing
    },
    onopenclose: function (header, index, state, isuseractivated) { //custom code to run whenever a header is opened or closed
        //do nothing
    }
});


/////////////////////////////////////////////
// 02-15-2012 Temporary Survey             //
/////////////////////////////////////////////
    function getCookie(c_name)
    {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++)
        {
              x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
              y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
              x = x.replace(/^\s+|\s+$/g, "");
              if (x == c_name)
            {
                return unescape(y);
            }
        }
    }
        
    function setCookie(c_name, value, exdays)
    {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }


