function managerDenunciar(id, comand)
{
//	alert(id);
	if(comand)
		$(id).show();
	else
		$(id).hide();
}

function atualizarListaPergunta(ancid)
{
	divCarregando();
	$.post('/publico/ajax/atualizarListaPergunta/anuncio/' + ancid, function (perg){
		$('#divPergunta').html(perg);
		divCarregado();
	});
}    

function excluirFoto(arqid)
{
	if (confirm('Deseja apagar a foto?')){
		$('[id*="arqid_'+arqid+'"]').remove();
		$('#foto_' + arqid).remove();
		$.post("/admin/anuncio/apagarfoto/img/" + arqid);
	}
}


function confirmar(txt, url){
	if ( confirm( txt ) ){
		location.href = url;
	}
}


/**
 * Seleciona todos os itens do campo select.
 * 
 * @param object campo_select
 * @return void
 */
function selectAllOptions( campo_select )
{
	if ( !campo_select )
	{
		return;
	}
	var j = campo_select.options.length;
	for ( var i = 0; i < j; i++ )
	{
		campo_select.options[i].selected = true;
	}
}

/*
 * function divCarregando
 * Cria e insere no nó de elementos uma DIV transparente com uma imagem de carregando
 * P.S.: Para esconder essa DIV use a função "divCarregado", após a execução de suas operações.
 *
 * @author  Felipe Tarchiani Cerávolo Chiavicatti
 * @access  public
 * @since   16-10-2010
 * @param   string|object id - Deve conter o id ou objeto onde se está clicando a fim de montar a imagem "carregando"
 							   tomando como referência o elemento encontrado por esse paramentro (não obrigatório).
 * @return  void 							   
 */
 function divCarregando(id){
	var d = document;
	var div, span, img, h, w, topImg, elementRefe;
	//var j = jQuery.noConflict();
	id = id ? id : '';
	h = d.body.scrollHeight;
	w = d.body.scrollWidth;
	
	elementRefe = typeof(id) != 'object' ? d.getElementById(id) : id;
	h = h < screen.height ? screen.height : h;
	
	if (elementRefe){
		topImg = findPosY(elementRefe);
	}else{
		topImg = (h/4);
	}
	
	if (!jQuery("#temporizador1")[0]){
		div = d.createElement("div");
	}else{
		div = jQuery("#temporizador1");		
		jQuery(div).remove(div);
	}
	
	// Monta Span
	if (jQuery("span", div).length == 0){
		span = d.createElement("span");
	}else{
		span = jQuery("span", div).eq(0);
		jQuery("span", div).remove();
	}
	
	jQuery(span).attr({
		id : 'spanCarregando'
	})
	.css({
		'position' : 'relative',
		'top'	   : topImg + 'px'
	})
	.append('<center>Aguarde...</center>');
	
	// Monta Imagem
	if (jQuery("img", span).length == 0){
		img = d.createElement("img");
	}else{
		img = jQuery("img", span).eq(0);
		jQuery("img", span).eq(0).remove();
	}
	
	jQuery(img).attr({
		src : '/img/carregando.gif'
	});
	jQuery("center", span).before(img);
	
	// Insere span com img na div, e prepara a mesma
	jQuery(div).append(span)
	.attr({
		id : 'temporizador1'			
	})
	.css({
		'-moz-opacity' : '0.8', 
		'filter' 	   : 'alpha(opacity=80)', 
		'background'   : '#ffffff',
		'text-align'   : 'center',
		'position' 	   : 'absolute', 
		'top' 		   : '0px', 
		'left' 		   : '0px', 
		'width'		   : w + 'px', 
		'height' 	   : h + 'px', 
		'z-index' 	   : '1000'		
	});
		
	// Insere no nó a div	
	jQuery(d.body).append(div);
	
	return;
	//return div;
	
	function findPosY(obj){
		var curtop = 0;
	    if(obj.offsetParent)
	        while(1)
	        {
	          curtop += obj.offsetTop;
	          if(!obj.offsetParent)
	            break;
	          obj = obj.offsetParent;
	        }
	    else if(obj.y)
	        curtop += obj.y;
	    return curtop;
	}
	
}

/*
 * function divCarregado
 * Retira a DIV que nubla a tela criada pela função "divCarregando"
 *
 * @author  Felipe Tarchiani Cerávolo Chiavicatti
 * @access  public
 * @since   11/05/2010
 * @return  void
 */
function divCarregado(){
	//var j = jQuery.noConflict();
	jQuery('#temporizador1').hide(300, function (){jQuery('#temporizador1').remove();});  
}

function mascaraglobal(mascara, valor){

        var mascara_utilizar;
        var mascara_limpa;
        var temp;
        var i;
        var j;
        var caracter;
        var separador;
        var dif;
        var validar;
        var mult;
        var ret;
        var tam;
        var tvalor;
        var valorm;
        var masct;
        tvalor = "";
        ret = "";
        caracter = "#";
        separador = "|";
        mascara_utilizar = "";
        valor = trim(valor);
        if (valor == "")return valor;
        temp = mascara.split(separador);
        dif = 1000;

        valorm = valor;
        //tirando mascara do valor já existente
        for (i=0;i<valor.length;i++){
                if (!isNaN(valor.substr(i,1))){
                        tvalor = tvalor + valor.substr(i,1);
                }
        }
        valor = tvalor;

        //formatar mascara dinamica
        for (i = 0; i<temp.length;i++){
                mult = "";
                validar = 0;
                for (j=0;j<temp[i].length;j++){
                        if (temp[i].substr(j,1) == "]"){
                                temp[i] = temp[i].substr(j+1);
                                break;
                        }
                        if (validar == 1)mult = mult + temp[i].substr(j,1);
                        if (temp[i].substr(j,1) == "[")validar = 1;
                }
                for (j=0;j<valor.length;j++){
                        temp[i] = mult + temp[i];
                }
        }


        //verificar qual mascara utilizar
        if (temp.length == 1){
                mascara_utilizar = temp[0];
                mascara_limpa = "";
                for (j=0;j<mascara_utilizar.length;j++){
                        if (mascara_utilizar.substr(j,1) == caracter){
                                mascara_limpa = mascara_limpa + caracter;
                        }
                }
                tam = mascara_limpa.length;
        }else{
                //limpar caracteres diferente do caracter da máscara
                for (i=0;i<temp.length;i++){
                        mascara_limpa = "";
                        for (j=0;j<temp[i].length;j++){
                                if (temp[i].substr(j,1) == caracter){
                                        mascara_limpa = mascara_limpa + caracter;
                                }
                        }

                        if (valor.length > mascara_limpa.length){
                                if (dif > (valor.length - mascara_limpa.length)){
                                        dif = valor.length - mascara_limpa.length;
                                        mascara_utilizar = temp[i];
                                        tam = mascara_limpa.length;
                                }
                        }else if (valor.length < mascara_limpa.length){
                                if (dif > (mascara_limpa.length - valor.length)){
                                        dif = mascara_limpa.length - valor.length;
                                        mascara_utilizar = temp[i];
                                        tam = mascara_limpa.length;
                                }
                        }else{
                                mascara_utilizar = temp[i];
                                tam = mascara_limpa.length;
                                break;
                        }
                }
        }

        //validar tamanho da mascara de acordo com o tamanho do valor
        if (valor.length > tam){
                valor = valor.substr(0,tam);
        }else if (valor.length < tam){
                masct = "";
                j = valor.length;
                for (i = mascara_utilizar.length-1;i>=0;i--){
                        if (j == 0) break;
                        if (mascara_utilizar.substr(i,1) == caracter){
                                j--;
                        }
                        masct = mascara_utilizar.substr(i,1) + masct;
                }
                mascara_utilizar = masct;
        }

        //mascarar
        j = mascara_utilizar.length -1;
        for (i = valor.length - 1;i>=0;i--){
                if (mascara_utilizar.substr(j,1) != caracter){
                        ret = mascara_utilizar.substr(j,1) + ret;
                        j--;
                }
                ret = valor.substr(i,1) + ret;
                j--;
        }
        return ret;
}

function trim(valor){
	valor+='';
        for (i=0;i<valor.length;i++){
                if(valor.substr(i,1) != " "){
                        valor = valor.substr(i);
                        break;
                }
                if (i == valor.length-1){
                        valor = "";
                }
        }
        for (i=valor.length-1;i>=0;i--){
                if(valor.substr(i,1) != " "){
                        valor = valor.substr(0,i+1);
                        break;
                }
        }
        return valor;
}

function janela(pagina,TW,TH,dest) {
		var j = window.open(pagina, dest, "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes"+",width="+TW+",height="+TH);
		j.focus();
 }


/**
 * Abre a janela de interação do combo_popup. Veja restante dos
 * comentário do arquivo www/global/combopopup.php
 * 
 * @param string nome
 * @param integer height
 * @param integer width
 * @param string funcao
 * @return void
 */
function combo_popup_abre_janela( nome, height, width, funcao )
{
	var campo_select = document.getElementById( nome );
	for ( var i = 0; i < campo_select.options.length; i++ )
	{
		campo_select.options[i].selected = false;
	}
	
	if(funcao != false)
		funcao = '&funcao=' + funcao;
	else
		funcao = '';
	
	//window.open( '../global/combopopup.php?nome=' + nome, nome, "height=" + height +  ",width=" + width +  ",scrollbars=yes,top=50,left=200" );
	a = window.open( '../global/combopopup.php?nome=' + nome + funcao, 'Combopopup', "height=" + height +  ",width=" + width +  ",scrollbars=yes,top=50,left=200" );
	a.focus();
}

function combo_popup_alterar_campo_busca( campo_select )
{
	var campo_busca_id = 'combopopup_campo_busca_' + campo_select.id;
	var campo_busca = document.getElementById( campo_busca_id );
	if ( !campo_busca )
	{
		return;
	}
	var selecionados = 0
	var opcao = null;
	for ( var i = 0; i < campo_select.options.length; i++ )
	{
		if ( campo_select.options[i].selected )
		{
			selecionados++;
			opcao = campo_select.options[i]
		}
	}
	if ( selecionados != 1 )
	{
		return;
	}
	campo_busca.value = opcao.value;
}

function combo_popup_keypress_buscar_codigo( event, nome, valor )
{
	if ( event.keyCode == 13 )
	{
		combo_popup_buscar_codigo( nome, valor );
	}
}

function combo_popup_recebe_buscar_codigo( input, nome )
{
	httpRequest = input.httpRequest;
	if ( httpRequest.readyState == 4 )
	{
		if ( httpRequest.status == 200 )
		{
			var dados = httpRequest.responseText.split( "\n" );
			if ( dados.length == 2 )
			{
				combo_popup_adicionar_item( nome, dados[0], dados[1], true );
				input.value = '';
			}
			else
			{
				alert( 'Nenhum registro encontrado com o código indicado.' );
			}
			input.focus();
		}
	}
}

function combo_popup_codigo_selecionado( nome, cod )
{
	var campo_select = document.getElementById( nome );
	var j = campo_select.length;
	for( var i = 0; i < j; i++ )
	{
		if ( cod == campo_select.options[i].value )
		{
			return true;
		}
	}
	return false;
}

function add_texto_2_areatexto(texto, areatexto){
	if (!(texto == '' || areatexto == '') ){
		
	}
}

function combo_popup_buscar_codigo( nome, cod )
{
	if ( !cod )
	{
		return;
	}
	var input = document.getElementById( 'combopopup_campo_busca_' + nome );
	if ( combo_popup_codigo_selecionado( nome, cod ) == true )
	{
		input.value = '';
		input.focus();
		return;
	}
	var input = document.getElementById( nome );
	var maximo = input.getAttribute( 'maximo' ) - 0;
	if ( maximo > 0 ) {
		var quantidade = input.options.length;
		if ( quantidade > 1 || input.options[0].value != '' ) {
			if ( quantidade >= maximo ) {
				alert( 'A quantidade mpaxima de itens que podem ser selecionados é ' + maximo );
				return;
			}
		}
	}
	/*
	for ( i = input.options.length - 1; i >= 0; i-- )
	{
		if ( input.options[i].selected && input.options[i].value == cod )
		{
			alert( 'O item já está presenta lista' );
			return;
		}
	}
	*/
	input.httpRequest = window.XMLHttpRequest ? new XMLHttpRequest : new window.ActiveXObject( 'Microsoft.XmlHttp' );
	input.httpRequest.onreadystatechange = function(){ combo_popup_recebe_buscar_codigo( input, nome ); };
	input.httpRequest.open( 'GET', '../global/combopopup.php?nome=' + escape( nome ) + '&pegar_dados_item=1&codigo_busca=' + escape( cod ), true );
	input.httpRequest.send( null );
}

/**
 * Abre a janela de interação do texto_popup. Veja restante dos
 * comentário do arquivo www/global/textopopup.php
 * 
 * @param string nome
 * @param integer height
 * @param integer width
 * @return void
 */
function texto_popup_abre_janela( nome, height, width, param )
{
	window.open( '../global/textopopup.php?nome=' + nome + param, nome, "height=" + height +  ",width=" + width +  ",scrollbars=yes,top=50,left=200" );
}

/**
 * Adiciona um item ao combo popup.
 * 
 * @param string nome_combo
 * @param string codigo
 * @param string descricao
 * @param boolean ordenar
 * @return void
 */
function combo_popup_adicionar_item( nome_combo, codigo, descricao, ordenar, naoChamarEvento )
{
	var campo_select = document.getElementById( nome_combo );
	if ( campo_select.options[0].value == '' )
	{
		campo_select.options[0] = null;
	}
	campo_select.options[campo_select.options.length] = new Option( descricao, codigo, false, false );
	
	var evento = campo_select.getAttribute( 'onpush' );
	if ( evento && !naoChamarEvento )
	{
		eval( evento );
	}
	
	if ( ordenar == true )
	{
		sortSelect( campo_select );
	}
}

/**
 * Remove um item do combo popup.
 * 
 * @param string nome_combo
 * @param string codigo
 * @param boolean ordenar
 * @return void
 */
function combo_popup_remover_item( nome_combo, codigo, ordenar, naoChamarEvento )
{
	var campo_select = document.getElementById( nome_combo );
	var removeu = false;
	for( var i = 0; i <= campo_select.length-1; i++ )
	{
		if ( codigo == campo_select.options[i].value )
		{
			campo_select.options[i] = null;
			removeu = true;
		}
	}
	if ( removeu && !naoChamarEvento )
	{
		var evento = campo_select.getAttribute( 'onpop' );
		if ( evento )
		{
			eval( evento );
		}
	}
	if ( campo_select.options.length == 0 )
	{
		campo_select.options[0] = new Option( 'Duplo clique para selecionar da lista', '', false, false );
	}
	if ( ordenar == true )
	{
		sortSelect( campo_select );
	}
}

/**
 * Adiciona uma lista de itens ao combo popup.
 * 
 * @param string nome_combo
 * @param string[][] lista
 * @return void
 */
function combo_popup_adicionar_itens( nome_combo, lista )
{
	var j = lista.length;
	for ( var i =0; i < j; i ++ )
	{
		combo_popup_adicionar_item( nome_combo, lista[i][0], lista[i][1], false, true );
	}
	var campo_select = document.getElementById( nome_combo );
	var evento = campo_select.getAttribute( 'onpush' );
	if ( evento )
	{
		eval( evento );
	}
	sortSelect( campo_select );
}

/**
 * Remove uma lista de itens ao combo popup.
 * 
 * @param string nome_combo
 * @param string[][] lista
 * @return void
 */
function combo_popup_remover_itens( nome_combo, lista )
{
	var j = lista.length;
	for ( var i =0; i < j; i ++ )
	{
		combo_popup_remover_item( nome_combo, lista[i][0], false, true, true );
	}
	var campo_select = document.getElementById( nome_combo );
	var evento = campo_select.getAttribute( 'onpush' );
	//alert( evento );
	if ( evento )
	{
		eval( evento );
	}
	sortSelect( campo_select );
}

function combo_popup_remove_selecionados( event, nome_combo )
{
	if( window.event ) // IE
	{
		var keynum = event.keyCode
	}
	else if( event.which ) // Netscape/Firefox/Opera
	{
		var keynum = event.which
	}
	if ( keynum != 46 )
	{
		return;
	}
	var campo_select = document.getElementById( nome_combo );
	for( var i = 0; i <= campo_select.length-1; )
	{
		if ( campo_select.options[i].selected )
		{
			combo_popup_remover_item( nome_combo, campo_select.options[i].value, false, true );
		}
		else
		{
			i++;
		}
	}
	var evento = campo_select.getAttribute( 'onpop' );
	
	//alert( evento );
	if ( evento )
	{
		eval( evento );
	}
	sortSelect( campo_select );
}

function MouseOver(objeto)
{
	if (objeto.type == "text" || objeto.type == "password"){
		if(objeto.className != 'clsMouseFocus'){
				objeto.className = objeto.className.replace("normal", "clsMouseOver");
		}

	}else if(objeto.type == "textarea"){
		if(objeto.className != 'txareaclsMouseFocus'){
				objeto.className = objeto.className.replace("txareanormal", "txareaclsMouseOver");
		}
	}
	return true;
}

function MouseOut(objeto)
{
	if (objeto.type == "text" || objeto.type == "password")
	{
		if(objeto.className != 'clsMouseFocus'){
					objeto.className = objeto.className.replace("clsMouseOver", "normal");
			}
	
	}else if(objeto.type == "textarea"){
		if(objeto.className != 'txareaclsMouseFocus'){
				objeto.className = objeto.className.replace("txareaclsMouseOver", "txareanormal");
		}
	}
	return true;
}


function MouseClick(objeto){
	if (objeto.type == "text" || objeto.type == "password"){
		objeto.className = objeto.className.replace("clsMouseOver", "clsMouseFocus");
		objeto.className = objeto.className.replace("normal", "clsMouseFocus");
	}else if(objeto.type == "textarea"){
		objeto.className = objeto.className.replace("txareanormal", "txareaclsMouseFocus");
		objeto.className = objeto.className.replace("txareaclsMouseOver", "txareaclsMouseFocus");
	}
}


function MouseBlur( objeto )
{
	if ( objeto.type == "text" || objeto.type == "textarea" || objeto.type == "password" )
	{
		if ( objeto.type == "textarea")
		{
			objeto.className = objeto.className.replace("txareaclsMouseOver", "txareanormal");
			objeto.className = objeto.className.replace("txareaclsMouseFocus", "txareanormal");
		}
		else
		{
			objeto.className = objeto.className.replace("clsMouseOver", "normal");
			objeto.className = objeto.className.replace("clsMouseFocus", "normal");
		}
	}
}

function sortSelect(obj) {
		var o = new Array();
		if (obj.options==null) { return; }
		for (var i=0; i<obj.options.length; i++) {
			o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
			}
		if (o.length==0) { return; }
		o = o.sort( 
			function(a,b) { 
				if ((a.text+"") < (b.text+"")) { return -1; }
				if ((a.text+"") > (b.text+"")) { return 1; }
				return 0;
				} 
			);
	
		for (var i=0; i<o.length; i++) {
			obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
			}
}

