var altura = 135 //serve pra compensar a altura dos componentes de layout
var string_classificacoes = 'Selecionar de um a três projetos';

// quando a pagina carrega sao executadas essas funcoes --------------------------

$(document).ready(function(){
	ativa_clicks()
	ativa_select_uf()
	toggle_next()
	busca_resultados()
	act_seleciona_projeto()
	toggle_div_projetos()
	toggle_barra()
	AjustaTamanho()
	$(window).wresize(function(){
		AjustaTamanho()
	})		

	/* menu do topo */
	if (typeof($.event.special.hover) == 'object') {
		$.event.special.hover.delay = 100;
		$.event.special.hover.speed = 10;
	}
			
	$("ul.menu_principal").superfish({ 
		animation: {height:'show'},
		speed:'fast',
	    delay:600
	}); 


})

// define a url utilizada pelo ajax ----------------------------------------------
function base_url(){
	//return 'http://bernunca/rep/onid/lista/trunk/';
	//return 'http://dev.ipso.org.br/onid/lista/trunk/';
	return 'http://lista.onid.org.br/';
}

//funcoes de ativacao iniciais --------------------------------------------------
function ativa_clicks(){	
	$('.exibe_div').click(function(){
		$(this).prev().toggle('fast')
	})	
	$('body').click(function(){
		$('.exibe_div').prev().hide()
	})	
	$('#filtro').submit(function(){
		busca_resultados()
		return false
	})
	$('#btn_limpa').click(function(){
		limpa_filtro()
		return false
	})	
	ativa_exportar_planilha()
}
function ativa_select_uf(){
	$('#select_ufs_municipios').html(selectUfs()+'<select class="hidden"></select>')
	$('select[@name="uf_sigla"]').change(function(){
		$.get(base_url()+'includes/AjaxUf.php', [{name:'UF', value:$(this).val()}], function(response){
			$('select[@name="uf_sigla"]').next().replaceWith(response)
		})
	})
}

//funcoes de dinamica genericas ---------------------------------------------------
function toggle_next(){
	$('.toggle_next').click(function(){
		$(this).nextAll('.toggle:first').slideToggle('fast')
		return false
	})
}

//funcoes que pegam variaveis do filtro e buscam resultados por ajax ----------------
function busca_resultados(){
	processandoToggle()
	$.post(base_url()+'includes/AjaxBusca.php', eval('['+pega_valores_do_filtro()+']'), function(response){
		imprime_tabela(response)
		ativa_paginacao($('.modulo'), base_url()+'includes/AjaxBusca.php')
		processandoToggle()
	})
}
function pega_valores_do_filtro(){
	var paramjson = ''  
	$(':input', $('#filtro')).each(function(){
		paramjson += "{ name:'"+$(this).attr('name')+"', value:'"+escape( $(this).val() )+"'},"
	})	
	var classificacoes = new Array() 
	$('.act_seleciona_projeto.selecionado').each(function(i){
		classificacoes[i] = $(this).attr('categoria_id')
	})
	paramjson += "{ name:'classificacoes', value:'"+escape(classificacoes.join('|'))+"'},"

	return paramjson
}

function limpa_filtro(){
	$(':input', $('#filtro')).each(function(){
		if($(this).attr('type') != 'button' && $(this).attr('type') != 'submit')
			$(this).val(' ')
	})
	ativa_select_uf()
	$('#div_todosprojetos').html(string_classificacoes)
	$('.act_seleciona_projeto.selecionado').each(function(i){
		$(this).removeClass('selecionado')
	})	
}

function imprime_tabela(str){
	$('#map').html(str)
	callback_paginacao()
}
//exportar ------------------------------------------------------------------------
function ativa_exportar_planilha(){
	$('#exportar_todos').click(function(){
		window.location = base_url()+'includes/AjaxBusca.php?csv=true&por_pg=500000'
	})
	$('#exportar_busca').click(function(){
		var valores = eval('['+pega_valores_do_filtro()+']')
		var get = '?csv=true&por_pg=50000000'
		for (i in valores){
			get = get+'&'+valores[i].name+'='+valores[i].value
		}
		window.location = base_url()+'includes/AjaxBusca.php'+get
	})
}

//funcao chamada pelo estatico paginacao.js quando recebe o response do ajax ------
function callback_paginacao(){
	define_alturas()
	tr_hover()
	tr_click()
	imprime_num_rows()
}

//dinâmicas da tabela -----------------------------------------------------------
function tr_hover(){
	$('#content_table tr').hover(
		function(){
			$(this).toggleClass('iluminado');	
		},
		function(){
			$(this).toggleClass('iluminado');	
		}
	);
}
function tr_click(){
	$('#content_table tr').click(function(){
		var next = $(this).next();
		if(next.attr('class') == 'detalhe'){
			next.replaceWith(' ');	
			$('td:first', this).removeClass('bg_azul_escuro');				
		}else{
			$('td:first', this).addClass('bg_azul_escuro');
			$(this).after('<tr class="detalhe"><td colspan="5"><div align="center">'+ajax_load()+'</div></td></tr>');						
			buscaDetalhes($(this).attr('id'), $(this).nextAll('.detalhe:first'));
		}
		
	});
}
function ativa_link_plano(obj, plano){
	$('.projetos', obj).click(function(){					
		$(this).next().html('<p>'+plano+'</p>')
		$(this).next().toggle('fast')
	})
}
function buscaDetalhes(id, obj){
	$.get('includes/AjaxDetalhes.php?id='+id, '', function(response){
		$('td', obj).html(response);
		ativa_balao_programa($('td', obj))
	});
}

//imprime a quantidade de registros encontrados na busca ------------------------
function imprime_num_rows(){
	var num_rows = parseInt($('#num_rows').val());
	var por_pg = parseInt($(".por_pg option:selected").val());
	if (por_pg > num_rows) {
		var cont = "";
	}else{
		var cont = '<br />Exibindo <strong>'+por_pg+'</strong> por página';
	}
	$('#painel_num_rows').html('<p class="num_rows">Foram encontrados <strong>'+num_rows+'</strong> registros. '+cont+' </p>').show('fast');
}

//devolve o select de ufs ---------------------------------------------------------
function selectUfs(sel, name){
    if(!name)
		name = 'uf_sigla'		
	ufs =['AC','AL','AM','AP','BA','CE','DF','ES','GO','MA','MG','MS','MT','PA','PB','PE','PI', 'PR','RJ','RN','RO','RR','RS','SC','SE','SP','TO']
    str_select = "<select id='id_uf_sigla' name='"+name+"'>\n\t\t<option value=''>Escolha uma UF...</option>"
    for(x=0; x<ufs.length; x++){
        
		str_sel = ''
        if(sel == ufs[x]) 
            str_sel = 'selected'
           
        str_select += '<option value="'+ufs[x]+'" '+str_sel+'>'+ufs[x]+'</option>'
    }
    str_select += '</select>'
    return str_select
}

//funcoes pra exibir caixa de projetos do filtro ---------------------------------
function act_seleciona_projeto(){
	$('.act_seleciona_projeto').click(function(){
		if($('#div_todosprojetos').html() == string_classificacoes)
			$('#div_todosprojetos').html(' ')
		
		var obj = $(this)
		var categoria_id = obj.attr('categoria_id')
		obj.toggleClass('selecionado')
		
		if(obj.hasClass('selecionado')){
			$('#div_todosprojetos').append('<div categoria_id="'+categoria_id+'"><a href="#" title="remover">Remover</a>'+obj.text()+'</div>')
			$('[@categoria_id="'+categoria_id+'"] a', $('#div_todosprojetos')).click(function(){
				$(this).parent().hide('fast', function(){
					$(this).remove()
					checa_div_todosprojetos()
					$('[@categoria_id="'+categoria_id+'"]', $('#div_projetos')).removeClass('selecionado')
				})
			})
		}else{
			$('[@categoria_id="'+categoria_id+'"]', $('#div_todosprojetos')).hide('fast', function(){
				$(this).remove()
				checa_div_todosprojetos()
			})
		}	

		return false
	})
}
function checa_div_todosprojetos(){
	//serve pra verificar se existe algum perfil selecionado. Se nao tiver nenhum ele coloca a palavra 'selecionar caracteristicas'
	var obj = $('#div_todosprojetos')
	if(obj.html() == ' ')
		obj.html('Selecionar características')
}
function toggle_div_projetos(){
	$('html').click(function(){
		$('#div_projetos').hide('function')
	})
	$('#div_todosprojetos').click(function(){
		$('#div_projetos').toggle('fast')
		return false
	})
}

//funcoes pra ajustar tamanho dos elementos
function AjustaTamanho(){
	var dif_h = altura
	
	if($('#container_barra').css('display') == 'block')
		dif_w = 295
	else
		dif_w = 20
	
	var w = $(window).width()
	var h = $(window).height()
	
	$('#container_map').css('height', h-dif_h).css('width', w-dif_w)
	$('#processando').css('height', h-dif_h).css('width', w-dif_w)
	$('#container_barra').css('height', h-dif_h)	
	$('#togglebarra').css('height', h-dif_h)
	$('.container_filtros').css('height', h-(113+dif_h))

	define_alturas()
}
function define_alturas(){
	var map_h = $('#container_map').height();
	if($('#content_table').next().length)
		var dif_h = 45
	else
		var dif_h = 26
	
	var h = map_h - dif_h
	if($.browser.msie)
		var h = h-5
	$('#content_table').height(h);
}

//funcao pra esconder os filtros
function toggle_barra(){
	$('#togglebarra').click(function(){
		if ($(this).hasClass('barraExpand')) {
			$('#container_barra').hide('fast', function(){
				AjustaTamanho()
			})
			$(this).removeClass('barraExpand').addClass('barraContract')
		}
		else {
			$('#container_barra').show('fast', function(){
				AjustaTamanho()
			})
			$(this).removeClass('barraContract').addClass('barraExpand')
		}
		return false
	})
}

//funcoes pra exibir alertas de load
function ajax_load(){				
	return '<img src="http://estatico.ipso.org.br/images/icons/ajax-loader_clock.gif">';
}
function carregando(){
	processandoToggle()
}
function processandoToggle(){
	var obj = $('#processando')
	if(obj.css('display') != 'block')
		obj.show().fadeTo('fast', 0.8)
	else
		obj.fadeTo('fast', 0).hide()	
}


//funcao para exibir balao de detalhes de um programa de ID
function ativa_balao_programa(obj){
    $('li', obj).click(function(){
        apaga_baloes($(this).next())
        $(this).next().slideToggle();
        ativa_fechar_balao($(this).next())
    })
    
}
function apaga_baloes(obj){
    $('div', obj).each(function(){
        $(this).hide()
    })
}
function ativa_fechar_balao(obj){
    $('#fecha_balao_projetos', obj).click(function(){
        obj.slideUp()
    })

}
