jQuery(document).ready(function($) {

    function detectbrowser() {
        var userAgent = navigator.userAgent.toLowerCase();
        $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
        
        // Is this a version of IE?
        if($.browser.msie){
            return "IE";
        };
        
        
        // Is this a version of Chrome?
        if($.browser.chrome){
            // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
            // -- hmm, it seems OK to me. Maybe on older versions it poops itself.
            $.browser.safari = false;
            
            return "CHROME";
        };
        
        // Is this a version of Safari?
        if($.browser.safari){
            return "SAFARI";
        };
        
        // Is this a version of Mozilla?
        if($.browser.mozilla){
            
            //Is it Firefox?
            if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
                return "FF";
            }
            // If not then it must be another Mozilla
            else{
                return "MOZILLA";
            };
        };
        
        // Is this a version of Opera?
        if($.browser.opera){
            return "OPERA";
        };
    };
    
    $('#logos').cycle({speed: 500,timeout: 4000, delay: -2000,});
    
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        };
    };
    
    // preload images.
    $.preLoadImages('App_Themes/Assembly-SMS/images/grey.png', 'App_Themes/Assembly-SMS/images/dark-blue.png');
    
    
    $('.height-equal, .height-equal-clear').each(function () {
        //if (!this.equalHeight_check) {
            var me = $(this),
                height = me.height(),
                tempEl,
                elList = [];
                
            $(['prev', 'next']).each(function(k, func) {
                tempEl = me[func]();
                while (tempEl.length) {
                    if (tempEl.css('clear') == 'both') {
                        if (me.hasClass('height-equal-clear')) {
                            break;
                        }
                        else {
                            tempEl = tempEl[func]();
                            continue;
                        }
                    }
                    //this.equalHeight_check = true;
                    height = Math.max(height, tempEl.height());
                    elList.push(tempEl);
                    tempEl = tempEl[func]();
                }
            });

            me.css({minHeight: height + 'px'});
            $(elList).css({minHeight: height + 'px'});
        //}
    });
    
    
    // reposition the bg image of the header on inner pages.
    $(window).resize(function() {
        if($('body :not(.home)').length) {
            var winWidth = $(this).width(),
                innerWidth = $('header .inner').width();
                
            pos = Math.floor((winWidth-innerWidth)/2);
            if(pos < 80) {
                pos = 80;
            };
            $('header .inner').css({'background-image' : 'url(App_Themes/Assembly-SMS/images/gradient-background.png)',
                                    'background-position': pos+'px 0px',
                                    'background-repeat': 'no-repeat'});
        }
    });
    $(window).trigger('resize');
    
    
    /* ---------------------- *
     * Video Player Handling.
     * ---------------------- */
     
    // used to load the appropriate video in order. - @see loadVideo.
    var videos = {admin: 0,
                 teachers: 1,
                 principals: 2};
                 
    $('.inside #watch').css('height',0); 
    
    /* ----------------------------------------------------- *
     * Extract the query strings - if video
     * is present, then we will try and load the appropriate
     * video.
     * ----------------------------------------------------- */
    var a = window.location.href.indexOf('?');
    var b = window.location.href.substr(a+1).split('&');
    var queryStr ={};
    $.each(b, function(x,y){
        var temp = y.split('=');
        queryStr[temp[0]] = temp[1];
    });
    
    if(queryStr.video !== undefined && 
        (queryStr.video == 'admin' || queryStr.video == 'teachers' || queryStr.video == 'principals')) { // I wish there was a decent membership operation in js.
        var video = queryStr.video;
        var target = $('.inside #watch .grid_3 ul').find('.'+video);
        var timer = setTimeout(function() { clearTimeout(timer); loadVideo(target, video);}, 500);
    };
    
    // Set up video players.
    if(jwplayer !== undefined) {
        $('.videoplayer').each(function() {
            var id = $(this).attr('id'),
                file = $(this).attr('src'),
                image = $(this).attr('poster');
            options =   {flashplayer: 'CMSScripts/Assembly-SMS/longtail/player.swf',
                        skin: 'CMSScripts/Assembly-SMS/longtail/five/five.xml',
                        file: file,
                        image: image,
                        events: {
                            onReady: function(event) {
                                //alert('loaded');
                            }
                        }
                        };
            
            if(detectbrowser() == 'IE') {
                options.players = [{ type: "flash", src: "CMSScripts/Assembly-SMS/longtail/player.swf" },
                                  { type: "html5" }];
            };
            
            jwplayer(id).setup(options);
        });
    };
    
    function loadVideo(target, video) {
        // open up the watch box if needed.
        $('.inside #watch').css({'display': 'block'}).animate({height: '449px'}, 500, function() {
            target.parent().parent('ul').children('li').children('p').slideUp();
            target.parent().parent('ul').children('li').removeClass('active');
            target.next('p').slideToggle();
            target.parent('li').addClass('active');
            
            $('.inside #watch .grid_9').children().hide();
            $($('.inside #watch .grid_9').children()[videos[video]]).show();
        });
    };
    
    $('.inside .video').click(function() {
        var classNames = $(this).attr('class').split(' '),
            video = '',
            i = 0;
            
        // grab the first class that is not the video class.
        // - this may be dangerous if more classes are added.
        for(i in classNames) {
            if(classNames[i] != 'video') {
                video = classNames[i];
                break;
            };
        };
        
        // find the target h2.
        if($(this).is('h2')) {
            target = $(this);
        } else {
            target = $('.inside #watch .grid_3 ul').find('.'+video);
        };
            
        // only run this if the clicked link, is not the current active link.
        if(target.parent('li').hasClass('active')) {
            return false;
        };
        
        loadVideo(target, video);
        
        return false;
    });
    
    $('.inside #watch .close').click(function() {
        $('.inside #watch').find('.active').removeClass('active');
        $('.inside #watch').css({'display': 'none'}).animate({height: 0, 'min-height': 0}, 500, function() {
            $(this).hide();
        });
        return false;
    });
});
