// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/*
function completaEndereco(cep){

	var url = 'http://cep.republicavirtual.com.br/web_cep.php';
	var pars = 'cep='+cep+'&formato=json';

	new Ajax.Request(url, 
	{
		method:'get', parameters: pars,
		
		onComplete: showResponse,
		onException: function(error) {
			alert('O CEP informado não existe na base de dados.'+Ajax.Request.prototype.readyState)
			$("property_address").focus();
		},
	});

}*/

function showResponse(originalRequest)
	{
		var response = originalRequest.responseText.evalJSON();
		$("property_address") = response.tipo_logradouro + " " + response.logradouro;
		$("property_neighborhood") = response.bairro;
		$("property_city") = response.cidade;
		$("property_state") = response.uf;
	}

//Completa a data com as barras "/"
function ajustarData(input, evento){
	if(!soNumero(evento)){
		return false;
	} else { 
		if ((input.value.length == 2)||(input.value.length == 5)) {
		   input.value = input.value + "/" ;
		   }
	}
	return true;
}


//Formata CPF / CNPJ
function ajustarCpf(input, evento){
	var ie = (typeof window.ActiveXObject != 'undefined');  

	if (ie)
		tecla = evento.keyCode;
	else
		tecla = evento.which; 

	//alert(tecla);
	if(!soNumero(evento)){
		return false;
	}else{
		if((tecla<48)||(tecla>57)){
			evento.returnValue =false;
			return false;
		}else{
			if ((input.value.length == 3)||(input.value.length == 7)) {
				input.value = input.value + "." ;
			}
			if (input.value.length == 11) {
				input.value = input.value + "-" ;
			}
			if(input.value.length == 15){
				input.value = input.value.replace('.','');
				input.value = input.value.replace('.','');
				input.value = input.value.replace('-','');
				input.value = input.value.substr(0, 2) + '.' + input.value.substr(2, 3) + '.' + input.value.substr(5, 3) + '/' + input.value.substr(8, 4);
				input.value = input.value + "-" ;
			}
		}
	}
	return true;
}



function soNumero(evento){
	var BACKSPACE=  8; 
	var TAB= 9;
	var DEL=  46; 
	var FRENTE=  39; 
	var TRAS=  37; 
	var tecla;
	var ie = (typeof window.ActiveXObject != 'undefined'); 
	if (ie)
		tecla = evento.keyCode;
	else
		tecla = evento.which;
		
	//var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
	
	if (( tecla == BACKSPACE )||(tecla == DEL)||(tecla == FRENTE)||(tecla == TRAS)||(tecla == TAB)){
		 return true; 
	}
	if ( tecla == 13 )     return false; 

	if ((tecla >= 48 && tecla <= 57) || (tecla == 44)) {
		return true;
	}else{
		evento.returnValue = false; 
		return false;
	}
}

//ajustar Telefone
function ajustarFone(input, evento){
	var tecla = evento.keyCode;
	valor = input.value;
	valor = valor.replace( "(", "" );
	valor = valor.replace( ")", "" );
	valor = valor.replace( " ", "" );
	valor = valor.replace( "-", "" );
	tamanhoMaximo = 10;
	tamanho = valor.length;
	if(!soNumero(evento)){
		return false;
	} else { 
		if (tamanho < tamanhoMaximo && tecla != 8) {
		tamanho = valor.length + 1 ;
		}
		if (tecla == 8 ) {
			tamanho = tamanho - 1 ;
		}
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
			if ( tamanho <= 4 ) { 
				input.value = valor ;
			}
			if ( (tamanho > 4) && (tamanho <= 8) ) {
				input.value = valor.substr(0,tamanho-4) + '-' + valor.substr( tamanho - 4, tamanho ) ;
			}
			if ( (tamanho >= 9) && (tamanho <= 10) ) {
				input.value = '(' + valor.substr(0,2) + ') ' + valor.substr(2,tamanho-6) + '-' + valor.substr(tamanho-4,tamanho) ;			
			}
		}
	}
	return true;
}

//Formata CEP
function ajustarCep(input, evento){
	if(!soNumero(evento)){
		return false;
	} else { 
		if (input.value.length == 5) {
		   input.value = input.value + "-";
		}
	}
	return true;
}

function procuraMapa(id){
	if(id != 'E'){
		texto  = '<label for=\"geocodeInput\">Cep:&nbsp;&nbsp;</label>';
		texto += '<div class="inputs_new" style="width:500px;text-align: left">';
		texto += '<input type=\"text\" name=\"q\" id=\"geocodeInput\" maxlength=\"9\" onkeypress=\"ajustarCep(this,event)\" onblur=\"carregaCampos(1,this.value);\">';
		texto += '<input type=\"hidden\" name=\"latitude\" id=\"latitude\"><input type=\"hidden\" name=\"longitude\" id=\"longitude\">';
		texto += '<input type=\"hidden\" name=\"output\" value=\"html\"><input type=\"submit\" value=\"Encontrar local\"></div>';
		var content = document.getElementById("property_zip_code").value;
	}else{	
		texto  = '<label for=\"geocodeInput\">Endereço:&nbsp;&nbsp;</label>';
		texto += '<div class="inputs_new" style="width:500px;text-align: left">';
		texto += '<input type=\"text\" name=\"q\" id=\"geocodeInput\" onblur=\"carregaCampos(2,this.value);\">';
		texto += '<input type=\"hidden\" name=\"latitude\" id=\"latitude\"><input type=\"hidden\" name=\"longitude\" id=\"longitude\">';
		texto += '<input type=\"hidden\" name=\"output\" value=\"html\"><input type=\"submit\" value=\"Encontrar local\"></div>';
		var content = document.getElementById("property_address").value;
		content = content + "," + document.getElementById("property_city").value;
	}
	document.getElementById('tipo_procura_cep').innerHTML = texto;
	document.getElementById('tipo_procura_cep').style.display = "";
	document.getElementById("geocodeInput").value = content;
}

function carregaCampos(id,campo){
	var page =  document.getElementById("type_page").value;
	if (page == "new"){
		document.getElementById("property_zip_code").value = "";
		document.getElementById("property_address").value = "";  
		document.getElementById("property_neighborhood").value = "";  
		document.getElementById("property_city").value = "";  
		document.getElementById("property_state").value = ""; 
	}
	if (id != 2){
		document.getElementById("property_zip_code").value = campo;
		/*Busca por CEP*/
		if(campo != ""){  
			if (page == "new"){
				$J.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+campo, function(){  
					if(resultadoCEP["resultado"]){  
							// troca o valor dos elementos  
							$J("#property_address").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"]));  
							$J("#property_neighborhood").val(unescape(resultadoCEP["bairro"]));  
							$J("#property_city").val(unescape(resultadoCEP["cidade"]));  
							$J("#property_state").val(unescape(resultadoCEP["uf"]));  
					}else{  
							alert("Endereço não encontrado");  
					}  
				}); 
			}	 
	   } 
	}else{
		document.getElementById("property_address").value = campo;
	}
}

function buscaCep(campo,tabela){	
	if(campo != ""){ 
		if (campo.length == 9){
			document.getElementById("loading").style.display = "";
			$J.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+campo, function(){  
				if(resultadoCEP["resultado"]){  
						// troca o valor dos elementos  
						$J("#"+tabela+"_address").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"]));  
						$J("#"+tabela+"_neighborhood").val(unescape(resultadoCEP["bairro"]));  
						$J("#"+tabela+"_city").val(unescape(resultadoCEP["cidade"]));  
						$J("#"+tabela+"_state").val(unescape(resultadoCEP["uf"]));  
						if (resultadoCEP["tipo_logradouro"] == ""){
							//alert("Endereço não encontrado.");
							//document.getElementById(tabela+"_zip_code").focus();
						}else{
							document.getElementById(tabela+"_number").focus();
							if (document.geocodeForm.tipo_procura[0].checked){
								document.getElementById("geocodeInput").value = campo;
							}else{
								document.getElementById("geocodeInput").value = unescape(resultadoCEP["logradouro"]) +" "+resultadoCEP["cidade"] +" "+resultadoCEP["uf"] ;
							}
						}
						document.getElementById("loading").style.display = "none";
				}
			});
			
			//
		}else{
			alert("CEP inválido!");
			document.getElementById(tabela+"_zip_code").value = "";
		}
	}
	
}

function limpaLatitudes(){
	document.getElementById("latitude").value = 0;
	document.getElementById("longitude").value = 0;
	document.getElementById("property_latitude").value = 0;
	document.getElementById("property_longitude").value = 0;
}


//Função para que o usuario não digite pontos apenas virgula
//, :onFocus=>"javascript:this.value='';", :onKeyPress=>"return(FormataReais(this,'',',',event))"
function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (e.keyCode ? e.keyCode: e.which ? e.which : e.charCode)
	//var whichCode = (window.Event) ? e.which : e.keyCode;
	//alert(whichCode);

	if (whichCode == 13) 
		return true;
	key = String.fromCharCode(whichCode);  // Valor para o c?digo da Chave
	if (strCheck.indexOf(key) == -1) 
		return false;  // Chave inv?lida
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}


function ajusta_numero(campo){
	var num;
	num = campo.value;
	num = num.replace(",",".");
	campo.value = num;
}

function change_image(image){
	//alert(image);
	//$("#change_image").slideToggle("slow").delay(800);
	var div = document.getElementById("change_image");
	var texto;
	texto = '<BANNERAD>';
	texto += '<img src="' + image + '" name="bannerADrotator" style="filter:revealTrans(duration=2,transition=20)" border=0>';
	texto += '<script language="JavaScript">nextAd();</script>';
	texto += '</BANNERAD>';
	//var text = '';
	//text += '<img alt="Imóveis" src="' + image + '" />'; 
	//$("#change_image").slideToggle("slow");
	//$("#change_image").delay(800);
	div.innerHTML = texto;
	
}

function search_properties(){
	//desabilitar demais campso ate atualizar
	
	for(var i=0;i< document.frm_search.elements.length;i++){
		if (document.frm_search.elements[i].type == "checkbox"){
		 if (document.frm_search.elements[i].checked == false)
			document.frm_search.elements[i].disabled = true;
		}
	}
	
	document.frm_search.submit();
	return true;
}


 function limparTodosRegistros(campo,totRegs){
	for(var i = 1; i <= parseInt(totRegs); i++){
		document.getElementById(campo+"_"+i).checked=false;
	}
	document.frm_search.submit();
}


/*FUNCOES DO SITE DO PROPRIETA*/

// Valida endereço de e-mail
function validaEmail(email){
	var resultado = false
	var emailStr = new String(email)
	var index = emailStr.indexOf("@");
	if (index > 0){
		var indice = emailStr.indexOf(".",index);
		if ((indice > index+1) && (emailStr.length > indice+1)){
			resultado = true;
		}
	}
	return resultado;
}

function validateRegistrationStep1(){
	var x = 1;
	var texto = "Por favor Preencha corretamente os campos abaixo:";
	document.getElementById("name").style.border = "";
	document.getElementById("email").style.border = "";
	document.getElementById("password").style.border = "";
	document.getElementById("password_confirm").style.border = "";
	document.getElementById("terms").style.border = "";
	
	with(document.frm_cadastro){
		if (name.value == ""){
			document.getElementById("name").style.border = "solid red 2px";
			x = 0;
		}
		if (email.value == "" || !validaEmail(email.value)){
			document.getElementById("email").style.border = "solid red 2px";
			x = 0;
		}
		if (email_confirm.value != email.value){
			document.getElementById("email_confirm").style.border = "solid red 2px";
			document.getElementById("email").style.border = "solid red 2px";
			x = 0;
			texto = "Os emails não conferem. Por favor verifique e depois confirme.";
		}
		if (password.value == ""){
			document.getElementById("password").style.border = "solid red 2px";
			x = 0;
		}
		if (password_confirm.value == ""){
			document.getElementById("password_confirm").style.border = "solid red 2px";
			x = 0;
		}
		if (password_confirm.value != password.value){
			document.getElementById("password_confirm").style.border = "solid red 2px";
			document.getElementById("password").style.border = "solid red 2px";
			x = 0;
			texto = "As senhas não conferem. Por favor verifique e depois confirme.";
		}
		
		if (x == 0){
			document.getElementById("show_fields").style.display = "";
			document.getElementById("show_fields").innerHTML = texto;
			return false;
		}else{
			if (terms.checked == false){
				texto = "Atenção! É necessario aceitar o termo de condição antes de se cadastrar";
				document.getElementById("terms").style.border = "solid red 2px";
				document.getElementById("show_fields").style.display = "";
				document.getElementById("show_fields").innerHTML = texto;
				return false;
			}else{
				document.getElementById("show_fields_correct").style.display = "";
				document.getElementById("show_fields").style.display = "none";
				submit();
				return true;
			}	
		}
		
	}
}

function check_disponible(){
	var website;
	website = document.getElementById('website').value;
	document.getElementById("verify").value = "0";
	if (website == ""){
		//alert("Digite o Nome do Dominio antes de Verificar a Disponibilidade.");
		document.getElementById("resposta_disponib").innerHTML = "";
	}else{
		document.getElementById("resposta_disponib").innerHTML = "<img src='/images/carregando.gif' border=0> <span style='font-size:10px'>Verificando disponibilidade ...</span>";
		var url = "/proprieta/register/check_diponible/"+ website;
		window.open(url, "ifr_atualiza");
	}
}

function validateRegistrationStep2(){
	document.getElementById("domain_type_1").style.border = "";
	document.getElementById("domain_type_2").style.border = "";
	document.getElementById("domain_type_3").style.border = "";
	document.getElementById("website").style.border = "";
	document.getElementById("domain").style.border = "";
	var x = 1;
	var texto = "Por favor Preencha corretamente os campos abaixo:";
	//verifica a disponibilidade do dominio;
	
	with(document.frm_cadastro){		
		if (btn_step2.value == "VERIFICAR")
			check_disponible();

		if (website.value == ""){
			document.getElementById("website").style.border = "solid red 2px";
			x = 0;
		}
		if ((domain_type[1].checked || domain_type[2].checked) && domain.value == ""){
			document.getElementById("domain").style.border = "solid red 2px";
			x = 0;
		}
		
		//verifica se eh valido
		if (verify.value == "0" && website.value != ""){
			document.getElementById("website").style.border = "solid red 2px";
			texto = texto + " (<i>Selecione um domínio disponível</i>)";
			x = 0;
		}
		
		if (btn_step2.value != "VERIFICAR"){
			if (x == 0){
				document.getElementById("show_fields").style.display = "";
				document.getElementById("show_fields").innerHTML = texto;
				return false;
			}else{
				document.getElementById("show_fields_correct").style.display = "";
				document.getElementById("show_fields").style.display = "none";
				submit();
				return true;
			}
		}
	}
}

function validateRegistrationStep3(){
	var i;
	var x = 0;
	var texto = "Por favor selecione um dos LAYOUTS abaixo:";
	with(document.frm_cadastro){
		for(i=0;i<layout_type_id.length;i++){
			if (layout_type_id[i].checked){
				x = 1;
			}
		}
		if (x == 0){
			document.getElementById("show_fields").style.display = "";
			document.getElementById("show_fields").innerHTML = texto;
			return false;
		}else{
			document.getElementById("show_fields_correct").style.display = "";
			document.getElementById("show_fields").style.display = "none";
			submit();
			return true;
		}
	}	
}


function validateRegistrationStep4(){
	//document.getElementById("show_fields_correct").style.display = "";
	document.frm_add_logo.submit();
	return true;
}


function validateShedule(){
	document.getElementById("name").style.border = "";
	document.getElementById("email").style.border = "";
	var x = 0;
	var texto = "Por favor Preencha corretamente os campos abaixo:";
	with(document.frm_visit){
		if (name.value == ""){
			x = 1;
			document.getElementById("name").style.border = "solid red 1px";
		}
		if (email.value == ""  || !validaEmail(email.value)){
			x = 1;
			document.getElementById("email").style.border = "solid red 1px";
		}
		
		if (x == 1){
			document.getElementById("show_fields").style.display = "";
			document.getElementById("show_fields").innerHTML = texto;
			return false;
		}else{
			document.getElementById("show_fields").style.display = "none";
			submit();
			return true;
		}
			
	}
}


function validaSendMail(){
	document.getElementById("message_name").style.border = "";
	document.getElementById("message_email").style.border = "";
	document.getElementById("message_message").style.border = "";
	var x = 0;
	var texto = "Por favor Preencha corretamente os campos abaixo:";
	with(document.frm_send_contact){
		if (message_name.value == ""){
			x = 1;
			document.getElementById("message_name").style.border = "solid red 1px";
		}
		if (message_email.value == ""  || !validaEmail(message_email.value)){
			x = 1;
			document.getElementById("message_email").style.border = "solid red 1px";
		}
		if (message_message.value == ""){
			x = 1;
			document.getElementById("message_message").style.border = "solid red 1px";
		}
		
		if (x == 1){
			//alert(x);
			document.getElementById("show_fields").style.display = "";
			document.getElementById("show_fields").innerHTML = texto;
			return false;
		}else{
			//alert(x);
			document.getElementById("show_fields").style.display = "none";
			document.getElementById("show_fields_correct").style.display = "";
			submit();
			return true;
		}
	}	
}


function coordenadas(event){
	var x = event.clientX -120;
	var y = event.clientY - 220;
	$J("#help").css("top",80);
	$J("#help").css("left",615);
	document.getElementById("help").style.display = "";
}

function coordenadas_proprieta(event){
	$J("#help").css("top",290);
	$J("#help").css("left",250);
	document.getElementById("help").style.display = "";
}

function coordenadas_title(event){
	$J("#help").css("top",220);
	$J("#help").css("left",400);
	document.getElementById("help").style.display = "";
}

function coordenadas_register(event,id){
	if (id == 1){
		$J("#help_"+id).css("top",210);
		$J("#help_"+id).css("left",250);
	}else if(id == 2){
		$J("#help_"+id).css("top",235);
		$J("#help_"+id).css("left",230);
	}else if(id == 3){
		$J("#help_"+id).css("top",262);
		$J("#help_"+id).css("left",250);
	}else{
		$J("#help_"+id).css("top",290);
		$J("#help_"+id).css("left",240);	
	}
	document.getElementById("help_"+id).style.display = "";
}


function coordenadasWeb(event,page,title){
	var texto = "";
	var top, left;
	//page = home
	//alert(page);
//	if (page == "Página Inicial"){
		if (title == "title"){
			texto = "Digite um texto para aparecer na barra de título do navegador web dos visitantes. Ex: Imobiliária Teste - Certeza de bom negócio!";
			top = -315;
			left = 100;
		}else if(title=="description"){
			texto = "Digite uma descrição para esta página. Esse texto aparecerá nos resultados em sites de busca. Ex: Imobiliária com 10 anos de mercado especializada em imóveis de alto padrão.";
			top = -245;
			left = 100;
		}else{
			texto = "Digite as palavras-chaves com as quais você gostaria que esta página fosse encontrada nos buscadores. Ex: imoveis são paulo financiamento consultoria";
			top = -135;
			left = 100;
		}
//	}else if(page == "Sobre a Empresa" || page == "Serviços"){
//		if (title == "title"){
//			texto = "Digite um texto para aparecer na barra de título do navegador web dos visitantes. Ex: Imobiliária Teste - Certeza de bom negócio!";
//			top = -320;
//			left = 100;
//		}else if(title=="description"){
//			texto = "Digite uma descrição para esta página. Esse texto aparecerá nos resultados em sites de busca. Ex: Imobiliária com 10 anos de mercado especializada em imóveis de alto padrão.";
//			top = -245;
//			left = 100;
//		}else{
//			texto = "Digite as palavras-chaves com as quais você gostaria que esta página fosse encontrada nos buscadores. Ex: imoveis são paulo financiamento consultoria";
//			top = -135;
//			left = 100;
//		}
//	}else if (page == "Contato"){
//		if (title == "title"){
//			texto = "Digite um texto para aparecer na barra de título do navegador web dos visitantes. Ex: Imobiliária Teste - Certeza de bom negócio!";
//			top = 520;
//			left = 100;
//		}else if(title=="description"){
//			texto = "Digite uma descrição para esta página. Esse texto aparecerá nos resultados em sites de busca. Ex: Imobiliária com 10 anos de mercado especializada em imóveis de alto padrão.";
//			top = 570;
//			left = 100;
//		}else{
//			texto = "Digite as palavras-chaves com as quais você gostaria que esta página fosse encontrada nos buscadores. Ex: imoveis são paulo financiamento consultoria";
//			top = 650;
//			left = 100;
//		}
//	}else{
//		if (title == "title"){
//			texto = "Digite um texto para aparecer na barra de título do navegador web dos visitantes. Ex: Imobiliária Teste - Certeza de bom negócio!";
//			top = 200;
//			left = 100;
//		}else if(title=="description"){
//			texto = "Digite uma descrição para esta página. Esse texto aparecerá nos resultados em sites de busca. Ex: Imobiliária com 10 anos de mercado especializada em imóveis de alto padrão.";
//			top = 230;
//			left = 100;
//		}else{
//			texto = "Digite as palavras-chaves com as quais você gostaria que esta página fosse encontrada nos buscadores. Ex: imoveis são paulo financiamento consultoria";
//			top = 350;
//			left = 100;
//		}
//	}
	//page = about
	//page = service
	//page = leasing
	//page = sale
	//page = contact
	//alert(texto); 
	document.getElementById("helSearchText").innerHTML = texto;
	$J("#helpSearch").css("marginTop",top);
	$J("#helpSearch").css("left",left);
	document.getElementById("helpSearch").style.display = "";
}

//apagar imagens
function deleteIMGproperties(img){
	var span;
	span = "img_photo" + img;
	document.getElementById(span).innerHTML = "<br /><img src='/images/carregando.gif'> Excluindo...";
	url = "/admin/properties/delete_img_properties/"+img;
	window.open(url,'ifr_update'); 
}

function deleteIMGlogo(id){
	var span;
	span = "img_logo";
	document.getElementById(span).innerHTML = "<br /><img src='/images/carregando.gif'> Excluindo...";
	url = "/admin/web_contents/delete_img_logo/"+id;
	window.open(url,'ifr_update'); 
}

function deleteIMGservices(id){
	var span;
	span = "img_logo";
	document.getElementById(span).innerHTML = "<br /><img src='/images/carregando.gif'> Excluindo...";
	url = "/admin/web_contents/delete_img_services/"+id;
	window.open(url,'ifr_update'); 
}

function deleteIMGabout(id){
	var span;
	span = "img_logo";
	document.getElementById(span).innerHTML = "<br /><img src='/images/carregando.gif'> Excluindo...";
	url = "/admin/web_contents/delete_img_about/"+id;
	window.open(url,'ifr_update'); 
}

function wait_loading(){
	document.getElementById("uploading").style.display = "";
	document.frm_cadastro.submit();
	return true;
}

function selecionMapa(map){
	if (map == "S"){
		document.getElementById("property_show_map").value = 'S';
		document.getElementById("show_select_map").style.display = "";
	}else{
		document.getElementById("property_show_map").value = 'N';
		document.getElementById("show_select_map").style.display = "none";
	}
}


function validaCpfCnpj(valor){
	if (valor.length <= 14)
		validaCpf(valor);
	else
		validaCnpj(valor);	
}

function validaCpf(cpf){ 
	var i;
	var x = 0;
	cpf = cpf.substr(0,3) + cpf.substr(4,3) + cpf.substr(8,3) + cpf.substr(12,2);
	var c = cpf.substr(0,9); 
	var dv = cpf.substr(9,2); 
	var d1 = 0; 
	for (i = 0; i < 9; i++) { 
		d1 += c.charAt(i)*(10-i); 
	} 

	if (d1 == 0){
		alert("CPF Invalido") ;
		return false; 
		x = 1;
	} 
	d1 = 11 - (d1 % 11); 

	if (d1 > 9) d1 = 0; 

	if (dv.charAt(0) != d1){ 
		alert("CPF Invalido") 
		return false;  
		x = 1;
	}
	d1 *= 2; 
	for (i = 0; i < 9; i++){ 
		d1 += c.charAt(i)*(11-i); 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(1) != d1){ 
		alert("CPF Invalido")
		return false; 
		x = 1;
	} 
	if (x == 0)
		return true; 
} 

						/* CNPJ */
function validaCnpj(cnpj) {
	var n = 0;
	CNPJ = cnpj;
	erro = new String;
	if (CNPJ.length < 18) erro += "Preencha corretamente o numero do CNPJ! \n\n"; 
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "Preencha corretamente o numero do CNPJ! \n\n";
	}
	//substituir os caracteres que n?o s?o n?meros
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x; 
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "CNPJ invalido! \n\n"; 
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]); 
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="CNPJ Invalido!";
		n = 1;
	}
	if (erro.length > 0){
		alert(erro);
		return false;
	}
	if (n == 0)
		return true;
}


function voltar(){
	history.back();
	//history.go(0);
}

function mudaBtn(id){
	if(id == 1 || id == "1"){
		document.getElementById("teste_gratis").innerHTML = '<img src="/images/proprieta/button-test.gif" title="Teste por 30 dias" alt="Teste por 30 dias" border="0" class="faca_teste" />';
	}else{
		document.getElementById("teste_gratis").innerHTML = '<img src="/images/proprieta/button-test2.gif" title="Teste por 30 dias" alt="Teste por 30 dias" border="0" class="faca_teste" />';
	}
}

function validateFAQ(){
	document.getElementById("show_fields").style.display = "none";
	document.getElementById("show_fields_correct").style.display = "none";
	with(document.frm_cadastro){
		if (question.value == ""){
			document.getElementById("show_fields").innerHTML = "Por favor digite sua dúvida antes de enviar.";
			document.getElementById("show_fields").style.display = "";
			question.focus();
			
			window.scroll(0,445); // horizontal and vertical scroll increments
			
			return false;
		}else if(jcap() == false){
			document.getElementById("show_fields").innerHTML = "Por favor digite corretamente a palavra de segurança.";
			document.getElementById("show_fields").style.display = "";
			
			window.scroll(0,445); // horizontal and vertical scroll increments
			
			return false;
		}else{
			document.getElementById("show_fields_correct").style.display = "";
			submit();
			return true;
		}
	}
}



function changeSpecial(id,session){
	if (document.getElementById("special_"+id).checked){
		var url = "/admin/properties/changeSpecial/"+id;
	}else{
		var url = "/admin/properties/changeSpecial/"+id+"?ex=1";
	}
	window.open(url,'ifr_update');
}

function changeNewProperties(type){
	/*VOLATRA AS DEMAIS NA COR ORIGINAL*/
	document.getElementById("btn_1").style.backgroundImage="url(/images/property_type/flat.gif)";
	document.getElementById("btn_2").style.backgroundImage="url(/images/property_type/house.gif)";
	document.getElementById("btn_3").style.backgroundImage="url(/images/property_type/industry.gif)";
	document.getElementById("btn_4").style.backgroundImage="url(/images/property_type/farm.gif)";
	document.getElementById("btn_5").style.backgroundImage="url(/images/property_type/season.gif)";
	document.getElementById("btn_6").style.backgroundImage="url(/images/property_type/lot.gif)";
	
	var name = "btn_"+type;
	//alert("btn"+type);
	
	//document.getElementById(name).className = "botao"+type;
	document.getElementById(name).style.backgroundImage="url(/images/property_type/"+type+"_selected.gif)";
	
	
	if (type == 6){
		document.getElementById("contents_properties").style.display = "none";
	}else{
		document.getElementById("contents_properties").style.display = "";
	}
	url = "/admin/properties/searchPropertyTypes/"+type
	window.open(url,'ifr_update');
	document.getElementById("type_category").value = type;
	document.getElementById("detail_information_properties").style.display = "";
}

function changePriceProperties(dealing){
	document.getElementById("price_leasing").style.display = "none";
	document.getElementById("price_sale").style.display = "none";
	document.getElementById("price_season").style.display = "none";
	if (dealing == "1" || dealing == 1){
		document.getElementById("price_leasing").style.display = "";
	}else if (dealing == "2" || dealing == 2){
		document.getElementById("price_sale").style.display = "";
	}else if (dealing == "3" || dealing == 3){
		document.getElementById("price_season").style.display = "";
	}else if (dealing == "4" || dealing == 4){
		document.getElementById("price_leasing").style.display = "";
		document.getElementById("price_sale").style.display = "";
	}
	
}

function showHideMaps(){
	if (document.getElementById("show_map").checked){
		document.getElementById("property_show_map").value = "S";
		document.getElementById("show_select_map").style.display = "";
	}else{
		document.getElementById("property_show_map").value = "N";
		document.getElementById("show_select_map").style.display = "none";
	}
}

function submeteFrmLocation(){
	document.getElementById("frm_location").submit();
}


/*Validates do New Properties*/

function validateFrmDetailInformation(){
	document.getElementById("loading_form").style.display = "";
	document.getElementById("span_property_dealing_id").style.border = "";
	var error = "0";
	with(document.frm_detail_information){
		if (property_dealing_id.value == ""){
			document.getElementById("span_property_dealing_id").style.border = "solid red 1px";
			error = "1";
		}
		
		if (error == "0"){
			var valor;
			var pos;
			//LOCAÇÃO
			valor = document.getElementById("property_price_leasing").value;
			if (valor != ""){
				pos = valor.indexOf(".");
				while (pos > -1){
					valor = valor.replace(".","");
					pos = valor.indexOf(".");
				}
				valor = valor.replace(",",".");
				document.getElementById("property_price_leasing").value = valor;
			}
			//VENDA
			valor = document.getElementById("property_price_sale").value;
			if (valor != ""){
				pos = valor.indexOf(".");
				while (pos > -1){
					valor = valor.replace(".","");
					pos = valor.indexOf(".");
				}
				valor = valor.replace(",",".");
				document.getElementById("property_price_sale").value = valor;
			}
			//TEMPORADA
			valor = document.getElementById("property_price_season").value;
			if (valor != ""){
				pos = valor.indexOf(".");
				while (pos > -1){
					valor = valor.replace(".","");
					pos = valor.indexOf(".");
				}
				valor = valor.replace(",",".");
				document.getElementById("property_price_season").value = valor;
			}
			//CONDOMINIO
			valor = document.getElementById("property_flat_rate").value;
			if (valor != ""){
				pos = valor.indexOf(".");
				while (pos > -1){
					valor = valor.replace(".","");
					pos = valor.indexOf(".");
				}
				valor = valor.replace(",",".");
				document.getElementById("property_flat_rate").value = valor;
			}
			//IPTU
			valor = document.getElementById("property_iptu").value;
			if (valor != ""){
				pos = valor.indexOf(".");
				while (pos > -1){
					valor = valor.replace(".","");
					pos = valor.indexOf(".");
				}
				valor = valor.replace(",",".");
				document.getElementById("property_iptu").value = valor;
			}

			//Submeter
			submit();
			return true;
		}else{
			document.getElementById("system_error").innerHTML = "Por Favor Preencha todos os campos obrigatórios.";
			document.getElementById("system_messages_error").style.display = "";
			//document.getElementById("system_error").focus();
			document.getElementById("loading_form").style.display = "none";
			return false;
		}
	}
	
}

function validateFrmLocation(){
	document.getElementById("loading_form").style.display = "";
	document.getElementById("span_property_state").style.border = "";
	document.getElementById("span_property_city").style.border = "";
	document.getElementById("span_property_neighborhood").style.border = "";
	var error = "0";
	with(document.frm_location){
		if (property_state.value == ""){
			document.getElementById("span_property_state").style.border = "solid red 1px";
			error = "1";
		}
		if (property_city.value == ""){
			document.getElementById("span_property_city").style.border = "solid red 1px";
			error = "1";
		}
		if (property_neighborhood.value == ""){
			document.getElementById("span_property_neighborhood").style.border = "solid red 1px";
			error = "1";
		}
		
		//alert(error);
		if (error == "0"){
			submit();
			return true;
		}else{
			document.getElementById("system_error").innerHTML = "Por Favor Preencha todos os campos obrigatórios.";
			document.getElementById("system_messages_error").style.display = "";
			//document.getElementById("system_error").focus();
			document.getElementById("loading_form").style.display = "none";
			return false;
		}

	}
}

function validateFrmFeatures(){
	document.getElementById("loading_form").style.display = "";
	with(document.frm_features){
		submit();
		return true;
	}
}

function validatePropertyPhotos(){
	document.getElementById("loading_form").style.display = "";
	with(document.frm_insert_photos){
		submit();
		return true;
	}
}

/*Mascara moeda apos a pessoa tirar o foco do campo tipo moeda*/
function formataMoeda(campo) {
	var aux = "";
	txt = document.getElementById(campo).value;
	
	var pos = txt.indexOf(".");
	while (pos > -1){
		txt = txt.replace(".","");
		pos = txt.indexOf(".");
	}
	var pos = txt.indexOf(",");
	while (pos > -1){
		txt = txt.replace(",","");
		pos = txt.indexOf(",");
	}

	var decVal = txt.substr(txt.length-2,2);
	var intVal = txt.substr(0,txt.length-2);

	for (var i=0;i<intVal.length;i++) {
		if(((intVal.length-i) % 3)==0 && (intVal.length-i)!=intVal.length ) 
			aux += '.';
		aux += intVal.substr(i,1);
	}
	decVal = '00' + decVal;
	decVal = decVal.substring(decVal.length-2);

	while (aux.length>0 && (aux.substr(0,1)==0 || aux.substr(0,1)=='.')) 
		aux = aux.substr(1);

	if (aux.length==0) 
		aux='0';

	aux += ',' + decVal;
	
	document.getElementById(campo).value = aux;
}

/*End*/

function submitMoreInfo(){
	document.getElementById("message_name").style.border = "solid #c5c5c5 1px";
	document.getElementById("message_email").style.border = "solid #c5c5c5 1px";
	with(document.frm_more_info){
		var x = 0;
		if (message_name.value == ""){
			x = 1;
			document.getElementById("message_name").style.border = "solid red 1px";
		}
		if(message_email.value == "" || !validaEmail(message_email.value)){
			x = 1;
			document.getElementById("message_email").style.border = "solid red 1px";
		}
		var texto;
		if (x == 0){
			texto = "Dados enviados com sucesso.";
			document.getElementById("confirm_message").className = "confirm_message";
			document.getElementById("confirm_message").innerHTML = texto;
			submit();
			return true;
		}else{
			texto = "Por favor verifique os dados e tente novamente.";
			document.getElementById("confirm_message").className = "error_message";
			document.getElementById("confirm_message").innerHTML = texto;
			return false;
		}
		
	}
}


/*SUA BUSCA*/
function submitFrmSearch(){
	with(document.frm_search){
		if (keywords.value == "" || keywords.value == "%" || keywords.value == " "){
			document.getElementById("error").style.display = "";
			document.getElementById("keywords").style.border = "solid red 2px";
			return false;
		}else{
			submit();
			return true;
		}
	}
}

function verifySupport(){
	document.getElementById("nome").style.border = "solid #dddddd 2px";
	document.getElementById("email").style.border = "solid #dddddd 2px";
	document.getElementById("pergunta").style.border = "solid #dddddd 2px";
	x = 0;
	with(document.frm_support){
		if (nome.value==""){
			document.getElementById("nome").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (email.value=="" || !validaEmail(email.value)){
			document.getElementById("email").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (pergunta.value==""){
			document.getElementById("pergunta").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (x==0){
			submit();
			return true;
		}else{
			document.getElementById("error").style.display = "";
			return false;
		} 
	}
}


function verifySuggest(){
	document.getElementById("nome").style.border = "solid #dddddd 2px";
	document.getElementById("email").style.border = "solid #dddddd 2px";
	document.getElementById("duvida").style.border = "solid #dddddd 2px";
	x = 0;
	with(document.frm_suggest){
		if (nome.value==""){
			document.getElementById("nome").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (email.value=="" || !validaEmail(email.value)){
			document.getElementById("email").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (duvida.value==""){
			document.getElementById("duvida").style.border = "solid #ff0000 2px";
			x = 1;
		}
		if (x==0){
			submit();
			return true;
		}else{
			document.getElementById("error").style.display = "";
			return false;
		} 
	}
}

function changeLayout(id,modelo,cor){
	document.getElementById('layout_type_id').value = id;
	if (confirm("Tem certeza que deseja escolher o " + modelo + " na cor "+ cor +"?") == true){
		document.getElementById('layout_type_id').value = id;
		document.getElementById('frm_cadastro').submit();
	}
}

function showPages(page){
	if (document.getElementById("page_"+page).checked)
		document.getElementById(page).style.display = "";
	else
		document.getElementById(page).style.display = "none";
	
	document.getElementById("frm_add_pages").submit();
	document.getElementById("page_leasing").disabled = "disabled";
	document.getElementById("page_sale").disabled = "disabled";
	document.getElementById("page_build").disabled = "disabled";
	document.getElementById("page_about").disabled = "disabled";
	document.getElementById("page_service").disabled = "disabled";
}

function verifyFieldsInfo(id){
	if (id == "Agendar uma Visita"){
		document.getElementById("span_data").style.display = "";
		document.getElementById("span_hora").style.display = "";
	}else{
		document.getElementById("span_data").style.display = "none";
		document.getElementById("span_hora").style.display = "none";
	}
}

function submitAdvertise(){
	document.getElementById("message_name").style.border = "solid #c5c5c5 1px";
	document.getElementById("message_email").style.border = "solid #c5c5c5 1px";
	document.getElementById("message_details").style.border = "solid #c5c5c5 1px";
	with(document.frm_advertise){
		var x = 0;
		if (message_name.value == ""){
			x = 1;
			document.getElementById("message_name").style.border = "solid red 1px";
		}
		if(message_email.value == "" || !validaEmail(message_email.value)){
			x = 1;
			document.getElementById("message_email").style.border = "solid red 1px";
		}
		if (message_details.value == ""){
			x = 1;
			document.getElementById("message_details").style.border = "solid red 1px";
		}
		var texto;
		if (x == 0){
			texto = "Dados enviados com sucesso.";
			document.getElementById("confirm_message").className = "confirm_message";
			document.getElementById("confirm_message").innerHTML = texto;
			submit();
			return true;
		}else{
			texto = "Por favor verifique os dados e tente novamente.";
			document.getElementById("confirm_message").className = "error_message";
			document.getElementById("confirm_message").innerHTML = texto;
			return false;
		}

	}
}
