var Directions = {
	map: null,
	center: null,
	zoom: 10,
	directions: null,
	isPrintMode: false,
	type: 'n',
	initialize: function(fromAddress, toAddress) {
		$("#gm_error").hide();
		Directions.map = new GMap2($('#gm_map_map')[0]);
		Directions.map.enableScrollWheelZoom();
		Directions.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(80,10)));
		GEvent.addListener(Directions.map, 'zoomend', function (oldValue, newValue) { Directions.setZoom(newValue); } );

		Directions.directions = new GDirections(Directions.map, $('#gm_directions')[0]);
		GEvent.addListener(Directions.directions, "load", Directions.onGDirectionsLoad);
		GEvent.addListener(Directions.directions, "error", Directions.handleErrors);
		if (Directions.isPrintMode)
			Directions.directions.load('from: ' + fromAddress + ' to: ' + toAddress, {"preserveViewport": true });
		else
			Directions.directions.load('from: ' + fromAddress + ' to: ' + toAddress);                   
	},
	onGDirectionsLoad: function() {
		if (Directions.isPrintMode) {
			Directions.resetCenter();
			Directions.changeMapType(Directions.type);
		}
		else {
			Directions.center = Directions.directions.getBounds().getCenter();
			Directions.zoom = Directions.map.getBoundsZoomLevel(Directions.directions.getBounds());
		}		
	},
	handleErrors: function() {
		$("#gm_error").show();
		$("#gm_directions").hide();
		$("#gm_map").hide();
	},
	changeMapType: function(type) {
		var list = $(".gm_mapViewsMatrix > li");
		list.removeClass("on");
		if(type == 'n') {
			Directions.map.setMapType(G_NORMAL_MAP);
			$(".gm_mapViewsMatrix > li:eq(0)").addClass("on");
		} else if(type == 'h') {
			Directions.map.setMapType(G_HYBRID_MAP);
			$(".gm_mapViewsMatrix > li:eq(1)").addClass("on");
		} else if(type == 's') {
			Directions.map.setMapType(G_SATELLITE_MAP);
			$(".gm_mapViewsMatrix > li:eq(2)").addClass("on");
		}
		Directions.type = type;
	},
	setZoom: function(value) {
		Ext.getCmp('gmapSlider').setValue(value);
	},
	resetCenter: function() {
		Directions.map.setCenter(Directions.center, Directions.zoom);
	},
	initializePrint: function (centerLat, centerLng, zoom, maptype) {
		Directions.type = maptype;
		Directions.isPrintMode = true;
		Directions.center = new GLatLng(centerLat, centerLng);
		Directions.zoom = zoom;
	},
	print: function (parameters) {
		window.open("/directions?" + parameters + "&print=1&zoom=" + Directions.map.getZoom() + "&centerLat=" + Directions.map.getCenter().lat() + "&centerLng=" + Directions.map.getCenter().lng() + "&maptype=" + Directions.type,'', "menubar=yes,toolbar=yes,scrollbars=yes,width=900,height=680,resizable=yes");
	}         
};
