/* Página Principal */

var loaderCount = 0;
var currentDetail = null;
var selectedFeature = null;
var markedFeature = null;
var currentZona = null;

var routingAction = null;
var routingType = null;
var routeStart = null;
var routeEnd = null;

var customPoi = null;
var customAction = null;

var getPoint = null;

// TODO: no fim verificar que vars ainda estao em uso.
var poiInfo = null;
var tipOn = -1;
var tipVerificationDelay = 0;
var currentPOIs = null;
var activeInfoDivs = new Array();
var infoDivTagCounter = 1;

var timeoutMouseMoveMapa = null;
var timeoutPesquisa = null;

var poiIcons = null;
var ballonStyle = null;
var tooltipStyle = null;

/* ------> Classes <-------- */
function TooltipStyle(scale, brushColor, brushAlpha, penColor, border, font, fontColor, fontSize) {
	this.scale = scale;
	this.brushColor = brushColor;
	this.brushAlpha = brushAlpha;
	this.penColor = penColor;
	this.border = border;
	this.font = font;
	this.fontColor = fontColor;
	this.fontSize = fontSize;
}

function InfoDIV(px, py, POIs) {
	this.minimized = false;
	var res = map_localScreenToWorld(px, py);
	this.x = res[0];
	this.y = res[1];
	this.POIs = POIs;
	this.tagId = "InfoDiv" + infoDivTagCounter++;
}

function POI(nome, px, py, id, feature_id) {
	this.id = id;
	this.nome = nome;
	this.x = px;
	this.y = py;
	this.feature_id = feature_id;
}

function Feature(fid,nome,concelho,icon) {
	this.id = fid;
	this.nome = nome;
	this.concelho = concelho;
	this.icon = icon;
	
	if(this.id && !this.concelho) {
		var me = this;
		map_getFeatureConcelho(this.id, function(req){me.concelho = map_getConcelho(req);});
	}
}


function RoutePoint(param1, param2) {
	this.feature = null;
	this.point = null;
	
	if (param2) 
		if (param2.indexOf('/')>=0) this.feature = param2;
		else if (param2.indexOf(',')>=0) this.point = param2;
	
	if (param1)
		if (param1.indexOf('/')>=0) this.feature = param1;
		else if (param1.indexOf(',')>=0) this.point = param1;
		
	if (this.feature && !this.point) {
		var me = this;
		map_getSnapToFeature(this.feature, function(req){point=map_getXY(req); if(!point) return; me.point=point.join(','); ui_updateBandeiras();});
	}
}


function CustomPoi(text,icon,x,y) {
	this.label = text;
	this.icon = icon;
	this.x = x;
	this.y = y;

	if (this.icon && document.getElementById("custom_poi_holder"))
		document.getElementById("custom_poi_holder").style.background = "transparent url(" + this.icon + ") no-repeat center";
	
	if (this.label && document.getElementById("custom_label"))
		document.getElementById("custom_label").innerHTML = this.label;
}


/* -------> Startup <------- */

function ui_onLoad() {
	if(document.getElementById("ZonaSelection")) data_fillZonas();
	if(document.getElementById("TipoSelection")) data_fillTipos();
	
	// Show dynamic content
	document.getElementById('main_container').style.display = 'block';
	document.getElementById('noscript').style.display = 'none';
	
	var selection = getQueryVariable("select");
	
	if(selection) {
		map_selectInitialFeature(selection);
		return;
	}
	
	var zona = getQueryVariable("zona");
	
	if(zona) {
		ui_selectZona(zona);
		return;
	}

	var start = getQueryVariable("start");
	var end = getQueryVariable("end");
	var type = (getQueryVariable("type")?getQueryVariable("type"):"car");
	
	if(start && end) {
		//map_selectRoute(start, end, type);
		routeStart = new RoutePoint(start);
		routeEnd = new RoutePoint(end);
		ui_getPercurso(type);
		return;
	}
	
	ui_selectZona(0);
	
	loadXMLDoc(server + "/geticons" , data_loadIcons);
	loadXMLDoc("styles/ballons.xml", data_loadBallonStyle);
	loadXMLDoc("styles/tooltips.xml", data_loadTooltipStyle);
}

/* -------> getPoint <------- */

function ui_setPontoGetPoint(req) {
	wp = map_getXY(req);
	if (wp) {
		//window.returnValue = wp;
		window.returnValue = wp[0] + "," + wp[1];
		document.getElementById("getpoint_text").innerHTML = "<br/>X: "+wp[0]+"<br/>Y: "+wp[1];
	}
}

/* -------> Loader <------- */

function ui_showLoader() {
	loaderCount++;
	document.getElementById("loader_holder").style.display = "block";
}

function ui_hideLoader() {
	loaderCount--;
	if(loaderCount <= 0) {
		loaderCount = 0;
		document.getElementById("loader_holder").style.display = "none";
		// BIG HACK!! qualquer que seja o pedido que peça o loader, ele actualiza as posições.
		// Isto devia estar apos o update do mapa (function map_update(req)) mas apresenta melhores resultados assim.
		ui_updatePoiInfoPosition();
	}
}

/* -------> Print <------- */

function ui_printPage(type) {
	if(type == "route") {
		if(routeStart && routeEnd)
			data_getPercurso(routingType, (routeStart.point?routeStart.point:routeStart.feature), (routeEnd.point?routeEnd.point:routeEnd.feature), data_populatePrintableRoute);
	}
}


/* -------> Tipo <------- */

function ui_selectTipo() {
    if (document.getElementById("TipoSelection").value == "-1") {
		document.getElementById("TipoSelection").value = "/feature"
	}
	if (document.getElementById("NomeSelection").value != "") ui_submitPesquisa();
}

/* -------> Zona <------- */

function ui_selectZona(zona_id) {
	ui_showLoader();
	
	if(zona_id == undefined) zona_id = document.getElementById("ZonaSelection").value;
	else ui_changeZonaBox(zona_id);
	
	if (zona_id == "-1") {
		zona_id = 0;
		ui_changeZonaBox(zona_id);
	}
	
	if (document.getElementById("NomeSelection").value != "") ui_submitPesquisa();
	
	map_selectZona(zona_id);
}

function ui_changeZonaBox(zona_id) {
	document.getElementById("ZonaSelection").value = zona_id;
	currentZona = zona_id;
}

function ui_onChangeZona() {
	if(document.getElementById("ZonaSelection").value == "-1") document.getElementById("ZonaSelection").value = currentZona;
	else currentZona = document.getElementById("ZonaSelection").value;
}

/*function ui_changeMapaZona(zona_id) {
	var image;
	switch(zona_id) {
		case 2: image = "mapa_acores"; break;
		case 3: image = "mapa_madeira"; break;
		case 4: image = "mapa_norte"; break;
		case 5: image = "mapa_centro"; break;
		case 6: image = "mapa_lisboa"; break;
		case 7: image = "mapa_alentejo"; break;
		case 8: image = "mapa_algarve"; break;
		default: image = "mapa";
	}
		
	document.getElementById("quick_map_image").src = "resources/img/" + image + ".png";
}

function ui_setQuickMap() {
	if(inBoundingBox(limite_portugal, x, y)) {
		map_worldToScreen(x+","+y, ui_updateQuickMap, "size=154,153", centro_minimapa[0]+","+centro_minimapa[1]+","+centro_minimapa[2]);
	}
	else if (inBoundingBox(limite_acores, x, y)) {
		ui_updateQuickMapSelection(38,48);
	}
	else if (inBoundingBox(limite_madeira, x, y)) {
		ui_updateQuickMapSelection(38,111);
	}
	else {
		document.getElementById("quick_map_selection").style.display = "none";
	}
}

function ui_updateQuickMap(req) {
	pixel = map_getXY(req);
	if (pixel) {
		ui_updateQuickMapSelection((Math.round(pixel[0]) - selection_adjust[0]),Math.round(pixel[1])-selection_adjust[1]);
	}
}

function ui_updateQuickMapSelection(left, top) {
	document.getElementById("quick_map_selection").style.display = "block";
	document.getElementById("quick_map_selection").style.left = left + "px";
	document.getElementById("quick_map_selection").style.top = top + "px";
}*/

/* -------> Pesquisa <------- */

function ui_submitPesquisa() {
	var tipo = document.getElementById("TipoSelection").value.split("/").pop();
	var zona = document.getElementById("ZonaSelection").value;
	var nome = escape(document.getElementById("NomeSelection").value.replace(/^\s+|\s+$/g, ''));
	
	if (nome.length<2) {
		var html = "<p>Demasiado abrangente!</p>";
		html += "<div id='lista'><ul id='innerlista'>";
		html += "&nbsp;<p>Por favor indique um nome com 2 ou mais caracteres.</p>";
		html += "</ul></div>";
		
		document.getElementById("results").innerHTML = html;
		return;
	}
	
	selectedFeature = null;
	ui_changeEstadoFavorito(0);
	ui_changeEstadoRouting();
	data_doPesquisa(tipo, zona, nome, 0);
}

function ui_submitOnEnter(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		ui_submitPesquisa()
		return false;
	}
	else {
		ui_delayPesquisa();
		return true;
	}
}

function ui_delayPesquisa() {
	if (timeoutPesquisa!=null) clearTimeout(timeoutPesquisa);
	timeoutPesquisa = setTimeout(ui_submitPesquisa,500);
}

function ui_submitMaisProximos() {
	var tipo = document.getElementById("TipoSelection").value;
	var zona = document.getElementById("ZonaSelection").value;
	
	// Limpa os resultados
	document.getElementById("results").innerHTML = "";
	
	// Limpa selecções e atribui a selecção do ponto
	emptySelections();
	selections['point'] = x+","+y;
	
	// Desactiva a feature selecionada e as várias opções
	selectedFeature = null;
	ui_changeEstadoFavorito(0);
	ui_changeEstadoRouting();
	
	ui_showLoader();
	
	if (tipo == "/feature/via" || tipo == "/feature/pov" || tipo == "/feature/locais") tipo = "/feature";
	
	data_doMaisPerto(tipo, zona);
}

function ui_submitPesquisaDerivada(tipo, zona, nome, offset) {
	document.getElementById("TipoSelection").value = tipo;
	document.getElementById("ZonaSelection").value = zona;
	document.getElementById("NomeSelection").value = nome;
	
	data_doPesquisa(tipo.split("/").pop(), zona, escape(nome.replace(/^\s+|\s+$/g, '')), offset);
}

/* -------> Mapas Grátis <------- */

function ui_setCustomPoi() {
	ui_showLoader();
	/*var customPoiId = getQueryVariable('custompoi_id');
	
	if(customPoiId)
		map_selectCustomPoi(customPoiId);
	else
		ui_hideLoader();*/
}

function ui_updateCustomPoi() {
	if (x && y && scale && customPoi && customPoi.x && customPoi.y) {
		map_worldToScreen(customPoi.x +","+ customPoi.y ,ui_updateCustom);
	} else ui_setCustomPoi(-1,-1);
}

function ui_setCustomPoi(sx, sy) {
	var id = "custom_poi_holder";
	if (sx>0 && sx<size_h && sy>0 && sy<size_v) {
		document.getElementById(id).style.display = "block";
		document.getElementById(id).style.top = (sy - 16) + "px";
		document.getElementById(id).style.left = (sx - 16) + "px";
		
		id = "custom_label";
		document.getElementById(id).style.display = "block";
		document.getElementById(id).style.top = (sy + 15) + "px";
		
		//label_size = size_h + "px";
		label_size = (sx < size_h/2)?sx*2:(size_h-sx)*2;
		//document.getElementById(id).style.left = (sx - (size_h/2)) + "px";
		document.getElementById(id).style.left = (sx - (label_size/2)) + "px";
		document.getElementById('custom_label').style.width = label_size + "px";
	} else {
		document.getElementById(id).style.display = "none";
		id = "custom_label";
		document.getElementById(id).style.display = "none";
	}
}

function ui_updateCustom(req) {
	var pixel = map_getXY(req);
	if (pixel) {
		ui_setCustomPoi(Math.round(pixel[0]),Math.round(pixel[1]));
	} else ui_setCustomPoi(-1,-1);
}

function ui_showMapasGratis(state, action) {
	if(action == 'clear') customPoi = null;
		
	switch(state) {
		case 'on':
			document.getElementById("free_maps").style.display = "block";
			document.getElementById("main_container").style.display = "none";
			break;
		case 'off':
			document.getElementById("free_maps").style.display = "none";
			document.getElementById("main_container").style.display = "block";
			break;
	}
}

function ui_setPontoCustomPoi(req) {
	var wp = map_getXY(req);
	if (wp) {
		document.getElementById("fm_x").value = wp[0];
		document.getElementById("fm_y").value = wp[1];
		
		ui_showMapasGratis('on');
	}
}

function ui_beforeSubmitCustomPoi() {
	// Form Callback
	// make something useful before submit (onStart)
	if(isEmpty(document.getElementById('fm_nome').value)) {
		alert("É necessário indicar o seu nome!");
		return false;
	}
	if(!checkEmail(document.getElementById('fm_email').value)) {
		alert("O seu email é inválido!");
		return false;
	}
	if(isEmpty(document.getElementById('fm_website').value)) {
		alert("É necessário indicar o seu website!");
		return false;
	}
	if(isEmpty(document.getElementById('fm_x').value) || isEmpty(document.getElementById('fm_y').value)) {
		alert("Tem de indicar as coordenadas do seu site!");
		return false;
	}
	if(document.getElementsByName("fm_logo")[0].checked) {
		// Arranjar maneira de validar input type=file
	}
	else if(!document.getElementsByName("fm_logo")[1].checked) {
		alert("Tem de escolher o logótipo a utilizar!");
		return false;
	}
	/*if(isEmpty(document.getElementById('fm_nivel_zoom').value)) {
		alert("Tem de indicar um nome de empresa válido!");
		return false;
	}*/
	if(isEmpty(document.getElementById('fm_company_name').value)) {
		alert("Tem de indicar um nome de empresa válido!");
		return false;
	}
	
	return true;
}

function ui_afterSubmitCustomPoi(response) {
	response = response.replace("<pre>","").replace("</pre>","");
	
	if(customAction == 'confirm') {
		var message = "Obrigado por utilizar o nosso serviço. \n\nEm breve receberá um email com as hiperligações necessárias para aceder ao serviço.";
		alert(message);
	}
	else {
		window.open("custom.html?select="+response,"Preview","height=510,width=500");
	}
}

function ui_submitMapasGratis(action) {
	var cp_action = null;
	customAction = action;
	
	if(action == 'confirm') cp_action = "clear";

	document.getElementById('fm_submit').value = action;
	document.getElementById("fm_submit").click();
	ui_showMapasGratis('off', cp_action);
}

function ui_getMapaGratisCoords() {
	ui_showMapasGratis('off');
	document.getElementById("mapimage").style.cursor = "crosshair";
	
	customPoi = new CustomPoi();
	//customPoi = 'true';	
}

/* -------> Routing <------- */

function ui_enablePontoPercurso(action) {
	document.getElementById(action).className = "active";
	
	if(action == routingAction && document.getElementById("mapimage").onmousemove != null) {
		document.getElementById("mapimage").style.cursor = "auto";
		document.getElementById("mapimage").onmousemove = null;
		document.getElementById("mapimage").onmouseout = null;
		
		routingAction = null;
		return;
	}

	document.getElementById("mapimage").style.cursor = "crosshair";
	document.getElementById("mapimage").onmousemove = ui_mouseMoveBandeira;
	document.getElementById("mapimage").onmouseout = ui_mouseOutBandeira;

	routingAction = action;
	switch(action) {
		case 'inicio':
			if(routeStart){
				routeStart = null;
				ui_setBandeira("route_start_flag",-1,-1);
			}
			break;
		case 'fim':
			if(routeEnd){ 
				routeEnd = null;
				ui_setBandeira("route_end_flag",-1,-1);
			}
			break;
	}
	ui_changeEstadoRouting();
}

function ui_setFeaturePercurso(action) {
	switch(action) {
		case 'inicio':
			if(routeEnd && selectedFeature.id == routeEnd.feature) routeEnd = null;
			routeStart = new RoutePoint(selectedFeature.id);
			break;
		case 'fim':
			if(routeStart && selectedFeature.id == routeStart.feature) routeStart = null;
			routeEnd = new RoutePoint(selectedFeature.id);
			break;
	}
	//document.getElementById(action).className = "inactive";
	ui_updateBandeiras();
	ui_changeEstadoRouting();
}

function ui_changeEstadoRouting() {
	document.getElementById("routing_start").className = (selectedFeature && (!routeStart || routeStart.feature != selectedFeature.id))?"active":"inactive";
	document.getElementById("routing_end").className = (selectedFeature && (!routeEnd || routeEnd.feature != selectedFeature.id))?"active":"inactive";
	
	var state = "inactive";
	if(routeStart && routeEnd) {
		state = "active";
	}
	
	document.getElementById("calculo_pe").className = state;
	document.getElementById("calculo_carro").className = state;
	
	if(!routeStart) document.getElementById("inicio").className = "active";
	if(!routeEnd) document.getElementById("fim").className = "active";
}

function ui_setPontoPercurso(req) {
	
	wp = map_getXY(req);
	if (wp) {
		//alert(wp);
		window.returnValue = wp;
		var info = wp[0]+","+wp[1];
		//document.getElementById(routingAction).className = "inactive";
			
		switch(routingAction) {
			case "inicio":
				routeStart = new RoutePoint(info); break;
			case "fim":
				routeEnd = new RoutePoint(info); break;
		}
		
		ui_changeEstadoRouting();
	
		routingAction = null;
	}
}

function ui_getPercurso(tipo) {
    routingType = tipo;
	if(routeStart && routeEnd)
		data_getPercurso(tipo, (routeStart.point?routeStart.point:routeStart.feature), (routeEnd.point?routeEnd.point:routeEnd.feature), data_populateResultadoPercurso);
	
	emptySelections();
	ui_changeEstadoFavorito(0);
	document.getElementById("routing_start").className = "inactive";
	document.getElementById("routing_end").className = "inactive";
}

/* -------> Bandeiras da rota <------- */


function ui_setBandeira(id, sx, sy) {
	if (sx>0 && sx<size_h && sy>0 && sy<size_v) {
		document.getElementById(id).style.display = "block";
		/*document.getElementById(id).style.top = (sy - 17) + "px";
		document.getElementById(id).style.left = sx + "px";*/
		document.getElementById(id).style.top = (sy - 17) + "px";
		document.getElementById(id).style.left = (sx - 8) + "px";
	} else {
		document.getElementById(id).style.display = "none";
	}
}

function ui_updateBandeiras() {
	if (x && y && scale && routeStart && routeStart.point) {
		map_worldToScreen(routeStart.point,ui_updateBandeiraInicio);
	} else ui_setBandeira("route_start_flag",-1,-1);
	if (x && y && scale && routeEnd && routeEnd.point) {
		map_worldToScreen(routeEnd.point,ui_updateBandeiraFim);
	} else ui_setBandeira("route_end_flag",-1,-1);
}

function ui_updateBandeiraInicio(req) { ui_updateBandeira(req,"route_start_flag");}
function ui_updateBandeiraFim(req) { ui_updateBandeira(req,"route_end_flag");}

function ui_updateBandeira(req,id) {
	pixel = map_getXY(req);
	if (pixel) {
		ui_setBandeira(id,Math.round(pixel[0]),Math.round(pixel[1]));
	} else ui_setBandeira(id,-1,-1);
}

function ui_mouseMoveBandeira(event) {
	if (!event) var event = window.event;
	screenx = event.offsetX?(event.offsetX):event.pageX-document.getElementById("map_overlap").offsetLeft;
	screeny = event.offsetY?(event.offsetY):event.pageY-document.getElementById("map_overlap").offsetTop;
	
	switch(routingAction) {
		case 'inicio': ui_setBandeira("route_start_flag",screenx,screeny); break;
		case 'fim': ui_setBandeira("route_end_flag",screenx,screeny); break;
	}
}

function ui_mouseOutBandeira(event) {
	switch(routingAction) {
		case 'inicio': ui_setBandeira("route_start_flag",-1,-1); break;
		case 'fim': ui_setBandeira("route_end_flag",-1,-1); break;
	}
}

/* -------> Mapa <------- */

function ui_onLoadMapa() {
	if (document.getElementById("route_start_flag") && document.getElementById("route_end_flag")) 
		ui_updateBandeiras();
	if (document.getElementById("custom_poi_holder")) 
		ui_updateCustomPoi();
	ui_hideLoader();
}

function ui_onErrorMapa() {
	ui_hideLoader();
}

function ui_onClickMapa(event) {
	if (!event) var event = window.event;
	screenx = event.offsetX?(event.offsetX):event.pageX-document.getElementById("map_overlap").offsetLeft;
	screeny = event.offsetY?(event.offsetY):event.pageY-document.getElementById("map_overlap").offsetTop;
	
	if(routingAction) {
		document.getElementById("mapimage").style.cursor = "auto";
		document.getElementById("mapimage").onmousemove = null;
		document.getElementById("mapimage").onmouseout = null;
		map_screenToWorld(screenx, screeny, ui_setPontoPercurso);
		if (routingAction=="inicio") ui_setBandeira("route_start_flag",screenx,screeny);
		else if (routingAction=="fim") ui_setBandeira("route_end_flag",screenx,screeny);
	}
	else if(customPoi && !customPoi.x && !customPoi.y) {
		document.getElementById("mapimage").style.cursor = "auto";
		map_screenToWorld(screenx, screeny, ui_setPontoCustomPoi);
		document.getElementById('fm_nivel_zoom').value = parseInt(scale);
	}
	else if(getPoint) {
		map_screenToWorld(screenx, screeny, ui_setPontoGetPoint);
	}
	else {
		for (var i = 0; i < activeInfoDivs.length; i++) {
			if (activeInfoDivs[i]) {
				var equals = ui_equalsCurrentPOIs(activeInfoDivs[i].POIs);
			
				if (equals) {
					// new version
					//ui_maximizePoiInfo(activeInfoDivs[i].tagId);
					// old version
					ui_closePoiInfo(activeInfoDivs[i].tagId);
					return;
				}
			}
		}
		
		UnTip();
		if (currentPOIs && currentPOIs.length > 0) ui_createInfoDIV();
	}
}

function ui_onMouseMoveMapa(tid, x, y) {
	ui_getPOIInfo(tid, map_localScreenToWorld(x, y), x, y);
}

function ui_delayMouseMoveMapa(event) {
	if (!document.getElementById("map_overlap")) return;
	if (!event) var event = window.event;
	
	screenx = event.offsetX?(event.offsetX):event.pageX-document.getElementById("map_overlap").offsetLeft;
	screeny = event.offsetY?(event.offsetY):event.pageY-document.getElementById("map_overlap").offsetTop;
	
	if (timeoutMouseMoveMapa)
		clearTimeout(timeoutMouseMoveMapa);
	if (navigator.userAgent.toLowerCase().indexOf("msie") == -1 && event.target && event.target.id)
		timeoutMouseMoveMapa = setTimeout('ui_onMouseMoveMapa(\'' + event.target.id + '\',' + screenx + ',' + screeny + ')', tipVerificationDelay);
	else if (event.srcElement && event.srcElement.id)
		timeoutMouseMoveMapa = setTimeout('ui_onMouseMoveMapa(\'' + event.srcElement.id + '\',' + screenx + ',' + screeny + ')', tipVerificationDelay);
}


function ui_zoomRelativo(dir) {
	ui_showLoader();
	map_zoomRelativo(dir);
}

function ui_zoomNivel(nivel) {
	ui_showLoader();
	map_zoomNivel(nivel);
}

function ui_highlightZoomNivel(nivel) {
	for(var i=0; i<10; i++)
		document.getElementById("zoom"+i).className = 'default';
	
	document.getElementById("zoom"+nivel).className = 'selected';
	currentNivel = nivel;
}

function ui_panMapa(dir) {
	ui_showLoader();
	map_pan(dir);
}

/* -------> Favoritos <------- */

function ui_viewFavoritos() {
	selectedFeature = null;
	ui_changeEstadoFavorito(0);	
	ui_changeEstadoRouting();
	ui_showFavoritos();
	if(informationIcon) document.getElementById("informacao").className = "inactive";
}

function ui_addFavorito() {
	var favoritos = readCookie();
	
	if(favoritos == "")
		favoritos = selectedFeature.id+"="+selectedFeature.concelho+"="+selectedFeature.nome+"="+selectedFeature.icon;
	else {
		if (favoritos.indexOf(selectedFeature.id)==-1)
			favoritos += "|"+selectedFeature.id+"="+selectedFeature.concelho+"="+selectedFeature.nome+"="+selectedFeature.icon;
	}

	createCookie(cookieName,favoritos);
	
	ui_changeEstadoFavorito(2);
	ui_showFavoritos();
}

function ui_delFavorito() {
	var favoritos = readCookie();
	var newfav = "";
	
	array_fav = favoritos.split("|");
	for (i=0; i<array_fav.length; i++) {
		if (array_fav[i].indexOf(selectedFeature.id) == -1)
			newfav += array_fav[i]+"|";
	}
	
	newfav = newfav.substring(0,newfav.length-1);
	
	createCookie(cookieName,newfav);
	
	document.getElementById("routing_start").className = "inactive";
	document.getElementById("routing_end").className = "inactive";
	ui_changeEstadoFavorito(0);
	ui_showFavoritos();	
}

function ui_existsFavorito() {
	var favoritos = readCookie();
	
	return (favoritos.indexOf(selectedFeature.id)==-1)?false:true;
}

function ui_changeEstadoFavorito(estado) {
	document.getElementById("favorites_add").className = (estado==1?"active":"inactive");
	document.getElementById("favorites_del").className = (estado==2?"active":"inactive");
}

function ui_showFavoritos() {

	var favoritos = readCookie();
	var nfavoritos = 0;
	var array_fav = new Array();
	var marked = null;
		
	if(favoritos != "") {
		array_fav = favoritos.split("|");
		
		nfavoritos = array_fav.length;
	}
		
	var html = "<p>Lista de favoritos: "+nfavoritos+"</p>";
	html += "<div id='lista'><ul id='innerlista'>";
	
	var grouped_favs = new Object();
	
	for (i=0; i<nfavoritos; i++) {
		// Sintaxe: id = grupo = nome
		var fav = array_fav[i].split("=");
		
		if (grouped_favs[fav[1]]==null)
			grouped_favs[fav[1]] = new Array(new Array(fav[0],fav[2],fav[3]));
		else 
			grouped_favs[fav[1]][grouped_favs[fav[1]].length] = new Array(fav[0],fav[2],fav[3]);
	}
	
	var ordered_favs = new Array();
	
	for (var group in grouped_favs) {
		ordered_favs[ordered_favs.length] = new Array(group, orderArrayOfArrays(grouped_favs[group],1));
	}
	
	// Ordenar os grupos
	ordered_favs = orderArrayOfArrays(ordered_favs,0);
		
	for (i=0; i<ordered_favs.length; i++) {
		html += "<li class='title'>"+ordered_favs[i][0]+"</li><ul class='sublista'><table>";
		
		var pois = ordered_favs[i][1];
		
		for (j=0; j<pois.length; j++) {
			var item_parts = pois[j][0].split("/");
			var tipo = item_parts[2];
			var colspan = " colspan=2";
			var icon = pois[j][2];
			var icon_arg = 'null';			
			
			var rid = "r" + i + "" + j;
						
			if(selectedFeature && selectedFeature.id == pois[j][0])
				marked = rid;
				
			html += "<tr>";
			if(tipo == "poi") {
				colspan = "";
				tipo = item_parts[3];
				html += "<td class='infoicon'>";
				html += "<span title=\"Ver descrição\"><a href='javascript: ui_selectFeature(\""+pois[j][0]+"\", \""+ordered_favs[i][0]+"\", \""+pois[j][1].replace(/"/g, "\\x22").replace(/'/g, "\\x27")+"\", true, null);' onclick='javascript: ui_markFeature(\""+rid+"\");'></a></span>";
				html += "</td>";
			}
			html += "<td"+colspan+">";
			
			var icon_style = " "+tipo;
			if(icon != "null") {
				icon_style = "' style='background-image: url("+icon+")";
				icon_arg = "\""+icon+"\"";
			}
							
			html += "<a href='javascript: ui_selectFeature(\""+pois[j][0]+"\", \""+ordered_favs[i][0]+"\", \""+pois[j][1].replace(/"/g, "\\x22").replace(/'/g, "\\x27")+"\", false, "+icon_arg+");'><span id='"+rid+"' onclick='javascript: ui_markFeature(\""+rid+"\");' title=\"Ver no mapa\" class='resultitem"+icon_style+"'>"+pois[j][1]+"</span></a>";
			html += "</td></tr>";
		}
		
		html += "</table></ul>";
	}
	
	html += "</ul></div>";

	document.getElementById("results").innerHTML = html;
	markedFeature = document.getElementById("fav_selection");
	if(marked)
		ui_markFeature(marked);
}

/* -------> Detalhe <------- */

function ui_viewMaisInformacao() {
	if(selectedFeature && selectedFeature.id != null && document.getElementById("informacao").className == 'active')
		ui_showDetalhe(selectedFeature.id);
}

function ui_showDetalhe(resource) {
	currentDetail = resource;
	data_getDetalhe(resource);
}

function ui_hideDetalhe() {
	document.getElementById("detail_holder").style.display = 'none';
	document.getElementById("left").style.display = 'block';
	document.getElementById("middle").style.display = 'block';
	
	currentDetail = null;
}

/* -------> Selecção <------- */

/*function ui_markFeature(obj) {
	if (markedFeature)
		markedFeature.className = markedFeature.className.replace("selected","");
	
	markedFeature = obj;
	
	if (markedFeature)
		markedFeature.className = markedFeature.className + " selected";
}*/

function ui_markFeature(id) {
	if (markedFeature)
		markedFeature.className = markedFeature.className.replace("selected","");
	
	markedFeature = document.getElementById(id);
	
	if (markedFeature)
		markedFeature.className = markedFeature.className + " selected";
}


function ui_selectFeature(resource, group, nome, showinfo, icon) {
	selectedFeature = new Feature(resource, nome, group, icon);
	
	if(showinfo)
		ui_showDetalhe(resource);
			
	if(informationIcon) {
		var tipo = resource.split("/")[2];
		switch(tipo) {
			case 'poi':
				document.getElementById("informacao").className = "active";
				break;
			default:
				document.getElementById("informacao").className = "inactive";
		}
	}
	
	ui_existsFavorito(selectedFeature.id)?ui_changeEstadoFavorito(2):ui_changeEstadoFavorito(1);
	
	ui_changeEstadoRouting();
	
	if(!showinfo)
		ui_hideDetalhe();
		
	map_selectFeature(resource);
	
}

/* -------> POI <------- */

function ui_setPoiTips(req) {
	if (!validateJSON(req)) return false;
	
	poiInfo = eval('(' + req.responseText + ')');
}

function ui_getPOIIcon(feature_id, scl) {
	var url = 'default.gif';
	if (poiIcons && poiIcons[feature_id]) {
		var zoom = Infinity;
		
		for (var i = 0; i < poiIcons[feature_id].length; i++) {
			if (poiIcons[feature_id][i][1] <= zoom && poiIcons[feature_id][i][1] > scl) {
				zoom = poiIcons[feature_id][i][1];
				url = poiIcons[feature_id][i][0];
			}
		}
	}
	
	return url;
}

function ui_getPOIIconResults(feature_id) {
	var url = null;
	if (poiIcons && poiIcons[feature_id]) {
		if (poiIcons[feature_id][poiIcons[feature_id].length - 1] && poiIcons[feature_id][poiIcons[feature_id].length - 1][0])
			url = poiIcons[feature_id][poiIcons[feature_id].length - 1][0];
	
		var zoom = Infinity;
		
		for (var i = 0; i < poiIcons[feature_id].length; i++) {
			if (poiIcons[feature_id][i][1] <= zoom && poiIcons[feature_id][i][1] > scale * 2) {
				zoom = poiIcons[feature_id][i][1];
				url = poiIcons[feature_id][i][0];
			}
		}
	}
	
	return url;
}

function ui_getPOIInfo(tid, pixel, px, py) {
	var mapa = document.getElementById("mapimage");
	
	currentPOIs = new Array();
	
	if (px >= 0 && px < size_h && py >= 0 && py < size_v && tid == 'mapimage') {
		var tipNew;
	
		if (pixel && poiInfo) {
			for (var i = 0; i < poiInfo.result.length; i++) {
				var dx = pixel[0] - poiInfo.result[i][0];
				var dy = pixel[1] - poiInfo.result[i][1];
				
				if (Math.abs(dx) <= 7 * scl && Math.abs(dy) <= 7 * scl)
					currentPOIs.push(new POI(poiInfo.result[i][3], poiInfo.result[i][0], poiInfo.result[i][1], poiInfo.result[i][2], poiInfo.result[i][4]));
			}
		}
	
		if (currentPOIs.length != 0) {
			tipNew = '';
			for (var i = 0; i < currentPOIs.length; i++) {
				tipNew += currentPOIs[i].feature_id;
			}
			if (tipOn != tipNew) {
				for (var i = 0; i < activeInfoDivs.length; i++) {
					if (activeInfoDivs[i]) {
						var equals = ui_equalsCurrentPOIs(activeInfoDivs[i].POIs);
			
						if (equals) {
							tipOn = '';
							mapa.style.cursor = 'pointer';
							return;
						}
					}
				}
				if (tooltipStyle) {
					for (var i = tooltipStyle.length - 1; i >= 0; i--) {
						if ((Math.max(size_v, size_h) / (scale * 2)) > tooltipStyle[i].scale) {
							var tipHTML = '<ul class="tooltipList">';
							for (var j = 0; j < currentPOIs.length; j++) {
								tipHTML += ('<li style="color: ' + tooltipStyle[i].fontColor + ';"><img width="15" height="15" src="' + ui_getPOIIcon(currentPOIs[j].feature_id, 0) + '" />' + currentPOIs[j].nome + '</li>');
							}
							tipHTML += '</ul>';
							Tip(tipHTML, DELAY, 100,
										 FADEIN, 150,
										 BGCOLOR, tooltipStyle[i].brushColor,
										 BORDERCOLOR, tooltipStyle[i].penColor,
										 BORDERWIDTH, tooltipStyle[i].border,
										 FONTFACE, tooltipStyle[i].font,
										 FONTSIZE, tooltipStyle[i].fontSize,
										 OPACITY, tooltipStyle[i].brushAlpha);
							tipOn = tipNew;
							break;
						}
					}
					
				}
			}
			mapa.style.cursor = 'pointer';
		}
		else {
			UnTip();
			tipOn = '';
			mapa.style.cursor = 'default';
		}	
	}
	else {
		UnTip();
		tipOn = '';
		mapa.style.cursor = 'default';
	}
}

function ui_equalsCurrentPOIs(list) {
	var equals = 0;
	for (var i = 0; i < list.length; i++) {		
		for (var k = 0; k < currentPOIs.length; k++) {
			if (list[i].id == currentPOIs[k].id) {
				equals++;
				break;
			}
		}
	}
	
	return (list.length == equals);
}

function ui_createInfoDIV() {
	var POIs = new Array();
	for (var i = 0; i < currentPOIs.length; i++) {
		POIs.push(currentPOIs[i]);
	}
	
	var res = map_localWorldToScreen(currentPOIs[0].x, currentPOIs[0].y);
	
	var px = res[0];
	var py = res[1];
	var info = new InfoDIV(px, py, POIs);
	activeInfoDivs.push(info);

	var map = document.getElementById("map_draw");
	var newTable = document.createElement('table');
	var newTBody = document.createElement('tbody');
	var rowUpBorder = document.createElement('tr');
	var rowHeader = document.createElement('tr');
	var rowBody = document.createElement('tr');
	var rowDownBorder = document.createElement('tr');
	
	// upBorder
	var cell11 = document.createElement('td');
	cell11.className = 'ballon1';
	var cell12 = document.createElement('td');
	cell12.colSpan = 2;
	cell12.className = 'ballon2';
	var cell13 = document.createElement('td');
	cell13.className = 'ballon3';
	
	// header
	var cellLeft = document.createElement('td');
	//cellLeft.rowSpan = 2;
	cellLeft.className = 'ballon8';
	var cellNames = document.createElement('td');
	cellNames.className = 'poiInfoHeader ballon9';
	
	var tableHTML = '<table><tbody>';
	for (var i = 0; i < currentPOIs.length; i++) {
		if (currentPOIs[i])
			tableHTML += '<tr><td align="center"><img src="' + ui_getPOIIcon(currentPOIs[i].feature_id, 0) + '" /></td><td><a href=\'javascript: ui_setPOIInfo("' + info.tagId + '", "' + currentPOIs[i].id + '");\'>' + currentPOIs[i].nome + '</a></td></tr>';
	}
	tableHTML += '</tbody></table>';
	cellNames.innerHTML = tableHTML;
	
	
	var cellActions = document.createElement('td');
	cellActions.className = 'poiInfoActions ballon9';
	
	var cellRight = document.createElement('td');
	//cellRight.rowSpan = 2;
	cellRight.className = 'ballon4';
	
	// body
	var cellBody = document.createElement('td');
	cellBody.className = 'poiInfoBody ballon9';
	cellBody.colSpan = 2;
	
	// downBorder
	var cell21 = document.createElement('td');
	cell21.className = 'ballon7';
	var cell22 = document.createElement('td');
	cell22.colSpan = 2;
	cell22.className = 'ballon6';
	var cell23 = document.createElement('td');
	cell23.className = 'ballon5';
	
	// append everything
	rowUpBorder.appendChild(cell11);
	rowUpBorder.appendChild(cell12);
	rowUpBorder.appendChild(cell13);
	
	rowHeader.appendChild(cellLeft);
	rowHeader.appendChild(cellNames);
	rowHeader.appendChild(cellActions);
	rowHeader.appendChild(cellRight);
	
	rowBody.appendChild(cellBody);
	
	rowDownBorder.appendChild(cell21);
	rowDownBorder.appendChild(cell22);
	rowDownBorder.appendChild(cell23);
	
	newTable.style.position = "absolute";
	newTable.style.left = px + 'px';
	newTable.style.top = py + 'px';
	newTable.id = info.tagId;
	
	newTBody.appendChild(rowUpBorder);
	newTBody.appendChild(rowHeader);
	//newTBody.appendChild(rowBody);
	newTBody.appendChild(rowDownBorder);
	
	newTable.appendChild(newTBody);
	
	map.appendChild(newTable);
	
	ui_setPOIInfoActions(info.tagId);
	// new version
	//ui_setPOIInfo(info.tagId, currentPOIs[0].id);
	// old version
	ui_minimizePoiInfo(info.tagId);
	
	ui_refreshPoiInfoClassName(info.tagId);
}

function ui_refreshAllPoiInfoClassNames() {
	for (var i = 0; i < activeInfoDivs.length; i++)
		if (activeInfoDivs[i])
			ui_refreshPoiInfoClassName(activeInfoDivs[i].tagId);
}

function ui_refreshPoiInfoClassName(tagId) {
	for (var i = 0; i < activeInfoDivs.length; i++) {
		if (activeInfoDivs[i] && activeInfoDivs[i].tagId == tagId) {
			var ballon = document.getElementById(tagId);
			if (activeInfoDivs[i].POIs.length > 1)
				ballon.className = 'defaultBallon ' + data_getBallonClassName(0);
			else
				ballon.className = 'defaultBallon ' + data_getBallonClassName(activeInfoDivs[i].POIs[0].feature_id);
		}
	}
}

function ui_setPOIInfo(tagId, poiId) {
	var elem = getElementsByClass('poiInfoBody', document.getElementById(tagId), 'td');
	
	// new version
	//loadXMLDoc(server + poiId + "/detail", data_populateDetalhe, elem[0]);
	//ui_maximizePoiInfo(tagId);
	// old version
	loadXMLDoc(server + poiId + "/detail", data_populateDetalhe);
}

function ui_choosePoiInfo(tagId) {
	for (var i = 0; i < activeInfoDivs.length; i++)
		if (activeInfoDivs[i] && activeInfoDivs[i].tagId == tagId)
			return activeInfoDivs[i];
	
	return null;
}

function ui_setPOIInfoActions(tagId) {
	var poiInfo = ui_choosePoiInfo(tagId);
	
	if (poiInfo) {
		var elem = getElementsByClass('poiInfoActions', document.getElementById(tagId), 'td');
		var tempHTML = '';
	
		// new version
		/*
		if (poiInfo.minimized) {
			tempHTML += '<a href=\'javascript: ui_maximizePoiInfo(\"' + tagId + '\");\'>+</a>';
		}
		else {
			tempHTML += '<a href=\'javascript: ui_minimizePoiInfo(\"' + tagId + '\");\'>-</a>';
		}
		*/
		tempHTML += '<a href=\'javascript: ui_closePoiInfo(\"' + tagId + '\");\'>x</a>';
	
		if (elem.length >= 1) elem[0].innerHTML = tempHTML;
	}
}

function ui_maximizePoiInfo(tagId) {
	var poiInfo = ui_choosePoiInfo(tagId);
	
	if (poiInfo) {
		var elem = getElementsByClass('poiInfoBody', document.getElementById(tagId), 'td');
		
		if (elem.length >= 1) elem[0].style.display = '';
		
		poiInfo.minimized = false;
		ui_setPOIInfoActions(tagId);
	}
}

function ui_minimizePoiInfo(tagId) {
	var poiInfo = ui_choosePoiInfo(tagId);
	
	if (poiInfo) {
		var elem = getElementsByClass('poiInfoBody', document.getElementById(tagId), 'td');
		
		if (elem.length >= 1) elem[0].style.display = 'none';
		
		poiInfo.minimized = true;
		ui_setPOIInfoActions(tagId);
	}
}

function ui_closePoiInfo(tagId) {
	for (var i = 0; i < activeInfoDivs.length; i++) {
		if (activeInfoDivs[i] && activeInfoDivs[i].tagId == tagId) {
			activeInfoDivs[i] = null;
			
			var elem = document.getElementById(tagId);
			elem.parentNode.removeChild(elem);
			
			break;
		}
	}
}

function ui_updatePoiInfoPosition() {
	for (var i = 0; i < activeInfoDivs.length; i++) {
		if (activeInfoDivs[i]) {
			var elem = document.getElementById(activeInfoDivs[i].tagId);
			
			if (elem) {
				var res = map_localWorldToScreen(activeInfoDivs[i].x, activeInfoDivs[i].y);
			
				elem.style.left = res[0] + 'px';
				elem.style.top = res[1] + 'px';
			}
		}
	}
}
