/*********************************************************************************
* Mass Leg Public. Stylesheet                                                    *
* File Name: map.js                                                             *
* Date created: 6/2/2010                                                        *
* The contents of this file may not be copied, duplicated, or redistributed      *
* in any form without the prior written consent.                                 *
**********************************************************************************/



/**Tabbed Content**/

function ddtabcontent(tabinterfaceid) {
    this.tabinterfaceid = tabinterfaceid //ID of Tab Menu main container
    this.tabs = document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container
    this.enabletabpersistence = true
    this.hottabspositions = [] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
    this.currentTabIndex = 0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array
    this.subcontentids = [] //Array to store ids of the sub contents ("rel" attr values)
    this.revcontentids = [] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
    this.selectedClassTarget = "link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
    this.onClickHookFunction = function (tabref) { }
}

ddtabcontent.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 ""
}

ddtabcontent.setCookie = function (name, value) {
    document.cookie = name + "=" + value + ";path=/" //cookie value is domain wide (path=/)
}

ddtabcontent.prototype = {

    expandit: function (tabid_or_position) { //PUBLIC function to select a tab either by its ID or position(int) within its peers
        this.cancelautorun() //stop auto cycling of tabs (if running)
        var tabref = ""
        try {
            if (typeof tabid_or_position == "string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
                tabref = document.getElementById(tabid_or_position)
            else if (parseInt(tabid_or_position) != NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
                tabref = this.tabs[tabid_or_position]
        }
        catch (err) { alert("Invalid Tab ID or position entered!") }
        if (tabref != "") //if a valid tab is found based on function parameter
            this.expandtab(tabref) //expand this tab
    },

    cycleit: function (dir, autorun) { //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )
        if (dir == "next") {
            var currentTabIndex = (this.currentTabIndex < this.hottabspositions.length - 1) ? this.currentTabIndex + 1 : 0
        }
        else if (dir == "prev") {
            var currentTabIndex = (this.currentTabIndex > 0) ? this.currentTabIndex - 1 : this.hottabspositions.length - 1
        }
        if (typeof autorun == "undefined") //if cycleit() is being called by user, versus autorun() function
            this.cancelautorun() //stop auto cycling of tabs (if running)
        this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])
    },

    setpersist: function (bool) { //PUBLIC function to toggle persistence feature
        this.enabletabpersistence = bool
    },

    setselectedClassTarget: function (objstr) { //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
        this.selectedClassTarget = objstr || "link"
    },

    setOnClickFunction: function (sFunction) { //PUBLIC function to toggle persistence feature
        this.onClickHookFunction = function (tabref) { window[sFunction](tabref) }
    },

    getselectedClassTarget: function (tabref) { //Returns target element to assign "selected" CSS class to
        return (this.selectedClassTarget == ("linkparent".toLowerCase())) ? tabref.parentNode : tabref
    },

    urlparamselect: function (tabinterfaceid) {
        var result = window.location.search.match(new RegExp(tabinterfaceid + "=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL
        return (result == null) ? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
    },

    expandtab: function (tabref) {
        var subcontentid = tabref.getAttribute("rel") //Get id of subcontent to expand
        //Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through
        var associatedrevids = (tabref.getAttribute("rev")) ? "," + tabref.getAttribute("rev").replace(/\s+/, "") + "," : ""
        this.expandsubcontent(subcontentid)
        this.expandrevcontent(associatedrevids)
        for (var i = 0; i < this.tabs.length; i++) { //Loop through all tabs, and assign only the selected tab the CSS class "selected"
            this.getselectedClassTarget(this.tabs[i]).className = (this.tabs[i].getAttribute("rel") == subcontentid) ? "selected" : ""
        }
        if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
            ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)
        this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array
    },

    expandsubcontent: function (subcontentid) {
        for (var i = 0; i < this.subcontentids.length; i++) {
            var subcontent = document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)
            subcontent.style.display = (subcontent.id == subcontentid) ? "block" : "none" //"show" or hide sub content based on matching id attr value
        }
    },

    expandrevcontent: function (associatedrevids) {
        var allrevids = this.revcontentids
        for (var i = 0; i < allrevids.length; i++) { //Loop through rev attributes for all tabs in this tab interface
            //if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
            document.getElementById(allrevids[i]).style.display = (associatedrevids.indexOf("," + allrevids[i] + ",") != -1) ? "block" : "none"
        }
    },

    setcurrenttabindex: function (tabposition) { //store current position of tab (within hottabspositions[] array)
        for (var i = 0; i < this.hottabspositions.length; i++) {
            if (tabposition == this.hottabspositions[i]) {
                this.currentTabIndex = i
                break
            }
        }
    },

    autorun: function () { //function to auto cycle through and select tabs based on a set interval
        this.cycleit('next', true)
    },

    cancelautorun: function () {
        if (typeof this.autoruntimer != "undefined")
            clearInterval(this.autoruntimer)
    },

    init: function (automodeperiod) {
        var persistedtab = ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
        var selectedtab = -1 //Currently selected tab index (-1 meaning none)
        var selectedtabfromurl = this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index
        this.automodeperiod = automodeperiod || 0
        for (var i = 0; i < this.tabs.length; i++) {
            this.tabs[i].tabposition = i //remember position of tab relative to its peers
            if (this.tabs[i].getAttribute("rel")) {
                var tabinstance = this
                this.hottabspositions[this.hottabspositions.length] = i //store position of "hot" tab ("rel" attr defined) relative to its peers
                this.subcontentids[this.subcontentids.length] = this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)
                this.tabs[i].onclick = function () {
                    tabinstance.expandtab(this)
                    tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
                    tabinstance.onClickHookFunction(this) // allows user to specify an additional function to run after tab loads
                    return false
                }
                if (this.tabs[i].getAttribute("rev")) { //if "rev" attr defined, store each value within "rev" as an array element
                    this.revcontentids = this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
                }
                if (selectedtabfromurl == i || this.enabletabpersistence && selectedtab == -1 && parseInt(persistedtab) == i || !this.enabletabpersistence && selectedtab == -1 && this.getselectedClassTarget(this.tabs[i]).className == "selected") {
                    selectedtab = i //Selected tab index, if found
                }
            }
        } //END for loop
        if (selectedtab != -1) //if a valid default selected tab index is found
            this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class)
        else //if no valid default selected index found
            this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
        if (parseInt(this.automodeperiod) > 500 && this.hottabspositions.length > 1) {
            this.autoruntimer = setInterval(function () { tabinstance.autorun() }, this.automodeperiod)
        }
    } //END int() function

} //END Prototype assignment



//Start Slideshow
jQuery.noConflict()

function fadeSlideShow(settingarg) {
    this.setting = settingarg
    settingarg = null
    var setting = this.setting
    setting.fadeduration = setting.fadeduration ? parseInt(setting.fadeduration) : 500
    setting.curimage = (setting.persist) ? fadeSlideShow.routines.getCookie("gallery-" + setting.wrapperid) : 0
    setting.curimage = setting.curimage || 0 //account for curimage being null if cookie is empty
    setting.currentstep = 0 //keep track of # of slides slideshow has gone through (applicable in displaymode='auto' only)
    setting.totalsteps = setting.imagearray.length * (setting.displaymode.cycles > 0 ? setting.displaymode.cycles : Infinity) //Total steps limit (applicable in displaymode='auto' only w/ cycles>0)
    setting.fglayer = 0, setting.bglayer = 0 //index of active and background layer (switches after each change of slide)
    setting.oninit = setting.oninit || function () { }
    setting.onslide = setting.onslide || function () { }
    if (setting.displaymode.randomize) //randomly shuffle order of images?
        setting.imagearray.sort(function () { return 0.5 - Math.random() })
    var preloadimages = [] //preload images
    setting.longestdesc = "" //get longest description of all slides. If no desciptions defined, variable contains ""
    for (var i = 0; i < setting.imagearray.length; i++) { //preload images
        preloadimages[i] = new Image()
        preloadimages[i].src = setting.imagearray[i][0]
        preloadimages[i].alt = setting.imagearray[i][3]
        if (setting.imagearray[i][3] && setting.imagearray[i][3].length > setting.longestdesc.length)
            setting.longestdesc = setting.imagearray[i][3]
    }
    var closebutt = fadeSlideShow_descpanel.controls[0] //add close button to "desc" panel if descreveal="always"
    setting.closebutton = (setting.descreveal == "always") ? '<img class="close" src="' + closebutt[0] + '" style="float:right;cursor:hand;cursor:pointer;width:' + closebutt[1] + 'px;height:' + closebutt[2] + 'px;margin-left:2px" title="Hide Description" alt="Hide Description" />' : ''
    var slideshow = this
    jQuery(document).ready(function ($) { //fire on DOM ready
        var setting = slideshow.setting
        var fullhtml = fadeSlideShow.routines.getFullHTML(setting.imagearray) //get full HTML of entire slideshow
        setting.$wrapperdiv = $('#' + setting.wrapperid).css({ position: 'relative', visibility: 'visible', background: 'black', overflow: 'hidden', width: setting.dimensions[0], height: setting.dimensions[1] }).empty() //main slideshow DIV
        if (setting.$wrapperdiv.length == 0) { //if no wrapper DIV found
            alert("Error: DIV with ID \"" + setting.wrapperid + "\" not found on page.")
            return
        }
        setting.$gallerylayers = $('<div class="gallerylayer"></div><div class="gallerylayer"></div>') //two stacked DIVs to display the actual slide 
			.css({ position: 'absolute', left: 0, top: 0, width: '100%', height: '100%', background: 'black' })
			.appendTo(setting.$wrapperdiv)
        var $loadingimg = $('<img src="' + fadeSlideShow_descpanel.controls[2][0] + '" style="position:absolute;width:' + fadeSlideShow_descpanel.controls[2][1] + ';height:' + fadeSlideShow_descpanel.controls[2][2] + '" alt="Loading" />')
			.css({ left: setting.dimensions[0] / 2 - fadeSlideShow_descpanel.controls[2][1] / 2, top: setting.dimensions[1] / 2 - fadeSlideShow_descpanel.controls[2][2] }) //center loading gif
			.appendTo(setting.$wrapperdiv)
        var $curimage = setting.$gallerylayers.html(fullhtml).find('img').hide().eq(setting.curimage) //prefill both layers with entire slideshow content, hide all images, and return current image
        if (setting.longestdesc != "" && setting.descreveal != "none") { //if at least one slide contains a description (versus feature is enabled but no descriptions defined) and descreveal not explicitly disabled
            fadeSlideShow.routines.adddescpanel($, setting)
            if (setting.descreveal == "always") { //position desc panel so it's visible to begin with
                setting.$descpanel.css({ top: setting.dimensions[1] - setting.panelheight })
                setting.$descinner.click(function (e) { //asign click behavior to "close" icon
                    if (e.target.className == "close") {
                        slideshow.showhidedescpanel('hide')
                    }
                })
                setting.$restorebutton.click(function (e) { //asign click behavior to "restore" icon
                    slideshow.showhidedescpanel('show')
                    $(this).css({ visibility: 'hidden' })
                })
            }
            else if (setting.descreveal == "ondemand") { //display desc panel on demand (mouseover)
                setting.$wrapperdiv.bind('mouseenter', function () { slideshow.showhidedescpanel('show') })
                setting.$wrapperdiv.bind('mouseleave', function () { slideshow.showhidedescpanel('hide') })
            }
        }
        setting.$wrapperdiv.bind('mouseenter', function () { setting.ismouseover = true }) //pause slideshow mouseover
        setting.$wrapperdiv.bind('mouseleave', function () { setting.ismouseover = false })
        if ($curimage.get(0).complete) { //accounf for IE not firing image.onload
            $loadingimg.hide()
            slideshow.paginateinit($)
            slideshow.showslide(setting.curimage)
        }
        else { //initialize slideshow when first image has fully loaded
            $loadingimg.hide()
            slideshow.paginateinit($)
            $curimage.bind('load', function () { slideshow.showslide(setting.curimage) })
        }
        setting.oninit.call(slideshow) //trigger oninit() event
        $(window).bind('unload', function () { //clean up and persist
            if (slideshow.setting.persist) //remember last shown image's index
                fadeSlideShow.routines.setCookie("gallery-" + setting.wrapperid, setting.curimage)
            jQuery.each(slideshow.setting, function (k) {
                if (slideshow.setting[k] instanceof Array) {
                    for (var i = 0; i < slideshow.setting[k].length; i++) {
                        if (slideshow.setting[k][i].tagName == "DIV") //catches 2 gallerylayer divs, gallerystatus div
                            slideshow.setting[k][i].innerHTML = null
                        slideshow.setting[k][i] = null
                    }
                }
            })
            slideshow = slideshow.setting = null
        })
    })
}
var fadeSlideShow_descpanel = {
    controls: [['/Content/Images/x.png', 7, 7], ['/Content/Images/restore.png', 10, 11], ['/Content/Images/loading.png', 54, 55]], //full URL and dimensions of close, restore, and loading images
    fontStyle: 'normal 11px Verdana', //font style for text descriptions
    slidespeed: 500 //speed of description panel animation (in millisec)
}

//No need to edit beyond here...

jQuery.noConflict()

fadeSlideShow.prototype = {

    navigate: function (keyword) {
        var setting = this.setting
        clearTimeout(setting.playtimer)
        if (setting.displaymode.type == "auto") { //in auto mode
            setting.displaymode.type = "manual" //switch to "manual" mode when nav buttons are clicked on
            setting.displaymode.wraparound = true //set wraparound option to true
        }
        if (!isNaN(parseInt(keyword))) { //go to specific slide?
            this.showslide(parseInt(keyword))
        }
        else if (/(prev)|(next)|(pause)/i.test(keyword)) {
            this.showslide(keyword.toLowerCase())
        }
        else if (/(play)/i.test(keyword)) {
            setting.displaymode.type = "auto" //switch to "auto" mode when play button is clicked
            this.showslide(keyword.toLowerCase())
        }
    },

    showslide: function (keyword) {
        var slideshow = this
        var setting = slideshow.setting
        if (setting.displaymode.type == "auto" && setting.ismouseover && setting.currentstep <= setting.totalsteps) { //if slideshow in autoplay mode and mouse is over it, pause it
            setting.playtimer = setTimeout(function () { slideshow.showslide('next') }, setting.displaymode.pause)
            return
        }
        var totalimages = setting.imagearray.length
        var imgindex = (keyword == "next") ? (setting.curimage < totalimages - 1 ? setting.curimage + 1 : 0)
			: (keyword == "prev") ? (setting.curimage > 0 ? setting.curimage - 1 : totalimages - 1)
			: (keyword == "play") ? (setting.curimage > 0 ? setting.curimage : 0)
			: (keyword == "pause") ? (setting.curimage > 0 ? setting.curimage : 0)
			: Math.min(keyword, totalimages - 1)
        var $slideimage = setting.$gallerylayers.eq(setting.bglayer).find('img').hide().eq(imgindex).show() //hide all images except current one
        var imgdimensions = [$slideimage.width(), $slideimage.height()] //center align image
        $slideimage.css({ marginLeft: (imgdimensions[0] > 0 && imgdimensions[0] < setting.dimensions[0]) ? setting.dimensions[0] / 2 - imgdimensions[0] / 2 : 0 })
        $slideimage.css({ marginTop: (imgdimensions[1] > 0 && imgdimensions[1] < setting.dimensions[1]) ? setting.dimensions[1] / 2 - imgdimensions[1] / 2 : 0 })
        if (setting.descreveal == "peekaboo" && setting.longestdesc != "") { //if descreveal is set to "peekaboo", make sure description panel is hidden before next slide is shown
            clearTimeout(setting.hidedesctimer) //clear hide desc panel timer
            slideshow.showhidedescpanel('hide', 0) //and hide it immediately
        }
        setting.$gallerylayers.eq(setting.bglayer).css({ zIndex: 50, opacity: 0 }) //background layer becomes foreground
			.stop().css({ opacity: 0 }).animate({ opacity: 1 }, setting.fadeduration, function () { //Callback function after fade animation is complete:
			    clearTimeout(setting.playtimer)
			    try {
			        setting.onslide.call(slideshow, setting.$gallerylayers.eq(setting.fglayer).get(0), setting.curimage)
			    } catch (e) {
			        alert("Fade In Slideshow error: An error has occured somwhere in your code attached to the \"onslide\" event: " + e)
			    }
			    if (setting.descreveal == "peekaboo" && setting.longestdesc != "") {
			        slideshow.showhidedescpanel('show')
			        setting.hidedesctimer = setTimeout(function () { slideshow.showhidedescpanel('hide') }, setting.displaymode.pause - fadeSlideShow_descpanel.slidespeed)
			    }
			    setting.currentstep += 1
			    if (setting.displaymode.type == "auto") {
			        if (setting.currentstep <= setting.totalsteps || setting.displaymode.cycles == 0)
			            setting.playtimer = setTimeout(function () { slideshow.showslide('next') }, setting.displaymode.pause)
			    }
			}) //end callback function
        setting.$gallerylayers.eq(setting.fglayer).css({ zIndex: 49 }) //foreground layer becomes background
        setting.fglayer = setting.bglayer
        setting.bglayer = (setting.bglayer == 0) ? 1 : 0
        setting.curimage = imgindex
        if (setting.$descpanel) {
            setting.$descpanel.css({ visibility: (setting.imagearray[imgindex][3]) ? 'visible' : 'hidden' })
            if (setting.imagearray[imgindex][3]) //if this slide contains a description
                setting.$descinner.empty().html(setting.closebutton + setting.imagearray[imgindex][3])
        }
        if (setting.displaymode.type == "manual" && !setting.displaymode.wraparound) {
            this.paginatecontrol()
        }
        if (setting.$status) //if status container defined
            setting.$status.html(setting.curimage + 1 + "/" + totalimages)
        if (setting.$captiondiv) //if caption container defined
            setting.$captiondiv.html(setting.imagearray[imgindex][3])
    },

    showhidedescpanel: function (state, animateduration) {
        var setting = this.setting
        var endpoint = (state == "show") ? setting.dimensions[1] - setting.panelheight : this.setting.dimensions[1]
        setting.$descpanel.stop().animate({ top: endpoint }, (typeof animateduration != "undefined" ? animateduration : fadeSlideShow_descpanel.slidespeed), function () {
            if (setting.descreveal == "always" && state == "hide")
                setting.$restorebutton.css({ visibility: 'visible' }) //show restore button
        })
    },

    paginateinit: function ($) {
        var slideshow = this
        var setting = this.setting
        if (setting.togglerid) { //if toggler div defined
            setting.$togglerdiv = $("#" + setting.togglerid)
            setting.$prev = setting.$togglerdiv.find('.prev').data('action', 'prev')
            setting.$next = setting.$togglerdiv.find('.next').data('action', 'next')
            setting.$play = setting.$togglerdiv.find('.play').data('action', 'play')
            setting.$pause = setting.$togglerdiv.find('.pause').data('action', 'pause')

            //assign click behavior to prev, next, play, and pause controls
            setting.$prev.add(setting.$next).add(setting.$play).add(setting.$pause).click(function (e) {
                var $target = $(this)
                setting.$pause.css('display', 'none')
                setting.$play.css('display', 'inline')
                slideshow.navigate($target.data('action'))
                e.preventDefault()
            })
            setting.$play.click(function (e) {
                var $target = $(this)
                setting.$pause.css('display', 'inline')
                setting.$play.css('display', 'none')
                slideshow.navigate($target.data('action'))
                e.preventDefault()
            })
            setting.$status = setting.$togglerdiv.find('.status')
        }
        if (setting.captionid) { //if caption div defined
            setting.$captiondiv = $("#" + setting.captionid)
        }
    },

    paginatecontrol: function () {
        var setting = this.setting
        setting.$prev.css({ opacity: (setting.curimage == 0) ? 0.4 : 1 }).data('action', (setting.curimage == 0) ? 'none' : 'prev')
        setting.$next.css({ opacity: (setting.curimage == setting.imagearray.length - 1) ? 0.4 : 1 }).data('action', (setting.curimage == setting.imagearray.length - 1) ? 'none' : 'next')
        if (document.documentMode == 8) { //in IE8 standards mode, apply opacity to inner image of link
            setting.$prev.find('img:eq(0)').css({ opacity: (setting.curimage == 0) ? 0.4 : 1 })
            setting.$next.find('img:eq(0)').css({ opacity: (setting.curimage == setting.imagearray.length - 1) ? 0.4 : 1 })
        }
    }
}

fadeSlideShow.routines = {

    getSlideHTML: function (imgelement) {
        var layerHTML = (imgelement[1]) ? '<a href="' + imgelement[1] + '" target="' + imgelement[2] + '">\n' : '' //hyperlink slide?
        layerHTML += '<img src="' + imgelement[0] + '" width="' + imgelement[4] + '" height="' + imgelement[5] + '" alt="' + imgelement[6] + '" style="border-width:0;" />\n'
        layerHTML += (imgelement[1]) ? '</a>\n' : ''
        return layerHTML //return HTML for this layer
    },

    getFullHTML: function (imagearray) {
        var preloadhtml = ''
        for (var i = 0; i < imagearray.length; i++)
            preloadhtml += this.getSlideHTML(imagearray[i])
        return preloadhtml
    },

    adddescpanel: function ($, setting) {
        setting.$descpanel = $('<div class="fadeslidedescdiv"></div>')
			.css({ position: 'absolute', visibility: 'hidden', width: '100%', left: 0, top: setting.dimensions[1], font: fadeSlideShow_descpanel.fontStyle, zIndex: '50' })
			.appendTo(setting.$wrapperdiv)
        $('<div class="descpanelbg"></div><div class="descpanelfg"></div>') //create inner nav panel DIVs
			.css({ position: 'absolute', left: 0, top: 0, width: setting.$descpanel.width() - 8, padding: '4px' })
			.eq(0).css({ background: 'none', opacity: 0.7 }).end() //"descpanelbg" div
			.eq(1).css({ color: 'white' }).html(setting.closebutton + setting.longestdesc).end() //"descpanelfg" div
			.appendTo(setting.$descpanel)
        setting.$descinner = setting.$descpanel.find('div.descpanelfg')
        setting.panelheight = setting.$descinner.outerHeight()
        setting.$descpanel.css({ height: setting.panelheight }).find('div').css({ height: '100%' })
        if (setting.descreveal == "always") { //create restore button
            setting.$restorebutton = $('<img class="restore" alt="Restore Description" title="Restore Description" src="' + fadeSlideShow_descpanel.controls[1][0] + '" style="position:absolute;visibility:hidden;right:0;bottom:0;z-index:1002;width:' + fadeSlideShow_descpanel.controls[1][1] + 'px;height:' + fadeSlideShow_descpanel.controls[1][2] + 'px;cursor:pointer;cursor:hand" />')
				.appendTo(setting.$wrapperdiv)


        }
    },

    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=/"
    }
}





//*****Start Thumbnail Viewer****

jQuery.noConflict()

jQuery.thumbnailviewer2 = {
    loadmsg: 'Loading Large Image...', //HTML for loading message. Make sure image paths are correct
    dsetting: { trigger: 'mouseover', preload: 'yes', fx: 'fade', fxduration: 500, enabletitle: 'yes' }, //default settings
    buildimage: function ($, $anchor, setting) {
        var imgDesc = $('input', $anchor).val();
        if (imgDesc == undefined)
            imgDesc = ' ';
        var imghtml = '<img id="loadedImage" src="' + $anchor.attr('href') + '"' + ((setting.w != '') ? ' width="' + setting.w + '"' : '') + ((setting.h != '') ? ' height="' + setting.h + '"' : '') + '" style="border-width:0" alt="' + htmlEncode($anchor.find('img:first').attr('alt')) + '" />'
        if (setting.link)
            imghtml = '<a href="' + setting.link + '">' + imghtml + '</a>'
        imghtml = '<div>' + imghtml + ((setting.enabletitle && imgDesc != '') ? '<br /><br />' + imgDesc : '') + '</div>'
        return $(imghtml)
    },
    showimage: function ($image, setting) {
        $image.stop()[setting.fxfunc](setting.fxduration, function () {
            if (this.style && this.style.removeAttribute)
                this.style.removeAttribute('filter') //fix IE clearType problem when animation is fade-in
        })
    }
}

jQuery.fn.addthumbnailviewer2 = function (options) {
    var $ = jQuery

    return this.each(function () { //return jQuery obj
        if (this.tagName != "A")
            return true //skip to next matched element

        var $anchor = $(this)
        var s = $.extend({}, $.thumbnailviewer2.dsetting, options) //merge user options with defaults
        s.fxfunc = (s.fx == "fade") ? "fadeIn" : "show"
        s.fxduration = (s.fx == "none") ? 0 : parseInt(s.fxduration)
        if (s.preload == "yes") {
            var hiddenimage = new Image()
            hiddenimage.src = this.href
        }
        var $loadarea = $('#' + s.targetdiv)
        var $hiddenimagediv = $('<div />').css({ position: 'absolute', visibility: 'hidden', left: -10000, top: -10000 }).appendTo(document.body) //hidden div to load enlarged image in

        if (s.trigger == 'click' || s.trigger == 'both') {
            var triggerevt = 'click' + '.thumbevt' //"click" or "mouseover"
            $anchor.unbind(triggerevt).bind(triggerevt, function () {
                if ($loadarea.data('$curanchor') == $anchor) //if mouse moves over same element again
                    return false
                $loadarea.data('$curanchor', $anchor)
                if ($loadarea.data('$queueimage')) { //if a large image is in the queue to be shown
                    $loadarea.data('$queueimage').unbind('load') //stop it first before showing current image
                }
                $loadarea.html($.thumbnailviewer2.loadmsg)
                var $hiddenimage = $hiddenimagediv.find('img')
                if ($hiddenimage.length == 0) { //if this is the first time moving over or clicking on the anchor link
                    var $hiddenimage = $('<img src="' + this.href + '" />').appendTo($hiddenimagediv) //populate hidden div with enlarged image
                    $hiddenimage.bind('loadevt', function (e) { //when enlarged image has fully loaded
                        var $targetimage = $.thumbnailviewer2.buildimage($, $anchor, s).hide() //create/reference actual enlarged image
                        $loadarea.empty().append($targetimage) //show enlarged image
                        $.thumbnailviewer2.showimage($targetimage, s)
                    })
                    $loadarea.data('$queueimage', $hiddenimage) //remember currently loading image as image being queued to load
                }

                if ($hiddenimage.get(0).complete)
                    $hiddenimage.trigger('loadevt')
                else
                    $hiddenimage.bind('load', function () { $hiddenimage.trigger('loadevt') })
                return false
            })
        }

        if (s.trigger == 'mouseover' || s.trigger == 'both') {
            var triggerevt = 'mouseover' + '.thumbevt' //"click" or "mouseover"
            $anchor.unbind(triggerevt).bind(triggerevt, function () {
                if ($loadarea.data('$curanchor') == $anchor) //if mouse moves over same element again
                    return false
                $loadarea.data('$curanchor', $anchor)
                if ($loadarea.data('$queueimage')) { //if a large image is in the queue to be shown
                    $loadarea.data('$queueimage').unbind('load') //stop it first before showing current image
                }
                $loadarea.html($.thumbnailviewer2.loadmsg)
                var $hiddenimage = $hiddenimagediv.find('img')
                if ($hiddenimage.length == 0) { //if this is the first time moving over or clicking on the anchor link
                    var $hiddenimage = $('<img src="' + this.href + '" />').appendTo($hiddenimagediv) //populate hidden div with enlarged image
                    $hiddenimage.bind('loadevt', function (e) { //when enlarged image has fully loaded
                        var $targetimage = $.thumbnailviewer2.buildimage($, $anchor, s).hide() //create/reference actual enlarged image
                        $loadarea.empty().append($targetimage) //show enlarged image
                        $.thumbnailviewer2.showimage($targetimage, s)
                    })
                    $loadarea.data('$queueimage', $hiddenimage) //remember currently loading image as image being queued to load
                }

                if ($hiddenimage.get(0).complete)
                    $hiddenimage.trigger('loadevt')
                else
                    $hiddenimage.bind('load', function () { $hiddenimage.trigger('loadevt') })
                return false
            })
        }

    })
}

jQuery(document).ready(function ($) {
    var $anchors = $('a[rel="enlargeimage"]') //look for links with rel="enlargeimage"
    $anchors.each(function (i) {
        var options = {}
        var rawopts = this.getAttribute('rev').split(',') //transform rev="x:value1,y:value2,etc" into a real object
        for (var i = 0; i < rawopts.length; i++) {
            var namevalpair = rawopts[i].split(/:(?!\/\/)/) //avoid spitting ":" inside "http://blabla"
            options[jQuery.trim(namevalpair[0])] = jQuery.trim(namevalpair[1])
        }
        $(this).addthumbnailviewer2(options)
    })
})



/***************************
* FORM HANDLING FUNCTIONS *
***************************/

function checkForEnter(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return false;
    if (keycode == 13) {
        return true;
    }
    return false;
}


/*****************************
* Link Invoked Popup Windows *
******************************/

function popup(mylink, windowname, width, height) {
    if (!window.focus) return true;
    var href;
    if (typeof (mylink) == 'string')
        href = mylink;
    else
        href = mylink.href;
    var w = isNaN(parseInt(width)) ? 600 : width;
    var h = isNaN(parseInt(height)) ? 800 : height;
    window.open(href, windowname, 'width=' + w + ',height=' + h + ',scrollbars=yes,resizable=yes,location=yes,status=yes');
    return false;
}


function registerExternalLinks() {
    jQuery(document).ready(function ($) {

        $('a.printerFriendlyLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").printPreview($);
            return (false);
        });

        $('a.printCloseLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").closePrintPreview($);
            return (false);
        });

        $('a.printerFriendlyWithTableLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").printPreviewWithTable($);
            return (false);
        });

        $('a.printCloseWithTableLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").closePrintPreviewWithTable($);
            return (false);
        });

        $('a.printCloseWithContainerLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").closePrintPreviewWithContainer($);
            return (false);
        });
        $('a.printerFriendlyWithContainerLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").printPreviewWithContainer($);
            return (false);
        });
        $('a.printLink').live('click', function (e) {
            e.preventDefault();
            $(".printable").print($);
            return (false);
        });

        $('a.popupLink').click(function () {
            return popup(this, "_blank");
        });

        $('a.externalLink').click(function () {
            window.open(this.href, "_blank");
            return false;
        }).append(' <img src="/Content/Images/icons/ico_externalLink.png" alt="external website" />');

        $('a.externalPdf').click(function () {
            window.open(this.href, "_blank");
            return false;
        }).append(' <img src="/Content/Images/icons/ico-mini-file_acrobat.png" alt="external website PDF file" />');

        $('a.internalPdf').click(function () {
            window.open(this.href, "_blank");
            return false;
        }).append(' <img src="/Content/Images/icons/ico-mini-file_acrobat.png" alt="PDF file" />');

        $('a.externalXls').click(function () {
            window.open(this.href, "_blank");
            return false;
        }).append(' <img src="/Content/Images/icons/ico-mini-file_excel.gif" alt="external website Excel file" />');

        $('a.internalXls').click(function () {
            window.open(this.href, "_blank");
            return false;
        }).append(' <img src="/Content/Images/icons/ico-mini-file_excel.gif" alt="Excel file" />');
    });
}

/**************************
* JQuery Helper Functions *
***************************/

// "test" -> &quot;test&quot;
// Originally quotes were not supported and had to manually be added.
function htmlEncode(value) {
    return jQuery('<div/>').text(value).html().replace(/\"/g, '&quot;').replace(/\'/g, '&apos;');
}

// &quot;test&quot; -> "test"
function htmlDecode(value) {
    return jQuery('<div/>').html(value).text();
}



/*************************
* Math Helper Functions *
*************************/
// Hyperbolic trig functions originally taken from the following blog bost:  
// www.webdeveloper.com/forum/archive/index.php/t-141409.html

// Hyperbolic Sine (x angle in radians)
Math.sinh = function (x) {
    var e = Math.E;
    var p = Math.pow(e, x);
    var n = 1 / p;
    return (p - n) / 2;
}
// Hyperbolic Cosine (x angle in radians)
Math.cosh = function (x) {
    var e = Math.E;
    var p = Math.pow(e, x);
    var n = 1 / p;
    return (p * 1 + n * 1) / 2;
}
// Hyperbolic Tangent (x angle in radians)
Math.tanh = function (x) {
    var s = Math.sinh(x);
    var c = Math.cosh(x);
    return s / c;
}

// Hyperbolic Arcsine
Math.asinh = function (x) {
    var L = x * 1 + Math.sqrt(x * x + 1);
    return Math.log(L);
}
// Hyperbolic Arccosine
Math.acosh = function (x) {
    var L = x * 1 + Math.sqrt(x * x - 1);
    return Math.log(L);
}
// Hyperbolic Arctangent
Math.atanh = function (x) {
    var L = (1 + x * 1) / (1 - x);
    return Math.log(L) / 2;
}


/*************************
* Slide Toggling Functions *
*************************/
jQuery(document).ready(function ($) {

    // Initialize megaFooter togggling; hide to start off; 
    $("#megaFooterTableWrapper").hide();
    $("#megaFooterToggle").click(function (event) {
        event.preventDefault();
        $("#megaFooterTableWrapper").slideToggle("slow");
    });


    // general slide toggling (mainly for search options hiding); hide to start off;
    $(".toggleTarget").hide();
    $(".toggleTargetInitClose").hide();
    $(".toggleSource").click(function (event) {
        event.preventDefault();
        $(".toggleTarget").slideToggle("slow");
        $(".toggleTargetInitClose").slideToggle("slow");
        $(".toggleTargetInitOpen").slideToggle("slow");
        $("a.toggleSource").find("span").toggleClass("closedState openState");
    });
});
    

