/**
 * @author Peter Goulborn
 * @modifiedby David Cordner
 *
 * Date: 03/05/2009
 * 
 * Class: Astun.iSharemaps.MapSourceManager
 * Provides iSharemaps map source configuration for the extended OpenLayers
 * maps. Instances of this class are created with the 
 * <Astun.iSharemaps.MapSOurceManager> constructor.  
 */

if (!OpenLayers || !Prototype) throw new Error('Dependent library not found');  // Needs to be nicer, possibly iSharemaps-wide library error?

if (!Astun) var Astun = {};
if (!Astun.iSharemaps) Astun.iSharemaps = {};
Astun.iSharemaps.MapSourceManager = Class.create(
{
/**
     * Constructor: Astun.iSharemaps.MapSourceManager
     * Create a new iShareMaps map source manager. This class makes available 
     *    map source configuration information that can be used to configure
     *    other elements in the iSharemaps OpenLayers interfacel.
     *
     * Parameters:
     * url : {String} url of the web service that returns map sources in JSON
     *    format.
     * eventElement: {Object} the HTML element on which custom events will be
     *    fired. 
     */
	'initialize': function ( url , eventElement ) {
		
		this.url = url;
		this.eventElement = eventElement;
		this.collection = $H({});
		this.queryHandler = new Astun.iSharemaps.Common.QueryHandler ({
			'MapSource': 'ms'
		});
		var urlMapSource = this.queryHandler.getParameter('MapSource');
		//this.ms = 'root';
		//alert(urlMapSource);
		//if (this.queryHandler.getParameter('MapSource') == undefined) 
		//    {urlMapSource='root';}
		var manager = this; //make available in AJAX functions
		var successFunc = function (transport) {
			var root =  transport.responseText.evalJSON();
			var msStub = {};
			while (root.mapSources.length) {
					msStub = root.mapSources.shift();
					 var opt = document.createElement('option');
                       opt.text = msStub.displayName;
                       opt.value = msStub.mapName;
		       if (root.defaultMapSource == msStub.mapName)
                           (opt.selected = true)
                       $('ddlProfiles').options.add(opt);

					this.collection.set(msStub.mapName, Object.extend({'loaded': false}, msStub));
			}
			var loadMapSourceEvent = function(mapSourceName) {
			    var ddlProfiles = $F('ddlProfiles');
			    if (ddlProfiles) {
					var controls = null;
					if (astun.mypages.mymaps.mapWrapper) {
					    astun.mypages.mymaps.mapWrapper.layerControl.layerGroups=[];
						if (astun.mypages.mymaps.mapWrapper.map) {
							astun.mypages.mymaps.doMap=false;}
					    }
					else {
						astun.mypages.mymaps.doMap=true;}
					
					//if ($('atMap')) {$('atMap').innerHTML="";}
					if ($('atThematics')) {$('atThematics').innerHTML="";}

			        this.loadMapSource(ddlProfiles);
					/*if (controls!=null) {
						astun.mypages.mymaps.mapWrapper.map.controls = controls;
					}*/
			    }
			    else {
				    if (!!mapSourceName && this.collection.get(mapSourceName)){
					    this.loadMapSource(mapSourceName);
				    }
				    else {
					    this.loadMapSource(root.defaultMapSource);
				    }
				}
			} 
			/*
			if (urlMapSource) {
				this.loadMapSource(urlMapSource);
			}
			else {
				this.eventElement.fire('astun:loadSetting', {setting: 'mapSource', loadFunction: loadMapSourceEvent.bindAsEventListener(this)});
			}
			*/
			this.eventElement.fire('astun:loadSetting', {setting: 'mapSource', loadFunction: loadMapSourceEvent.bindAsEventListener(this)});
			var ddlProfiles = $('ddlProfiles')
			Event.observe(ddlProfiles, 'change', loadMapSourceEvent.bindAsEventListener(this));
		}
		
		
		this.thisms = 'root';
		if (urlMapSource != undefined) 
		    {this.thisms = urlMapSource;}
		
		var options = {
			'method': 'get',
			parameters : {
				'RequestType': 'Json',
				'Type': 'MapSource',
				'ms': this.thisms
			},
			onSuccess: successFunc.bindAsEventListener(this)
		};
		var initialRequest = new Ajax.Request(url, options);
		
	},
	'loadMapSource': function (name, force) {
		var mapSource = this.collection.get(name);
		
		if (!mapSource.loaded && !force) {
			mapSource.loaded = false;
			var successFunc = function (transport) {
				var json =  transport.responseText.evalJSON();
				var mapSource = this.collection.get(name);
				Object.extend(mapSource, json);
				// FT - added to handel zoom level displays.
				var zoomToGeom = function(a,zLevel) {
					var map = astun.mypages.mymaps.mapWrapper.map;
					map.setCenter(map.center,zLevel);

				};
				
				var atGeomPanel = $('atGeomPanel');
				if (atGeomPanel) {
					atGeomPanel.innerHTML = '';
					for (var i=0 ; i < json.layerGroups[0].zoomLevels.length ; i++) {
						var divG = new Element('div', {'id': 'div'+json.layerGroups[0].zoomLevels[i].friendlyName , 'class': 'atZoom'});
						var spanG = new Element('span', {'id': 'span'+json.layerGroups[0].zoomLevels[i].geometrySource , 'class': 'atZoomHover'});
						var imgG = new Element('img', {'id': 'img'+json.layerGroups[0].zoomLevels[i].friendlyName , 'src': json.layerGroups[0].zoomLevels[i].icon , 'class': 'atZoomIcon'});
						//imgG.setStyle({'vertical-align': 'middle'});
						divG.insert(imgG);
						divG.insert(json.layerGroups[0].zoomLevels[i].friendlyName+'<br />');
						spanG.insert('&nbsp;');
						divG.insert(spanG);
						atGeomPanel.insert(divG);
						Event.observe(divG, 'click', zoomToGeom.bindAsEventListener(this,json.layerGroups[0].zoomLevels[i].level[0]));
						
						}
				}
				mapSource.loaded = true;
				this.current = mapSource;
				// added by FT
				astun.mypages.mymaps.mapSource = mapSource;
				this.eventElement.fire('astun:saveSetting', {'setting': 'mapSource', 'value': this.current.mapName});
				this.eventElement.fire('astun:mapSourceLoad', mapSource);
				
			}
			var failFunc =  function (transport) {
					alert('Failed to load map source!');
					this.eventElement.fire('astun:mapSourceLoadError');
				}
			
			var options = {
				'method': 'get',
				parameters : {
					'RequestType': 'Json',
					'Type': 'MapSource',
					'ms': name
				},
				onSuccess: successFunc.bindAsEventListener(this),
				onFailure: failFunc.bindAsEventListener(this)
			};
			var msRequest = new Ajax.Request(this.url, options);

		}
		else {
			
			this.current = mapSource;
			this.eventElement.fire('astun:saveSetting', {'setting': 'mapSource', 'value': this.current.mapName});
			this.eventElement.fire('astun:mapSourceLoad', mapSource);
		}
	},
    CLASS_NAME: "Astun.iSharemaps.MapSourceManager"
});
