﻿(function ($) {
    $.fn.slideNavigation = function (instanceSettings) {

        // COMPONENTES DE TELA
        var _root = $('#main-wrapp');
        var _home = _root.find('#home');
        var _sobre = _root.find('#sobre');
        var _cases = _root.find('#cases');
        var _cadastro = _root.find('#cadastro');
        var _contato = _root.find('#contato');
        var _menu = _root.find('.menu');
        var _menuwrapp = _root.find('.menu-wrapp');
        var _btNavCases = _cases.find(".nav");
        var _case = _cases.find(".case");
        var _caseNext = _cases.find(".caseNext");
        var _playerCases = _cases.find(".player-wrapper");

        // VARIAVEIS DE CONFIGURAÇÃO
        var paginaAtiva;
        var indiceAtivo;
        var indiceCaseAtivo;
        var caseAtivo;
        var movimentoAtivo = false;
        var totalCases;

        // INICIALIZAÇÃO DO COMPONENTE
        function init() {

            $.fn.slideNavigation.defaultSettings = {
                paginaAtiva: 'home',
                arrBGMazah: [],
                arrBGCases: [],
                arrVideosCases: [],
                strPathBGMazah: 'Uploads/Bg/',
                strPathBGCases: 'Uploads/Cases/',
                easeType: "easeInOutExpo"
            };
            settings = $.extend({}, $.fn.slideNavigation.defaultSettings, instanceSettings || {});
            paginaAtiva = settings.paginaAtiva;

            adjustMainPosition();
        };
        init();

        // Transforma proporções da div conforme palco principal
        function ajustaTamanhoTela(obj) {
            obj.show();
            obj.width(_root.width());
            obj.height(_root.height());
        }

        // Apresentação dos Cases a partir da Home
        _home.find('div.nav').click(function () {
            if (!movimentoAtivo) {
                navegaTelas(_menuwrapp.find('li#menu-cases').find('img'));
            }
        });

        // Evento de clique no menu
        _menuwrapp.find('img').click(function () {
            if (!movimentoAtivo) {
                navegaTelas($(this));
            }
        });

        // Controle de navegação entre as telas
        navegaTelas = function (menu) {

            var _this = menu;
            var _new = _root.find('#' + _this.attr('rel'));
            var _old = _root.find('#' + paginaAtiva);

            if (_new.attr('index') != indiceAtivo) {

                var old_posYStart;
                var old_posYFinish;
                var new_posYStart;
                var new_posYFinish;

                movimentoAtivo = true;
                ajustaTamanhoTela(_new);

                if (_new.attr('index') > indiceAtivo) {
                    old_posYFinish = _root.height() * -1;
                    new_posYStart = _root.height();
                }
                else {
                    old_posYFinish = _root.height();
                    new_posYStart = _root.height() * -1;
                }

                if (!_new.hasClass('loaded')) {
                    if (_new.attr('id') != 'cases') {
                        _new.append("<img class='bg' src='" + settings.strPathBGMazah + settings.arrBGMazah[_new.attr('index')] + "'/>");
                    }
                    _new.addClass('loaded');
                }

                if (_new.attr('id') == 'cases') {
                    initCases(_new);
                }

                _new.find('img.bg').one('load', function () {

                    adjustBackground(_new.find('img.bg'));
                    _new.css('top', new_posYStart);

                    _old.animate({ top: old_posYFinish }, "slow", settings.easeType, function () {
                        if (paginaAtiva == 'sobre') { restorePage('sobre'); }
                        if (_old.attr('id') == 'cases') { restorePage('cases'); }
                    });

                    _new.animate({ top: 0 }, "slow", settings.easeType, function () {
                        paginaAtiva = _new.attr('id');
                        movimentoAtivo = false;
                        configuraPosicoesTelas();
                    });
                }).each(function () { if (this.complete) $(this).load(); });
            }
        }

        // Restaura a pagina de "Sobre"
        function restorePage(objTela) {

            switch (objTela) {
                case "sobre":
                    $('.sobre-video').empty();
                    $('.bt-nosso-video').css('left', 459);
                    $('.sobre-conteudo').css('left', 30);
                    $('.sobre-video').css('left', 800);
                    break;
                case "cases":
                    _playerCases.find('.fader').fadeIn('fast', function () {
                        _playerCases.find('iframe#frmPlayer').remove();
                    });
                    break;
            }
        }

        // Configura posições e estados das paginas
        function configuraPosicoesTelas() {
            _root.find(".page-wrapp").each(function () {
                var _this = $(this);

                if (_this.attr('id') != paginaAtiva) {
                    _this.css('top', _root.height());
                    _this.removeClass('ativo')
                    _this.hide();
                }
                else {
                    ajustaTamanhoTela(_this);
                    _this.css('top', 0);
                    _this.addClass('ativo')
                    indiceAtivo = _this.attr('index');

                    if (!_this.hasClass('loaded')) {
                        _this.append("<img class='bg' src='" + settings.strPathBGMazah + settings.arrBGMazah[indiceAtivo] + "'/>");
                        _this.addClass('loaded');

                        _this.find('img.bg').one('load', function () {
                            adjustBackground(_this.find('img.bg'));

                            // CONTINUAR AQUI

                        }).each(function () { if (this.complete) $(this).load(); });
                    }
                }
            });
        }

        // Listener de redimensionamento do browser
        $(function () {
            $(window).resize(function () {
                adjustMainPosition();
                adjustBackground(_root.find('#' + paginaAtiva).find('img.bg'));
            });
        });

        // Ajuste da altura e largura do stage
        function adjustMainPosition() {
            _root.width($(window).width());
            _root.height($(window).height());

            if (_root.height() < 670) {
                _root.height(670);
            }

            configuraPosicoesTelas();
        };

        // Ajuste da proporção dos backgrounds
        function adjustBackground(objImg) {

            objImg.removeAttr('width');
            objImg.removeAttr('height');
            objImg.attr('width', _root.width());
            if (_root.height() > objImg.height()) {
                objImg.removeAttr('width');
                objImg.removeAttr('height');
                objImg.attr('height', _root.height());
                objImg.css('marginLeft', (_root.width() - objImg.width()) / 2);
            }
            else {
                objImg.css('marginLeft', 0);
            }
        };

        /*********************************************** NAVEGAÇÃO NOS CASES
        ********************************************************************/

        // Auxilia no redimensionamento dos backgrounds
        configuraDimensoesCase = function (objCase) {
            if (objCase.hasClass('active')) {
                objCase.css('left', 0);
            }
            else {
                objCase.css('left', _root.width());
            }
        }

        // Monta estrutura inicial dos cases
        function initCases(parametro) {
            if (_cases.find('div.case').length < 1) {

                totalCases = settings.arrBGCases.length;
                if (indiceCaseAtivo == undefined) {
                    indiceCaseAtivo = 0;
                }

                for (i = 0; i < totalCases; i++) {
                    _cases.append("<div class='case' id='case_" + i + "'></div>");
                    configuraDimensoesCase(_cases.find('#case_' + i));
                }

                caseAtivo = _cases.find('#case_' + indiceCaseAtivo);
                caseAtivo.addClass('loaded');
                caseAtivo.addClass('active');
                caseAtivo.css('left', 0);
                caseAtivo.append("<img class='bg' src='" + settings.strPathBGCases + settings.arrBGCases[indiceCaseAtivo] + "'/>");

                caseAtivo.find('img.bg').one('load', function () {
                    loadVideoCase(settings.arrVideosCases[indiceCaseAtivo]);
                }).each(function () { if (this.complete) $(this).load(); });
            }
            else {
                loadVideoCase(settings.arrVideosCases[indiceCaseAtivo]);
            }
        }

        // Retorna HTML do player de vídeo
        loadVideoCase = function (src) {
            if (_playerCases.find('iframe').length < 1) {
                _playerCases.append('<iframe src="' + src + '" id="frmPlayer" width="640" height="360" frameborder="0" webkitAllowFullScreen="" allowFullScreen=""></iframe>');
                _playerCases.find('.fader').fadeOut('slow');
            }
            else {
                _playerCases.find('iframe').attr('src', src).change();
            }
        }

        // Gerencia a navegação entre os cases
        navegaCase = function (sentido) {

            movimentoAtivo = true;

            var new_posXInicial;
            var atual_posXFinal;
            var caseProximo;

            switch (sentido) {
                case 'left':
                    new_posXInicial = _root.width() * -1;
                    atual_posXFinal = _root.width();
                    if (indiceCaseAtivo > 0) {
                        indiceCaseAtivo--;
                    }
                    else {
                        indiceCaseAtivo = totalCases - 1;
                    }
                    break;
                case 'right':
                    new_posXInicial = _root.width();
                    atual_posXFinal = _root.width() * -1;

                    if (indiceCaseAtivo < (totalCases - 1)) {
                        indiceCaseAtivo++;
                    }
                    else {
                        indiceCaseAtivo = 0;
                    }
                    break;
            }

            caseProximo = _cases.find('#case_' + indiceCaseAtivo);
            caseProximo.css('left', new_posXInicial);

            if (!caseProximo.hasClass('loaded')) {
                caseProximo.append("<img class='bg' src='" + settings.strPathBGCases + settings.arrBGCases[indiceCaseAtivo] + "' />");
            }
            else {
                caseProximo.find('img').show();
            }

            // Transição do vídeo
            _cases.find('.fader').fadeIn('fast', function () {
                loadVideoCase(settings.arrVideosCases[indiceCaseAtivo]);

                // Animação de troca dos cases
                caseProximo.find('img').one('load', function () {

                    adjustBackground(caseProximo.find('img.bg'));

                    caseAtivo.animate({ left: atual_posXFinal }, "slow", "easeInOutExpo", function () {
                        $(this).removeClass('active');
                        $(this).find('img').hide();
                    });
                    caseProximo.animate({ left: 0 }, "slow", "easeInOutExpo", function () {
                        $(this).addClass('active');
                        _cases.find('.fader').fadeOut('slow');
                        movimentoAtivo = false;
                    });

                    caseAtivo = caseProximo;
                    caseProximo.addClass('loaded');

                }).each(function () { if (this.complete) $(this).load(); });
            });
        }

        _btNavCases.click(function () {
            if (!movimentoAtivo) {
                navegaCase($(this).hasClass('left') ? 'left' : 'right');
            }
        });

    };
})(jQuery);
