/*
 * Hvor.no map measurement class
 * Depends on 
 * Norkart ajaxmap.js
 * jQuery draggable (+ jQuery, obviously)
 */
 
 
function Measurement(map)
{
	this.map = map;
	this.points = [];
	this.annotations = { points: [] };
	this.mapMovement = false;
	this.pointAddingEnabled = false;
    this.polyLine = null;
	
	
    this.redraw = function()
    {
        
        if(this.map.getDrawCanvas() == null)
        {
            this.map.addDrawCanvas(new WAPICanvas());
        }
        this.map.getDrawCanvas().clear();
        var polyLine = this.getPolyLine();
        if(polyLine)
        {
            this.map.getDrawCanvas().addPolyLine(polyLine);
        }
        
        //this.map.getDrawCanvas().redraw();
    }
    
    
    
	this.redrawAnnotations = function()
	{
		//this.map.removeAnnotationGroup('measurement-path-annotations');
        for(annotationGroup in this.annotations)
        {
            if(annotationGroup.length > 0)
            {
        		for(var i = 0; i<annotationGroup.length; i++)
        		{
        			this.map.addAnnotation(annotationGroup[i]);
        		}
            }
        }
	}    

	this.getPolyLine = function()
	{
        return this.polyLine;

	}
	
	this.clearPoints = function()
	{
        this.map.getDrawCanvas().clear();
        this.map.removeAnnotationGroup('measurement-path-annotations');
		this.points = [];
        this.annotations.points = [];
        this.polyLine = null;
    }
    
    this.addPoint = function(coords)
    {
        
        this.points.push(coords);
        var currentIndex = this.points.length - 1;
        //console.log("Added point to this.points["+currentIndex+"]");
        // If no canvas is present, attach one and add our polyline to it
        if(this.map.getDrawCanvas() == null)
        {
            this.map.addDrawCanvas(new WAPICanvas());
        }
        
        // If we don't have a polyline yet, create one
        if(this.polyLine == null)
        {
            this.polyLine = new PolyLine([], {'rgba' : "rgba(255,0,0,0.6)", 'lineWidth' : 6});
            this.map.getDrawCanvas().clear();
            this.map.getDrawCanvas().addPolyLine(this.polyLine);            
        }                    
        
        // Add point to polyline
        this.polyLine.addPoint(this.points[currentIndex]);
        
        // Redraw canvas to update
        this.map.getDrawCanvas().redraw();
        
        // Add annotation
        var annotation = new Annotation(this.points[currentIndex], 'Punkt '+(currentIndex+1), '','/images/points_measure.png', -7, -7, null, null, 'measurement-path-annotations');
        annotation.pointReference = currentIndex;
        this.annotations.points.push({ id: annotation.id, pointReference: annotation.pointReference });
        this.map.addAnnotation(annotation);
        
        // Update descriptions on all annotations
        this.updateAnnotations();
    }
    
    this.updateAnnotations = function()
    {
        for(var i=0;i<this.annotations.points.length;i++)
        {
            //console.log("Updating annotation annotations.points["+i+"]. annotationId is "+this.annotations.points[i].id+ ", pointReference is "+this.annotations.points[i].pointReference);
            var currentIndex = this.annotations.points[i].pointReference;
            var annotationId = this.annotations.points[i].id;
            var description = '';
            description += (currentIndex-1 >= 0) ? 'Avstand til forrige punkt: ' + Math.round(this.getLengthBetweenPoints(this.points[currentIndex], this.points[currentIndex-1])) + 'm<br />' : '';
            description += (currentIndex+1 < this.points.length) ? 'Avstand til neste punkt: ' + Math.round(this.getLengthBetweenPoints(this.points[currentIndex], this.points[currentIndex+1])) + 'm<br />' : '';
            
            this.map.getAnnotation(annotationId).description = description;
        }
    }
    
    this.getArea = function()
    {
        var area = 0.0;
    
        if (this.points.length < 3)
        {
            return 0.0;
        }
        
        for(var i = 0; i < this.points.length; i++)
        {
            i_n = i + 1;
            
            if (i_n == this.points.length)
            {
                i_n = 0
            }
            
            area += ((this.points[i].x * this.points[i_n].y) - (this.points[i_n].x * this.points[i].y));
        }
        
        if (area < 0)
        {
            area = area * -1;
        }
        
        return area / 2;
    }
    
    this.getAreaFormatted = function()
    {
        var squareMeters = this.getArea();
        
        if (squareMeters >= 1000000)
        {
            return (squareMeters / 1000000.0).toFixed(1) + " km²";
        }
        else if (squareMeters > 1000)
        {
            return (squareMeters / 1000.0).toFixed(1) + " m&aring;l";
        }
        else 
        {
            return squareMeters.toFixed(1) + " m²";
        }
    }

 	this.getLengthBetweenPoints = function(point1, point2)
	{
			var k1 = point1.x - point2.x;
			var k2 = point1.y - point2.y;
			var hyp = Math.sqrt(Math.pow(k1,2) + Math.pow(k2,2));	
			return hyp;
	}	
	
	this.getTotalLengthFormatted = function()
	{
		var meters = this.getTotalLengthInMeters();
		var distance = {};
		// Norwegian/swedish miles!
		distance.miles = Math.floor(meters / 10000);
		distance.km = Math.floor(meters/1000) - (distance.miles * 10);
		distance.m = Math.round(meters % 1000);
        
		var formatted = '';
		formatted += distance.miles > 0 ? distance.miles + 'mil ' : '';
		formatted += distance.km > 0 ? distance.km + 'km ' : '';
		formatted += distance.m > 0 ? distance.m + 'm' : '';
		
		return formatted;
	}
	
	this.getTotalLengthInMeters = function()
	{
		var totalLength = 0;
		for(var i = 1; i<this.points.length; i++)
		{
			var hyp = this.getLengthBetweenPoints(this.points[i], this.points[i-1]);
			totalLength += hyp;
		}
		
		return totalLength;
	} 
    
    this.getPoints = function()
    {
        if(this.points.length > 0)
        {
            return this.points;
        }
        else
        {
            return false;
        }
    }
    
    this.loadFromPoints = function(loadPoints)
    {
        this.map.removeAnnotationGroup('measurement-path-annotations');
		this.points = [];
        this.annotations.points = [];
        
        for(var p=0;p<loadPoints.length;p++)
        {
            this.addPoint(new Coordinate(loadPoints[p].x, loadPoints[p].y));
        }
        
    }
}