/*
(c) 2008 www.TUFaT.com, All Rights
Reserved. Please do not re-distribute
or re-sell this software.
*/
function adjustValue(dblValue, dblBase){
	
	/*
		This method adjust the value to a base number and format the resulting number
	*/
	  			
	dblValue = dblValue / dblBase;
	dblValue = Math.round(dblValue * decimalRounder) / decimalRounder;
	dblValue = addCommas(dblValue);
	
	return dblValue;
	
}
   		
function addCommas(nStr){

	/*
		This method adds corresponding commas to a number
	*/

	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	
	var rgx = /(\d+)(\d{3})/;
	
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	
	return x1 + x2;
	
}
function handleMapClick(overlay, point) {
		    	        
   	/*
   		This method handles map click
   	*/
   	
    if(points.length == maxPoints){
		return;
	}
         	
    if (point) {
    	registerPoint(point);
    } 
                
}
		    
function searchAddress(address) {

	/*
		This method searchs an address. If found, it creates a point to represent it
	*/

	if (geocoder) {
   	geocoder.getLatLng(
     		address,
     		function(point) {
     			
       		if (!point) {
         			alert(address + " not found");
       		} else {
       			map.setCenter(point, zoomLevel);
       			registerPoint(point);
       		}
      }
   	);
}
}

function setDirections() {
	
	/*
		This method draws the points for the Trip Advisor report
	*/
	
	if(checkPoints("Trip Advisor", 2) == false){
		return;
	}
   	
	map.clearOverlays();
	var latlon = new Array(0);
   			
	for(var i = 0; i < points.length; i++){
   		latlon.push(points[i].lat() + "," + points[i].lng());
   	}
   	
   	gdir.loadFromWaypoints(latlon); 
   	
}
    
function onGDirectionsLoad(){
	
	/*
		This method calculates Trip Advisor values
	*/
	
	var distance = gdir.getDistance().meters;
	var duration = gdir.getDuration().seconds;
	
	distance = adjustValue(distance, 1000);
	duration = adjustValue(duration, 60);
	
	document.getElementById("lzapp").generateReport("Trip Advisor", "The trip between selected points has a distance of <b>" + distance + " km</b> and a duration of <b>" + duration + " minutes</b>.");
	
}

function registerPoint(point){
	
	/*
		This method adds a point to the array and draw it on the map
	*/
	
	document.getElementById("lzapp").addPoint(point);
    points.push(point);
	drawPoints();
	
}
    		
function drawPoint(point){	
	
	/*
		This method draws a point on the map
	*/
	
	var letter = String.fromCharCode("A".charCodeAt(0) + pointCounter);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

    markerOptions = {icon:letteredIcon };
    	    	
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);		

}

function drawPoints(){		    	
	
	/*
		This method re-draws points on the array on the map
	*/
	
	pointCounter = 0;
	
	map.clearOverlays();
	
	for(var i = 0; i < points.length; i++){
		var point = points[i];
		drawPoint(point);
		pointCounter = pointCounter + 1;		
	}
	
}
		    		    
function drawRoute(){
 	
	/*
		This method draws lines on the map
	*/
	
	var polyline = new GPolyline(points, lineColor, lineThick, 1);
	map.addOverlay(polyline);
 	
}
function drawArea(){
	
	/*
		This method draws an area on the map
	*/
	
	points.push(points[0]);
	
	var polygon = new GPolygon(points, lineColor, lineThick, 1, fillColor);	
	
	points.pop();
	
	drawPoints();
	
	map.addOverlay(polygon);
	
	return polygon;
	
}
		    
function remove(position){
	
	/*
		This method removes a point from the array and invokes the redraw method
	*/
	
	points.splice(position,1);
	drawPoints();
	
}
		    
function calcDistance(){
	
	/*
		This method perform the calculations for the Distance Calculator report
	*/
	
	if(checkPoints("Distance Calculator", 2) == false){
		return;
	}
	
	var distance = 0;
	
	for(id = 0; id < (points.length - 1); id += 1) {
		distance = distance + points[id].distanceFrom(points[id + 1]);
	}

	distance = adjustValue(distance, 1000);

	document.getElementById("lzapp").generateReport("Distance Calculator", "Total distance between selected points is <b>" + distance + " km</b>.");

	drawPoints();
	drawRoute();

}
		    
function calcArea(){

	/*
		This method draw an area on the map and performs the calculations for the Area Calculator report
	*/
	
	if(checkPoints("Area Calculator", 3) == false){
		return;
	}
	
	var polygon = drawArea();	
	
	area = polygon.getArea();
	area = adjustValue(area, 1000000);
	document.getElementById("lzapp").generateReport("Area Calculator", "Total size of the area between selected points is <b>" + area + " km2</b>.");
	
}
function checkPoints(strTitle, lngPoints){

	if(points.length < lngPoints){
		document.getElementById("lzapp").generateReport(strTitle, "You have to select at least " + lngPoints + " points to generate this report.");
		return false;
	}else{
		return true;	
	}
	
}

function handleErrors(){
    	
    /*
    	This method handles GeoCoding related errors
    */
    
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

	else alert("An unknown error occurred.");
	
}
