
if(jQuery) {
	var objThis = null;
	var btnClear = null;
	var btnSelRect = null;
	var btnSelCircle = null;
	var btnSelPoly = null;
	var geometria = null;
	
 	function pesquisa(divPesqAlf, divPesqGeo, divResults, objMapa, onLoadFinish){
		this.divPesq = $("div#"+divPesqAlf);
		this.divPesqGeo = $("div#"+divPesqGeo);
		this.divResul = $("div#"+divResults);
		this.objMapa = objMapa;
		this.onLoadFinish = onLoadFinish;
				
		this.pesqUrl = 'pesquisa/pesquisa.jsp';
		this.loadMessage = 'A inicializar...';
		this.pesqMessage = 'A pesquisar...';
		
		this.temas = null;
		this.limAdmin = null;
		
		this.inicializa();
	};
	
	pesquisa.prototype.inicializa = function(){
		objThis = this;
		var temasloaded = false;
		var limAdloaded = false;
		// Loading message
		objThis.divPesq.html('<div class="loading">' + this.loadMessage + '</div>');
		
		$.ajax({
			type: "POST",
			url: this.pesqUrl,
			dataType: "json",
			cache: false,
			async: true,
			data:{ op: 'temas' },
			success: function(data){
				objThis.temas = data;
				dataloaded('temas');
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					if (objThis.onLoadFinish) objThis.onLoadFinish(false);
					//objBloq.desbloquear();
					//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Ocorreram problemas na inicializa&ccedil;&atilde;o deste geoportal!<br/><br/><input name="" type="button" value="Tentar novamente" onclick="window.location=\'http://geo.valimardigital.pt/maps/geoportal\';" /><br/><br/></div>');
			}
		});
		
		$.ajax({
			type: "POST",
			url: this.pesqUrl,
			dataType: "json",
			cache: false,
			async: true,
			data:{ op: 'lim_admin' },
			success: function(data){
				objThis.limAdmin = data;
				dataloaded('lim_admin');
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					if (objThis.onLoadFinish) objThis.onLoadFinish(false);
					//objBloq.desbloquear();
					//objBloq.showMessage('<div><br /><img src="images/error.gif"/><br/><br/>Ocorreram problemas na inicializa&ccedil;&atilde;o deste geoportal!<br/><br/><input name="" type="button" value="Tentar novamente" onclick="window.location=\'http://geo.valimardigital.pt/maps/geoportal\';" /><br/><br/></div>');
			}
		});
		
		function dataloaded(tipo) {
			if (tipo == 'temas') temasloaded = true;
			if (tipo == 'lim_admin') limAdloaded = true;
			
			if (temasloaded && limAdloaded) {				
				var strTemas = objThis.renderOptions("temas", objThis.temas);
				
				var strTable =	'<table class="pesquisa" width="310" border="0" cellpadding="0" cellspacing="4">' +
								'<tr><td>Procurar:</td><td><input id="searchbox" type="text" name="findText"/></td></tr>' +
								'<tr><td>Tema:</td><td><select name="tema"></select></td></tr><tr><td>Sub-tema:</td><td><select name="subtema"></select></td></tr>' +
								'<tr><td>Concelho:</td><td><select name="concelho"></select></td></tr><tr><td>Freguesia:</td><td><select name="freguesia"></select></td></tr>' +
								'<tr><td>&nbsp;</td><td><input class="searchButton" onfocus="this.blur();" type="submit" value="Procurar"/></td></tr></table>';
				
				var strTableGeo='<table class="pesquisa" width="310" border="0" cellpadding="0" cellspacing="4">' +
								'<tr><td>Tema:</td><td><select name="temageo"></select></td></tr><tr><td>Sub-tema:</td><td><select name="subtemageo"></select></td></tr>' +
								'<tr><td colspan=2>Limite geogr&aacute;fico para pesquisa:</td></tr>' +
								'<tr><td colspan=2 align="right"><div id="tbarPesquGeo" style="margin-top:-32px;">&nbsp;</div></td></tr>' +
								'<tr><td colspan=2><input class="searchButton" onfocus="this.blur();" type="submit" value="Procurar"/></td></tr>' +
								'<tr><td colspan=2><div id="messageBox" style="display:none;">Defina o limite geogr&aacute;fico de pesquisa no mapa!</div></td></tr></table>';
				
				objThis.divPesq.html(strTable);
				objThis.divPesqGeo.html(strTableGeo);

				objThis.divPesq.find("select[name='tema']").replaceWith(objThis.renderOptions("tema", objThis.temas));
				objThis.divPesq.find("select[name='subtema']").replaceWith(objThis.renderOptions("subtema", objThis.temas[0].subtemas));
				objThis.divPesq.find("select[name='concelho']").replaceWith(objThis.renderOptions("concelho", objThis.limAdmin));
				objThis.divPesq.find("select[name='freguesia']").replaceWith(objThis.renderOptions("freguesia", objThis.limAdmin[0].freguesias));
				
				objThis.divPesqGeo.find("select[name='temageo']").replaceWith(objThis.renderOptions("temageo", objThis.temas));
				objThis.divPesqGeo.find("select[name='subtemageo']").replaceWith(objThis.renderOptions("subtemageo", objThis.temas[0].subtemas));
				
				objThis.divPesq.find("select[name='tema']").change(objThis.onChangeTema);
				objThis.divPesq.find("select[name='concelho']").change(objThis.onChangeConcelho);
				
				objThis.divPesqGeo.find("select[name='temageo']").change(objThis.onChangeTema);
				
				objThis.divPesq.find("input.searchButton").click(objThis.evtPesquisar);
				objThis.divPesq.find("input#searchbox").keyup(function (e) { if (e.keyCode==13) objThis.evtPesquisar(); });
				objThis.divPesqGeo.find("input.searchButton").click(objThis.evtPesquisarGeo);
				
				var tbPesqGeom = new Ext.Toolbar({autoHeight:true});
			    tbPesqGeom.render('tbarPesquGeo');
				btnClear = createButton('btnClear', 'icons/selectClear.gif', 'Limpar limite de pesquisa geográfica', objThis.btnClick, false);
				btnSelRect = createButton('btnSelRect', 'icons/selectRect.gif', 'Seleccionar por rectângulo', objThis.btnClick, false);
				btnSelCircle = createButton('btnSelCircle', 'icons/selectCircle.gif', 'Seleccionar por circulo', objThis.btnClick, false);
				btnSelPoly = createButton('btnSelPoly', 'icons/selectPoly.gif', 'Seleccionar por polígono', objThis.btnClick, false);
				
				tbPesqGeom.add(btnClear, '  ',btnSelRect, '  ', btnSelCircle, '  ',btnSelPoly);
				
				if (objThis.onLoadFinish) objThis.onLoadFinish(true);
			}
		}
	};
	
	pesquisa.prototype.btnClick = function(item) {
		objThis.divPesqGeo.find("#messageBox").hide();
		geometria = null;
		objThis.objMapa.divMap.finishDraw();
		objThis.objMapa.divMap.stopMeasuring(objThis.removeInfoWindow);
		objThis.objMapa.clearViaSelected();
		objThis.objMapa.divMap.removeMarker();
		objThis.objMapa.removeInfoWindow();
		switch(item.id)
		{
			case 'btnClear':
			break;
			case 'btnSelRect':
				btnSelCircle.toggle(false); btnSelPoly.toggle(false); //btnSelRect.toggle(true);
				objThis.objMapa.divMap.drawRectangle(fimGeometria, "L.SEARCH");
			break;
			case 'btnSelCircle':
				btnSelRect.toggle(false); btnSelPoly.toggle(false); //btnSelCircle.toggle(true);
				objThis.objMapa.divMap.drawCircle(fimGeometria, "L.SEARCH");
			break;
			case 'btnSelPoly':
				btnSelRect.toggle(false); btnSelCircle.toggle(false); //btnSelPoly.toggle(true);
				objThis.objMapa.divMap.drawPoly(fimGeometria, "L.SEARCH", "C.AREA", "MARCA_DIST");
			break;
		}
		
		function fimGeometria(g) { geometria = g; }
	};
	
	pesquisa.prototype.MVSdoGeomToSDO_GEOM=function(mvg){
		var geom="SDO_GEOMETRY(";
		geom+=mvg.gtype+",";
		geom+=mvg.srid+",";
		if (mvg.sdo_point!=null) geom+="sdo_point_type("+mvg.sdo_point.x+","+mvg.sdo_point.y+","+mvg.sdo_point.z+"),";
		else geom+=mvg.sdo_point+",";
		if(mvg.sdo_elem_info!=null) geom+="sdo_elem_info_array("+mvg.sdo_elem_info+"),";
		else geom+="null,";
		if(mvg.sdo_ordinates!=null) geom+="sdo_ordinate_array("+mvg.sdo_ordinates+"))";
		else geom+="null)";
		return geom;
	};
	
	pesquisa.prototype.renderOptions = function(identify, opcoes) {
		var htmlStr = '';
		for (var op in opcoes) {
			if (opcoes[op].id != undefined && opcoes[op].nome != undefined) {
				htmlStr += "<option value='" + op + "'>" + opcoes[op].nome + "</option>";
			}
		}
		htmlStr = "<select name='" + identify + "'>" + htmlStr + "</select>";
		return htmlStr;
	};
	
	pesquisa.prototype.onChangeConcelho = function() {
		objThis.divPesq.find("select[name='freguesia']").replaceWith(objThis.renderOptions("freguesia", objThis.limAdmin[this.value].freguesias));
	};
	
	pesquisa.prototype.onChangeTema = function() {
		if (this.name == 'tema')
			objThis.divPesq.find("select[name='subtema']").replaceWith(objThis.renderOptions("subtema", objThis.temas[this.value].subtemas));
		else objThis.divPesqGeo.find("select[name='subtemageo']").replaceWith(objThis.renderOptions("subtemageo", objThis.temas[this.value].subtemas));
	};
	
	pesquisa.prototype.evtPesquisar = function() {
		objThis.objMapa.clearViaSelected();
		var strSearch = objThis.divPesq.find("input[name='findText']")[0].value;
		var strTema = objThis.divPesq.find("select[name='tema']")[0].value;
		var strSubTema = objThis.divPesq.find("select[name='subtema']")[0].value;
		var strConc = objThis.divPesq.find("select[name='concelho']")[0].value;
		var strFreg = objThis.divPesq.find("select[name='freguesia']")[0].value;					
		var tema = objThis.temas[strTema].id;
		var subTema = objThis.temas[strTema].subtemas[strSubTema].id;
		var conc = objThis.limAdmin[strConc].id;
		var freg = objThis.limAdmin[strConc].freguesias[strFreg].id;
		objThis.getResults(strSearch, tema, subTema, conc, freg, '');
	};
	
	pesquisa.prototype.evtPesquisarGeo = function() {
		objThis.divPesqGeo.find("#messageBox").hide();
		btnSelRect.toggle(false); btnSelCircle.toggle(false); btnSelPoly.toggle(false);
		if (geometria) {
			var strTema = objThis.divPesqGeo.find("select[name='temageo']")[0].value;
			var strSubTema = objThis.divPesqGeo.find("select[name='subtemageo']")[0].value;					
			var tema = objThis.temas[strTema].id;
			var subTema = objThis.temas[strTema].subtemas[strSubTema].id;
			
			var geom = encodeURI(objThis.MVSdoGeomToSDO_GEOM(geometria));
			//geometria = null;
			objThis.getResults('', tema, subTema, '0', '0', geom);
			//objThis.objMapa.divMap.finishDraw();
		}
		else objThis.divPesqGeo.find("#messageBox").show("fast");
	};
	
	pesquisa.prototype.getResults = function(strSearch, tema, subTema, conc, freg, geom){
		var divResult = this.divResul;
		// Loading message
		divResult.html('<div class="loading">' + this.pesqMessage + '</div>');
		
		strSearch = strSearch.replace(/^\s+|\s+$/, ''); //retira espaços no inicio e fim da string		
		var sendStr = 'op=getRes' + (strSearch.length>0?'&strPesq=' + strSearch:'') + (tema!='0' ? '&tm=' + tema : '') + (subTema!='0' ? '&st=' + subTema : '') + (freg!='0' ? '&fr=' + freg : (conc != '0' ? '&co=' + conc : '')) + (geom.length>0?'&geom=' + geom:'');
				
		if (this.ajaxPesq) this.ajaxPesq.abort();
		this.ajaxPesq = $.ajax({
			type: "POST",
			url: this.pesqUrl,
			dataType: "json",
			cache: false,
			async: true,
			data: sendStr,
			success: function(data){
				objThis.results = data;
				if (objThis.results.resultsExcess == undefined) {
					if (objThis.results.length > 0) {
						divResult.html(renderResults(objThis.results));
					}
					else divResult.html("<div class='noresults'><br/><img src='images/error.gif' /><br/><br/>N&atilde;o foi encontrado nenhum resultado, altere os par&acirc;metros de pesquisa...</div>");

					objThis.divResul.find("div.pesq-group-expanded").click(objThis.expandeGrupo);
				}
				else divResult.html("<div class='noresults'><br/><img src='images/error.gif' /><br/><br/>Demasiados resultados, refine a sua pesquisa alterando os par&acirc;metros de pesquisa...</div>");
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) { divResult.html("<div class='noresults'><br/><img src='images/error.gif' /><br/><br/>De momento, não foi possível obter o resultado da sua pesquisa...</div>"); }
		});
		
		function renderResults(results) {
			var htmlStr = '';
			for (var res in results) {
				if ( results[res].nome != undefined) {
					htmlStr += "<li id=" + results[res].id + "><div class='pesq-hand-pointer pesq-group-expanded'><div class='pesq-group-header'>" + results[res].nome + "</div></div><br/>" + renderItens(results[res].tabela, results[res].temafoi, results[res].itens) + "</li>";
				}
			}
			htmlStr = "<ul class='pesqResult'>" + htmlStr + "</ul>";
			if ($.browser.msie) htmlStr = "<div style='width:1000px;'>" + htmlStr + "</div>";
			return htmlStr;
		};
		
		function renderItens(tabela, temafoi,itens) {
			var htmlStr = "";
			for (var iten in itens) {
				if ( itens[iten].desc != undefined) {
					var href = "#";
					var params = "";
					if (tabela != undefined) {
						if (itens[iten].ponto != undefined)
							params = "tp='pt' tab='" + tabela + "' chv='" + itens[iten].id + "' ptx=" + itens[iten].ponto.x + " pty=" + itens[iten].ponto.y;
						else if (itens[iten].area != undefined)
							params = "tp='ar' tab='" + tabela + "' chv='" + itens[iten].id + "' xmin=" + itens[iten].area.xmin + " ymin=" + itens[iten].area.ymin + " xmax=" + itens[iten].area.xmax + " ymax=" + itens[iten].area.ymax + " cx=" + itens[iten].centro.x + " cy=" + itens[iten].centro.y;
					}
					else if (temafoi != undefined) {
						params = "tp='vi' tab='" + temafoi + "' chv='" + itens[iten].id + "' xmin=" + itens[iten].area.xmin + " ymin=" + itens[iten].area.ymin + " xmax=" + itens[iten].area.xmax + " ymax=" + itens[iten].area.ymax;
					}
					htmlStr += "<li><a href='javascript:objThis.viewItem(\""+itens[iten].id+"\");' " + params + ">" + itens[iten].desc + "</a></li>";
				}
			}
			htmlStr = "<ul class='pesqResult'>" + htmlStr + "</ul>";
			return htmlStr;
		}
	};
		
	//function viewItem() {
	pesquisa.prototype.viewItem = function(chv) {
		var obj = $("a[chv='"+chv+"']");
		var tipo = obj.attr("tp"); var tab = obj.attr("tab");
		if (tipo=='pt'){
			var x = parseFloat(obj.attr("ptx")); var y = parseFloat(obj.attr("pty"));
			objThis.objMapa.viewPointInMap(tab, chv, x, y);
		} else if (tipo=='ar'){
			var xmin = parseFloat(obj.attr("xmin")); var ymin = parseFloat(obj.attr("ymin")); var xmax = parseFloat(obj.attr("xmax")); var ymax = parseFloat(obj.attr("ymax"));
			var cx = parseFloat(obj.attr("cx")); var cy = parseFloat(obj.attr("cy"));
			objThis.objMapa.viewAreaInMap(tab, chv, xmin, ymin, xmax, ymax, cx, cy);
		} else if (tipo=='vi'){
			var xmin = parseFloat(obj.attr("xmin")); var ymin = parseFloat(obj.attr("ymin")); var xmax = parseFloat(obj.attr("xmax")); var ymax = parseFloat(obj.attr("ymax"));
			objThis.objMapa.viewViaInMap(tab, chv, xmin, ymin, xmax, ymax);
		}
	};
	
	pesquisa.prototype.expandeGrupo = function() {
		if ($(this).hasClass('pesq-group-collapsed')) {
			// Expand
			//$(this).parent().children('UL').slideDown({ duration: 700, easing: 'easeOutBounce' });
			$(this).parent().children('UL').slideDown("fast");
			$(this).removeClass('pesq-group-collapsed').addClass('pesq-group-expanded');
		} else {
			// Collapse
			//$(this).parent().find('UL').slideUp({ duration: 700, easing: 'easeOutBounce' });
			$(this).parent().find('UL').slideUp("fast");
			$(this).removeClass('pesq-group-expanded').addClass('pesq-group-collapsed');
		}
	};
}
