VisorUMAT = function() {
	var _this = this;
	
	this.debug = false;

	this.connectat = true;
	this.disponible = true;

	this.dragging = false;
	this.panning = false;

	this.theX = 0;
	this.theY = 0;

	this.isNav = (window.navigator.appName.toLowerCase().indexOf("netscape")>=0);
	this.isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

	this.mtop;
	this.mleft;
	this.mwidth;
	this.mheight;
	this.mbroder;

	// Envelope de la imatge actual
	this.minx = 0;
	this.maxx = 0;
	this.miny = 0;
	this.maxy = 0;

	this.x1;
	this.y1;
	this.x2;
	this.y2;

	this.zleft = 0;
	this.zright = 0;
	this.ztop = 0;
	this.zbottom = 0;

	this.mapDivId;
	this.activeTool;
	
	this.extraHeight = 0;

	this.coord_x;
	this.coord_y;
	
	this.mesura_x;
	this.mesura_y;
	this.mesura_total = 0;
	
	this.eines = new Array();
	
	this.baseUrl;
	
	this.toc = new Array();

	{
		var strHref = window.location.href;
		var strQueryString = "";
		if (strHref.indexOf("?") > -1 ) {
		    strQueryString = strHref.substr(0, strHref.indexOf("?"));
		} else {
			strQueryString = strHref;
		}
		_this.baseUrl = strQueryString.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '') + '/';
		
		var handler = function(message, ex) {
			if (message == 'sessio_caducada') {
				_this.sessio_caducada();
			} else if (message == 'no_disponible') {
				//FIXME: i18n
				_this.no_disponible("Servei no disponible temporalment. Disculpeu les molèsties.");
				_this.connectat = false;
			} else if (message == 'Timeout') {
				//FIXME: i18n
				alert("S'ha esgotat el temps d'espera. Torneu a intentar-ho.");
			} else if (message == "Error") {
				alert("S'ha produit un error al realitzar l'operació (1)");
			} else if (ex.javaClassName == "java.lang.NullPointerException") {
				alert("S'ha produit un error al realitzar l'operació (2)");
			} else {
				if (_this.debug) {
					alert(message + ":\n" + ex.javaClassName + ": " + ex.message);
				}
				alert("S'ha produit un error al realitzar l'operació (3)");
			}

			_this.cancelar_refresh();
		};
		
		dwr.engine.setErrorHandler(handler);
		dwr.engine.setWarningHandler(handler);

		DWREngine.setTimeout(30000);
	}

	// Canviar el tamany dels divs per ajustar-nos a la pantalla
	this.contingut_tamany_canviar = function () {

		// Altures
		var nova_altura = dojo.html.getViewport().height;
		var capsalera_altura = dojo.html.getMarginBox(dojo.byId('capsalera')).height;
		var opcions_servei_altura = dojo.html.getMarginBox(dojo.byId('opcions_servei')).height;
		var centre_altura = nova_altura - capsalera_altura - 75;
		var eines_altura = dojo.html.getMarginBox(dojo.byId('divEines')).height;
		if (eines_altura > centre_altura) {
			centre_altura = eines_altura - 3;
		}
		var mapa_altura = centre_altura - opcions_servei_altura - _this.extraHeight;

		// Amplades
		var nova_amplada = dojo.html.getViewport().width;
		var eines_width = dojo.html.getMarginBox(dojo.byId('divEines')).width;
		var toc_width = dojo.html.getMarginBox(dojo.byId('menu')).width;
		var centre_amplada = nova_amplada - 20;
		dojo.html.setMarginBox(dojo.byId('taula_centre'), {width: centre_amplada});

		var mapa_amplada = nova_amplada - eines_width - toc_width - 20;
		dojo.html.setMarginBox(dojo.byId('centre'), {height: centre_altura});
		dojo.html.setMarginBox(dojo.byId('mapDiv'), {height: mapa_altura});
		dojo.html.setMarginBox(dojo.byId('mapDiv'), {width: mapa_amplada});

		dojo.html.setMarginBox(dojo.byId('mapArea'), {height: mapa_altura});
		dojo.html.setMarginBox(dojo.byId('mapArea'), {width: mapa_amplada});
	
		var mtop = dojo.html.getAbsolutePosition(dojo.byId('mapDiv'), true).y;
		var mleft = dojo.html.getAbsolutePosition(dojo.byId('mapDiv'), true).x;
		var mwidth = mapa_amplada;
		var mheight = mapa_altura;
		
		dojo.byId('progres').style.top = ((mapa_altura / 2) - 50) + "px";
		dojo.byId('progres').style.left = ((mapa_amplada / 2) - 50) + "px";

		_this.border = 1;
		_this.mtop = mtop + _this.border;
		_this.mleft = mleft + _this.border;
		_this.mwidth = mwidth - (2 * _this.border);
		_this.mheight = mheight - (2 * _this.border);
		_this.mborder = _this.border;

		_this.queue_refresh();
	}
	
	this.setExtraHeight = function(height) {
		_this.extraHeight = height;
	}

	// Número de peticions pendents
	this.actions_queued = 0;

	// Encuar les peticions
	this.queue_refresh = function() {
		if (!_this.connectat) {
			return;
		}

		_this.actions_queued++;
		dojo.lang.setTimeout(_this, "unqueue_refresh", 1000);
	}

	// Fer la petició del mapa al desencuar totes les peticions
	this.unqueue_refresh = function() {
		_this.actions_queued--;

		if (!_this.connectat) {
			return;
		}

		if (_this.actions_queued == 0) {
			_this.requestMap();
		}
	}
	
	this.cancelar_refresh = function() {
		dojo.byId('progres').style.display = "none";
		_this.loading = 0;
	}

	this.loading = 0;

	this.last_action = 0;


	// Funció d'actualització per les crides amb dwr
	this.updateVisor = function(canvis) {
		if (canvis.urlMapa != null) {
			var image = dwr.util.byId("theImage");
			image.src = canvis.urlMapa;
			image.onload = _this.resetAfterPan;
		}

		if (canvis.urlOverview != null) {
			var image = dwr.util.byId("ovimage0");
			image.src = canvis.urlOverview;
		}
		
		if (canvis.missatge != null) {
			alert(canvis.missatge);
			dojo.byId('progres').style.display = "none";
			_this.loading = 0;
		}
		
		if ((canvis.minx != null) && (canvis.minx != 0.0)) {
			var canviat = false;
			if ((_this.minx != canvis.minx)
			  ||(_this.miny != canvis.miny)
			  ||(_this.maxx != canvis.maxx)
			  ||(_this.maxy != canvis.maxy)) {
				_this.minx = canvis.minx;
				_this.miny = canvis.miny;
				_this.maxx = canvis.maxx;
				_this.maxy = canvis.maxy;

				_this.refreshOVMap();
			}
		}

		if (canvis.imatges != null) {
			for (var imatge in canvis.imatges) {
				var object = dwr.util.byId(imatge);
				if ((object == undefined) && (_this.debug)) {
					alert("not found: " + imatge);
				}
				object.src = canvis.imatges[imatge];
			}
		}

		if (canvis.valors != null) {
			for (var valor in canvis.valors) {
				var object = dwr.util.byId(valor);
				dwr.util.setValue(valor, canvis.valors[valor], { escapeHtml:false });
				if (valor == "divIdentify") {
					dojo.byId('fletxaIdentify').src = 'imatges/fletxa2.gif';
					dojo.lang.setTimeout(_this, "stop_identify_animation", 5000);
				}
			}
		}

		if (canvis.hyperlink != null) {
			var hl = canvis.hyperlink;
			if (hl.nom == '_self') {
				location.href = hl["url"];
				window.open(hl["url"], hl["nom"], hl["opcions"]);
			} else {
				window.open(hl["url"], hl["nom"], hl["opcions"]);
			}
		}

		if (canvis.tocNodes != null) {
			var nodes = canvis.tocNodes;
			
			for (i = 0; i < nodes.length; i++) {
			 	var id = nodes[i].id;
			 	if (_this.toc[id] != undefined) {
					_this.toc[id].visible = nodes[i].visible;
					_this.toc[id].displayed = nodes[i].displayed;
					_this.toc[id].visibleStatus = nodes[i].visibleStatus;
					_this.toc[id].updateIcon();
				}
			}
		}

		if (canvis.coordenades != null) {
			var coord = canvis.coordenades;

			for (i = 0; i < coord.length; i++) {
				tipus = coord[i].tipus;
				
				if (tipus == "afegir") {
					var x = coord[i].x;
					var y = coord[i].y;
					var anar = coord[i].anar;
					var esborrar = coord[i].esborrar;
					var data = {0:x, 1:y, 2:anar, 3:esborrar};
					table_append_row('taula_coordenades', 'coord_' + x + '_' + y, data);
				}

				if (tipus == "esborrar") {
					var id = coord[i].rowId;
					table_remove_row('taula_coordenades', id);
				}
			}
		}
  	}

	this.getVisorId = function() {
		return dwr.util.getValue("mapId");
	}

	this.ping = function() {
		dojo.lang.setTimeout(_this, "ping", 300000);
		
		Visor.ping(_this.getVisorId(), {
			callback: function(data) {},
  			errorHandler: function(errorString, exception) {},
  			warningHandler: function(errorString, exception) {}
  			});
	}

	// Comandes directes
	this.requestMap = function() {
		_this.startLoading();
		Visor.requestMap(_this.getVisorId(),
					 _this.mheight, _this.mwidth, /* mida del mapa */
					 _this.updateVisor);
	}

	this.refreshOVMap = function() {
		Visor.refreshOVMap(_this.getVisorId(),
					 _this.updateVisor);
	}

	this.zoomIn = function(left, bottom, right, top) {
		_this.startLoading();
		Visor.zoomIn(_this.getVisorId(),
					 left, bottom, right, top,
					 _this.updateVisor);
	}
	
	this.zoomOut = function(left, bottom, right, top) {
		_this.startLoading();
		Visor.zoomOut(_this.getVisorId(),
					 left, bottom, right, top,
					 _this.updateVisor);
	}

	this.zoomInFixed = function(x, y) {
		_this.startLoading();
		Visor.zoomInFixed(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
	}

	this.zoomFull = function() {
		_this.startLoading();
		Visor.zoomFull(_this.getVisorId(),
					 _this.updateVisor);
	}

	this.zoomPrevious = function() {
		_this.startLoading();
		Visor.zoomPrevious(_this.getVisorId(),
					 _this.updateVisor);
	}

	this.hyperlink = function(x, y) {
		//FIXME: indicador de progrés per l'identify
//				_this.startLoading();
				Visor.hyperlink(_this.getVisorId(),
							 _this.getLayerActiu(), /* grup seleccionat */
							 x, y,
							 _this.updateVisor);
	}

	this.identify = function(x, y) {
//FIXME: indicador de progrés per l'identify
//		_this.startLoading();
		Visor.identify(_this.getVisorId(),
					 _this.getLayerActiu(), /* grup seleccionat */
					 x, y,
					 _this.updateVisor);
	}

	this.selection = function(left, bottom, right, top) {
		_this.startLoading();
		Visor.selection(_this.getVisorId(),
					 _this.getLayerActiu(), /* grup seleccionat */
					 left, bottom, right, top,
					 _this.updateVisor);
	}

	this.coordenadesAfegir = function(x, y) {
		Visor.coordenadesAfegir(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
		_this.queue_refresh();
	}

	this.coordenadesAnar = function(x, y) {
		_this.startLoading();
		Visor.coordenadesAnar(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
	}

	this.coordenadesEsborrar = function(x, y) {
		Visor.coordenadesEsborrar(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
		_this.queue_refresh();
	}

	this.coordenadesUTMAfegir = function(x, y) {
		Visor.coordenadesUTMAfegir(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
		_this.queue_refresh();
	}

	this.clear = function(eina) {
		_this.startLoading();
		Visor.clear(_this.getVisorId(),
					 eina,
					 _this.updateVisor);
	}

	this.mesura = function(x, y) {
		Visor.mesura(_this.getVisorId(),
					 x, y,
					 _this.updateVisor);
		_this.queue_refresh();
	}
		
	this.seleccio_carrer = function(carrer) {
		_this.startLoading();
		Visor.seleccioCarrer(_this.getVisorId(),
					 carrer,
					 _this.updateVisor);
	}

	this.seleccio_edifici = function(edifici) {
		_this.startLoading();
		Visor.seleccioEdifici(_this.getVisorId(),
					 edifici,
					 _this.updateVisor);
	}

	this.seleccio_facana = function(numero) {
		_this.startLoading();
		Visor.seleccioFacana(_this.getVisorId(),
					 numero,
					 _this.updateVisor);
	}

	this.seleccio_parcela = function(parcela) {
		_this.startLoading();
		Visor.seleccioParcela(_this.getVisorId(),
					 parcela,
					 _this.updateVisor);
	}

	this.seleccio = function(selector, valor) {
		_this.startLoading();
		Visor.seleccio(_this.getVisorId(),
					 selector, valor,
					 _this.updateVisor);
	}

	this.aimsconsulta = function(layer, query, c, d) {
		_this.startLoading();
		Visor.aimsconsulta(_this.getVisorId(),
					 layer, query,
					 _this.updateVisor);
	}

	this.vista = function(vista) {
		_this.startLoading();
		Visor.vista(_this.getVisorId(),
					 vista,
					 _this.updateVisor);
	}

	// Ajudes
	this.startLoading = function() {
		_this.loading = _this.loading + 1;
		dojo.byId('progres').style.display = "";
	}

	this.getLayerActiu = function() {
		var layerActiu = dojo.byId('layerActiu');
		if (layerActiu != undefined) {
			return layerActiu.options[layerActiu.selectedIndex].value;
		} else {
			//FIXME:
			return 0;
		}
	}

	this.processarResposta = function(type, data, evt) {
		var json = data;

		if (json.no_disponible != undefined) {
			_this.no_disponible(json.no_disponible);
			_this.connectat = false;
			_this.cancelar_refresh();
			return;
		}

		if (json.identify != undefined) {
			dojo.byId('divIdentify').innerHTML = json.identify;
			dojo.byId('fletxaIdentify').src = 'imatges/fletxa2.gif';
			dojo.lang.setTimeout(_this, "stop_identify_animation", 5000);
		}

	}

	this.stop_identify_animation = function() {
		dojo.byId('fletxaIdentify').src = 'imatges/fletxa.gif';
	}

	// Auxiliars
	this.sessio_caducada = function() {
		alert("La sessió ha caducat, es reiniciarà l'aplicació");
		_this.connectat = false;
		window.location.reload();
	}

	this.no_disponible = function(missatge) {
		var me = dojo.byId("no_disponible");
		me.style.display = "";
		me.innerHTML = missatge;

		_this.contingut_tamany_canviar();
	}

	// aplicació
	this.actualitzaCoordenades = function(e) {
		if (_this.coord_x == undefined) {
			_this.coord_x = dojo.byId('coord_x');
		}
		if (_this.coord_y == undefined) {
			_this.coord_y = dojo.byId('coord_y');
		}
		_this.getXY(e);
		var x = _this.theX - _this.mleft + _this.border;
		var y = _this.theY - _this.mtop + _this.border;
		var point = _this.convertPixelToMap(x, y);

		_this.coord_x.value = point[0].toFixed();
		_this.coord_y.value = point[1].toFixed();

  		switch(_this.activeTool) {
		case "measure":
			var mesura_segment = dojo.byId('mesura_segment');
			if (mesura_segment != undefined) {
				if (_this.mesura_x != undefined) {
					var distancia = _this.distancia(_this.coord_x.value, _this.coord_y.value, _this.mesura_x, _this.mesura_y);
					mesura_segment.value = distancia.toFixed(1) + " metres";
				}
			}
	  		break;
	  	}

	}

	this.distancia = function(x1, y1, x2, y2) {
		var x = x1 - x2;
		var y = y1 - y2;
		return Math.sqrt(x*x + y*y);
	}

	this.convertPixelToMap = function(px, py) {
		var dx = (_this.maxx - _this.minx)/_this.mwidth;
		var mx = _this.minx + (dx * px);
		var dy = (_this.maxy - _this.miny)/_this.mheight;
		var my = _this.maxy - (dy * py);
		var newpoint = new Array();
		newpoint[0] = mx;
		newpoint[1] = my;
		return newpoint;
	}

	this.resetAfterPan = function(){
		_this.moveLayer(_this.mapDivId, 0, 0);
		_this.clipLayer2(_this.mapDivId, 0, 0, 500, 500);
		document.getElementById('theImage').onload = null;
		_this.loading = _this.loading - 1;
		if (_this.loading < 1) {
			dojo.byId('progres').style.display = "none";
			_this.loading = 0;
		}
	}
	
	this.moveLayer = function(name, x, y) {
	  	var layer = _this.getLayer(name);
	    layer.left = x + "px";
	   	layer.top  = y + "px";
	}
	
	this.clipLayer2 = function(name, clipleft, cliptop, clipright, clipbottom) {
		var layer = _this.getLayer(name);
		layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	}

	this.getLayer = function(name) {
		var theObj = document.getElementById(name);
		if (theObj!=null) {
			return theObj.style
		} else {
			return(null);
		}
	}

	this.startDragging = function(e){
		_this.panning = false;
		if(!_this.dragging){
			_this.dragging = true;
			_this.getXY(e);
			_this.x1 = _this.theX;
			_this.y1 = _this.theY;
			_this.x2 = _this.x1+1;
			_this.y2 = _this.y1+1;

			_this.showZoomBox(_this.x1,_this.y1,_this.x2,_this.y2);
			
			document.onmousemove = _this.updateDragging;
			document.onmouseup = _this.stopDragging;
			
		}
		return false;
	}

	this.startMapDragging = function(e) {
		_this.dragging = false;
		if (!_this.panning) {
			_this.panning = true;
			_this.getXY(e);
			_this.x1 = _this.theX;
			_this.y1 = _this.theY
			_this.x2 = _this.x1+1;
			_this.y2 = _this.y1+1;
			var layer = document.getElementById(_this.mapDivId);
	 
			document.onmousemove = _this.updateMapDragging;
			document.onmouseup = _this.stopMapDragging;
		}
		return false;
	}

	this.updateDragging = function(e){
		if (_this.dragging) {
			_this.getXY(e);
			_this.x2 = _this.theX;
			_this.y2 = _this.theY;
			//var inside = true;
			if (_this.x2 < _this.mleft) {
				_this.x2 = _this.mleft;
				//inside = false;
			}
			if (_this.x2 >  _this.mleft + _this.mwidth ) {
				_this.x2 = _this.mleft + _this.mwidth ;
				//inside = false;
			}
			if (_this.y2 < _this.mtop ) {
				_this.y2 = _this.mtop;
				//inside = false;	
			}
			if (_this.y2 > _this.mtop + _this.mheight) {
				_this.y2 = _this.mtop +  _this.mheight ;
				//inside = false;
			}
			_this.setClip();
		}
		return false
	}
	
	this.updateMapDragging = function(e) {
		if (_this.panning) {
			_this.getXY(e);
			_this.x2 = _this.theX;
			_this.y2 = _this.theY;
			if (_this.x2 < _this.mleft) _this.x2 = _this.mleft;
			if (_this.x2 > _this.mleft + _this.mwidth) _this.x2 = _this.mleft + _this.mwidth;
			if (_this.y2 < _this.mtop) _this.y2 = _this.mtop;
			if (_this.y2 > _this.mtop + _this.mheight) _this.y2 = _this.mtop + _this.mheight;
			var dx = _this.x2 - _this.x1;
			var dy = _this.y2 - _this.y1;

			var cLeft = - dx;
			var cTop = - dy;
			var cRight = _this.mwidth;
			var cBottom = _this.mheight;
			if (dx>0) {
				cLeft = 0;
				cRight = _this.mwidth - dx;
			}
			if (dy>0) {
				cTop = 0;
				cBottom = _this.mheight - dy;
			}
	
			_this.moveLayer(_this.mapDivId, dx, dy);
			_this.panClipLayer(_this.mapDivId,cLeft,cTop,cRight,cBottom);
			
		}
		return false;
	}

	this.stopMapDragging = function(e){
		if (_this.panning) {
			_this.panning = false;
			
			_this.getXY(e);
			document.onmousemove = null;
			document.onmouseup = null;
			
			var ixOffset = _this.x2 - _this.x1;
			var iyOffset = _this.y2 - _this.y1;

			var point = _this.convertPixelToMap(ixOffset, iyOffset);

			var dx = _this.minx - point[0];
			var dy = _this.maxy - point[1];
			_this.zoomIn((_this.minx + dx).toFixed(),
					(_this.miny + dy).toFixed(),
					(_this.maxx + dx).toFixed(),
					(_this.maxy + dy).toFixed());

			return false;
		}
	}

	this.stopDragging = function(e){
		if (_this.dragging) {
			_this.dragging = false;
			
			_this.getXY(e);
			document.onmousemove = null;
			document.onmouseup = null;
			_this.hideZoomBox();
			_this.setClip();
			// adjust for offsets
			_this.zleft -= _this.mleft;
			_this.zright -= _this.mleft;
			_this.zbottom -= _this.mtop;
			_this.ztop -= _this.mtop;

			var p1 = _this.convertPixelToMap(_this.zleft, _this.zbottom);
			var p2 = _this.convertPixelToMap(_this.zright, _this.ztop);

			switch (_this.activeTool) {
			case "zoomin":
				if (_this.zleft + 10 <= _this.zright) {
					_this.zoomIn(p1[0].toFixed(), p1[1].toFixed(), p2[0].toFixed(), p2[1].toFixed());
				} else {
					_this.zoomInFixed(((p1[0] + p2[0])/2).toFixed(), ((p1[1] + p2[1])/2).toFixed());
				}
				break;

			case "zoomout":
				_this.zoomOut(p1[0].toFixed(), p1[1].toFixed(), p2[0].toFixed(), p2[1].toFixed());
				break;

			case "selection":
				_this.selection(p1[0].toFixed(), p1[1].toFixed(), p2[0].toFixed(), p2[1].toFixed());
				break;

			default:
				break;
			}
			return false;
		}
	}
	
	this.afegirEina = function(eina) {
		_this.eines[_this.eines.length] = eina;
	}

	this.setActiveTool = function(tool) {
		if (_this.activeTool == tool) {
			return;
		}

		// Amagar les opcions de l'eina anterior
		var div;
		switch(_this.activeTool) {
		case "hyperlink":
		case "selection":
			div = dojo.byId('identify' + 'OptionsDiv');
			break;

		default:
			div = dojo.byId(_this.activeTool + 'OptionsDiv');
			break;
		}
		if (div != undefined) {
			div.style.display = "none";
		}

  		var layer = document.getElementById(_this.mapDivId);

  		switch(tool) {
  		// Accion on marquem una zona
		case "zoomin":
		case "zoomout":
      		layer.onmousedown = _this.startDragging;
   			layer.onclick = null;
   			layer.style.cursor = "crosshair";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
	  		break;

		case "hyperlink":
   			layer.onmousedown = _this.pointClick;
   			layer.onclick= null;
   			layer.style.cursor = "crosshair";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			_this.ensenyaElement('identify' + 'OptionsDiv');
	  		break;
	  	
		case "selection":
      		layer.onmousedown = _this.startDragging;
   			layer.onclick = null;
   			layer.style.cursor = "crosshair";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			_this.ensenyaElement('identify' + 'OptionsDiv');
	  		break;

		case "pan":
			layer.onmousedown = _this.startMapDragging;
   			layer.onclick = null;
   			layer.style.cursor = "move";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
   			break;

		case "identify":
		case "measure":
		case "capturaCoordenades":		
   			layer.onmousedown = _this.pointClick;
   			layer.onclick= null;
   			layer.style.cursor = "crosshair";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			break;

		case "print":
			layer.onmousedown = null;
   			layer.onclick = null;
   			layer.style.cursor = "crosshair";
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			_this.ensenyaElement(tool + 'OptionsDiv');
			break;

		case "save":
			var iframe = dojo.byId('iframe2');
			iframe.visorId.value = dojo.byId("mapId").value;
			iframe.submit();
			break;

		case "informacio_csv":
			var iframe = dojo.byId('iframe_csv');
			iframe.visorId.value = dojo.byId("mapId").value;
			iframe.layer.value = _this.getLayerActiu();
			iframe.submit();
			break;

	  	// Accions directes
	  	case "zoomfull":
	  		_this.zoomFull();
	  		break;

	  	case "zoomprevious":
	  		_this.zoomPrevious();
			break;

	  	case "clear":
			_this.clear(_this.activeTool);

	  		if (_this.activeTool == "capturaCoordenades") {
				var table = document.getElementById('taula_coordenades');
				while (table.rows.length > 0) {
					table.deleteRow(0);
				}
	  		}

			if (_this.activeTool == "measure") {
				_this.mesura_total = 0;
				_this.mesura_x = undefined;
				_this.mesura_y = undefined;
				dojo.byId('mesura_segment').value = "0 metres";
				dojo.byId('mesura_total').value = "0 metres";
			}
			break;

		case "anarCoordenades":
	  		_this.activeTool = tool;
	  		break;

		// Accions directes amb retràs
		case "zoominfixed":
			_this.zoomInFixed((_this.minx + _this.maxx)/2, (_this.miny + _this.maxy)/2);
			break;

		case "zoomoutfixed":
			_this.zoomOut((_this.minx + _this.maxx)/2, (_this.miny + _this.maxy)/2,
							  (_this.minx + _this.maxx)/2, (_this.miny + _this.maxy)/2);
			break;

		case "cercaAdresa":
		case "cercaParcela":
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			break;
			
		default:
	  		_this.activeTool = tool;
			break;
  		}

		// Ensenyar les opcions de l'eina actual
		var div;
		switch(_this.activeTool) {
		case "hyperlink":
		case "selection":
			div = dojo.byId('identify' + 'OptionsDiv');
			break;

		default:
			div = dojo.byId(_this.activeTool + 'OptionsDiv');
			break;
		}
		if (div != undefined) {
			_this.ensenyaElement(div);
		}
	}

	this.highlightTool = function(tool) {
		if ((tool!=null) && (tool!="")) {
			for (i = 0; i < _this.eines.length; i++) {
				var s = _this.eines[i]
				var e = dojo.byId(s + "Tool");
				if (e != undefined) {
					e.src = "imatges/" + s + ".gif";
				}
			}

			var e = dojo.byId(tool + "Tool");
			if (e != undefined) {
				e.src = "imatges/" + tool + "D.gif";
			}
		}
	}
	
	this.anarCoordenades = function (e) {
		var KeyID = (window.event) ? event.keyCode : e.keyCode;
		if (KeyID == '13') {
			_this.coordenadesUTMAfegir(dojo.byId('coord_x').value, dojo.byId('coord_y').value);
		}
	}

	this.ensenyaElement = function(nom) {
		var el = dojo.byId(nom);
		if (el != undefined) {
			el.style.display = "";
		}
	}

	this.createZoomBoxDivs = function(){
		_this.createLayer("zoomboxTop", _this.mleft, _this.mtop, _this.mwidth, _this.mheight, false, "");
		_this.createLayer("zoomboxBottom", _this.mleft, _this.mtop, _this.mwidth, _this.mheight, false, "");
		_this.createLayer("zoomboxLeft", _this.mleft, _this.mtop, _this.mwidth, _this.mheight, false, "");
		_this.createLayer("zoomboxRight", _this.mleft, _this.mtop, _this.mwidth, _this.mheight, false, "");
		_this.setLayerBackgroundColor("zoomboxTop", "blue");
		_this.setLayerBackgroundColor("zoomboxBottom", "blue");
		_this.setLayerBackgroundColor("zoomboxLeft", "blue");
		_this.setLayerBackgroundColor("zoomboxRight", "blue");
	}

	this.ButtonOut = function(id, tool, flatimage, downimage) {
		var imgsrc = flatimage;
		if (_this.activeTool == tool) {
			imgsrc = downimage;
		}

		var imgObj = document.getElementById(id);
		if(imgObj != null)
			imgObj.src = imgsrc;
	}

	this.setMapDivProperties = function(mapId) {
		_this.mapDivId = mapId;
	}

	this.createLayer = function(name, inleft, intop, width, height, visible, content) {
		  var layer;
		    document.writeln('<div id="' + name + '" style="position:absolute; overflow:hidden; left:' + inleft + 'px; top:' + intop + 'px; width:' + width + 'px; height:' + height + 'px;' + '; z-index:1; visibility:' + (visible ? 'visible;' : 'hidden;') +  '">');
		    document.writeln(content);
		    document.writeln('</div>');
	}

	// set layer background color
	this.setLayerBackgroundColor = function(name, color) {
	  	var layer = this.getLayer(name);		
		layer.backgroundColor = color;
	}

	// replace layer's content with new content
		// not working with Mozilla Milestone 12 (Nav5)
	this.replaceLayerContent = function(name, content) {
		var theObj = document.getElementById(name);
		if (theObj!=null) {	  
			theObj.innerHTML = content;	
		}
	}

	this.clipLayer = function(name, clipleft, cliptop, clipright, clipbottom) {		
		var layer = _this.getLayer(name);
		var newWidth = clipright - clipleft;
		var newHeight = clipbottom - cliptop;
		layer.height = newHeight;
		layer.width	= newWidth;
		if (_this.isIE) {
			layer.top	= (cliptop - _this.mtop) + "px";
			layer.left	= (clipleft - _this.mleft) + "px";
		} else {
			layer.top	= cliptop  + "px";
			layer.left	= clipleft + "px";
		}
	}

	this.panClipLayer = function(name, clipleft, cliptop, clipright, clipbottom) {
		var layer = _this.getLayer(name);
		if (layer!=null) {
			layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
		} 
		return false;
	}
	
	this.setClip = function() {
		var inSize = 3;
		var lSize = parseInt(inSize) - 1;
		if (lSize < 1) lSize = 1;
		var tempX = _this.x1;
		var tempY = _this.y1;
		if (_this.x1 > _this.x2) {
			_this.zright = _this.x1
			_this.zleft = _this.x2;
		} else {
			_this.zleft = _this.x1;
			_this.zright = _this.x2;
		}
		if (_this.y1 > _this.y2) {
			_this.zbottom = _this.y1;
			_this.ztop = _this.y2;
		} else {
			_this.ztop = _this.y1;
			_this.zbottom = _this.y2;
		}
		
		if ((_this.x1 != _this.x2) && (_this.y1 != _this.y2)) {
			_this.clipLayer("zoomboxTop", _this.zleft, _this.ztop, _this.zright, _this.ztop + lSize);
			_this.clipLayer("zoomboxLeft", _this.zleft, _this.ztop, _this.zleft + lSize, _this.zbottom);
			_this.clipLayer("zoomboxRight", _this.zright - lSize, _this.ztop, _this.zright, _this.zbottom);
			_this.clipLayer("zoomboxBottom", _this.zleft, _this.zbottom - lSize, _this.zright, _this.zbottom);
		}
		return false;
	}

	// toggle layer to invisible
	this.hideLayer = function(name) {
	  	var layer = _this.getLayer(name);		
	  	layer.visibility = "hidden";
	}
	
	// toggle layer to visible
	this.showLayer = function(name) {
	  	var layer = _this.getLayer(name);
	  	layer.visibility = "visible";
	}
	
	// clip layer display to clipleft, cliptip, clipright, clipbottom
	// Not working with Mozilla Milestone 12 (Nav5)
	this.clipLayer2 = function(name, clipleft, cliptop, clipright, clipbottom) {		
		var layer = _this.getLayer(name);		
		layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	}

	this.showZoomBox = function(left, top, right, bottom){
		_this.clipLayer("zoomboxTop",left,top,right,bottom);
		_this.clipLayer("zoomboxLeft",left,top,right,bottom);
		_this.clipLayer("zoomboxRight",left,top,right,bottom);
		_this.clipLayer("zoomboxBottom",left,top,right,bottom);
		_this.showLayer("zoomboxTop");
		_this.showLayer("zoomboxLeft");
		_this.showLayer("zoomboxRight");
		_this.showLayer("zoomboxBottom");
	}
	
	this.pointClick = function(e) {
		_this.getXY(e);
		var x1 = _this.theX - _this.mleft;
	
		var y1 = _this.theY - _this.mtop;
		var coordString = "point::";
		coordString = coordString + x1 +"::";
		coordString = coordString + y1;

		var point = _this.convertPixelToMap(x1, y1);
		
		switch (_this.activeTool) {
		case "hyperlink":
			_this.hyperlink(point[0], point[1]);
			break;
			
		case "identify":
			_this.identify(point[0], point[1]);
			break;

		case "measure":
			var point = _this.convertPixelToMap(x1, y1);

			if (_this.mesura_x != undefined) {
				var distancia = _this.distancia(_this.mesura_x, _this.mesura_y, point[0].toFixed(1), point[1].toFixed(1));
				_this.mesura_total = parseFloat(_this.mesura_total) + parseFloat(distancia.toFixed(1));

				var mesura_total = dojo.byId('mesura_total');
				if (mesura_total != undefined) {
					mesura_total.value = _this.mesura_total.toFixed(1) + " metres";
				}
			}

			_this.mesura_x = point[0].toFixed(1);
			_this.mesura_y = point[1].toFixed(1);

			_this.mesura(_this.mesura_x, _this.mesura_y);
			break;

		case "capturaCoordenades":
			var point = _this.convertPixelToMap(x1, y1);

			_this.coordenadesAfegir(point[0].toFixed(), point[1].toFixed());
			break;
		}
		return false;
	}

	this.getXY = function(e) {
		if (_this.isNav) {
			_this.theX = e.pageX;
			_this.theY = e.pageY;
		} else {
			_this.theX = event.clientX + document.body.scrollLeft;
			_this.theY = event.clientY + document.body.scrollTop;
		}
		return false;
	}

	this.isVisible = function (name) {
		var layer = _this.getLayer(name);
		if (_this.isNav && layer.visibility == "show")
	    	return(true);
		if (_this.isIE && layer.visibility == "visible")
	    	return(true);
		return(false);
	}

	this.hideZoomBox = function() {
//FIXME: removed
//		window.scrollTo(0,0);
		_this.hideLayer("zoomboxTop");
		_this.hideLayer("zoomboxLeft");
		_this.hideLayer("zoomboxRight");
		_this.hideLayer("zoomboxBottom");
	}


	// Overview functions
	this.overviewCenter = function(e) {
		_this.getXY(e);
		var ovtop = dojo.html.getAbsolutePosition(dojo.byId('ovimage0'), true).y;
		var ovleft = dojo.html.getAbsolutePosition(dojo.byId('ovimage0'), true).x;

		var coordString = "point::";
		coordString = coordString + (_this.theX - ovleft) +"::";
		coordString = coordString + (_this.theY - ovtop);

		_this.startLoading();
		Visor.overviewCenter(_this.getVisorId(),
			 _this.theX - ovleft, _this.theY - ovtop,
			 _this.updateVisor);
	}

	// TOC functions
	this.createTocNode = function(id, tipus, visible) {
		var tocNode = new TocNode();
		tocNode.id = id;
		tocNode.tipus = tipus;
		tocNode.visible = visible;
		tocNode.displayed = "true";
		_this.toc[id] = tocNode;
		tocNode.updateIcon();
	}
	
	this.tocNodeClick = function(id) {
		var tocNode = _this.toc[id];

		tocNode.doClick();

		Visor.uitocnode_clic(_this.getVisorId(),
			 id,
			 _this.updateVisor);

		// Cal demanar una imatge nova?
		if (tocNode.displayed == "true") {
			_this.queue_refresh();
		}
	}

	this.uitoc_folder_set_expanded = function(folder, state) {
		var now;
	
		if (document.getElementById("item" + folder).className == "tocHeaderOpener") {
			now = "tancat";
			if (state == undefined) {
				state = "obert";
			}
		} else {
			now = "obert";
			if (state == undefined) {
				state = "tancat";
			}
		}
		
		if (state != now) {
			var imatge = document.getElementById("item" + folder).src;
			imatge = imatge.replace('menys.gif','');
			imatge = imatge.replace('mes.gif','');
			if (state == "obert") {
				document.getElementById("item" + folder).className = "tocHeaderCloser";
				document.getElementById("item" + folder).src = imatge + "menys.gif";
				dojo.lfx.html.wipeIn(document.getElementById("folder" + folder), 400).play();
			} else {
				document.getElementById("item" + folder).className = "tocHeaderOpener";
				document.getElementById("item" + folder).src = imatge + "mes.gif";
				dojo.lfx.html.wipeOut(document.getElementById("folder" + folder), 400).play();
			}
		}
	}
	
};

visorUMAT = new VisorUMAT();

var cmdString = document.location.search;
if (cmdString.indexOf("debug") > -1) {
	visorUMAT.debug = true;
}

dojo.addOnLoad(function() {
	dojo.lang.setTimeout(visorUMAT, "ping", 300000);

    dojo.event.connect(window, "onresize", visorUMAT, 'contingut_tamany_canviar');
	visorUMAT.contingut_tamany_canviar();

	var mapArea = dojo.byId('mapArea');
	mapArea.onmousemove = visorUMAT.actualitzaCoordenades;
	
	var ovimage = dojo.byId('ovimage0');
	ovimage.onmouseup = visorUMAT.overviewCenter;

});

function imprimir() {
	var iframe = dojo.byId('iframe');
	iframe.titol.value = dojo.byId("print_titol").value;
	iframe.escala.value = dojo.byId("print_escala").value;
	iframe.full.value = dojo.byId("print_full").value;
	iframe.print_minx.value = visorUMAT.minx.toFixed();
	iframe.print_maxx.value = visorUMAT.maxx.toFixed();
	iframe.print_miny.value = visorUMAT.miny.toFixed();
	iframe.print_maxy.value = visorUMAT.maxy.toFixed();
	iframe.visorId.value = dojo.byId("mapId").value;
	iframe.submit();
}

function wipeToggle(node, time) {
	if (document.getElementById(node).style.display == "none") {
		dojo.lfx.html.wipeIn(document.getElementById(node), 400).play();
	} else {
		dojo.lfx.html.wipeOut(document.getElementById(node), 400).play();
	}
}

function overviewSetup() {
}

function table_append_row(tableId, rowId, data) {
	var table = document.getElementById(tableId);
	var newRow = table.insertRow(table.rows.length);
	newRow.id = rowId;

	for (var obj in data) {
		var newCell = newRow.insertCell(newRow.cells.length);
		newCell.innerHTML = data[obj];
	}
}

function table_remove_row(tableId, rowId) {
	var table = document.getElementById(tableId);
	var row = document.getElementById(rowId);
	table.deleteRow(row.rowIndex);
}


TocNode = function() {
	var _this = this;

	this.id;
	this.type;
	this.visible;
	this.visibleStatus;
	this.displayed;

	this.iconHidden = "imatges/icon_hidden.gif";
	this.iconZoom = "imatges/icon_visscale.gif";
	this.iconVisible = "imatges/icon_visible.gif";
	this.iconSome = "imatges/icon_some.gif";

	this.doClick = function () {
		var id = 'layer' + _this.id + '_visible';
		var img = dojo.byId(id);

		if (_this.tipus == "query") {
			if (_this.visibleStatus == "hidden") {
				_this.visibleStatus = "some";
			} else if (_this.visibleStatus == "some") {
				_this.visibleStatus = "visible";
			} else {
				_this.visibleStatus = "hidden";
			}
		} else {
			// tipus simple
			if (_this.visible == "false") {
				_this.visible = "true";
			} else {
				_this.visible = "false";
			}
		}

		_this.updateIcon();
	}
	
	this.updateIcon = function () {
		var id = 'layer' + _this.id;
		var node = dojo.byId(id);
		var img = dojo.byId(id + '_visible');

		if (_this.tipus == "query") {
			if (_this.visibleStatus == "hidden") {
				img.src = _this.iconHidden;
			} else if (_this.visibleStatus == "some") {
				img.src = _this.iconSome;
			} else {
				img.src = _this.iconVisible;
			}
		} else {
			// tipus simple
			if (_this.visible == "false") {
				img.src = _this.iconHidden;
			} else {
				if (_this.displayed == "true") {
					img.src = _this.iconVisible;
				} else {
					img.src = _this.iconZoom;
				}
			}
		}
		
		// nom del layer en gris
		if (node != null) {
			var class1 = dojo.html.getClass(node);
			var class2 = class1.split("_");
			var clase = class2[0];

			if (_this.displayed == "true") {
				dojo.html.setClass(node, clase);
			} else {
				dojo.html.setClass(node, clase + "_ocult");
			}
		}
	}
	
}

