// TODO implement _t()
var i18n = i18n || {};

;(function($) {
	
	$.fn.DemandMap_RegionControl = function(mapSelector) { 
		return this.each(function(){
			var $this = $(this);
			var container = this;

			// objects
			var map = $(mapSelector);

			// config
			var defaultRegionZoom = 8;
			
			// handle dropdown change
			$('select[name=RegionID], form', container).bind('submit change', function(e) {
				if(!Number(e.target.value)) return false;
				
				// Get region via json
				$.getJSON(
					$.sprintf('api/v1/Region/%d.json', e.target.value),
					// Update map center
					function(json) {
						$this.fn('regionSelected', json.Point, json.MapZoom);
					}
				);

				// notify map and searchbar of the change			
				var title = e.target.options[e.target.selectedIndex].text;
				$(document).trigger('DemandRegionControl:select', [title]);

				// reset dropdown to avoid UI inconsistencies
				//e.target.selectedIndex = 0;

				return false;
			});
			
			// Overloadable public methods
			
			// This is called when a map is selected
			// Note: this would probably be better handled with event trapping but it gives you the idea
			$(this).fn({
				'regionSelected': function(point, mapZoom) {
					map.fn('setCenter',
						new GLatLng(point.y, point.x), 
						(mapZoom) ? Number(mapZoom) : defaultRegionZoom);
				}
			});
		});
	}
})(jQuery);