// Map, geocoder, actual polyline, actual polilyne points
var map = null;
var geocoder = null;
var path = null;
var points = [];
var overlays = [];

// Constants
var defaultZoomLevel; 

// Actions being done by the user
var search = false;
var creatingpath = false;

// Listeners
var mapclicklistener = null;

// Parse an string into an array of points
function parsePoints(p){
	var ret = [];
	while (p.search(/\),\(/) != -1)
		p = p.replace(/\),\(/, ");(")
	p = p.split(';');
	for (i = 0; i < p.length; i++) {
		var current = p[i].split(",");
		var x = current[0].replace(/\(/, "");
		var y = current[1].replace(/\)/, "");
		var point = new GLatLng(parseFloat(x), parseFloat(y));
		ret.push(point);
//		alert(point);
	}
//	alert(ret);
	return ret;
}

// Init method
function loadMap() {
	if (GBrowserIsCompatible()) {
    	map = new GMap2(document.getElementById("map-content"));
		// Map controls
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		// Fill constants
		defaultZoomLevel = map.getZoom();
		// Default moveend event
        GEvent.addListener(map, "moveend", function() {
			if (search) { 
			//	createMarkers();
			}
			search = false;
        });
		// Geocoder
		geocoder = new GClientGeocoder();
//		createMarkers();
	}
}

// Creates a simple marker
function createMarker(point, msg) {
	var marker = new GMarker(point);
	if (msg != null) {
		GEvent.addListener(marker, "click", function() {
        	marker.openInfoWindowHtml(msg);
		});
	}
	return marker;
}

function createPoint(point) {
	return new GLatLng(point.y, point.x);
}

// Search for an address and center the map in it
function showAddress(address) {
	search = true;
	map.clearOverlays();
	if (geocoder) {
		geocoder.getLatLng(address, function(point) {
			if (!point) {
				alert(address + " no se encuentra!");
			} else {
				map.setCenter(point, 13);
				map.addOverlay(createMarker(point, address));
			}
        });
    }
}

// Calculate the distance of the given points in meters
function calculateDistance(p) {
	var distance = 0;
	for (i = 1; i < p.length; i++)
    	distance = distance + p[i].distanceFrom(p[i-1]);
    distance = distance / 1000;
	return Math.round(distance*100)/100;
}

// Starts or stop path creating
function createPath() {
	// Create a path
	if (!creatingpath) {
		creatingpath = true;
		points = [];
		overlays = [];
		// Prepare the map
		map.clearOverlays();
		// Add the click action
		mapclicklistener = GEvent.addListener(map, "click", function(overlay, point) {
			points.push(createPoint(point));
			var overlay = createMarker(point, null);
			overlays.push(overlay)
			map.addOverlay(overlay);
			// Create the polyline and refresh the distance
			if (points.length > 1)
				refreshPath();
			else document.getElementById("track_starts_at").value = createPoint(point);
		});
	// Finish creating a path
	} else {
		creatingpath = false;
		//
	    GEvent.removeListener(mapclicklistener);
	}
}

function deleteLastAddedPoint() {
	if (creatingpath && points.length >= 1) {
		points.pop();
		map.removeOverlay(overlays.pop());
		refreshPath();
	}
}

function refreshPath() {
	if (path != null)
		map.removeOverlay(path);
	path = new GPolyline(points, "#ff0000", 5, 1, {geodesic:true})
	map.addOverlay(path);
	document.getElementById("track_points").value = points;
	document.getElementById("track_distance").value = calculateDistance(points);
}

function showPath(p, name, lenght) {
	points = parsePoints(p);
	map.clearOverlays();
	map.addOverlay(createMarker(points[0], name + " (" + lenght + " kilometers)"));
	map.panTo(points[0]);
	map.addOverlay(new GPolyline(points, "#ff0000", 5, 1, {geodesic:true}));
    map.addOverlay(createMarker(points[points.length-1], null));
}

function zoomIn() {
	if (map != null) map.zoomIn();
}

function zoomOut() {
	if (map != null) map.zoomOut();
}

function setDefaultZoom() {
	if (map != null) map.setZoom(defaultZoomLevel)
}

function resizeMap() {
	if (map != null) map.checkResize();
}

// Create 10 random markers in the map
function createMarkers() {
	// Add 10 markers to the map at random locations
    bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    for (var i = 0; i < 10; i++) {
    	var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
       	southWest.lng() + lngSpan * Math.random());
        map.addOverlay(createMarker(point, "Marker "+i));
	}
}
