var baseURL = "http://"+document.location.host+"/maps";
var datasource_name = "geoportalvalimar";

var objMapa = null;
var objPesq = null;
var objBloq = null;
var winMeassure = null;
var winRotas = null;

var themeGeoSelect = null;
var loadSucCont = 0;
var loadSuc = true;


function createButton(idBtn, iconImg, tooltipTxt, onClick, mapTool) {
	var btn = new Ext.Button({id: idBtn, icon: iconImg, cls: 'x-btn-icon', tooltip: tooltipTxt, enableToggle: mapTool });
	btn.setHandler(onClick);
	return btn;
};

function testePDFReader() {
	var acrobat=new Object();
	acrobat.installed=false;
	acrobat.version='0.0';

	if (navigator.plugins && navigator.plugins.length) {
		for ( var x = 0, l = navigator.plugins.length; x < l; ++x ) {
			if ((navigator.plugins[x].description.indexOf('Adobe Acrobat') != -1) || (navigator.plugins[x].description.indexOf('Adobe PDF Plug-In') != -1))	{
				acrobat.version=parseFloat(navigator.plugins[x].description.split('Version ')[1]);
				if (acrobat.version.toString().length == 1) acrobat.version+='.0';
				acrobat.installed=true;
				break;
			}
		}
	} else if (window.ActiveXObject) {
		for (x=2; x<10; x++) {
			try	{
				oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
				if (oAcro) {
					acrobat.installed=true;
					acrobat.version=x+'.0';
				}
			}
			catch(e) {}
		}
		try	{
			oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
			if (oAcro4) {
				acrobat.installed=true;
				acrobat.version='4.0';
			}
		}
		catch(e) {}
		try {
			oAcro7=new ActiveXObject('AcroPDF.PDF.1');
			if (oAcro7) {
				acrobat.installed=true;
				acrobat.version='7.0';
			}
		}
		catch(e) {}
	}
	return acrobat.installed;
};
	
Ext.onReady(function(){
	var params_pesq_Panel = { id:'params_pesquisa', region:'north', contentEl:'pesquisaParams', border:false, autoScroll: false };
	var results_pesq_Panel = { id:'results_pesq', region:'center', contentEl:'pesquisaResults', border:false, autoScroll:true };

	var viewport = new Ext.Viewport({
		layout:'border',
		items:[
			{ region:'north', contentEl:'cabecalho', split:false, border:false, height: 90, collapsible: false, margins:'10 10 5 10',
			    bodyStyle:'background:transparent url(images/imgTop.png) no-repeat right top'},
			{ region:'west', id:'west-panel', title:'Geoportal Valimar', split:true, width: 340, minSize: 200, maxSize: 600, collapsible: true,
				margins:'0 0 0 10', layout:'accordion', renderHidden:true, sequence:true, layoutConfig:{ animate:true }, items: [
					{ contentEl:'legend', title:'Legenda', border:false, autoScroll:true,	iconCls:'legendaTur'},
					/*{ contentEl:'legendaTecnica', title:'Território', border:false, autoScroll:true, iconCls:'legendaTec' },*/
					{ title:'Pesquisa', layout:'border', border:false, autoScroll:false, iconCls:'pesquisaTab', items: [params_pesq_Panel, results_pesq_Panel]}]
			},
			{ region:'center', contentEl:'center', margins:'0 10 0 0', cls:'empty', bodyStyle:'background:#ffffff' },
			{ region:'south', contentEl: 'rodape', split:false, border:false, height: 31, collapsible: false, margins:'5 10 10 10' }
		]
	});
	Ext.QuickTips.init();
		
	var tb = new Ext.Toolbar({autoHeight:true});
    tb.render('toolbar');
	
	var btnFullExt = createButton('btnFullExt', 'icons/full_extent.gif', 'Ver mapa completo', btnClick, false);
	var btnMetro = createButton('btnMetro', 'icons/metro.gif', 'Medir distância no mapa', btnClick, false);
	var btnArea = createButton('btnArea', 'icons/area.gif', 'Medir área no mapa', btnClick, false);
	var btnPrint = createButton('btnPrint', 'icons/print.gif', 'Imprimir mapa', btnClick, false);
	var btnRotas = createButton('btnRotas', 'icons/rotas_ico.png', 'Lista de rotas', btnClick, false);
	tb.add( btnFullExt, '  ', btnMetro, '  ', btnArea , '  ', btnPrint, '  ', btnRotas );
	
	function btnClick(item) {
		switch(item.id) {
			case 'btnFullExt':
				_GEO.divMap.zoomExtent();
			break;
			case 'btnMetro':
				startMessuare(true);
			break;
			case 'btnArea':
				startMessuare(false);
			break;
			case 'btnPrint':
				if (!objBloq) objBloq = new bloquearWin();
				if (testePDFReader()) {
					var html = '<div id="frmPrint" style="border: 1px solid #cccccc; width:100%; height:auto;"><div class="tilulo"><img hspace="4" height="14" border="0" align="absmiddle" width="14" vspace="2" src="images/printer.gif"/> Imprimir</div><table width="100%" border="0" cellspacing="10" cellpadding="0"><tr><td class="label">Titulo:</td><td colspan="2"><input class="inputText" type="text" id="txtTitulo" /></td></tr><tr><td class="label">Sub-titulo:</td><td colspan="2"><input class="inputText" type="text" id="txtSubTitulo" /></td></tr><tr><td class="label" width="135">Orienta&ccedil;&atilde;o da p&aacute;gina:</td><td align="center"><input type="radio" value="landscape" id="pageOrient" name="pageOrient" checked="checked" /> <img src="images/land.gif" width="16" height="16" /></td><td align="center"><input type="radio" value="portrait" id="pageOrient" name="pageOrient" /><img src="images/port.gif" width="16" height="16" /></td></tr><tr><td>&nbsp;</td><td><input type="button" onfocus="this.blur();" value="Cancelar" id="btnCancel" class="Button" style="background-image:url(images/cancel.gif)" /></td><td><input type="button" onfocus="this.blur();" value="Imprimir" id="btnPrintOk" class="Button" style="background-image:url(images/printer.gif)" /></td></tr></table></div>';
					objBloq.openPopup(html);
		
					$('#btnCancel').click(function() { objBloq.desbloquear(); });
					$('#btnPrintOk').click(function() {
						_GEO.divMap.printMap($('#txtTitulo')[0].value, $('#txtSubTitulo')[0].value, ($('#pageOrient')[0].checked?'ls':'pt'));
						objBloq.desbloquear();
					});
				} else {
					objBloq.showMessage('<div style="margin:20px;"><img src="images/error.gif"/><br/><br/>Para aceder a esta funcionalidade necessita de um visualizador de ficheiros no formato PDF... <br/><br/><a href="http://www.adobe.com/pt/" target="_blank"><img alt="Get Adobe Reader" src="images/get_adobe_reader.gif"/></a><br/><br/><br/><input class="botao" type="button" onfocus="this.blur();" value="OK" onclick="objBloq.desbloquear();"/></div>');
				}
			break;
			case 'btnRotas':
				winRotas.show();
			break;		
			default:
			break;
		}
    }
});

if(jQuery) {
    var _GEO = null;
	
	// Inicializa valores para os browsers antigos
	var winW = 630, winH = 460;
	function winResize() {
		// Atribui os valores conforme o browser
		if (parseInt(navigator.appVersion)>3) {
			// Firefox, NetScape
			if (navigator.appName=="Netscape") { winW = window.innerWidth; winH = window.innerHeight; }
			// Internet Explorer
			if (navigator.appName.indexOf("Microsoft")!=-1) { winW = document.body.offsetWidth; winH = document.body.offsetHeight; }
		}		
		if (winW < 950 || winH < 600) {
			$("div.msgAlertResolucao").show();
		} else { $("div.msgAlertResolucao").hide(); }
	};
		
	$(document).ready( function() {
			window.onresize = winResize; winResize();
			objBloq = new bloquearWin();
			objBloq.bloquear('<div align="center"><br /><img src="images/large_loading.gif"/><br/><br/>A inicializar...<br/><br/></div>');
			
			// Controlo de Tabs da pesquisa
			$('#tabPesqAlf').click(function() { $("#pesquisaParamsGeo").hide();	$("#pesquisaParamsAlf").show();	$('#tabPesqGeo').removeClass('btn-tipo-pesq-sel'); $('#tabPesqAlf').addClass('btn-tipo-pesq-sel'); });
			$('#tabPesqGeo').click(function() { $("#pesquisaParamsAlf").hide(); $("#pesquisaParamsGeo").show(); $('#tabPesqAlf').removeClass('btn-tipo-pesq-sel'); $('#tabPesqGeo').addClass('btn-tipo-pesq-sel'); });
	});
	
	function verificaBrowser() {
		var bVersion = parseFloat(jQuery.browser.version);
		if(!(($.browser.msie && bVersion >= 6.0) || ($.browser.mozilla && bVersion >= 1.8) || ($.browser.safari && bVersion >= 525))){ 
			objBloq.showMessage('<div style="margin:20px;" align="left"><div style="font-weight: bold;font-size: 16px;color: #333333;background:url(images/error.gif) no-repeat;height: 46px;line-height: 46px;"><span style="vertical-align: middle; margin-left:50px;">Aviso</span></div><p style="color:#333333;font-size:12px;">Este geoportal n&atilde;o foi optimizado para o Web Browser que est&aacute; a utilizar. Nem todas as funcionalidades poder&atilde;o funcionar correctamente... Por favor, utilize um dos seguintes Web Browers:</p><ul style="color:#333333;font-size:12px;"><li>Mozila Firefox, vers&atilde;o 2.0 ou superior;</li><li>Safati for Macintosh, vers&atilde;o 3.1 ou superior; </li><li>Internet explorer, vers&atilde;o 7.0 ou superior;</li></ul><div align="center"><a href="http://www.mozilla-europe.org/" target="_blank"><img border="0" src="images/get_ffx.gif" alt="get firefox" style="padding-right:10px;" /></a><a href="http://www.apple.com/safari" target="_blank"><img border="0" src="images/get_safari.gif" alt="get firefox" style="padding-right:10px;" /></a><a href="http://www.microsoft.com/windows/products/winfamily/ie/default.mspx" target="_blank"><img border="0" src="images/get_ie7.gif" alt="get ie7" /></a></div><div align="center" style="padding-top:20px;"><input class="botao" type="button" value="Ok" onfocus="this.blur();" onclick="objBloq.desbloquear();"/></div></div>');
		}
	};
	
	function startMessuare(dist) {
		if (dist) {
			winMeassure.setTitulo('Dist&acirc;ncia');
			$("#divMeasureWin_rodape").html("Para medir uma dist&acirc;ncia, desenhe uma linha no mapa inserindo pontos.");
			$("#MeasureVal").html("0 metros");
			_GEO.divMap.startMeasureDistance(function(dist) { $('#MeasureVal').html(dist);},'DISTANCIA', 'C.DISTANCE', 'MARCA_DIST');
		} else {
			winMeassure.setTitulo('&Aacute;rea');
			$("#divMeasureWin_rodape").html("Para medir uma &aacute;rea, delimite a &aacute;rea no mapa inserindo pontos. Para terminar clique sobre o primeiro ponto inserido.");
			$("#MeasureVal").html("Perímetro: 0 metros<br/>Área: 0 m&sup2;");
			_GEO.divMap.startMeasureArea(function(area) { $('#MeasureVal').html(area);} ,'DISTANCIA', 'C.AREA', 'MARCA_DIST');
		}
	};
	
	function loadFinish(sucesso)
	{
		if (!sucesso && loadSuc) {
			loadSuc = false;
			objBloq.desbloquear();
			//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Problemas na inicializa&ccedil;&atilde;o deste geoportal...<br/><br/><input class="botao" type="button" value="Tentar novamente" style="width:120px;" onfocus="this.blur();" onclick="window.location.reload(true);" /><br/><br/></div>');
			objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>De momento, não foi possível apresentar esta página. Tente novamente dentro de momentos...<br/><br/><input class="botao" type="button" value="Tentar novamente" style="width:120px;" onfocus="this.blur();" onclick="window.location.reload(true);" /><br/><br/></div>');
//			objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Problemas de comunica&ccedil;&atilde;o...<br/><br/><br/><div align="center"><input class="botao" type="button" value="Tentar novamente" style="width:120px;" onfocus="this.blur();" onclick="window.location.reload(true);"/></div><br/></div>');
		}
		else if (loadSuc) loadSucCont++;
		
		if (loadSucCont==3) { objBloq.desbloquear(); verificaBrowser(); }
	};
	
	function onLoadPag(afterLoadMap, showRotas) {
		objMapa = new geo('map', 'legend', afterLoadMap);
		objPesq = new pesquisa('pesquisaParamsAlf', 'pesquisaParamsGeo', 'pesquisaResults', objMapa, loadFinish);
		//criar janela de apresentacao de resultados de medidas
		var conteudo = '<div style="margin:5px;"><div style="height:40px;" id="MeasureVal">&nbsp;</div></div>' +
			'<div id="btnNewM" style="width:64px; cursor:pointer; border:1px solid #cccccc; text-align:center; background-color:#D1E5B9;position:absolute;right:2px;top:22px;z-index:1;font-size:9px;">Medir de novo</div>' +
			'<div id="divMeasureWin_rodape">&nbsp;</div>';
		winMeassure = new mWindow('divMeasureWin', '', conteudo, ['btnMetro','btnArea'], 430, 110, 250, 'images/close.gif', '#D1E5B9', '#025B8C', 0.95, function(){ _GEO.divMap.stopMeasuring(null); });
		$("div#btnNewM").click( function(){ if (_GEO.divMap.getMeassState()==1){startMessuare(true);}else if(_GEO.divMap.getMeassState()==2){startMessuare(false);}});
						
		// lista de rotas
		$.ajax({
			type: "POST",
			url: "geo/getListRotas.jsp",
			dataType: "json",
			cache: false,
			async: true,
			success: function(data){
				createWinRotas(data.rotas, showRotas!=undefined && showRotas!=null && showRotas);
				loadFinish(true);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					loadFinish(false);
			}
		}); 
	};
	
	function createWinRotas(listRotas, show) {
		var htmlListRotas = '';
		for (var rt in listRotas) {
			if ( listRotas[rt].nome != undefined) {
				if (listRotas[rt].nome){
					var stl = (listRotas[rt].tp?"rt"+listRotas[rt].tp+".gif":null);
					htmlListRotas += "<li style='list-style:"+(stl?"url(images/"+stl+") ":"")+"circle; -moz-user-select:none;margin-bottom:2px;'><a id=\"" + listRotas[rt].id + "\" href=\"javascript:void(0)\" onclick='_GEO.viewAreaInMap(\"VROTAS_NEW\"," + listRotas[rt].id  + "," + listRotas[rt].area.xmin + "," + listRotas[rt].area.ymin + "," + listRotas[rt].area.xmax + "," + listRotas[rt].area.ymax + "," + listRotas[rt].centro.x + "," + listRotas[rt].centro.y + ")'>" + listRotas[rt].nome + "</a></li>";
				}
			}
		}
		htmlListRotas = "<ul style='margin:0px; padding-left: 16px;'>" + htmlListRotas + "</ul>";
		htmlListRotas = '<div style="width:100%; height:300px; overflow-y:auto; overflow-x:none;">' + htmlListRotas + '</div>';
		winRotas = new mWindow('divOtrRotas', 'Rotas', htmlListRotas, null, $(window).width()-230, 150, 210, 'images/close.gif', '#D1E5B9', '#025B8C', 0.95, null);
		if (show) winRotas.show();
	};
	
	function geo(divMapId, divLegId, afterLoadMapa){
		this.divLeg = $("div#"+divLegId);
		this.divMap = $("div#"+divMapId);
		this.afterLoadMapa = (afterLoadMapa)?afterLoadMapa:null;
				
		this.urlGetMapData = "geo/get_mapa.jsp";
		this.urlGetInfoPOI = "geo/getInfoPOI.jsp";
		this.loadMessage = "A carregar...";
	
		this.divLeg.html('<div class="loading">' + this.loadMessage + '</div>');
		this.inicGeo();
	};
			
	geo.prototype.inicGeo = function() {
		_GEO = this;
		_GEO.temas = new Array();
		
		$.ajax({
			type: "POST",
			url: _GEO.urlGetMapData,
			dataType: "json",
			cache: false,
			async: true,
			success: function(data){
				var dados = data;
				if (dados.erro == undefined) {
					// iniciar legenda
					_GEO.divLeg.mLeg({ dsSymb: datasource_name,	baseURL: baseURL, onThmChk: changeThemeChecked });
					_GEO.divLeg.inicLeg(dados.temas);
					
					// iniciar mapa
					_GEO.divMap.mMap({
						dataSource: datasource_name,
						baseURL: baseURL,
						copyRightNote: "&#169;2008 Valimar Digital",
						overView: (dados.overviewMap!=undefined ? dados.overviewMap : false),
						zoomLevelChangeCallBack: zoomLevelChangeEvt,
						onMapMouseMoveCallBack: onMouseMoveEvt,
						mErrorHandler: onError
					});
					_GEO.mapView = _GEO.divMap.iniMapWithLimits(dados.mapas, dados.limGeo.xmin,dados.limGeo.ymin,dados.limGeo.xmax,dados.limGeo.ymax, dados.nEscala);
					//_GEO.mapView = _GEO.divMap.iniMapWithCenter(dados.mapas, -59200, 223000, dados.nEscala);
					
					createThemes(dados.temas); addThemesToMap();
					zoomLevelChangeEvt(0,0,dados.nEscala[0]);
					if (_GEO.afterLoadMapa!=null) _GEO.afterLoadMapa(_GEO);
					
					loadFinish(true);
				}
				else {
					loadFinish(false);
					//objBloq.desbloquear();
					//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Problemas de comunica&ccedil;&atilde;o...<br/><br/><br/><div align="center"><input class="botao" type="button" value="Tentar novamente" style="width:120px;" onfocus="this.blur();" onclick="window.location.reload(true);"/></div><br/></div>');
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					loadFinish(false);
					//objBloq.desbloquear();
					//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Problemas na inicializa&ccedil;&atilde;o deste geoportal...<br/><br/><input class="botao" type="button" value="Tentar novamente" style="width:120px;" onfocus="this.blur();" onclick="window.location.reload(true);" /><br/><br/></div>');
				}
		});
		
		function createThemes(temas) {
			for (var t in temas) {
				var tema = temas[t];
				if (tema.nome != undefined) {
					if ((tema.grp != undefined) && (tema.grp == true)) { // um grupo
						createThemes(tema.temas);
					} else { // um tema
						var chk = (tema.checked != undefined) && (tema.checked == true);
						var minZLev = (tema.minZLevel != undefined ? tema.minZLevel : -1);
						var maxZLev = (tema.maxZLevel != undefined ? (tema.maxZLevel>minZLev ? tema.maxZLevel : -1) : -1);
						// criar BaseMap
						if (tema.tipoMapa != undefined && tema.tipoMapa.isBM != undefined && tema.tipoMapa.isBM == true) {
							tema.BaseMap = new MVMapTileLayer(datasource_name + "." + tema.id);
							if (minZLev >= 0 && maxZLev > 0) tema.BaseMap.setVisibleZoomLevelRange(minZLev, maxZLev);
							if (!chk) tema.BaseMap.setVisible(false);
							tema.pos=_GEO.divMap.addMapTileLayer(tema.nome, tema.BaseMap, null);
						}
						// criar FOIs
						else if (tema.tipoMapa != undefined && tema.tipoMapa.isFOI != undefined && tema.tipoMapa.isFOI == true) {
							tema.ThemeBasedFoi = new MVThemeBasedFOI(tema.id, datasource_name + "." + tema.id);
							if (tema.sub_temaId != undefined)
								tema.ThemeBasedFoiSub = new MVThemeBasedFOI(tema.sub_temaId, datasource_name + "." + tema.sub_temaId);
								
							if (!chk) {
								tema.ThemeBasedFoi.setVisible(false);
								if (tema.sub_temaId != undefined) tema.ThemeBasedFoiSub.setVisible(false);
							}
							if (tema.Clickable != undefined && tema.Clickable == true) {
								tema.ThemeBasedFoi.setClickable(true);
								tema.ThemeBasedFoi.setEventListener("mouse_click", function (point,foi) { _GEO.foiClick (this.name, null, point, foi.attrs[0]); } );
								
								if (tema.sub_temaId != undefined) {
									tema.ThemeBasedFoiSub.setClickable(true);
									tema.ThemeBasedFoiSub.setEventListener("mouse_click", function (point,foi) { _GEO.foiClick (this.name, null, point, foi.attrs[0]); } );
								}
							} else {
								tema.ThemeBasedFoi.setClickable(false);
								if (tema.sub_temaId != undefined) tema.ThemeBasedFoiSub.setClickable(false);
							}
							tema.ThemeBasedFoi.enableImageCaching(true);
							tema.ThemeBasedFoi.setBringToTopOnMouseOver(true);
							tema.ThemeBasedFoi.setQueryWindowMultiplier(1);
							tema.ThemeBasedFoi.enableInfoTip(true);
							if (maxZLev >= 0) tema.ThemeBasedFoi.setMaxVisibleZoomLevel(maxZLev);
							if (minZLev >= 0) tema.ThemeBasedFoi.setMinVisibleZoomLevel(minZLev);
							
							if (tema.sub_temaId != undefined) {
								tema.ThemeBasedFoiSub.enableImageCaching(true);
								tema.ThemeBasedFoiSub.setBringToTopOnMouseOver(true);
								tema.ThemeBasedFoiSub.setQueryWindowMultiplier(1);
								var minStZ = (tema.subTminZLevel != undefined ? (tema.subTminZLevel > minZLev ? tema.subTminZLevel : -1 ) : minZLev);
								var maxStZ = (tema.subTmaxZLevel != undefined ? (tema.subTmaxZLevel > minStZ ? (maxZLev >= 0 ? ( tema.subTmaxZLevel <= maxZLev ? tema.subTmaxZLevel : -1 ) : tema.subTmaxZLevel ) : -1 ) : maxZLev);
								
								if (maxStZ >= 0) tema.ThemeBasedFoiSub.setMaxVisibleZoomLevel(maxStZ);
								if (minStZ >= 0) tema.ThemeBasedFoiSub.setMinVisibleZoomLevel(minStZ);
							}
						}
						_GEO.temas[_GEO.temas.length] = tema;
					}
				}
			}
		};
		
		function addThemesToMap() {
			// adicionar do tipo poligono
			for (var t in _GEO.temas) {
				var tema = _GEO.temas[t];
				if (tema.tipoMapa!=undefined && tema.tipoMapa.isFOI!=undefined && tema.tipoMapa.isFOI==true && tema.tipoMapa.tpG!=undefined && tema.tipoMapa.tpG==3)
					tema.pos=_GEO.divMap.addThemeBasedFOI(tema.ThemeBasedFoi);
			}
			// adicionar do tipo linha
			for (var t in _GEO.temas) {
				var tema = _GEO.temas[t];
				if (tema.tipoMapa!=undefined && tema.tipoMapa.isFOI!=undefined && tema.tipoMapa.isFOI==true && tema.tipoMapa.tpG!=undefined && tema.tipoMapa.tpG==2)
					tema.pos=_GEO.divMap.addThemeBasedFOI(tema.ThemeBasedFoi);
			}
			// adicinar tema de linhas para hilight de vias nas pesquisa (necessário adicionar antes de temas de pontos)
			themeGeoSelect = new MVThemeBasedFOI('themeGeoSelect', datasource_name + '.TMB_VIA_SELECTED');
			themeGeoSelect.setQueryParameters(-1);
			themeGeoSelect.setVisible(false);
			_GEO.divMap.addThemeBasedFOI(themeGeoSelect);
			
			// adicionar do tipo ponto
			for (var t in _GEO.temas) {
				var tema = _GEO.temas[t];
				if (tema.tipoMapa!=undefined && tema.tipoMapa.isFOI!=undefined && tema.tipoMapa.isFOI==true && tema.tipoMapa.tpG!=undefined && tema.tipoMapa.tpG==1)
					tema.pos=_GEO.divMap.addThemeBasedFOI(tema.ThemeBasedFoi);
			}
			// adicionar sub-temas (considerando que são sempre pontos)
			for (var t in _GEO.temas) {
				var tema = _GEO.temas[t];
				if (tema.ThemeBasedFoiSub!=undefined) _GEO.divMap.addThemeBasedFOI(tema.ThemeBasedFoiSub);
			}
		};
		
		function zoomLevelChangeEvt(za,zd,escala) { actualizaThemesStates(zd); actualizaScaleLabel(escala);	};
		
		// actualiza estado (enabled / disabled) de todos os temas em funcao da escala passada como parâmetro
		function actualizaThemesStates(zoomLevel) {
			for (var t in _GEO.temas) {
				if (!jQuery.isFunction(_GEO.temas[t])) {
					var ver = true;
					var tema = _GEO.temas[t];
					var enab = _GEO.divLeg.getThemeState(t);
					
					if (tema.minZLevel != undefined && zoomLevel < tema.minZLevel) ver = false;
					if (tema.maxZLevel != undefined && zoomLevel > tema.maxZLevel) ver = false;
					
					if (ver != enab) {
						_GEO.divLeg.setThemeState(t, ver);
						if (ver && (tema.tipoMapa != undefined && tema.tipoMapa.isBM)) {
							if ((tema.minZLevel != undefined && tema.minZLevel <= zoomLevel) && (tema.maxZLevel != undefined && ttema.maxZLevel >= zoomLevel))
								tema.BaseMap.setVisible(tema.BaseMap.isVisible());
						}
					}
				}
			}
		};
	
		// actualiza label com escala em funcao o zoomLevel actual
		function actualizaScaleLabel(escala) {
			$("#Scale").html("1:" + escala);
		};
	
		function onMouseMoveEvt(x, y) {
			$("#CoordX").html(x.toFixed(2));
			$("#CoordY").html(y.toFixed(2));
		};
	
		function changeThemeChecked(themeIndex, chk) {
			var tema = _GEO.temas[themeIndex];
			if (tema.BaseMap != undefined) tema.BaseMap.setVisible(chk);
			if (tema.ThemeBasedFoi != undefined) {
				tema.ThemeBasedFoi.setVisible(chk);
				if (tema.ThemeBasedFoiSub != undefined) tema.ThemeBasedFoiSub.setVisible(chk);
			}
		};
		
		function onError(err) {			
			//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Problemas de comunica&ccedil;&atilde;o... Tente novamente<br/><br/><br/><div align="center"><input class="botao" type="button" value="Ok" onfocus="this.blur();" onclick="objBloq.desbloquear();"/></div><br/><p style="font-size: 9px; color:#cccccc;">' + err + '</p></div>');
			objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>De momento, não foi possível apresentar informação de pontos e rotas. Tente novamente...<br/><br/><br/><div align="center"><input class="botao" type="button" value="Ok" onfocus="this.blur();" onclick="objBloq.desbloquear();"/></div><br/></div>');
		};
	};
	
	geo.prototype.getThemeIndex = function(thmName) {
		for (var t in _GEO.temas) {
			if(_GEO.temas[t].id == thmName) return t;
		}
		return -1;
	};
	
	// Evento para tratar do click sobre um FOI em que o primeiro atributo é a chave primaria na tabela origem do FOI
	geo.prototype.foiClick = function (tema, tabela, point, chv) {
		_GEO.divMap.removeMarker();
		this.removeInfoWindow();
		this.clearViaSelected();
		_GEO.mapView.displayInfoWindow(point,'<div class="loading" align="center">' + this.loadMessage + '</div>', 280, 100);
		$("div#mvinfodiv img[src*='close']").click(function () { _GEO.divMap.removeMarker(); });
		if (this.ajaxGetInfoPOI) this.ajaxGetInfoPOI.abort();
		
		var strSend = "";
		if (tema != null && tema.length > 0)
			strSend = "TEMA="+tema+"&CHV="+chv;
		else if (tabela != null && tabela.length > 0)
			strSend = "TABLE="+tabela+"&CHV="+chv;
		
		this.ajaxGetInfoPOI = $.ajax({
			type: "GET",
			url: this.urlGetInfoPOI,
			dataType: "json",
			data: strSend,
			cache: false,
			async: true,
			success: function (data) {
				_GEO.cbGetInfoPOI(point, data); initFotos();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					//alert('ERRO...');
				}
		});
		
		function initFotos() {
			$.ImageBox.init({
				loaderSRC: 'css/images/imagebox/loading.gif',
				closeHTML: '<img src="css/images/imagebox/fechar.gif" />',
				textImage: 'Fotografia',
				textImageFrom: 'de',
				overlayOpacity: 0.6
			});
		}
	};
	
	geo.prototype.cbGetInfoPOI = function (point, objresp) {
		if ($("div#mvinfodiv").length > 0) {
			var strHtml = objresp.content;
			var di = $("div#infowin").html(strHtml);
			if (di.height() >= 250)
				strHtml = "<div style=\"width:470px; height:250px; overflow-y:auto; overflow-x:none;\">" + strHtml + "</div>";
			di.empty();
			_GEO.mapView.displayInfoWindow(point, strHtml, 480, 100, "MVInfoWindowStyle1", objresp.title);
			$("div#mvinfodiv img[src*='close']").click(function () { _GEO.divMap.removeMarker(); });		
		}
	};	

	geo.prototype.viewViaInMap = function(tema, params, xmin, ymin, xmax, ymax) {
		this.removeInfoWindow();
		themeGeoSelect = _GEO.mapView.getThemeBasedFOI("themeGeoSelect");
	    if (themeGeoSelect == null) {
	      themeGeoSelect = new MVThemeBasedFOI('themeGeoSelect', datasource_name + '.' + tema);
	      themeGeoSelect.setQueryParameters(params);
	      themeGeoSelect.setBringToTopOnMouseOver(false);
		  themeGeoSelect.setClickable(false);
	      _GEO.mapView.addThemeBasedFOI(themeGeoSelect);
	    }
	    else {
	      themeGeoSelect.setQueryParameters(params);
		  themeGeoSelect.setVisible(true);
	      themeGeoSelect.setBringToTopOnMouseOver(false);
		  themeGeoSelect.setClickable(false);
	      themeGeoSelect.refresh();
	    }
		
		var mWinBox = _GEO.mapView.getMapWindowBBox();
		var mRect = mWinBox.getMBR();
		var mRectZoom = MVSdoGeometry.createRectangle(xmin, ymin, xmax, ymax, _GEO.mapView.getSrid());
		
		if (((xmax-xmin) > (mRect[2]-mRect[0])) || ((ymax-ymin) > (mRect[3]-mRect[1])))
			_GEO.mapView.zoomToRectangle(mRectZoom);
		else {
			_GEO.mapView.setZoomLevel(10);
			var cx = xmin + (xmax-xmin)/2; var cy = ymin + (ymax-ymin)/2;
			var center=MVSdoGeometry.createPoint(cx, cy, _GEO.mapView.getSrid());
			_GEO.mapView.setCenter(center);
		}
	};
	
	geo.prototype.clearViaSelected = function() {
		if (themeGeoSelect != null) { themeGeoSelect.setQueryParameters(-1); themeGeoSelect.setVisible(false); themeGeoSelect.refresh(); }
	};
	
	geo.prototype.removeInfoWindow = function() {
		if ($("div#mvinfodiv").length > 0) { _GEO.mapView.removeInfoWindow(); }
		_GEO.divMap.removeMarker();
	};
	
	geo.prototype.viewPointInMap = function(tabela, chave, x, y) {
		var pt = MVSdoGeometry.createPoint(x, y, _GEO.mapView.getSrid());
		if (_GEO.mapView.getZoomLevel() < 10) _GEO.mapView.setZoomLevel(10);
		_GEO.mapView.setCenter(pt, false);
		if (tabela != 'GEO_TOPONIMIA')
			this.foiClick (null, tabela, pt, chave);
		if (tabela != 'VPONTOS_ROTAS') _GEO.divMap.addMarker(pt);
	};
	
	geo.prototype.viewAreaInMap = function(tabela, chave, xmin, ymin, xmax, ymax, cx, cy) {
		var mRectZoom = MVSdoGeometry.createRectangle(xmin, ymin, xmax, ymax, _GEO.mapView.getSrid());
		_GEO.mapView.zoomToRectangle(mRectZoom);
		var mptCenter = MVSdoGeometry.createPoint(cx, cy, _GEO.mapView.getSrid());
		if (tabela=="VROTAS_NEW") {
			var p = _GEO.getThemeIndex("THM_ROTAS_NEW");
			if (p>=0 && !_GEO.divLeg.getThemeChecked(p)) _GEO.divLeg.setThemeChecked(p, true);
		}
		this.foiClick (null, tabela, mptCenter, chave);
	};
}

