// 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': 10,
			'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 = [];

			// add loading indicator
			$('.Actions', container).append(options.loadingIndicator);
			$('.Actions .loadingIndicator', container).hide();
			
			// events
			$('.supplierList :checkbox', container).livequery('click', function(e) {
				// count all already selected checkboxes
				if($('.supplierList :checked', container).length > options.maxNetworkSelections) {
					alert($.i18n._t('MAXSUPPLIERSELECTIONS'));
					e.target.checked = '';
					return false;
				}
				
				// make sure radiobutton "show netowkrs" is selected
				$(':radio[value=select networks]', container).click();
				
				var supplierID = e.target.value;
				if(e.target.checked) {
					console.log('Showing tiles for SupplierID #%s', supplierID);
					initTilingForSupplier(supplierID);
					//getSelectedSuppliers();
				} else {
					console.log('Clearing tiles for SupplierID #%s', supplierID);
					map.fn('clearOverlaysBySupplier', supplierID);
				}
				
				
				
				return true;
			});
			
			loadSuppliers();
			
			// load supplier overlayed when they're selected
			function loadSuppliers() {
				supplierIDs = getSelectedSuppliers();
				$(supplierIDs).each(function(el, i) {
					initTilingForSupplier(i);
				});
			}
			
			
			// get all the selected Supplier ids 
			function getSelectedSuppliers() {
				return $.map($('input:checked', container),function(el, i) {
					if (el.value == parseInt(el.value)) return el.value;
				});
			}
			
			// "show coverage" (toggling of all layers with fake ID '0')
			// radiobutton selection: either "show coverage" or "select networks"
			$('input[name=supplierview]', container).livequery('click', function(e) {
				if(e.target.value == 'showcoverage') {
					// uncheck all existing elements
					$('.supplierList :checkbox', container).each(function() {
						this.checked = '';
						this.disabled = 'disabled';
						$(this).change();
					});
					
					// init or remove tiling
					if(e.target.checked) {
						// clear all supplier overlays
						map.fn('clearOverlaysBySupplier');
						// and re-initialize
						initTilingForSupplier(0);
					} else {
						map.fn('clearOverlaysBySupplier', 0);
					}
				} else {
					$('.supplierList :checkbox', container).each(function() {
						this.disabled = '';
					});
					
					// remove coverage tiling
					map.fn('clearOverlaysBySupplier', 0);
				}
				
			});
			$('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) {
				// 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);
			}
			
			/*
			function getSelectedSuppliers() {
				var url = 'api/v1/SupplyShape/?SupplierNetworkID=%s&Bounds[sw]=%s,%s&Bounds[ne]=%s,%s&relationdepth=0&add_fields=ParentCategoryID&limit=%d';
				var bounds = map.fn('getQueryBounds');
				var ne = bounds.getNorthEast();
				var sw = bounds.getSouthWest();
				var ids = [];
				
				$('.supplierList :checked').each(function() {
					var id = $(this).val();
					// Get suppliers via json
					$.getJSON(
						$.sprintf(url, 
							id,
							sw.lng(),
							sw.lat(),
							ne.lng(),
							ne.lat(),
							500 // debug
						),
						addEncodedPolygons
						//addPolygons
					);
				});
				
			}
			
			function addPolygons(networkData) {
				var overlays = [];
				// iterate through supplyshape records
				for(var i=0; i<networkData.length; i++) {
					// iterate polygons
					// @todo switch between polygons and polylines
					for(var j=0; j<networkData[i].Polygon.rings.length; j++) {
						var polyPoints = [];
						// iterate rings
						// @todo just render first ring? GPolygon doesn't seem to have support for multi-ring polys
						for(var k=0; k<networkData[i].Polygon.rings[j].points.length; k++) {
							var polyPoint = new GLatLng(networkData[i].Polygon.rings[j].points[k][1], networkData[i].Polygon.rings[j].points[k][0]);
							polyPoints.push(polyPoint);
						}
						var polygon = new GPolygon(polyPoints,"#000000",2,.5,"#000000",.5);
						overlays.push(polygon);
					}
				}
				map.fn('addOverlays', overlays);
			}
			
			function addEncodedPolygons(networkData) {
				var overlays = [];
				var totalVertexCount = 0;
				// iterate through supplyshape records
				for(var i=0; i<networkData.length; i++) {
					// iterate polygons
					// @todo switch between polygons and polylines
					for(var j=0; j<networkData[i].Polygon.rings.length; j++) {
						var polygon = new GPolygon.fromEncoded({
							polylines: [
								networkData[i].Polygon.rings[j].encoded
							],
							fill: true,
							color: "#0000ff",
							opacity: 0.4,
							outline: true
						});
						overlays.push(polygon);
						totalVertexCount += polygon.getVertexCount();
					}
				}
				
				map.fn('addOverlays', overlays);
				
				// debug
				console.log("Showing %d vertices on %d polys", totalVertexCount, overlays.length);
			}
			*/

		});
		
	}
})(jQuery);
