function QueryString(variavel)
{
    return qs[variavel.toUpperCase()];
}

function getIndexSelect(obj,value)
{
	//P1: Objecto select (document.getElementById('objName'));
	//P2: Valor seleccionado.
	for (i = 0; i < obj.length; i++)
	{
		if ( obj.options[i].value == value) return i ;
	}
	return 0;
}

function getFrameSize()
{
	var frameWidth = 0;
	var frameHeight = 0;

	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
				
	return  {"frameWidth":frameWidth,"frameHeight":frameHeight};
}

function resizeWindow(width,height)
{
	if (document.all)
	{						
 		top.window.resizeTo(width,height);
	}
	else if (document.layers||document.getElementById)
	{
 		top.window.outerHeight = height;
 		top.window.outerWidth = width;
  	}
}

//DC - Ago08 - usar vars globais para tamanho da janela CdE
//             e centrar a janela em vez de mover para 0,0
function maxWindow()
{
	var frm = getFrameSize();

	if (frm.frameWidth < mWid || frm.frameHeight < mHei)
	{

		//top.window.moveTo(0,0);
			
		if (screen.availWidth <= 1024 || screen.availHeight <= 768)
		{
		    //alert("janela <1024x768... resize total e moveto 0,0");
		    top.window.moveTo(0,0);
			resizeWindow(screen.availWidth,screen.availHeight);
		}
		else
		{
			var tmpWidth = 1024;
			var tmpHeight = 768;
			
			resizeWindow(tmpWidth,tmpHeight);
				
			frm = getFrameSize();
			//alert("frameseize:" + frm.frameWidth + ";" + frm.frameHeight);
				
			tmpWidth = mWid + (tmpWidth - frm.frameWidth);
			tmpHeight = mHei + (tmpHeight - frm.frameHeight);
			
			//alert("resize feito:" + tmpWidth + ";" + tmpHeight);		
			resizeWindow(tmpWidth,tmpHeight);
		
		    var xwin = (screen.availWidth/2)-(tmpWidth/2); var ywin = (screen.availHeight/2)-(tmpHeight/2);
		    //reajustar mais junto ao topo
		    ywin = ywin/2;
		    if (xwin <0) xwin=0; if (ywin <0) ywin=0;
		    //alert("ecra >1024x768, moveto calculado: " + xwin + ";" + ywin);	
			top.window.moveTo(xwin,ywin);
		}	
	}
				
	frm = getFrameSize();

	if (frm.frameWidth < mWid || frm.frameHeight < mHei)
	{
		IDT_MOUSE = { "clientX":480, "clientY": 295 };
		doTooltip(IDT_MOUSE, "Informação", "A janela aberta não tem as dimensões necessárias para visualizar toda a informação.<br><br>Para poder navegar correctamente, aumente a resolução do monitor, maximize a janela, desligue as barras de ferramentas ou escolha o modo ecrã inteiro (F11).");
	}
}


//Inicialização
function Init()
{
	//Ajuda no tab inferior
	buttonClick(toolbar_id)

	if (QueryString("debug"))
	{
		mDebug =true;
		toggleonoff('logArea',"ON");
	}
	defIdioma(); //define var global com PT, EN (_Idioma)
			
	//imagem de aguardar logo de inicio!
	toggleWait('ON');
	//definir eventos globais!
	document.getElementById("theMap").onmousedown = mouseDown;
	document.onmouseup = mouseUp;
	document.onmousemove = mouseMove;
	//document.getElementById("theMap").onmousemove = mouseMove;
	document.getElementById("theMap").onmouseover = mouseOver;
	offsetX = document.getElementById("theMap").offsetLeft;
	offsetY = document.getElementById("theMap").offsetTop;
	//sincronizar a tool activa com o eventos do rato
	setMapEvent(toolbar_id)
			
	//$('Panel_1_Content').innerHTML = '';
	//setup: todos os requests ajax devem ligar o loading
	var myGlobalHandlers = {onCreate: function(){hideTipNow();toggleWait('on');}};
	Ajax.Responders.register(myGlobalHandlers);
	//Instanciação de efeitos
	//fxAltura = new fx.Height('Panel_1_Bar', {duration: 400});
	//fxDesap = new fx.Opacity('Panel_1_Content', {duration: 400});
	//definições do mapa principal
	mMapa = new clsMapa('theMap','MAP');  //indicamos o div e a img
	//definições dos objectos persistentes
	//mPers = new clsPers(); 
												
	var menu = arvoreTemas();
	var theme = arvoreTheme(); //obter grafismo
	drawTree ('arvTemas', 'CARTOGRAFIA DO DISTRITO', menu, theme);  //desenhar
	//Alterar os checkboxs
	replaceChecks();


	//dnc1.1 - efeito do div resultados da pesquisa
	fxPesqRes = new fx.Height('Panel_PesquisaPI_Res', {duration: 400});	
	fxPesqResProx = new fx.Height('Panel_PesquisaProx_Res', {duration: 400});	
	$('Panel_Bottom_0_Content').style.width = $('Instrucoes').offsetWidth-10;
	fxInstr = new fx.Width('Panel_Bottom_0_Content',{duration:200});
	//dnc1.2 - efeito ovmap
	ovFx = new fx.Opacity('mapaEnq', {duration: 300});
	//ovFx.setOpacity(0);
	//toggleonoff('mapaEnq','ON');

	pedeDados("LISTACONCELHOS");
	pedeDados("LISTAPERCURSOS");
	preencheCategoria("Sel_Pesq_Cat");
	preencheCategoria("Sel_PesqProx_Cat");
	//criarPercursos();			
	
	if (QueryString("concelho"))
	{
		setLeftPanel('2');
		pedeMapa("CONCELHO",{"concelho":QueryString("concelho")});
	}
	else if (QueryString("rect"))
	{
		setLeftPanel('2');	
		var obj = QueryString("rect").replace(/{/gi,'{"').replace(/}/gi,'"}').replace(/:/gi,'":"').replace(/,/gi,'","')
		obj = JSON.parse(obj);
		//alert("xmin:" + obj.xmin + "\n" + "ymin:" + obj.ymin + "\n" + "xmax:" + obj.xmax + "\n" + "ymax:" + obj.ymax)
			
		pedeMapa("RECT",{"xmin":obj.xmin,"ymin":obj.ymin,"xmax":obj.xmax,"ymax":obj.ymax});	
	}
	else if (QueryString("freguesia"))
	{
		setLeftPanel('2');
		pedeMapa("FREGUESIA",{"freguesia":QueryString("freguesia")});			
	}
	else
	{
		if (QueryString("func"))
		{
			if (QueryString("func").toUpperCase() == "PERCURSO")
			{
				var perc = QueryString("perc");
				//alert(perc);
				ID_PERCURSO = perc;
				//$("Sel_Perc_Cat").selectedIndex = perc;
				mMapa.persist.updatePercurso(perc);
				setLeftPanel('8');
				buttonClick("PERCURSO")
				pedeMapa("PERCURSO",{"perc":perc});
			}
			else if (QueryString("func").toUpperCase() == "PROX")
			{
				consPI();
				setLeftPanel('1');
				setBottomPanel('1');
				idtema = QueryString("idtema");
				idtemaalvo = QueryString("idtemaalvo");
				ligarTemaSubCat(getIdAxl(idtema))
				ligarTemaSubCat(getIdAxl(idtemaalvo))

				//updateVisibleLayers();
				mMapa.persist.updatePesquisaProximidade('','',idtemaalvo,QueryString("dist"),QueryString("idsig"));
				pedeMapa('PESQUISARPROXIMIDADE',{"subcat":idtemaalvo,"bff":QueryString("dist"),"idsig":QueryString("idsig"),"subcattema":idtema});
				
			}
			else if (QueryString("func").toUpperCase() == "CONTEUDO")
			{
				//alert("OK")

				consPI();
				$("Sel_Pesq_Cat").selectedIndex = getIndexSelect($("Sel_Pesq_Cat"),QueryString("idtema").substr(0,2))
				//alert(getIndexSelect($("Sel_Pesq_Cat_Sub"),0101))
				preencheSubCategoria("Sel_Pesq_Cat")
				$("Sel_Pesq_Cat_Sub").selectedIndex = getIndexSelect($("Sel_Pesq_Cat_Sub"),QueryString("idtema"))

				mMapa.persist.updatePesquisaPI('%','QueryString("idtema")','',QueryString("idsig"));

				setLeftPanel('1');
				idtema = QueryString("idtema");
				ligarTemaSubCat(getIdAxl(idtema));
				mMapa.persist.updatePesquisaPI('',idtema,'',QueryString("idsig"));
				pedeMapa('PESQUISARPI',{"subcat":idtema,"idsig":QueryString("idsig")});						
			}
		}
		else
		{
			mMapa.actualizaImg("imagens/mapa/webgis_dummy_map.png")

			setLeftPanel('2');
			setTool('INIT');
			buttonClick(toolbar_id);
			pedeDados("INITDADOS");
		}
	}	
												
	Tooltip.init();
				
	addBtnTitle();

	maxWindow();
								
	return;
}
							
function debugPedirAJAX()
{
	window.status='A pedir: ' + toolbar_id;
}
			
function debugTexto(strTexto)
{
	if (debug) new Insertion.Bottom("Panel_1_Content", strTexto);
	//$("Panel_1_Content").innerHTML += strTexto;
}

function toggleWait(strOnOff)
{
	toggleonoff('aguarde',strOnOff.toUpperCase());
}
///////////////////////////////////////////////////////////////////////////
// Methods for debug logging
//
// To use these, add a div with id="logArea" to your page.
	
function log(m) 
{
	if (mDebug) 
	{
		var l = $("logArea");
	    	if (l) 
	    	{ 
	    		//new Insertion.Bottom("logArea", m + '<br/>');
			$("logArea").innerHTML += m + '<br/>';
		}
  	}
}

function openCloseMapaEnquadramento(obj)
{
	var cn = obj.className.split(" ")

	if (cn[1] == "openEnq")
	{
		obj.className = "enquadramento closeEnq";
		obj.title="Abrir mapa de enquadramento";
		ovFx.custom(1,0);
					
	}
	else
	{
		obj.className = "enquadramento openEnq";
		obj.title="Fechar mapa de enquadramento";
		ovFx.custom(0,1);
	}
	
	return false;	
}
			
function actualizarMapa(e)
{
	var evt = e || event;

	x = evt.clientX - 901;
	y = evt.clientY - 454;
				
	xmin = mMapa.width * x / -58;
	ymin = mMapa.height * y / -38;
				
	pedeMapa('PAN',{"x":xmin,"y":ymin});
}
			
//DC - Ago08 - actualizado para usar Base64 nos urls e evitar problemas com {} nos emails
function enviaMail()
{
	var sMail; var sArgs; var sUrl; var sTmp; var iIdx;
	sArgs = mMapa.getMailArgs();
	log("Mail sArgs: " + sArgs);
	sArgs = Base64.encode(sArgs);
	sUrl = 'http://' + window.location.host;
	sTmp = window.location.pathname;
	iIdx = sTmp.lastIndexOf('/');
	sTmp = sTmp.substring(0,iIdx+1);
	sUrl += sTmp + 'cde_proxy.html?mapaCdE=' + sArgs;
	//sUrl = escape( '<a href="' + sUrl + '">Link para Mapa no Caminhos de Évora</a>');
	if (document.all)  //para o IE não se usa escape
	{
	   sMail = '<' + 'escolha um endereço'  + '>'
	        + '?subject=' + 'Vê este mapa no site Caminhos de Évora' 
	        + '&body=' + 'A ligação para o mapa que quero mostrar é:' + '%0A%0A'
		    + sUrl
	        + '%0A%0A%0A%0A';
			/*+ 'Não te esqueças de ligar os seguintes Temas:' + '%0A%0A%0A%0A'
			+ '<indique aqui os temas que deseja indicar>';*/
	}
	else
	{
	    sMail = '<' + escape('escolha um endereço')  + '>'
	        + '?subject=' + escape('Vê este mapa no site Caminhos de Évora') 
	        + '&body=' + escape('A ligação para o mapa que quero mostrar é:') + '%0A%0A'
		    + escape(sUrl)
	        + '%0A%0A%0A%0A';
			/*+ escape('Não te esqueças de ligar os seguintes Temas:') + '%0A%0A'
			+ escape('<indique aqui os temas que deseja indicar>');*/
	}
	log("Mail: " + sUrl);
	return sMail;
}

//DC - Ago08 - usar vars globais para tamanho da janela CdE
function abreCdE(sUrl)
{
	var posx = parseInt(screen.width/2-(mWid/2));
	var posy = parseInt(screen.height/2-(mHei/2)-25);
	self.resizeTo(mHei,mWid);
	self.moveTo(pox,posy);
	self.focus();
}

//DC - Ago08 - usar vars globais para tamanho da janela CdE
function imprimir()
{
	var url = "print.html?";
	   
	url += "map=" +mMapa.mapaImg.src + "&";
	url += "legend=" + mMapa.legendSrc + "&";
	url += "escalaNumerica=" + $("escalaNumerica").innerHTML + "&";
	url += "escalaGrafica=" + $("escalaGrafica").innerHTML;

	var posx = parseInt(screen.width/2-(mWid/2));
	var posy = parseInt(screen.height/2-(mHei/2)-25);
	var sWinPos = "screenX=" + posx + ",left=" + posx + ",screenY=" + posy + ",top=" + posy + ",";
	var sOpcoes = "height=" + mHei + ",innerHeight=" + mHei + ",width=" + (mWid+10) + ",innerWidth=" + (mWid+10) + ",scrollbars=no,resizable=yes'";
	var wincde = window.open(url,"winCDE", sWinPos + sOpcoes, true);
	wincde.focus();
}
