// JavaScript Document

function iecompattest(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function CentralizaJanela() {

	var ie5=document.all&&document.getElementById
	var ns6=document.getElementById&&!document.all
	
	windowWidth = ns6? window.innerWidth : iecompattest().clientWidth;
	windowHeight = ns6? window.innerHeight : iecompattest().clientHeight;
	screenWidth = screen.availWidth;
	screenHeight = screen.availHeight;
	
	winY = Math.ceil((screenHeight - windowHeight) / 2);
	winX = Math.ceil((screenWidth - windowWidth) / 2);
	
	window.moveTo(winX,winY);
	
}

/*******************************************************************************************
POPUP (BROWSER)
*******************************************************************************************/

function MM_openBrWindow(theURL,winName,features) { //v2.0
  
  window.open(theURL,winName,features);
  
}

function MM_closeBrWindow() { //v2.0
  
	window.opener = self;
	self.close();
  
}

/*******************************************************************************************
LIMPA O CAMPO TEXTO (\n)
*******************************************************************************************/

function RetiraQuebraLinha(obj) {	
	
	// recebe um espaço no final
	obj.value += " ";
	
	// variáveis do texto
	var textoNovo = "";
	var texto = obj.value.split("\n");
	
	// monta novamente a string
	for (i=0; i<texto.length; i++) {
		
		if (texto[i] != "" && texto != "\n") {
			textoNovo += texto[i].substr(0,texto[i].length-1);	
		}
		
	}
	
	// insere o novo texto
	obj.value = textoNovo;
	
}

/*******************************************************************************************
PULAR CAMPOS
*******************************************************************************************/

function jumpField() {
	
	if(window.event.srcElement.type == 'text') { 
		
		var ele = window.event.srcElement;
		var index = ele.sourceIndex;
		
		if(ele.value.length == ele.getAttribute('maxlength')){
        	document.all.item(index + 1).focus();  
    	}
		
	} 
	
}
   
/*document.onkeyup = jumpField;*/

/**********************************************************************************
MUDA O TAMANHO DA FONTE EM UM DETERMINADO DIV
**********************************************************************************/

function MudaTamanhoFonte(tipo,id) {
  
	// pega o tamanho atual da fonte
	var tamanho_atual = document.getElementById(id).style.fontSize;
	var tamanho_minimo = 11;
	var tamanho_maximo = 20;
	
	// converte para inteiro
	tamanho_atual = tamanho_atual.replace("px","") * 1;	
	
	// verifica o tamanho mínimo a ser respeitado
	if (tamanho_atual == "") {
		tamanho_atual = tamanho_minimo;
	}
	
	// incrementa o tamanho atual
	if (tipo=="mais") {
		tamanho_atual += 1;
	} else {
		tamanho_atual -= 1;
	}
	
	// verifica se o tamanho esta dentro do limite
	if (tamanho_atual < tamanho_minimo) {
		tamanho_atual = tamanho_minimo;
	} else if (tamanho_atual > tamanho_maximo) {
		tamanho_atual = tamanho_maximo;
	}
		
	if (document.getElementById(id)) {
		document.getElementById(id).style.fontSize = tamanho_atual + 'px';
	}
						
}

/**********************************************************************************
LIMPAR TEXTO EDITOR
**********************************************************************************/

function LimpaTextoEditor(id_div,id_hidden) {
	
	if (id_div != "") {		
		document.getElementById(id_div).innerHTML = '<p align="center"><b>Nenhum texto foi inserido.</b><br>clique no ícone acima para inserir um conteúdo</p>';		
	}
	
	if (id_hidden != "") {
		document.getElementById(id_hidden).value = '';
	}
	
}

/*******************************************************************************************
VALIDAÇÃO DE DATA
*******************************************************************************************/

function CheckDate(v) {
	 if (v.length!=10) return false
	 var date=v.split('/')
	 var d=parseInt(date[0],10)
	 var m=parseInt(date[1],10)
	 var y=parseInt(date[2],10)
	 if(!checkDateDay(d))return false
	 else if(!checkDateMonth(m))return false
	 else if(!checkDateYear(y))return false
	 else if( (m==4||m==6||m==9||m==11) && (d==31)) return false
	 else if(m==2 && (d>29 || (d==29&&((y%4)!=0)))) return false
	 return true
}

function checkDateDay(v){if(v>=1&&v<=31)return true}
function checkDateMonth(v){if(v>=1&&v<=12)return true}
function checkDateYear(v){if(v>=1)return true}

/***********************************************************************************/
/* pré formatação de campo telefone */
/***********************************************************************************/

function FormatTelefone(e1) {
   if ( e1.value != '' ) {
      if ( (e1.value.length < 9) && (e1.value.length > 0) ) {
         alert('Número inválido');
         e1.focus();
      } else {
         var ddd = e1.value.substring(0,2);
         var fone = e1.value.substring(2,e1.value.length);
         var indice;
         if (e1.value.length == 9)
            indice = 3;
         else
            indice = 4;
         var fone1 = fone.substring(0, indice);
         var fone2 = fone.substring(indice, fone.length);
         e1.value = '(' + ddd + ') ' + fone1 + '-' + fone2;
      }
   }
}

/***********************************************************************************/
/* pré formatação de campo telefone */
/***********************************************************************************/

function FormataCNPJ(Campo, teclapres){

   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;

   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
}

/***********************************************************************************/
/* Valida um e-mail e testa se ele foi preenchido */
/***********************************************************************************/
function validaEmail(idObj, obrigatorio)
{
 	var email = document.getElementById(idObj);
 	if((obrigatorio == 1) || (obrigatorio == 0 && email.value != ""))
	{
 		if(!email.value.match(/([a-zA-Z0-9._-]+@+[a-zA-Z0-9._-]+\.+[a-zA-Z])/))
		{
 			alert("E-mail inválido");
 			email.focus();
 			return false
 		}
 	}
}


/***********************************************************************************/
/* remove caracteres */
/***********************************************************************************/

function removeCaracs(Campo) {

	wrkCampo = '';
	var type= "";
	var caracter= "", ok= false;

	vr = Campo.value;
	
	for ( i=0; i < vr.length; i++ ) {
		
		caracter = vr.substring(i,i+1);
		
		ok = ( caracter != '.' && caracter != '/' && caracter != '-' && caracter != ' ' && caracter != '%' && caracter != '(' && caracter != ')');

		if ( ok) {
			wrkCampo += caracter;
		}
		
	}
	
	Campo.value = wrkCampo;
	
}

/***********************************************************************************/
// Confere se o CPF dado esta' OK
/***********************************************************************************/

function isCPF(cpf) 
{
	var result = "";
	var OK = false;
	var temp = apenasNumeros(cpf);
	
	if ( apenasNumerosRepetidos(temp)) 
	{
		return false;
	}

	if (temp.length>10)
	{
		var work=temp.substring(0,(temp.length)-2)
		var resto = Resto(work);
		OK = (resto==parseInt(temp.charAt((temp.length)-2)));
		
		if (OK) 
		{
			work=work+resto;
			resto= Resto(work);
			OK = (resto==parseInt(temp.charAt((temp.length)-1)));
		}
	}
	return (OK);
}

/***********************************************************************************/
/* formata Moeda */
/***********************************************************************************/

function currencyFormat(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 = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	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; 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;
}

/**********************************************************************************
MOSTRA RELÓGIO
**********************************************************************************/

function getRelogioServidor() {
	
	var objecto = document.getElementById("DisplayData");
	
	executaAjax(__URL__ + '_loadfiles/geral/relogio_load.php','DisplayData','relogio');
	
}

//setInterval("getRelogioServidor()",1000);

/***********************************************************************************/
/* somente números podem ser digitados */
/***********************************************************************************/

function valNumero(obj,event) {
	
	var str = obj.value;
	var Tecla = event.which;
	
	if(Tecla == null)
		Tecla = event.keyCode;
	
	if (Tecla != 13) {
	
		if ( Tecla < 48 || Tecla > 57 ) {
		
			event.returnValue = false;
			//alert("Neste campo somente números podem ser digitados");
			return false;
		
		}
	
	}
	
	event.returnValue = true;
	return true;
}

/***********************************************************************************/
/* máscara de cpf */
/***********************************************************************************/



/***********************************************************************************/
/* gera um numero randomico */
/***********************************************************************************/

function GetNumeroRandomico(possibilidades) {	
	return Math.round( Math.random() * possibilidades);
}



/**********************************************************************************
PEGA UM OBJETO PELO ID
**********************************************************************************/

function GetObject(id) {	
	return document.getElementById(id);	
}


/**********************************************************************************
PEGA O VALOR DE UM CAMPO TEXT
**********************************************************************************/

function GetValorText(id) {
	
	var campo = document.getElementById(id);
	
	if (campo != null) {		
		return campo.value;		
	}
	
}

/**********************************************************************************
PEGA O VALOR DE UM CAMPO RADIOBOX
**********************************************************************************/

function getValorRadioButton(campo) {
	
	var valor = '';
	
	if (campo != null) {		
		
		var tamanho = campo.length;

		for (i=0; i<tamanho; i++) {
			
			if (campo[i].checked == true) {
				valor = campo[i].value;
				break;
			}
			
		}
		
	}
	
	return valor;
	
}

/**
 * Função para exibir uma DIV com uma msg
 */
function showMsg(idObj, strMsg, fcn)
{
	if( strMsg != '' )
	{
		document.getElementById(idObj).style.display = 'inline';
		document.getElementById(idObj).innerHTML = strMsg;
		document.getElementById(idObj).innerHTML+= '<p align="center"><a href="javascript:;" onclick="closeMsg(\''+idObj+'\');' +fcn+ '">Fechar</a></p>';
	}
	else
	{
		document.getElementById(idObj).innerHTML = '';
		document.getElementById(idObj).style.display = 'none';
	}
}

/**
 * função para fechar um DIV
 */
function closeMsg(idObj)
{
	if( idObj != '' )
	{
		document.getElementById(idObj).style.display = 'none';
	}
}

/**
 * Exibe uma div que estiver oculta
 */
function showDiv(idObj)
{
	if( idObj != '' )
	{
		document.getElementById(idObj).style.display = 'inline';
	}
}

/**
 * Exibe uma div que estiver oculta
 */
function closeDiv(idObj)
{
	if( idObj != '' )
	{
		closeMsg(idObj);
	}
}


/**
 * Função para limpar o valor default de um textfield quando o usuário setar o foco
 */
function clearDefaultValue(idObj)
{
	if(idObj != '')
	{
		if( document.getElementById(idObj).value == 'Busca por código' )
			document.getElementById(idObj).value = '';
	}
}

/**
 * Função para setar o valor default de um textfield quando o usuário retirar o foco
 */
function setDefaultValue(idObj, txt)
{
	if(idObj != '' && txt != '')
	{
		if( document.getElementById(idObj).value == '' )
			document.getElementById(idObj).value = txt;
		else
		{
			document.getElementById('dormitorios').options[0].selected = true;
			document.getElementById('regiao').options[0].selected = true;
			document.getElementById('tipoImovel').options[0].selected = true;
			document.getElementById('faixaPreco').options[0].selected = true;
		}
	}
}

/**
 * Função para setar o valor default no campo código do imóvel, caso
 * o usuário decida fazer a pesquisa por outros meios
 */
function clearCodigo()
{
	document.getElementById('idImovel').value = 'Busca por código'
}

/**
 * Função para restringir a digitação de caracteres númericos no campo do código
 */
function numberMask(event, idObj)
{
	if( !(event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) )
	{
		var tamStr = document.getElementById(idObj).value.length;
		document.getElementById(idObj).value = document.getElementById(idObj).value.substr(0, tamStr-1);
	}
}

/**
 * Função para permitir apenas a digitação de números
 */
function maskNumero(obj,event) 
{
	
	var str = obj.value;
	var Tecla = event.which;
	
	if(Tecla == null)
		Tecla = event.keyCode;
	
	//
	// Caracteres de escape são respectivamente
	// <enter>, <backspace>, <delete>, <left arrow>, <right arrow>	
	if (Tecla != 13 && Tecla != 8 && Tecla != 46 && Tecla != 37 && Tecla != 39) 
	{
	
		if ( (Tecla < 48 || Tecla > 57) && (Tecla < 96 || Tecla > 106) ) 
		{
			event.returnValue = false;
			//alert("Neste campo somente números podem ser digitados");
			return false;
		
		}
	
	}
	
	event.returnValue = true;
	return true;
}

// *************************************************
// Função para colocar a "/" no campo de data
// *************************************************
function AjustaData(obj, evnt)
{
	valNumero(obj, evnt);
	
	if (obj.value.length == 2 || obj.value.length == 5)
	{
 		obj.value += "/";
 	}
}