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

// language strings
jQuery.i18n.addDictionary({
	'MAXSUPPLIERSELECTIONS': "You can't select more than 10 suppliers at a time."
});

;(function($) {
	
	$.fn.DemandMap_SupplierControl = function(mapSelector, _options) { 
		var defaults = {
			'maxNetworkSelections': false,
			'loadingIndicator': '<div class="loadingIndicator"><img src="cms/images/network-save.gif" /></div>'
		};
		
		return this.each(function(){
			var $this = $(this);
			var container = this;
			
			var options = $.extend({}, defaults, _options);

			// objects
			var map = $(mapSelector);
			var tileLayers = [];
			
			loadSuppliers(getSelectedSuppliers());
			
			// url config
			if($.jget['hidesearchbar']) $this.hide();

			// add loading indicator
			$('.Actions', container).append(options.loadingIndicator);
			$('.Actions .loadingIndicator', container).hide();

			$('.supplierList', container).DemandMap_collapsible();
			
			// Click event for 'limit to networks in this region' checkbox.
			// We can't listen to 'change' as IE6 craps out on this...
			$('#LimitToVisible :input').bind('click', function(e) {
				toggleVisibleSuppliersButton();
			});
			
			// manual refresh
			$('#LimitToVisible a.refresh').livequery('click', function(e) {
				// make sure the checkbox is ticked
				var $input = $(this).parents('label').siblings(':input');
				$input.attr('checked', 'checked');
				toggleVisibleSuppliersButton();
				return false;
			});
			// Event listeners for changes to data filtering.
			// We don't listen to map position changes because of ajax delay/performance reasons
			$(document).bind('DemandSearchBar:searchend', function(e) {
				toggleVisibleSuppliersButton();
			});
			
			$('.supplierList', container).bind('selected', function(e, data) {
				if(data.removed) $(data.removed).each(function() {
					map.fn('clearOverlaysBySupplier', $(this).find(':checkbox').val());
				});
				if(data.added) {
					var supplierIDs = $.map(data.added, function(item) {
						// don't include supplier, only networks can be shown
						return ($(item).is('.suppliernetwork')) ? $(item).find(':checkbox').val() : false;
					});
					loadSuppliers(supplierIDs);
				}
			});
			
			// click event of supplier network checkbox
			$('.supplierList .supplier :checkbox', container).livequery('change', function(e) {
				// count all already selected checkboxes
				var suppliers = getSelectedSuppliers();
				if(suppliers && options.maxNetworkSelections && suppliers.length > options.maxNetworkSelections) {
					alert($.i18n._t('MAXSUPPLIERSELECTIONS'));
					$(e.target).removeAttr('checked');
					return false;
				}
			});
			
			/**
			 * Convenience wrapper around toggleVisibleSuppliers()
			 * which deals with button clicks and states.
			 */
			function toggleVisibleSuppliersButton() {
				$checkbox = $('#LimitToVisible :input');
				$(container).addClass('loading');
				$checkbox.attr('disabled', 'disabled');
				toggleVisibleSuppliers($checkbox.is(':checked'), function(e) {
					$(container).removeClass('loading');
					$checkbox.removeAttr('disabled');
				});
			}
			
			/**
			 * Transfer the current map bounds to the Restful Service
			 * and find out which suppliers have at least one geographical feature
			 * in this area. Used to limit the visible checkbox lists.
			 * 
			 * @param {Boolean} toggle
			 * @param {Function} callback
			 */
			function toggleVisibleSuppliers(toggle, callback) {
				if(toggle) {
					var bounds = map.fn('getQueryBounds');
					var ne = bounds.getNorthEast();
					var sw = bounds.getSouthWest();
					var url = 'api/v1/SupplierNetwork.json?Bounds[sw]=%s,%s&Bounds[ne]=%s,%s&relationdepth=0&fields=ID,SupplierID';
					$.getJSON(
						$.sprintf(url, 
							sw.lng(),
							sw.lat(),
							ne.lng(),
							ne.lat()
						),
						null,
						function(data, status) {
							var ids = jQuery(data.items).map(function() { return this.SupplierID;});
							$('.supplierList .supplier > .checkboxHolder :checkbox', container).each(function() {
								if($.inArray($(this).val(), ids) == -1) $(this).parents('.supplier').addClass('disabled').hide();
							});

							if(callback) callback(data, status);
						}
					);
				} else {
					// reset visibility
					$('.supplierList .supplier', container).removeClass('disabled').show();
					if(callback) callback();
				}
			}

			/**
			 * Tick or untick the network group (of the passed-in network) 
			 * if all of its networks are selected it will be selected 
			 * otherwise, it will be deselected. 
			 */
			function toggleSupplier(suppliernetworkID) {
				var supplierNetwork = $("#SupplierNetwork" + suppliernetworkID);
				var supplier = supplierNetwork.parents('.category');
				var supplierCheckbox = supplier.find(':checkbox:first');
				
			}
			
			// load supplier overlayed when they're selected
			function loadSuppliers(supplierIDs) {
				$(supplierIDs).each(function(el, i) {
					initTilingForSupplier(i);
				});

				$(document).trigger('SupplierControl:loadSuppliers', [supplierIDs]);
			}
			
			
			// get all the selected Supplier ids 
			function getSelectedSuppliers() {
				return $.map($('.suppliernetwork :checked', container),function(el, i) {
					if (el.value == parseInt(el.value)) return el.value;
				});
			}
			
			$('form', container).livequery('submit', function(e) {
				$('.Actions .loadingIndicator', container).show();
				
				// clear all overlays (might not be available for deselection in filtered result list)
				map.fn('clearOverlaysBySupplier');

				$(this).load(
					this.action,
					$(':input', this),
					function() {
						$('.Actions .loadingIndicator', container).hide();
					}
				);
				return false;
			});
			
			/**
			 * SupplierID can be '0' which means all overlays are shown at once
			 */
			function initTilingForSupplier(supplierID) {
				// Don't process non-numeric IDs
				if(Number(supplierID) != supplierID) return false;
				
				// initializing tiling
				var tileLayer = new GTileLayer(new GCopyrightCollection(''));
				
				tileLayer.supplierID = supplierID;
				
				// list node might not exist if ID=0
				if($('#SupplierNetwork' + supplierID).length) {
					var metadata = $('#SupplierNetwork' + supplierID).metadata();
					tileLayer.supplierOpacity = (metadata && typeof(metadata.LayerAlpha) != 'undefined') ? metadata.LayerAlpha : 0.4;
				} else {
					tileLayer.supplierOpacity = 0.4;
				}
				
				tileLayer.getTileUrl = function(tile, zoom) { 
					return 'cache/' + this.supplierID + '/' + tile.x + '-' + tile.y + '-' + zoom + '.gif';
					// Do enable anti-aliased PNGs, use this line instead: 
					// return 'cache/' + this.supplierID + '/' + tile.x + '-' + tile.y + '-' + zoom + '.png'; 
				}
	            tileLayer.isPng = function() { 
					return false; 
				}
	            tileLayer.getOpacity = function() { 
					return this.supplierOpacity; 
				}
				
				tileLayers[supplierID] = new GTileLayerOverlay(tileLayer);
				map.fn('addOverlays', [tileLayers[supplierID]], supplierID);
			}

		});
		
	}
})(jQuery);
