/* Variaveis globais */
var base_url = 'http://mapasdarede.ipso.org.br/mapa/'
var projSelecionados = new Array;
var lat = null, lon = null, end = null;
var slideEndereco, slideProjetos, slidePchaves;
var painelMaximizado = 'procura';
var legendaFixa = false;
var firePalavrasChave = '';
var funcFiredPalavraChave = function(e) {};

window.addEvent('domready', Inicia);

/******************************************/

function Inicia() {
	AjustaTamanho();  /* Ajusta o tamanho dos elementos */
	criaSlides(); /* Cria os slides */

	/* Prende os eventos */
	window.addEvent('resize',AjustaTamanho);
	$('select_uf').addEvent('change', CarregaEstados);
	$('div_todosprojetos').addEvent('click', mouseProjetos);
	$('btn_busca').addEvent('click',ativaBuscaTelecentros);
	$('togglebarra').addEvent('click', toggleBarra);

	$('exportar_csv').addEvent('click', toggleBarraExportarCsv);
	$('exportar_resultados_csv').addEvent('click', exportarResultadosCsv);

	$('exportar_imprimir').addEvent('click', toggleBarraExportarImprimir);
	$('exportar_resultados_imprimir').addEvent('click', exportarResultadosImprimir);

	$('a_procura').addEvent('click', function(e) {MaxPainel('procura');});
	$('a_resultados').addEvent('click', function(e) {MaxPainel('resultados');});
	$$('html').addEvent('click', limpaJanelas);
	$('select_numtelecentros').addEvent('change', validaBusca);
	$('txt_palavraschave').addEvent('keyup', function(e) {
			$clear(funcFiredPalavraChave);
			firePalavrasChave = $('txt_palavraschave').getValue();
			funcFiredPalavraChave = validaBusca.delay(2000, this)
		}
	);
	/* Executa procura quando o enter eh pressionado com foco num input dentro do div_procura */
	$$('#div_procura input').addEvent('keyup', function(e)
		{
			if (e.keyCode == 13)
				$('btn_busca').fireEvent('click',0,0);
	    }
	);

	$('btn_limpa').addEvent('click', function(e)
		{
			$$('div#div_procura input[type=text]').each(
				function(input)
				{
					input.value = '';
				});

            $$('div#div_procura select').each(
                function(select)
                {
                    select.selectedIndex = 0;
                    CarregaEstados();
                });

            $$('div#div_procura *').each(
                function(element)
                {
                    element.fireEvent('blur',0,0);
                });

			if ($('end_definido')) {
				$('end_definido').remove();
				$('txt_endereco').value = '';
				$('txt_endereco').setStyle('display','');
				slideEndereco.slideOut();
				map.removeOverlay(markCasa)
				markCasa = lat = lon = end = null;
			}

			projsRemover = projSelecionados.copy();
			projsRemover.forEach(function(projeto)
                {
                    setClassificacao(projeto,1);
                });
			validaBusca();
		}
	);

	var endCompleter = new Autocompleter.Local($('txt_endereco'),{});

	inciaGoogleMap();
	validaBusca();
	pega_hash();
	//processandoToggle(testaJson());
}

/******************************************/

function pega_hash() {
	var hash = window.location.href.split('#');
	if(hash.length > 1 && hash[1].length > 2) {
		var valores = hash[1].split('=');
		var param = valores[0];
		var url = 'includes/AjaxBusca.php?'+hash[1]
		if (param == 'id' || param == 'idIpso') {
			var id = valores[1];

            if ("01234567890".indexOf(id.substring(0,1)) == -1)
                url += "&tipoId=idIpso"
            else
                url += "&tipoId=id"

            submete_busca(url, id);
		}
        else {
    		submete_busca(url)
		}
		removeShapesEstados()
	}
}

/******************************************/

function submete_busca(url, id){
	zera_legenda();
	processandoToggle(function(e)
    {
      new Ajax(url,
        {
    		  method: 'get',
    		  onComplete: function(e) {
    		  	processaPontos(e)
    		  	if(id){
    		  	    id = eval("(" +e+ ")").markers[0].id;
                    idIpso = eval("(" +e+ ")").markers[0].cod;
    		  	    abreBalao(id)
    		  	    map.panTo(matPontos[id].getLatLng())
    		  	}
    		  }
        }
      ).request();
    });
}

/******************************************/

function limpaJanelas(e) {
	e = new Event(e);
	if ($('div_projetos').getStyle('visibility') != 'hidden') {
		divProjCoord = $('div_projetos').getCoordinates();
		if (e.page.x < divProjCoord.left ||
        	e.page.x > divProjCoord.right ||
        	e.page.y < divProjCoord.top ||
        	e.page.y > divProjCoord.bottom)
			projetosToggle(0);
	}
	limpaBarraExportar()

}

/******************************************/

function toggleBarra() {
	var tdBarra = $('td_barra');
	var tdBarraVisivel = tdBarra.getStyle('display') != 'none' ? 1 : 0;

	var mapCenter = map.getCenter();

	if (tdBarraVisivel) {
		tdBarra.setStyle('display','none');
		$('togglebarra')
			.removeClass('barraExpand')
			.addClass('barraContract');
	} else {
		tdBarra.setStyle('display','');
		$('togglebarra')
			.removeClass('barraContract')
			.addClass('barraExpand');
	}

	AjustaTamanho();
	map.panTo(mapCenter);
}

/******************************************/

function refreshToggleBarra() {
	if (!$('togglebarra'))
		new Element('a', {'id':'togglebarra', 'href':'javascript:void(0)', 'class':'barraExpand'})
			.addEvent('click', toggleBarra)
			.injectAfter($('map'));

	var gMapCoords = $('map').getCoordinates();
	$('togglebarra').setStyles(
		{
			'left':gMapCoords.right,
			'top':gMapCoords.top,
			'height':gMapCoords.height
		});
}

/******************************************/

function criaSlides() {
	var pchaves_texto = 'palavras chave';
	var endereco_texto = 'endereço';

	$('div_numtelecentros').setStyle('display','none');

	/* Cria os slides */
	slideEndereco = new Fx.Slide('fset_endereco',
	{
		duration: 500,
		onComplete: function(e)
		{
			if ($('txt_endereco').getValue() == '') {
				$('abre_endereco').setStyle('display', '');
				$('txt_endereco').value = endereco_texto;
				$('div_numtelecentros').setStyle('display','none');
			} else {
				$('txt_endereco').focus();
				$('fset_endereco').getParent().setStyle('height','');
			}
		}
    }).hide();

	slideProjetos = new Fx.Slide('fset_projetos',
	{
		duration: 500,
		onComplete: function(e)
		{
			if ($('fset_projetos').getParent().getStyle('height') == '0px')
				$('abre_projetos').setStyle('display', '');
			else
				$('fset_projetos').getParent().setStyle('height','');
		}
	}).hide();

	slidePchaves = new Fx.Slide('fset_pchaves',
	{
		duration: 500,
		onComplete: function(e)
		{
			if ($('txt_palavraschave').getValue() == '') {
				$('abre_pchaves').setStyle('display', '');
				$('txt_palavraschave').value = pchaves_texto;
			} else
				$('txt_palavraschave').focus();
		}
	}).hide();

	$('abre_endereco').addEvent('click', function(e) {verificaFechaProjetos(); $('abre_endereco').setStyle('display', 'none'); slideEndereco.slideIn();});
	$('abre_projetos').addEvent('click', function(e) {$('abre_projetos').setStyle('display', 'none'); slideProjetos.slideIn();});
	$('abre_pchaves').addEvent('click', function(e) {verificaFechaProjetos(); $('abre_pchaves').setStyle('display', 'none'); slidePchaves.slideIn();});

	$('txt_endereco').addEvent('focus', function(e) {
		verificaFechaProjetos();
		if ($('txt_endereco').getValue() == endereco_texto)
		$('txt_endereco').value = '';
	});

	$('txt_endereco').addEvent('blur', function(e) {
		if ($('txt_endereco').getValue() == '')
			slideEndereco.slideOut();
	});

	$('txt_palavraschave').addEvent('focus', function(e) {
		verificaFechaProjetos();
		if ($('txt_palavraschave').getValue() == pchaves_texto)
			$('txt_palavraschave').value = '';
	});

	$('txt_palavraschave').addEvent('blur', function(e) {
		if ($('txt_palavraschave').getValue() == '')
		slidePchaves.slideOut();
	});
}

/******************************************/

function verificaFechaProjetos() {
	if (projSelecionados.length == 0)
		slideProjetos.slideOut();
}

/******************************************/

function AjustaTamanho() {

	var numWidthMap = $('td_barra').getStyle('display') != 'none' ? 282 : 22;
	var mapLoaded = (typeof(map) == 'object');

	if (mapLoaded)
    	var mapCenter = map.getCenter();

	/* Redimensiona elementos para caber na tela */
	$('map').setStyle('height',window.getHeight()-99);
	$('map').setStyle('width',window.getWidth()-numWidthMap);

	var gMapCoords = $('map').getCoordinates();
  	$('td_map').setStyle('width',gMapCoords.width+6);
	$('barra_lateral').setStyle('height',window.getHeight()-99);
	$('rodape').setStyle('width',window.getWidth()-16);

	if (mapLoaded) {
		map.checkResize();
		map.panTo(mapCenter);
	}

	/* Atualiza tamanho e posicao do link para expandir o mapa */
	refreshToggleBarra();

	/* Redimensiona as caixas da barra lateral */
	if (painelMaximizado == 'procura') {
		$('div_procura').setStyle('height',Math.round((window.getHeight()-242)));
		$('div_resultados').setStyle('height',0);
	} else {
		$('div_procura').setStyle('height',0);
		$('div_resultados').setStyle('height',Math.round((window.getHeight()-242)));
	}
	$('div_opcoes').setStyle('height',64);

	/* Redimensiona o box translucido sobre o Google Maps */
	if ($defined($('processando')))
		$('processando').setStyles(
		{
			'left':gMapCoords.left+1,
			'top':gMapCoords.top+1,
			'width':gMapCoords.width-2,
			'height':gMapCoords.height-2
		});

	/* Redimensiona a posição da caixa de projetos */
	AtualizaProjetosPos();

	/* Atualiza posicao do botao e caixa de legenda */
	atualizaLegendaPos();

	/* Atualiza a posicao da legenda dos estados */
	atualizaPosicaoLegenda();
}

/******************************************/

function CarregaEstados(e) {
	validaBusca();
	if ($('select_municipio')) {
		selMunicipio = $('select_municipio')
		selMunicipio.parentNode.removeChild(selMunicipio);
	}

	if ($('select_uf').getValue() != "0") {
		var ajaxMunicipio = new Ajax('includes/AjaxUf.php?UF=' + $('select_uf').getValue(),
		{
			method: 'get',
			onComplete: function(jsonResult)
			{
				var MunicipiosObj = eval("(" + jsonResult + ")");
				selMunicipio = new Element('select',
				{
					'id':'select_municipio',
					'name':'select_municipio'
				}).addEvent('change', function(e) {validaBusca()});

				optionMun = new Element('option', {'value':'0'})
					.setText('Todos os municípios')
					.injectInside(selMunicipio);

				for (i=0; i < MunicipiosObj.length; i++) {
					optionMun = new Element('option', {'value': MunicipiosObj[i].cod})
						.setText(MunicipiosObj[i].nome)
						.injectInside(selMunicipio);
				}
				selMunicipio.injectAfter($('select_uf'));
			}
		}).request();
	}
}

/******************************************/

function processandoToggle(funcao) {
	if ($defined($('processando'))) {
		var divProcessando = $('processando');
		divProcessando.effect('opacity',
		{
			duration:1000,
			transition:Fx.Transitions.linear,
			onComplete: function(e)
			{
				$('btn_busca').removeProperty('disabled');
				$('processando').remove();
				if ($type(funcao) == 'function')
					funcao();
			}
		}).start(0.75,0);
	} else {
		var gMap = $('map');
		var gMapCoords = gMap.getCoordinates();

		var divProcessando = new Element('div', {'id':'processando'})
			.setStyles(
			{
				'left':gMapCoords.left+1,
				'top':gMapCoords.top+1,
				'width':gMapCoords.width-2,
				'height':gMapCoords.height-2
			})
			.setOpacity(0)
			.injectAfter($('map'));

		$('btn_busca').setProperty('disabled','disabled');

		divProcessando.effect('opacity',
		{
			duration:1000,
			transition:Fx.Transitions.linear,
			onComplete: function(e)
			{
				if ($type(funcao) == 'function')
					funcao();
			}
		}).start(0,0.75);
	}
}

/******************************************/

function mouseProjetos(e) {
	e = new Event(e);
	var divTPCoords = $('div_todosprojetos').getCoordinates();

	if (e.page.x < divTPCoords.left+19)
		projetosToggle();
}

/******************************************/

function projetosToggle(acao) {

	AtualizaProjetosPos();

	if ($type(acao) != 'number') {
		if ($('div_projetos').getStyle('visibility') == 'hidden')
			acao = 1;
		else
			acao = 0;
	}

	if (acao) {
		if ($('div_projetos').getStyle('visibility') == 'hidden')
			$('div_projetos')
				.effect('opacity', {duration:1000, transition:Fx.Transitions.linear})
				.start(0,1);
	} else {
		if ($('div_projetos').getStyle('visibility') != 'hidden')
			$('div_projetos')
				.effect('opacity', {duration:1000, transition:Fx.Transitions.linear})
				.start(1,0);
	}
}

/******************************************/

function AtualizaProjetosPos() {

	var divTPCoords = $('div_todosprojetos').getCoordinates();
	var divProjetosCoords = $('div_projetos').getCoordinates();

	$('div_projetos').setStyles(
    {
		'left':divTPCoords.left-divProjetosCoords.width+2,
		'top':divTPCoords.top,
		'height':window.getHeight()-divTPCoords.top-27
	});
}

/******************************************/

function setClassificacao(nproj, limpa) {
	var txtTodosProjetos = 'Selecionar características';

	var divTPCoords = $('div_todosprojetos');
	$('div_classficacao_'+nproj).toggleClass('selecionado');

	if ($('div_projsel_'+nproj)) {
		projSelecionados.remove(nproj);
		$('div_projsel_'+nproj).remove();

		if (projSelecionados.length == 0) {
			divTPCoords.setText(txtTodosProjetos)
			if (limpa == 1)
				verificaFechaProjetos()
		}
	} else {
		if (projSelecionados.length == 0)
			divTPCoords.setText('')
		projSelecionados.include(nproj);

		var divProjetoAdd = new Element('div', {'id':'div_projsel_'+nproj})

		new Element('a', {'href':'javascript:setClassificacao('+nproj+',1)', 'title':'remover'})
			.setText('Remover')
			.injectInside(divProjetoAdd);

		divProjetoAdd
			.appendText($('div_classficacao_'+nproj).getText())
			.injectInside(divTPCoords);
	}

	AtualizaProjetosPos();
	validaBusca();
}

/******************************************/

function zera_legenda() {
	legenda['ponto'] = 0;
	legenda['pontao'] = 0;
	legenda['rede'] = 0;
}

/******************************************/
function ativaBuscaTelecentros(){
    buscaTelecentros(false)
}



function buscaTelecentros(return_url) {
	/* fazer validacao dos campos aqui */
	//if (!validaBusca())
		//return;
	zera_legenda();

    var url = ''


	if ($('select_uf').getValue() != 0)
		url += "uf="+$('select_uf').getValue();

	if ($('select_municipio'))
		if ($('select_municipio').getValue() != 0)
			url += "&cidade=" + $('select_municipio').getValue();

	if (lat != null && lon != null)
		url += '&lat=' + lat + '&lon=' + lon + '&ntelec=' + $('select_numtelecentros').getValue() + '&end=' + escape(end);

	if (projSelecionados.length) {
		url += "&classificacoes=";
		for (i=0; i<projSelecionados.length; i++)
			url+= projSelecionados[i]+"|";
		url = url.substring(0,url.length-1);
	}

	if ($('txt_palavraschave').getValue() != '' && $('txt_palavraschave').getValue() != 'palavras chave')
		url += "&pchave=" + escape($('txt_palavraschave').getValue());

    if(return_url)
        return url

	processandoToggle(function(e)
	{
		new Ajax("includes/AjaxBusca.php?"+url,
		{
			method: 'get',
			onComplete: processaPontos
		}).request();
	});
}

/******************************************/

function processaPontos(jsonData) {
	var jsonData = eval("(" + jsonData + ")");
	var municipio = '';
	var dr = $('div_resultados');
	var ulTag, liTag;

	limpaMapa();
	//criaLegenda(jsonData.legendas);

	dr.empty();

	/* feature_todo
	new Element('p', {'class':'resHeader'})
		.setText('Sua busca retornou ' + jsonData.markers.length + ' telecentros.')
		.injectInside(dr);
	*/

	if (jsonData.markers.length == 0)
		$('a_resultados').setText('nenhum resultado');
	else if (jsonData.markers.length == 1)
		$('a_resultados').setText(jsonData.markers.length + ' resultado');
	else
		$('a_resultados').setText(jsonData.markers.length + ' resultados');

	for (var i=0; i<jsonData.markers.length; i++) {
		if (jsonData.markers[i].mun != municipio) {
			if ($type(ulTag) == 'element')
				ulTag.injectInside(dr);

			municipio = jsonData.markers[i].mun
			new Element('p', {'class':'municipio'})
				.setText(municipio)
				.injectInside(dr);

			ulTag = new Element('ul', {'class':'resultados'});
		}

		liTag = new Element('li', {'class': jsonData.markers[i].ico });

		if (jsonData.markers[i].temAudio == 1) new Element('p', {'class':'audio', 'title':'Áudio na aba multimídia'}).setText(' ').injectInside(liTag);
        if (jsonData.markers[i].temWradio == 1) new Element('p', {'class':'wradio', 'title':'Link para programa na Webrádio'}).setText(' ').injectInside(liTag);
		if (jsonData.markers[i].temImagem == 1) new Element('p', {'class':'imagem', 'title':'Fotos na aba multimídia'}).setText(' ').injectInside(liTag);
		if (jsonData.markers[i].temVideo == 1) new Element('p', {'class':'video', 'title':'Vídeo na aba multimídia'}).setText(' ').injectInside(liTag);

		pontoLink = new Element('a', {'href':'javascript:abreBalao(' + jsonData.markers[i].id + ')', 'title':jsonData.markers[i].cod})
			.setText(jsonData.markers[i].nom)
			.injectInside(liTag);

		if (jsonData.markers[i].desc == '0')
			pontoLink.addClass('sem_desc');

		if (jsonData.markers[i].end != '') new Element('p').setText(jsonData.markers[i].end).injectInside(liTag);
		if (jsonData.markers[i].tel != '') new Element('p', {'class':'tel'}).setText(jsonData.markers[i].tel).injectInside(liTag);
		if (jsonData.markers[i].ema != '') new Element('p', {'class':'email'}).setText(jsonData.markers[i].ema).injectInside(liTag);

		liTag.injectInside(ulTag);
		criaPonto(jsonData.markers[i]);
	}

	criaLegenda();

	//alert(legenda['ponto']+' - '+legenda['pontao']+' - '+legenda['rede'] );

	if (jsonData.markers.length) {
		ulTag.injectInside(dr);
		ajustaMapaPontos();
	} else
		dr.setText('Sua busca não retornou resultados.');

	/* Esconde a mensagem de carregamento */
	processandoToggle(function(e) {MaxPainel('resultados');});
}

/******************************************/

function MaxPainel(painel) {
	var divBuscaHeight = $('div_procura').getStyle('height');
	divBuscaHeight = parseInt(divBuscaHeight.substring(0,divBuscaHeight.length-2));

	var divResultsHeight = $('div_resultados').getStyle('height');
	divResultsHeight = parseInt(divResultsHeight.substring(0,divResultsHeight.length-2));

	//if (painel == 'procura')
	if (divBuscaHeight == 0) {
		var divBuscaHeightFinal = divResultsHeight + divBuscaHeight;
		var divResultsHeightFinal = 0;
		painelMaximizado = 'procura';
	} else {
		var divResultsHeightFinal = divResultsHeight + divBuscaHeight;
		var divBuscaHeightFinal = 0;
		painelMaximizado = 'resultados';
	}

	new Fx.Elements($$('#div_procura', '#div_resultados')).start({
		'0': {'height': [divBuscaHeight,divBuscaHeightFinal]},
		'1': {'height': [divResultsHeight,divResultsHeightFinal]}
	});
}

/******************************************/

function defineEndOrigem(objEnd) {
	$('txt_endereco').value = objEnd.address;
	$('txt_endereco').setStyle('display','none');

 	var divEndereco = new Element('div', {'id':'end_definido'})
		.addEvent('click', function(e)
		{
			divEndereco.remove();
			$('txt_endereco').value = objEnd.address;
			$('txt_endereco').setStyle('display','');
			$('txt_endereco').focus();
			$('txt_endereco').select();
			map.removeOverlay(markCasa)
			markCasa = lat = lon = end = null;
			validaBusca();
		});

	new Element('a', {'id':'remEndOrigem', 'href':'javascript:void(0)'})
		.addEvent('click', function(e)
		{
			divEndereco.remove();
			$('txt_endereco').value = '';
			$('txt_endereco').setStyle('display','');
			slideEndereco.slideOut();
			map.removeOverlay(markCasa)
			markCasa = lat = lon = end = null;
			validaBusca();
		})
		.injectInside(divEndereco);

	divEndereco
		.appendText(objEnd.address)
		.injectAfter($('txt_endereco'));

	lat = objEnd.Point.coordinates[1];
	lon = objEnd.Point.coordinates[0];
	end = objEnd.address;

	$('div_numtelecentros').setStyle('display','');
	criaPontoCasa();
	validaBusca();
}

/******************************************/

function atualizaLegendaPos() {
	if ($('aLegenda') && $('ulLegenda')) {
		var gMapCoords = $('map').getCoordinates();

		$('ulLegenda').setStyle('display','');
		var ulLeCoords = $('ulLegenda').getCoordinates();
		if (!legendaFixa)
			$('ulLegenda').setStyle('display','none');

		var aLegCoords = $('aLegenda').getCoordinates();

		$('aLegenda').setStyles(
		{
			'left':gMapCoords.right - aLegCoords.width - 8,
			'top':gMapCoords.top + 34
		});

		$('ulLegenda').setStyles(
		{
			'left':gMapCoords.right - ulLeCoords.width - 8,
			'top':gMapCoords.top + aLegCoords.height + 34
		});
	}
}

/******************************************/

function CriaEndBusca(arquivo, hash) {

	var url = '';

	if ($('select_uf').getValue() != 0)
		url += "uf="+$('select_uf').getValue();

	if ($('select_municipio'))
		if ($('select_municipio').getValue() != 0)
			url += "&cidade=" + $('select_municipio').getValue();

	if (lat != null && lon != null)
		url += '&lat=' + lat + '&lon=' + lon + '&ntelec=' + $('select_numtelecentros').getValue() + '&end=' + escape(end);

	if (projSelecionados.length) {
		url += "&classificacoes=";
		for (i=0; i<projSelecionados.length; i++)
			url+= projSelecionados[i]+"|";
		url = url.substring(0,url.length-1);
	}

	if ($('txt_palavraschave').getValue() != '' && $('txt_palavraschave').getValue() != 'palavras chave')
		url += "&pchave=" + escape($('txt_palavraschave').getValue());

    if (hash && url != '')
        window.location.hash = '#'+url

	return arquivo + url;
}

/******************************************/

function validaBusca() {
	var limite = 1000;
	url = CriaEndBusca("includes/AjaxBusca.php?", true) + '&count=1';

	$('p_validacao')
		.setText('Contando itens...')
		.removeClass('exclamacao')
		.removeClass('ok')
		.removeClass('carregando')
		.addClass('carregando');

	new Ajax(url,
		{
			method: 'get',
			onComplete: function(e)
			{
				if (e > limite) {
					classEl = 'exclamacao';
					mensagem = 'Sua busca irá retornar ' + e + ' pontos.<br/> Para aparecer no mapa ela deve trazer menos de ' + limite + '.';
					submit = false;
            	} else if (e > 1) {
					classEl = 'ok';
					mensagem = 'Sua busca irá retornar ' + e + ' pontos.'
					submit = true;
				} else if (e == 1) {
					classEl = 'ok';
					mensagem = 'Sua busca irá retornar ' + e + ' ponto.'
					submit = true;
				} else {
					classEl = 'exclamacao';
					mensagem = 'Sua busca não retornará resultados.<br/>Por favor seja menos específico.'
					submit = false;
        	    }

				$('p_validacao')
					.setHTML(mensagem)
					.removeClass('exclamacao')
					.removeClass('ok')
					.removeClass('carregando')
					.addClass(classEl);

				if (submit) {
					$('btn_busca').removeProperty('disabled');
					return true;
				} else {
					$('btn_busca').setProperty('disabled','disabled');
					return false;
				}
			}
		}).request();
}


/******************************************/

function toggleBarraExportarCsv() {
    limpaBarraExportar()
	aplicaToggleExportar($('div_exportar_csv'))
}
function toggleBarraExportarImprimir() {
    limpaBarraExportar()
    aplicaToggleExportar($('div_exportar_imprimir'))
}
function aplicaToggleExportar(div){
    if (div.getStyle('visibility') == 'hidden')
		div.effect('opacity', {duration:500, transition:Fx.Transitions.linear}).start(0,1);
	else
	    apagaBarraExportar(div)
}
function limpaBarraExportar(){
    apagaBarraExportar($('div_exportar_csv'))
    apagaBarraExportar($('div_exportar_imprimir'))
}
function apagaBarraExportar(div){
    div.effect('opacity', {duration:0, transition:Fx.Transitions.linear}).start(1,0);
}

function exportarResultadosCsv(){
    var url = base_url+'includes/DownloadCsv.php?'+buscaTelecentros(true)
    window.open(url, "Window1", "menubar=no,toolbar=no")
}
function exportarResultadosImprimir(){
    var url = base_url+'includes/Imprime.php?'+buscaTelecentros(true)
    window.open(url, "Window2")
}

/******************************************/
