var overFlyout = false;

(function ($) {

    var min_footer_height = 317;

    $(document).ready(function(){
        updateFooterHeight();

        //set search box text
        $("div#search-box input[type=text]").val("Search this site");

        $("div#search-box input[type=text]").focus(function(){
            if ($(this).val()=="Search this site")
                $(this).val("");
        });

        $("div#search-box input[type=text]").blur(function(){
            if ($(this).val()=="")
                $(this).val("Search this site");
        });

        //Image/link to IWHS replacement for photo albums
        $(".media-gallery-collection .gallery-thumb-inner").prepend('<div class="mosaic-block mosaic-block-gallery bar2"><a href="" class="mosaic-overlay" style="bottom: -89px; left: 0px; "><div class="details"><br><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation.</p></div></a><a href="" class="mosaic-header"><div class="details"><br><p>SCHOOL CULTURE</p></div></a><a href="" class="mosaic-backdrop"><img typeof="foaf:Image" src="" alt=""></a></div>');

        $(".media-gallery-collection .gallery-thumb-inner").each(function(i) {
            var $this = $(this);
            var title = $this.closest(".node-media-gallery.node-teaser").children("h2").text();
            var link = $this.children(".media-gallery-thumb").attr("href");
            var image = $this.children(".media-gallery-thumb").children("img").attr("src");
            $this.find(".mosaic-header p").text(title);
            $this.find(".mosaic-block > a").attr("href", link);
            $this.find(".mosaic-backdrop > img").attr("src", image);
            $this.children(".media-gallery-thumb").hide();
        });

        //Image w/ Hovering Slider animation
        $('.bar2').mosaic({
            animation: 'slide',
            speed: 200,
            opacity: 1,
            preload: 0,
            anchor_x: 'bottom',
            anchor_y: 'left',
            hover_x: '0px',
            hover_y: '0px'
        });

        //Code for hiding main menu tooltips on mouse hover
        $('#superfish-1 a').hover(
            // In: Store and remove title
            function() {
                old_title = $(this).attr('title');
                $(this).attr('title','');
            },
            // Out: Replace title
            function() {
                $(this).attr('title', old_title);
            }
        );

        //Placeholder text
        $('label[for].placehold').overplaceholder();

        //Forms filter selection
        $('#forms-filter-block').find('a').click(function() {
            var newFilter = $(this).attr("title");
            $('#forms-filter-block').find('a').removeClass('current-form-filter');
            $(this).addClass('current-form-filter');
            if ($('#block-views-forms-available-view-fav').children('h2').html() != (newFilter.toUpperCase() + " FORMS")) {
                $('#edit-field-form-type-value').val(newFilter).trigger('change');


                $('#block-views-forms-available-view-fav').fadeOut(500, function() {
                    $(this).children('h2').html(newFilter.toUpperCase() + " FORMS");
                    $('#block-views-forms-available-view-fav').fadeIn(500);
                });

                if (!($(".view-forms-available-view").parent().hasClass("content"))) {
                    $(".view-forms-available-view").unwrap();
                }
            }
            return false;
        });

        //Text expander for sports recaps
        $(".block-views-feed.recap-view .views-field-body .field-content").expander({
            slicePoint: 300,
            expandText: 'read more &raquo;',
            userCollapseText: '&laquo; read less'
        });

        //contact email icon
        $("div#contact-info a.email").hover(
            function() {
                $(this).children("img").attr("src", $(this).children("img").attr("src").replace(".png", "_red.png"));
            },
            function() {
                $(this).children("img").attr("src", $(this).children("img").attr("src").replace("_red.png", ".png"));
            }
        );

        //diamond for active page
        $(".sf-menu.sf-style-triad_menu .active-trail a.sf-depth-1").addClass("active");
        $(".sf-menu.sf-style-triad_menu a.sf-depth-1.active").prepend("<span></span>");
    });

    //calendar functions
    $(".calendar-calendar .month-view .full td .inner div.day a, div.view-sports-event-schedule .month-view .full td .inner div.day a").live("click", function() {
        return false;
    });

    var cal_selector = ".calendar-calendar .month-view .full tr.date-box td .inner div.day a";

    $(".calendar-calendar .month-view .full tr.single-day td .event-wrapper div.flyout").live("mouseenter mouseleave", function(event) {
        if (event.type == "mouseenter") {
            overFlyout = true;
        }
        else if (event.type == "mouseleave") {
            $("div.flyout.visible").removeClass("visible");
            overFlyout = false;
        }
    });

    $(cal_selector).live("mouseenter mouseleave", function(event) {
        var $targ;

        if ($(this).is("a"))
            $targ = $(this);
        else
            $targ = $(this).children("a");

        if ($targ.length == 0)
            return false;

        var eventDate = $targ.closest("td").attr("date");
        var selector_beg = "td#calendar-";
        if ($targ.closest("td").attr("id").indexOf("sports_event_schedule") > -1) {
            selector_beg = "td#sports_event_schedule-";
        }

        if (event.type == "mouseenter") {
            setTimeout('onCalMouseEnter("' + selector_beg + '", "' + eventDate + '")', 10);
        }
        else if (event.type == "mouseleave") {
            setTimeout('onCalMouseLeave("' + selector_beg + '", "' + eventDate + '")', 10);
        }
        return false;
    });

    //sports schedule filtering
    $("ul.sports-filter li input[type=checkbox]").live("click", function(){
        if ($(this).attr("id") == "sports-filter-all-sports") {
            if ($(this).attr("checked")) {
                window.location.href = window.location.href.substring(0, window.location.href.indexOf("?"));
            }
        }
        else {
            if ($("#sports-filter-all-sports").attr("checked")) {
                $("#sports-filter-all-sports").attr("checked", "");
            }

            var sport = $(this).attr("id").replace("sports-filter-", "").replace(/_/g, " ");
            sport = sport.split(" ");
            var new_sport = "";
            for (var i = 0; i < sport.length; i++) {
                var s = sport[i];
                if (s != "and")
                    new_sport += s.charAt(0).toUpperCase() + s.slice(1) + " ";
                else
                    new_sport += s + " ";
            }
            sport = encodeURI(new_sport.trim());

            var urlTarget = "sport[]=" + sport + "&upcoming_sport[]=" + sport;
            if ($(this).attr("checked")) {
                //add to URL
                if (window.location.href.indexOf("?") > -1) {
                    window.location.href = window.location.href + "&" + urlTarget;
                }
                else {
                    window.location.href = window.location.href + "?" + urlTarget;
                }
            }
            else {
                //remove from URL
                var separtor = window.location.href.substr(window.location.href.indexOf(urlTarget)-1, 1);
                if (separtor == "&" || (separtor == "?" && window.location.href.indexOf("&") == -1)) {
                    window.location.href = window.location.href.replace(separtor + urlTarget, "");
                }
                else if (separtor == "?" && window.location.href.indexOf("&") > -1) {
                    window.location.href = window.location.href.replace(separtor + urlTarget, "").replace("&", "?");
                }
            }
        }
    });

    //open info direct links in new tab
    $("a").live("click", function(){
        if ($(this).attr("href").indexOf("infodirect") > -1)
            $(this).attr("target", "_blank");

        return true;
    });

    //sports recap archive navigation (in content, just here for .svn purposes)
//    jQuery("div.view-sports-recap-archive-navigation h3 span.date-display-single").each(function(){
//        var text = jQuery(this).html();
//        var year = jQuery(this).closest("div.item-list").children("ul").children("li:first").find("a").attr("rel");
//        var date = new Date(Date.parse(text + " 1, " + year));
//        var monthInt = date.getMonth() + 1;
//        var url = "?date=" + year + "-" + monthInt.toString();
//        var newLink = jQuery("<a></a>").attr("href", url).html(text);
//        jQuery(this).replaceWith(newLink);
//    });
//
//    var year_arr = [];
//    jQuery("div.view-sports-recap-archive-navigation div.item-list").children("ul").children("li").find("a").each(function(){
//        var year = jQuery(this).attr("rel");
//
//        if (year_arr.indexOf(year) > -1) {
//            return true;
//        }
//
//        year_arr.push(year);
//
//        var yearHeading = jQuery("<h2 class='year'>" + year + "</h2>");
//        jQuery(this).closest("div.item-list").before(yearHeading);
//    });

    //news archive navigation (in content, just here for .svn purposes)
//    jQuery("div.view-news-archive-navigation h3 span.date-display-single").each(function(){
//        var text = jQuery(this).html();
//        var year = jQuery(this).closest("div.item-list").children("ul").children("li:first").find("a").attr("rel");
//        var date = new Date(Date.parse(text + " 1, " + year));
//        var monthInt = date.getMonth() + 1;
//        var url = "?date=" + year + "-" + monthInt.toString();
//        var newLink = jQuery("<a></a>").attr("href", url).html(text);
//        jQuery(this).replaceWith(newLink);
//    });
//
//    var year_arr = [];
//    jQuery("div.view-news-archive-navigation div.item-list").children("ul").children("li").find("a").each(function(){
//        var year = jQuery(this).attr("rel");
//
//        if (year_arr.indexOf(year) > -1) {
//            return true;
//        }
//
//        year_arr.push(year);
//
//        var yearHeading = jQuery("<h2 class='year'>" + year + "</h2>");
//        jQuery(this).closest("div.item-list").before(yearHeading);
//    });

    //rotator link update code (in content, just here for .svn purposes)
    //modify based on page name
//    var curSlideNum = ($(".views-slideshow-controls-bottom").find(".views-slideshow-pager-field-item.active").find(".views-content-counter").html().trim() - 1).toString();
//    var curSlideLink = $("#views_slideshow_cycle_div_student_resources_rotator-why_triad_rotator_block_" + curSlideNum).find(".views-field-field-slide-link .field-content a").attr("href");
//    $("#read-more-banner a").attr("href", curSlideLink);

    $("form#subForm input:submit").live("click", function(){
        // First, disable the form from submitting
        $('form#subForm').submit(function() { return false; });

        var str = $("form#subForm").serialize();

        // Add form action to end of serialized data
        // CDATA is used to avoid validation errors
        //<![CDATA[
        var serialized = str + "&action=" + $("form#subForm").attr("action");
        // ]]>

        $.ajax({
            url: "proxy.php",
            type: "POST",
            data: serialized,
            success: function(data){
              // Server-side validation
              if (data.search(/invalid/i) != -1) {
                alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
              }
              else
              {
                  alert('You were successfully added to the subscriber list.');
                  resetForm();
              }
            },
            error: function(data) {
                alert('An error occured.  Please try again later.');
            }
        });
    });

    function resetForm() {
        $("form#subForm input[type='text']").val("");
    }

    $(window).resize(function(){
        updateFooterHeight();
    });

    function updateFooterHeight() {
        //find out how short the footer mid section is.
        var extra_height = calcFooterMidHeightDiff($("#wrap").height(), $("#header").height(), $("#main").height(), $("#footer-mid").height());

        //expand footer mid section by adding the height diff to it's current height
        extra_height += $("#footer-mid").height();
        if (extra_height > min_footer_height)
            $("#footer-mid").height(extra_height+"px");
        else
            $("#footer-mid").height(min_footer_height+"px");
    }
})(jQuery);

function calcFooterMidHeightDiff(wrap_height, header_height, main_height, footer_mid_height) {
    return wrap_height - (header_height+main_height+footer_mid_height);
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function onCalMouseEnter(selector_beg, eventDate) {
    if (overFlyout)
        return false;

    //close any existing flyouts
    jQuery("div.flyout").removeClass("visible");
    jQuery(selector_beg + eventDate + "-0 div.event-wrapper div.flyout").addClass("visible");
}
function onCalMouseLeave(selector_beg, eventDate) {
    if (overFlyout)
        return false;

    jQuery(selector_beg + eventDate + "-0 div.event-wrapper div.flyout").removeClass("visible");
};
/*
	Mosaic - Sliding Boxes and Captions jQuery Plugin
	Version 1.0.1
	www.buildinternet.com/project/mosaic
	
	By Sam Dunn / One Mighty Roar (www.onemightyroar.com)
	Released under MIT License / GPL License
*/

(function(a){if(!a.omr){a.omr=new Object()}a.omr.mosaic=function(c,b){var d=this;d.$el=a(c);d.el=c;d.$el.data("omr.mosaic",d);d.init=function(){d.options=a.extend({},a.omr.mosaic.defaultOptions,b);d.load_box()};d.load_box=function(){if(d.options.preload){a(d.options.backdrop,d.el).hide();a(d.options.overlay,d.el).hide();a(window).load(function(){if(d.options.animation=="fade"&&a(d.options.overlay,d.el).css("opacity")==0){a(d.options.overlay,d.el).css("filter","alpha(opacity=0)")}a(d.options.overlay,d.el).fadeIn(500,function(){a(d.options.backdrop,d.el).fadeIn(500)});d.allow_hover()})}else{a(d.options.backdrop,d.el).show();a(d.options.overlay,d.el).show();d.allow_hover()}};d.allow_hover=function(){switch(d.options.animation){case"fade":a(d.el).hover(function(){a(d.options.overlay,d.el).stop().fadeTo(d.options.speed,d.options.opacity)},function(){a(d.options.overlay,d.el).stop().fadeTo(d.options.speed,0)});break;case"slide":startX=a(d.options.overlay,d.el).css(d.options.anchor_x)!="auto"?a(d.options.overlay,d.el).css(d.options.anchor_x):"0px";startY=a(d.options.overlay,d.el).css(d.options.anchor_y)!="auto"?a(d.options.overlay,d.el).css(d.options.anchor_y):"0px";var f={};f[d.options.anchor_x]=d.options.hover_x;f[d.options.anchor_y]=d.options.hover_y;var e={};e[d.options.anchor_x]=startX;e[d.options.anchor_y]=startY;a(d.el).hover(function(){a(d.options.overlay,d.el).stop().animate(f,d.options.speed)},function(){a(d.options.overlay,d.el).stop().animate(e,d.options.speed)});break}};d.init()};a.omr.mosaic.defaultOptions={animation:"fade",speed:150,opacity:1,preload:0,anchor_x:"left",anchor_y:"bottom",hover_x:"0px",hover_y:"0px",overlay:".mosaic-overlay",backdrop:".mosaic-backdrop"};a.fn.mosaic=function(b){return this.each(function(){(new a.omr.mosaic(this,b))})}})(jQuery);;
/*!
 * jQuery overplaceholder Plugin 1.0.1
 *
 * http://diapeira.1gb.ru/diapeira/jquery-plugins/overplaceholder.html
 * http://plugins.jquery.com/project/overplaceholder
 *
 * Copyright (c) 2011 Amphiluke
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(f){var b=function(k,j){var m=f("<span class='oph-wrapper'></span>");var l=j.attr("id");if(l){m.attr("id","oph-"+l)}j.wrap(m);k.insertAfter(j)},c=function(l,j){if(!j){j=f("#"+l.attr("for"))}var k=j.offset(),m=j.parent().offset();l.css({left:(k.left-m.left)+"px",top:(k.top+((j.outerHeight()-l.outerHeight())>>1)-m.top)+"px"})},a=function(j,k){if(j.val().replace(k,"")===""){j.val("")}return j.val()},d=function(k,j){k=k.get(0);try{return(k.options[k.selectedIndex].text.replace(j,""))}catch(l){return""}},h=function(j,k){var l=(j.get(0).nodeName.toUpperCase()=="SELECT")?d:a;return l(j,k)},g=function(l,j,k){l.click(function(){k.onhide.call(this)});l.bind("parentformreset",function(){var m=j.get(0).defaultValue;if(!m||(m.replace(k.reEmpty,"")==="")){k.onshow.call(l.get(0))}else{k.onhide.call(l.get(0))}});if(("unselectable" in l.get(0))||("expando" in document)){l.attr("unselectable","on")}},i=function(l,j,k){j.focus(function(){if(!h(j,k.reEmpty)){k.onhide.call(l.get(0))}}).blur(function(){if(!h(j,k.reEmpty)){k.onshow.call(l.get(0))}})},e=function(l,k){var j=f("#"+l.attr("for"));if(j.length==0){return false}l.addClass("overplaceholder");b(l,j);if(typeof k.onafterWrap=="function"){k.onafterWrap(l,j)}c(l,j);if(h(j,k.reEmpty)){k.onhide.call(l.get(0))}g(l,j,k);i(l,j,k)};f.fn.overplaceholder=function(k){var j={},l={onhide:function(){f(this).hide()},onshow:function(){f(this).show()},onafterWrap:null,reEmpty:/^$/};f.extend(j,l,k);return this.each(function(){e(f(this),j)})};f(document).ready(function(){var j=(f.support.submitBubbles)?"live":"bind";f("form")[j]("reset",function(){f(".overplaceholder",this).trigger("parentformreset")})})})(jQuery);;
/*!
 * jQuery Expander Plugin v1.1
 *
 * Date: Mon Sep 12 11:39:53 2011 EDT
 * Requires: jQuery v1.3+
 *
 * Copyright 2011, Karl Swedberg
 * Dual licensed under the MIT and GPL licenses (just like jQuery):
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 *
 *
 *
*/
(function(c){c.expander={version:"1.1",defaults:{slicePoint:100,preserveWords:true,widow:4,expandText:"read more",expandPrefix:"&hellip; ",summaryClass:"summary",detailClass:"details",moreClass:"read-more",lessClass:"read-less",collapseTimer:0,expandEffect:"fadeIn",expandSpeed:250,userCollapse:true,userCollapseText:"read less",userCollapsePrefix:" ",onSlice:null,beforeExpand:null,afterExpand:null,onCollapse:null}};c.fn.expander=function(E){function F(b,e){var g=e?"div":"span";return[b.summary,e?"":
b.moreLabel,"<"+g,' class="'+b.detailClass+'">',b.details,"</"+g+">"].join("")}function u(b,e){if(b.lastIndexOf("<")>b.lastIndexOf(">"))b=b.slice(0,b.lastIndexOf("<"));if(e)b=b.replace(G,"");return b}function v(b,e){e.hide();e.prev("span."+b.moreClass).show().length||e.parent().children("div."+b.summaryClass).show().find("span."+b.moreClass).show()}function H(b,e,g){if(b.collapseTimer)w=setTimeout(function(){v(b,e);c.isFunction(b.onCollapse)&&b.onCollapse.call(g,false)},b.collapseTimer)}var x=c.extend({},
c.expander.defaults,E),I=/^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i,G=/(&(?:[^;]+;)?|\w+)$/,J=/<\/?(\w+)[^>]*>/g,y=/<(\w+)[^>]*>/g,z=/<\/(\w+)>/g,K=/^<[^>]+>.?/,w;this.each(function(){var b,e,g,q,j,k,l,t,A=[],r=[],m={},n=this,f=c(this),B=c([]),a=c.meta?c.extend({},x,f.data()):x;k=!!f.find("."+a.detailClass).length;var o=!!f.find("*").filter(function(){return/^block|table|list/.test(c(this).css("display"))}).length,s=(o?"div":"span")+"."+a.detailClass,L="span."+a.moreClass,M=a.expandSpeed||
0,p=c.trim(f.html());b=c.trim(f.text());var d=p.slice(0,a.slicePoint);if(!(b.length<=a.slicePoint&&!k)){c.each(["onSlice","beforeExpand","afterExpand","onCollapse"],function(h,i){m[i]=c.isFunction(a[i])});d=u(d);for(summTagless=d.replace(J,"").length;summTagless<a.slicePoint;){newChar=p.charAt(d.length);if(newChar=="<")newChar=p.slice(d.length).match(K)[0];d+=newChar;summTagless++}d=u(d,a.preserveWords);q=d.match(y)||[];j=d.match(z)||[];g=[];c.each(q,function(h,i){I.test(i)||g.push(i)});q=g;e=j.length;
for(b=0;b<e;b++)j[b]=j[b].replace(z,"$1");c.each(q,function(h,i){var C=i.replace(y,"$1"),D=c.inArray(C,j);if(D===-1){A.push(i);r.push("</"+C+">")}else j.splice(D,1)});r.reverse();if(!f.find(s).length){b=p.slice(d.length);if(b.split(/\s+/).length<a.widow&&!k)return;k=r.pop()||"";d+=r.join("");b=A.join("")+b;a.moreLabel='<span class="'+a.moreClass+'">'+a.expandPrefix;a.moreLabel+='<a href="#">'+a.expandText+"</a></span>";if(o){d='<div class="'+a.summaryClass+'">'+d+a.moreLabel;d+=k+"</div>";b=p;a.expandPrefix=
""}else d+=k;a.summary=d;a.details=b;if(m.onSlice)a=(g=a.onSlice.call(n,a))&&g.details?g:a;o=F(a,o);f.html(o)}l=f.find(s);t=f.find(L);l.hide();t.find("a").unbind("click.expander").bind("click.expander",function(h){h.preventDefault();t.hide();B.hide();m.beforeExpand&&a.beforeExpand.call(n);l[a.expandEffect](M,function(){l.css({zoom:""});m.afterExpand&&a.afterExpand.call(n);H(a,l,n)})});B=f.find("div."+a.summaryClass);a.userCollapse&&!f.find("span."+a.lessClass).length&&f.find(s).append('<span class="'+
a.lessClass+'">'+a.userCollapsePrefix+'<a href="#">'+a.userCollapseText+"</a></span>");f.find("span."+a.lessClass+" a").unbind("click.expander").bind("click.expander",function(h){h.preventDefault();clearTimeout(w);h=c(this).closest(s);v(a,h);m.onCollapse&&a.onCollapse.call(n,true)})}});return this};c.fn.expander.defaults=c.expander.defaults})(jQuery);
;

