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

;(function($) {
	
	$.fn.DemandMap_SearchLink = function(mapSelector, formSelector, _options) { 
		var defaults = {};
		
		return this.each(function(){
			var options = $.extend({}, defaults, _options);
			
			// Reference to this control
			var $this = $(this);
			
			// objects
			var $map = $(mapSelector);
			var $form = $(formSelector);
			var $linkEl = $('a', $this);
			
			// Update map whenever it moves
			$map.bind('DemandMap:move', function(e, bounds, zoom) {
				updateLink();	
			});
			$(document).bind('SupplierControl:loadSuppliers', function(e) {
				updateLink();
			});
			$(document).bind('DemandSearchBar:searchend', function(e) {
				updateLink();
			});
			$('#DemandCategoryControl').bind('DemandCategoryControl:loadcategories', function(e) {
				updateLink();
			});
			
			function updateLink() {
				var ignoredParams = ['SecurityID'];
				var params = jQuery.grep($(':input', $form).serializeArray(),function(n,i) {
					return n.value != '' && jQuery.inArray(n.name,ignoredParams) == -1;
				});
				var bounds = $map.fn('getQueryBounds');
				var ne = bounds.getNorthEast();
				var sw = bounds.getSouthWest();
				// @todo Fix hasDefaultValue "q" param
				params.push({
					'name': 'bounds[ne]',
					'value': ne.lat() + ',' + ne.lng()
				});
				params.push({
					'name': 'bounds[sw]',
					'value': sw.lat() + ',' + sw.lng()
				});
				// @todo Doesn't cope well with URLs that have GET parameters by default
				var href = $linkEl.attr('href').replace(/\?.*/, '');
				href += '?' + $.param(params);

				$linkEl.attr('href', href);
			}
		
		});
	}
})(jQuery);