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

        window.isiOS = navigator.userAgent.match(/iPad|iPod|iPhone/i) != null;
        window.debug = false;
        window.slideshowTimeout = 7000;
        window.contentHeight = 1000;
        window.siteReady = false;
        window.contentMinHeight = 440;

        // Effets à l'ouverture de la homepage
        var enterHomepage = function(){
            // Positionner la page à la dernière position de scroll vertical connue
            scrollToPreviousPagePos();
            // Agrandir la ligne centrale pour pousser le contenu en dehors de l'écran avant de le faire réapparaître
            $('#content-center-center').css('height', $(document.body).height());
            // Faire apparaître l'entête
            $('#animation-header-mask').animate({
                'opacity': 1,
                'top': '0px'
            }, 500, function(){
                // Faire apparaître le contenu central et le pied-de-page
                $('#content-center-center, #content').animate({
                    'height': window.contentHeight,
                    'opacity': 1
                }, 1250, function(){
                    $('.homepage').css('overflow', 'auto');
                    window.siteReady = true;
                });
                // Faire apparaître le contenu de l'entête
                $('#content-top').animate({
                    'opacity': 1
                }, 250, function(){
                    // Faire apparaître les images de fond
                    launchSlideshow();
                    // Faire apparaître le contenu après quelques millisecondes
                    setTimeout(function(){
                        $('#article-wrapper, .btn-fullscreen-on').fadeTo(1500, .9);
                    }, 1750);
                });
            });
        };

        // Effets à l'ouverture de la page
        var enterPage = function(){
            window.siteReady = true;
            // Positionner la page à la dernière position de scroll vertical connue
            scrollToPreviousPagePos();
            // Redimensionner le contenu central (en hauteur) pour s'adapter à l'écran
            resizeContent();
            // Faire apparaître les images de fond
            launchSlideshow();
            // Faire apparaître le contenu
            $('#article-wrapper, .btn-fullscreen-on').fadeTo(500, .9);
        };

        var resizeContent = function(){
            $('#content-center-center, #content').height(window.contentHeight);
        };

        // Effets à la fermeture de la page
        window.leavePage = function(url){
            var a = $('#menu-bottom-nav .current a');
            if (a.length == 1) {
                // grab the text and width
                var title = a.html();
                var h = a.outerHeight();
                // append a span with the content in, to mask over the link      
                a.append("<span style='display:block;top:0px'>"+title+"</span>");
                a.parent('li').removeClass('current');
                a.find('span').animate({
                  top: h+'px'
                }, 250, function(){ 
                    a.find('span').hide();
                    animating = false;
                });
            }
            // Mémoriser la position verticale du scroll
            $.cookie('yscroll', $(window).scrollTop());
            // Faire disparaître le contenu
            $('#article-wrapper, img[asyncsrc]').fadeTo(500, 0, function(){
                location.href = url;
            });
        };

        var scrollToPreviousPagePos = function(){
            var yscroll = $.cookie('yscroll') || 0;
            setTimeout(function(){ window.scrollTo(0, yscroll) }, 1);
        };

        var _slidingImage = 0;
        var _slideImages = $('img[asyncsrc].background-photo');

        var toggleImages = function(){
            if (_slideImages.length >= 1) {
                _slideImages.fadeOut(750);
                setTimeout(function(){
                    var img = $(_slideImages[_slidingImage])
                    loadAsyncImage(img);
                    _slidingImage++;
                    if (_slidingImage > _slideImages.length-1) _slidingImage = 0;
                }, 750);
            }
        };

        // Charger l'image de fond de manière asynchrone
        var launchSlideshow = function(){
            if (window.debug) return;
            toggleImages();
            if (_slideImages.length > 1) setInterval(toggleImages, window.slideshowTimeout);
        };

        // Charger une image de manière asynchrone
        var loadAsyncImage = function(img){
            var src = img.attr('asyncsrc');
            if (isPanoramicDisplay()) {
                var screenRatio = $(document.body).outerHeight() / $(document.body).outerWidth();
                var imgHeight   = $(document.body).outerHeight() - 30;
                var imgWidth    = img.attr('data-width') * imgHeight / img.attr('data-height');
                img.height(imgHeight);
                img.width(imgWidth);
                img.hide().attr('src', src).css({
                    'top': '30px',
                    'left': '50%',
                    'margin-left': - imgWidth / 2
                }).fadeIn(1000);
            }
            else {
                img.hide().attr('src', src).fadeIn(1000);
            }
        };

        var isPanoramicDisplay = function(){
            return $(document.body).hasClass('panoramic-display');
        };

        var fullScreenOn = function(event){
            event.preventDefault();
            var btnHide = $('.btn-fullscreen-on');
            var btnPos = btnHide.offset();
            btnHide.clone().appendTo($(document.body)).css({
                position: 'absolute',
                top: btnPos.top,
                left: btnPos.left
            }).animate({
                top: 35,
                opacity: 0
            }, 750, function(){
                $(this).remove();
            });
            $('#article-wrapper').fadeTo(350, 0, function(){
                $('.hide-menu-element').fadeTo(500, 0, function(){ $(this).hide() });
                $('.btn-fullscreen-off').fadeTo(350, 1);
            });
        };

        var fullScreenOff = function(event){
            event.preventDefault();
            $('.hide-menu-element').show().fadeTo(500, 1);
            $('.btn-fullscreen-off').fadeTo(250, 0);
            $('#article-wrapper').fadeTo(500, .9);
        };

        /**
         * Masque coulissant au rollover sur le menu du haut
         */
        var rolloverFromTop = function(){
            // make the iteration object a jquery object
            var a = $(this);
            var animating = false;
            // grab the text and width
            var title = a.html();
            var h = a.height();
            // append a span with the content in, to mask over the link      
            a.append("<span style='height: 0px; display: none'>"+title+"</span>");
            var span = a.find('span');
            // iOS
            if (window.isiOS) {
                a.click(function(){
                    span.stop(true,true).show().animate({ height: h+'px' }, 250);
                });
            }
            // Other browsers
            else {
                a.hover(function(){
                    span.stop(true,true).show().animate({
                        height: h+'px'
                    }, 250, function(){
                        animating = false;
                    });
                }, function() {
                    span.animate({
                        height: '0px'
                    }, 150, function(){ 
                        span.hide();
                        animating = false;
                    });
                });
            }
        };

        /**
         * Masque coulissant au rollover sur le menu du bas
         */
        var rolloverFromBottom = function(){
            // make the iteration object a jquery object
            var a = $(this);
            var animating = false;
            // grab the text and width
            var title = a.html();
            var h = a.outerHeight();
            // append a span with the content in, to mask over the link      
            a.append("<span style='display:none'>"+title+"</span>");
            var span = a.find('span');
            // iOS
            if (window.isiOS) {
                a.click(function(){
                    span.stop(true,true).show().animate({ top: 0 }, 400);
                });
            }
            // Other browsers
            else {
                a.hover(function(){
                    span.stop(true,true).show().animate({
                        top: 0
                    }, 400, function(){
                        animating = false;
                    });
                }, function() {
                    span.animate({
                      top: h+'px'
                    }, 150, function(){ 
                        span.hide();
                        animating = false;
                    });
                });
            }
        };

        /**
         * Masque coulissant au rollover sur le menu des articles
         */
        var rolloverFromLeft = function(){
            // make the iteration object a jquery object
            var a = $(this);
            var animating = false;
            // grab the text and width
            var title = a.html();
            var w = a.width();
            // append a span with the content in, to mask over the link      
            a.append("<span style='display:none'>"+title+"</span>");
            var span = a.find('span');
            // iOS
            if (window.isiOS) {
                // do the hover funcs
                a.click(function(){
                    span.stop(true,true).show().animate({ width: w+'px' }, 350);
                });
            }
            // Other browsers
            else {
                a.hover(function(){
                    span.stop(true,true).show().animate({
                        width: w+'px'
                    }, 350, function(){
                        animating = false;
                    });
                }, function() {
                    span.animate({
                        width: 0
                    }, 150, function(){ 
                        span.hide();
                        animating = false;
                    });
                });
            }
        };

        /* * * * * * * * * * * * * * * * * * * * *
         *   ROLLOVER SUR LES MENUS HAUT ET BAS  *
         * * * * * * * * * * * * * * * * * * * * */

        $('a[rel="animate"]').each(function(){
            $(this).attr('href', "javascript:window.leavePage('" + $(this).attr('href') + "');");
        });

        $('#menu-top-nav a').each(rolloverFromTop);
        $('#menu-bottom-nav a').each(rolloverFromBottom);

        /* * * * * * * * * * * * * * * * * * * * *
         *   GESTION DE LA NAVIGATION D'ARTICLE  *
         * * * * * * * * * * * * * * * * * * * * */

        // Barre de scroll personnalisée
        $('div[class|="scrollable-article"]').scrollbar();

        var articleNav = $('.article-nav');
        var articleNavLinks = articleNav.find('a');

        var showArticleSection = function(){
            var scrollableArticles = $('div[class|="scrollable-article"]');
            // Masquer les sections et le lien du menu actif
            scrollableArticles.css('display','none');
            articleNav.find('.current').removeClass('current');
            // Afficher la section par défaut
            if (location.hash == '') {
                scrollableArticles.first().css('display','block');
                articleNavLinks.first().parent().addClass('current');
            }
            // Afficher la section en fonction du hash
            else {
                $('a[name="'+location.hash.substring(1)+'"]').closest('div[class|="scrollable-article"]').css('display','block');
                articleNavLinks.filter('a[href="'+location.hash+'"]').parent().addClass('current');
            }
            articleNav.trigger('lameloise_show_article', [location.hash]);
        };

        // La navigation est présente
        if (articleNav.length) {
            // Activer le rollover sur le menu
            articleNavLinks.each(rolloverFromLeft);
            // Activer le menu en cours
            articleNavLinks.click(function(event){
                articleNav.find('.current').removeClass('current');
                $(this).parent('li').addClass('current');
            });
            $(window).bind('hashchange', showArticleSection);
            showArticleSection();
        }

        // Afficher/masquer l'article
        $('.btn-fullscreen-on').click(fullScreenOn);
        $('.btn-fullscreen-off').click(fullScreenOff);

        $('a.button, a.previous-page').hover(function(){
            $(this).fadeTo(700, 1);
        }, function(){
            $(this).fadeTo(500, .7);
        });

        $('#menu-bottom-address').hover(function(){
            $('#menu-bottom-address-bkg').fadeTo(500, .7);
        }, function(){
            $('#menu-bottom-address-bkg').fadeTo(250, 0);
        });

        /* * * * * * * * * * * * * * * * * * * *
         *   GESTION DES RESOLUTIONS D'ECRANS  *
         * * * * * * * * * * * * * * * * * * * */

        // Resolution breakpoints
        var onWindowResize = function(event){
            var windowWidth  = $(this).width();
            var windowHeight = $(this).height();
            if (windowWidth <= 1100) {
                $('body').addClass('max-width-1100');
            } else {
                $('body').removeClass('max-width-1100');
            }
            windowWidth/windowHeight >= 1.88 ?
                $(document.body).addClass('panoramic-display') :
                $(document.body).removeClass('panoramic-display');
            window.contentHeight = windowHeight-300 > window.contentMinHeight ? windowHeight-300 : window.contentMinHeight;
            if (window.siteReady) resizeContent();
        };
        $(window).bind('resize', onWindowResize);
        $(window).trigger('resize');

        /* * * * * * * * * * * * * * * * * * * * * *
         *   GESTION DES PNG TRANSPARENTS POUR IE  *
         * * * * * * * * * * * * * * * * * * * * * */

        $(document).pngFix();

        /* * * * * * * * * * * * * * * * *
         *   INITIALISATION DE LA PAGE   *
         * * * * * * * * * * * * * * * * */

        // Actions une fois le chargement de la page terminé
        if (window.isHomepage) {
            setTimeout(enterHomepage, 250);
        } else {
            setTimeout(enterPage, 250);
        }
    });
})(jQuery);
