/* 
 * JavaScript created for Sarah Lawrence College slc.edu
 * Created by Stuart Basden stu@t.apio.ca 2011
 * Released as Open Source under MIT
 * 
 */

// Console log debugger
if (!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0, len = names.length; i < len; ++i) {
        window.console[names[i]] = function(){};
    }
}

if (typeof Modernizr === 'undefined') {Modernizr = {touch:false};}
var touchOrMouse = Modernizr.touch ? 'click' : 'mouseover', toggleOrHover = Modernizr.touch ? 'toggle' : 'hover';
//var touchOrMouse = Modernizr.touch ? 'mouseover' : 'click', toggleOrHover = Modernizr.touch ? 'hover' : 'toggle';

if (!API) {var API = 0}

jQuery(function($) {

    // Get location.search as JSON
    var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
    $.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });


    // Using core-dev CSS and JS
    if (queryJSON.test == 'dev') {
        $("link[href='http://www.slc.edu/core/v5.0/css/styles.css']").attr('href','http://www.slc.edu/core-dev/v5.0/css/styles.css');
        $.getScript('/core-dev/v5.0/js/slc.scripts.js');
        $("script[src='/core/v5.0/js/slc.scripts.js']").remove();
        return;
    }


    // Load in the menu JSON
    $.getScript("http://www.slc.edu/core/v5.0/xml/menuJSON.js");
    
    
    // Insert slideshows
    if (API) { // The API variable is the URL of the Director-made JSON or XML, which is output by Cascade by the relevant pages
        if (typeof(window.xmlSettings) == "undefined") {var xmlSettings = {}}
        if (API.indexOf("study") == -1) {
            JSONrequest(API,parseSlidesJSON,'#gallery',window.xmlSettings);
        } else {
            // Areas of Study pages
            XMLrequest(API,parsePageBG,'#pageBGSlideshow',window.xmlSettings);
        }
    }


    // Scroll to ID on page
    var searchJSON = getUrlVars();
    if (searchJSON.name) {
        $("body,html,document").delay(200).animate({
            scrollTop: $("#"+searchJSON.name).offset().top
        }, 1000);
    }
    // Add toTop link on long pages
    if ($('body').height() > 2000) {$().UItoTop();}


    // Mobile switcher
    if (queryJSON.test == 'mob' 
      || $.cookie("viewMobileVersion") != 'false' && screen.width <= 960 && $('#mobileSwitcher').length && $('#mobileSwitcher .remember').attr('href') != undefined 
      && $('#content-heading').text().indexOf('404:') === -1 && $('#content-heading').text().indexOf('410:') === -1 ) {
        $('#mobileSwitcher').show();
        $('body').delay(1000).animate({'margin-top':'68px'},500,'easeOutExpo');
        
        /* Change commenting on next 5 lines for cookies */
        /*$('#mobileSwitcher .gotomobile').attr('href',function() {return $('#mobileSwitcher .yestomobile .remember').attr('href')});*/
        $('#mobileSwitcher .gotomobile').click(function() {
            $('#mobileSwitcher .yestomobile').show();
            $('#mobileSwitcher .options').hide();
        });
        
        $('#mobileSwitcher .nomobile').click(function() {
            $('#mobileSwitcher .notomobile').show();
            $('#mobileSwitcher .options').hide();
        });
        $('#mobileSwitcher .yestomobile .remember').click(function() {
            $.cookie("viewMobileVersion", true, { expires: 365, path: '/' });
        });
        $('#mobileSwitcher .notomobile .remember').click(function() {
            $.cookie("viewMobileVersion", 'false', { expires: 365, path: '/' });
            $('body').animate({'margin-top':'0'},500,'easeOutExpo', function() {
                $('#mobileSwitcher').remove();
            });
        });
        $('#mobileSwitcher .notomobile .tryit').click(function() {
            $('body').animate({'margin-top':'0'},500,'easeOutExpo', function() {
                $('#mobileSwitcher').remove();
            });
            
        });
    }


    // Search
    if (!Modernizr.input.placeholder) {
        $("input[placeholder]").placeholder({ placeholderTextColour: "#999" });
    }
    // Search pages
    $('#siteimprove_searchinput').focus();
    $('#siteimprove_searchinput').autocomplete({
        serviceUrl: 'http://search.slc.edu/autocomplete/autocomplete.aspx?callback=?',
        submitButtonName: '#siteimprove_searchinput',
        width:250
    });
    $('#q').autocomplete({
        serviceUrl: 'http://search.slc.edu/autocomplete/autocomplete.aspx?callback=?',
        submitButtonName: '#q',
        width:216
    });


    // Info for... drop-down
    $('#search #infoFor .infoFor').toggle(function() {
        $(this).next().slideDown('fast');
    }, function() {
        $(this).next().slideUp('fast');
    });
    
    
    // A Deeper Education toggler
    $('.expander').css('height','0px');
    $('#deeper')[toggleOrHover](function() {
        $('#deeper .expander').stop().animate({'height':$('.expanderContent').height()+'px'}).css('cursor','auto');
        $('#deeper .togglerArrow').css('background-position','-180px -150px');
        $('#deeper .togglerArrow').stop().animate({shadow: '0 0 0 #fff'});
    }, function() { 
        $('#deeper .expander').stop().animate({'height':'0px','padding-top':'20px'});
        $('#deeper .togglerArrow').css('background-position','-180px -130px');
        $('#deeper .togglerArrow').stop().animate({shadow: '0 0 12px #fff'});
        $('.tooltip').hide();
    });
    $('#deeper a, #deeper dl').click(function(e) {e.stopPropagation();});
    // End Deeper Education toggler
    
    
    // Deeper Tooltips
    tooltips('dons');
    tooltips('nars');
    tooltips('meet');
    tooltips('disc');
    tooltips('eval');
    
    function tooltips(tip) {
        $('#'+tip)[toggleOrHover](function() {
            $('.tooltip').hide();
            $('.'+tip).slideDown('fast');
        }, function() {
            $('.tooltip').hide();
        });
    }


    // Carousel cycler
    if ($('#carousel').length) {
        var slideCount = Math.floor(Math.random()*$('#carousel').children().length);
        $('#carousel').css({'margin-bottom':0}).after('<div class="carouselPager"><div id="carouselPrev">&lt;</div><div id="carouselPager"></div><div id="carouselNext">&gt;</div></div>').cycle({
            fx: "scrollHorz",
            easing: "easeOutExpo",
            timeout: 10000,
            delay: 4000,
            startingSlide: slideCount,
            pager: "#carouselPager",
            next: "#carouselNext",
            prev: "#carouselPrev"
        });
    } // */


    // News and Events
    $('#newsEventsItems').cycle({
        fx: "cover",
        height: "330px",
        timeout: 0,
        speed: 500
    });
    $('#newsEventsMore').cycle({
        fx: "fade",
        timeout: 0,
        speed: 500
    });
    
    // Go to relevant category if hash is set
    var hash = window.location.hash;
    if (hash.indexOf('events') != -1) {newsEventsCycler('-125px',1);$('#newsEvents .events').addClass('active');}
    if (hash.indexOf('dates') != -1) {newsEventsCycler('-50px',2);$('#newsEvents .dates').addClass('active');}
    
    // Control pager
    $('#newsEvents .pager .news a').attr('href','#newsBlock');
    $('#newsEvents .pager .events a').attr('href','#eventsBlock');
    $('#newsEvents .pager .news')[touchOrMouse](function() {
        newsEventsCycler('-190px',0);
        $(this).addClass('active');
    });
    $('#newsEvents .pager .events')[touchOrMouse](function() {
        newsEventsCycler('-125px',1);
        $(this).addClass('active');
    });
    $('#newsEvents .pager .dates')[touchOrMouse](function() {
        newsEventsCycler('-50px',2);
        $(this).addClass('active');
    });
    
    function newsEventsCycler(bgPos,slide) {
        $('#newsEvents .pager .active').removeClass('active');
        $('#newsEventsItems').cycle(slide);
        $('#newsEventsMore').cycle(slide);
        $('#newsEvents .pager').stop().animate({backgroundPosition: bgPos +' -323px'});
    } // newsEventsCycler
    
    // Animate News and Events tags (previously in behaviors.js, cleaned up)
    $('#newsEvents li span em').hide();
    $('#newsEvents li span').css('height','auto');
    $('#newsEvents li').hover(function(){
        $(this).children("a").children("span").children("em").slideToggle("fast");
    }, function(){
        $(this).children("a").children("span").children("em").slideToggle("fast");
    });


    // Study Pages

    if ($('#drawerHandle').length > 0) {
        var handleDelay, initCloseDrawer = setTimeout(closeDrawer,1200);
        // Make the drawerHandle 'float' down the screen
        positionDrawerHandle();
        $(window).scroll(function() {
            positionDrawerHandle();
        });
    }
    function positionDrawerHandle() {
        if ($("body,html,document").scrollTop() >= 150) {
            var drawerBottomCoord = $('#drawerRunners').height()-23;
            if ($("body,html,document").scrollTop() >= drawerBottomCoord) {
                $('#drawerHandle').css('margin-top','0').attr('class','').addClass('pinnedBottom');
            } else {
                $('#drawerHandle').css('margin-top','0').attr('class','').addClass('floating');
            }
        } else {
            $('#drawerHandle').attr('class','').addClass('pinnedTop');
        }
    } // End positionDrawerHandle
    function correctDrawerHandle() { // Slide the handle up if it is below the drawer after the profiles have cycled
        var drawerBottomCoord = $('#drawerRunners').height()-23;
        if ($("body,html,document").scrollTop() >= drawerBottomCoord) {
            $('#drawerHandle').animate({'margin-top':$('#drawerRunners').height()-$("body,html,document").scrollTop()-23}, 700, function() {redrawWebkit();});
        }
    } // End correctDrawerHandle

    // Animate the drawer opening and closing
    $('#drawerHandle').click(function() {
        // If the handle animation is running, cancel it
        if(handleDelay) {clearTimeout(handleDelay);handleDelay='';}
        // Open the drawer
        if ($('#drawerRunners').hasClass('drawerClosed')) {
            $('#drawerRunners').stop().animate({'width':'400px'},400, 'easeOutExpo', function() {redrawWebkit();}).removeClass('drawerClosed');
            $('#drawerHandle').removeAttr('style');
            $('#drawer').css({'box-shadow':'-2px 2px 2px rgba(0,0,0,0.3)','-moz-box-shadow':'-2px 2px 2px rgba(0,0,0,0.3)','-webkit-box-shadow':'-2px 2px 2px rgba(0,0,0,0.3)'});
        } else {
            closeDrawer(); // Close it
        }
    }); 
    function closeDrawer() {
        $('#drawerRunners').stop().animate({'width':'40px'},800, 'easeOutExpo', function() {
            $('#drawerRunners').addClass('drawerClosed');
            redrawWebkit();
            if(handleDelay) {clearTimeout(handleDelay);handleDelay='';}
            handleDelay = setTimeout(animateDrawerHandle,10000);
            function animateDrawerHandle() {
                $('#drawerHandle').animate({backgroundPosition:'-37px 0'},1000, function() {
                    if(handleDelay) {clearTimeout(handleDelay);handleDelay='';}
                    handleDelay = setTimeout(animToOpen,5000);
                    function animToOpen() {
                        $('#drawerHandle').animate({backgroundPosition:'-74px 0'},1000, function() {
                            $('#drawerHandle').removeAttr('style');
                            if(handleDelay) {clearTimeout(handleDelay);handleDelay='';}
                            handleDelay = setTimeout(animateDrawerHandle,10000);
                        });
                    }
                });
            }
        });
        $('#drawer').css({'box-shadow':'none','-moz-box-shadow':'none','-webkit-box-shadow':'none'});
    } // End closeDrawer
    function redrawWebkit() { // Correct for webkit bug
        $('#drawerHandle').fadeOut(1, function() {
            $('#drawerHandle').show();
        });
    }


    // Profiles cycler
    if ($('.profiles').length) {
        $('.profiles').parent().prepend('<div class="pager prePager profilesPager"><a href="#Prev" class="profilesPrev">&lt;</a> <span class="pagerNumbers"></span> <a href="#Next" class="profilesNext">&gt;</a></div>');
        $('.profiles').parent().append('<div class="pager apPager profilesPager"><a href="#Prev" class="profilesPrev">&lt;</a> <span class="pagerNumbers"></span> <a href="#Next" class="profilesNext">&gt;</a></div>');
        $('.profiles').cycle({
            fx: "scrollVert",
            easing: "easeOutExpo",
            timeout: 0,
            pager: ".profilesPager .pagerNumbers",
            next: ".profilesNext",
            prev: ".profilesPrev",
            before: resizeCycle,
            after: correctDrawerHandle
        });
    } // */


    // Study text controller
    $('.studyContainer .item .description').wrap('<div class="descriptionWrapper" />').parent().css({'overflow':'hidden','height':'8.5em','border-bottom':'1px solid silver'});
    $('.studyContainer .item').each(function() {
        $(this).append('<a href="#" class="expander">Expand</a>')
        $(this).children('.discipline-links').clone().appendTo($(this).children().children('.description'));
    });
    $('.studyContainer .item .expander').click(function() {
        closeDrawer();
        var fullHeight = $(this).prev().children('.description').height();
        if ($(this).prev().hasClass('expanded')) {
            $(this).removeClass('expanded').html('Expand');
            $(this).prev().removeClass('expanded');
            $(this).prev().animate({'height':'8.5em'});
        } else {
            $(this).addClass('expanded').html('Collapse');
            $(this).prev().addClass('expanded');
            $(this).prev().animate({'height':fullHeight});
        }
        return false;
    });


    // Graduate Study page
    $('.accordion').liteAccordion({
        containerWidth : 880,
        containerHeight : 300, 
        headerWidth : 70,
        theme: 'gradAccordion',
        easing: "easeOutExpo"
    });


    // News Stream
    // Categories generation
    if ($('.news-stream').length > 0) {
        var activeCategories = '', activeCategory = '', newsCategories = {'news-release':'News Release', 'news-itn':'SLC In The News', 'news-announcement':'Announcements', 'news-buzz':'Buzz', 'news-brief':'News Brief', 'news-feature':'Features', 'news-video':'Videos', 'news-sports':'Sports'};
        $.each(newsCategories, function(i) {
            if ($('ul.news-stream .'+i).length > 0) {activeCategories += '<div class="'+i+'">'+this+' <span class="categoryCount">'+$('ul.news-stream .'+i).length+'</span></div> '}
        });
        $('ul.news-stream').parent().prepend('<div id="newsCategories"><span class="clearCategory">Clear</span>'+activeCategories+'</div>');
        $('#content-sidebar .sleeve').append('<div id="newsFilter">News filtering: <div class="currentFilter">showing all items</div></div>');
    }

    // Tag Cloud generation
    var tagJSON = {}, tagCloudHTML = '', activeTag = '', newsItems = $('.news-stream li').length;
    if (newsItems < 128) {newsItems=128;} // Ensure the tagSizes are differentiated
    $('ul.news-stream li .tags span').each(function() { // Build the JSON
        var thisTag = $(this).attr('class');
        if (tagJSON[thisTag]) {
            tagJSON[thisTag]++;
        } else {
            tagJSON[thisTag] = 1;
        }
    });
    // console.log(tagJSON);
    $.each(tagJSON, function(i,v) {
        var tagSize='tags1';
        if (v > 1) {
            if (v <= newsItems/64) {tagSize="tags2"} else
            if (v <= newsItems/32) {tagSize="tags3"} else
            if (v <= newsItems/16) {tagSize="tags4"} else
            if (v <= newsItems/8) {tagSize="tags5"} else
            if (v <= newsItems/4) {tagSize="tags6"} else
            {tagSize="tags7"}
        }
        tagCloudHTML += '<span class="'+tagSize+' '+i+'">'+i.replace('tag-','').replace(/-/g,' ')+'</span> '; // Create the tags
    });
    $('.tagCloud').html('<div class="clearTag">Clear</div>'+tagCloudHTML); //*/
    
    // Hovering
    $('ul.news-stream li').hover(function() {
        $(this).animate({backgroundColor:'#F7F4D4'}).children('.tags').slideDown('fast');
    }, function() {
        $(this).stop().attr('style','').children('.tags').slideUp('fast');
    });
    // $('ul.news-stream li a').click(function(e) {e.stopImmediatePropagation();});

    // Tag and category clicking
    $('#newsCategories div').click(function() {
        if ($(this).hasClass('activeCategory')) {return;}
        $('.activeCategory').removeClass('activeCategory');
        activeCategory = $(this).attr('class');
        $(this).addClass('activeCategory');
        showTags(0);
    });
    $('.tagCloud span').click(function() {
        if ($(this).hasClass('activeTag')) {return;}
        $('.activeTag').removeClass('activeTag');
        var tag = $(this).attr('class').replace(/tags[0-9]\s/,'');
        $(this).addClass('activeTag');
        activeTag = tag;
        showTags(1);
    });
    $('.tags span').click(function() {
        var tag = $(this).attr('class');
        $('.activeTag').removeClass('activeTag');
        $('.tagCloud .'+tag).addClass('activeTag');
        activeTag = tag;
        showTags(0);
    });
    // Clearing
    $('#newsCategories .clearCategory').click(function() {
        $('.activeCategory').removeClass('activeCategory');
        activeCategory = '';
        showTags(0);
    });
    $('.tagCloud .clearTag').click(function() {
        $('.activeTag').removeClass('activeTag');
        activeTag = '';
        showTags(0);
    });
    // Show the relevant news items
    function showTags(cloudClicked) {
        var activeItems = '', currentFilter = '';
        if (activeTag != '') {activeItems += '.'+activeTag.replace('tag-','');}
        if (activeCategory != '') {activeItems += '.'+activeCategory;}
        //console.log(activeItems);
        if ($('ul.news-stream li'+activeItems).length > 0) {
            $('ul.news-stream li').hide();
            $('ul.news-stream li'+activeItems).show();
        } else {
            if (cloudClicked) {
                $('.activeCategory').removeClass('activeCategory').css({backgroundColor:'#c00'}).animate({backgroundColor:'#eee'}, 900, function() {$(this).attr('style','')});
                activeCategory = '';
            } else {
                $('.activeTag').removeClass('activeTag').css({backgroundColor:'#c00'}).animate({backgroundColor:'#fff'}, 900, function() {$(this).attr('style','')});
                activeTag = '';
            }   
            showTags();
        }
        if (activeTag) {
            if (activeCategory) {
                currentFilter = newsCategories[activeCategory] +' + '+ activeTag.replace('tag-','').replace(/-/g,' ');
            } else {
                currentFilter = activeTag.replace('tag-','').replace(/-/g,' ');
            }
        } else {
            if (activeCategory) {
                currentFilter = newsCategories[activeCategory];
            } else {
                currentFilter = "showing all items"
            }
        }
        //console.log(currentFilter);
        $('#newsFilter .currentFilter').html(currentFilter).parent().stop().css({backgroundColor:'#EFDE7B'}).delay(500).animate({backgroundColor:'#F7F4D4'}, 900, function() {$(this).attr('style','')});
    }


    // Events
    $('.eventTiles .tile').live('click', function(e) {
        if ($(this).hasClass('tileSpaceholder') || $('.is-overlaying').length != -1) {
            if ($(this).hasClass('tileSpaceholder')) {var noNewOverlay = 1;}
            if ($(this).hasClass('is-overlaying')) {
                var noNewOverlay = 1;
                $("body,html,document").animate({
                    scrollTop: $("#"+$(this).attr('id').substring(1)).offset().top
                }, 500);
            }
            $('.tile.is-overlaying').remove();
            $('.tileSpaceholder').removeClass('tileSpaceholder');
            if (noNewOverlay) {
                return;
            }
        }
        $(this).after($(this).clone()
            .addClass('is-overlaying')
            .css({'max-width':$('#content-main').width()-50})
            .attr('id','C'+$(this).attr('id'))
        ).addClass('tileSpaceholder');
        var elink = 'http://' + window.location.host + window.location.pathname + $('.is-overlaying .eventLink').attr('href').replace('index.html','');
        $('.is-overlaying .eventLink').text(elink).selText().before('<div>Right-click URL for options:</div>');
    });
    if (queryJSON.ref === "event") {$(".eventTiles "+window.location.hash).click();}


    // Catalogue pages related courses
    $('.course-links .course-list, .course-links .related-course-list').masonry({itemSelector : 'a',columnWidth : 160});

    // Catalogue Area expander
    $('.discipline-description').wrap('<div class="longTextWrapper" />').parent().after('<a href="#" class="longTextExpander">Expand</a>').parent().addClass('catalogueArea');
    controlExpander('.catalogueArea .longTextExpander','.discipline-description','5.4em');

    // Adding Catalogue Search to left nav
    $('body.catalogue h3.section-heading').append('<div class="catalogueSearchBox"><form method="get" action="http://search.slc.edu/search.aspx"><input type="hidden" value="1451594033" name="pckid"/><input type="hidden" value="90781508" name="aid"/><input type="text" placeholder="Catalogue Search" autocomplete="off" name="sw" class="catalogueSearchInput"/><input type="submit" value="Go" class="searchSubmit"/></form></div>');
    if (!Modernizr.input.placeholder) {$('.catalogueSearchBox').prepend("<a>Search the Catalogue:</a>");}

    // Faculty Bio pop-ups
    if(typeof(faculty) != "undefined"){
    $('.course-faculty a.faculty-link, .related-course a.faculty-link').each(function() {
        var facID = $(this).attr('class').replace('faculty-link ','');
        if (faculty[facID].bio) {$(this).addClass('expander');}
    });
    $('.course-faculty a.faculty-link, .related-course a.faculty-link').click(function(e) {
        var facID = $(this).attr('class').replace('faculty-link ','').replace(' expander',''), $facLink = $(this), facImg = '';
        if (faculty[facID].bio) {
            // Only act if the bio does not already exist
            if ($facLink.parent().children('.facultyBio.'+facID).length == 0) {
                e.preventDefault();
                if (faculty[facID].img) {facImg = '<a href="'+$facLink.attr('href')+'" class="facultyLink"><img src="'+faculty[facID].img+'" alt="'+$facLink.text()+'" /></a>';}
                var facBio = '<div class="facultyBio clearfix '+facID+'"><div class="facClose">Close</div><div class="facClose facCloseAll">Close All</div><h3><a href="'+$facLink.attr('href')+'" class="facultyLink">'+$facLink.html()+'</a></h3>'+facImg+'<div class="bio">'+faculty[facID].bio+'<a href="'+$facLink.attr('href')+'" class="facultyLink facultyLinkBottom">Faculty Web Page</a></div></div>';
                $facLink.parent().find('.faculty-link').filter(":last").after(facBio).parent().children('.facultyBio.'+facID).fadeIn();
            }
        }
    });
    $('.facultyBio div.facClose').live('click', function() {
        $(this).parent().slideUp(400,'easeOutExpo',function() {$(this).remove()});
    });
    $('.facultyBio div.facCloseAll').live('click', function() {
        $('.facultyBio').slideUp(400,'easeOutExpo',function() {$(this).remove()});
    });
    }
    // Faculty Bio
    $('a.email').each(function() {
        $(this).attr('href',$(this).attr('href').replace('REM0VE',''));
    });


    // Giving
    $('#donorProfiles').cycle({"pause":1,"timeout":8000,"random":1,"before":resizeCycle});


    // Page content masonry
    $('#main-body:not(.no-section-sidebar) div.level2-masonry').masonry({"itemSelector":"div.tile", "columnWidth":350});
    $('#main-body.no-section-sidebar div.level2-masonry').masonry({"itemSelector":"div.tile", "columnWidth":197});
    $('#main-body.no-section-sidebar div.level2-masonry').masonry({"itemSelector":"div.tile"});
    // Staff Directory
    $('.jumpToDepartment').toggle(function() {$('#departments').slideDown();},function() {$('#departments').slideUp();});
    $('#staff-directory td.n a').each(function() {
        $(this).attr('href',$(this).attr('href').replace('REM0VE',''));
    });


    // Sitemap Search function
    $('#siteNavSearch').submit(function(e) {e.preventDefault();});
    var typingTimer, sitemapScope = "siteIndex";
    if ($('body.news').length) {sitemapScope = "newsArchive";}
    console.log(sitemapScope);
    $('#siteNavSearch #siteNavInput').keyup(function() {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function() {filterSitemap(sitemapScope)}, 200);
    });
    $('#siteNavSearch #siteNavReset').click(function() {
        typingTimer = setTimeout(function() {filterSitemap(sitemapScope)}, 100);
    });
    $('.sitemap-navigation').prepend('<span class="showAll hidden">Show All</span>').children('.showAll').click(function() {
        $(this).addClass('hidden').next().next().find('.hidden').removeClass('hidden');
        $(this).next().next().find('.helperDir').remove();
    });


    // jCaption
    $('img.usecaption').jcaption({
        wrapperElement: 'span', //Element to wrap the image and caption in
        wrapperClass: 'caption',    //Class for wrapper element
        captionElement: 'span', //Caption Element
        imageAttr: 'alt',   //Attribute of image to use as caption source
        requireText: true,  //If true, it checks to make sure there is caption copy before running on each image
        copyStyle: false,   //Should inline style be copied from img element to wrapper
        removeStyle: true,  //Strip inline style from image
        removeAlign: true,  //Strip align attribute from image
        copyAlignmentToClass: false,    //Assign the value of the images align attribute as a class to the wrapper
        copyFloatToClass: false,    //Assign the value of the images float value as a class to the wrapper
        autoWidth: false,   //Assign a width to the wrapper that matches the image
        animate: false, //Animate on hover over the image
        show: {opacity: 'show'},    //Show Animation
        showDuration: 200,
        hide: {opacity: 'hide'},    //Hide Animation
        hideDuration: 200   
    });


    // This would go inline
    var sophContent = {
        individual: {
            content: '<p><Strong>Lots of colleges claim you’re more than a number.</strong> SLC means it—from refusing to consider SAT and ACT scores to the one-one-one nature of the conference system. Explore our site to learn more. No need to take a <strong>number</strong>.</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/individual.jpg" width="500" height="350" alt="Image"/>'
        },
        distinctive: {
            content: '<p><strong>Vanilla or Jamoca Almond Fudge?</strong> Generic and bland or bold and intense? You can ask the same about your college choices. At SLC, bold and intense are the ingredients in all we do. There’s an entire palette of flavors on our site, so have a taste.</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/distinctive.jpg" width="500" height="350" alt="Image"/>'
        },
        immersion: {
            content: '<p><strong>Students at many colleges</strong> have an experience more like a wading pool than a diving pool. Why experience just the top few inches of life when you can <strong>dive in</strong> and experience its full intensity and richness? Intensity isn’t for everyone, but it defines SLC, so spend a few minutes on our site and see if it’s for you.</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/immersion.jpg" width="500" height="350" alt="Image"/>'
        },
        academics: {
            content: '<h5>No Majors. No Limits</h5><p>If college is a time for personal exploration and growth, why should you be restricted by majors and requirements? A dance student can gain much from a course in anthropology.  An interest in environmental science can strengthen with courses in economics or political science.  Whatever your passion, the benefits of exploring new territory are unlimited.  Which is why the only limits at SLC are the those you impose on yourself.  Explore all the possibilities at slc.edu.</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/academics.jpg" width="500" height="290" alt="Image"/>'
        },
        gateway: {
            content: '<h5>London. Paris. New York.</h5><p>SLC is the gateway to a much bigger world. Half of our students take advantage of our study abroad programs in Oxford, Paris, London, Florence, Catania, and Havana. For the other half, New York City is equally compelling. Before you see the world, explore our site.</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/gateway.jpg" width="500" height="290" alt="Image"/>'
        },
        metro: {
            content: '<h5>The 8-million-person learning lab.</h5><p>The NYC learning lab is huge and a breeze to access. From internships to cultural resources, the City can play a big part in your life at SLC. Plus, the world’s greatest city isn’t too shabby a place for fun and adventure, either. See our site before you see the sights!</p><div class="instructions">(click anywhere to continue)</div><img src="/core/v5.0/img/cards/metro.jpg" width="500" height="290" alt="Image"/>'
        }
    }

    // Sophomore Cards
    if (queryJSON.ref == 'card' && sophContent[queryJSON.url]) {
        $('#headerWrapper').append('<div id="fullOverlay"><div class="inner"><div class="close"></div><div class="content">'+sophContent[queryJSON.url].content+'</div></div></div>');
        $('#fullOverlay').click(function() {
            $('#fullOverlay .content').animate({'color':'black'}, function() {
                $('#fullOverlay .content').animate({'opacity':0}, function() {
                    $('#fullOverlay .inner').animate({'opacity':0,'width':0,'height':0}, function() {
                        $('#fullOverlay').remove();
                    });
                });
            });
        });
    }


    // HTML5 video
    if (window.videoArray && $('.videoWrapper').length) {
    if (videoArray.length == 1) {
        $('.videoWrapper .fallback-message').remove();
        insertPlayer(0);
    } else {
        var firstPass = true;
        
        // Make video pager
        $('.videoWrapper').append('<div class="pager apPager videosPager">'+makeVideoPager()+'</div>');
        
        // Control clicks
        $('.videosPager div').click(function() {
            if ($(this).hasClass('activeSlide')) {return false;}
            // Update pager
            $('.videosPager .activeSlide').removeClass('activeSlide');
            var currentVid = parseInt($(this).attr('class').replace('pager',''));
            $(this).addClass('activeSlide');
            
            // Remove previous video (only if it exists) and add the new holder
            if (firstPass) {firstPass = false;}
            else {jwplayer($('.videos div').attr('id').replace('_wrapper','')).remove();}
            $('.videos').html('<div id="'+videoArray[currentVid].id+'"></div>');
            
            insertPlayer(currentVid);
        });
        $('.videosPager .pager0').click();
        $('.videoWrapper .videos').css({'min-height':layoutJSON[layout].height});
    }
    }

}); // End doc.ready

var layoutJSON = {
    'small':{width:280,height:158},
    'smallWide':{width:280,height:210},
    'medium':{width:450,height:338},
    'mediumWide':{width:450,height:253},
    'large':{width:640,height:480},
    'largeWide':{width:640,height:360}
};

function makeVideoPager() {
    var videoPager = '';
    $.each(videoArray, function(i,v) {
        videoPager += '<div class="pager'+i+'">'+videoArray[i].nav+'</div>';
    });
    return videoPager;
}

function insertPlayer(currentVid) {
    // Set the options for JW Player

    var videoPaths = {}
    if (videoArray[currentVid].desktop.path.match(/youtube.com/)) {
        videoPaths = {
            'file': videoArray[currentVid].desktop.path,
            'provider': 'youtube',
            'height': layoutJSON[layout].height+25,
            'modes': [{'type': 'html5'},{'type': 'flash', 'src': '/jwplayer.swf'}]
        }
    } else if (videoArray[currentVid].desktop.path.match(/\.mp4$/) || videoArray[currentVid].desktop.path.match(/\.flv$/)) {
        videoPaths = {
            'modes': [{
                'type': 'html5', 'config': { 'file': videoArray[currentVid].desktop.path }},{
                'type': 'flash', 'src': '/jwplayer.swf', 'config': { 'file': videoArray[currentVid].desktop.path }
            }]
        }
    } else if (videoArray[currentVid].desktop.path.match(/\.rss$/)) {
        videoPaths = {
            'playlistfile': videoArray[currentVid].desktop.path,
            'playlist.position': 'bottom',
            'playlist.size': 210,
            'height': layoutJSON[layout].height+210,
            'modes': [{'type': 'html5'},{'type': 'flash', 'src': '/jwplayer.swf'}],
            'repeat': 'list'
        }
    } else if (videoArray[currentVid].desktop.path.match(/^rtmp/)) {
        videoPaths = {
            'flashplayer': '/jwplayer.swf',
            'provider': 'rtmp',
            'file':'livestream',
            'autostart': true,
            'rtmp.subscribe': true,
            'streamer': videoArray[currentVid].desktop.path
        }
    } else {
        videoPaths = {'modes': videoModes(videoArray[currentVid].desktop.path)}
    }
     
    var defaultVideo = $.extend({
        'image': videoArray[currentVid].desktop.img,
        'width': layoutJSON[layout].width,
        'height': layoutJSON[layout].height
    }, videoPaths, videoArray[currentVid].desktop.options );

    // Insert the video
    jwplayer(videoArray[currentVid].id).setup(defaultVideo);
}

// Set the order of preference for video encoding output
function videoModes(vid) {
    var allModes = [{
    'type': "html5", 'config': { 'file': vid+'.webm' }},{
    'type': 'html5', 'config': { 'file': vid+'.mp4' }},{
    'type': 'flash', 'src': '/jwplayer.swf', 'config': { 'file': vid+'.mp4' }},{
    'type': 'download', 'config': { 'file': vid+'.webm' }
    }];
    return allModes;
}


// Resize jQuery.Cycle instances to the height of the new slide. Use: {before: resizeCycle}
function resizeCycle(curr, next, opts, fwd) {opts.$cont.animate({'height':$(next).height()}, 200);}


// Control expansion of long paragraphs (Areas of study pages)
function controlExpander(controller,expandable,shortHeight) {
    $(controller).click(function(e) {
        e.preventDefault();
        var fullHeight = $(this).prev().children(expandable).height();
        if ($(this).prev().hasClass('expanded')) {
            $(this).removeClass('expanded').html('Expand').prev().removeClass('expanded').animate({'height':shortHeight});
        } else {
            $(this).addClass('expanded').html('Collapse').prev().addClass('expanded').animate({'height':fullHeight});
        }
    });
}


/*!
 * parseSlidesXml function created for Saral Lawrence College, (c) slc.edu 2010
 * Author: Stuart Basden stu@t.apio.ca
 * Released as Open Source under MIT license
 */
function parseSlidesXml(xml,slideshowID,settings) {
    // Destroy the static slide (present for nojs)
    $(slideshowID+' .slide').remove();
    
    // Get the initial slide order
    var slideshowOrder = [], newSlideID = 0;
    slideshowOrder = orderSlides(xml,settings,slideshowOrder);
    
    // Initially add two slides so that jquery.cycle will function. Add another if you want images to be loaded with more buffering
    anotherSlide(0);
    anotherSlide(0); 
    
    // Initial fade in of slideshow (or rather, fadeOut of cover)
    $('#fadeOut').css('z-index','120').delay('250').fadeOut();
    
    // Set the default cycle options
    var defaultCycle = {
        fx: "fade",
        speed: 500,
        pause: 1,
        autostop: 1,
        autostopCount: 99, // Stop the show after 99 slides to save server from loading images for unattended browsers
        timeoutFn: slideTimeout,
        before: onbefore,
        after: onafter
    };
    // Extend the cycle options
    $.extend( defaultCycle, settings.cycle );
    
    // Start jquery.cycle
    $(slideshowID).cycle(defaultCycle);
    
    
    
    function anotherSlide(withinCycle, curr, next, opts, fwd) {
        var newSlide = '', img = $(xml).find('img[id='+slideshowOrder[newSlideID]+']');
        
        /* Define the new slides HTML */
        createSlideHTML(img, newSlideID);
        
        // Add the new slide (different method called from within jquery.cycle than outside)
        if (withinCycle == 1) {
            opts.addSlide(newSlide);
        } else {
            $(slideshowID).append(newSlide);
        }
        
        // Prepare for the next slide. If we have seen them all, reset and reorder.
        newSlideID++;
        if (newSlideID >= slideshowOrder.length) {
            newSlideID = 0;
            orderSlides(xml,settings);
        }
        
        function createSlideHTML(img, newSlideID) {
            newSlide = "<div id='slide" + newSlideID + "' class='slide slideID"+$(img).attr("id")+"'>"; // Create slide div
            var title = "";
            $(img).find("mobile").remove(); // Remove the mobile attributes from the equation
            if ($(img).find("title").text().length>0) { // Determine title
                var p = $(img).find("title").text().replace(/\'/g,"&#39;").replace(/\"/g,'&quot;'); //'
                title = p.replace("'","");
            } else {
                title = $(img).attr("id");
            }
            var hasLink = "";
            if ($(img).find("href").text().length>0) { // Add link if exists
                newSlide += "<a href='" + $(img).find("href").text().replace(/\&/g,"&amp;") + "' title='" + title + "'>";
                hasLink = "</a>";
            }
            newSlide += "<img src='" + $(img).find("src").text().replace(/\&/g,"&amp;") + "' alt='" + title + "' width='" + $(img).find("width").text() + "' height='" + $(img).find("height").text() + "' />"; // Add image
            if ($(img).find("caption").text().length>0) { // Add caption if exists
                newSlide += "<span>" + $(img).find("caption").text().replace(/\'/g,"&#39;").replace(/\"/g,'&quot;') + "</span>"; //'
            }
            newSlide += hasLink + "</div>"; // Close link and div
            return newSlide;
        } // End createSlideHTML
    } // End anotherSlide


    function slideTimeout(currElement, nextElement, opts, isForward) {
        // Get the current slide ID
        var arrayNum = $(this).attr('id').replace('slide','');
        // Return the number of miliseconds for the slide, as 5s + the pause number of seconds
        var extraPause = $(xml).find('img[id='+slideshowOrder[arrayNum]+']').find('pause').text();
        return 7000 + 1000*parseInt(extraPause);
    } // End slideTimeout
    
    function onbefore(curr, next, opts, fwd) {
        // on the first pass, addSlide is undefined (plugin has not created the fn yet) 
        if (!opts.addSlide) {return;}
        
        // Add another slide
        anotherSlide(1, curr, next, opts, fwd);
    } // End onbefore
    
    function onafter(curr, next, opts, fwd) {
        // on the first pass, removeSlide is undefined (plugin has not created the fn yet) 
        if (!opts.removeSlide) {return;}
        // Remove the first slide
        opts.removeSlide();
    } // End onafter
    
    
} // End parseSlidesXml


function parseSlidesJSON(JSON,slideshowID,settings) {
    // Destroy the static slide (present for nojs)
    $(slideshowID+' .slide').remove();
    
    // Get the initial slide order
    var slideshowOrder = [], newSlideID = 0, newSlide = '', slide = {};
    slideshowOrder = orderJSONSlides(JSON,settings,slideshowOrder);
    
    // Initially add two slides so that jquery.cycle will function. Add another if you want images to be loaded with more buffering
    anotherSlide(0);
    anotherSlide(0); 
    
    // Initial fade in of slideshow (or rather, fadeOut of cover)
    $('#fadeOut').css('z-index','120').delay('250').fadeOut();
    
    // Set the default cycle options
    var defaultCycle = {
        fx: "fade",
        speed: 500,
        pause: 1,
        autostop: 1,
        autostopCount: 99, // Stop the show after 99 slides to save server from loading images for unattended browsers
        timeoutFn: slideTimeout,
        before: onbefore,
        after: onafter
    };
    // Extend the cycle options
    $.extend( defaultCycle, settings.cycle );
    
    // Start jquery.cycle
    $(slideshowID).cycle(defaultCycle);
    
    
    function anotherSlide(withinCycle, curr, next, opts, fwd) {
        newSlide = '', slide = slideshowOrder[newSlideID];
        createSlideHTML(slide, newSlideID); /* Define the new slides HTML */
        
        // Add the new slide (different method called from within jquery.cycle than outside)
        if (withinCycle == 1) {
            opts.addSlide(newSlide);
        } else {
            $(slideshowID).append(newSlide);
        }
        
        // Prepare for the next slide. If we have seen them all, reset and reorder.
        newSlideID++;
        if (newSlideID >= slideshowOrder.length) {
            newSlideID = 0;
            orderJSONSlides(JSON,settings,slideshowOrder);
        }
        
        function createSlideHTML(slide, newSlideID) {
            newSlide = "<div id='slide" + newSlideID + "' class='slide slideID"+slide.id+"'>"; // Create slide div
            var title = "", endLink = "";
            if (slide.title.length>0) { // Determine title
                var p = slide.title.replace(/\'/g,"&#39;").replace(/\"/g,'&quot;'); //'
                title = p.replace("'","");
            } else { title = slide.id; }
            if (slide.href.length>0) { // Add link if exists
                newSlide += "<a href='" + slide.href.replace(/\&/g,"&amp;") + "' title='" + title + "'>";
                endLink = "</a>";
            }
            newSlide += "<img src='" + slide.src.replace(/\&/g,"&amp;") + "' alt='" + title + "' width='" + slide.width + "' height='" + slide.height + "' />"; // Add image
            if (slide.caption.length>0) { // Add caption if exists
                newSlide += "<span>" + slide.caption.replace(/\'/g,"&#39;").replace(/\"/g,'&quot;') + "</span>"; //'
            }
            newSlide += endLink + "</div>"; // Close link and div
            return newSlide;
        } // End createSlideHTML
    } // End anotherSlide

    function slideTimeout(currElement, nextElement, opts, isForward) {
        // Get the current slide ID
        var arrayNum = $(this).attr('id').replace('slide','');
        // Return the number of miliseconds for the slide, as 5s + the pause number of seconds
        return 7000 + 1000*parseInt(slide.pause);
    } // End slideTimeout

    function onbefore(curr, next, opts, fwd) {
        // on the first pass, addSlide is undefined (plugin has not created the fn yet) 
        if (!opts.addSlide) {return;}
        // Add another slide
        anotherSlide(1, curr, next, opts, fwd);
    } // End onbefore

    function onafter(curr, next, opts, fwd) {
        // on the first pass, removeSlide is undefined (plugin has not created the fn yet) 
        if (!opts.removeSlide) {return;}
        // Remove the first slide
        opts.removeSlide();
    } // End onafter
} // End parseSlidesJSON


function parsePageBG(xml,slideshowID,settings) {
    // Destroy the static bg (present for nojs)
    $(slideshowID+' img').remove();
    
    // Get the initial slide order
    var slideshowOrder = [], newSlideID = 0, newSlide = '', img = '';
    slideshowOrder = orderSlides(xml,settings);
    
    // Make the slideshow
    $.each(slideshowOrder, function(index) {
        img = $(xml).find('img[id='+slideshowOrder[index]+']');
        var image = "<img src='" + $(img).find("src").text().replace(/\&/g,"&amp;") + "' alt='" + $(img).find("caption").text().replace(/\'/g,"&#39;").replace(/\"/g,'&quot;') + /*'*/ "' width='" + $(img).find("width").text() + "' height='" + $(img).find("height").text() + "' />";
        $(slideshowID).append(image);
    });
    
    // Add the pager DIV
    $(slideshowID).parent().append('<div id="'+slideshowID.replace('#','')+'Pager"></div>')
    
    // Set the default cycle options    
    var defaultCycle = {
        fx: 'fade',
        timeout: 6000, 
        delay: 2000, 
        autostop: 1, 
        autostopCount: 99,
        pager:  slideshowID+'Pager', 
        pagerAnchorBuilder: function(index, slide) { 
            img = $(xml).find('img[id='+slideshowOrder[index]+']');
            return '<li><a href="#"><img src="' + $(img).find("thumb").attr("src") + '" width="' + $(img).find("thumb").attr("width") + '" height="' + $(img).find("thumb").attr("height") + '" /></a></li>';
        }
    };
    // Extend the cycle options
    $.extend( defaultCycle, settings.cycle );
    
    // Start jquery.cycle
    $(slideshowID).cycle(defaultCycle);
}


function orderSlides(xml,settings,slideshowOrder) {
     slideshowOrder = []; // Reset
    $(xml).find("album").each(function() {
        var albumIDArray = [];
        $(this).find('img').each(function() {
            albumIDArray.push($(this).attr('id'));
        });
        // Randomize the album
        if (settings.random) {randomizeArray(albumIDArray);}
        // Add to the main order
        slideshowOrder = slideshowOrder.concat(albumIDArray)
    });
    //console.log(slideshowOrder);
    return(slideshowOrder);
} // End orderSlides


function loadMenu() {
    $("#nav li").each( function() {
        $(this).hover(function(){
            $(this).addClass('active').append('<div class="submenu"></div>').children(".submenu").hide().html(menu[$(this).attr('id')].content).delay(200).slideDown('fast');
            // Clear the menu when a link is clicked (for location.hash changes)
            $('#nav a').live('click', function(){
                $('.submenu').fadeOut('fast');
                $('#nav li').removeClass('active');
            });
        },function(){
            $(this).removeClass('active').children(".submenu").remove();
        });//hover
    }); //each
}


function orderJSONSlides(JSON,settings,slideshowOrder) {
     slideshowOrder = []; // Reset
     $.each(gallery.albums, function() {
        var albumIDArray = [];
        $.each(this.imgs, function() {
            albumIDArray.push(this);
        });
        // Randomize the album
        if (settings.random) {randomizeArray(albumIDArray);}
        // Add to the main order
        slideshowOrder = slideshowOrder.concat(albumIDArray)
    });
    //console.log(slideshowOrder);
    return(slideshowOrder);
} // End orderJSONSlides


function randomizeArray(sourceArray) {
    for (var n = 0; n < sourceArray.length - 1; n++) {
        var k = n + Math.floor(Math.random() * (sourceArray.length - n));
        var temp = sourceArray[k];
        sourceArray[k] = sourceArray[n];
        sourceArray[n] = temp;
    }
}


function getUrlVars()   {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}


function JSONrequest(JSONurl,sucFn,elementID,settings) {
    if ($(elementID).length) {
        // Settings are options, but default to random
        if (!settings) {settings={};}
        if (settings.random == undefined) {
            if (sucFn == parsePageBG) {settings.random=0;} else {settings.random=1;}
        }
        if (settings.cycle == undefined) {settings.cycle={};}
        $.getScript(JSONurl, function(data, textStatus) {
            sucFn(data,elementID,settings);
        });
    }
}

function XMLrequest(XMLurl,sucFn,elementID,settings) {
    if ($(elementID).length) {
        // Settings are options, but default to random
        if (!settings) {settings={};}
        if (settings.random == undefined) {
            if (sucFn == parsePageBG) {settings.random=0;} else {settings.random=1;}
        }
        if (settings.cycle == undefined) {settings.cycle={};}
        $.ajax({
            type: "GET",
            url: XMLurl,
            dataType: "xml",
            success: function(xhr, textStatus, error) {
                sucFn(xhr,elementID,settings);
            }
        });
    }
}


function filterSitemap(helper) {
    var query = $('#siteNavSearch #siteNavInput').attr('value');
    $('.contentSleeve .hidden').removeClass('hidden'); // reset
    $('#siteIndexFilters .noResults').hide();
    $('.helperDir').remove();
    $('.showAll').addClass('hidden');
    if (query.length > 1) {
    
        $('.showAll').removeClass('hidden');
        $('.sitemap-navigation').each(function() {
            var allGone = 1;
            $(this).find('li > a').each(function() {
                if ($(this).text().toLowerCase().indexOf(query) == -1) {
                    $(this).addClass('hidden');
                } else {
                    allGone = 0;
                    if (helper == "siteIndex") {
                        $(this).parent().prepend('<span class="helperDir">in: '+$(this).parent().parent().prev().text()+'</span>');
                    } else if (helper == "newsArchive") {
                        $(this).parent().prepend('<span class="helperDir">'+$(this).parent().attr('class').replace(/_/g,' ')+'</span>');
                    }
                }
            });
            if (allGone == 1) { // Control section headings and filters
                if ($(this).find('.sitemap-section-heading').text().toLowerCase().indexOf(query) == -1) {
                    $(this).addClass('hidden');
                    var sitemapID = $(this).attr('id');
                    $('#siteIndexFilters .filter.'+sitemapID).addClass('hidden');
                    if ($('#siteIndexFilters .filter.hidden').length == $('#siteIndexFilters .filter').length) {
                        $('#siteIndexFilters .noResults').show();
                    }
                }
            }
        });
    }
}
