/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

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 terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/* 
 * Some Constants for Layer Status
 */

var LAYER_IMAGE_LOADING = 0;
var LAYER_IMAGE_LOADED  = 1;
var LAYER_DATA_OVERLOAD = 2;
var LAYER_DATA_LOADED	= 4;
var LAYER_IMAGE_ERROR   = 8;

function Layer(width, height, LayerName) {
	var ImageObject;
	var MapFile;

	this.elementType = '';

	var OriginalTitle;

	this.ErrorMessage = '';

	var TimeStamp = (new Date()).getTime();

	this.IconSrc = MAP_DEFAULT_ICON;

	var Status = LAYER_IMAGE_LOADING;

	var mapCenterPoint = new Point();
	var mapScale = 1;

	var icon;
	var iconStatus;

	var legendChip;

	var LayerParameters = new Array();

	this.data = true;
	this.active = false;

	this.displayable = true;

	this.show_table = true;

	this.hasData = false;

	var Error = false;

	var NonDisplayAbleIndex = 0;

	this.PopupMaster = new Popups(document);

	this.setMapFile = function(f) {
		MapFile = f;
	}

	this.getMapFile = function() {
		return MapFile;
	}

	this.setOriginalTitle = function(n) {
		OriginalTitle = n;
	}

	this.getOriginalTitle = function() {
		return OriginalTitle;
	}

	var Buffers = new Array();

	this.hasBuffers = function() {
		return(Buffers.length > 0);
	}
	
	this.addBuffer = function(Poly) {
		Buffers[Buffers.length] = Poly;
	}

	this.clearBuffers = function() {
		delete Buffers;
		Buffers = new Array();
	}

	this.getBuffers = function() {
		return Buffers;
	}

	this.hasBufferType = function(btype) {
		btype = new String(btype);
		for(var i = 0; i < Buffers.length; i++) {
			if(Buffers[i].type.toLowerCase() == btype.toLowerCase()) {
				return true;
			}
		}
		return false;
	}
	
	this.buffer = function(rad) {
		var bb = new Array();
		for(var i = 0; i < Buffers.length; i++) {
			var bufferedBuffers = Buffers[i].buffer(rad);
			if(!bufferedBuffers.length) {
				bb[bb.length] = bufferedBuffers;
			} else {
				for(var x = 0; x < bufferedBuffers.length; x++) {
					bb[bb.length] = bufferedBuffers[x];
				}
			}
		}
		return bb;
	}
	this.setErrorState = function(e) {
		Error = e;
	}

	this.isError = function() {
		return Error;
	}

	this.initialize = function() {
	}

	this.setParameter = function(name, value) {
		logDebugMessage('Layer', false, LayerName+' Parameter '+name+' set to '+value);
		LayerParameters[name] = value;
	}

	this.getParameter = function(name) {
		return LayerParameters[name];
	}

	this.getLayerParams = function() {
		return LayerParameters;
	}

	this.getStatus = function() {
		return Status;
	}

	this.resetStatus = function() {
		Status = LAYER_IMAGE_LOADING;
		this.setStatus(LAYER_IMAGE_LOADING);
	}

	this.setStatus = function(status) {
		if(status < Status) { return; }
		Status = status;
		switch(status) {
			case LAYER_IMAGE_LOADING:
				iconStatus.src = 'fade.png';
				logDebugMessage('Layer', false, LayerName+' Loading Image...');
				Error = false;
				break;
			case LAYER_IMAGE_LOADED:
				iconStatus.src = this.IconSrc;
				logDebugMessage('Layer', false, LayerName+' Image Loaded.');
				Error = false;
				break;
			case LAYER_IMAGE_ERROR:
				iconStatus.src = 'trash.png';
				logDebugMessage('Layer', true, LayerName+' Error with Image!');
				Error = true;
				break;
			case LAYER_DATA_OVERLOAD:
				iconStatus.src = 'zoomin.gif';
				logDebugMessage('Layer', false, LayerName+' Too Many Elements To Display!');
				Error = false;
				break;
			case LAYER_DATA_LOADED:
				iconStatus.src = 'data.png';
				logDebugMessage('Layer', false, LayerName+' Loaded Data and Image.');
				Error = false;
				break;
		}
	}

	this.rename = function (newName) {
		LayerName = newName;
	}

	/** Accessor Functions **/
	this.setScale = function (ms) {
		mapScale = ms;
	}

	this.getScale = function () {
		return mapScale;
	}

	this.getIndex = function () {
		if(!this.displayable) { return NonDisplayAbleIndex; }
		return parseInt(ImageObject.style.zIndex);
	}

	this.setIndex = function(z) {
		if(this.displayable)
			ImageObject.style.zIndex = z;
		else
			NonDisplayAbleIndex = z;
	}

	this.removeIcon = function () {
		if(icon.parentNode) {
			p = icon.parentNode;
			p.removeChild(icon);
		}
	}

	this.remove = function () {
		if(this.displayable && ImageObject.parentNode) {
			var p = ImageObject.parentNode;
			p.removeChild(ImageObject);
		}
		this.removeIcon();
	}

	this.setCenterPoint = function (p) {
		mapCenterPoint = p;
	}

	this.getCenterPoint = function() {
		return mapCenterPoint;
	}

	this.setViewer = function(v) {
		Viewer = v;
	}

	this.getViewer = function() {
		return Viewer;
	}

	this.getImageObject = function() {
		if(!ImageObject) {
			ImageObject = document.createElement('img');
		}
		return ImageObject;
	}

	this.setSize = function(p) {
		width = p.x;
		height = p.y;
	}

	this.setIcon = function(i) {
		icon = i;
		var imgs = icon.getElementsByTagName('img');
		for(var i = 0; i < imgs.length; i++) {
			if(imgs[i].className == 'Status') {
				iconStatus = imgs[i];
			} else if(imgs[i].className == 'Legend') {
				legendChip = imgs[i];
			}
		}
	}

	this.setLegend = function(url) {
		legendChip.src = url;	
		// This code pretty much just makes sure IE displays the Legend.
		legendChip.onload = function() {
			legendChip.style.height = 'auto';
			legendChip.style.width = 'auto';
		}
	}

	this.getIcon = function() {
		return icon;
	}

	this.onload = function() {
	}


	// Adds the items to the popup
	function addPopupItems(popup, obj) {
		var items = popup.getElementsByTagName('item');
		for(var i = 0; i < items.length; i++) {
			var itemLine = new String();
			if(items[i].getAttribute('title')) {
				var itemTitle = document.createElement('b');
				itemTitle.appendChild(document.createTextNode(items[i].getAttribute('title')));
				obj.appendChild(itemTitle);
			}
			if(!items[i].getAttribute('type')) {
				if(items[i].firstChild) {
					obj.appendChild(document.createTextNode(items[i].firstChild.nodeValue));
					obj.appendChild(document.createElement('br'));
					
				}
			} else if(items[i].getAttribute('type').match(/image/i)) {
				var w = items[i].getAttribute('width');
				var h = items[i].getAttribute('height');
				var src = items[i].getAttribute('src');

				var newImg = document.createElement('img');

				newImg.width = w;
				newImg.height = h;
				newImg.src = src;
				obj.appendChild(newImg);
				obj.appendChild(document.createElement('br'));
			} else if(items[i].getAttribute('type').match(/link/i) || items[i].getAttribute('type').match(/internal/i)) {
				var action;
				if(items[i].getAttribute('type').match(/internal/i)) {
					action = 'javascript:'+items[i].getAttribute('command');
				} else {
					action = items[i].getAttribute('href');
				}
				var newA = document.createElement('a');
				newA.href = action;
				newA.appendChild(document.createTextNode(items[i].firstChild.nodeValue));
				obj.appendChild(newA);
				obj.appendChild(document.createElement('br'));
			}

		}
	}

	function getStyleFunction(tagType, styleXML) {
		if(!styleXML) { return function(obj) { }; }
		var tag = styleXML.getElementsByTagName(tagType);
		var evalString = '';

		for(var t = 0; t < tag.length; t++) {
			var attrs = tag[t].getElementsByTagName('attr');
			for(var a = 0; a < attrs.length; a++) {
				evalString += ('obj.style.'+attrs[a].getAttribute('name')+'="'+attrs[a].getAttribute('value')+'";');
			}
		}	
		return function(obj) { eval(evalString); };
	}

	this.LayerPopups = null;

	this.getImageMap = function() {
		AllResults.removeTab(LayerName);	
		logDebugMessage('getImageMap', false, LayerName+' Called');
		this.getImageMapMaster(false, true);
	}
	
	
	this.getImageMapMaster = function(overrideLimits, loadData) {

		var layerServer = new Server(overrideLimits);
		
		if(!this.displayable) { return false; }
		if(!ImageObject) {
			ImageObject = document.createElement('img');
		}

		var gisW = width / 2 * mapScale;
		var gisH = height / 2 * mapScale;
		var minCoords = new Point(mapCenterPoint.x - gisW, mapCenterPoint.y - gisH), maxCoords = new Point(mapCenterPoint.x + gisW, mapCenterPoint.y + gisH);
		//Viewer.coords = new LineSegment(minCoords, maxCoords);
		//Viewer.imageSize = new Point(width, height);

		var mySelf = this;
		//Viewer.LayerParameters = LayerParameters;
		//this.setStatus(LAYER_IMAGE_LOADING);

		var reqTime = (new Date()).getTime();

		layerServer.setLayerName(LayerName);
		layerServer.setCoordinates(new LineSegment(minCoords, maxCoords));
		layerServer.setMapSize(new Point(width, height));
		layerServer.setParameters(LayerParameters);
		layerServer.setMapFile(MapFile);
		layerServer.setMapServerPath('');
		layerServer.onImageLoad = function(obj) {
			var src = obj.getAttribute('src');
			src = src.replace('.ci.stpaul.mn.us','');
			ImageObject.src = src;
			var imgObj = new Image();
			imgObj.onload = function() {
				ImageObject._onload = ImageObject.onload;
				ImageObject.src = src;
				ImageObject.onload = function() {
					ImageObject.onload = ImageObject._onload;
				}
			}
			imgObj.src = src;
			logDebugMessage('Layer', false, 'Loaded Image For: '+LayerName, src);
		}
	
		layerServer.onLegendLoad = function(obj) {
			var src = obj.getAttribute('src');
			src = src.replace('.ci.stpaul.mn.us','');
			mySelf.setLegend(src);
			var imgObj = new Image();
			imgObj.onload = function() {
				mySelf.setLegend(src);
			}

			imgObj.src = src;
			logDebugMessage('Layer', false, 'Loaded Legend For: '+LayerName,src);
		}
		
		layerServer.onTooMuchData = function() {
			mySelf.setStatus(LAYER_DATA_OVERLOAD);
			mySelf.hasData = false;
		}

		layerServer.onDataLoad = function(xmlDoc) {
			if(reqTime > TimeStamp) {
				TimeStamp = reqTime;
			}

			var allPopups = xmlDoc.getElementsByTagName('popup');
			logDebugMessage('Layer', false,LayerName+' Got Layer Popups into Array.');

			if(mySelf.data) {
				mySelf.hasData = true;
				if(allPopups.length < 400 && mySelf.show_table) {
					viewLayerAsService(convertPopupXMLtoResultsXML(xmlDoc));
				}
				// Get the style function for the contents + title
				var styleElm = xmlDoc.getElementsByTagName('style')[0];
				var popupFunction = getStyleFunction('popup', styleElm);
				var titleFunction = getStyleFunction('title', styleElm);
				var contentsFunction = getStyleFunction('contents', styleElm);
				// Load the Data into Popups
				mySelf.setStatus(LAYER_DATA_LOADED);
				logDebugMessage('Layer', false,LayerName+' Loaded '+allPopups.length+' Popups');
				for(var i = 0; i < allPopups.length; i++) {
					var popupId = allPopups[i].getElementsByTagName('id')[0];

					if(popupId && popupId.firstChild) {
						popupId = popupId.firstChild.nodeValue;
					} else {
						var time = new Date();	// Used to create Generic Id's
						popupId = time.getTime();
					}


					var tmpDiv = document.createElement('div');
					addPopupItems(allPopups[i], tmpDiv);

					var newPopup = new Popup(popupId,LayerName, LayerName, tmpDiv.innerHTML);
					newPopup.styleTitle = titleFunction;
					newPopup.styleContents = contentsFunction;

					var popupShape;
				
					var popupType = allPopups[i].getAttribute('shape');
					if(!popupType || popupType.match(/point/i) || popupType.match(/circle/i)) {
						var popupCoords = new Point();
						popupCoords.fromString(allPopups[i].getAttribute('displayxy'),',');
						var circle = new Circle();
						circle.Center = popupCoords;
						circle.Radius = 7;
						popupShape = circle;
					} else if(popupType.match(/line/i)) {
						var linePoints = allPopups[i].getAttribute('coords').split(' ');
						var linePointA = new Point();
						linePointA.fromString(linePoints[0],',');
						var linePointB = new Point();
						linePointB.fromString(linePoints[1],',');

						var theLine = new LineSegment(linePointA, linePointB);
						popupShape = theLine.buffer(5);
						//logDebugMessage('Layer',false,'Line Object! '+theLine.toString(',')+' '+popupShape.toString(','));
					} else if(popupType.match(/poly/i)) {
						var linePoints = allPopups[i].getAttribute('coords').split(' ');
						var setOfPoints = new Array();
						for(var p = 0; p < linePoints.length; p++) {
							setOfPoints[p] = new Point();
							setOfPoints[p].fromString(linePoints[p], ',');
						}
						popupShape = new Polygon();
						popupShape.buildFromPoints(setOfPoints);
						//logDebugMessage('Layer', true, 'Poly Object');
					} else {
						logDebugMessage('Layer', true,' Other Shape! '+popupType);
					}
					mySelf.PopupMaster.addPopup(popupShape, newPopup);
				}
			}
			
		}

		layerServer.onError = function(http) {
			// Display Error Condition
			ImageObject.style.visibility = 'hidden';
			logDebugMessage('Layer', true, LayerName+' ERROR!');
			mySelf.setStatus(LAYER_IMAGE_ERROR);
			mySelf.ErrorMessage = http.responseText;
		}

		layerServer.load(loadData);

		return false;
	}

	
	function viewLayerAsService(resultsXML) {
		var mockService = document.createElement('service');
		mockService.setAttribute('title', LayerName);
		var serviceObj = new Service(mockService);
		serviceObj.displayResults(resultsXML);
	}



}

function convertPopupXMLtoResultsXML(popupXML) {
	var resultsXML = document.createElement('results');
	// Use the first popup to determine the header information.
	var popups = popupXML.getElementsByTagName('popup');
	var firstPopup = popups[0];

	var columnNames = new Array();
	var headerTemplate = popups[0].getElementsByTagName('item');
	var header = document.createElement('header');
	for(var i = 0; i < headerTemplate.length; i++) {
		var col = document.createElement('col');
		col.setAttribute('value', headerTemplate[i].getAttribute('title'));
		header.appendChild(col);
	}
	resultsXML.appendChild(header);

	
	for(var i = 0; i < popups.length; i++) {
		var items = popups[i].getElementsByTagName('item');
		var newRow = document.createElement('row');
		for(var item = 0; item < items.length; item++) {
			var newCol = document.createElement('col');
			newRow.appendChild(newCol);
			if(items[item].firstChild && items[item].firstChild.nodeValue) {
				newCol.setAttribute('value', items[item].firstChild.nodeValue);
			}

			if(!items[item].getAttribute('type')) {
			} else if(items[item].getAttribute('type').match(/image/i)) {
				var copyAttrs = (new String("width,height,src,type,href")).split(',');
				for(var x = 0; x < copyAttrs.length; x++) {
					newCol.setAttribute(copyAttrs[x], items[item].getAttribute(copyAttrs[x]));
				}
			} else if(items[item].getAttribute('type').match(/link/i) || items[item].getAttribute('type').match(/internal/i)) {
				var copyAttrs = (new String("type,href,command")).split(',');
				for(var x = 0; x < copyAttrs.length; x++) {
					newCol.setAttribute(copyAttrs[x], items[item].getAttribute(copyAttrs[x]));
				}
			}

		}
		resultsXML.appendChild(newRow);
	}
	logDebugMessage('Convert', false, resultsXML.getElementsByTagName('col').length);
	return resultsXML;
}
