$(function() {


    ////////////////////////////////////////
    // Footer rotation
    $('.spons a:gt(0)').hide();
    setInterval(function(){
        $('.spons a:first-child').fadeOut()
                                 .next('a')
                                 .fadeIn()
                                 .end()
                                 .appendTo('.spons');
        }, 5000);

    $('.suppl a:gt(0)').hide();
    setInterval(function(){
        $('.suppl a:first-child').fadeOut()
                                 .next('a')
                                 .fadeIn()
                                 .end()
                                 .appendTo('.suppl');
        }, 3000);
    // Footer rotation
    ////////////////////////////////////////

    ////////////////////////////////////////
    // Headers
    if (shouldLoadHeaders()) {
        loadHeaders();
    }
    // Headers
    ////////////////////////////////////////

    ////////////////////////////////////////
    // Overlay
    if (shouldDisplayOverlay()) {
        getOverlay();
    } else {
        main_setDefaultHeader();
        $("#overlay_gallery").remove();
        $("#overlay_news").remove();
        $("#overlay_ports").remove();
        $("#overlay_race").remove();
        $("#overlay_teams").remove();
        $("#overlay_village").remove();
        $("#overlay_rdc").remove();
    }
    // Overlay
    ////////////////////////////////////////

    if (!system_enableRotatingHeaders) {
        // Setup a header image in case the overlay is disabled
        main_setDefaultHeader();
        return;
    }


    ////////////////////////////////////////
    // MULTIMEDIA WIDGET TAB
    // Activate the first tab on media widget;
    var tabActive = 0;
    //
    if ($('ul.multimediaTabs').length > 0) {
        $('ul.multimediaTabs').tabs('div.multimediaPanes > div', {
            /* tabs configuration goes here */

            // Active Tab definded by tabActive var.
            initialIndex: tabActive

        });
    }
    // MULTIMEDIA WIDGET TAB
    ////////////////////////////////////////

    ////////////////////////////////////////
    // TABS
    // setup ul.tabs to work as tabs for each div directly under div.panes
    if ($('ul.tabs').length > 0) {
        $('ul.tabs').tabs('div.panes > div', {

            effect: 'fade',
            event:'mouseover',

            // start from the beginning after the last tab
            rotate: true
        });
    }
    // TABS
    ////////////////////////////////////////

     ////////////////////////////////////////
    // TABS RDC WIDGET
    // setup ul.tabs to work as tabs for each div directly under div.panes
    if ($('ul.contentTabs').length > 0) {
        $('ul.contentTabs').tabs('div.contentPanes > div', {

            effect: 'fade',
            // Active Tab definded by tabActive var.
            initialIndex: 0


        });
    }
    // TABS
    ////////////////////////////////////////

         ////////////////////////////////////////
    // SUBTABS
    // setup ul.tabs to work as tabs for each div directly under div.panes
    if ($('ul.subcontentTabs').length > 0) {
        $('ul.subcontentTabs').tabs('div.subcontentPanes > table', {

            effect: 'fade',
            // Active Tab definded by tabActive var.
            initialIndex: 0


        });
    }
    // TABS
    ////////////////////////////////////////

});

function main_setDefaultHeader() {
    $("#header").css('background-image', 'url(http://c43690.r90.cf2.rackcdn.com/m3605_crop14_980x170.jpg)');
}

function debug(d) {
    if (system_debug) {
        //console.debug(d);
    }
}

/**
 * take a string like "some_text_id_56" and grab only the part after the last underscore
 */
function getSuffix(id, separator) {
    if (separator == undefined) {
        separator = '_';
    }
    var arr = id.split(separator);
    return arr[arr.length - 1];
};

function getOverlay() {
    // AJAX overlays
    var overlayURL = '/' + system_language + '/overlay.json';
    $.get(overlayURL, {}, function(json){
        $("#overlay_gallery").html(json['gallery']);
        $("#overlay_news").html(json['news']);
        $("#overlay_ports").html(json['ports']);
        $("#overlay_race").html(json['race']);
        $("#overlay_teams").html(json['teams']);
        $("#overlay_village").html(json['village']);
        $("#overlay_rdc").html(json['rdc']);

        // Set dynamic rdc link to incoming url
        $(".dynamicRdcLink").attr('href', json['rdcLink']);

        if (system_enableRotatingHeaders) {
            changeRotatingHeaders(json['rotatingHeaders']);
        }
    }, 'json');
}

function loadHeaders() {
    // Headers and countdowns
    var url = '/' + system_language + '/headerData.json';

    $.get(url, {}, function(json){
       headers_injectServerTimeIntoHeaderDataAndDoSetup(json['headerData']);
    }, 'json');
}


////////////////////////////////
// Header rotation

function changeRotatingHeaders(headers) {
    var randomHeaderIndex = Math.floor(Math.random() * headers.length);
    var headerURL = headers[randomHeaderIndex];

    // Pre load the image so that when we set it to the header we don't
    // have to wait with an empty header
    var image = new Image();
    image.onload = function() {
        $("#header").css('background-image', 'url(' + headerURL + ')');
    };
    image.src = headerURL;
}
// Header rotation
////////////////////////////////////////

function shouldLoadHeaders() {
    if (!system_enableHeaders) {
        return false;
    }

    return true;
}

/**
 * Do some broser detection and return wheter the overlay should be displayed or not.
 * Basically avoid these browsers:
 *      iPod, iPad, iPhone
 *      IE6, IE7
 *
 * @return bool
 */
function shouldDisplayOverlay() {

    if (!system_enableOverlay) {
        return false;
    }

    var deviceAgent = navigator.userAgent.toLowerCase();
    var iDevice = deviceAgent.match(/(iphone|ipod|ipad)/);

    if (iDevice) {
        return false;
    }

    if ($.browser.msie) {
        var majorVersion = parseInt($.browser.version, 10);
        if (majorVersion == 6 || majorVersion == 7) {
            return false;
        }
    }

    return true;
}

function setCookie(name,value,minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

function postComment() {
    if (!$('#recaptcha_response_field').val() || !$('#formComment_name').val() || !$('#formComment_email').val() || !$('#formComment_comment').val()) {
        if (!$('#formComment_name').val()){
            $('#formComment_name').addClass('redField');
        }
        if (!$('#formComment_email').val()){
            $('#formComment_email').addClass('redField');
        }
        if (!$('#formComment_comment').val()){
            $('#formComment_comment').addClass('redField');
        }
        $('.errorForm').show();
        $('.errorForm').html($('#lang_comments_mandatory_error').val());
    } else {
        $('#commentFormShow').hide();
        $('#commentFormAjax').show();
        $("#commentFormAjax").addClass("ajaxLoaderComments");
        $("#commentFormAjax").html("");
        idNews  = $('#newsId').val();
        $.post('/' + system_language + '/news/'+idNews+'/post-comment.json', {
                'name':     $('#formComment_name').val(),
                'email':    $('#formComment_email').val(),
                'website':  $('#formComment_website').val(),
                'comment':  $('#formComment_comment').val(),
                'captchar': $('#recaptcha_response_field').val(),
                'captchac': $('#recaptcha_challenge_field').val()
            }, function(response) {
                if (response.success) {
                    $('#commentFormShow').hide();
                    $('#commentFormAjax').show();
                    $("#commentFormAjax").removeClass("ajaxLoaderComments");
                    $("#commentFormAjax").html($('#lang_comments_success').val());
                } else {
                    $('#formComment_comment').removeClass('redField');
                    $('#formComment_email').removeClass('redField');
                    $('#formComment_name').removeClass('redField');
                    $('.errorForm').html(response.error)
                    $('.errorForm').show();
                    Recaptcha.reload();
                    $('#commentFormShow').show();
                    $('#commentFormAjax').hide();
                    $("#commentFormAjax").removeClass("ajaxLoaderComments");
                    $("#commentFormAjax").html("");
                }
        })
    }
}

function comments_resetForm() {
    $('#formComment_name').val(''),
    $('#formComment_email').val(''),
    $('#formComment_website').val(''),
    $('#formComment_comment').val(''),
    $('#recaptcha_response_field').val(''),
    $('#recaptcha_challenge_field').val('')
    $('.errorForm').hide();
    $('.errorForm').html('');
    $('#commentFormShow').show();
    $('#commentFormAjax').hide();
    Recaptcha.reload()
}

function sendMediaZoneRegister() {
    firstname       = $('#firstname').val()
    email           = $('#email').val()
    password        = $('#password').val()
    repeatpassword  = $('#repeatpassword').val()
    lastname        = $('#lastname').val()
    company         = $('#company').val()
    media_type      = $('#media_type').val()
    country         = $('#country').val()
    captcha         = $('#recaptcha_response_field').val()
    if (!firstname || !email || !password || !repeatpassword || !lastname || !company || !media_type || !country || !captcha) {
        if (!firstname){
            $('#firstname').addClass('redField');
        }
        if (!email){
            $('#email').addClass('redField');
        }
        if (!password){
            $('#password').addClass('redField');
        }
        if (!repeatpassword){
            $('#repeatpassword').addClass('redField');
        }
        if (!lastname){
            $('#lastname').addClass('redField');
        }
        if (!company){
            $('#company').addClass('redField');
        }
        if (!media_type){
            $('#media_type').addClass('redField');
        }
        if (!email){
            $('#email').addClass('redField');
        }
        if (!country){
            $('#country').addClass('redField');
        }
        if (!captcha){
            $('#captcha').addClass('redField');
        }
        $('.errorMessage').show();
        $('.errorMessage').html($('#lang_comments_mandatory_error').val());
    } else {
        if (password != repeatpassword) {
            $('.errorMessage').show();
            $('.errorMessage').html($('#lang_mediazone_passwords_not_match').val());
        } else {
            return true;
        }
    }
    window.scrollTo(0,171);
    return false;
}

function sendMediaZoneProfile() {
    firstname       = $('#firstname').val()
    password        = $('#password').val()
    repeatpassword  = $('#repeatpassword').val()
    lastname        = $('#lastname').val()
    company         = $('#company').val()
    media_type      = $('#media_type').val()
    country         = $('#country').val()
    if (!firstname || !lastname || !company || !media_type || !country) {
        if (!firstname){
            $('#firstname').addClass('redField');
        }
        if (!email){
            $('#email').addClass('redField');
        }
        if (!lastname){
            $('#lastname').addClass('redField');
        }
        if (!company){
            $('#company').addClass('redField');
        }
        if (!media_type){
            $('#media_type').addClass('redField');
        }
        if (!country){
            $('#country').addClass('redField');
        }
        $('.errorMessage').show();
        $('.errorMessage').html($('#lang_comments_mandatory_error').val());
    } else {
        if (password != repeatpassword) {
            $('.errorMessage').show();
            $('.errorMessage').html($('#lang_mediazone_passwords_not_match').val());
        } else {
            return true;
        }
    }
    window.scrollTo(0,171);
    return false;
}

function sendPasswordChange() {
    password        = $('#vorpassword').val()
    password2       = $('#vorpassword2').val()
    if (!password || !password2) {
        if (!password){
            $('#vorpassword').addClass('redField');
        }
        if (!password2){
            $('#vorpassword2').addClass('redField');
        }
        $('.errorMessage').show();
        $('.errorMessage').html($('#lang_comments_mandatory_error').val());
    } else {
        if (password != password2) {
            $('.errorMessage').show();
            $('.errorMessage').html($('#lang_mediazone_passwords_not_match').val());
        } else {
            return true;
        }
    }
    window.scrollTo(0,171);
    return false;
}

function sendSyndicateRegister() {
    firstname       = $('#firstname').val()
    email           = $('#email').val()
    password        = $('#password').val()
    repeatpassword  = $('#repeatpassword').val()
    lastname        = $('#lastname').val()
    company         = $('#company').val()
    country         = $('#country').val()
    captcha         = $('#recaptcha_response_field').val()
    if (!firstname || !email || !password || !repeatpassword || !lastname || !company || !country || !captcha) {
        if (!firstname){
            $('#firstname').addClass('redField');
        }
        if (!email){
            $('#email').addClass('redField');
        }
        if (!password){
            $('#password').addClass('redField');
        }
        if (!repeatpassword){
            $('#repeatpassword').addClass('redField');
        }
        if (!lastname){
            $('#lastname').addClass('redField');
        }
        if (!company){
            $('#company').addClass('redField');
        }
        if (!email){
            $('#email').addClass('redField');
        }
        if (!country){
            $('#country').addClass('redField');
        }
        if (!captcha){
            $('#captcha').addClass('redField');
        }
        $('.errorMessage').show();
        $('.errorMessage').html($('#lang_comments_mandatory_error').val());
    } else {
        if (password != repeatpassword) {
            $('.errorMessage').show();
            $('.errorMessage').html($('#lang_mediazone_passwords_not_match').val());
        } else {
            return true;
        }
    }
    window.scrollTo(0,171);
    return false;
}

////////////////////////////////////////
// Countdown

var HEADER_COOKIE = "headers_do_not_propmpt_user";

var HEADER_ID_SUBSEC_LEG    = 1;
var HEADER_ID_SUBSEC_INPORT = 2;

var HEADER_ID_CAT_CLOCK      = 1;
var HEADER_ID_CAT_NOCLOCK    = 2;

var HEADER_COUNTDOWN_TEMPLATE = '<div class="hours"><span class="value">{hnn}:{mnn}:{snn}</span> H:M:S</div><div class="days"><span class="value">{dn}</span> {dl}</div>';

function headers_injectServerTimeIntoHeaderDataAndDoSetup(headerData) {

    var time = null;
    // Inject the serverTime key from fresh data off the cloud sites server
    // This can't be taken from the cache. It has to be fresh.
    $.ajax({url: 'http://vorsitecloud.info/serverTimeJsonp.php',
        async: true,
        dataType: 'jsonp',
        success: function(json) {
            debug('Using remote server time: ' + json['time'])
            time = new Date(json['time']);
            headerData['serverTime'] = time;
            headers_setup(headerData);

        }, error: function(http, message, exc) {
            debug('Using local browser time. Server returned message: ' + message + ', exc: ' + exc);
            time = new Date();
            headerData['serverTime'] = time;
            headers_setup(headerData);
    }});

}

function headers_setup(headerData) {

    if (headerData['id_cat'] == HEADER_ID_CAT_NOCLOCK) {
        headers_setupNoclock(headerData);
        return;
    }

    ////////////////////////////////////////
    // GLOBAL TIMER DEFAULTS

    // Timer language
    if (system_language == 'en') {
        $.countdown.setDefaults($.countdown.regional['']);
    } else {
        $.countdown.setDefaults($.countdown.regional[system_language]);
    }

    // Timer layout
    $.countdown.setDefaults({layout: HEADER_COUNTDOWN_TEMPLATE});

    // GLOBAL TIMER DEFAULTS
    ////////////////////////////////////////


    if (headerData['live'] == 1) {
        headers_setupLive(headerData);
    } else {
        if (headerData['countdown'] == 0) {
            // live = 0, countdown = 0
            if (headerData['pause']['pause'] == '0000-00-00 00:00:00') {
                // Regular countup
                headers_setupCountup(headerData);
            } else {
                // Paused countup
                headers_setupPausedCountup(headerData);
            }
        } else {
            // live = 0, countdown = 1
            if (new Date(headerData['countdownFinishTime']) < headerData['serverTime']) {
                // Countdown has expired. Show countup.
                headers_setupCountup(headerData);
            } else {
                // Show countdown
                headers_setupCountdown(headerData);
            }

        }
    }
}




/**
 * Get live time from cloud server. If server is not available default
 * to the client's time
 */
function headers_getServerTime() {
    var time = null;
    $.ajax({url: 'http://vorsitecloud.info/serverTime.php',
        async: false,
        dataType: 'text',
        success: function(text) {
            debug('Using remote server time')
            time = new Date(text);
        }, error: function(http, message, exc) {
            debug('Using local browser time');
            debug(http);
            debug(message);
            debug(exc);
            time = new Date();
    }});
    return time;
}

function headers_setupLive(headerData) {
    debug('Header: LIVE');
    $('#header_timer').hide();
    $('#header_live').show();

    $('#header_live').find('.xLine1').text(headerData['legport']);
    $('#header_live').find('.xLine2').text(headerData.vars['headers_live_streaming_now']);

    // Remove cookie for when we go back to non live mode
    deleteCookie(HEADER_COOKIE);
}

function headers_setupNoclock(headerData) {
    debug('Header: NO CLOCK');
    var $header_noclock = $('#header_noclock');

    $('#header_timer').hide();
    $('#header_live').hide();
    $header_noclock.show();

    $header_noclock.find('.xLine1').text(headerData['legport']);
    $header_noclock.find('.xLine2').html(headerData['livestream']);
    $header_noclock.find('.xLine3').text(headerData.vars['headers_fleet_transit']);

    // Remove cookie for when we go back to non live mode
    deleteCookie(HEADER_COOKIE);
}

/**
 * Countup from a certain date in headerData.
 * Set "useCurrentTime" to true if you want to use the browsers current time to
 * count up from. This prevents the countdown to display the wrong time in the following scenario:
 * - The user loads the page and the countdown will expire in 10 minutes. When the countdown expires,
 *   the headerData['countdownFinishTime'] will be set to ten minutes in the past, so the countup will
 *   start from 00:10:00 instead from 00:00:00
 */
function headers_setupCountup(headerData, useCurrentTime) {
    debug('Header: COUNT UP');
    var $header_timer = $('#header_timer');

    $header_timer.show();
    $('#header_live').hide();

    $header_timer.find('.xLine1').text(headerData['legport']);
    $header_timer.find('.xLine2').text(headerData['livestream']);
    $header_timer.find('.xLine3').text(headerData.vars['headers_elapsed_time']);

    // Simple hack to completely destroy the timer as it's destroy method is buggy
    $('#globalCountdown').replaceWith('<div id="globalCountdown"></div>');

    if (useCurrentTime) {
        // Make sure NOT to use serverSync when setting the local date as the
        // server might have different minutes:seconds setup and this will generate
        // an undesirable offset in the countdown. If you use serverSync the countup
        // might start from some seconds or minutes instead of from 00:00:00
        $('#globalCountdown').countdown({
            since     : new Date()
        });
    } else {
        $('#globalCountdown').countdown({
            since     : new Date(headerData['countdownFinishTime']),
            serverSync: headers_getServerTime
        });
    }
}

/**
 * Countup from a certain date in headerData but pause the countup (so it never moves)
 */
function headers_setupPausedCountup(headerData) {
    debug('Header: PAUSED COUNT UP');
    var $header_timer = $('#header_timer');

    $header_timer.show();
    $('#header_live').hide();

    $header_timer.find('.xLine1').text(headerData['legport']);
    $header_timer.find('.xLine2').text(headerData['livestream']);
    $header_timer.find('.xLine3').text(headerData.vars['headers_elapsed_time_paused']);

    // Simple hack to completely destroy the timer as it's destroy method is buggy
    $('#globalCountdown').replaceWith('<div id="globalCountdown"></div>');

    var html = HEADER_COUNTDOWN_TEMPLATE;
    html = html.replace(/{hnn}/i, headerData['pause']['hours']);
    html = html.replace(/{mnn}/i, headerData['pause']['minutes']);
    html = html.replace(/{snn}/i, headerData['pause']['seconds']);
    html = html.replace(/{dn}/i,  headerData['pause']['days']);
    html = html.replace(/{dl}/i,  headerData['vars']['time_days']);

    $('#globalCountdown').html(html);
}

function headers_setupCountdown(headerData) {
    debug('Header: COUNT DOWN');
    $('#header_timer').show();
    $('#header_live').hide();

    var $header_timer = $('#header_timer');

    $header_timer.show();
    $('#header_live').hide();

    var serverTime                     = headerData['serverTime'];
    var countDownFinishTime            = new Date(headerData['countdownFinishTime']);
    var countDownFinishTimeInSeconds   = (countDownFinishTime.getTime() - serverTime.getTime()) / 1000;

    var countDownFinishTime15          = new Date(countDownFinishTime.getTime() - (15 * 60000)); // minutes * 60000
    var countDownFinishTime15InSeconds = (countDownFinishTime15.getTime() - serverTime.getTime()) / 1000;

    var countDownFinishTime5           = new Date(countDownFinishTime.getTime() -  (5 * 60000)); // minutes * 60000
    var countDownFinishTime5InSeconds  = (countDownFinishTime5.getTime() - serverTime.getTime()) / 1000;

    var twentyFourHsToGo               = new Date(countDownFinishTime.getTime() - (24 * 3600000)); // hours * 3600000

    // Paint countdown red when there are less than 24hs to reach the expiry time.
    if (headerData['serverTime'] > twentyFourHsToGo) {
        $('#globalCountdown').addClass('highlight');
    }

    // IMPORTANT: Since we are using a cross-domain JSONP call to get the server time, the serversync
    // function cannot make any ajax calls. It already needs to have the time ready to be returned.
    $('#globalCountdown')        .countdown({until: countDownFinishTimeInSeconds,   onExpiry: function() {headers_finishCountdown(headerData)}});
    $('#globalCountdownMin15Min').countdown({until: countDownFinishTime15InSeconds, onExpiry: function() {headers_alert(headerData, 2)}});
    $('#globalCountdownMin5Min') .countdown({until: countDownFinishTime5InSeconds,  onExpiry: function() {headers_alert(headerData, 3)}});

    $header_timer.find('.xLine1').text(headerData['legport']);
    $header_timer.find('.xLine2').text(headerData['livestream']);
    $header_timer.find('.xLine3').text(headerData.vars['headers_action_start_in']);

}

function headers_finishCountdown(headerData) {
    if (headerData['id_subsec'] == HEADER_ID_SUBSEC_LEG) {
        headers_setupCountup(headerData, true);
    } else if (headerData['id_subsec'] == HEADER_ID_SUBSEC_INPORT) {
        headers_setupLive(headerData);
    }
}

function headers_alert(headerData, messageNumber) {

    var message;

    if (headerData['id_subsec'] == HEADER_ID_SUBSEC_LEG) {
        message = headerData.vars['header_message' + messageNumber];

    } else if (headerData['id_subsec'] == HEADER_ID_SUBSEC_INPORT) {
        message = headerData.vars['header_port_message' + messageNumber];
    }

    debug('ALERT ' + message);

    var promptUser = getCookie(HEADER_COOKIE);

    if (promptUser != null) {
        // Cookie is present so don't prompt the user
        return;
    }

    if (confirm(message)) {
        // User confirmed so set cookie in order to not display this dialog again
        setCookie(HEADER_COOKIE, 1, 16000);
        window.location = "http://www.volvooceanrace.com";
    }
}

//Countdown
////////////////////////////////////////
