$(document).ready(function(){
    var activeMenuItem = $('#level-1>li.active')[0];
    var activeSubmenuItem = $('#level-1 ol.level-2 li.active')[0];
    var sliderExists = false;
    var l2sliderExists = true;
    var timeout;
    var timeoutSubmenu;
    var initSubmenuStaticLock = true;
    var sinkingLock = false;
    var risingLock = false;
    var activeSubmenu = $("ol#level-1>li.active ol");
    var pageLeftOffset = $('#top-nav-separator').offset().left;
    
    $('#top-nav-highlight, #top-nav-highlight-copy')
    .css('left', $(activeMenuItem).offset().left - pageLeftOffset - 1 + 'px')
    .width($(activeMenuItem).width() + 10)
    .css('display', 'block');
    
    
    $('ol#level-1').mouseover(function(e){
        clearTimeout(timeout);
        target = e.target;
        if(target.nodeName == 'A')
            target = target.parentNode;
        overTopNav(target);
    });
    $('ol#level-1>li>a').mousemove(function(e){
        if(!sinkingLock && !risingLock && !sliderExists){
            risingLock = true;
            clearTimeout(timeout);
            target = e.target;
            if(target.nodeName == 'A')
                target = target.parentNode;
            //console.log('raising');
            overTopNav(target);
        }
        
    })
    
    
    function overTopNav(target){
        if(target.nodeName == "LI" && target.parentNode.id == 'level-1' && !sinkingLock)
        {
            if(target.className.indexOf("active") != -1){
                if(sliderExists)
                    sinkSlider();
                return;
            }
            if(!sliderExists){
                risingLock = true;
                $('#top-nav-highlight').stop()
                .css({left: $(target).offset().left - pageLeftOffset - 6 + 'px', width: $(target).width() + 10 + 12, height: 0, top: 96})
                .animate({height: 46, top: 50}, function(){
                    sliderExists = true;
                    risingLock = false;
                });
            }
            else{
                $('#top-nav-highlight').stop()
                .animate({left: $(target).offset().left - pageLeftOffset - 6 + 'px', width: $(target).width() + 10 + 12});
            }
            if(!activeSubmenu.length)
                activeSubmenu = $("ol#level-1>li.active ol");
            //console.log("active:" + activeSubmenu + ":" + activeSubmenu.html());
            //console.log("target:" + $(target).children('ol') + ":" + $(target).children('ol').html());
            if(activeSubmenu[0] !== $(target).children('ol')[0])
            {
                activeSubmenu.stop()
                .css('opacity', 1)
                .attr('rel', 'disappearing')
                .animate({opacity: 0}, "normal", function(){
                    $(this).css('display', 'none')
                    .attr('rel', '');
                    activeSubmenu = $(target).children('ol');
                    activeSubmenu.css('display', 'block')
                    .animate({opacity: 1}, "normal");
                });
                
                $('#top-nav-submenu-highlight').stop().fadeOut();
                l2sliderExists = false;
                clearTimeout(timeoutSubmenu);
            }
        }
    }
    $('ol#level-1').mouseout(function(e){
        if(activeSubmenu[0] != $("ol#level-1>li.active ol")[0])
            timeout = setTimeout(sinkSlider, 450);
    });
    function sinkSlider(){
        if(!sinkingLock){
            sinkingLock = true;
            $('#top-nav-highlight').stop()
            .animate({height: 0, top: 96});
            sliderExists = false;
            
            $('#top-nav-submenu-highlight').stop().fadeOut();
            
            if(!activeSubmenu.length)
                activeSubmenu = $("ol#level-1>li.active ol");
            
            activeSubmenu.stop()
            .animate({opacity: 0}, "normal", function(){
                $(this).css('display', 'none');
                activeSubmenu = $("ol#level-1>li.active ol");
                activeSubmenu.css('display', 'block')
                .animate({opacity: 1}, "normal", function(){
                    sinkingLock = false;
                });
                initSubmenuStatic();
            });
            initSubmenuStaticLock = true;
            //.animate({left: $(target).offset().left - 150 + 'px', width: $(target).width() + 10});
        }
    }

    
    
    
    function initSubmenuStatic(){
        l2sliderExists = true;
        $('#top-nav-submenu-highlight')
        .css('left', $(activeSubmenuItem).offset().left - pageLeftOffset - 3)
        .width(0)
        .animate({width: $(activeSubmenuItem).width() + 0 + 4})
        .css('display', 'block');
        initSubmenuStaticLock = false;
    }
    initSubmenuStatic();
    
    $('ol.level-2').mouseover(function(e){
        target = e.target;
        if(target.nodeName == 'A')
            target = target.parentNode;
        if($(target).parent().attr('rel') != 'disappearing'){
            clearTimeout(timeoutSubmenu);
            if(target.nodeName == "LI" && target.parentNode.className.indexOf('level-2') != -1 && !initSubmenuStaticLock)
            {
                //console.log(target.innerHTML + "      " + $(target).offset().left);
                if(!l2sliderExists){
                    $('#top-nav-submenu-highlight').stop()
                    .css({left: $(target).offset().left - pageLeftOffset - 3, width: 0, opacity: 1})
                    .animate({width: $(target).width() + 0 + 4}, function(){
                        l2sliderExists = true;
                    });
                }
                else{
                    $('#top-nav-submenu-highlight').stop()
                    .css({opacity: 1})
                    .animate({left: $(target).offset().left - pageLeftOffset - 3, width: $(target).width() + 0 + 4}, "slow");
                }
            }
        }
    });
    $('ol.level-2').mouseout(function(){
        if($('li.active', this).length)
            timeoutSubmenu = setTimeout(function(){
                if($(activeSubmenuItem).parent().css('opacity') == 1)  //hack
                    $('#top-nav-submenu-highlight').stop()
                    .css({opacity: 1})
                    .animate({left: $(activeSubmenuItem).offset().left - pageLeftOffset - 3, width: $(activeSubmenuItem).width() + 0 + 4}, "slow");
            }, 250);
        
    });
    
    
    $(window).resize(function(){
        pageLeftOffset = $('#top-nav-separator').offset().left;
    });
    
    
    
    
    
    jQuery.fn.stopIfPossible = function(){
        return sliderExists ? this.stop() : this;
    }
    jQuery.preloadImages = function()
    {
        for(var i = 0; i<arguments.length; i++)
        {
            jQuery("<img>").attr("src", arguments[i]);
        }
    }
    
    
    
    if(jQuery.browser.msie)
    {
        $('#top-search').css('margin-top', '-22px');
    }
    
    
    
    // rules, prize
    var current_3l = null;
    var lock_3l = false;
    function initPrize(){
        $('div#wall div.page-content div.main-panel-left div.inner-content div.competition-prize, div#wall div.page-content div.main-panel-left div.inner-content div.competition-rules')
        .css('display', 'none');
    }
    initPrize();
    $('div#wall div.page-content div.main-panel-left div.inner-content div.three-links a').live("click", function(e){
        if(!lock_3l){
            lock_3l = true;
            if($(this).attr('href').indexOf('register') == -1) // not a click on current
            {
                $p = $(this).parent();
                
                var newH = $(this).closest('.main-panel-left .content').outerHeight(true);
                //console.log('init: h='+newH);
                
                if(current_3l != null && current_3l.length){
                    newH -= current_3l.outerHeight(true);
                    current_3l.slideUp();
                }
                
                if(!(current_3l != null && (current_3l[0] == $($(this).attr('href'))[0]))){  // not self
                    current_3l = $($(this).attr('href'));
                    newH += current_3l.outerHeight(true);
                    
                    current_3l.slideDown();
                }
                else{
                    current_3l = null;
                }
                
                
                $(this).closest('.main-panel-left').each(function(){
                    var h = newH;       //88 +53x + 59
                    //console.log('would try to reach '+h);
                    n = Math.ceil((h - 88 - 59) / 53);
                    $(this).animate({height: 88 + 53*n + 59});
                    //console.log('got ' + (88 + 53*n + 59) + '  offshoot: '+(53 - ((h - 88 - 59) % 53)) % 53);
                    $('div.mid', this)
                    .animate({height: 53 * n}, function(){
                        lock_3l = false;
                    });
                });
            }
            else
                lock_3l = false;
        }
        
        //alert($(this).attr('href'));
        return false;
    });
    
    
    
    // tabs
    var before = '<div class="top"></div><div class="mid"></div><div class="bot"></div>';
    var around = '<div class="content"></div>';
    var after  = '<div class="loading-block"><div class="loading-overlay"></div><div class="loading-anim"></div></div>';
    function initTabHeaders(){
        //console.log($('div.tabs').width());
        $('div.tabs ul li').width($('div.tabs').width() / $('div.tabs ul li').length);
        $('div.tabs ul li.active').css('background-color', 'transparent').prepend('<div id="tab-highlight"></div>');
        $('div.tabs').css('background-image', 'url(/style/img/tab-baseline.png)');
        $('div.tabs ul li:not(:last)').css('background-image', 'url(/style/img/tab-separator.png)');
        $('#tab-highlight').width($('div.tabs ul li').width());
    }
    initTabHeaders();
    $('#wall .page-content .main-panel-left, #wall .page-content .main-panel-right').each(function(){
        $(this)
        .wrapInner(around)
        .prepend(before)
        .append(after)
        
        $('div.content', this).css({paddingTop: $(this).css('padding-top'), paddingRight: $(this).css('padding-right'), paddingBottom: $(this).css('padding-bottom'), paddingLeft: $(this).css('padding-left')});
        $(this).width($(this).width() + 2*$(this).css('padding-left').slice(0, -2));
        $(this).css('padding', 0);
        
        h = $('.content', this)
        .outerHeight(true);       //88 +53x + 59
        
        n = Math.ceil((h - 88 - 59) / 53);
        //console.log('offshoot: '+(53 - ((h - 88 - 59) % 53)) % 53);
        $(this).height(88 + 53*n + 59);
        $('div.mid', this)
        .css({display: 'block', height: 53 * n});
    });
    //$('div.tabs').closest('.content').css('padding-top','65px');
    
    
    
    function initPanel(selector){
        $(selector).each(function(){
            //$('div.content', this).css({paddingTop: $(this).css('padding-top'), paddingRight: $(this).css('padding-right'), paddingBottom: $(this).css('padding-bottom'), paddingLeft: $(this).css('padding-left')});
            //$(this).width($(this).width() + 2*$(this).css('padding-left').slice(0, -2));
            //$(this).css('padding', 0);
            
            h = $('.content', this)
            .outerHeight(true);       //88 +53x + 59
            
            n = Math.ceil((h - 88 - 59) / 53);
            //console.log('offshoot: '+(53 - ((h - 88 - 59) % 53)) % 53);
            $(this).height(88 + 53*n + 59);
            $('div.mid', this)
            .css({display: 'block', height: 53 * n});
        });
    }
    
    
    // ajax load
    $.preloadImages("/style/img/ajax-loader.gif");
    
    /*$('li.active>a').live("click", function(e){
        e.preventDefault();
        e.stopPropagation();
    });*/
    
    $('div.tabs a').live("click", function(e){
        //console.log(this.href);
        //console.log($(e.target).attr('href'));
        ajaxLoad($(e.target).attr('href'));
        
        e.preventDefault();
    });
    $('#top-nav ol#level-1>li.active ol.level-2 a').click(function(e){
        ajaxLoad($(e.target).attr('href'));
        
        $(this).closest('ol.level-2').children().removeClass('active');
        $(this).parent().addClass('active');
        activeSubmenuItem = $('#level-1 ol.level-2 li.active')[0];
        $('#hand-tag').removeClass().addClass($(e.target).attr('href').split('/').join(' ').trim());
        
        e.preventDefault();
    });
    
    function ajaxLoad(path){
        ajaxLoadPane(path, 'main-panel-left');
        ajaxLoadPane(path, 'main-panel-right');
    }
    function ajaxLoadPane(path, paneID){
        $('#' + paneID).addClass('ajax-loading');
        $.ajax({
            url: '/ajax/load',
            type: "POST",
            dataType: "html",
            data: {path: path, element: paneID},
            complete: function(res, status){
                if (!( status == "success" || status == "notmodified" ))
                    res = 'Data Error';
                else{
                    res = res.responseText;
                    // page loaded log this in analytics
                    pageTracker._trackPageview(path);
                }
                $('div.content', $('#' + paneID)).html(res);
                initPrize();
                initPanel($("#" + paneID)[0]);
                if(paneID == 'main-panel-left')
                    initTabHeaders();
                otherInit();
                $('#' + paneID).removeClass('ajax-loading');
            }
        })
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    //ie6 shit
    if(jQuery.browser.msie && jQuery.browser.version=='6.0')
        $('#wall .page-content').prepend('<div class="main-error">You are using an unsupported browser. You will, as you can see, be heavily penalized for doing so :) Please upgrade to at least Internet Explorer 7.0 or try one of the other modern broswers: Firefox, Chrome, Safari</div>');
    //ie6 shit
    
    
    
    otherInit = function(){
        // gallery
        $('div#gallery a.gallery-item-link').fancybox();
        
        $('a[rel="external"]').attr('target', '_blank');
        
        $('#top-search, .subevent-register').fancybox({
            hideOnContentClick: false,
            frameWidth: 200,
            frameHeight: 75
        });
        
        $('#top-right a#register').fancybox({
            hideOnContentClick: false,
            frameWidth: 650,
            frameHeight: 750,
            centerOnScroll: false
        });
        
        $('#top-right a#login').fancybox({
            hideOnContentClick: false,
            frameWidth: 470,
            frameHeight: 270,
            centerOnScroll: false
        });
        
        $('a.account_actions').fancybox({
            hideOnContentClick: false,
            frameWidth: 630,
            frameHeight: 510,
            centerOnScroll: false
        });
        
        $('a.view-all').fancybox({
            hideOnContentClick: false,
            frameWidth: 535,
            frameHeight: 510,
            centerOnScroll: false
        });
    }
    otherInit();
    
    $.history.init(load);
    
    
    
    
    
    //updates
    var updateCurrent = 0;
    var updateTotal = $('div#updates-content p').length;
    var updateTimeout;
    $('div#updates-content p:gt(0)').hide();
    $('#updates-next').click(function(){changeUpdate(1);});
    $('#updates-previous').click(function(){changeUpdate(-1);});
    
    function changeUpdate(delta){
        clearTimeout(updateTimeout);
        if(updateCurrent == null) updateCurrent = 0;
        $('div#updates-content p:eq(' + updateCurrent + ')')
        .stop()
        .fadeOut(function(){
            if(updateCurrent == null) updateCurrent = 0;
            updateCurrent = (updateCurrent + delta ) % updateTotal;
            $('div#updates-content p:eq(' + updateCurrent + ')')
            .css('opacity', '1')
            .stop()
            .fadeIn();
            updateTimeout = setTimeout(function(){changeUpdate(1);}, 4000);
        })
    }
    
    updateTimeout = setTimeout(function(){changeUpdate(1);}, 4000);
    
    
    
    
    
    //sponsors right
    var sponsorCurrent = 0;
    var sponsorTotal = $('#sponsors-right div.content a').length;
    var sponsorTimeout;
    $('#sponsors-right div.content a:gt(2)').hide();
    var sponsorSelector;
    
    function changeSponsor(delta){
        clearTimeout(sponsorTimeout);
        if(sponsorCurrent == null) sponsorCurrent = 0;
        //console.log("sponsorsCurrent = " + sponsorCurrent + " -- fading out " + $('#sponsors-right div.content a').slice(sponsorCurrent, sponsorCurrent + 3).length + " items");
        $('#sponsors-right div.content a').slice(sponsorCurrent + 1, sponsorCurrent + 3)
        .stop()
        .fadeOut();
        $('#sponsors-right div.content a:eq(' + sponsorCurrent + ')')
        .stop()
        .fadeOut(function(){
            $('#sponsors-right div.content a').slice(sponsorCurrent, sponsorCurrent + 3).hide();
            if(sponsorCurrent == null) sponsorCurrent = 0;
            sponsorCurrent = (sponsorCurrent + delta ) % sponsorTotal;
            //console.log("sponsorsCurrent = " + sponsorCurrent + " -- fading in " + $('#sponsors-right div.content a').slice(sponsorCurrent, sponsorCurrent + 3).length + " items");
            $('#sponsors-right div.content a').slice(sponsorCurrent, sponsorCurrent + 3)
            .css('opacity', '1')
            .stop()
            .fadeIn();
            sponsorTimeout = setTimeout(function(){changeSponsor(3);}, 4000);
        })
    }
    
    sponsorTimeout = setTimeout(function(){changeSponsor(3);}, 4000);
    
    
});

function load(hash){
    if(hash.match(/^\/register.*/)){//console.log(hash);
        $("<a href='" + hash + "' class='iframe'></a>").fancybox({
            hideOnContentClick: false,
            frameWidth: 650,
            frameHeight: 750,
            centerOnScroll: false
        }).click();
        //$('#top-right a').click();
    }
    else if(hash == "/login"){
        $("<a href='" + hash + "' class='iframe'></a>").fancybox({
            hideOnContentClick: false,
            frameWidth: 455,
            frameHeight: 350,
            centerOnScroll: false
        }).click();
    }
}