$(document).ready(function() { //no carregamento da página    
    if(this.location.hash.length > 0) {
		substituiForm();
	} else {
        ativaFormulario();
        ativaResultado();		
    }
});


function formataValores(tipo) {
    //tipo pode ser 'post' ou 'hash'
    //

    var validos = new Array()
    
    var campos = []
    $('#filtro :input').each(function(){ 
            if($(this).val() && $(this).val() != 0 && $(this).val() != '') {
                val = $(this).val()
                if($(this).attr('type') == 'text'){
                    val = escape($(this).val())
                }
                if($(this).attr('type') == 'checkbox' && !$(this).attr('checked')){
                   val = 'nao'
                }
                if(tipo=='post'){
                  validos.push($(this).attr('name')+"="+val)                  
                } else {
                  validos.push($(this).attr('name')+":"+val)
                }
             }
    });
    
    if (tipo == 'hash') {
        return validos.join('/');
    } else {
        validos.push("ajax=true");
        return validos.join('&');        
    }
    
}
	

function ativaFormulario() {
	//TROCA BOTÂO QUE SUBMETE POR LINK
	$("[@name='listar']").attr('id','link_submete');
	
	$("form#filtro").bind("submit", function(event){
		 event.preventDefault();
  		 $("#link_submete").click();
	 });
	
	$("#link_submete").click(function() {
		$("form [@name='pg_atual']").val(1);
		atualizaUrl();
        submeteForm();
		return false;									  
	});
    gera_drop_municipios()  
    $('#fixme').hide('normal')
    var doc = this;
    
}

function ativaResultado() {
	
    //Ativa a ordenacao
    $(".lista-header a").click(function(){
		sentido = "ASC";
        if($(this).parent('div').hasClass("baixo")) {
			sentido = "DESC";
		}
		$("form [@name='ordenacao']").val($(this).attr("id")+" "+sentido);
		atualizaUrl();
		submeteForm();			
		return false;
	});
	
    //Ativa a paginacao
    $(".paginacao a").click(function(){
        pg = $(this).attr('href')
        $("[@name='pg_atual']").val(pg)       
        atualizaUrl();
		submeteForm();
        return false;
    })
	$(".por_pg").change(function(){
		$("[@name='por_pg']").val($(this).val())
		atualizaUrl();
		submeteForm();
        return false;
	})
   	$('#fixme').hide('normal')
    $('.reduzir_url').click(function(){
        return reduzUrl();
    });
}

function atualizaUrl() {
	this.location.hash = formataValores('hash');
}

function carregaHash() {
	if(this.location.hash.length > 0) {	
    	//Passa o hash pra variaveis;
    	arrhash = this.location.hash.replace("#","").split("/");
    	paramjson = "";
    	for (key in arrhash) {
    		item = arrhash[key].split(":");
            
    		if(item[0] == "q") {
    			item[1] = escape(item[1]);
    		}
    		paramjson += "{ name:'"+item[0]+"', value:'"+item[1]+"'},";
    		
    	}
        paramjson += "{ name:'ajax', value:true},";		
        paramjson += "{ name:'categoria', value:'"+$('[@name=categoria]').val()+"'},";		
    	
        param = eval("["+paramjson+"]");
    	
    	return param;
	} else {
		return false;	
	}
}

function submeteForm() {
	$('#fixme').show('normal')  
	valores = formataValores('post');
    
	$.post(base_url()+"listagem/gera_ajax_resultado", 
            valores,
            function (response) {//'response' é o q vem do ajax 
                atualizaResultado(response);
			});
}

function substituiForm() {
  
	    valores = carregaHash();//formataValores('post');

        $.post(base_url()+"listagem/gera_ajax_form", 
            valores,
            function (response) {//'response' é o q vem do ajax 
                atualizaForm(response);
			});
}

function atualizaForm(response) {
	$('#fixme').show('normal')
    $("#filtro").replaceWith(response);
	ativaFormulario();
	submeteForm();
}

function atualizaResultado(response) {
	$("#resultado").show().html(response);
	ativaResultado();
}
function reduzUrl() {
    url = this.location.href+this.location.hash; 
    $.post(base_url()+"ajax_modulos/ext",{url:"http://is.gd/api.php?longurl="+url}, function(data){
          alert("Data Loaded: " + data);
    });

    return false;
}

function carregando(){
	$('#fixme').toggle('normal');
}
