/*
Copyright (c) 2009, Dan "Ducky" Little & GeoMOOSE.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

function GeomooseCatalog(parentDivId, olMap) {
	var elementCounter = 0;
	var MyCatalog = false;
	var MySelf = this;

	var MapbookLoaded = false;

	function getCatalogElementId() {
		elementCounter++;
		return 'catalog-'+elementCounter;
	}

	function toggleGroup() {
		/*var g = document.getElementById(groupElementId);*/
		var grpList = this.nextSibling;
		var className = new String(grpList.className);
		if(className.match('catalog-group-collapsed')) {
			grpList.className = className.replace('collapsed','expanded');
		} else {
			grpList.className = className.replace('expanded','collapsed');
		}
	}


	function renderGroup(groupElementId, group) {
		var p = document.getElementById(groupElementId);
		var ul = document.createElement('ul');
		ul.className = 'catalog';

		if(p.tagName == 'UL' && group.getAttribute('title')) {
			var li = document.createElement('li');
			p.appendChild(li);
			li.appendChild(document.createTextNode(group.getAttribute('title')));
			li.className = 'catalog-group';
			li.onclick = toggleGroup;
			li = null;
			if(parseBoolean(group.getAttribute('expand'))) {
				ul.className += ' catalog-group-expanded';
			} else {
				ul.className += ' catalog-group-collapsed';
			}
		} else {
			ul.className += ' catalog-group-expanded';
		}
		ul.id = getCatalogElementId();
		p.appendChild(ul);

		for(var i = 0; i < group.childNodes.length; i++) {
			var tagName = group.childNodes[i].tagName;
			if(tagName) {
				if(tagName == 'group') {
					renderGroup(ul.id, group.childNodes[i]);
				} else if(tagName == 'layer') {
					renderLayer(ul.id, group.childNodes[i]);
				}
			}
		}

		ul = null;
		p = null;
	}

	function iterateThroughLayers(pathString, fn) {
		var services = MyCatalog.getElementsByTagName('map-source');
		var paths = new String(pathString).split(':');

		for(var i = 0; i < services.length; i++) {
			var root = services[i].getAttribute('name');
			var layers = services[i].getElementsByTagName('layer');
			for(var l = 0; l < layers.length; l++) {
				var layerName = layers[l].getAttribute('name')
				for(var p = 0; p < paths.length; p++) {
					if(root+'/'+layerName == paths[p]) {
						var mapLayer = Map.getLayersByName(root)[0];
						if(mapLayer) {
							fn(mapLayer, paths[p]);
						}
					}
				}

			}
		}
	
	}

	this.refreshLayer = function(pathString) {
		iterateThroughLayers(pathString, function(mapLayer) {
			/* This forces the image to reload */
			mapLayer.params['GEOMOOSE_REFRESH'] = (new Date()).getTime();
			mapLayer.redraw();
		});
	}

	this.fadeLayer = function(pathString) {
		iterateThroughLayers(pathString, function(mapLayer) {
			if(mapLayer.opacity == null) { mapLayer.opacity = 1; }
			var newOpac = mapLayer.opacity - CONFIGURATION.layer_controls.fade.change_percent/100;
			if(newOpac < 0) { newOpac = 0; }
			mapLayer.setOpacity(newOpac);
		});
	}


	this.unfadeLayer = function(pathString) {
		iterateThroughLayers(pathString, function(mapLayer) {
			if(mapLayer.opacity == null) { mapLayer.opacity = 1; }
			var newOpac = mapLayer.opacity + CONFIGURATION.layer_controls.unfade.change_percent/100;
			if(newOpac > 1) { newOpac = 1; }
			mapLayer.setOpacity(newOpac);
		});
	}

	this.upLayer = function(pathString) {
		iterateThroughLayers(pathString, function(mapLayer) {
			mapLayer.map.raiseLayer(mapLayer, 1);
		});
	}

	this.downLayer = function(pathString) {
		iterateThroughLayers(pathString, function(mapLayer) {
			mapLayer.map.raiseLayer(mapLayer, -1);
		});
	}

	this.cycleLayer = function(pathString) {
	}


	var legendImages = new Array();

	function updateLegendURLs(pathString) {
		iterateThroughLayers(pathString, function(mapLayer,layerPath) {
			var legendURL = false;
			if(!legendImages[layerPath]) {
				return false;	// nothing to do, no image available
			}
			var lname = layerPath.split('/').pop();
			if(mapLayer instanceof OpenLayers.Layer.MapServer) {
				legendURL = mapLayer.getURL(Map.getExtent()).replace('mode=map','mode=legend');

				/* specify THIS layer */
				legendURL = legendURL.replace(/layers=[\+\_\%a-zA-Z0-9\/]*\&/, 'layers='+lname+'&');
			}
			if(mapLayer instanceof OpenLayers.Layer.WMS) {
				legendURL = mapLayer.getURL(Map.getExtent()).replace('REQUEST=GetMap', 'REQUEST=GetLegendGraphic');
				legendURL += '&LAYER=' + lname;
				legendURL += '&SCALE=' + Map.getScale();
			}
			if(legendURL) {
				document.getElementById(legendImages[layerPath]).setAttribute('src',legendURL);
			}
		});
	}

	this.legendLayer = function(pathString) {
		var id = this.id;
		var parentControl = this;
		var legendParent = document.getElementById(id+'-legend');

		if(legendParent.className.indexOf('Visible') >= 0) {
			legendParent.className = legendParent.className.replace('Visible','Hidden');
			while(legendParent.childNodes[0]) {
				legendParent.removeChild(legendParent.childNodes[0]);
			}
			iterateThroughLayers(pathString, function(mapLayer, layerPath) {
				legendImages[layerPath] = false;
			});
			parentControl.className = parentControl.className.replace('sprite-control-legend-visible', '');
		} else {
			legendParent.className = legendParent.className.replace('Hidden','Visible');
			if(parentControl.className.indexOf('sprite-control-legend-visible') < 0) {
				parentControl.className += ' sprite-control-legend-visible'; 
			}
			iterateThroughLayers(pathString, function(mapLayer, layerPath) {
				if(!legendImages[layerPath]) {
					var legendImg = document.createElement('img');
					legendImg.className = 'catalog-legend-image';
					legendImg.id = 'catalog-legend-'+getCatalogElementId();
					legendImages[layerPath] = legendImg.id;
					legendParent.appendChild(legendImg);
					legendImg.setAttribute('src','images/blank.gif'); /* Default to prevent display issues */
					legendImg = null;
				}
			});

			updateLegendURLs(pathString);
		}
	}


	this.setLayerVisibility = function(pathString, visibility) {
		var services = MyCatalog.getElementsByTagName('map-source');
		var paths = new String(pathString).split(':');

		var foundSomething = false;

		for(var i = 0; i < services.length; i++) {
			var root = services[i].getAttribute('name');
			var layers = services[i].getElementsByTagName('layer');
			var updateRequired = false;
			for(var l = 0; l < layers.length; l++) {
				var layerName = layers[l].getAttribute('name')
				for(var p = 0; p < paths.length; p++) {
					if(root+'/'+layerName == paths[p]) {
						foundSomething = true;
						var v = 'false';
						if(visibility) {
							v = 'true';
						}
						if(parseBoolean(visibility) != parseBoolean(layers[l].getAttribute('visible'), false)) {
							layers[l].setAttribute('visible', v);
							updateRequired = true;
						}
					}
				}
			}

			if(updateRequired) {
				var layersList = new Array();
				for(var l = 0; l < layers.length; l++) {
					if(parseBoolean(layers[l].getAttribute('visible'))) {
						layersList.push(layers[l].getAttribute('name'));
					}
				}
			
				var mapLayer = Map.getLayersByName(root)[0];
				if(mapLayer instanceof OpenLayers.Layer.MapServer) {
					mapLayer.params['layers'] = layersList.join(' ');
				} else if (mapLayer instanceof OpenLayers.Layer.WMS) {
					mapLayer.params['LAYERS'] = layersList.join(',');
				}
				if(layersList.length == 0) {
					mapLayer.setVisibility(false);
				} else {
					mapLayer.setVisibility(true);
				}
				if(MapbookLoaded) {
					mapLayer.redraw();
				}

			}
			

		}
		return foundSomething;
	}

	function multiSelectLayer() {
		MySelf.setLayerVisibility(this.value, this.checked);
	}

	function singleSelectLayer() {
		var p = this.parentNode.parentNode;
		var inputs = p.getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++) {
			if(inputs[i].name == this.name) {
				inputs[i].checked = false;
			}
			MySelf.setLayerVisibility(inputs[i].value, false);
		}
		this.checked = true;
		MySelf.setLayerVisibility(this.value, true);
	}

	function inScale(minscale, maxscale) {
		var scale = olMap.getScale();
		if(!maxscale && !minscale) { return true; }
		if(!maxscale && scale >= minscale) { return true; }
		if(!minscale && scale <= maxscale) { return true; }
		return (minscale <= scale && scale <= maxscale);
	}

	function renderLayer(groupElementId, layer) {
		var p = document.getElementById(groupElementId);
		var li = document.createElement('li');
		li.className = 'catalog-layer';
		p.appendChild(li);
		var cbox = document.createElement('input');
		cbox.id = 'catalog-'+layer.getAttribute('src');

		if(parseBoolean(layer.parentNode.getAttribute('multiple'),true)) {
			cbox.name = layer.parentNode.getAttribute('name');
			cbox.type = 'checkbox';
			cbox.value = layer.getAttribute('src');
			cbox.onclick = multiSelectLayer;
		} else {
			cbox.type = 'radio';
			cbox.value = layer.getAttribute('src');
			cbox.onclick = singleSelectLayer;
		}
		li.appendChild(cbox);

		var layerTitle = document.createElement('span');
		layerTitle.className = 'catalog-layer-title';
		li.appendChild(layerTitle);

		layerTitle.appendChild(document.createTextNode(layer.getAttribute('title')));

		if(layer.getAttribute('tip')) {
			layerTitle.title = layer.getAttribute('tip');
		}

		if(layer.getAttribute('minscale')) {
			layerTitle.minscale = parseFloat(layer.getAttribute('minscale'));
		}

		if(layer.getAttribute('maxscale')) {
			layerTitle.maxscale = parseFloat(layer.getAttribute('maxscale'));
		}

		if(inScale(layerTitle.minscale, layerTitle.maxscale)) {
			layerTitle.className += ' catalog-inscale';
		} else {
			layerTitle.className += ' catalog-outscale';
		}
		
		var controlSpan = document.createElement('span');
		controlSpan.className = 'catalog-controls-container';
		li.appendChild(controlSpan);
		
		var controlsId = getCatalogElementId();

		for(var control_name in CONFIGURATION.layer_controls) {
			var layerSwitch = CONFIGURATION.layer_controls[control_name].on;
			if(layer.getAttribute(control_name)) {
				layerSwitch = parseBoolean(layer.getAttribute(control_name));
			}
			if(layerSwitch) {
				var toolDiv = document.createElement('div');
				toolDiv.className = 'sprite-control sprite-control-'+control_name;
				toolDiv.value = layer.getAttribute('src');
				toolDiv.controlFn = eval("MySelf."+control_name+"Layer");
				toolDiv.id = controlsId;
				toolDiv.onclick = function () {
					this.controlFn(this.value);
				}

				var tooltip = CONFIGURATION.layer_controls[control_name].tip;
				if(tooltip) {
					tooltip = tooltip.replace('%LAYER%', layer.getAttribute('title'));
					toolDiv.title = tooltip;
				}
				controlSpan.appendChild(toolDiv);
			}
		}
		var legend = document.createElement('div');
		legend.className = 'catalog-legend Hidden';
		legend.id = controlsId+'-legend';
		// Leave the legend "blank" for the time being.
		//legend.src = 'images/blank.gif';
		li.appendChild(legend);

		/* check to see if the layer is "on" */
		if(parseBoolean(layer.getAttribute('status'))) {
			cbox.checked = true;
			cbox.onclick();
		}

		cbox = null;
		li = null;
		p = null;
	}

	function onRefreshMap () {
		var p = document.getElementById(parentDivId);
		var span = p.getElementsByTagName('span');
		for(var i = 0; i < span.length; i++) {
			if(span[i].className.indexOf('catalog-layer-title') >= 0) {
				var layerTitle = span[i];
				if(inScale(layerTitle.minscale, layerTitle.maxscale)) {
					layerTitle.className = layerTitle.className.replace('catalog-outscale', 'catalog-inscale');
				} else {
					layerTitle.className = layerTitle.className.replace('catalog-inscale', 'catalog-outscale');
				}
				layerTitle = null;
			}
		}

		for(var pathString in legendImages) {
			updateLegendURLs(pathString);
		}
	}

	function toggleTool(obj, tool) {
		var visClassName = 'sprite-control-'+tool+'-selected';

		/* so it's current visible ... so remove it */
		if(obj.className.indexOf(visClassName) >= 0) {
			obj.className = obj.className.replace(' '+visClassName, '');
			obj.className = obj.className.replace(visClassName, '');
		} else {
			obj.className = obj.className + ' ' + visClassName;
			onSelectTool.push(function() {
				toggleTool(obj, tool);
			});
		}

	}

	this.onLoadedMapbook = function(mapbookXML) {
		MyCatalog = mapbookXML;
		var catalog = mapbookXML.getElementsByTagName('catalog')[0];
		var layerControls = mapbookXML.getElementsByTagName('layer-control');
		for(var i = 0; i < layerControls.length; i++) {
			CONFIGURATION.layer_controls[layerControls[i].getAttribute('name')] = {'on' : parseBoolean(layerControls[i].getAttribute('on')), 'tip' : layerControls[i].getAttribute('tip')}	
			var funcString = "function(paths) { selectTool(); toggleTool(this, '%service_name%'); GeoMOOSE.startService('%service_name%', {'%input%' : paths}); }";
			funcString = funcString.replace(/%service_name%/g, layerControls[i].getAttribute('service-name'));
			funcString = funcString.replace('%input%', layerControls[i].getAttribute('layer-input'));


			eval("MySelf."+layerControls[i].getAttribute('name')+"Layer = "+funcString);
		}

		renderGroup(parentDivId, catalog);

		olMap.events.register('moveend', this, onRefreshMap);
		onRefreshMap();
		MapbookLoaded = true;
	}
}
