//Fix an issue with IE caching of images causing some images to flicker on mouseover
try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}
// given a JQuery selection string, the function will toggle a class of 'className'
// on the items parent whenever the item is clicked
function toggleState(target, className) {
    $(target).toggle(
        function() {
            $(this).parent().addClass(className);
        },
        function() {
            $(this).parent().removeClass(className);
        }
    );
}
function tabify(el, className) {
    if(jQuery.browser.version <= 418.8 && $.browser.safari) {
        $("body").addClass("safari");
    }
    
    var container = $(el);
    container.attr("class", className);
    
    $(el + " div h2").click(function() {
        var id = $(this).parent().attr("id");
        container.attr("class", id);
    });
}
// First, let's tell tag the page when javascript is on.
$(function() {
    $("body").addClass("jsOn");
// HP Slideshow (Rotating Images) speed control
$(".slideshow").cycle({
    timeout: 5500,
    speed:  2500
}); 
// IE6 checker for browser checking
    if(jQuery.browser.version == 6.0 && $.browser.msie) {
        ie6 = true;
    }
// Student Life "Week in the Life..." Next/Previous Profile Navigation
    $("#profiles div.story:first").addClass("active");
    $("#nextStudent").click(function(){
        var nextSize = $("#profiles .story.active").next(".story").size();
        if ( nextSize > 0 ) {
        $("#profiles .story.active").removeClass("active").next().addClass("active");
        $("#profiles li a").removeClass("active");
        var first = $("#profiles .active li a:first");
        first.addClass("active")
        //swap p text
        $("#profiles div.studentName p").text(getText($("#profiles li a.active")));
        //change img src
        $("#profiles img.full").attr("src", getHref($("#profiles li a.active")));
        }
    });
    $("#previousStudent").click(function() {
        var prevSize = $("#profiles .story.active").prev(".story").size();
        if ( prevSize > 0 ) {
        $("#profiles .story.active").removeClass("active").prev().addClass("active");
        $("#profiles li a").removeClass("active");
        var first = $("#profiles .active li a:first");
        first.addClass("active")
        //swap p text
        $("#profiles div.studentName p").text(getText($("#profiles .active li a.active")));
        //change img src
        $("#profiles img.full").attr("src", getHref($("#profiles .active li a.active")));
        }
    });
// addClass first
    $(".navSecondary li:first, .generalContacts ul li:first-child").addClass("first");
    $("#extra .module:first").addClass("firstModule");
// gallery pop up
$("a.galleryLink").click(function() {
        window.open(this.getAttribute('href'), '_blank', 'width=604px,height=582px,fullscreen=no,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
        return false;
    });
// gallery close
$("a.closeGallery").click(function() {
        window.close()
    });
// if "active" addClass 
if($("#navPhoto").hasClass("active")) {
    $(".media").addClass("photo")
} 
if($("#navVideo").hasClass("active")) {
    $(".media").addClass("video")
}
if($("#navAudio").hasClass("active")) {
    $(".media").addClass("audio")
}
if($("body").hasClass("gallery")) {
    $(".mediaGallery h2").addClass("active")
}
// addClass last
    $("#schoolsNews .col p:last-child, .departmentNews .col p:last, #content #contactTabs li:last, table tr th:last-child, table tr td:last-child, #content .playlist li:last").addClass("last");
    $("#extra .module:last").addClass("lastModule");
// adding hyphen to Level 6 navSecondary item
    $(".navSecondary .active .active .active li a").prepend("&#45;&nbsp;");
// adding raquo and/or "//" to link to calendar detail
    $("#listings li a.detailLink").append("&nbsp;&raquo;");
    $("#listings li span.location").prepend("//&nbsp;");
// Support show/hide
    $(".supportSalemState ul").hide()
    $(".supportSalemState h2").click(function() {
        $(this).parent().toggleClass("active");
        $(this).parent().children("ul").toggle();
        return false
    });
// Feedback show/hide
// added by William Phillips
    $(".feedbackSalemState ul").hide()
    $(".feedbackSalemState h2").click(function() {
        $(this).parent().toggleClass("active");
        $(this).parent().children("ul").toggle();
        return false
    });
// zebra tables
    $("table").each(function(){
        $("tr:nth-child(odd)").addClass("odd");
    });
// Accordion ------------------------------
//    First, set the height of each hidden section so IE can show/hide it properly.
    $(".accordion li ul").each(function() {
        var myHeight = $(this).height()
        $(this).css({ height:myHeight+8 });
    });
//    Hide all nested ULs with js (so users with js turned off can see everything)
    $(".accordion ul").hide();
//    Hover state for headlines
    $(".accordion h3.handle").hover(
      function () { $(this).addClass("over"); }, 
      function () { $(this).removeClass("over"); }
    );
//    Accordion actions
    $(".accordion h3.handle").click(function() {
    //    If clicking on an active section, just close it and remove the active state.
        if($(this).parent().hasClass("active")) {
            $(".accordion li.active ul").slideUp(300)
            $(".accordion li").removeClass("active")
        }
    //    Otherwise, the click triggers three actions: close the active section, open
    //    the section that's clicked on, and mark it active.
        else if($(this).hasClass("handle")) {
            $(".accordion li.active ul").slideUp(300)
            $(".accordion li").removeClass("active")
            $(this).parent().addClass("active")
            $(".accordion li.active ul").slideDown(300)
        }
    });
// Dropdown Nav Hover
    $("#dropdown").mouseover(function() {$(this).addClass("sfhover")});
    $("#dropdown").mouseout(function() {$(this).removeClass("sfhover")});
// Home Feature ------------------------------
//    First, set the height of each hidden section so IE can show/hide it properly.
/*
    $(".feature li ul").each(function() {
        var myHeight = $(this).height()
        $(this).css({ height:myHeight+31 });
    });
*/
//    Hide all nested ULs with js (so users with js turned off can see everything)
//    Hover state for headlines
    $(".feature h3.handle").hover(
      function () { $(this).addClass("over"); }, 
      function () { $(this).removeClass("over"); }
    );
//    Home Feature actions
    $(".feature h3.handle").click(function() {
    //    If clicking on an active section, just close it and remove the active state.
        if($(this).parent().hasClass("active")) {
            $(".feature .section").removeClass("active")
        }
    //    Otherwise, the click triggers three actions: close the active section, open
    //    the section that's clicked on, and mark it active.
        else if($(this).hasClass("handle")) {
            $(".feature .section").removeClass("active")
            $(this).parent().addClass("active")
        }
    });
    
    $(".feature .section .thumb").hover(
      function () { $(this).addClass("hover"); }, 
      function () { $(this).removeClass("hover"); }
    );
    $(".feature .section .thumb").click(function() {
        $(this).parent().siblings().removeClass("active");
        $(this).parent().addClass("active");
    });
}); // Bye-bye jQuery! ------------------------------

function accSecondayNav(startOpen) {
//    Hide all nested ULs with js (so users with js turned off can see everything)
    $("#navigation .navAccordion ul").hide();
    $("#navigation .navAccordion div.active h3.handle").addClass("active");
    $("#navigation .navAccordion div.active ul").show();
//    Hover state for headlines
    $("#navigation .navAccordion h3.handle").hover(
      function () { $(this).addClass("over"); }, 
      function () { $(this).removeClass("over"); }
    );
//    Accordion actions
    $("#navigation .navAccordion h3.handle").click(function() {
    //    If clicking on an active section, just close it and remove the active state.
        if($(this).parent().hasClass("active")) {
            $(this).parent().children("ul").slideUp(300)
            $(this).parent().removeClass("active")
            $(this).removeClass("active")
        }
    //    Otherwise, the click triggers three actions: close the active section, open
    //    the section that's clicked on, and mark it active.
        else if($(this).hasClass("handle")) {
            $(this).parent().addClass("active")
            $(this).addClass("active")
            $("#navigation .navAccordion div.active ul").slideDown(300)
        }
    });
}

// Student Life "Week in the Life..." profiles
function studentProfile() {
    var first = $("#profiles li a:first");
    first.addClass("active")
    $("#profiles div.studentName").append("<p>"+getText(first)+"</p>");
    $("#profiles").prepend("<img class='full' src='"+getHref(first)+"' />");
    
    $("#profiles li a").click(function() {
        
        //set active
        $("#profiles li a").removeClass("active");
        $(this).addClass("active");
        
        //swap p text
        $("#profiles div.studentName p").text(getText($(this)));
        
        //change img src
        $("#profiles img.full").attr("src", getHref($(this)));
        
        return false;
    });
}
function getText(item) {
    return item.children("span").text();
}
function getHref(item) {
    return item.attr("href");
}
 // HP Slideshow (Rotating Images)
/*
 * jQuery Cycle Lite Plugin
 * http://malsup.com/jquery/cycle/lite/
 * Copyright (c) 2008 M. Alsup
 * Version: 1.0 (06/08/2008)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.3 or later
 */
;(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery);

//  Photo gallery ------------------------------  
function gallery(increment, visibleItems) {
    if ($(".media").length == 1)
    {
    //Add buttons to scroll the photo gallery
    $(".photo #thumbs").prepend("<a href='#next' id='scroll-left'>Scroll Left</a>");
    $(".photo #thumbs").append("<a href='#previous' id='scroll-right'>Scroll Right</a>");
    //Add Container for media and text
    $(".media").prepend("<div id='showcase'></div>");    
    $("#showcase").prepend("<div id='image'><div id='imageWrapper'></div></div>");
    $(".photo #showcase").append("<p id='caption'></p>");
    //Wrap the photo gallery ul in a holder tag
    $(".photo #thumbs ul").wrap("<div id='slide-holder'></div>");
    var totalImages = $("#thumbs li").length;
    var galleryItem = $("#thumbs li:first");
    
    //Get the size of each item and any margin, padding, or border
    var totalDimensions;
    var itemSize = galleryItem.width();
    totalDimensions = new Array("margin-left", "margin-right", "padding-left", "padding-right");
    for (var n = 0; n < totalDimensions.length; n++) {
        itemSize += Number(galleryItem.css(totalDimensions[n]).replace("px", ""));
    }
    var incrementAmount = increment * itemSize;
    var visibleItemsSize = visibleItems * itemSize;
    var maxOffset = (totalImages * itemSize) - visibleItemsSize;

    //Add events to the scroll buttons to photo gallery
    var target = $(".photo #thumbs ul");
    var imageSet = 1;
    var curImage = 0
    $("#scroll-left").click(function() {
        scroll(target, "left", incrementAmount, maxOffset);
        imageSet --;
        curImage = curImage - 4
            if (curImage < 0)
            {
            curImage = 0
            }
            $("#counter").html("Displaying " +(curImage + 1)+ " - " +(curImage + 4)+ " <span>(of " +totalImages+ ")</span>")
        return false;
    });
    $("#scroll-right").click(function() {
        scroll(target, "right", incrementAmount, maxOffset);
        imageSet ++;
        curImage = curImage + 4
        if (curImage >= totalImages - 4)
        {
            curImage = totalImages - 4
        }    
            $("#counter").html("Displaying " +(curImage + 1)+ " - " +(curImage + 4)+ " <span>(of " +totalImages+ ")</span>")
        return false;
    });
    var totalItems = $("#thumbs li").length;
    var counter = 0;
    // Make first gallery item active by default
    $("#thumbs li:first").each(function() {
        var text = $(this).children("a").children("em").text();
        $("#counter").html("Displaying " +1+ " - " +4+ " <span>(of " +totalImages+ ")</span>")
        $(this).siblings().removeClass("active");
        $(this).addClass("active");
        
        var mediaContent = getMediaContent($(this));
        addMediaToPage($(this), 1, totalItems, mediaContent, text);
        
        $(".photo #showcase p").text(text);
    });
    var $thumbs = $("#thumbs li")
    $thumbs.each(function() {
        counter ++;
        var itemNumber = counter;
        var text = $(this).children("a").children("em").text();        
        var mediaContent = getMediaContent($(this));
        //When thumbnail clicked, set as active item and load content into main display area
        $(this).click(function() {
            addMediaToPage($(this), itemNumber, totalItems, mediaContent, text);
            return false;
        });
        //Add hover effect to gallery items
        $(this).mouseover(function() {
            $(this).addClass("jsHover");
        });
        $(this).mouseout(function() {
            $(this).removeClass("jsHover");
        });
        this.onclick = function() { return false; };
    });
}
}
/* 
 * parse the media url and determine the type of media file
 * return the appropriate html to display the media
 */
function getMediaContent(el) {
    var link = el.children("a").attr("href");
    var altText = el.children("a").children("img").attr("alt");
    var splitLink = link.split("?");
    var end = splitLink[0].lastIndexOf(".");
    var mediaType = splitLink[0].substring(end+1);
    var height, width;
    var mediaContent;
    //Generate code based on the type of media to be displayed
    switch(mediaType) {
        //Flash
        case "swf":
            //Get all the parameters for the flash movie
            var urlParams = link.split("?");
            link = urlParams[0];
            var properties = getQueryString(urlParams[1]);
            
            width = properties['width'];
            height = properties['height'];
            
            //If dimensions not defined or too large then set to max size
            if(!height || height > 270) height = 270;
            if(!width || width > 320) width = 320;
            
            flashVars = 'var1='+ properties['var1'];
            mediaContent = '<object class="item" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" height="' + height + '" width="' + width + '" align="top">'+
                '<param value="noscale" name="scale"/>'+
            '<param name="movie" value="'+ link +'">'+
            '<param name="quality" value="high">'+
            '<param value="'+ flashVars +'" name="flashvars"/>'+
            '<embed flashvars="'+ flashVars +'" height="' + height + '" pluginspage="http://www.macromedia.com/go/getflashplayer" src="' + link + '" type="application/x-shockwave-flash" width="' + width + '" quality="high">'+
            '<\/embed><\/object>';
            break;
        //Images
        case "jpg":
        case "jpeg":
        case "gif":
        case "png":
        case "bmp":
            mediaContent = '<img alt="' +  altText + '" class="item" src="' + link + '" />';
            break;
    }
    
    return mediaContent;
}
/*
 * After all the work has been done, this will add the html to the page
 * It also removes any existing media in the showcase
 */
function addMediaToPage(el, itemNumber, totalItems, mediaContent, text, wallpaper) {
    //Display Counter
    $("#showcase").empty();
    $("#showcase").prepend("<div id='image'><div id='imageWrapper'></div></div>");
    $(".photo #showcase").append("<p id='caption'></p>");
    //Set current item as active
    el.siblings().removeClass("active");
    el.siblings().removeClass("jsHover");
    el.addClass("active");
    //Remove existing content
    try {
        document.gallery-media.Stop();
    }
    catch(e){}
    $("#imageWrapper .item").css("display", "none");
    $("#imageWrapper").empty();
    
    //Add new content
    document.getElementById("imageWrapper").innerHTML = mediaContent;
    $(".photo #showcase p#caption").text(text);
    
    //Remove existing content
    try {
        document.gallery-media.Stop();
    }
    catch(e){}
    $("#imageWrapper .item").css("display", "none");
    $("#imageWrapper").empty();
    //Add new content
    document.getElementById("imageWrapper").innerHTML = mediaContent;
    $("#showcase p#caption").text(text);
}
/*
 * Get the dimensions of the media content from a query string
 * Returns an array containing width and height
 */
function getDimensions(params) {
    var dim = new Array();
    params = params.split("&");
    dim[0] = params[1].substring(6);
    dim[1] = Number(params[0].substring(7)) + 16;
    return dim;
}
function getQueryString(params) {
    var props = new Array();
    
    $(params.split("&")).each(function(i) {
        var param = this.split("=");
        props[param[0]] = param[1];
    });
    return props;
}
/*
 * Scroll the gallery the required amount in the specified direction
 */
function scroll(container, direction, amount, maxOffest) {
    var cur = container.css("left");
    if(cur == "auto") cur = 0;
    else cur = Number(cur.replace("px", ""));
    switch(direction) {
        case "left":
            cur = cur + amount;
            if(cur > 0) cur = 0;
            break;
        case "right":
            cur = cur - amount;
            if(cur < - maxOffest) cur = - maxOffest;
            break;
    }
    container.css("left", cur+"px");
}
$(function() {
            gallery(4, 4);
        });
 

/*
 * Added by Chad Goodrich
 */

function toggleDisplay(elm, display) {
    if (document.getElementById(elm)) {
        if (display == true) {
            document.getElementById(elm).style.display = "";
        }
        else if (display == false) {
            document.getElementById(elm).style.display = "none";
        }
        else if (document.getElementById(elm).style.display == "none") {
            document.getElementById(elm).style.display = "";
        }
        else {
            document.getElementById(elm).style.display = "none";
        }
    }
}