var _mapApp;       
var _gline;

$(function() { init(); });

function init() {
	_mapApp = new MapApp();
	//mapApp.loadRoutes();
	
    options = { 
        modifyStart: function() { 
            return $J("#addtostart").checked; 
        },
        onCurrDist: function(leg) { 
            $J("#dist_currleg").innerHTML = (leg/1609.344).toFixed(3); 
        },
        onAddPoint: function(point, leg, total) { 
            $J("#dist_lastleg").innerHTML = (leg/1609.344).toFixed(2);
            $J("#dist_total").innerHTML = (total/1609.344).toFixed(2); 
        },
        onRemovePoint: function(point, leg, total) { 
            $J("#dist_lastleg").innerHTML = (leg/1609.344).toFixed(2);
            $J("#dist_total").innerHTML = (total/1609.344).toFixed(2);
        }
    };
    
    _gline = new GDrawLine(_mapApp._map, options);	 
    
    window.onunload = GUnload;
    $J('#message').innerHTML = '';
}


var MapApp = jQuery.createClass();
MapApp.prototype = {
	_map: null, 
    _mapElement: null,
	_icons: {base: null, start: null, end: null},
	_routes: null,
	
	initialize: function() {
        this._mapElement = $J("#map");
		this._map = new GMap2(this._mapElement, {
			draggableCursor: 'crosshair', 
			draggingCursor: 'pointer'
		});
		this._map.addControl(new GLargeMapControl());
		this._map.addControl(new GMapTypeControl());
		this._map.setCenter(new GLatLng(45.52, -122.67), 13);

		baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(10, 10);
		baseIcon.iconAnchor = new GPoint(5, 5);
		baseIcon.infoWindowAnchor = new GPoint(9, 9);
		//baseIcon.infoShadowAnchor = new GPoint(18, 25);
		this._icons.base = baseIcon
	
		this._icons.start = new GIcon(this._icons.base);
		this._icons.start = "http://mapper/images/dot_start.png";
		this._icons.end = new GIcon(this._icons.base);
		this._icons.end = "http://mapper/images/dot_end.png";
        
        window.onresize = this.windowResize.bind(this);
        
        this.windowResize();
	},
	
	loadRoutes: function() {
		url = "ajaxengine.php?op=loadRoutes";
		$.getJSON(url, null,this._displayRoutes.bindListener(this));
	},
    
    windowResize: function() {
        var h = $(window).height();
        var map = this._mapElement;
        map.style.height = (h - 110)+'px';
        this._map.checkResize();
    },    

	_displayRoutes: function(data, status) {
		$J("#message").innerHTML = "Loaded!";
		this._routes = data;
	
		if ( this._routes.length == 0 ) return;
		
		var html = "";
		var bg = "#fff";
		for (i=0; i<this._routes.length; i++) {
			var rt = this._routes[i];
			bg = bg == "#fff" ? "#eef" : "#fff";
			html += "<div style=\"margin: 2px; background-color: " + bg + " \">";
			html += "<span style='float:left;'><strong>" + rt.name + "</strong></span> <span style='float:right'>";
			html += "<a href=\"javascript: showRoute(" + i + ");\">select</a> | "
			html += "<a href=\"javascript: delRoute(" + i + ");\">del</a> </span><br></div>"
		}
		$("#routes").html(html);
	}	
	
	
}
