/*
 * Validar somente a entrada de digitos numéricos 
 * 
 * USO:
 * Coloque essa função no evento onKeyPress, dessa forma:
 * onKeyPress="return soNumero(this, true/false, event)"
 *
 * PARAMETROS:
 * campo, objeto do campo que quer efetuar a alidação
 * decimais, true ou false, se aceita numeros decimais
 * evento, passe sempre "event"
 */
function soNumero(campo, decimais, evento)
{
	var whichCode = (window.Event) ? evento.which : evento.keyCode;	
	var permitidos = decimais ? '0123456789,' : '0123456789';

	key = String.fromCharCode(whichCode); // Get key value from key code	

	if (parseInt(whichCode) < 32){
		return true;
	}
	
	if (permitidos.indexOf(key) == -1) {
		return false; // Not a valid key
	}
	
	if (key == ','){
		if (campo.value.indexOf(',') > -1) {
			return false;
		}
	}
	
	return true;
}

function cmdVerificarDigitos(campo, tamanho) {
	return campo.value.length <= tamanho;
}

function cmdCont(campo, tamanho, span) {    
    document.getElementById(span).innerHTML = (tamanho - campo.value.length);
}

function me(pElemento, pSinal) {
    oElemento = document.getElementById(pElemento);
    oSinal = document.getElementById(pSinal);
    if (oElemento.style.display == 'none') {
            oElemento.style.display = '';
            oSinal.innerHTML = '-';
    } else {
            oElemento.style.display = 'none';
            oSinal.innerHTML = '+';
    }
}

function mostrarOpcoesComboPesquisa() {
    var campo = document.getElementById('comboPesquisaOpcoes');
    if (campo.style.display == 'none' || campo.style.display == '') {
        campo.style.display = 'block';
    } else {
        campo.style.display = 'none';
    }
}

function selecionarValorComboPesquisaInterno(opcao, texto) {
    document.getElementById('comboPesquisaValor').value = opcao;
    document.getElementById('comboPesquisaValorSelecionado').innerHTML = texto;
}

function selecionarValorComboPesquisa(opcao, texto) {
    selecionarValorComboPesquisaInterno(opcao, texto);
    mostrarOpcoesComboPesquisa();
}

/*
 * Funções para maximizar/minimizar a pesquisa (estava no layout mas foi decidido tirar)
 * 
function minimizar() {
	document.getElementById("pesquisa").style.display = 'none';
	document.getElementById("max").style.display = '';
	document.getElementById("min").style.display = 'none';
}

function maximizar() {
	document.getElementById("pesquisa").style.display = '';
	document.getElementById("max").style.display = 'none';
	document.getElementById("min").style.display = '';
}
*/

function buscaAvancada() {
	try{
        //var buscas = document.getElementsByName('tdPesquisaAvancada');
		var buscasBruto = document.getElementsByTagName('tr');
		var buscas = new Array();
		var i = 0;
		for (i = 0; i< buscasBruto.length;i++){
			if (buscasBruto[i].getAttribute('name') == 'tdPesquisaAvancada'){
				buscas.push(buscasBruto[i]);
			}
		}
        var td = 0;
        for (td=0; td< buscas.length;td++){
            var busca = buscas[td];
            if (busca.style.display == ''){
                busca.style.display = 'none';
                document.getElementById("max").style.display = '';
                document.getElementById("min").style.display = 'none';
            } else {
                busca.style.display='';
                document.getElementById("max").style.display = 'none';
                document.getElementById("min").style.display = '';
            }
        }
    }catch(e){window.alert(e);};
}

// Esconde as tags <h1 /> das pesquisas
function esconderHeaders() {
	document.getElementById('headerPesquisa').style.display = '';
	document.getElementById('headerDestaque').style.display = 'none';
}

// Faz aparecer a mascara
function openMask() {
	
	//Get the screen height and width  
    var maskHeight = $(document).height();  
    var maskWidth = $(window).width();  
  
    //Set height and width to mask to fill up the whole screen  
    $('#mask').css({'width':maskWidth,'height':maskHeight});  
      
    //transition effect       
    $('#mask').show();
    //$('#mask').fadeTo("slow",0.2);
}

// Some com a mascara
function closeMask() {
    $('#mask, .window').hide();
}

/*Função para fazer a substring dos anúncios*/
function doSubString(text, limite) {
	var limiteAplicado = limite || 20; 
	var cont = text.length;
	if (cont > limiteAplicado) {
		var newText = text.substring(0, limiteAplicado-1) + '...';
		return newText;
	} else {
		return text;
	}
}

// Redirecionar Menus
function redirecionar(dsCaminho) {
    window.location = dsCaminho;
}

//Redirecionar front end
function redirecinarFrontEnd() {
	window.location = "./classicaxias/website/FrontEndBean.action?menuAtual=7";
}

//Redirecionar website
function redirecinarWebSite() {
	window.location = "./classicaxias/FrontEndBean.action?menuAtual=7";
}

//Redirecionar manager
function redirecinarManager() {
	window.location = "./login.jsp";
}

//Abrir popUp para impressão do anúncio
function abrirPopUpAnuncio(endereco) {
	window.open(endereco, '', 'width=642');	
}

//Buscar somente o nome da imagem
function buscarNomeImagem(imagem) {
	try
	{
		//TODO: alterar para algo não tão atrelado ao caminho virtual das imagens
		if (imagem.split("/")[5] != undefined) {
			return imagem.split("/")[5];
		} else {
			var nome = imagem.split("/")[4];
			return nome.split("_")[1];
		}
	}
	catch(e)
	{
		return "";
	}
}

//Modal
$(document).ready(function() {    
	  
    //select all the a tag with name equal to modal  
    $('div[name=modal]').click(function(e) {  
        //Cancel the link behavior  
        e.preventDefault();  
        //Get the A tag  
        var id = '#anuncios';
      
        carregarMascara(false);
      
        //Get the window height and width  
        var winH = $(window).height();  
        var winW = $(window).width();  
                
        //Set the popup window to center  
        $(id).css('top',  winH/2-$(id).height()/2);  
        $(id).css('left', winW/2-$(id).width()/2);  
      
        //transition effect  
        //$(id).fadeIn(2400);   
        $(id).show();
      
    });  
      
    //if close button is clicked  
    $('.window .close').click(function (e) {  
        //Cancel the link behavior  
        e.preventDefault();  
        $('#mask, .window').fadeOut(300);
        document.getElementById("titulo").innerHTML = '';
        document.getElementById("iAnuncios").src = './blank.jsp';
    });
});

function carregarMascara(mostrarAguarde) {
	//Get the window height and width  
    var winH = $(window).height();  
    var winW = $(window).width();
    
	if (mostrarAguarde) {
		var imgAguardeHeight = $('#imgAguarde').height();
		var imgAguardeWidth = $('#imgAguarde').width();
		$('#imgAguarde').css('top',  winH/2-imgAguardeHeight/2);  
        $('#imgAguarde').css('left', winW/2-imgAguardeWidth/2);

    	$('#imgAguarde').show();
    }
    
	//Get the screen height and width  
    var maskHeight = $(document).height();  
    var maskWidth = $(window).width();  
  
    //Set height and width to mask to fill up the whole screen  
    $('#mask').css({'width':maskWidth,'height':maskHeight, 'position':'fixed', 'opacity':'0.5'});  
      
    //transition effect
    //$('#mask').fadeIn(200);
    $('#mask').show();
}

function fecharMascara() {
	$('#imgAguarde').hide();
	//$('#mask').fadeOut(200);
	$('#mask').hide();
}

function formatarEndereco(cidade, bairro, endereco) {
	var enderecoCompleto = "";

	if (cidade != "") {
		enderecoCompleto = completarEndereco(cidade);
	}
	
	if (bairro != "") {
		if (enderecoCompleto != "") {
			enderecoCompleto += "+" + completarEndereco(bairro); 
		} else {
			enderecoCompleto = completarEndereco(bairro);
		}
	}

	if (endereco != "") {
		if (enderecoCompleto != "") {
			enderecoCompleto += "+" + completarEndereco(endereco); 
		} else {
			enderecoCompleto = completarEndereco(endereco);
		}
	}

	return enderecoCompleto;
}

function completarEndereco(endereco) {
	var enderecoCompleto = "";
	var arrayEndereco = new Array();
	arrayEndereco = endereco.split(" ");
	for(i=0; i < arrayEndereco.length; i++) {
		if (enderecoCompleto == "") {
			enderecoCompleto = arrayEndereco[i];
		} else {
			enderecoCompleto += "+" + arrayEndereco[i];
		}
	}

	return enderecoCompleto;	
}
