var timeoutID3 = 0;
var timeoutID2 = 0;
var timeoutID = 0;
function showMessageHelp(msg)
{
    var pre_id = "";

    $(pre_id+" #msg_help").html(msg);
    $(pre_id+" #msg_help").show('slow');
     window.clearTimeout(timeoutID2);
     timeoutID2 = window.setTimeout(hideMessage, 4000, true);	
}
function hideMessage() { $("#footer #msg_help").hide('slow');  $("#header #msg_help").hide('slow'); }


	

$(document).ready(function(){

	$(".abas a.btn-cad span.btn-finalizar-cad").parent().hide();
	$(".abas:last").find("a.btn-cad span.btn-finalizar-cad").parent().show();
	$(".abas:last").find("a.btn-cad span.btn-prox-cad").parent().hide();	
	$("input[type='textarea']").css('resize','none');
	$(".cod-input ,.detailform_top #endereco_busca").keyup(function(e){
	//alert(e.keyCode);
		if(e.keyCode == 13)
		{
			$(".detailform_bot .link1").eq(0).trigger('click');
		}
		});

	/* PLUGIN DE PNG FIX */
	if($.browser.msie && ($.browser.version == "6.0")){ $(document).pngFix(); }

    $('*[rel="toolTip"], *[rel="tooltip"]').tooltip({
		bgColor: '#FFFFFF',
		color: '#2D4E78',
		borderColor: '#003660',
		fontSize: '11',
		width: '300'
	});
	
	/* HABILITA OS SELECTS CUSTOM */
	//$('#sl1').sSelect();
	$('.sel1 select, .sel2 select, .sel4 select').sSelect();	
	/* HABILITA OS SELECTS CUSTOM */

    /*$("#data_nasc").val("Data de Nascimento:");
    $("#rg").val("RG:");
    $("#cpf").val("CPF:");
    $("#cep").val("CEP:");
    $("#fone_residencial").val("Fone Residencial:");
    $("#celular").val("Celular:");
    $("#phone_com").val('* Comercial');
    $("#phone_cel").val('* Celular');
    $("#phone").val('* Residencial');
    $("#valor_cond").val('Valor cond.:');
    $("#valor_cond").css('text-align','left');*/
      //$("#valor_cond").val('Valor cond.:');
    //$("#valor_cond").css('text-align','left');	
    $(".rg_cad").val("RG:");	
    //$("#fone_recados").val("Fone Recados:");	
    $("#search").val("Palavra-chave");
   // $("#cpf").val("* CPF:");
    //$("#telefone").val("* Telefone:");
    //$("#data_nasc").val("Data Nasc.:");	
	$(".data_nasc_cad").val("Data Nascimento:");
	$(".data_cas_cad").val("Data Casamento:");	
	$(".data_nasc_cad2").val("Data Nasc.:"); 
	//$("#phone").val("* Residencial:");
	//$("#phone_com").val("* Comercial:");	
	//$("#phone_cel").val("* Celular:");		
	//$("#valor_cond").val("Valor cond.:");
	
	// VALOR PADRAO CADASTRO PESSOA E OUTROS
    $(".ddd_cad").val("DDD:");		
    $(".fone_cad").val("Fone:");	
    $(".fone_rec_cad").val("Fone Recados:");		
    $(".fone_res_cad").val("Fone Residencial:");	
    $(".fone_com_cad").val("Fone Comercial:");		
    $(".fone_cel_cad").val("Fone Celular:");	
    $(".fone_res_cad_obrig").val("* Fone Residencial:");	
    $(".fone_com_cad_obrig").val("* Fone Comercial:");		
    $(".fone_cel_cad_obrig").val("* Fone Celular:");
    $(".fone_pai_cad").val("Fone Pai:");
    $(".fone_mae_cad").val("Fone Mãe:");		
    $(".cel_cad").val("Celular:");			
    $(".cnpj_cad").val("CNPJ:");			
    $(".cpf_cad").val("CPF:");
    $(".cic_cad").val("CIC:");	
    $(".cic_cad_obrig").val("* CIC:");		
    $(".cep_cad").val("CEP:");	
    //$(".email_cad").val("E-mail:");	
    $(".cel_cad_obrig").val("* Celular:");				
    $(".ddd_cad_obrig").val("* DDD:");		
    $(".fone_cad_obrig").val("* Fone:");		
    $(".cnpj_cad_obrig").val("* CNPJ:");			
    $(".cpf_cad_obrig").val("* CPF:");
    $(".cep_cad_obrig").val("* CEP:");	
    $(".email_cad_obrig").val("* E-mail:");
    //$("#data_construcao").val("Data de Constituição:");		
	//$("#data_expedicao").val("Data da Expedição:");
	//$("#fone_empresa").val("Fone com.:");
	//$("#expedicao_conjugue").val("Data Expedição:");
	//$(".data_cad_cad").val("* Data cadastro:");
	//$("#fone_res_prop").val("* Fone Residencial:");
	//$("#fone_com_prop").val("* Fone Comercial:");	
	//$("#fone_cel_prop").val("Fone Celular:");	
	//$("#dta_exp_id_prop, #dta_exp_id_proc_prop").val("Data Exp.:");
	//$("#cpf_cgc").val("CPF/CGC:");
	//$("#dta_exp_id_conjuge_prop").val("Data Exp.:");
	//$("#fone_res_conjuge_prop, #fone_res_proc_prop").val("Fone Res.:");
	//$("#fone_com_conjuge_prop, #fone_com_proc_prop").val("Fone Comercial:");	
	//$("#fone_cel_conjuge_prop, #fone_cel_proc_prop").val("Fone Celular:");		
	//$("#fone_cont1").val("Fone Cont.1:");
	//$("#fone_cont2").val("Fone Cont.2:");	
	//$("#cpf_correntista").val("CPF Correntista:");
	
	$(".obrig").each( function() { $(this).val("* " +$(this).val()) })
	$(".sem2pontos").each( function() { $(this).val($(this).val().replace(':','')) })


	function nextField()
	{
	
			var yourFormFields = $("#yourForm").find('button,input,textarea,select');


			var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1

			if ( index > -1 && ( index + 1 ) < yourFormFields.length ) { 

					var nextElement = yourFormFields.eq( index + 1 );
					nextElement.focus();	
			}
	
	}

	
$(document).ready(function(){




	// down
	$(":input[type='text']").attr('autocomplete','off');	
	
	$(":input[type='text']").keyup(function(e){
	//alert(e.keyCode);
		if(e.keyCode == 40)
		{
			
		//	if($(this).val().length>0)
			//{
				var yourFormFields = $(this).parents('form').find('button,input,textarea,select');


				var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1

				if ( index > -1 && ( index + 1 ) < yourFormFields.length ) { 

						var nextElement = yourFormFields.eq( index + 1 );
						nextElement.focus();	
				}
		//	}			
		}
		if(e.keyCode == 38)
		{
		//	if( $(this).val().length>0)
		//	{
				var yourFormFields = $(this).parents('form').find('button,input,textarea,select');


				var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1

				if ( index > -1 && ( index - 1 ) >=0 ) { 

						var nextElement = yourFormFields.eq( index -1 );
						nextElement.focus();	
				}
		//	}	
		
		}
	});
	// up
	/*$("form :input").keyup(function(e){
		if(e.keyCode == 40)
		{
			var yourFormFields = $("#yourForm").find('button,input,textarea,select');


			var index = yourFormFields.index( this ); // the index of your current element in the list. if the current element is not in the list, index = -1

			if ( index > -1 && ( index + 1 ) < yourFormFields.length ) { 

					var nextElement = yourFormFields.eq( index + 1 );
					nextElement.focus();	
			}			
		}

	});*/
});	
	
    /* PLUGIN DE WATERMARK */
    watermark.init();
	
    /* PLUGIN DE PNG FIX */
    if($.browser.msie && ($.browser.version == "6.0")){
        $(document).pngFix();
    }

    /* CUSTOM SELECT */
    if($('select.styled').size()) $('select.styled').customStyle();

    /* SCRIPTS NON OBSTRUCTIVE  */
    $('.call-us a').click(function() {
        if($('.call-us .filial').hasClass('hide'))  {
            $('.call-us .filial').removeClass('hide');
            $('.call-us .matriz').addClass('hide');
        } else {
            $('.call-us .matriz').removeClass('hide');
            $('.call-us .filial').addClass('hide');
        }
    });

    $('ul.list a.anchor').click(function() {
        var goTo = 'top_'+$(this).attr('rel');
        gotoAnchor(goTo);
    });

    /* search top */
    $("div.contaba").hide();
    $("div.contaba:first").show();
    $("#abas a:first").addClass("selected");

    $("#abas a").click(function(){
        $("div.contaba").hide();
        $("#abas a").removeClass("selected");
        $(this).addClass("selected");
        $($(this).attr("href")).show();
        return false;
    });

    /* search bottom top */
    $("div.contaba_bottom").hide();
    $("div.contaba_bottom:first").show();
    $("#abas_bottom a:first").addClass("selected");

    $("#abas_bottom a").click(function(){
        $("div.contaba_bottom").hide();
        $("#abas_bottom a").removeClass("selected");
        $(this).addClass("selected");
        $($(this).attr("href")).show();
        return false;
    });

    /* SCROLL ANIMATE */
    $('.scrollPage').click(function() {
        var elementClicked = $(this).attr("href");
        var destination = $(elementClicked).offset().top;
        $("html:not(:animated),body:not(:animated)").animate({
            scrollTop: destination-20
            }, 500 );
        return false;
    });
	
	
	// Adiciona e Deleta itens da lista de favoritos
	$(".btn-add-fav").click( function() {  setFavoritos('add',$("#ref").val()); } );
	$(".btn-del-fav").click( function() {  setFavoritos('del',$("#ref").val()); } );
	
	$('ul.abas_cad li span a').click( function() {
			var id_li = $(this).parent().parent().attr('id');
			var id_aba = id_li.substr(1);
			$('ul.abas_cad li').removeClass('ativo');
			$(this).parent().parent().addClass('ativo');
			$('.abas').hide();
			$("#"+id_aba).show();
	
	});
	
	
	// comparar na busca
	/*$(".comparar_d a").click( function() {
		$(".check-comp input[type='checkbox']:checked ").each(
			function() {
				setFavoritos('add',$(this).val());
			}
		)
	});*/
	


})


function setFavoritos(acao,cod)
{
	if(acao=='add' || acao=='del')
	{
        $.ajax({
            type: "POST",
            url: base_url+"index.php?on=appImovel_ajax&in=setFavoritos",
            data: 'acao='+acao+"&cod="+cod,
            success: function(msg){
				if(acao=='add')
					$('#retorno_erro2').html('Item Adicionado com sucesso!');
				else if(acao=='del')
					$('#retorno_erro2').html('Item Removido com sucesso!');					
		        window.clearTimeout(timeoutID2);
		        timeoutID2 = window.setTimeout(hideError2, 4000, true);				
            }
        });		
	}
				
}

// FUNCAO USADA NOS FORMULARIOS DA GUARIDA - MANTIDA A PEDIDO DELES.
function autotab(current,to){
    if (current.getAttribute && 
      current.value.length==current.getAttribute("maxlength")) {
        to.focus() 
        }
}

function validaAbaGo(idAba,nome_cad)
{
	var i = 1;
	var msg = '';
	
    disabledFormButton(".btn-cad");
	
	for(i=1; i<idAba; i++)
	{
		msg = validaAba(i,nome_cad);
		if(msg.length>0)
		{
			aba_errada =  i;		
			break;
		}
	}	msg = validaAba(1,nome_cad);

		
    if(msg != "") {
        msg = "<span><b>Os seguintes campos encontram-se com problemas:</b></span><br />" + msg + "<br />";
        $('#retorno_erro').html(msg);
		$('ul.abas_cad li').removeClass('ativo');
		$('#haba'+aba_errada).addClass('ativo');
		$('.abas').hide();
		$("#aba"+aba_errada).show();	
		gotoAnchor('topFromSave');
        enabledFormButton(".btn-cad");
	
        window.clearTimeout(timeoutID);
        timeoutID = window.setTimeout(hideError, 4000, true);

    } else {
		$('ul.abas_cad li').removeClass('ativo');
		$('#haba'+idAba).addClass('ativo');
		$('.abas').hide();
		$("#aba"+idAba).show();	
		gotoAnchor('abasCad');
        enabledFormButton(".btn-cad");
			
    }
	
    return false;


}

function validaTudo(nabas,nome_cad)
{
	var i = 1;
	var msg = '';
	var aba_errada = 0;
	
    disabledFormButton(".btn-cad");
	
	for(i=1; i<=nabas; i++)
	{
		msg = validaAba(i,nome_cad);
		if(msg.length>0)
		{
			aba_errada =  i;
			break;
		}
	}	
		
    if(msg != "") {
		$('ul.abas_cad li').removeClass('ativo');
		$('#haba'+aba_errada).addClass('ativo');
		$('.abas').hide();
		$("#aba"+aba_errada).show();	
		gotoAnchor('topFromSave');
        msg = "<span><b>Os seguintes campos encontram-se com problemas:</b></span><br />" + msg + "<br />";
        $('#retorno_erro').html(msg);
		
        enabledFormButton(".btn-cad");
		
        window.clearTimeout(timeoutID);
        timeoutID = window.setTimeout(hideError, 4000, true);
    } else {
		$('ul.abas_cad li').removeClass('ativo');
		$('#haba'+nabas).addClass('ativo');
		$('.abas').hide();
		$("#aba"+nabas).show();	
		gotoAnchor('topFromSave');
			
        // MENSAGEM DE AGUARDO DE ENVIO
        $('#retorno_erro').html('Enviando Formulário ...<br /><br />');
		
        $('#'+nome_cad).submit();
    }
	
    return false;


}






/* verify pass */
function verifyPass() {

    if($("#pass").val() !=  $("#pass_confirm").val()){
        alert("Senhas não conferem!");
    } else {
        $('#save').submit();
    }

}
/* verify pass */

/* send newsletter */
function sendNews() {
    msg = "";

    if($("#n_name").val() == "" || $("#n_name").val() == "Nome"){
        msg += "* Nome não preenchido. \n";
    }

    if($("#n_email").val() == "" || $("#n_email").val() == "Email"){
        msg += "* Email não preenchido. \n";
    } else if(!valEmail.test($("#n_email").val())){
        msg += "* E-mail inválido. \n";
    }

    if(msg != ""){
        alert("Os seguintes campos contém erros:\n\n"+msg);
    } else {
        var separador = '';
        
        $.ajax({
            type: "POST",
            url: base_url+"index.php|on=home&in=saveNews",
            data: "name="+$("#n_name").val()+"&email="+$("#n_email").val(),
            success: function(msg){
                alert('Seu email foi cadastrado com sucesso!');
                $('#n_name').val('Nome');
                $('#n_email').val('Email');
            }
        });
    }
}
/* send newsletter */

/* login */
function login() {
    msg = "";

    if($("#email").val() == ""  || $("#email").val() == "email") 	msg += "* Email não preenchido. \n";
    if($("#pass").val() == "" ) 									msg += "* Senha não preenchida. \n";

    disabledFormButton(".btn-enter");

    if(msg != "") {
        msg = "Os seguintes campos encontram-se com problemas: \n\n" + msg + "";
        alert(msg);

        enabledFormButton(".btn-enter");
    } else {
        // ajax pra login e retorno faz as paradas
        $.ajax({
            type: "POST",
            url: base_url+"index.php?on=login&in=login",
            data: 'email='+$('#email').val()+'&pass='+$('#pass').val() ,
            success: function(msg){
                if(msg == 'ok') {
                    window.location = base_url;
                } else if(msg == 'adm') {
                    window.location = base_url+'area-usuario';
                } else {
                    enabledFormButton(".btn-enter");
                    alert('Erro de email e senha!');
                    $('#pass').val('');
                    $('#pass').blur();
                    $('#email').val('email');
                }
            }
        });
    }

    return false;
}
/* login */

/* forgot pass */
function forgotPass() {
    msg = "";

    if($("#email").val() == "" || $("#email").val() == "email")	msg += "* Email não preenchido";
    else if(!valEmail.test($("#email").val()))					msg += "* Email não válido. \n";

    disabledFormButton(".btn-send");

    if(msg != "") {
        msg = "Os seguintes campos encontram-se com problemas: \n\n" + msg + "";
        alert(msg);

        enabledFormButton(".btn-send");
    } else {
        // ajax pra login e retorno faz as paradas
        $.ajax({
            type: "POST",
            url: base_url+"index.php?on=login&in=sendPass",
            data: 'email='+$('#email').val(),
            success: function(msg){
                if(msg == 'ok') {
                    enabledFormButton(".btn-send");
                    alert('Acesse seu email e logue no sistema.');
                    $('#email').val('email');
                    window.reload();
                } else {
                    enabledFormButton(".btn-send");
                    alert('Este email não é válido. Tente novamente!');
                    $('#email').val('email');
                }
            }
        });
    }

    return false;
}
/* forgot pass */

function str_replace(haystack, needle, replacement) {
    var temp = haystack.split(needle);
    return temp.join(replacement);
}

function disabledFormButton(ct) {
    $(ct).attr('disabled','disabled').css('cursor','default').css('filter','alpha(opacity=40)').css('-moz-opacity','0.4').css('opacity','0.4');
}

function enabledFormButton(ct) {
    $(ct).attr('disabled','').css('cursor','pointer').css('filter','alpha(opacity=100)').css('-moz-opacity','1').css('opacity','1');
}

function hideError() {
    $("#retorno_erro").animate({
        left:'+=50',
        height:'toggle'
    },2000, function() {
        $("#retorno_erro").html('');
        $("#retorno_erro").css('display','block');
    });
    window.clearTimeout(timeoutID);
}
function hideError2() {
    $("#retorno_erro2").animate({
        left:'+=50',
        height:'toggle'
    },2000, function() {
        $("#retorno_erro2").html('');
        $("#retorno_erro2").css('display','block');
    });
    window.clearTimeout(timeoutID); 
}
function hideModal() {
	$("#containerModal .contentModal .btn_close").trigger('click');
    window.clearTimeout(timeoutID);
}

function topo() {
    window.location = document.URL+'#';
}

function gotoAnchor(value) {
    var elementClicked = '#'+value;
    var destination = $(elementClicked).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({
        scrollTop: destination-20
        }, 500 );
}



var valEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
