/*
* oculta o obj
*/
function hide(obj){
	obj.style.display = "none";
}


/*
* faz um overlay no obj
*/
function overlay(obj){
	obj.style.background = "#D9DEE2";
}


/* 
* retira o overlay do obj
*/
function _overlay(obj){
	obj.style.background = "transparent";
}


/*
* coloca o campo passado pelo id em Focu
*/
function setFocus(id){
	var obj = document.getElementById(id);
	obj.focus();
}


/*
* muda o background do obj selecionado
*/
function selected(obj){
	obj.style.background = "#efefef";
}


/*
* retira o background do obj
*/
function _selected(obj){
	obj.style.background = "#ffffff";
}


/*
* rola a página até o element
*/
function scrollTo(element){
	var obj = document.getElementById(element);
	obj.scrollIntoView();
}


/*
* abre uma popUp com os parametros passados
*/
function popUp(url, titulo, width, height, target, scrollbar){
	
	if (scrollbar!=null || scrollbar!=undefined) {
		var scroll = "yes";
	} else {
		var scroll = 0;
	}

	if( (target!=null) && (target!=undefined) )
		var janela = window.open(url, target, 'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars='+scroll+',resizable=0');
	else {
		var janela = window.open(url, null, "toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars="+scroll+",resizable=0");
	}
	janela.resizeTo(width, height);
}


/*
* executa o método em looping através dos segundos
*/
function reload(metodo, segundos){
	setTimeout(metodo, (segundos*1000)); /* x 1000, milisegundos */
}


/*
* cria uma mascara para campos input
*/
// onkeypress=mascara(this, "(99)9999-9999", event);
function mascara(objeto, sMask, evtKeyPress) {

	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) { // Internet Explorer
	    nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
	    nTecla = evtKeyPress.which;
	} else {
	    nTecla = evtKeyPress.which;
	    if (nTecla == 8) {
	        return true;
	    }
	}

    sValue = objeto.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++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
}

/*
* Checa se o valor do Campo é um número
*/
function checaNumero(campo){
	var numero = campo.value;
	var sClasse = document.getElementById("mensagem");
	
	if(isNaN(numero)){		
		sClasse.className='ativo';		
		
		var resposta = document.getElementById("resposta");
		resposta.innerHTML = "Valor Inválido para o campo <u>"+campo.name+"</u>";
		
		campo.parentNode.childNodes(0).style.color="red";		
	}else{
		sClasse.className='oculto';
		return true;
	}
}	
/* 
*  Funcão winSize
*  Retorna o tamanho útil da janela
*  Valmir - copiado do arquivo 'lightbox.js'
*/
	
function winSize() {
	var x;
	var y;
	if (window.innerHeight && window.scrollMaxY) {
		x = document.body.scrollWidth;
		y = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}
	return { x:x, y:y };
}

/* 
*  Funcão tirarEspacos
*  Retorna a string recebida como parâmetro, sem espaços
*  Valmir - 26/09/08
*/
	
function tirarEspacos(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

/* 
*  Funcão mostraLoading
*  Retorna mostra imagem de carregando quando chamar AJAX
*  Fernando - 10/10/08
*/
	
function mostraLoading(div,img,txt) {
	var div = document.getElementById(div);
	var img = '<center><img src="'+img+'" border="0">'+(txt == undefined ? '' : '<br>'+txt)+'</center>';
	
	div.innerHTML = img;
}

/*
*	Função	detectarNavegador
*	Função para pegar navegador utilizada pelo usuário
*	Retorna string
*	Cristian - 20/10/08
*/

function detectarNavegador(){
	var navegador = navigator.appName + " " + navigator.appVersion;
	return navegador;
}

/*
*	Função	detectarNavegador
*	Função para pegar Resolução utilizada pelo usuário
*	Retorna string
*	Cristian - 20/10/08
*/
function detectarResolucao(){
	var resolucao	=	screen.width+"x"+screen.height;	
	return resolucao;
}


/* verifica se é um email válido */
function is_mail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
            return true;
        }
    }else{
        return false;
    }
}


/*
*	Função	numeros
*	Função permite apenas a inserção de numeros no campo
*	Retorna boolean
*/

function numeros(campo){
	var digits="0123456789"
	var campo_temp
	for (var i=0;i<campo.value.length;i++){
		campo_temp=campo.value.substring(i,i+1)    
		if (digits.indexOf(campo_temp)==-1) {
			campo.value = campo.value.substring(0,i);
			break;
		}
	}    
}

/*
*	Valida CNPJ
*/
function validaCNPJ(cnpj) {
	
     var erro = new String;
     
   var nonNumbers = /\D/;
   if (nonNumbers.test(cnpj)) erro += "A verificação de CNPJ suporta apenas números! "; 
   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 +="Dígito verificador com problema!";
    }
	if (erro.length > 0){	
		return false;
	}else{
		return true;
	}
}

/*
*	Valida CPF
*/
function validaCPF(cpf) {

	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
       return false;
   }
   var a = [];
   var b = new Number;
   var c = 11;
   for (i=0; i<11; i++){
      a[i] = cpf.charAt(i);
      if (i < 9) b += (a[i] * --c);
   }
   if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
        for (y=0; y<10; y++) b += (a[y] * c--); 
        if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
        if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
              return false;
      	}else{	
   			return true;
      	}
}




/* ******************************************************************************************** *
* Altera o estilo css do campo passado por refêrencia (id_input), para estilo de erro			*
* ********************************************************************************************* */
function formErro(id_input){
	if( (id_input!=null) && (id_input!="undefined") ){
		var obj = document.getElementById(id_input);
		obj.style.border = "1px solid red";
	}
}

function _formErro(id_input,color){
	if( (id_input!=null) && (id_input!="undefined") ){
		var obj = document.getElementById(id_input);
		if (color==null || color=="undefined") {
			obj.style.border = "1px solid #CCCCCC";
		} else {
			obj.style.border = "1px solid "+color;
		}
	}
}

/*************************************************************
*				MAXLENGTH para TEXTAREA						 *
*************************************************************/
function maxLength(obj){
  
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
}

/****************************************************************************
*					EXPAND A DIV ATÉ A ALTURA DESEJADA						*
****************************************************************************/
function expandDiv(destino, altura, velocidade, bool){
	
	var fim 		= 		false;
	var effect 		= 		(bool==undefined ? false : bool );
	var obj 		= 		document.getElementById(destino);	
	
	obj.setAttribute("class", "");
	obj.className='';
	
	var y			= 		obj.offsetHeight;	
	
	if( !effect ) {
		if( y < altura ) {
			obj.style.height = (y+velocidade)+"px";		
			
		}else{
			if( y < altura ){
				obj.style.height = (y+velocidade)+"px";
			}
			else
				effect = true;
		}
	}else {
		obj.style.height = (y-velocidade)+"px";

		if( y <= altura ) {
			fim = true;
		}
	}
	
	if(!fim){
		reload('expandDiv("'+destino+'",'+altura+','+velocidade+','+effect+')', 0.01);
	}
}

/****************************************************************************
*					EXPAND A DIV ATÉ A ALTURA DESEJADA						*
****************************************************************************/
function recolheDiv(destino, altura, velocidade){
	
	var fim 		= 		false;
	var obj 		= 		document.getElementById(destino);	
	
	var y			= 		obj.offsetHeight;	
	
	if( y > altura ) {
		
		if( (y - velocidade) <= 0){
			obj.style.height = "0px";
			fim = true;	
		}else{
			obj.style.height = (y-velocidade)+"px";	
		}
	}
		
	if(!fim){
		reload('recolheDiv("'+destino+'",'+altura+','+velocidade+')', 0.01);
	}else{
		
		obj.setAttribute("class", "oculto");
		obj.className='oculto';
		
	}
}

/********************************************************************
*								LIMPA CAMPO							*
********************************************************************/
function limpar_campo(obj, valor_padrao){
	
	if(obj.value == valor_padrao){
		
		obj.value	=	'';
		
	}else if(obj.value == ''){
		
		obj.value	=	valor_padrao;
	}
}

function setDate(obj, ev){
	
	// verifica qual tecla foi pressionada //
	if(document.all)
	    nTecla = ev.keyCode;
	else { 
		if(document.layers) 
	    	nTecla = ev.which;
	    else
	    	nTecla = ev.which;
	}
	
	// separa a string do ultimo caractere digitado //
	var string 	= obj.value.substr(0, obj.value.length-1);
	var c		= obj.value.substr(obj.value.length-1, 1);
	var value	= "";
	
	
	if( !isNaN(c) && c!==" " )
		string = string+c;

	// se não foi pressionado backspace (8) então executa o script *** para poder apagar a barra "/" *** //
	if ( nTecla!=8 ) {

		var strTmp = "";
		for(var i=0; i<string.length; i++ ){
			if( !isNaN(string.substr(i, 1)) && string.substr(i, 1) != " " )
				strTmp+=string.substr(i, 1);
		}
		string = strTmp;
		
		for(var i=0; i<string.length; i++){
			if( (i==2) || (i==4) )
				value += "/";
			value+=string.substr(i, 1);
		}
		string = value;
	} 
	
	obj.value = string;	
}

function replaceAll(search, replace, string){
	
	var pos = null;
    while (por=string.indexOf(search) > -1){
		string 	= string.replace(search, replace);
	}
    return (string);
    
}

function formatarValor(obj) {
	var vlr = obj.value;
	var vlrFmt = '';
	var centavos = '00';
	var inteiro = vlr;
	if(' ' + vlr.indexOf('.') > 0) {
		var centavos = (vlr + '00').substr((vlr+'00').indexOf('.')+1,2);
        var inteiro  = vlr.substr(0, vlr.indexOf('.'));
	}
	
	while(inteiro > 0) {
		var resto = parseInt(inteiro % 1000);
		if(inteiro > 99) {
			vlrFmt = ('000'+resto.toString()).substr(resto.toString().length, 3) + '.' + vlrFmt;
		}
		else if(inteiro > 9) {
			vlrFmt = ('00'+resto).toString().substr(resto.toString().length, 2) + '.' + vlrFmt;
		}
		else {
			vlrFmt = ('0'+resto).toString().substr(resto.toString().length, 1) + '.' + vlrFmt;
		}
		inteiro = (inteiro - resto) / 1000;
	}
	if(vlrFmt == '') {
		vlrFmt = '0.';
	}
	obj.value = vlrFmt.substr(0,vlrFmt.length - 1) + "," + centavos;
}



/* ****************************************************************************************	*
* Funcao que possibilita o floatbanner no fullbanner										*
* ***************************************************************************************** */
function onFullBanner(obj){
	obj.style.height = "240px";
}

function offFullBanner(){
	var obj = document.getElementById("fullbanner");
	var obj2 = document.getElementById("banner_destaque");
	obj.style.height = "80px";
	obj2.style.height = "80px";
}

/* ****************************************************************************************	*
* Funcao que conta o numero de caracteres digitados em um campo								*
* ***************************************************************************************** */
function contarCaracteresDigitados(obj, destino){
	
	var respostasCampo		=		document.getElementById(destino);
	
		respostasCampo.innerHTML = obj.value.length;
	
}




/**
* Retira a acentuação da string
*/
function retirarAcentos(string){
	
	var  str 	= "áàÁÀéèêÉÈÊíìÍÌóòôÓÒÔúùÚÙçÇ"; // string especiais
	var _str 	= "aaAAeeeEEEiiIIoooOOOuuUUcC"; // string equivalente
	var _string = "";
	var pos		= "";
	var c		= "";

	for(var i=0; i<string.length; i++){
		c 	= string.substring(i,i+1);
		pos = str.indexOf(c);
		_string+= ( pos>=0 ? _str.substring(pos,pos+1) : c );
	}

	return _string;	
}



/**
* desabilita o clique com o botão direito do mouse
*/
function disableClick(){
	if (event.button==2||event.button==3)
		oncontextmenu='return false';
}

document.onmousedown = "disableClick"
document.oncontextmenu = new Function("return false;");



/**
* Função para controle de teclado
* ex de uso: onKeyUp(event, "F9", "listarImoveis()");
*/

var _key_code = new Array();

_key_code[9] 	= "ESPACO";
_key_code[13] 	= "ENTER";
_key_code[27] 	= "ESC";
_key_code[37] 	= "ESQUERDA";
_key_code[38] 	= "CIMA";
_key_code[39] 	= "DIREITA";
_key_code[40] 	= "BAIXO";
_key_code[120] 	= "F9";
_function		= null;
_key			= null;


function keypress(event, key, response){
	
	if( event.keyCode in _key_code ){
		if( _key!=null && _function!=null ){
			if( _key_code[event.keyCode] == _key.toUpperCase() )
				eval(_function);
		}
		
		if( key!=null && key!=undefined ){
			if( _key_code[event.keyCode] == key.toUpperCase())
				eval(response);
		}
	}
			
}




/**
* função para contar clique no imóvel
*/
function addClick(id_imovel, tipo_clique, origem, id_filial, id_opcao_negocio, id_tipo_imovel, id_status){
	
	if( id_imovel!=null && tipo_clique!=null && origem!=null ){
		var ajax 	= new Ajax();
		var params 	= "";
		
		params += "id_imovel="+id_imovel;
		params += "&tipo_clique="+tipo_clique;
		params += "&origem="+origem;
		params += "&id_filial="+( id_filial==null ? "" : id_filial );
		params += "&id_opcao_negocio="+( id_opcao_negocio==null ? "" : id_opcao_negocio );
		params += "&id_tipo_imovel="+( id_tipo_imovel==null ? "" : id_tipo_imovel );
		params += "&id_status="+( id_status==null ? "" : id_status );
	
		ajax.load("POST", SITE+"ajax/add_click.php", params);
	}
	
}



function formatarMoeda(obj, verificar_zeros){

	var string		= obj.value;
	var validos 	= "1234567890";
	var newString 	= "";
	var string_final= "";
	var count 		= 0;
	var zeros		= ( verificar_zeros==null ? false : true );
	
	
	for( var i=string.length; i>0; i-- ){
		c = string.substr(i-1, 1);
		if( validos.indexOf(c)>=0 )
			newString += c;
	}
	
	if( zeros ){
		if( newString.length==2 )
			newString += "0";
		if( newString.length==1 )
			newString += "00";
		if( newString.length==0 )
			newString += "000";
	}
	
	
	for( i=0; i<newString.length; i++ ){
		c = newString.toString().substr(i, 1);
		if( i==2 ){
			string_final += ",";
			count = 0;
		}
		else {
			if( ++count==3){
				string_final += ".";
				count = 0;
			}
		}
		string_final += c;
	}
	
	newString = "";
	for( i=string_final.length; i>0; i-- ){
		c = string_final.toString().substr(i-1, 1);
		newString += c;
	}
	
	obj.value = newString;

}

/**
* funcao que retorna os valores do campo selecionado
*
* @params string $object_id id do input
*/
function getFormObjectValue(object_id) {
	if(object_id==null) {
		return "";
	} else {
		var object = document.getElementById(object_id);
		if( object!=null && object!="undefined" ){
			return object.value;
		}
		else
			return "";
	}
}

/**
* funcao que seta o valor para o objeto selecionado
*
* @params string $object_id id do input
* @params string $value valor a passar
*/
function setFormObjectValue(object_id,value) {
	if(object_id!=null) {
		var object = document.getElementById(object_id);
		if( object!=null && object!="undefined" ){
			object.value = value;
		}
	}
}
