$(document).ready(function() {
    $(window).resize(function() {
        scale();
    });

    redirect();
    preLoadImages();
    scale();
});

var navigate = function(a, section, language) {
    window.location.href = '#/' + section;
    return false;
}

var getContent = function(a, section, language) {

    var urlProperties = '/' + language + '/' + section + '/proprietes';
    var urlContent = '/' + language + '/' + section + '/contenu';
    var top = left = 0;
    var container = $('.container');

    // Affiche la section en blanc clair.
    $('#menu ul li a.active').removeClass('active');
    $(a).addClass('active');
    
    $.getJSON(urlProperties, {}, function(properties) {
        var specifications = {
            left: getLeft(properties),
            top : properties.top,
            width : properties.width,
            height : properties.height,
            opacity : properties.opacity
        }

        // fadeOut la fenêtre
        if (jQuery.browser.msie) {
            container.hide();
        } else {
            container.fadeOut('slow');
        }

           // fadeOut l'image de fond
        $('#bg_image').fadeOut(800, function() {
            $('#bg_image').attr('src', '/medias/img/backgrounds/' + language + '/bg_' + section + '.jpg');

            // On récupère le contenu de la prochaine fêntre.
            $.get(urlContent, {}, function(content) {
                $('.content').html(content);
                container.css('zIndex', -1);
                container.show();
                init(specifications, false);
                container.hide();
                container.css('zIndex', 1);
                // On réaffiche l'image du fond
                $('#bg_image').fadeIn('slow', function() {
                    // Puis la fenêtre
                    if (jQuery.browser.msie) {
                        container.show();
                    } else {
                        container.fadeIn('800');
                    }
                });
            });
        });
    });

    return false;
}

var redirect = function() {
    var url = window.location.href;
    var pathname = url.substr(url.indexOf(window.location.pathname));
    var params = pathname.split('/');
    var pos = -1;
    var lang = '', controller = '', section = '';
    var toBeRedirected = true;

    try {
        lang = params[1];
        controller =  (typeof params[2] != 'undefined') ? params[2] : (lang == 'fr' ? 'nouvelles' : 'news');
        if (controller == '#') {
            toBeRedirected = false;
            controller = (typeof params[3] != 'undefined') ? params[3] : (lang == 'fr' ? 'nouvelles' : 'news');
        }
    } catch (err) {
        lang = 'en';
        controller = 'news';
    }
    
    if (toBeRedirected) {
        location.href = '/' + lang + '/#/' + controller;
    }
}

var init = function(specifications, first) {

        var container = $('.container');
        var isDisplayed = container.css('display', 'none') ? false : true;

        if (!isDisplayed) {
            container.css('zIndex', -1);
            container.show();
        }
        
        $('.opaque').css('background-image', 'url(/medias/img/opacity_' + specifications.opacity + '.png)');
        container.css('left', specifications.left);
        container.css('top', specifications.top);
        container.width(specifications.width);
        container.height(specifications.height);

        // html controls
        var content = $('.container .content');
        var h2 = $('.content h2');
        var text = $('.container .text');

        // dimensions
        var paddingContent = content.padding();
        var containerHeight = container.height();
        var marginH2 = h2.margin();
        var heightH2 = h2.height();
        var paddingText = text.padding();

        content.height(containerHeight - paddingContent.bottom);
        var heightText = content.height() - marginH2.top - marginH2.bottom - heightH2 - paddingText.top - paddingText.bottom;
        text.height(heightText - 2); // - moins les bordures;
        
        if ($('#jquery_jplayer').length > 0) {
            buildPlayer();
            $('.scroll-pane').height(heightText - 2 - $('.jp-interface').height()); // on set la hauteur aussi sur le conteneur qui contient les bars et le player.
        } else {
            $('.scroll-pane').height(heightText - 2); // on set la hauteur aussi sur le conteneur qui contient les bars.
        }
        $('.scroll-pane').jScrollPane(); // on relance une fois que le calcul est fait;
        setTabs();
        
        buildSlideshow();


        if (!isDisplayed) {
            container.hide();
            container.css('zIndex', 1);
        }

        if (first) {
            $(window).load(function() {
                show();
            })
        }
}

var show = function() {
    var container = $('.container');
    // On affiche le fond
    $('#bg_image').fadeIn('slow', function() {
        // Puis la fenêtre
        if (jQuery.browser.msie) {
            container.show();
        } else {
            container.fadeIn('slow');
        }
    });
}

var scale = function() {
    var browserheight = $(window).height();
    var offset = $('#content').offset();
    var margin = $('#footer').height();
    $('#content').height(browserheight - offset.top - $('#content').padding().bottom);
    $('#bg_image').cjObjectScaler({
         method: "fitHeight",
         fade:0
    });

}

var getLeft = function(properties) {
    if (properties.align == 'center') {
        return $(window).width()/2 - properties.width/2;
    } else if (properties.align == 'right') {
        return $(window).width() - properties.right - properties.width;
    } else {
        return properties.left;
    }
}

var setTabs = function() {

    $('.tab_off').hide();
    $('.tab_active').show();

    $('.tabs a').unbind('click').click(function() {
        var link = $(this).attr('href');
        var id = link.substr(link.indexOf('#')+1);

        $('.tabs a').removeClass('active');
        $(this).addClass('active');
        $('.tab').hide();
        $('.tab_active').removeClass('tab_active');
        $('#' + id).addClass('tab_active').show();
        if ($('#jquery_jplayer').length > 0) { //Si un player existe on réinit
            playItem = 0;
            displayPlayList();
            playListInit(false);
        }
        return false;
    });
}

var hashChange = function() {

    $(window).hashchange(function(){
        var hash = location.hash;
        var controller = hash.replace(/^#\//, '');
        var params = window.location.pathname.split('/');
        var lang = params[1];
        getContent($('a.menu_' + controller), controller, lang);
    });
    $(window).hashchange();
}

var playItem = 0;
var buildPlayer = function() {

    // Local copy of jQuery selectors, for performance.
    var jpRemainingTime = $('#jplayer_remaining_time');
    var hTotalTime = $('#h_total_time');
    
    $("#jquery_jplayer").jPlayer({
        ready: function() {
            displayPlayList();
            playListInit(false); // Parameter is a boolean for autoplay.
        },
        swfPath : '/medias/js',
        nativeSupport: true,
        errorAlerts : false,
        warningAlerts: false
    })
    .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
        var remainingTime = totalTime - playedTime;
        jpRemainingTime.text((totalTime == hTotalTime.val() && totalTime != 0 ? '-' : '') + $.jPlayer.convertTime(remainingTime));
        hTotalTime.val(totalTime);
    })
    .jPlayer("onSoundComplete", function() {
        playListNext();
    });

    $("#jplayer_previous").click( function() {
        playListPrev();
        $(this).blur();
        return false;
    });

    $("#jplayer_next").click( function() {
        playListNext();
        $(this).blur();
        return false;
    });
}


var buildSlideshow = function() {
    $("a[rel^='prettyPhoto']").prettyPhoto({
        animationSpeed:'fast',
        slideshow:false,
        modal: true,
        theme: 'facebook',
        overlay_gallery: false,
        opacity: 0.60
    });
}

/**
 * Fonctions de lecteur de jPlayer
 */

function displayPlayList() {
    var playList = $('.tab_active .jp-playlist ul li a');
    var index = 0;
    
    playList.each(function() {
        var _this = $(this);
        _this.data("index", index);
        _this.click(function() {
            var songIndex = $(this).data('index');
            if (playItem != songIndex) {
                playListChange(songIndex);
            } else {
                $("#jquery_jplayer").jPlayer("play");
            }
            $(this).blur();
            return false;
        });
        index += 1;
    })
}

function playListInit(autoplay) {
    if(autoplay) {
        playListChange( playItem );
    } else {
        playListConfig( playItem );
    }
}

function playListConfig( index ) {
    var currentSong = $('.tab_active .jp-playlist ul li a:eq(' + index + ')');
    var previousSong = $('.tab_active .jp-playlist ul li a:eq(' + playItem + ')');
    previousSong.removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
    currentSong.addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
    playItem = index;
    $("#jquery_jplayer").jPlayer("setFile", currentSong.attr('href'));
}

function playListChange( index ) {
    playListConfig(index);
    $("#jquery_jplayer").jPlayer("play");
}

function playListNext() {
    var playList = $('.tab_active .jp-playlist ul li a');
    var index = (playItem+1 < playList.length) ? playItem+1 : 0;
    playListChange( index );
}

function playListPrev() {
    var index = (playItem-1 >= 0) ? playItem-1 : playList.length-1;
    playListChange( index );
}

/* Preloader */

var cache = [];
var loadImage = function(i) {
    if (i == images.length) {
        $('#overlay p:first').html((lang == 'fr' ? 'Chargement ' : 'Loading ') + '100%');
        setTimeout(function() {
            $('#overlay').fadeOut("slow", function() {
                $(this).remove();
            });
        }, 500);
        
        hashChange();
        
    } else {
        var cacheImage = document.createElement('img');
        cache.push(cacheImage);
        $('#overlay p:first').html((lang == 'fr' ? 'Chargement ' : 'Loading ') + Math.floor(i * 100 / images.length) + '%...');
        $(cacheImage).load(function() {
            i+=1;
            loadImage(i);
        });
        $(cacheImage).attr('src', images[i]);
    }
}

var preLoadImages = function() {
    loadImage(0);
}

