window.addEvent('domready', function(){
    myStickyWinModalObj = myStickyWinModal();
    myMaskObj = myMask();
    myDefaultPais = loadMyDefaultPais();
    
    MooHistory.init({
        ignoreClassName: 'noMooHist'
    });
    window.addEvent('hashload', submitRequestViewController);
    
    window.addEvent('startLinks', function(){
        $$('a.prev').addClass('noMooHist').set('href', 'javascript: history.go(-1); void(0);');

        $$('a.home').set('href', '/View_Home.php');
        $$('a.demo').set('href', '/View_Demo.php');
        $$('a.download').set('href', '/View_Download.php');
        $$('a.free').each(function(obj){
            obj.set('href', '/View_Free.php?openAccordion=' + (obj.get('activeAccordion') == null ? 0 : obj.get('activeAccordion')));
        });
        $$('a.ultimate').each(function(obj){
            obj.set('href', '/View_Ultimate.php?openAccordion=' + (obj.get('activeAccordion') == null ? 0 : obj.get('activeAccordion')));
        });
//        $$('a.comprar').set('href', '/Stage_Produto.php');
        $$('a.comprar').addClass('noMooHist').set('href', 'http://www.vscyber.com/shopp').set('target', '_BLANK');
        $$('a.pagamento').addEvent('click', function(){
            requestViewController.options.url = 'include/view/Stage_Checkout.php';
            requestViewController.send();
        }).addClass('noMooHist').set('href', 'javascript: void(0)');
        $$('a.contato').set('href', '/View_Contato.php');
        $$('a.versoes').set('href', '/View_Versoes.php');
        $$('a.suporte').set('href', '/View_Suporte.php');
        $$('a.servicos').set('href', '/View_Servicos.php');
//        $$('a.suporteExt').set('href', 'Stage_Suporte.php');
        $$('a.anuncie').set('href', '/View_Anuncie.php');
        $$('a.suporteExt').addClass('noMooHist').set('href', 'http://www.snetcommerce4.com.br/ecommerce_site/produto_44239_1054_Suporte-Extensivo').set('target', '_BLANK');
        $$('a.declaracaoReqAlvara').addClass('noMooHist').set('href', 'http://www.snetcommerce4.com.br/ecommerce_site/produto_48604_1054_Declaracao-VSCyber').set('target', '_BLANK');
        $$('a.comercialMail').addClass('noMooHist').set('href', 'mailto: comercial@vitesoft.com');

        $$('a.Anuncie_NossosNumeros').addClass('noMooHist').addEvent('click', function(){
            myStickyWinModalObj.update('include/view/Modal_Anuncie_NossosNumeros.php');
        }).set('href', 'javascript: void(0)');
        $$('a.Anuncie_ModeloPubServidor').addClass('noMooHist').addEvent('click', function(){
            myStickyWinModalObj.update('include/view/Modal_Anuncie_ModeloPubServidor.php');
        }).set('href', 'javascript: void(0)');
        $$('a.Anuncie_ModeloPubCliente').addClass('noMooHist').addEvent('click', function(){
            myStickyWinModalObj.update('include/view/Modal_Anuncie_ModeloPubCliente.php');
        }).set('href', 'javascript: void(0)');
        
        MooHistory.updateLinks();
    });
    window.addEvent('start', function(){
//        REMOVIDO ATÉ TRADUÇÃO COMPLETA DAS VERSÕES EN E ES;
//        langs = JSON.decode(langs);
//
//        listLang = new Array();
//        listLang[0] = getLang;
//        iLangs = 0;
//        for (i in langs) {
//            if (langs[i][2][0] != listLang[0]) {
//                listLang.push(langs[i][2][0])
//            }
//            iLangs++;
//        }
//
//        var z = new dhtmlXCombo("top_lang", "lang", 200);
//        z.readonly(true);
//        z.addOption([[listLang[1], langs[listLang[1]][0]], [listLang[2], langs[listLang[2]][0]]]);
//        z.setComboText(langs[listLang[0]][0]);
//        z.attachEvent("onChange", function() {
//            langDirect = z.getSelectedValue();
//            if (langDirect != null) {
//                window.location = '?hl='+langDirect;
//            }
//        });

        
        submitRequestViewController(location);
        window.fireEvent('startLinks');

        new SimpleCarousel($('banner_news').getElement('.banner_txt'), $$('#banner_news .slide'), $$('#banner .button'), {slideInterval: 7500});
        
//        $('PedidoStatus').addEvent('submit', function(){
//            this.set('send', {
//                onRequest: function(){
//                    $('PedidoStatusResponse').set('html', '<img src="img/ajax-loader_2.gif" />');
//                },
//                onSuccess: function(response){
//                    response = JSON.decode(response);
//
//                    if(response['success']){
//                        response['msg'] = "<b>" + response['date'] + '</b> - ' + response['msg'];
//                    }
//                    $('PedidoStatusResponse').set('html', response['msg']);
//                }
//            });
//
//            this.send();
//        });
//        $('DisparaPedidoStatus').addEvent('click', function(){
//            if($('IdPedido').value != '') $('PedidoStatus').fireEvent('submit');
//        });
    });

    window.addEvent('home', function(){
        window.fireEvent('startLinks');

        clearTimeout(activeTimeOut);
        $('command_pause').addEvent('click', function(){
            clearTimeout(activeTimeOut);
        });
        $('command_prev').addEvent('click', loadPrevFlash);
        $('command_next').addEvent('click', loadNextFlash);

        var counter = 0;
        for(i in availableFlash){
            if(typeof availableFlash[i] == 'string'){
                if(i != 0){
                    $(availableFlash[i]).fade(0).setStyle('z-index', 9);
                }
                
                var newEl = new Element('td').set('text', counter+1).addEvent('click', function(){
                    var myCount = this.get('text') - 1;
                    loadSelectedFlash(myCount);
                });

                newEl.inject($('flash_command').getElement('td.empty'), 'before');

                counter++;
            }
        }
        
        window.fireEvent(availableFlash[0]);
        activeTimeOut = setTimeout(loadNextFlash, 10000);
    });
    window.addEvent('flash_verde', function(){
        activeFlash = 0;
        cleanLocalTimeOut();
    });
    window.addEvent('flash_cinza', function(){
        activeFlash = 1;
        cleanLocalTimeOut();
    });
    window.addEvent('flash_branco', function(){
        activeFlash = 2;
        cleanLocalTimeOut();
    });
    window.addEvent('flash_vermelho', function(){
        activeFlash = 3;
        cleanLocalTimeOut();
    });

    window.addEvent('anuncie', function(){
        window.fireEvent('startLinks');
        createAccordion();
    });
    window.addEvent('free', function(){
        window.fireEvent('startLinks');
        createAccordion();

    });
    window.addEvent('ultimate', function(){
        window.fireEvent('startLinks');
        createAccordion();
    });
    window.addEvent('suporte', function(){
        window.fireEvent('startLinks');
        createAccordion();
    });
    window.addEvent('servicos', function(){
        window.fireEvent('startLinks');
        createAccordion();
    });
    window.addEvent('demo', function(){
        $('content').getElements('a[rel^=lightbox]').each(function(obj){
            var ahref = obj.get('ahref');
            obj.set('href', ahref);
        });
        
        new Lightbox({
            useDefaultCss: false
        });
    });
    window.addEvent('versoes', function(){
        window.fireEvent('startLinks');
        createAccordion();

//        $('comparativoLnk').addEvent('click', function(){
//            myStickyWinModalObj.update('include/view/Modal_Compare.php');
//        });
    });
    window.addEvent('contato', function(){
        maskForm.setRequired($('Nome'));
        maskForm.setRequired($('SobreNome'));
        maskForm.setRequired($('Email'));
        maskForm.setEmail($('Email'));
        maskForm.setRequired($('ConfirmEmail'));
        maskForm.setEmail($('ConfirmEmail'));
        $('ConfirmEmail').addClass('check-confirm-email');
        maskForm.setRequired($('Mensagem'));

        var formVal = new FormValidator('myForm', {
            stopOnFailure: true,
            serial: true,
            
            onElementPass: function(element){
                $(element.id + '_Error').setStyle('display', 'none');
            },
            onElementFail: function(element, validators){
                errorMsg = formValidatorStr[validators[0]];
                $(element.id + '_Error').set('html', errorMsg).setStyle('display', 'block');
            }
        });
        formVal.add('check-confirm-email', {
            test: function(element){
                if(element.value != $('Email').value) return false;
                return true;
            }
        });

        $('responseMsgClose').addEvent('click',  function(){
            this.getParent().setStyle('display', 'none');
        });

        $('submitter').addEvent('click', function(){
            $('responseMsg').setStyle('display', 'none');
            
            var testForm = formVal.validate();
            if(testForm){
                $('myForm').fireEvent('submit');
            }
        });
        $('myForm').addEvent('submit', function(){
            this.set('send', {
                link: 'cancel',
                onRequest: function(){
                    myStickyWinModalObj.update('wait.html');
                },
                onSuccess: function(response){
                    Recaptcha.reload();
                    
                    hideMyStickyWinModal();
                    response = JSON.decode(response);

                    for( i in response['error'] ){
                        if(typeof response['error'][i] == 'string'){
                            $(i + '_Error').set('html', response['error'][i]).setStyle('display', 'block');
                        }
//                        alert(i + ' typeof: ' + typeof response['error'][i]);
                    }

                    $('responseMsgTxt').set('html', response['msg']);
                    $('responseMsg').setStyle('display', 'block');

                    if(response['success']){
                        $('myForm').reset();
                    }
                }
            });

            this.send();
        });
    });
    
    window.addEvent('Stage_Produto', function(){
        window.fireEvent('startLinks');

        if($('DisparaCupomDesconto') != null){
            $('DisparaCupomDesconto').addEvent('click', function(){
                var requestCupomDesconto = new Request.JSON({
                    url: 'libs/request_CartController.php',
                    method: 'get',
                    data: {'action': 'setCupomDesconto', 'Codigo': null},
                    link: 'cancel',
                    onRequest: function(){
                        $('CupomDescontoResponse').setStyle('display', 'block').set('html', '<img src="img/ajax-loader_3.gif" />');
                    },
                    onSuccess: function(response){
                        $('CupomDescontoResponse').set('html', response.msg);
                        $('precoFinal').set('html', "R$ " + response.precoFinal)
                    }
                });

                requestCupomDesconto.options.data.Codigo = $('Codigo').value;
                requestCupomDesconto.send();
            });
        }

        $$('.IdFaixa').each(function(obj){
            obj.addEvent('change', function(){
                var ProdKey = this.id;
                var IdFaixa = this.value;

                setProdFaixaCart(ProdKey, IdFaixa);

            });
        });
        $$('.IdValidade').each(function(obj){
            obj.addEvent('change', function(){
                var ProdKey = this.id;
                var IdValidade = this.value;

                setProdValidadeCart(ProdKey, IdValidade);
            });
        });
    });
    window.addEvent('Stage_Suporte', function(){
        alert('teste');
    });
    window.addEvent('Stage_Checkout', function(){
        $$('a.comprar').addEvent('click', function(){
            requestViewController.options.url = 'include/view/Stage_Produto.php';
            requestViewController.send();
        }).set('href', 'javascript: void(0)');
        
        $('AccountModify').addEvent('click', function(){
            window.fireEvent('AccountTab');
        });
        $('AccountKeep').addEvent('click', function(){
            window.fireEvent('PaymentTab');
        });

        $('Submit_UserLogin').addEvent('click', function(){
            $('UserLoginForm').fireEvent('submit');
        });
        $('UserLoginForm').addEvent('submit', function(){
            $('UserLoginForm').getElement('.response').setStyle('display','none');
            
            this.set('send', {
                link: 'cancel',
                onRequest: function(){
                    myStickyWinModalObj.update('wait.html');
                },
                onSuccess: function(response){
                    hideMyStickyWinModal();

                    response = JSON.decode(response);
                    if(response['success']){
                        $('AccountTp').setStyle('display','block').getElement('span').set('text', response['msg']);
                        window.fireEvent('PaymentTab');
                    } else {
                        $('UserLoginForm').getElement('.response').set('text', response['msg']).setStyle('display', 'block');
                    }
                }
            });

            this.send();
        });

        $('account-type-submit').addEvent('click', function(){
            $('account-type-form').getElements('input[name=account-type]').each(function(obj){
                if(obj.checked){
                    myStickyWinModalObj.update("include/view/Form_" + obj.value + ".php");
                }
            });            
        });
        $('forgotPass').addEvent('click', function(){
            myStickyWinModalObj.update("include/view/Form_LostPassword.php");
        });

        $$('.boleto').addEvent('click', function(){
            var pagInfo = this.id.split("_");
            loadBoletoPagamento(pagInfo[0], pagInfo[1]);
        });
        $$('.deposito').addEvent('click', function(){
            var pagInfo = this.id.split("_");
            loadDepositoPagamento(pagInfo[0], pagInfo[1]);
        });
        $$('.cartao').addEvent('click', function(){
            var pagInfo = this.id.split("_");
            var parcelas = $('parcelas_' + pagInfo[0]).value;
            loadCartaoPagamento(pagInfo[0], pagInfo[1], parcelas);
        });
        $$('.online').addEvent('click', function(){
            var pagInfo = this.id.split("_");
            loadOnlinePagamento(pagInfo[0], pagInfo[1]);
        });

        var requestCheckLoggedUser = new Request.JSON({
            url: 'libs/request_CheckLoggedUser.php',
            method: 'get',
            link: 'cancel',
            data: {'typeOf': 'checkLogged'},
            onSuccess: function(response){
                if(response['success']){
                    window.fireEvent('PaymentTab');
                    
                    $('AccountTp').setStyle('display','block').getElement('span').set('text', response['msg']);
                }
            }
        });
        requestCheckLoggedUser.send();
    });
    window.addEvent('Form_LostPassword', function(){
        $('form_wait').hide();
        
        var LostPasswordValidator = new FormValidator('LostPasswordForm');
        maskForm.setEmail($('Email'));

        $('LostPasswordForm').addEvent('submit', function(){
            submitAccountFloatForm(this, LostPasswordValidator);
        });

        $('Cancel_LostPassword').addEvent('click', hideMyStickyWinModal);
        $('Submit_LostPassword').addEvent('click', function(){
            $('LostPasswordForm').fireEvent('submit');
        });
    });
    window.addEvent('Form_Guest', function(){
//        $('tpPessoa')
        $('tpIdentf_formObjEl').dispose().inject($('tpPessoa'), 'bottom');
        $('CPF_formObjEl').dispose().inject($('tpPessoa'), 'bottom');
        $('CNPJ_formObjEl').dispose().inject($('tpPessoa'), 'bottom');

        $('form_wait').hide();
        $('Pais').addEvent('change', function(){
            paisChangeEvent(this.value, 'UF');
        });
        
        $('UF').getParent().adopt(
            new Element('img', {'src':'img/ajax-loader_2.gif'}).setStyles({'display': 'none', 'margin-left': 10})
        );
        changeTpPessoa();

        var GuestValidator = new FormValidator('GuestForm');
        GuestValidator.add('gtThanZero', {
            test: function(element){
                if(element.value == 0) return false;
                else return true;
            }
        });
        maskForm.setEmail($('Email'));
        maskForm.setEmail($('ConfirmEmail'));
        maskForm.setNumero($('TelPessoal_ddd'));
        maskForm.setSimpleTel($('TelPessoal'));
        maskForm.setNumero($('Celular_ddd'));
        maskForm.setSimpleTel($('Celular'));
        maskForm.setCEP($('CEP'));
        maskForm.setCPF($('CPF'));
        maskForm.setCNPJ($('CNPJ'));
        maskForm.setRequired($('NomeCompleto'));
        maskForm.setRequired($('Email'));
        maskForm.setRequired($('ConfirmEmail'));
        $('UF').addClass('gtThanZero');
        maskForm.setRequired($('Locd'));
        maskForm.setRequired($('Endereco'));

        $('GuestForm').addEvent('submit', function(){
            submitAccountFloatForm(this, GuestValidator);
        });
        $('Cancel_Guest').addEvent('click', hideMyStickyWinModal);
        $('Submit_Guest').addEvent('click', function(){
            $('GuestForm').fireEvent('submit');
        });
    });
    window.addEvent('Form_NewAccount', function(){
//        $('tpPessoa')
        $('tpIdentf_formObjEl').dispose().inject($('tpPessoa'), 'bottom');
        $('CPF_formObjEl').dispose().inject($('tpPessoa'), 'bottom');
        $('CNPJ_formObjEl').dispose().inject($('tpPessoa'), 'bottom');

        $('form_wait').hide();
        $('Pais').addEvent('change', function(){
            paisChangeEvent(this.value, 'UF');
        });
        
        $('UF').getParent().adopt(new Element('img', {'src':'img/ajax-loader_2.gif'}).hide());
        changeTpPessoa();

        var NewAccountValidator = new FormValidator('NewAccountForm');
        NewAccountValidator.add('gtThanZero', {
            test: function(element){
                if(element.value == 0) return false;
                else return true;
            }
        });
        maskForm.setRequired($('NomeCompleto'));
        maskForm.setEmail($('Login'));
        maskForm.setEmail($('ConfirmLogin'));
        maskForm.setRequired($('PW'));
        maskForm.setNumero($('TelPessoal_ddd'));
        maskForm.setSimpleTel($('TelPessoal'));
        maskForm.setNumero($('Celular_ddd'));
        maskForm.setSimpleTel($('Celular'));
        maskForm.setCEP($('CEP'));
        maskForm.setCPF($('CPF'));
        maskForm.setCNPJ($('CNPJ'));
        maskForm.setRequired($('Login'));
        $('UF').addClass('gtThanZero');
        maskForm.setRequired($('Locd'));
        maskForm.setRequired($('Endereco'));
        
        $('NewAccountForm').addEvent('submit', function(){
            submitAccountFloatForm(this, NewAccountValidator);
        });
        $('Cancel_NewAccount').addEvent('click', hideMyStickyWinModal);
        $('Submit_NewAccount').addEvent('click', function(){
            $('NewAccountForm').fireEvent('submit');
        });
    });

    window.addEvent('AccountTab', function(){
        $('AccountKeep').setStyle('display', 'block');
        var targetElSize = $('AccountObjEl').getElement('div').getSize();
        $('AccountObjEl').tween('height', targetElSize.y);
        $$('.accordionObjEl').each(function(obj){
            if(obj.id != 'AccountObjEl') obj.tween('height', 0);
        });
    });
    window.addEvent('PaymentTab', function(){
        var targetElSize = $('PaymentObjEl').getElement('div').getSize();
        $('PaymentObjEl').tween('height', targetElSize.y);
        $$('.accordionObjEl').each(function(obj){
            if(obj.id != 'PaymentObjEl') obj.tween('height', 0);
        });       
    });
    window.addEvent('Modal_Compare', function(){
        $('cancela').addEvent('click', hideMyStickyWinModal);
    });
});