/*********************************************************************************
 Copyright (c) 2002-2005 Armin Burger
 
 Permission is hereby granted, free of charge, to any person obtaining 
 a copy of this software and associated documentation files (the "Software"), 
 to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 and/or sell copies of the Software, and to permit persons to whom the Software 
 is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included 
 in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR OR 
 COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
  USES THE JAVASCRIPT LIBRARIES JSGRAPHICS FROM WALTER ZORN
  SEE FILE /JAVASCRIPT/WZ_JSGRAPHICS.JS FOR DETAILS OF COPYRIGHT
  
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 Modifications for polygon drawing provided by Federico Nieri 
 
**********************************************************************************/

// -------------------------
//  FUNCTIONS FOR MEASURING
// -------------------------

// ADAPT LINE COLOR
var lineColor = '#FF0000';

// ADAPT LINE WIDTH
var lineWidth = 2;

// ADAPT FACTOR FOR DISTANCE/AREA CALCULATION
// eg. 1000 for km, 1 for m
//****var calcFact = 1000;
var calcFact = 1;

var numSize;

// Mouse click X/Y
var clickXprev;      // Previous clicks
var clickYprev;
var clickCount = 0;  // Counter for clicks; reset when clearing lines


// For area measurement
var xc = new Array;
var yc = new Array;
var xcPixel = new Array;
var ycPixel = new Array;
var nc = 0;
var area = 0;


//
// MAIN FUNCTION, DRAWS SYMBOL POINTS BETWEEN MOUSECLICKS
//
function measureDrawSymbols(e, clickX, clickY, dblClick) {
     //****INSERT: change factor and measure unit on scale] 
	var currentScale = parseInt(document.getElementById("scaleform").scale.value);
	if (currentScale > 25000) {
		calcFact = 1000;
		var uMA = " km2.";
		var uML = " km.";
	}	else {
		calcFact = 1;
		var uMA = " m2.";
		var uML = " m.";		
	}

	// Reset everything when last measure ended with double click
    if (clickCount == 0) resetMeasure();
    
    // Don't go outside map
    outerloop:
    if ((clickX < mapW) && (clickY < mapH)) {
        var x_geo = minx_geo + ((clickX/mapW)  * xdelta_geo);
        var y_geo = maxy_geo - ((clickY/mapH) * ydelta_geo);
        
        // First point for start click
        if (clickCount < 1) {
            drawLineSegment(clickX, clickY, clickX, clickY); 
            clickCount++;
    
        // Fill distance between clicks with symbol points
        } else {
            // Diff X/Y between current new and previous click
            var x_delta = clickXprev - clickX;
            var y_delta = clickYprev - clickY;
            
            // SINGLE CLICK
            if (dblClick != 1) { 
                // Segment length in Pixel
                var segLenPix = Math.sqrt((Math.pow(x_delta, 2)) + (Math.pow(y_delta, 2)));
                
                // Segment length in  map coordinates,  write values to input boxes
                var segLenGEO_0 = ((segLenPix/mapW) * xdelta_geo) / calcFact ;
                var cntSegLen = Math.round(segLenGEO_0).toString().length;
                numSize = Math.max(0, (4 - cntSegLen));
                var segLenGEO = roundN(segLenGEO_0, numSize); 
        
                
                if (document.measureForm.sumLen.value != '') {
                    sumLenGEO = roundN(parseFloat(document.measureForm.sumLen.value) + segLenGEO, numSize);
                } else {
                    sumLenGEO = roundN(segLenGEO, numSize);
                }
    
                document.measureForm.sumLen.value = sumLenGEO;
                document.measureForm.segLen.value = segLenGEO;
                
                
                // USE wz_jsgraphics.js TO DRAW LINE
                drawLineSegment(clickXprev, clickYprev, clickX, clickY);
                
            
            // DOUBLE CLICK => CALCULATE AREA
            } else if (dblClick) {
                counter = 0;

                // calculate polygon area
                xc[xc.length] = xc[0] - xc[(xc.length)-1]; 
                yc[yc.length] = yc[0] - yc[(yc.length)-1]; 

                area = 0;
                for(var k=0; k<nc; k++) {
                   var j = (k+1);
                   area = area + ( xc[k] * yc[j] );
                   area = area - ( xc[j] * yc[k] );
                }
                area = area / 2;
                area = Math.abs(roundN (area / (calcFact * calcFact), numSize-1)) ;
                //alert('Area: ' + area + ' m2');

                // Change input text box to 'Area'
				//****CHANGE: add mesure unit show
				document.getElementById("mSegTxt").innerHTML = localeList['Area'] + uMA; 
				//****INSERT: r// Change input text box to 'Perimeter'
				document.getElementById("mSumTxt").innerHTML = localeList['Perimeter'] + uML; 
				
				//document.getElementById("mSumTxt").innerHTML = "Perimetro"; 
                document.measureForm.segLen.value = area;
                
                // Close the Polygon
                // and delete the nc point born to calculate area		        
		        xc[nc-1] = xc[0];
		    	yc[nc-1] = yc[0];
		    	xc.length = nc;
		    	yc.length = nc;		    	
		    	xcPixel[nc-1] = xcPixel[0];
		    	ycPixel[nc-1] = ycPixel[0];		         
         	
               	drawLineSegment(xcPixel[nc-1], ycPixel[nc-1], clickX, clickY)               	
                
                // Reset variables and delete measure points
                nc = 0;
                area = 0;
                xc = new Array;
                yc = new Array;
                xcPixel = new Array;
                ycPixel = new Array;
                clickCount = 0;
                
                // remove measure line
                //jg.clear();
                
                break outerloop;
            }
        }
        
        // Set previous click to current, increase counter         
        clickXprev = clickX;
        clickYprev = clickY;
        clickCount = 2;
		//clickCount ++;
        
        // Add x/y clicks to array for area measurement
        xc[nc] = x_geo;
    	yc[nc] = y_geo;
    	xcPixel[nc] = clickX;
    	ycPixel[nc] = clickY;
        nc++; 
    }    
}

// REDRAW THE LAST AND THE CLOSING SIDE OF THE POLYGON
function redrawAll(currX, currY) {

    if (nc>0) {    	
        jg.clear();
    	jg.setColor(lineColor); 
    	jg.setStroke(lineWidth); 
	    jg.drawPolyline(xcPixel, ycPixel);
   
	    // Drawing last side	    
	    jg.drawLine(xcPixel[nc-1], ycPixel[nc-1], currX, currY);
	    
  	    // Drawing closing side  	    
	    jg.setStroke(Stroke.DOTTED); 
	    jg.drawLine(xcPixel[0], ycPixel[0], currX, currY);
	    
	    jg.paint();
	}		    

}

//
// DRAW LINE USING JSGRAPHICS
//
function drawLineSegment(xfrom, yfrom, xto, yto) {
    jg.setColor(lineColor); 
    jg.setStroke(lineWidth); 
    jg.drawLine(xfrom, yfrom, xto, yto); 
    jg.paint();
}


//
// Remove all measure settings
//
function resetMeasure() {
    // remove lines
    jg.clear();
     //****INSERT: change  measure unit on scale] 
	var currentScale = parseInt(document.getElementById("scaleform").scale.value);
	if (currentScale > 25000) {
		var uML = " km.";
	}	else {
		var uML = " m.";		
	}
    
    // Reset form fields 
    if (document.measureForm) {
        document.measureForm.sumLen.value = '';
        document.measureForm.segLen.value = '';
        //****CHANGE: add mesure unit show
		document.getElementById("mSegTxt").innerHTML = localeList['Segment'] + uML; 
		//****INSERT: replace localeList['Perimeter'] con localeList['Total'] 
		document.getElementById("mSumTxt").innerHTML = localeList['Total'] + uML; 
    }
    // Reset Click counter
    clickCount = 0;
}


//
// Round to a specified decimal
//
function roundN(numin, rf) {
    return ( Math.round(numin * Math.pow(10, rf)) / Math.pow(10, rf) );
} 
