OpenLayers.Control.Linia = OpenLayers.Class(OpenLayers.Control.DrawFeature, {
	title: "Dibuixar línies i mesurar distàncies",
	dialegHTML: 'A mida que vagis clicant punts en el mapa es dibuixarà una línia i indicarà en aquest requadre les distàncies:<br>'+
        '<table border="0" cellpadding="0" cellspacing="0" width="160">'+
        '<tbody><tr><td valign="top" width="84">Tram<br>'+
		'<input id="funcionsAvancadesLiniaTram" size="12" type="text">'+
		'<br></td>'+
        '<td class="combo" valign="top" width="76">Acumulada<br>'+
        '<input id="funcionsAvancadesLiniaAcumulat" size="12" type="text">'+
        '</td></tr></tbody></table>',
    type: OpenLayers.Control.TYPE_TOOL,

    handler: null,
    handlerOptions: null,
    callbacks: null,

	initialize: function(layer, options) {
		OpenLayers.Control.prototype.initialize.apply(this, [options]);
		this.callbacks = {done: this.drawFeature, point: this.updateFeature};
		this.layer = layer;
        this.handler = new OpenLayers.Handler.Path(this, this.callbacks, this.handlerOptions);
	},
	
	updateFeature: function(point) {
		var line = this.handler.line.geometry;
		var distanciaAcumulada = line.getLength();
		var distanciaDarrerTram = 0;
		var numPunts = line.components.length;
		if (numPunts > 2) {
			distanciaDarrerTram = line.components[numPunts-3].distanceTo(point);
		} else if (numPunts = 2) {
			distanciaDarrerTram = distanciaAcumulada;
		}
		//$('funcionsAvancadesLiniaAcumulat').value=this.formatLength(distanciaAcumulada);
		//$('funcionsAvancadesLiniaTram').value=this.formatLength(distanciaDarrerTram);
		if ($('ctl_acumulada') == null) return;
		$('ctl_acumulada').value=this.formatLength(distanciaAcumulada);
		$('ctl_tram').value=this.formatLength(distanciaDarrerTram);
		//this.map.div.style.cursor = "crosshair";	
	},
	
	formatLength: function(length) {
		var lengthUnits = 'm';
		var numDecimals = 1;
		if (length >= 10000) {
            length /= 1000;
            lengthUnits = 'km';
        }
        return length.toFixed(numDecimals) + " " + lengthUnits;
	},
        
	CLASS_NAME: "OpenLayers.Control.Linia"
});