$(document).ready(function(){
    
    function aguarde_in() {
        //$("input[name='submitt']").attr('disabled', true);
    }
    
    function aguarde_off() {
        //$("input[name='submitt']").removeAttr('disabled');
    }
    
    $('a.mapa').click(function(){
        window.open('http://maps.google.com.br/maps?f=q&source=s_q&hl=pt-BR&geocode=&q=Av.+Presidente+Wilson,+2432&sll=-23.099944,-41.989746&sspn=5.970343,11.634521&ie=UTF8&hq=&hnear=Av.+Pres.+Wilson,+2432+-+M%C3%B3oca,+S%C3%A3o+Paulo,+03107-001&ll=-23.574568,-46.601257&spn=0.011053,0.022724&t=h&z=16');
    });
    
    tinyMCE.init({
        mode : "textareas",
        theme : "simple",
        editor_selector : "curriculo"
    });
    
    
    //LOOP IMAGENS
    $('div.flash').cycle({ 
        fx:     'fade', 
        speed:   2000, 
        timeout: 8000, 
        next:   'div.flash',
        continuos: true,
        pause:   1
    });
    
    
    //ADICIONANDO MASCARA
    function addMask() {
        //MASCARA CAMPO DATA E HORA
        $("input.dh").mask("99/99/9999 99:99",{placeholder:" "});
        $("input.d").mask("99/99/9999",{placeholder:" "});
        $("input.cep").mask("99.999-999",{placeholder:" "});
        $("input.tel").mask("(99) 9999-9999",{placeholder:" "});
        $("input.uf").mask("aa",{placeholder:" "});
        $("input.cpf").mask("999.999.999-99",{placeholder:" "});
    }
    
    addMask();
    
    $('div.headerin>ul>li>a').dropShadow({
        left: 0,
        top: 2,
        blur: 0,
        opacity:1,
        color: "black",
        swap: false
    });
    
    $('ul.vmenu li').mouseover(function(){
        $(this).children('div.submenu').css({'display':'block'});
    });
    
    $('ul.vmenu li').mouseout(function(){
        $(this).children('div.submenu').css({'display':'none'});
    });
    
    //$('ul.vmenu li div.submenu ul.submenu2 li').mouseover(function(){
    //    $(this).children('div').css({'display':'block'});
    //    $(this).children('a').css({'background':'#E5E5E5'});
    //    $(this).children('a').css({'color':'#000000'});
    //});
    //
    //$('ul.vmenu li div.submenu ul.submenu2 li').mouseout(function(){
    //    $(this).children('div').css({'display':'none'});
    //    $(this).children('a').css({'background':'#2D2D2D'});
    //    $(this).children('a').css({'color':'#6DBFFD'});
    //});
    

    $("#slider").easySlider({
        continuous: true
    });
    
    
    //FUNCAO PARA LIMPAR CAMPOS DOS FORMS
    $("div.newsletter form ul li input:text, div.busca form ul li input:text").focus(function(){
        if(this.value == this.title) {
            $(this).val('');
        }
    });
    
    $("div.newsletter form ul li input:text, div.busca form ul li input:text").blur(function(){
        if($.trim(this.value) == '') {
            $(this).attr('value', this.title);
        }
    });
    //
    
    
    //GALERIA DE IMAGENS E VIDEO
    $(function(){
        if($('div.fotos')[0]) {
            $('a.video').css({'color':'#6DBFFD','background':'url(../img/bt_produto_galeria.jpg) no-repeat'});
            $('div.videos').css({'display':'none'});
        } else {
            $('a.video').css({'color':'#000000','background':'url(../img/bt_produto_galeria_hover.jpg) no-repeat'});
            $('div.videos').css({'display':'block'});
        }
        $('a.foto').css({'color':'#000000','background':'url(../img/bt_produto_galeria_hover.jpg) no-repeat'});
        $('a.zoom_img:first').css({'border':'1px solid #6DBFFD'});
    });
    
    $('a.zoom_img').click(function(){
        $('div.produto_galeria_zoom').html('<img src="'+this.href+'" />');
        $('div.produto_galeria ul li a').css({'border':'1px solid #CFD0D2'});
        $(this).css({'border':'1px solid #6DBFFD'});
        return false;
    });
        
    $('a.foto').click(function(){
        $('div.videos').css({'display':'none'});
        $('div.fotos').css({'display':'block'});
        $('a.video').css({'color':'#6DBFFD','background':'url(../img/bt_produto_galeria.jpg) no-repeat'});
        $(this).css({'color':'#000000','background':'url(../img/bt_produto_galeria_hover.jpg) no-repeat'});
    });
        
    $('a.video').click(function(){
        $('div.fotos').css({'display':'none'});
        $('div.videos').css({'display':'block'});
        $('a.foto').css({'color':'#6DBFFD','background':'url(../img/bt_produto_galeria.jpg) no-repeat'});
        $(this).css({'color':'#000000','background':'url(../img/bt_produto_galeria_hover.jpg) no-repeat'});
    });
    
    
    
    //FUNCAO PARA SUBMETER FORMULARIOS COM O JQUERY FORM [GERAL]
function submitForms() {
    
    //tinyMCE.triggerSave();
    $("input[type='submit']:not(input[name='submit2'])").click(function(){
        aguarde_in();
        //$(this).attr('disabled', true);
        
        //QUANDO FORM COM TINYMCE E ATIVADO POR UMA FUNCAO EXTERNA, E NECESSARIO SALVAR O CONTEUDO NO TEXTAREA
        //tinyMCE.triggerSave();
        //PEGA PELO ATRIBUTO TITULO DO SUBMIT O TIPO DE ACAO DO FORMULARIO
        var acao = $(this).attr('title');
        //PEGA PELO ID DA TABELA A CATEGORIA DO FORMULARIO
        var idTable = $(this).parent().parent().attr('id');
        //PEGA ID DO ITEM
        var id = $("form#"+idTable+" input[name='id']").fieldValue()[0];
        //PEGA ULTIMA PAGINACAO
        var pag = $("form#"+idTable+" input[name='pag']").fieldValue()[0];
        //PEGA REDIRECIONAMENTO
        var redirect = $("form#"+idTable+" input[name='redirect']").fieldValue()[0];
        //PEGA RETORNO
        var retorno = $("form#"+idTable+" input[name='retorno']").fieldValue()[0];
        var noajax = $("form#"+idTable+" input[name='noajax']").fieldValue()[0];
        //PEGA RETORNO
        var ajax = $("form#"+idTable+" input[name='ajax']").fieldValue()[0];
        
        //PEGA RETORNO
        var shadowClose = $("form#"+idTable+" input[name='shadow']").fieldValue()[0];
        
        
        
        if($(this).attr('class') !== 'ajax') {
        
            //INICIA PROCESSO DE POSTAGEM DO FORMULARIO
            $(function(){
                var options = { target: null, beforeSubmit: validate, success: processJson, forceSync:true, url: '/ajax/'+idTable+'-'+acao+'/?iefix='+ Math.random(), type: 'post', dataType:'json'};
                    $('form#'+idTable).ajaxForm(options);
            });
        
        } else {
            //INICIA PROCESSO DE POSTAGEM DO FORMULARIO
            $(function(){
                var options = { target: null, beforeSubmit: showRequest, success: showResponse, forceSync:true, url: '/ajax/'+idTable+'-'+acao+'/?iefix='+ Math.random(), type: 'post', dataType:'html'};
                    $('form#'+idTable).ajaxForm(options);
            });
        }
        
        //PARAMETRIZANDO CAMPOS DO FORMULARIO
        function showRequest(formData, jqForm, options) {
            var queryString = $.param(formData);
            return true;
        }
        //PARAMETRIZANDO CAMPOS DO FORMULARIO
        function showResponse(responseText, statusText)  { 
            $('div.resultado').html(responseText);
        }
        
        //VALIDANDO CAMPOS
        function validate(formData, jqForm, options) {

            
            //MONTANDO MENSAGEM INICIAL DE ERRO E NUMERACAO PARA CADA ERRO
            var inconsistencias = '';
            var inconsistenciasE = false;
            var x = 0;
            
            //REINICIANDO CORES DOS FORMULARIOS APOS NOVO SUBMIT
            $('form#'+idTable+' ul li input, form#'+idTable+' ul li textarea').removeClass('form_error');
            $('form#'+idTable+' ul li input, form#'+idTable+' ul li textarea').keyup(function(){
                $(this).removeClass('form_error');
            });
            $('form#'+idTable+' ul li select').change(function(){
                $(this).removeClass('form_error');
            });
            
            
            //INICIANDO PROCESSO DE VALIDACAO PASSANDO POR CADA CAMPO DE FORMULARIO
            for (var i=0; i < formData.length; i++) {
                
                //PROCESSO DE VALIDACAO DE CAMPOS DO TIPO INPUT, CASO ESTEJA VAZIO E COM CLASS SETADO PARA OBG
                if($('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').hasClass('obg') & $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('value') == '') {
                    $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').addClass('form_error');
                    x++;
                    inconsistencias += x+'. Preencha o campo '+$('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('title')+'<br/>';
                    inconsistenciasE = true;
                }
                
                //PROCESSO DE VALIDACAO DE CAMPOS DO TIPO TEXTAREA, CASO ESTEJA VAZIO E COM CLASS SETADO PARA OBG
                if($('form#'+idTable+' ul li textarea[name=\''+formData[i].name+'\']').hasClass('obg') & $('form#'+idTable+' ul li textarea[name=\''+formData[i].name+'\']').attr('value') == '') {
                    $('form#'+idTable+' ul li textarea[name=\''+formData[i].name+'\']').addClass('form_error');;
                    x++;
                    inconsistencias += x+'. Preencha o campo '+$('form#'+idTable+' ul li textarea[name=\''+formData[i].name+'\']').attr('title')+'<br/>';
                    inconsistenciasE = true;
                }
                
                if($('form#'+idTable+' ul li select[name=\''+formData[i].name+'\']').hasClass('obg') & $('form#'+idTable+' ul li select[name=\''+formData[i].name+'\']').attr('value') == '') {
                    $('form#'+idTable+' ul li select[name=\''+formData[i].name+'\']').addClass('form_error');;
                    x++;
                    inconsistencias += x+'. Selecione o campo '+$('form#'+idTable+' ul li select[name=\''+formData[i].name+'\']').attr('title')+'<br/>';
                    inconsistenciasE = true;
                }
                
                if($('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').hasClass('obgext') & $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('rel') != '' & $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('value') != '') {
                    var textensoes = $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('rel')
                    if(valExt($('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('value'), $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('rel')) == false) {
                        $('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').addClass('form_error');
                        x++;
                        inconsistencias += x+'. Arquivo inválido para o campo '+$('form#'+idTable+' ul li input[name=\''+formData[i].name+'\']').attr('title')+'. (Permitido '+textensoes.toString().replace(/,/g,', ')+')<br/>';
                        inconsistenciasE = true;
                    }
                    
                    
                }
                
                
            }
            
            if(inconsistenciasE) {
                //$("input[type='submit']").attr('disabled', false);
                aguarde_off();
                alert0("Inconsistências", inconsistencias);
                return false;
            } else {
                if($("input[name='APC_UPLOAD_PROGRESS']")[0]) {
                    $("span.status").css({'width':'0'});
                    $("strong.percent").text('0%');
                    var uid = $("input[name='APC_UPLOAD_PROGRESS']").val();
                    getProgress(uid);
                    setTimeout(function(){
                        $('input.uploadProgress').attr('disabled', true);
                    }, 200);
                }
            }
        }
        
        //PROCESSANDO JSON E VALIDACOES DO LADO DO SERVIDOR
        function processJson(data) {
            //$("input[type='submit']").attr('disabled', false);
            //SE O CAMPO OK ESTIVER SETADO PARA "0" RETORNAR MENSAGEM DE ERRO
            if(data.ok == 0) {
                aguarde_off();
                //alert(data.msg);
                alert0('Erro', data.msg);
                   
            //SE NAO TIVER SETADO PARA "0" MOSTRAR MENSAGEM DE CONFIRMACAO E REDIRECIONAMENTO
            } else {
                
                if(retorno == 1) {
                    
                    if(shadowClose == 1) {
                        alert(data.msg)
                        window.parent.location = "/";
                        window.parent.Shadowbox.close();
                        
                    } else {
                        alert0('Mensagem', data.msg)
                    }
                    
                    
                    
                    
                    if(noajax==undefined) {
                        $.post(redirect, {ajax: '1', iefix: Math.random(), id: id, pag: pag}, function(data){
                            $("div#content").html(data);
                            
                        });
                    } else {
                        setTimeout(function(){
                            window.location = noajax;
                        },3000);
                        
                    }
                    
                } else {
                    $.post(redirect, {ajax: '1', iefix: Math.random(), id: id, pag: pag}, function(data){
                        $("div#content").html(data);
                        $("div#content_img").html(data);
                        if(ajax == 'galeria') {
                            listImagens();
                        }
                        
                    });
                }
                
            }
        }
        
        
        
    });
}
    submitForms();
    
    function alert0(titulo, texto) {
        
        $("#alert").attr('title', titulo);
        $("#alert").html(texto);
        
        $("#alert").dialog({
            bgiframe: true,
            resizable: false,
            minHeight: 0,
            modal: true,
            overlay: {
            backgroundColor: '#000',
            opacity: 0.5
            },
            buttons: {
                'OK!': function() {
                    $(this).dialog('destroy');
                }
            }
        });
        
        $("#alert").dialog('open');
        
    }
    
    function alert1(titulo, texto, tsim) {
        
        $("#alert").attr('title', titulo);
        $("#alert").html(texto);
        
        $("#alert").dialog({
            bgiframe: true,
            resizable: false,
            minHeight: 0,
            modal: true,
            overlay: {
            backgroundColor: '#000',
            opacity: 0.5
            },
            buttons: {
                'OK!': function() {
                    $(this).dialog('destroy');
                    tsim();
                }
            }
        });
        
        $("#alert").dialog('open');
    }
    
    
    
    
});
