
var voltarParaPosicao=null;
//motivo do ajax do hash
var viewLote='nao';
var navegadorOk=false;
$(function(){
    
    //organizarPlanoDeFundo();
    //window.onresize = organizarPlanoDeFundo;

    navegadorOk=testaNavegador();
    
    if(navegadorOk==false){
        window.attachEvent("onload", corrigePNG);
    }
    $('#informativo').show(); //exibe a div pai
    $('#informativo').cycle({
        fx:     'scrollVert',
        timeout: 6000,
        speed: 500
    }); 
    $(".infos").show();

    $(window).scroll(function () {
        var h = $("div#pagina").height()+165;
        $("#rodape").css('top',h).show();
    });
    
    setTimeout(function(){
        var h = $("div#pagina").height()+165;
        $("#rodape").css('top',h).show();
    },700);
    setTimeout(function(){
        var h = $("div#pagina").height()+165;
        $("#rodape").css('top',h).show();
    },1200);
    
    mascaras();

    horas();

    acoesLogin();

    acoesBotoesNavegacao();
    
    acoesQTip();
   
    //usada no hover da imagem
    $(".hover").hover( function() {
        var hoverImg2 = hoverImg($(this).attr("src"));
        $(this).attr("src", hoverImg2);
    }, function() {
        var normalImg2 = normalImg($(this).attr("src"));
        $(this).attr("src", normalImg2);
    }
    );
    
    //hover do background da div
    $(".hoverBackground").hover( function() {
        var hoverImg2 = hoverImg($(this).css("background-image"));
        $(this).css("background-image", hoverImg2);
    }, function() {
        var normalImg2 = normalImg($(this).css("background-image"));
        $(this).css("background-image", normalImg2);
    }
    );
    
    
    //hover no link
    $(".hoverlk").hover( function() {
        var hoverImg2 = hoverImg($(this).children('img').attr("src"));
        $(this).children('img').attr("src", hoverImg2);
    }, function() {
        var normalImg2 = normalImg($(this).children('img').attr("src"));
        $(this).children('img').attr("src", normalImg2);
    }
    );
    
    // click no itens do menu esquerdo logado
    $('#menu-esquerdo-logado > li,.subtitulo > li').click(function(){
        if ($.browser.msie)
            window.event.returnValue = false;
        if(typeof($(this).children('a').attr('href'))!='undefined')
        location.href=$(this).children('a').attr('href');
    });
    
    
    //desativado por motivo do hash ter q ser usado em outros ajax também
    //me mostrar o motivo pra gente resolver
    if(viewLote=='sim')
        acoesVisualizarLote();
      
      
});

function mostraDialog(titulo,mensagem) {
    $("#mensagem").dialog('close');
    var modal=true;
//    if(titulo=='Erro') {
//        modal = false;
//    }
    $("#mensagem").dialog({
        autoOpen: false,
        closeOnEscape: true,
        modal: modal,
        height: 120,
        width: 300,
        title:titulo,
        zIndex:99999
    });
    $("#mensagem").find('p').html(mensagem);
    $("#mensagem").dialog('open');
}

function acoesVisualizarLote()
{
    $.history.init(function(hash){        
        if(hash == "") {
                        
        }
        else {
            largura=940;            
            altura=720;
            if($.browser.msie){
                largura=940;                
                altura=720;
                
                voltarParaPosicao=$(window).scrollTop();
                $('body').scrollTo(0,0);
            }
            
            $.colorbox({
                href:baseUrl+"lotes/visualizar-simples/lote/"+hash
                ,
                'height':altura+'px'
                ,
                'width':largura+'px'                
                ,
                'scrolling':'false'
                , 
                onComplete:function(){
                    acoesPosteriorAnterior();
                    /*
                    $(document).bind({
                        keyup: function(e) {
                            if(e.which == 39){
                                $("#box-navegador-direito").click(); 
                            } else if (e.which == 37){
                                $("#box-navegador-esquerdo").click(); 
                            }
                        } 
                    });
                    */
                }
                ,
                onClosed:function(){
                    //$(document).unbind()
                    //acoesLinha();
                }
            });               
        }
    },
    {
        unescape: ",/"
    });
      
   
    $(document).bind('cbox_closed', function(){
        
        var pos = $(window).scrollTop(); // get scroll position
//         if(!$.browser.msie){ 
//             window.location.hash = '';
//         }
//         
        $(window).scrollTop(pos); // set scroll position back        
//        $("#tb-lotes > tbody > tr").removeClass('linha-selecionada');
//        $("#tb-lotes > tbody > tr.linha-selecionada").removeClass('linha-selecionada');
        $("#tb-lotes > tbody > tr").removeClass('linha-selecionada');
        $("#tb-lotes > table > tbody > tr.linha-selecionada").removeClass('linha-selecionada');
        
        if(voltarParaPosicao!=null)
            setTimeout(function(){
                $("body").scrollTo(voltarParaPosicao)
            },700);
            
        if(typeof(tempo)!='undefined') {
            clearTimeout(tempo);
        }                  
         
    });
    
    $(document).bind('cbox_complete', function(){
        //acoesPosteriorAnterior();
        acoesVisualizacaoSimples();     
    });
    
    acoesLinha();
}

function acoesLinha()
{
    $(".linha").live('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            if($(this).hasClass('impar')){ 
                $(this).removeClass('impar');
                $(this).addClass('impar-voltar');
            }
            $(this).addClass('linha-hover');
        } else {
            $(this).removeClass('linha-hover');
            if($(this).hasClass('impar-voltar')){ 
                $(this).removeClass('impar-voltar');
                $(this).addClass('impar');
            }
        }
    });

    $(".linha").live('click',function(data){
        if($(data.target).hasClass('semClick')==false && $(this).hasClass('semClick')==false) {
           if(!$.browser.msie){   
            jQuery.history.load($(this).attr('rel'));
            $("#tb-lotes > tbody > tr").removeClass('linha-selecionada');
            $(this).addClass('linha-selecionada');
           }
           else{
               window.open(baseUrl+'lote/'+$(this).attr('rel'),'lote'+$(this).attr('rel'),'height=600,width=900,scrollbars=yes');
           }
//            $("#tb-lotes > tbody > tr").removeClass('linha-selecionada');
//            $(this).parent().find('input[type="checkbox"]').removeAttr('checked');
//            $(this).find('input[type="checkbox"]').attr('checked','checked');
        }
    });
}

function testaNavegador(){
    var retorno = true; 
    
    /*
    if($.browser.chrome)
        alert("chrome");
    
    if($.browser.mozilla || $.browser.msie || $.browser.chrome){
        retorno = true; 
    }
    */

    
    if($.browser.msie){          
        if ($.browser.version == "6.0" || $.browser.version == "7.0"||
        $.browser.version == "6.1" || $.browser.version == "7.1"){
            retorno = false;
        }
    }
    
    return retorno;   
}

function acoesQTip(){
    
    
    if(navegadorOk==true && (navigator.platform.indexOf("iPhone") == -1) &&
        (navigator.platform.indexOf("iPod") == -1)){ 
    $('.tooltip').qtip({
        effect: function(api, offset) {
            $(this).animate(offset, 400, 'swing'); // "this" refers to the tooltip
        },
        style: {
            classes: 'ui-tooltip-red ui-tooltip-rounded ui-tooltip-shadow'
        },
        position: {
            target: 'mouse',
            adjust: {
                mouse: true , // Can be ommited (e.g. default behaviour)
                y:10,
                x:10
            }
        }
    });
    }
}

function acoesBotoesNavegacao() {
    $("#navegacao").children(".voltar").click(function(){
        history.back();
    });

    $("#navegacao").children(".topo").click(function(){
        $('body').scrollTo($("#menu-topo-conteudo"),500);
    });
}

function acoesLogin() {

    $(".menu-box-login").click(function(){

        if(!$(this).hasClass('menu-box-logado')) {
            if(!$(this).hasClass('apertado')) {
                if($("#box-cidades").css('display')=='block') $("#box-cidades").slideUp('slow');
                $("#box-login").slideDown('slow');
                $(this).addClass('apertado');
                setTimeout(function(){
                    $("#ipt-email-login").focus();
                },600);
                $("img").show();
            }
            else {
                $("#box-login").slideUp('slow');
                $(this).removeClass('apertado');
                $("#box-erro-form-login").html('');
                $("#box-erro-form-login").hide();
            }
            return false;
        }
    });
    
    $("#senhaLogin").keyup(function(e)
    {        
        if(e.which == "13"){
           if($("#processando-requisicao").val()==0) 
            $("#form-login-menu").submit();
           //return false; 
        }
        
    });

    $("#bt-login-menu").click(function(){
        if($("#processando-requisicao").val()==0)
            $("#form-login-menu").submit();
        //return false;
    });
    
    $(".gravar").click(function(){
        if($('input[name="gravarLogin"]').is(':checked')) {
            $('input[name="gravarLogin"]').attr('checked',false);
        } else {
            $('input[name="gravarLogin"]').attr('checked',true);
        }
    });

    $("#form-login-menu").validate({
        errorLabelContainer: $("#box-erro-form-login"),
        errorElement: "div",
        submitHandler:function(){
            $("#form-login-menu").ajaxSubmit({
                beforeSend: function(){                    
                    $("#processando-requisicao").val(1);
                    $("#box-erro-form-login").css('display','block');
                    $("#box-erro-form-login").html('Enviando dados...');
                },
                error: function(){
                    $("#box-erro-form-login").css('display','block');
                    $("#box-erro-form-login").html('erro');                    
                },
                dataType: "json",
                success: function(data) {
                    $("#box-erro-form-login").css('display','block');
                    
                    if(data.erro == 0 ) {
                        $("#box-logado").show();                        
                        $(".nome-logado").html(data.nome);
                        $(".menu-box-login").click();
                        $(".menu-box-login").hide();
                        $(".menu-box-sair").show();
                        $("#usuario-logado").val('1');
                        // se estiver na pagina de lotes, recarrega a lista
                        if ($(".btBuscarDados").length > 0){
                            $(".btBuscarDados").click();
                        }
                    }
                    else {
                        $("#box-erro-form-login").html(data.msg);
                    }
                    $("#processando-requisicao").val(0);
                }
            });// fim ajaxsubmit

        }
    });

    $(".esqueceuSenha").click(function(){
        $(".esqueceuSenha").hide();
        $("#bt-login-menu").hide();
        $("#box-erro-form-login").html("Enviando para "+$("#ipt-email-login").val()).show();
        $("#processamento-email").show();

        if($("#ipt-email-login").val().length==0) {
            $("#processamento-email").hide();
            $("#box-erro-form-login").html("Preencha seu e-mail");
            $("#ipt-email-login").focus();
            $(".esqueceuSenha").show();
            $("#bt-login-menu").show();
        }else {
            $.post(baseUrl+'esqueceu-senha',{
                email:$("#ipt-email-login").val()
            },function(data){
                $(".esqueceuSenha").show();
                $("#bt-login-menu").show();
                if(data.erro==0) {
                    $("#processamento-email").hide();
                    $("#box-erro-form-login").html("Recuperação de senha enviada para "+data.destinatario);
                }
                else {
                    $("#processamento-email").hide();
                    $("#box-erro-form-login").html("Email "+data.destinatario+" não está cadastrado");
                    $("#ipt-email-login").focus();
                }
            },'json');
        }
        return false;

    });
    
    $(".reenviarConfirmacao").live('click',function(){        
        $(".esqueceuSenha").hide();
        $("#bt-login-menu").hide();
        $("#box-erro-form-login").html("Enviando para "+$("#ipt-email-login").val()).show();
        $("#processamento-email").show();

        if($("#ipt-email-login").val().length==0) {
            $("#processamento-email").hide();
            $("#box-erro-form-login").html("Preencha seu e-mail");
            $("#ipt-email-login").focus();
            $(".esqueceuSenha").show();
            $("#bt-login-menu").show();
        }else {
            $.post(baseUrl+'pessoax/reenviar-confirmacao',{
                email:$("#ipt-email-login").val()
            },function(data){
                $(".esqueceuSenha").show();
                $("#bt-login-menu").show();
                if(data.erro==0) {
                    $("#processamento-email").hide();
                    $("#box-erro-form-login").html("Confirmação de cadastro enviado para "+data.destinatario);
                }
                else {
                    $("#processamento-email").hide();
                    $("#box-erro-form-login").html("Email "+data.destinatario+" não está cadastrado");
                    $("#ipt-email-login").focus();
                }
            },'json');
        }
        return false;

    });

};

function horas(){
    camada = document.getElementById('relogio');

    hoje = new Date();

    hora = hoje.getHours();
    if(hora<=9){
        hora = "0" + hora;
    }

    minuto = hoje.getMinutes();
    if(minuto<=9){
        minuto = "0" + minuto;
    }

    segundo = hoje.getSeconds();
    if(segundo<=9){
        segundo = "0" + segundo;
    }

    camada.innerHTML = hora + ":" + minuto + ":" + segundo;

    setTimeout("horas()",1000);
}

function hoverImg(file)
{
    var re = new RegExp("(.+)\\.(gif|png|jpg)", "g");
    return file.replace(re, "$1-hover.$2");
}
function normalImg(file)
{
    var re = new RegExp("(.+)-hover\\.(gif|png|jpg)", "g");
    return file.replace(re, "$1.$2");
}

function organizarPlanoDeFundo() {
    var e = ($("div#conteudo-esquerdo").height());
    var d = ($("div#conteudo-direito").height());
    
    if(e > d){
        $("div#conteudo-direito").css('height',e+55);
        $("div#conteudo-esquerdo").css('height',d+159);
    } else {
        $("div#conteudo-esquerdo").css('height',d);
    }
/*
    var h = $("div#pagina").height()+205;
    $("#rodape").css('top',h).show();
    var t = document.body.clientWidth;
   
    var e = (t-985)/2+212;
    //$("#rodape-forma-pagamento-cartoes").css('margin-left',e+'px');
    $("#box-escolha-cidade").css('left',490+e+'px');
    $("#box-escolha-cidade").hide();
    $("#rodape").show();
    */
}


function corrigePNG()
{
    for(var i=0; i<document.images.length; i++)
    {
        var img = document.images[i]
        var imgName = img.src.toUpperCase()
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
        {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i-1
        }
    }
}





function mascaras(){

    $('.data').mask("99/99/9999");
    $('.placa').mask("aaa-9999");
    $('.mesAno').mask("99/9999");
    $('.ano').mask("9999");
    $('.telefone').mask("(99) 9999-9999");
    $(".cpf").mask("999.999.999-99");
    $(".cnpj").mask("99.999.999/9999-99");
    $(".cep").mask("99999-999");
    
    $(".numero").keyup(function(e) {
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });
    $(".urlPossiveis").keyup(function(e) {
        this.value = this.value.replace(/[^0-9a-zA-Z\-_\.]/g,'');
    });
}

function obterCidades(uf,obj,selecionar) {
    $.ajax({
        type:'post',
        url:baseUrl+"cep/obter-cidades",
        data:{
            estado:uf,
            selecionar:selecionar
        },
        beforeSend:function(){
            obj.html('<option>Carregando...</option>');
        },
        success:function(data){
            //obj.attr('disabled',''); // NAO USAR!!!!!
            //obj.disable();            
            obj.html(data);
        }
    });
}

function empty(v){
    if (v==null || v==0 || v=='' || v==""){
        return true
    }else {
        return false
    }
}


jQuery.fn.disable = function(mode)
{
    var mode = mode || 'on';
    return this.each(function() {

        switch(mode)
        {
            case 'on':
                this.disabled = true;
                break;
            case 'off':
                this.disabled = false;
                break;
            case 'toggle':
                this.disabled = !this.disabled;
                break;
        }

    });
};

function blockjUI(pid,pheight,pwidth,pesc){
    //esqueci-senha
    $("#dialog").html($("#"+pid).html());
    //$("#dialog").html('oi');
    $( "#dialog" ).dialog({
        position:['center','middle'],
        show: "fold",
        hide: "fold",
        autoOpen:false,
        height:pheight,
        width:pwidth,
        resizable:false,
        modal: true
    });
    $("#dialog").siblings('div.ui-dialog-titlebar').remove();
    $("#dialog").dialog('open');
    $(".ui-dialog").css('background-color','white');

    $(".bt-fechar-dialog").click(function(){
        $( "#dialog" ).dialog('close');
    });

    return false;
    
}

function numberToMoeda(valor) {
    var SeparadorDecimal = ",";
    var SeparadorMilesimo = ".";
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    len = valor.length;
    for(i = 0; i < len; i++)
        if ((valor.charAt(i) != '0') && (valor.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(valor.charAt(i))!=-1) aux += valor.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) valor = '';
    if (len == 1) valor = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) valor = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        valor = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            valor += aux2.charAt(i);
        valor += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return valor;
}



