// console.log calls will fail in IE etc halting the current block
// http://stackoverflow.com/questions/1114187/is-it-a-bad-idea-to-leave-firebug-console-log-calls-in-your-producton-javascrip/1114200#1114200
if(typeof console === "undefined") {
    console = { log: function() { } };
}

function showArchiveLinks() {
    var target = this;
    var year_id = $(target).next('.news-yearlinks').attr('id');
    $('.news-yearlinks').not('#'+year_id).slideUp(function() {
        $('.yearlinks-active').html('&#x25B8;');
        $(target).next('.news-yearlinks').slideDown();
        $(target).children('.yearlinks-active').html('&#x25BE;');
    });
}

$(document).ready(function() {

    // video detail page tabs
    $('.tabs li a[rel]')
        .click(function(){
            var $tab = $(this);
            // change the active tab label
            $tab.closest('ul.tabs')
                .find('li a[rel]')
                .removeClass('active-tab');
            $tab.addClass('active-tab');
            // change the shown tab body
            $('#tab-body')
                .children('div')
                .hide(function(){
                    $('#tab-body')
                        .children('#'+$tab.attr('rel'))
                        .show();
                });
            return false;
        });


    // avoid the page jumping to the top when # links are clicked
    $('a.not-a-link')
        .click(function(){return false;});

    // fix team footer to initially list teams only
    $('ul.team_footer ul').hide();
    $('ul.team_footer h3 a').click(function() {
            var that = this;
            $(this).closest('li').find('ul')
                .slideToggle(400,
                    // display section heading in grey
                    // to differentiate from riders
                    function(){
                        $(that).toggleClass('grey');
                    }
                );
            return false;
        });

    // contest rules reveal
    $('.view-rules')
        .click(function(){
            $('.rules')
                .slideDown();
            $(this)
                .hide();
        });


    // search box etc use title attr to store a default msg
    // that dissapears when the input receives focus
    $('input').defaultInputText();

    // manually write the querystring without the search button so that the querystring is kept clean
    $('form.site-search')
        .submit(function(){
            window.location = (
                $(this).attr('action') +
                '?' +
                $(this)
                    .serialize()  // unlike browsers, jQuery ignores controls w/o names
            );                    // so we must make sure the submit buttons have no name attrs
            return false;
        });

    // select menu levels, but filter out team footer which extends from the master team template
    $('.first-level, .second-level, .third-level')
        .filter(function (){return $(this).closest('.team_footer').size()===0;})
        .parent('li')
        .mouseenter(function(){
            $(this).find('>ul').hide(0).fadeIn('slow');
        });
        //.mouseleave(function(){
            // leaving this blank unless requested
        //})


    if ($('body').attr('id') == 'home') {
        $("#showcase").awShowcase({
            content_width:  650,
            content_height: 388,
            auto: true,
            continuous: true,
            interval: 3000,
            arrows: true

        });
    }
    $('#blogroll li a').live('mouseover', function(){
        var anchorPosition = $(this).position();
        var bubbleObj = $(this).next().next('div');
        var bubblePosition = bubbleObj.position();
        bubblePositionTop = anchorPosition.top - bubbleObj.outerHeight() - 5;
        bubblePositionLeft = anchorPosition.left;
        if($.browser.msie && $.browser.version <= '7.0')  {bubblePositionTop = anchorPosition.top + 20;bubblePositionLeft = anchorPosition.left + 15;}

        bubbleObj.css({'top' : bubblePositionTop + 'px', 'z-index' : '99999999', 'left': bubblePositionLeft + 'px'});
        bubbleObj.fadeIn();
    }).live('mouseout', function(){
        $(this).next().next('div').fadeOut();
    });


    var teamRealHeight = $('#teamdetail-bio div').height();
    var teamMinHeight = $('#teamdetail-bio').css('height');
    teamLessMsg = $('#teamdetail-expandbio').attr('rel');
    teamMoreMsg = $('#teamdetail-expandbio').text();

    if(teamRealHeight < teamMinHeight) {
        $('#teamdetail-expandbio').remove();
    } else {
        $('#teamdetail-bio').css('height', teamMinHeight);
    };

    $('#teamdetail-expandbio').toggle(
        function() {
            var aTag = $(this);
            $('#teamdetail-bio')
                .animate(
                    {'height': teamRealHeight},
                    'slow',
                    function(){aTag.text(teamLessMsg);
                        $('.team-grad-cover').hide();
                    }
                );
        },
        function() {
            var aTag = $(this);
            $('#teamdetail-bio')
                .animate(
                    {'height': teamMinHeight},
                    'slow',
                    function(){aTag.text(teamMoreMsg);
                        $('.team-grad-cover').show();
                    }
                );
        }
    );

    var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
    chrome: /chrome/.test( userAgent ),
    safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
    if ($('body').attr('id') == 'video_detail') $('#echo-stream, #echo-submit-form').css('width','638px')
    $('.titlebar').bind('click', showArchiveLinks);
    $('.news-yearlinks:not(:first)').hide().prev('.titlebar').append('<span class="yearlinks-active">&#x25B8;</span>');
    $('.news-yearlinks:first').prev('.titlebar').append('<span class="yearlinks-active">&#x25BE;</span>');
});

$(window).load(function(){
    $('#ifram').html('');
});

// global ajax csrf https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        // added fallback to check for named hidden field ~TomV
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken') || $('[name="csrfmiddlewaretoken"]').val() );
    }
});

