//VARIABLES GENERALES
var $leftBox,
    $contBox,
    $gallery,
    $secondGallery,
    $cont,
    lWidth,
    rWidth,
    $carrusel,
    $gmap;

var mouseWheelEvent = ($.browser.mozilla) ? 'DOMMouseScroll' : 'mousewheel';

setGlobals();

function setGlobals(){
    $leftBox = $('#left-box');
    $contBox = $('#cont-box');
    $cont = $('#cont');
    $gallery = $('#gallery');
    $secondGallery = $('#second-gallery');
    $carrusel = $('#carrusel');
    $gmap = $('#g-map');
}
function clearLeftRightStyles(){
    $leftBox.removeAttr('style');
    $contBox.removeAttr('style');
}
function calculateWidths(){
    clearLeftRightStyles();
    lWidth = $leftBox.width();
    rWidth = $contBox.width();
}
/*FUNCIONES DETECTAR TAMAÑO DE LA PANTALLA*/
$(function(){

//    $(window).resize(calculateWidths)

    if($.browser.msie){

        $(window).resize(function(){
            adjustStyle($(this).width());
        });

        function adjustStyle(width){
            var _width = parseInt(width);
            
            if(_width < 1000)
                $('#detect-screen-width').attr('href','public/css/layout800.css');
            else
                $('#detect-screen-width').attr('href','public/css/layout.css');
            
            
        }
    }
});

/*FUNCIONES GOOGLE MAPS*/
var Gmap = (function(){
    var iniGmap = function(){
            if($gmap.length > 0){
                initializeGmap();
            }
        },
        initializeGmap = function(){
            var latLng = new google.maps.LatLng(latitude,longitude);
            var options = {
                zoom: 16,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map($gmap.get(0),options);
            var marker = new google.maps.Marker({
                position:latLng,
                title: 'Hola'
            });
            marker.setMap(map);
        }
    return {
        iniGmap: iniGmap
    }
})();

Gmap.iniGmap();

//FUNCIONES DEL CARRUSEL
var Carrusel = (function(){
    var iniCarrusel = function(){
            if($carrusel.length > 0){
                if($carrusel.find('li').length > 4)
                    doCarrusel();
                else
                    centerCarrusel();
            }
        },
        doCarrusel = function (){
            $carrusel
                .jcarousel({
                    buttonNextHTML: '<div class="btn-carousel"></div>',
                    buttonNextCallback: setEnabled,
                    buttonPrevHTML: '<div class="btn-carousel"></div>',
                    buttonPrevCallback: setEnabled,
                    itemFallbackDimension: $carrusel.find('li').width()
                })
                .bind(mouseWheelEvent, mouseWheelHandler);


            carruselHovers();

            function mouseWheelHandler(ev){
                ev.preventDefault();
                if(ev.wheelDelta < 0 || -ev.detail/3 < 0)
                    $(this).jcarousel('next');
                else
                    $(this).jcarousel('prev');
            }
            function setEnabled(carousel,button,enabled){
                if(enabled)
                    $(button).css('opacity', 1);
                else
                    $(button).css('opacity', 0.6);
            }
        },
        centerCarrusel = function (){
            var posX = $carrusel.parent().width()/2-$carrusel.width()/2;
            $carrusel.css('left', posX);

            carruselHovers();
        },
        carruselHovers = function (element){
            $carrusel.find("li")
                .css('opacity', 0.6)
                .mouseenter(mouseenterhandler)
                .mouseleave(mouseleavehandler);
        },
        mouseenterhandler = function (ev){
            $(this).css('opacity',1);
        },
        mouseleavehandler = function (ev){
            $(this).css('opacity',0.6);
        };
    return {
        iniCarrusel: iniCarrusel
    };
})();

Carrusel.iniCarrusel();

//FUNCIONES DE LA GALERIA
var Gallery = (function(){
    var ttm,
        indexImg,
        imagesLength,
        iniGallery = function(){
            if($gallery.length > 0){
                imagesLength = $gallery.find('li').length;
                if(imagesLength > 1) startGallery();
            }
        },
        startGallery = function(){
            clearInterval(ttm);
            indexImg = 0;
            $gallery.find('li:not(:first)').fadeOut(0);
            ttm = setInterval(changeImg,5000);
        },
        changeImg = function (){
            $gallery.find('li:eq('+indexImg+')').fadeOut(1000);
            indexImg = changeIndex();
            $gallery.find('li:eq('+indexImg+')').fadeIn(1000);
        },
        changeIndex = function (){
            return (indexImg < imagesLength-1) ? indexImg+1 : 0;
        },
        stopGallery = function(){
            clearInterval(ttm);
        };
    return {
        iniGallery: iniGallery,
        startGallery: startGallery,
        stopGallery: stopGallery
    }
})();

Gallery.iniGallery();

//FUNCIONES GALERIA SECUNDARIA
var SecondGallery = (function(){
    var iniSecondGallery = function(){
            if($secondGallery.length > 0){
                startSecondGallery();
            }
        },
        startSecondGallery = function(){
            $secondGallery
                .fadeTo(0,0.6)
                .mouseenter(mouseenterhandler)
                .mouseleave(mouseouthandler);
        },
        mouseenterhandler = function(){
            calculateWidths();
            $(this).fadeTo(500, 1);
            $leftBox.animate({width:lWidth-10},{duration:500,queue:false});
            $contBox.animate({width:rWidth-10},{duration:500,queue:false});
        },
        mouseouthandler = function(){
            $(this).fadeTo(500,0.6);
            $leftBox.animate({width:lWidth},{duration:500,queue:false});
            $contBox.animate({width:rWidth},{duration:500,queue:false});
        };
    return {
        iniSecondGallery: iniSecondGallery
    };
})();

SecondGallery.iniSecondGallery();

//FUNCIONES STYLED SCROLL
var Scroll = (function(){
    var $text,
        $mask,
        $sliderScroll,
        $sliderScrollCont,
        iniScroll = function(){
            $text = $('#slider_text');
            $mask = $('#mask_text');
            if($text.length > 0 && $mask.length > 0){
                if(calculateHeight($text) > calculateHeight($mask)){
                    doScroll();
                }
            }
        },
        calculateHeight = function($el){
            return $el.height();
        },
        doScroll =function(){
            $mask.css({
                position: 'relative',
                overflow: 'hidden',
                height: $mask.height()
            });
            $text.css({
                position:'absolute',
                width: $text.width() - 5
            });
            $sliderScroll = $('<div class="tiled-box"></div>');
            $sliderScrollCont = $('<div class="slider-scroll ver"></div>')
                .insertAfter($mask)
                .css({
                    position:'absolute',
                    right: 0,
                    height: $mask.height(),
                    top: $mask.position().top
                })
                .append('<div class="first-box"></div>')
                .append($sliderScroll)
                .append('<div class="second-box"></div>');
            $sliderScroll
                .css({
                    height: $mask.height()-31
                })
                .slider({
                orientation: 'vertical',
                min: 0,
                max: 100,
                value: 100,
                slide:slideHandler,
                change:slideHandler
            }).find('a').addClass('slider-handler');
            $mask.bind(mouseWheelEvent,mouseWheelHandler)
        },
        slideHandler = function(ev, ui){
            $text.css('bottom',- Math.round(ui.value / 100 * ($text.height()- $mask.height())));
        },
        mouseWheelHandler = function(ev){
            ev.preventDefault();
            var slide = (ev.wheelDelta) ? Math.round(ev.wheelDelta/100) : Math.round((-ev.detail/3));
            $sliderScroll.slider("value",$sliderScroll.slider("value")+slide);
        },
        destroy = function(){
            if($sliderScroll){
                $mask.unbind(mouseWheelEvent);
                $sliderScroll.slider("destroy");
                $sliderScrollCont.detach();
            }
        };
    return {
        iniScroll: iniScroll,
        destroy: destroy
    };
})();

Scroll.iniScroll();
//MODALES
var ModalWindow = (function(){
    var $modalLinks,
        $overlay = $('<div class="overlay"></div>').css('opacity',0.5),
        $modal = $('<div class="modal_window"></div>'),
        $closeModal = $('<a href="#" title="Cerrar" class="close-modal">x</a>'),
        
        initialize = function(){
            $modalLinks = $('a[rel=modal_window]');
            //console.log($modalLinks.length)
            if($modalLinks.length > 0){
                addEvents();
            }
        },
        addEvents = function(){
            $modalLinks.unbind('click').click(clickModalHandler);
        },
        clickModalHandler = function(ev){
            ev.preventDefault();
            doModal($(this).attr('href'));
        },
        doModal = function(href){
            $overlay.appendTo('body');
            $.getJSON(href,parseJSON);
        },
        parseJSON = function(json){
            var $content = $(json.content);
            $modal.html($content);
            
            showModal();
        },
        showModal = function(){
            $modal.find('h1').append($closeModal);
            $closeModal.unbind('click').click(destroyModal);
            $modal.appendTo('body');
            if($modal.find('img').length > 0){
               $modal.find('img').bind("load", centerModal); 
            }else{
                centerModal();
            }
        },
        centerModal = function(){
            var x = $overlay.width()/2 - $modal.width()/2;
            $modal.css({left:x, top: 150});
            ScrollModal.iniScroll();
        },
        destroyModal = function(ev){
            ev.preventDefault();
            $modal.detach();
            $overlay.detach();
        }
    return{
        initialize: initialize
    }
})();
ModalWindow.initialize();
//SCROLL MODAL
var ScrollModal = (function(){
    var $text,
        $mask,
        $sliderScroll,
        $sliderScrollCont,
        iniScroll = function(){
            $text = $('#slider_modal');
            $mask = $('#mask_modal');
            if($text.length > 0 && $mask.length > 0){
                if(calculateHeight($text) > calculateHeight($mask)){
                    doScroll();
                }
            }
        },
        calculateHeight = function($el){
            return $el.height();
        },
        doScroll =function(){
            $mask.css({
                position: 'relative',
                overflow: 'hidden',
                height: $mask.height()
            });
            $text.css({
                position:'absolute',
                width: $text.width() - 10
            });
            $sliderScroll = $('<div class="tiled-box"></div>');
            $sliderScrollCont = $('<div class="slider-scroll ver"></div>')
                .insertAfter($mask)
                .css({
                    position:'absolute',
                    right: 10,
                    height: $mask.height(),
                    top: $mask.position().top
                })
                .append('<div class="first-box"></div>')
                .append($sliderScroll)
                .append('<div class="second-box"></div>');
            $sliderScroll
                .css({
                    height: $mask.height()-31
                })
                .slider({
                orientation: 'vertical',
                min: 0,
                max: 100,
                value: 100,
                slide:slideHandler,
                change:slideHandler
            }).find('a').addClass('slider-handler');
            $mask.bind(mouseWheelEvent,mouseWheelHandler)
        },
        slideHandler = function(ev, ui){
            $text.css('bottom',- Math.round(ui.value / 100 * ($text.height()- $mask.height())));
        },
        mouseWheelHandler = function(ev){
            ev.preventDefault();
            var slide = (ev.wheelDelta) ? Math.round(ev.wheelDelta/100) : Math.round((-ev.detail/3));
            $sliderScroll.slider("value",$sliderScroll.slider("value")+slide);
        },
        destroy = function(){
            if($sliderScroll){
                $mask.unbind(mouseWheelEvent);
                $sliderScroll.slider("destroy");
                $sliderScrollCont.detach();
            }
        };
    return {
        iniScroll: iniScroll,
        destroy: destroy
    };
})();

//ANIMACIONES
$(function(){
    var $navigationLinks = $('#navigation a:not([href*="mailto"])');
    var $secondNavigationLinks = $('.sub-navigation a:not([rel=modal_window])');
    var $menuArticlesLinks = $('.articles-menu a:not([rel=modal_window])');
    var $carruselLinks = $('#carrusel').find('a');
    var first = true;
    
    bindMainNavigation();
    
    $.address.externalChange(function(ev){
        var exhref = $.address.baseURL().replace(/\/$/,'')+ev.value;
        if(first){
            first = false;
        }else{
            exitScreen(null,exhref);
        }
    });
    
    
    if($secondNavigationLinks.length > 0)
        bindSecondNavigation();
    if($carruselLinks.length > 0)
        bindCarruselLinks();
    if($menuArticlesLinks.length > 0)
        bindAtriclesLinks();
    
    function bindMainNavigation(){
        $navigationLinks.unbind('click').click(exitScreen);
    }
    function bindSecondNavigation(){
        $secondNavigationLinks.unbind('click').click(exitCont);
    }
    function bindCarruselLinks(){
        $carruselLinks.unbind('click').click(exitScreen);
    }
    function bindAtriclesLinks(){
       $menuArticlesLinks.unbind('click').click(exitScreen);
    }
    function unBindMainNaviagation(){
        $navigationLinks.unbind('click').click(preventDefaultLink);
    }
    /* animating */
    function exitScreen(ev,href){
        if(ev){
            preventDefaultLink(ev);
            $.address.value($(this).attr('href'));
            href = $(this).attr('href');
        }
        
        
        if($gallery.length > 0)
            hideGallery();
        if($secondGallery.length > 0)
            hideSecondGallery();
        if($cont.length > 0)
            hideCont();
        
        //unBindMainNaviagation();
        
        $(window).bind('animateFinish', {doAfter: getResponse, href: href}, checkAnimateFinsihed);
    }
    function exitCont(ev){
        ev.preventDefault();
        Scroll.destroy();
        $('.sub-navigation').find('.active').removeClass('active');
        $('#mask_text').fadeOut(500, dispatchAnimateFinish);
        if($(this).attr('href').indexOf('capacity') != -1){
            $contBox.find('.general-info').fadeOut(500, function(){$(this).detach();});
        }
        $(this).addClass('active');
        $(window).bind('animateFinish',{doAfter: getResponse, href: $(this).attr('href'), renderAction: redrawCont}, checkAnimateFinsihed)
    }
    function showScreen(extendAnimation){
        if(extendAnimation == 'expand'){
            showGalleries();
            $cont.fadeOut(0);
            $contBox.removeClass('extend').addClass('extend',{duration:1000,complete:afterExtendAnimating});
        }else if(extendAnimation == 'reduce'){
            if($secondGallery.length > 0)
                $leftBox.removeAttr('style').css({width:$leftBox.width() + 40})
            $contBox.addClass('extend').removeClass('extend', {duration:1000, complete: afterReduceAnimating});
        }else{
            showGalleries()
            showCont();
        }
    }
    function hideGallery(){
        Gallery.stopGallery();
        $gallery.animate({width: 0},{duration:750, complete:dispatchAnimateFinish});
    }
    function hideSecondGallery(){
        $leftBox.animate({width: $leftBox.width()+40},{duration:1000, complete:dispatchAnimateFinish});
        $contBox.animate({width: $contBox.width()+40},{duration:1000, complete:dispatchAnimateFinish});
    }
    function hideCont(){
        $cont.fadeOut(500, dispatchAnimateFinish);
    }
    function showGallery(){
        $gallery.css({width:1});
        Gallery.iniGallery();
        $gallery.animate({width: '25.20%'}, {duration:750});
    }
    function showSecondGallery(){
        SecondGallery.iniSecondGallery();
        $leftBox.animate({width: $leftBox.width() - 40},{duration:750});
        $contBox.css({width: $contBox.width() + 40}).animate({width: $contBox.width() - 40},{duration:750});
    }
    function showCont(){
        $cont.fadeIn(0);
        iniCont();
        $cont.fadeOut(0).fadeIn(500, function(){bindMainNavigation(); $(this).removeAttr('style')});
    }
    /* Response */
    function getResponse(href, doAfter){
        if(!doAfter)
            doAfter = parseJSON;
        $.getJSON(href,doAfter);
    }
    /* Manipulation */
    function parseJSON(json){
        var hasExtendClass = $contBox.hasClass('extend');
        
        $.each(json,replaceElement);
        
        if(!json.secondGallery && $secondGallery.length > 0){
            $secondGallery.detach();
            $secondGallery = [];
        }
        if(!json.mainGallery && $gallery.length > 0){
            $gallery.detach();
            $gallery = [];
        }
        
        showScreen(getExtendAnimation(hasExtendClass, json.extend));
    }
    function redrawCont(json){
        var newContent = $('<div />').append(json.content);
        if(newContent.find('.general-info').length > 0 && $contBox.find('.general-info').length < 1){
            var $generalInfo = newContent.find('.general-info').insertAfter($('.content h1'));
        }
        var newMaskText = newContent.find('#mask_text');
        var $maskText = setNewCont($('#mask_text'),newMaskText,$('.content'));
        if($maskText.find('#g-map').length > 0){
            $gmap = $maskText.find('#g-map');
            Gmap.iniGmap();
        }
        Scroll.iniScroll();
        ModalWindow.initialize();
        $maskText.fadeOut(0).fadeIn(500);
        if($generalInfo)
            $generalInfo.fadeOut(0).fadeIn(500);
    }
    function replaceElement(key,value){
        switch(key){
            case 'content':
                $contBox = setNewCont($contBox,value);
                $cont = $contBox.find('#cont');
            break;
            case 'mainGallery':
                $gallery = setNewCont($gallery, value, $('#main-box')).css({width:0});
            break;
            case 'secondGallery':
                $secondGallery = setNewCont($secondGallery,value, $('#main-box'));
            break;
            case 'head':
                var $head = $('<head />').append(value);
                $('title').replaceWith($head.find('title'));
                if($head.find('#color').attr('href') != $('#color').attr('href')){
                    var color = ($head.find('#color').attr('href').indexOf('red') != -1) ? 'red' : 'white'
                    $('#color').attr('href',$head.find('#color').attr('href'));
                    $('#logo-araceli').attr('src',(color == 'red') ? 'public/images/logo/logo-navigation-grupoaraceli.gif' : 'public/images/logo/logo-navigation-grupoaraceli-red.png');
                }
            break;
        }
    }
    function setNewCont(el,content,container){
        if(!container)
            container = $contBox;
        
        return (el.length > 0) ? $(content).replaceAll(el) : $(content).appendTo(container);
    }
    function getExtendAnimation(hasExtend, jsonExtend){
        return (hasExtend && !jsonExtend) ? 'reduce' : (!hasExtend && jsonExtend) ? 'expand' : false ;
    }
    function iniCont(){
        if($cont.find('#carrusel').length > 0){
            $carrusel = $cont.find('#carrusel');
            $carrusel.fadeTo(0,1);
            Carrusel.iniCarrusel();
            $carruselLinks = $('#carrusel').find('a');
            bindCarruselLinks();
        }
        if($cont.find('.sub-navigation a').length > 0){
            $secondNavigationLinks = $cont.find('.sub-navigation a');
            bindSecondNavigation();
        }
        if($cont.find('.articles-menu a').length > 0){
           $menuArticlesLinks = $cont.find('.articles-menu a');
           bindAtriclesLinks();
        }
        ModalWindow.initialize();
        Scroll.iniScroll();
    }
    /* custom events */
    function dispatchAnimateFinish(){
        //To fix :animate selector in complete of animation
        var tmo = setTimeout(triggerAnimateFinish,1);
        function triggerAnimateFinish(){
            $(window).trigger('animateFinish');
            clearTimeout(tmo);
        }
    }
    function checkAnimateFinsihed(ev){
        if(checkNoAnimateEl($gallery) && checkNoAnimateEl($leftBox) && checkNoAnimateEl($contBox) && checkNoAnimateEl($cont) && checkNoAnimateEl($('#mask_text'))){
            $(window).unbind('animateFinish');
            var args = [ev.data.href];
            if(ev.data.renderAction)
                args.push(ev.data.renderAction);
            ev.data.doAfter.apply(this,args);
        }
    }
    function checkNoAnimateEl($el){
        return ($el.length < 1 || !$el.is(':animated'));
    }
    function preventDefaultLink(ev){
        ev.preventDefault();
    }
    function afterExtendAnimating(){
        $contBox.addClass('extend');
        showCont();
    }
    function afterReduceAnimating(){
        $contBox.removeClass('extend');
        showGalleries();
        showCont();
    }
    function showGalleries(){
        if($gallery.length > 0)
            showGallery();
        if($secondGallery.length > 0)
            showSecondGallery();
    }
});
//INTRO
var Intro = (function($){
    var $introGaleries = $('.galery-intro'),
        $nav = $('#navigation').find('.nav'),
        $logo = $('#navigation').find('.logo-nav'),
        $tapa = $('#tapa-intro'),
        tmo,
        index,
        itv,
        
        initialize = function(){
            if($introGaleries.length > 0){
                $introGaleries.css({ left: function(i){ return $(this).width()*i; }})
                              .fadeOut();
                
                hideElements();
            }
        },
        hideElements = function(){
            Gallery.stopGallery();
            $gallery.fadeOut();
            $nav.fadeOut();
            $logo.fadeOut();
            $leftBox.css('width', $leftBox.width() + 19 );
            $contBox.css('width', $contBox.width() + 19 );
            
            tmo = setTimeout(hideTapa, 750);
        },
        hideTapa = function(){
            clearTimeout(tmo);
            $tapa.animate({width: 0}, 1000, startAnimations);
        },
        startAnimations = function(){
            $tapa.remove();
            index = 0;
            itv = setInterval(animateEl, 1200);
        },
        animateEl = function(){
            var $el = $($introGaleries.get(index));
            index++;
            
            if(index >= $introGaleries.length){
                clearInterval(itv);
                $el.fadeIn(750, moveLastImage);
            }else{
                if(index == 1){
                    $logo.data('itv', setInterval(showLogo, 5000));
                }else if(index == 2){
                    $contBox.data('itv', setInterval(showSecondGallery, 5000));
                }
                $el.fadeIn(750, moveImage);
            }
        },
        moveImage = function(){
            var $el = $(this),
                $img = $el.find('img');
            
            $img.animate({left: - $el.width()}, 5000);
            
            $el.data('itv', setInterval(function(){exitEl($el);}, 2500));
        },
        moveLastImage = function(){
            var $el = $(this),
                $img = $el.find('img');
                
            $img.animate({left: - $el.width()}, 5000);
            
            $el.data('itv', setInterval(function(){exitLastEl($el)}, 2500));
            
        },
        exitEl = function($el){
            clearInterval($el.data('itv'));
            $el.removeData('itv');
            
            $el.fadeOut(2500, removeEl);
        },
        exitLastEl = function($el){
            clearInterval($el.data('itv'));
            $el.removeData('itv');
            
            $el.css({right: 0, left: 'auto'})
               .animate({width: $gallery.width(), opacity: 0}, 2500, removeLastEl);
            $gallery.fadeIn(2500);
        },
        showLogo = function(){
            clearInterval($logo.data('itv'));
            $logo.removeData('itv');
            
            $logo.fadeIn(750);
        },
        showSecondGallery = function(){
            clearInterval($contBox.data('itv'));
            $contBox.removeData('itv');
            
            $leftBox.animate({width: $leftBox.width() -19 }, 2500);
            $contBox.animate({width: $contBox.width() -19 }, 2500);
        },
        removeEl = function(){
            $(this).remove();
        },
        removeLastEl = function(){
            $(this).remove();
            Gallery.startGallery();
            $nav.fadeIn(500);

            Promotions.show(1000, 'villalba');
        }
    return {
        initialize: initialize
    }
})($);

var Promotions = (function($){
    var $promotion = $('#promotions'),
        $banners,
        $link,
        init,
        h,
        intVal,
        tabActive,
        
        initialize = function () {
            if ($promotion.length > 0) {
                init = true;
                h = $promotion.height();
                $banners = $promotion.find('.banners');
                $link    = $promotion.find('.promotion-link').click(toggle);

                startStatus();
            }
        },
        startStatus = function () {
            $banners.find('li')
                .fadeOut(0)
                .hover(function (ev) {
                    stopGallery();
                }, function (ev) {
                    startGallery();
                });
            $banners.find('li:first').fadeIn(0);
            hide(0);
        },
        show = function (timing, tab) {
            if (init) {
                tabActive = tab;
                $banners.css('display', 'none').filter('[data-tab=' + tab + ']').css('display', 'block');
                $promotion.animate({'top': 0}, timing, function () { 
                    $link.removeClass('show').addClass('hide');
                    startGallery(true);
                });
            }
        },
        hide = function (timing) {
            if (init) {
                stopGallery();
                $promotion.animate({'top': -h}, timing, function () {
                    $banners.each(function (i, ul) { restartGallery($(ul)); });
                    tabActive = null;
                    $link.removeClass('hide').addClass('show');
                })
            }
        },
        toggle = function (ev) {
            var $this, tab;
            
            $this = $(this);
            tab   = $this.attr('data-tab');

            if ($this.hasClass('show') && tabActive == null) {
                show(750, tab);
            } else if($this.hasClass('hide') && tab == tabActive) {
                hide(750);
            } else {
                restartGallery($banners.filter('[data-tab=' + tab + ']'));
                $banners.filter('[data-tab=' + tabActive + ']').fadeOut(750);
                $banners.filter('[data-tab=' + tab + ']').fadeIn(750, function () {
                    startGallery(true);
                });
                tabActive = tab;
            }

            return false;
        },
        startGallery = function (restart) {
            stopGallery();
            $ul = $banners.filter('[data-tab=' + tabActive + ']');
            if (restart) restartGallery($ul);
            intVal = setInterval(function () {
                var $visible = $ul.find('li:visible').fadeOut(1000);
                if ($visible.next().length > 0) {
                    $visible.next().fadeIn(1000);
                } else {
                    $ul.find('li:first').fadeIn(1000);
                }
            }, 5000);
        },
        stopGallery = function () {
            clearInterval(intVal);
        },
        restartGallery = function ($gallery) {
            if ($gallery.css('display') == 'none') {
                $gallery.css('display', 'block').find('li').fadeOut(0).first().fadeIn(0);
                $gallery.css('display', 'none');
            } else {
                $gallery.find('li').fadeOut(0).first().fadeIn(0);
            }
        }
    
    return {
        initialize: initialize,
        show: show,
        hide: hide
    }
})($);

Intro.initialize();
Promotions.initialize();
