dojo.require("dojo.io.*");

VisorUMAT = function() {
	var _this = this;

	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();

	// 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;

		_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;

	// Comandes directes
	this.requestMap = function() {
		_this.doRequestCoords("point::0::0");
	}

	// Ajudes
	this.doRequestSimple = function(funcio) {
		_this.doRequestFull(funcio, "", "");
	}

	this.doRequestCoords = function(coordString) {
		_this.doRequestFull("request_map", coordString, "");
		_this.startLoading();
	}
	
	this.doRequestFuncioCoords = function(funcio, coordString, startLoading) {
		_this.doRequestFull(funcio, coordString, "");
		if (startLoading) {
			_this.startLoading();
		}
	}

	this.startLoading = function() {
		_this.loading = _this.loading + 1;
		dojo.byId('progres').style.display = "";
	}

	this.getLayerActiu = function() {
		var layerActiu = dojo.byId('mapForm:layerActiu');
		return layerActiu.options[layerActiu.selectedIndex].value;
	}

	// Funcio amb TOTS els parametres
	this.doRequestFull = function(funcio, coordString, layer) {
		var height = dojo.html.getMarginBox(dojo.byId('mapDiv')).height;
		var width = dojo.html.getMarginBox(dojo.byId('mapDiv')).width;

		var layerActiuSeleccionat = _this.getLayerActiu();
	
		var parametres = {
					  "funcio": funcio,
					  "coords": coordString,
				      "mapId": dojo.byId('mapId').value,
				      "height": height,
				      "width": width,
				      "layer": layer,
				      "eina": _this.activeTool,
				      "layerActiu": layerActiuSeleccionat
				      };
	
		_this.doRequestAJAX(parametres);
	}
	
	// Fer la petició al servidor amb els parametres corresponents
	this.doRequestAJAX = function(parametres) {
		var bindArgs = {
			url: "faces/ajax-visor-umat",
			method: "post",
			content: parametres,
			mimetype: "text/json-comment-filtered",
			
			load: _this.processarResposta,
			error: _this.processarError
		};
		dojo.io.bind(bindArgs);
	
		var time = (new Date()).getTime();
//		dojo.debug(time - _this.last_action);
		_this.last_action = time;
	}

	this.processarError = function(type, errObj) {
//		for (var i in errObj) {
//			alert(i + ': ' + errObj[i]);
//		}

		alert("S'ha produit un error, torneu-ho a intentar més tard.");
		_this.cancelar_refresh();
	}

	this.processarResposta = function(type, data, evt) {
		var json = data;

		if (json.event != undefined) {
			if (json.event == 'sessio_caducada') {
				_this.sessio_caducada();
				return;
			}
		}

		if (json.code != undefined) {
			var code = json.code;

			for (i = 0; i < code.length; i++) {
				eval(code[i].code);
			}
		}

		if (json.no_disponible != undefined) {
			_this.no_disponible(json.no_disponible);
			_this.connectat = false;
			_this.cancelar_refresh();
			return;
		}

		if (json.missatge != undefined) {
			alert(json.missatge);
		}

		if (json.mapa != undefined) {
//			dojo.debug("CARREGAR: " + json.mapa);
			document.getElementById('theImage').src = json.mapa;
			document.getElementById('theImage').onload = _this.resetAfterPan;
		}

		if (json.ov != undefined) {
//			dojo.debug("CARREGAR OV: " + json.ov);
			document.getElementById('ovimage0').src = json.ov;
		}
	
		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);
		}

		if (json.coordenades != undefined) {
			var coord = json.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);
				}
			}
		}

		if (json.varUpdate != undefined) {
			var vu = json.varUpdate;
	
			for (i = 0; i < vu.length; i++) {
				id = vu[i].id;
				field = vu[i].field;
				value = vu[i].value;
//				dojo.debug("" + id + " = " + value);
				_this[id] = value;
			}
		}

		if (json.valueUpdate != undefined) {
			var vu = json.valueUpdate;
	
			for (i = 0; i < vu.length; i++) {
				id = vu[i].id;
				field = vu[i].field;
				value = vu[i].value;
//				dojo.debug("(" + id + ")[" + field + "] = " + value);
				document.getElementById(id)[field] = value;
			}
		}
	}

	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.x1 - _this.x2;
			var iyOffset = _this.y2 - _this.y1;
			
			var coordString = "point::";
			coordString = coordString + ixOffset +"::";
			coordString = coordString + iyOffset;
			_this.doRequestCoords(coordString);
			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 f = document.forms['mapForm'];
			var coordString = "polygon::";
			coordString = coordString + _this.zleft +"::";
			coordString = coordString + _this.zbottom +"::";
			coordString = coordString + _this.zright +"::";
			coordString = coordString + _this.ztop;
			//f.coords.value=coordString;

			switch (_this.activeTool) {
			case "zoomin":
			case "zoomout":
				_this.doRequestCoords(coordString);
				break;
			case "selection":
				_this.doRequestFuncioCoords("selection", coordString, true);
				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 "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 "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.print_mapId.value = dojo.byId("mapId").value;
			iframe.submit();
			break;

		case "informacio_csv":
			var iframe = dojo.byId('iframe_csv');
			iframe.mapId.value = dojo.byId("mapId").value;
			iframe.layer.value = _this.getLayerActiu();
			iframe.submit();
			break;

	  	// Accions directes
	  	case "zoomfull":
	  	case "zoomprevious":
	  		_this.doRequestSimple(tool);
			_this.startLoading();
			break;

	  	case "clear":
	  		_this.doRequestSimple(tool);
			_this.startLoading();

	  		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":
		case "zoomoutfixed":
		    _this.doRequestSimple(tool);
			_this.queue_refresh();
			break;

		case "cercaAdresa":
		case "cercaParcela":
			_this.highlightTool(tool);
	  		_this.activeTool = tool;
			break;
  		}

		// Ensenyar les opcions de l'eina actual
		var div;
		switch(_this.activeTool) {
		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') {
			coordString = "point::" + dojo.byId('coord_x').value + "::" + dojo.byId('coord_y').value;
			_this.doRequestFuncioCoords("coordenadesUTMAfegir", coordString, true);
//			_this.queue_refresh();
		}
	}

	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(top, left, width, height, border, mapId) {
		_this.mtop = top+border;
		_this.mleft = left+border;
		_this.mwidth = width-(2*border);
		_this.mheight = height-(2*border);
		_this.mborder = border;
		_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;
		
		switch (_this.activeTool) {
		case "identify":
			_this.doRequestFuncioCoords("identify", coordString, false);
			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.doRequestFuncioCoords("mesura", coordString, false);
			_this.queue_refresh();
			break;
		case "capturaCoordenades":
			var point = _this.convertPixelToMap(x1, y1);
//			var coord_x = point[0].toFixed(1);
//			var coord_y = point[1].toFixed(1);

			_this.doRequestFuncioCoords("coordenadesAfegir", coordString, false);
			_this.queue_refresh();
			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.doRequestFull("overview_center", coordString, "");
		_this.startLoading();
	}

	// TOC functions
	this.uitocnode_clic = function(layer) {
		_this.doRequestFull("uitocnode_clic", "", layer);
		_this.queue_refresh();
	}

	this.uitocnode_clic2 = function(layer) {
		var id = 'layer' + layer + '_visible';
		var img = dojo.byId(id);

		if (img.src.indexOf("hidden.gif") == -1) {
			img.src = "imatges/icon_hidden.gif";
		} else {
			img.src = "imatges/icon_visible.gif";
		}

		_this.uitocnode_clic(layer);		
	}

	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();
			}
		}
	}
	
	this.seleccio_carrer = function(carrer) {
		_this.doRequestFull("seleccio_carrer", "", carrer);
		_this.startLoading();
	}

	this.seleccio_edifici = function(edifici) {
		_this.doRequestFull("seleccio_edifici", "", edifici);
		_this.startLoading();
	}

	this.seleccio_facana = function(numero) {
		_this.doRequestFull("seleccio_facana", "", numero);
		_this.startLoading();
	}

	this.seleccio_parcela = function(parcela) {
		_this.doRequestFull("seleccio_parcela", "", parcela);
		_this.startLoading();
	}

};

visorUMAT = new VisorUMAT();

dojo.addOnLoad(function() {
    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 changeDisplayed(id, displayed, visible) {
	var node = document.getElementById(id);
	if (node == null) {
		return;
	}

	var class1 = dojo.html.getClass(node);
	var class2 = class1.split("_");
	var clase = class2[0];
	
	if (displayed) {
		dojo.html.setClass(node, clase);
	} else {
		dojo.html.setClass(node, clase + "_ocult");
	}

	var icona = document.getElementById(id + "_visible");
	if (icona == null) {
		return;
	}

	if (visible) {
		if (displayed) {
			icona.src = 'imatges/icon_visible.gif';
		} else {
			icona.src = 'imatges/icon_visscale.gif';
		}
	} else {
		icona.src = 'imatges/icon_hidden.gif';
	}
	
	
}

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 = dojo.byId("minx").value;
	iframe.print_maxx.value = dojo.byId("maxx").value;
	iframe.print_miny.value = dojo.byId("miny").value;
	iframe.print_maxy.value = dojo.byId("maxy").value;
	iframe.print_mapId.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() {
	alert("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);
}
