// FICHA - INICIO

function verifica_classificado(){
	var divQtde = document.getElementById("divQtde");
	if (divQtde != null){
		largura = 600;
		altura  = 420;
		url_janela = 'imovel/imoveis.php';
		imoveis_ic = window.open(url_janela,'imoveis_ic','status=yes,scrollbars=yes,width='+largura+',height='+altura+',top='+(screen.availHeight/2-altura/2)+',left='+(screen.availWidth/2-largura/2));
		imoveis_ic.focus();
	}else{
		alert('Nenhuma ficha foi selecionada.');
	}
}

function envia(nomedoform){
	nomedoform.submit()
}

function SetCookie (name, value){
   var argv = SetCookie.arguments;
   var argc = SetCookie.arguments.length;
   var expires = (argc > 2) ? argv[2] : null;
   var path = "/";
   var domain = (argc > 4) ? argv[4] : null;
   var secure = (argc > 5) ? argv[5] : false;
   document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
   }

function SetTheCookie()   {
   if(document.forms[0].elements[0].value.length != 0)        {
      var expdate = new Date ();
      expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365));
      SetCookie('DemoName', document.forms[0].elements[0].value, expdate);
      alert('Cookie has been set to ' + document.forms[0].elements[0].value + '.');
      document.forms[0].elements[0].value = " ";
            return false;
      }    else       {
      alert('You must sign-in first.');
      return false;
      }
   }

function getCookieVal (offset)    {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1)
      endstr = document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
   }

function GetCookie (name)    {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen)       {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg)
         return getCookieVal (j);
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) break; 
      }
   return "";
   }


function adiciona(valor) {
	var janela_pai = false;
	if(opener!=undefined){
		var divImoveisSelecionadosPai = opener.document.getElementById("divImoveisSelecionados");
		var divQtdePai = opener.document.getElementById("divQtde");
		janela_pai = true;
	}
	var divImoveisSelecionados = document.getElementById("divImoveisSelecionados");
	var divQtde = document.getElementById("divQtde");

   if (testar(valor) == 0) { 
      alert("Esta ficha já foi selecionada.");
      return;
   }
   var valorantigo = GetCookie("ImoveisLitoralCatarinense");
   if(divQtde==null)
	   var qtde = 0;
   else
	   var qtde = eval(divQtde.innerHTML);
   

	if (valorantigo != "") {
		var valornovo = valorantigo + "|" + valor;
		divQtde.innerHTML = ( qtde + 1 );
		if(janela_pai) {
			divQtdePai.innerHTML = divQtde.innerHTML;
		}
		SetCookie("ImoveisLitoralCatarinense", valornovo);
	}else {
		divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarVcSelecionou()" class="link">Você selecionou <label style="font-weight:bold;" id="divQtde">'+( qtde + 1 )+'</label> imóveis em suas buscas</a>';
		if(janela_pai) {
			divImoveisSelecionadosPai.innerHTML = '<a href="javascript:;" onClick="aoClicarVcSelecionou()" class="link">Você selecionou <label style="font-weight:bold;" id="divQtde">'+( qtde + 1 )+'</label> imóveis em suas buscas</a>';
		}
		SetCookie("ImoveisLitoralCatarinense", valor);
	}
//	if(document.frame_funcao!=undefined){
//		document.frame_funcao.location = document.form_imovel.campo_funcao.value ;
//	}
	alert("Ficha selecionada com sucesso.");
}

function apagar() {
	janela_pai = false;
	if(opener!=undefined){
		var divImoveisSelecionadosPai = opener.document.getElementById("divImoveisSelecionados");
		janela_pai = true;
	}
	var divImoveisSelecionados = document.getElementById("divImoveisSelecionados");
    SetCookie("ImoveisLitoralCatarinense", "")
	divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarHelpSelecionou()" class="link3">Você ainda não selecionou imóveis em suas buscas, clique para saber mais.</a>';
	if(janela_pai){	
		divImoveisSelecionadosPai.innerHTML = '<a href="javascript:;" onClick="aoClicarHelpSelecionou()" class="link3">Você ainda não selecionou imóveis em suas buscas, clique para saber mais.</a>';
	}
	document.location = document.location;
}

function testar(numero) {
   
   count = 0
   vari = GetCookie("ImoveisLitoralCatarinense")
   var inicio = 0
   for (i=0;i < vari.length;i++ ) { 
       if (vari.substring(i,i+1) == "|") {  
          if (numero == vari.substring(inicio,i)) { return 0 }
          inicio = i+1     
       }
   }
   if (numero == vari.substring(inicio,i)) { return 0 }
   return 1


}
   


function contar() {
   
   ar = new Array
   count = 0
   vari = GetCookie("ImoveisLitoralCatarinense")
   var inicio = 0
   for (i=0;i < vari.length;i++ ) { 
       if (vari.substring(i,i+1) == "|") {  
          ar[count++] = vari.substring(inicio,i)
          inicio = i+1     
       }
   }
   ar[count++] = vari.substring(inicio,i)
   return count


}

function ler() {

    var divImoveisSelecionados = document.getElementById("divImoveisSelecionados");
	var valores = GetCookie("ImoveisLitoralCatarinense")
	if (valores == "") {
		var valores = "";
		divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarHelpSelecionou()" class="link3">Você ainda não selecionou imóveis em suas buscas, clique para saber mais.</a>';
	} else {
		qtde = contar();
		divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarVcSelecionou()" class="link">Você selecionou <label style="font-weight:bold;" id="divQtde">'+qtde+'</label> imóveis em suas buscas</a>';
	}

}

function apaga(numero) {
   janela_pai = false;
   if(opener!=undefined){
	  var divImoveisSelecionadosPai = opener.document.getElementById("divImoveisSelecionados");
	  var divQtdePai = opener.document.getElementById("divQtde");
	  janela_pai = true;
   }
   var divImoveisSelecionados = document.getElementById("divImoveisSelecionados");
   var divQtde = document.getElementById("divQtde");
   
   novaform_imovel = ""
   count = 0
   vari = GetCookie("ImoveisLitoralCatarinense")
   var inicio = 0
   for (i=0;i < vari.length;i++ ) { 
       if (vari.substring(i,i+1) == "|") {  
          if (vari.substring(inicio,i) != numero) { 
                    count++
					if (novaform_imovel == "") {
						novaform_imovel = vari.substring(inicio,i)
					} else {
					    novaform_imovel = novaform_imovel + "|" + vari.substring(inicio,i)
					}               
           }
           inicio = i+1
	    }
	}
   

   if (vari.substring(inicio,i) != numero) {
		count++ 
		if (novaform_imovel == "") {
				novaform_imovel = vari.substring(inicio,i)
		} else {
				novaform_imovel = novaform_imovel + "|" + vari.substring(inicio,i)
		}  
   }

   SetCookie("ImoveisLitoralCatarinense", novaform_imovel)
   if(count>0){
	  if(divQtde){
	  	divQtde.innerHTML = count;
	  }else{
		divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarVcSelecionou()" class="link">Você selecionou <label style="font-weight:bold;" id="divQtde">'+count+'</label> imóveis em suas buscas</a>';
	  }
   }else{
		divImoveisSelecionados.innerHTML = '<a href="javascript:;" onClick="aoClicarHelpSelecionou()" class="link3">Você ainda não selecionou imóveis em suas buscas, clique para saber mais.</a>';
   }
	if(janela_pai){
	   if(count>0){
		  if(divQtdePai){
		  	divQtdePai.innerHTML = count;
		  }else{
			divImoveisSelecionadosPai.innerHTML = '<a href="javascript:;" onClick="aoClicarVcSelecionou()" class="link">Você selecionou <label style="font-weight:bold;" id="divQtde">'+count+'</label> imóveis em suas buscas</a>';
		  }
	   }else{
			divImoveisSelecionadosPai.innerHTML = '<a href="javascript:;" onClick="aoClicarHelpSelecionou()" class="link3">Você ainda não selecionou imóveis em suas buscas, clique para saber mais.</a>';
	   }
	}
  alert('fazia submit');
  // document.form_imovel.submit()
}

// FICHA - FIM



function verificar_cep(cep,verif_cep,formulario){
	largura = 600;
	altura  = 400;
	url_janela = 'busca/cep.php?cep='+cep+''+verif_cep+'&formulario='+formulario;
	msg = window.open(url_janela,'janela_detalhe','scrollbars=yes,width='+largura+',height='+altura+',top='+(screen.availHeight/2-altura/2)+',left='+(screen.availWidth/2-largura/2));
	msg.focus();
}

function valida_cep(form,campo1,campo2){
	formulario = eval('document.'+form);
	cep = formulario[campo1].value;
	verif_cep = formulario[campo2].value;
	if((cep.length<5)||(verif_cep.length<3)){
		return false;
	}
	return true;
}

function SaltaCampo (form,campo,prox,tammax,teclapres){ //onKeyUP="SaltaCampo('form1','textfield6','textfield7','5',event);"
	formulario = eval('document.'+form);
	var tecla = teclapres.keyCode;
	vr = formulario[campo].value;
	if( tecla == 109 || tecla == 188 || tecla == 110 || tecla == 111 || tecla == 223 || tecla == 108 ){
		formulario[campo].value = vr.substr( 0, vr.length - 1 ); }
	else{
	 	vr = vr.replace( "-", "" );
	 	vr = vr.replace( "/", "" );
	 	vr = vr.replace( "/", "" );
	 	vr = vr.replace( ",", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	vr = vr.replace( ".", "" );
	 	tam = vr.length;	


		
	 	if (tecla != 0 && tecla != 9 && tecla != 16 )
			if ( tam == tammax )	
				formulario[prox].focus() ;	}
}

function visualiza_imagem(imageName,imageWidth,imageHeight,alt) {
	posTop = (screen.availHeight/2-imageHeight/2);
	posLeft = (screen.availWidth/2-imageWidth/2);
	
	imagemJanela = window.open("","imagemJanela","width="+imageWidth+",height="+imageHeight+",left="+posLeft+",top="+posTop);
	imagemJanela.document.open();
	imagemJanela.document.write('<html><META HTTP-EQUIV="imagetoolbar" CONTENT="no"><title>'+alt+'</title><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" onBlur="self.close()">');
	imagemJanela.document.write('<img src="'+imageName+'" width="'+imageWidth+'" height="'+imageHeight+'" alt="'+alt+'">');
	imagemJanela.document.write('</body></html>');
	imagemJanela.document.close();
	imagemJanela.focus();
}

function FormataValor(form,campo,tammax,teclapres) { //onKeyPress="FormataValor('form1','textfield5','10',event)" OU onKeyPress="FormataValor(this,'','10',event)"
	if(campo){
		formulario = eval('document.'+form);
		form = formulario[campo];
	}
	var tecla = teclapres.keyCode;
	
	vr = form.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8 && tecla != 46){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		form.value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		form.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		form.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		form.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		form.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		form.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
	}		
	
}

function FormataData(form, Campo, teclapres) {//onKeyDown="FormataData('formulario', 'textfield',event)"
	if(Campo){
		formulario = eval('document.'+form);
		form = formulario[Campo];
	}
	
	var tecla = teclapres.keyCode;
	vr = form.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8  && tecla != 46 ){
		if ( tam > 2 && tam < 5 )
			form.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			form.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); }
}

function selecionar(form) {
	 formulario = eval('document.'+form);
	 for (var i=0; i<formulario.elements.length; i++) {
	 	 if (formulario.elements[i].type=="checkbox") { 
		 	formulario.elements[i].checked=true;
		 }
	 }
} 

function desselecionar(form) {
	 formulario = eval('document.'+form);
	 for (var i=0; i<formulario.elements.length; i++) {
	 	if (formulario.elements[i].type=="checkbox") {
			formulario.elements[i].checked=false;
		}
	 }
} 

function inverter(form) {
	formulario = eval('document.'+form);
	for (var i=0; i<formulario.elements.length; i++) {
		if (formulario.elements[i].type=="checkbox") {
			formulario.elements[i].checked=!formulario.elements[i].checked;
		}
	}
} 


function func_janela(nome,url_destino,largura,altura,resize){
	nome = window.open(url_destino,''+nome+'',((resize)?'resizable=yes,':'')+'scrollbars=yes,status=yes,width='+largura+',height='+altura+',top='+(screen.availHeight/2-altura/2)+',left='+(screen.availWidth/2-largura/2));
	nome.focus();
	
}

function excluir_registro(form,msg,id){
	resposta = confirm(msg);
	if (resposta){
		formulario = eval('document.'+form);
		if(id=='submit'){
			formulario.submit();
		}else{
			if(formulario.action.indexOf("?")>=0)
				document.location = formulario.action+'&excluir='+id;
			else
				document.location = formulario.action+'?excluir='+id;
		}
	}else{
		return false;
	}
}

function excluir_foto_bairro(form,msg,id,foto,slot){
	if (confirm(msg)){
		formulario = eval('document.'+form);
		document.location = formulario.action+'?excluir_foto='+foto+'&id_bairro='+id+'&slot='+slot;
	}else{
		return false;
	}
}
function excluir_foto_cidade(form,msg,id,foto,slot){
	if (confirm(msg)){
		formulario = eval('document.'+form);
		document.location = formulario.action+'?excluir_foto='+foto+'&id_cidade='+id+'&slot='+slot;
	}else{
		return false;
	}
}

function janela_textarea(IDCampo,titulo,pag){
	largura = 450;
	altura  = 300;
	url_janela = pag+'?titulo='+titulo+'&campo='+IDCampo;
	textarea_ic = window.open(url_janela,'textarea_ic','width='+largura+',height='+altura+',top='+(screen.availHeight/2-altura/2)+',left='+(screen.availWidth/2-largura/2));
	textarea_ic.focus();
}

function sincroniza_login(objeto){
	formulario = objeto.form;
	nome = objeto.name;
	id = objeto.value;
	if(nome=='id_cliente'){
		campo = formulario.login;
	}else{
		campo = formulario.id_cliente;
	}
	total = campo.length;
	if (total >= 0){
		for (i=0;i<total;i++){ // Laço q passa por todas as linhas do select
			registro = campo.options[i];
			registro.selected = (registro.value==id)?true:false;
		}
	}
}

function limita(form,campo,limite){//onKeyDown="limita('form1','textfield2', '10')"
	if(campo){
		formulario = eval('document.'+form);
		form = formulario[campo];
	}
	var tamanho = form.value.length;
	var tex = form.value;
	if (tamanho>=[limite]) {
		form.value = tex.substring(0,[limite]);
	}
	return true;
}

function clock_load(tipo){
	if(tipo==1){
		parent.document.all.clock_status.src = "images/clock_on.gif";
	}else{
		parent.document.all.clock_status.src = "images/blank.png";
	}
}

var control = 3;
var titulo_antigo = top.document.title;

function aguarde()
{
	if (control == 1){
		msg="Aguarde, processando...";
		window.status=msg;
		top.document.title=msg+"                                     ";
		control=0;
	}else if (control == 2){
		msg="Concluido";
		window.status=msg;
		top.document.title=msg+"                                                                ";
		setTimeout("top.document.title=titulo_antigo;",2000);
	}else if(control == 0){
		msg="Aguarde,";
		window.status=msg;
		top.document.title=msg+"                                                                 ";
		control=1;
	}
	if (control<2)
		setTimeout("aguarde();",250);
}

function barraProgresso(perc){
	if(perc>0 && control==3){
		control=1;
		aguarde();
	}
	barra = document.getElementById("progresso");
	perc_progresso = document.getElementById("percentual");
	perc_progresso.style.color= "#000000";
	if(perc>=100){
		perc = 100;
		control = 2;
	}
	if(perc>=50)
		perc_progresso.style.color= "#FFFFFF";
	barra.style.width = perc+'%';
	barra.title = perc+'%';
	perc_progresso.innerHTML = perc+'%';
}

function tremer(tempo){
	n=tempo;
	for (i = 10; i > 0; i--) {
		for (j = n; j > 0; j--) {
			window.moveBy(0,i);
			window.moveBy(i,0);
			window.moveBy(0,-i);
			window.moveBy(-i,0);
	    }
	}	
}
function contacaracter(obj,destino){
	campo = document.getElementById(destino);
	campo.innerHTML = obj.value.length;
}

function mostraSWF(arquivo, largura, altura, cor_fundo, wmode, id){
	document.writeln('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="'+ largura + '" height="' + altura + '" id="' + id + '" align="middle">');
	document.writeln('<param name="allowScriptAccess" value="sameDomain" />');
	document.writeln('<param name="movie" value="'+ arquivo +'" />');
	document.writeln('<param name="quality" value="high" />');
	document.writeln('<param name="wmode" value="'+ wmode +'" />');
	document.writeln('<param name="bgcolor" value="'+ cor_fundo + '" />');
	document.writeln('<embed src="'+ arquivo +'" quality="high" bgcolor="' + cor_fundo + '" width="'+ largura + '" height="' + altura + '" name="' + id + '" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="'+ wmode +'" />');
	document.writeln('</object>');
}


function exportaXml(campo){
	if(campo.name=='exportaXMLImoveis'){
		selecionado = false;
		formulario = campo.form;
		i=0;
		while(i<formulario.elements.length){
		 	if (formulario.elements[i].type=="checkbox" && formulario.elements[i].checked){ 
				selecionado = true;
				break;
			}
			i++;
		}
		if(selecionado){
			action_old = formulario.action;
			target_old = formulario.target;
			formulario.action = '../export/tela_geraxml.php';
			formulario.target = 'geraxml';
			func_janela('geraxml','',400,220);
			formulario.submit();
			formulario.action = action_old;
			formulario.target = target_old;
		}else{
			alert('Você deve selecionar pelo menos um imóvel');
		}
	}else if(campo.name=='exportaXMLCliente'){
		formulario = campo.form;
		id_cliente = formulario.id_cliente.value;
		func_janela('geraxml','../export/tela_geraxml.php?id_cliente='+id_cliente,400,220);
	}else{
		alert('Exportação Inválida');
	}
}

function relaodImg(){
	document.getElementById("imgVerif").src = document.getElementById("imgVerif").src+Math.floor(Math.random()*5); ;
}
