// JavaScript Document

function ControlaCorretor(control,campo) {
//ControlaCorretor(this.checked,'cod_corretor')	
if(control=='sim') {
	document.getElementById(campo).disabled=false;
} else
if(control=='nao') {
	document.getElementById(campo).disabled=true;
	document.getElementById(campo).value='';
}
}


//funcao para escrever Email para pagina * EVITA SPAM
function spamMail(nome,emailHost){
	
	var name = nome ;
	var emailHost = "jtavares.com.br";
	document.write("<a href=" + "mail" + "to:" + name + "@" + emailHost + ">" + name + "@" + emailHost + "</a>")
	
}



//funcao que controla divs para abrir e fechar
function ControlaDiv(d){
//alert("div:" +d);
if(d.length < 1) { return; }
/*
if(document.getElementById(d).style.display == "none") { 
document.getElementById(d).style.display = "block"; 
} else { 
document.getElementById(d).style.display = "none"; }*/

if(document.getElementById(d).style.visibility == "hidden") { 
document.getElementById(d).style.visibility = "visible"; 
document.getElementById(d).style.position = "static";
document.getElementById(d).style.display = "block";
} else { 
document.getElementById(d).style.visibility = "hidden";
document.getElementById(d).style.position = "inherit";
document.getElementById(d).style.display = "none"; }
}

/*
//FUNÇÃO QUE escreve dentroa de um option de um select pegando array
function writeSelect(id){
	var x=0;
	var a=0; var b=0;
	var valor='';
	var valorx='';
	vtipos = document.getElementsByName("tipos[]").length;
	campo = document.getElementsByName("tipos[]");
	if(vtipos>0){
	for(i=0;i<vtipos;i++){
		//element.innerHTML=dados[i];
		if(campo[i].checked==true) {
			b++;
		}
	} 
	for(i=0;i<vtipos;i++){
		
		//element.innerHTML=dados[i];
		if(campo[i].checked==true) {
			c=vtipos-b;
			a++;
			x=1;
			valorx = valorx + campo[i].id+'';
			valor = campo[i].id.substr(0,10)+'... ';
		//document.getElementById(id).innerHTML=campo[i].id.substr(0,10)+'... ';
		//document.getElementById(id).innerHTML=valor;
			//document.getElementById(id).text = valor;
			//newOption.value = 'Selecione';
			var newOption = document.createElement('option');
			document.getElementById('tiposelecta').options.add(newOption);
			newOption.text = valor;
			newOption.value = 'x';
			newOption.selected=true;
			
		document.getElementById('tipos_sel').value='<b>Selecionados:</b> '+valorx;
			if(a<b) {
			valorx=valorx  + ', ';
			}
		}

	} 
	}
	
	if(x==0) { 
	document.getElementById(id).innerHTML='Selecione';
	document.getElementById('tipos_sel').value='Nenhum tipo selecionado';
	}
	//alert("tipos: "+ valorx);
}
*/


//Cookies para selecionar imoveis
/*
function GerarCookie(strCookie, strValor, lngDias)
{
	//alert(strValor);
    var dtmData = new Date();
	//verifica se o valor esta vazio e acrescenta mais um valor
	valor = "";
	if(LerCookie('imoveis')==null || LerCookie('imoveis')==""){
		valor = strValor;	
	}else
	{
		valor = LerCookie('imoveis')+";"+strValor;
		//alert(strValor);
	}
	//alert(valor);
	
	
    if(lngDias)
    {
        dtmData.setTime(dtmData.getTime() + (lngDias * 24 * 60 * 60 * 1000));
        var strExpires = "; expires=" + dtmData.toGMTString();
    }
    else
    {
        var strExpires = "";
    }
	ExcluirCookie('imoveis');
    document.cookie = strCookie + "=" + valor + strExpires + ";";
	//alert("tempo: "+strExpires);
	alert("cookie a gravar: "+document.cookie);
	alert(CarregaCookie('imoveis'));
	
}

function CarregaCookie(strCookie)
{
    var strNomeIgual = strCookie + "=";
    var arrCookies = document.cookie.split(';');

    for(var i = 0; i < arrCookies.length; i++){
		alert(arrCookies[i]);
	}
}

// Função para ler o cookie.
function LerCookie(strCookie)
{
    var strNomeIgual = strCookie + "=";
    var arrCookies = document.cookie.split(';');

    for(var i = 0; i < arrCookies.length; i++)
    {
        var strValorCookie = arrCookies[i];
        while(strValorCookie.charAt(0) == ' ')
        {
            strValorCookie = strValorCookie.substring(1, strValorCookie.length);
        }
        if(strValorCookie.indexOf(strNomeIgual) == 0)
        {
            return strValorCookie.substring(strNomeIgual.length, strValorCookie.length);
        }
    }
    return null;
}

// Função para excluir o cookie desejado
function ExcluirCookie(strCookie)
{
    //GerarCookie(strCookie, '', -1);
	//dtmData.setTime(dtmData.getTime() + (lngDias * 24 * 60 * 60 * 1000));
        var strExpires = "; expires=-1";
	 document.cookie = strCookie + "=" + strExpires + "; path=/";
}

function WritePageCookie(ck,div){
	
	var cookies = array();
	cookies = ck.split(';');
	alert(cookies[0]);
	
}
*/


var janelapop = null;
var janelapop_sub = null;
var janelapop_sub2 = null;

function abrejanela(entrada,largura,altura)
{

   if ( (janelapop != null) && (!janelapop.closed) )
   {
      janelapop.focus();
      janelapop.href = (entrada);
   }

   if(largura=='' || altura=='') {
   largura='890';
   altura='610';
   }
var res_ver = screen.height;
var res_hor = screen.width;
var pos_ver_x = (res_ver - altura)/2;
var pos_hor_x = (res_hor - largura)/2;
/*
  var largura = 0;
  var altura = 0;
  var esquerda = ((screen.width - largura) / 2);
  var topo = ((screen.height - altura) / 2);  
  Popup = window.open('', 'Janela', 'width = ' + largura + ', height = ' + altura + ', top = ' + topo + ', left = ' + esquerda + ', scrollbars = no, status = no, toolbar = no, location = no, directories = no, menubar = no, resizable = no, fullscreen = no');
*/  
   janelapop =window.open(entrada,'popup','resizable=no,toolbar=no,status=yes,menubar=no,scrollbars=yes,width='+largura+',height='+altura+',top='+pos_ver_x+',left='+pos_hor_x);
janelapop.focus();
}






function ShowHints(id,msg){
var span = document.getElementById('erro_'+id);
 		//show hints
		//document.getElementById('erro_'+id).lastChild.style.display='inline';
		
		message = unescape(msg);
		span.style.display='inline';
		span.innerHTML=message;
		
}

function HideHints(id){
var span = document.getElementById("erro_"+id);
// the span exists!  on focus, show the hint
				span.style.display = "none";
	}

	
//addLoadEvent(prepareInputsForHints);


function validaNome(vl,id){
	if(vl==""){
	
		ShowHints(id,escape('Favor preencha este campo'));
		document.getElementById(id).focus();
	}else{
		HideHints(id);
	}
}



function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function formataMoeda(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function telefone2(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1)$2") //Coloca parênteses em volta dos dois primeiros dígitos
//    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function databr(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1)$2") //Coloca parênteses em volta dos dois primeiros dígitos
//    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function hora(v){
//alert("Teste!");
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1:$2") //Esse é tão fácil que não merece explicações
    return v
}



function validaEmail(id)
{
  var obj = document.getElementById(id);
  var txt = obj.value;
  if (((txt.indexOf("@") < 1) || (txt.indexOf('.') < 7)))
  {
    ShowHints(id,escape('E-mail inválido'))
	obj.focus();
  }else{
  HideHints(id);
  }
}


function Email_Valido(Campo){
  var Valor = Campo.value;
  var erro=0;
  if (Campo.value=="")
    return true;
  else
  var acentos = new Array("à","â","ê","ô","û","ã","õ","á","é","í","ó","ú","ç","ü","À","Â","Ê","Ô","Û","Ã","Õ","Á","É","Í","Ó","Ú","Ç","Ü"," ","/","\\","#","*","[","]","{","}",">","<",":",";","?","!","(",")","$","%","=","|","@@","..",",","´","`","'","\"","+",".@","@.","@-","@_");
//  var acentos = new Array("à","â","á");
  var erro="";
  var pos=Valor.length-1;
for(var i=0;i<acentos.length;i++){
//if(Valor.indexOf(acentos[i]) >= 0) {
if((Valor.indexOf(acentos[i]) >= 0) || (Valor.indexOf(".",pos) == pos) || (Valor.indexOf(".") == 0)) {
erro++;
} 
}
	if(erro) {
	//alert("Tamanho campo: "+pos +Valor.length+Valor.indexOf(".",pos));
	alert("Este e-mail não está correto, não digite acentuação, acentos ou símbolos especiais (só é permitido os simbolos '@' e '.' (arroba e ponto!)!");
    Campo.focus();
    return false; 
	}


  if ( (Valor.indexOf("@") == -1) || (Valor.indexOf(".") == -1) || (Valor.length < 5) )
  {  alert("Este e-mail não é válido.  Por favor, digite novamente.");
     Campo.focus();
	 //alert("CAmpo: "+Campo);
     return false;  
  }
    else
  if ( (Valor.indexOf("@@") !== -1) || (Valor.indexOf("..") !== -1) || (Valor.indexOf(",") !== -1) )
  {  alert("Este e-mail não está correto!");
     Campo.focus();
	 //alert("CAmpo: "+Campo);
     return false;  
  }
    else
  if (Valor.indexOf("www@") !== -1)
  {  alert("Este e-mail não está correto!");
     Campo.focus();
	 //alert("CAmpo: "+Campo);
     return false;  
  }
  //else
  
     return true;
}




//function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
function txtBoxFormat(objForm, strField, sMask, e) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

		if(window.event) { // Internet Explorer
         var whichCode = e.keyCode; 
		 nTecla = whichCode;
		 }
        else if(e.which) { // Nestcape / firefox
         var whichCode = e.which;
		 nTecla = whichCode;
        } 


    sValue = objForm[strField].value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objForm[strField].value = sCod;

    //if (nTecla != 8) { // backspace
	if (nTecla != 8 ) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58) || (nTecla ==8)); } // números de 0 a 9
      else { // qualquer caracter...
        return true;
      } }
    else {
      return true;
    }
}


//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//Retorno: Booleano
//Autor: Gabriel Fróes - www.codigofonte.com.br
//-----------------------------------------------------
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;

    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    //var whichCode = (window.Event) ? e.which : e.keyCode;
	
if(window.event) { // Internet Explorer
         var whichCode = e.keyCode; }
        else if(e.which) { // Nestcape / firefox
         var whichCode = e.which;
        } 
	//	         var whichCode = e.which;
		
	
    //if (whichCode == 13) return true;
	if (whichCode == 13) return true;
	if(e.keyCode == 9 || e.which == 9 ) return true;
//	if(whichCode == 9 || whichCode == 9 ) return true;
	
	if (whichCode == 8) {
	objTextBox.value='';
	return true;
	}
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '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++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
 
function isNum( caractere ) 
{ 
         var strValidos = "0123456789" ;
         if ( strValidos.indexOf( caractere ) == -1 ) 
                 return false; 
         return true; 
} 


function trocarTodos(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}


function ControlaDiv2(campo,d) {
if(campo.checked==true || campo.value=="S" || campo.value=="sim") {
document.getElementById(d).style.display = "block"; 
} else {
document.getElementById(d).style.display = "none"; 
}
}



// verifica o cadastro do cliente (site e área do cliente)
function VerificaFormCadastroCliente() {
val=document.form;

if(val.nome_cliente.value=="0" || val.nome_cliente.value=="") {
alert("Por favor, informe seu nome!");
val.nome_cliente.focus();
return false;
}
else
if(val.email_cli.value=="") {
alert("Por favor, informe seu e-mail!");
val.email_cli.focus();
return false;
}
else
if(val.senha_cli.value=="") {
alert("Por favor, informe sua senha!");
val.senha_cli.focus();
return false;
}
else
if(val.senha_cli_conf.value=="") {
alert("Por favor, confirme sua senha!");
val.senha_cli_conf.focus();
return false;
}
else
if(val.senha_cli.value!==val.senha_cli_conf.value) {
alert("Atenção! A confirmação da senha não confere com a senha digitada!");
val.senha_cli_conf.focus();
return false;
}

  if (val.email_cli.value !=="") {
     if(!Email_Valido(val.email_cli)) {
	 	val.email_cli.focus();
         return false;
     } 
   }

if(val.busca_venda.checked==false && val.busca_aluguel.checked==false) {
alert("Por favor, informe se você procura imóveis para comprar e/ou para alugar!");
val.busca_venda.focus();
return false;
}

// caso passe dos requisitos acima, processa o formulário
document.form.submit();
//this.form.submit();
}






/*
 //funcao para mostrar e ocultar div de logar
$(document).ready(function() {
           $("a#btn_login_fechar").click(
                   function() {
                           $("div#loginbox").slideUp(); // ou slideDown()
                   }
           );
 });
*/

//funcao para add a favoritos 
function addFav(){
    var url      = "http://www.jtavares.com.br";
    var title    = "JTavares Consultoria Imobiliária";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

function checaTodos(campo){
for (i = 0; i < campo.length; i++)
	//campo[i].checked = true ;
	if(campo[i].checked == true) {
		campo[i].checked = false 
		} else {
		campo[i].checked = true
		}
}

function toogleDivs(at,div2){
if(document.getElementById(at).className=='esconde_div') {
//document.getElementById(at).style.display = "block";
//document.getElementById(div2).style.display = "none";
document.getElementById(at).className = "mostra_div";
document.getElementById(div2).className = "esconde_div";
} 

if(document.getElementById(at).style.display=='none') {
document.getElementById(at+"_aba").className = "esconde_aba";
document.getElementById(div2+"_aba").className = "mostra_aba";
} else {
document.getElementById(at+"_aba").className = "mostra_aba";
document.getElementById(div2+"_aba").className = "esconde_aba";
}
}



// trabalha com cookies:
function criaCookie(name,value,days) {
//alert("Valor do cookie a criar/gravar: "+value);
if(value!='') {

	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	// pega os valores atuais do cookie
	valcookies = CarregaCookie(name);
	val = ConcatenaCookie(name,value);
	//alert("valores atuais do cookie: " +valcookies+" - Veio da concat: "+val);
	if(valcookies!==null && valcookies!==undefined) {
	val = ConcatenaCookie(name,value);
	//alert("concatena cookie!!!");
	} else {
	//alert("pega valor passado!!!");
	val = value;
	}
	//alert("Valor do cookie: "+val);
	value = val;
	//alert("Valor a escrever no cookie: "+value);
	document.cookie = name+"="+value+expires+"; path=/";
} else {
//alert("nenhum valor a gravar em cookie");
}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function CarregaCookie(nome){
var x = readCookie(nome);
if (x) {
//alert(x);
return x;
}
}

function ConcatenaCookie(nome,valor){
var x = readCookie(nome);
if (x) {
var valores=x.split("|");
tam = valores.length;
var val='';
if (x.indexOf(valor)==-1){
//alert("nao achou valor, entao adiciona");
val=x+"|"+valor;
} else {
val=x;
}

} else {
val=valor;
//alert("valor para concatenação: "+valor);
}
val = val;
return val;
}

function mostraCookie(nome){
var x = readCookie(nome);
if (x) {
//alert(x);
}
}

// verifica se o valor do checkbox está no cookie (imovel selecionado no cookie)
// para selecionar o checkbox 
function VerificaCookie(nome,valor,idcheck){
var x = readCookie(nome);
if (x) {
if (x.indexOf(valor)!==-1){
document.getElementById(idcheck).checked=true;
} else {
document.getElementById(idcheck).checked=false;
}
}
}

// na listagem de imoveis apos a pesquisa ou listagem provinda da area do cliente
// verificar se os imoveis listados já estão no cookie para então marcar o checkbox
function VerificaItens() {
	var nome='imoveis'; // nome do cookie
	var vselecao=document.getElementsByName('selecao_imovel');
	//alert(vselecao.length);
	for(var i=0;i < vselecao.length;i++) {
	campovs=vselecao[i];
	idcampox=campovs.id;
	var x = readCookie(nome);
	if (x) {
		if (x.indexOf(campovs.value)!==-1){
		document.getElementById(idcampox).checked=true;
		} else {
		document.getElementById(idcampox).checked=false;
		}
	}
	}
}


function EscreveRemoveCookie(nome,valor,idcheck){

//alert(nome+" "+valor+" "+idcheck);

var x = readCookie(nome);
//alert("x = "+x);

if (x) {
//var valores= new Array(x);
var valores=x.split("|");
valores=x;
tam = valores.length;
//alert("valores: "+valores);
var val='';


if (document.getElementById(idcheck).checked==true || idcheck=="selec"){
	//alert("está marcado!");
	if(valores.indexOf(valor)==-1) {
	//alert("nao achou então adiciona para criar o cookie!");
	valx=valores+"|"+valor;
	document.getElementById(idcheck).checked=true;
	if(idcheck=='selec') alert('Imóvel adicionado à lista de seleção!');
	} else 
	if(idcheck=='selec') alert('Imóvel já está na lista de seleção!');
	
} else {
if (document.getElementById(idcheck).checked==false){
	//alert("nao está marcado! valores:"+valores+" valor:"+valor); 
	valx=removeItem(valores, valor);
		posV=valx.lastIndexOf("|");
		//alert("posição de | "+posV);
		if(posV>0) {
		valx=valx.slice(0,posV);
		//alert(posV+valx);
		}
	}
}

} else {

valx=valor;
//alert("valores do cookie: "+valx);
}
valx = valx;
//alert("Valor final do cookie: "+valx);
//return valx;
//if(valx!='') {
createCookie('imoveis',valx,360);
//}
}


//remove item (string or number) from an array
function removeItem(originalArray, itemToRemove) {
	var j = 0;
	var posV = 0;
	var fimArray="";
	//alert("Array original: "+originalArray);
	originalArray=originalArray.split("|");
	while (j < originalArray.length) {
		if (originalArray[j] == itemToRemove) {
			originalArray.splice(j, 1);
			//alert("Original tornou-se: "+originalArray);
		} else { 
		fimArray=fimArray+originalArray[j]+"|";
		j++; 
		}

	}
	//alert("Final, após remoção: "+fimArray);
return fimArray;
}


function validaLogin(){
	if(document.FormLogin.email_login.value==""){
		alert('Favor informe seu e-mail!');
		document.FormLogin.email_login.focus();
		return false;
	}
	
	if(document.FormLogin.senha.value==""){
		alert('Favor infomrme sua senha!');
		document.FormLogin.senha.focus();
		return false;
	}
	
	 if (document.FormLogin.email_login.value !=="") {
     if(!Email_Valido(document.FormLogin.email_login)) {
	 	document.FormLogin.email_login.focus();
         return false;
     } 
   }
   
	return true;
}







//funcao para add a favoritos 
function addFav(){
    var url      = "http://www.jtavares.com.br";
    var title    = "JTavares Consultoria Imobiliária";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

function checaTodos(campo){
for (i = 0; i < campo.length; i++)
	//campo[i].checked = true ;
	if(campo[i].checked == true) {
		campo[i].checked = false 
		} else {
		campo[i].checked = true
		}
}

function toogleDivs(at,div2){
if(document.getElementById(at).className=='esconde_div') {
//document.getElementById(at).style.display = "block";
//document.getElementById(div2).style.display = "none";
document.getElementById(at).className = "mostra_div";
document.getElementById(div2).className = "esconde_div";
} 

if(document.getElementById(at).style.display=='none') {
document.getElementById(at+"_aba").className = "esconde_aba";
document.getElementById(div2+"_aba").className = "mostra_aba";
} else {
document.getElementById(at+"_aba").className = "mostra_aba";
document.getElementById(div2+"_aba").className = "esconde_aba";
}
}





function validaLogin(){
	if(document.FormLogin.email_login.value==""){
		alert('Favor informe seu e-mail!');
		document.FormLogin.email_login.focus();
		return false;
	}
	
	if(document.FormLogin.senha.value==""){
		alert('Favor infomrme sua senha!');
		document.FormLogin.senha.focus();
		return false;
	}
	
	 if (document.FormLogin.email_login.value !=="") {
     if(!Email_Valido(document.FormLogin.email_login)) {
	 	document.FormLogin.email_login.focus();
         return false;
     } 
   }
   
	return true;
}



var pagina = null;
function openLogin(page) {
 
	var yes = 1;
	var no = 0;
	var page = "http://www.jtavares.net.br/sistemaweb/login.php";
	var menubar = no;       // Barra de menu
	var scrollbars = yes;    // Scrollbar Horizontal e vertical
	var locationbar = no;   // Caixa de Localizaçao da URL
	var directories = no;   // Diretórios e Links
	var resizable = no;     // Pode ou nao resizar a janela?
	var statusbar = yes;     // Status bar (com 'Document: Done')
	var toolbar = no;       // Back, Forward, Home, Stop toolbar
	var titlebar = no;      // título
	//pagina = page;
   if ( (pagina != null) && (!pagina.closed) )
   {
      pagina.focus();
      pagina.href = (page);
   }
   	
   
	//windowprops = "width=" + (screen.width-10) + ",height=" + (screen.height-75) + ",top=0,left=0";
	//windowprops = "width=524px,height=500px,top=150,left=150";
	//windowprops += (menubar ? ",menubars" : "") +
	windowprops = "width=" + (screen.width-5) + ",height=" + (screen.height-75) + ",top=0,left=0";
	windowprops += (menubar ? ",menubars" : "") +
	(scrollbars ? ",scrollbars" : "") +
	(locationbar ? ",location" : "") +
	(directories ? ",directories" : "") +
	(resizable ? ",resizable" : "") +
	(statusbar ? ",status" : "") +
	(titlebar ? ",titlebar" : "") +
	(toolbar ? ",toolbar" : "");
	window.open(page,"JTA", windowprops);
	pagina.focus();
	//self.close(); // Fecha janela principal

}



function limpaDiv(div){
//	alert(div);
	document.getElementById(div).innerHTML='';
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}




//Cria a funçao com os campos para envio via parâmetro
function setarCampos(oper,cod_imovel) {
	
campos = "nome="+encodeURI(document.getElementById('nome').value)+"&email="+encodeURI(document.getElementById('email').value+"&emp="+document.getElementById('emp').value+"&emp_at="+document.getElementById('emp_at').value+"&op="+oper+"&cod_imovel="+cod_imovel);
}

function createGetURL(form_id) {
    var form = $("#" + form_id);
    var inputs = $("input", form);
    
    var tmp = "";
    
    $.each(inputs, function (key, val) {
        tmp += $(val).attr('name') + "=" + encodeURI($(val).val());
        tmp += "&";
    });
    
    var textareas = $("textarea", form);
    
    $.each(textareas, function (key, val) {
        tmp += $(val).attr('name') + "=" + encodeURI($(val).val());
		tmp += "&";
    });
    
    campos = tmp.substr(0, tmp.length-1);
    //alert(campos);
    //return campos;
	//alert(campos);
}
