/*
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.
*/

function Server(dataOverride) {
	var PathToMapServer, MapFile, coords = new LineSegment(), imagesize = new Point();
	var LayerName;

	var Parameters = new Array();

	var Attempts = 0;

	this.setMapServerPath = function(path) {
		PathToMapServer = path;
	}

	this.setLayerName = function(lname) {
		LayerName = lname;
	}
	
	this.setMapFile = function(mfile) {
		MapFile = mfile;
	}

	this.setParameters =  function(params) {
		Parameters = params;
	}

	this.setCoordinates = function(crds) {
		coords = crds;
	}

	this.setMapSize = function(size) {
		imagesize = size;
	}
	
	this.onImageLoad = function(xmlObj) {
		logDebugMessage('Server', false, LayerName+' got image');
	}

	this.onDataLoad = function(xmlObj) {
		logDebugMessage('Server', false, LayerName+' got data');
	}

	this.onLegendLoad = function(xmlObj) {
		logDebugMessage('Server', false, LayerName+' got legend');
	}

	this.onTooMuchData = function() {
		logDebugMessage('Server', true, LayerName+' too much data');
	}

	this.onError = function(xmlObj) {
		logDebugMessage('Server', true, LayerName+' Error!');
	}
	
	this.getParameters = function(mode) {
		var seedTime = new Date(); 
		var MapServerString = 'searchmap=1';
		if(MAPSERVER_SEND_MAP) {
			MapServerString += '&map='+MapFile;
		}

		MapServerString += '&mapsize='+imagesize.x+'+'+imagesize.y;
		MapServerString += '&mapext='+coords.minX()+'+'+coords.minY()+'+'+coords.maxX()+'+'+coords.maxY();
		MapServerString += '&mode='+mode;
		MapServerString += '&seed='+seedTime.getTime();

		for(var param in Parameters) {
			MapServerString += '&'+param+'='+Parameters[param];
		}
		return MapServerString;
	}


	this.processLoad = function(xmlObj) {
		var map = xmlObj.getElementsByTagName('map');
		var data = xmlObj.getElementsByTagName('data');
		var legend = xmlObj.getElementsByTagName('legend');

		var mapFound = false, dataFound = false, legendFound = false;

		if(map[0]) {
			mapFound = true;
			if(!map[0].getAttribute('src').match(/html/)) {
				this.onImageLoad(map[0]);
			}
		} else {
			logDebugMessage('Server', false, 'No Map Element For: '+LayerName);
		}

		if(data[0]) {
			dataFound = true;
			if(!data[0].getAttribute('src').match(/html/)) {
				var count = parseInt(data[0].getAttribute('count'));
				if(count == 0) {
					logDebugMessage('Server',false,'No Data For: '+LayerName);
				} else if(count <= LAYER_MAXIMUM_OBJECTS || dataOverride) {
					var http = getHTTPObject();
					var mySelf = this;
					var src = data[0].getAttribute('src').replace('.ci.stpaul.mn.us','');
					http.open('GET', src, true); /* I don't want this to happen asynchronously */
					http.onreadystatechange = function() {
						if(http.readyState == 4) {
							if(http.responseXML) {
								mySelf.onDataLoad(http.responseXML);
							} else {
								logDebugMessage('Server', true, 'Error getting Response XML For: '+LayerName);
							}
															
						}
					};
					http.send(true);

					logDebugMessage('Server', false, 'Getting Data For: '+LayerName,src);
				} else {
					this.onTooMuchData();
				}
			} else {
				logDebugMessage('Server', false, 'Data Returned Error For: '+LayerName);
			}
		} else {
			logDebugMessage('Server', false, 'No Data Element For: '+LayerName);
		}

		if(legend[0]) {
			legendFound = true;
			if(!legend[0].getAttribute('src').match(/html/)) {
				this.onLegendLoad(legend[0]);
			} else {
				logDebugMessage('Server', true, 'No Legend For: '+LayerName);
			}
		}
		if(!legendFound || !dataFound || !mapFound) {
			this.load();
		} else {
			Attempts = 0;
		}
	}

	function processCallString(call,params) {
		call = call.replace('[MAPSERVER_PATH]', MAPSERVER_PATH);
		call = call.replace('[MAPFILE]', MapFile);
		call = call.replace('[MAPSERVER_HOST]', MAPSERVER_HOST);

		call = call.replace('[PARAMETERS]', params);
		return call;
	}

	if(CALL_SERVER_TYPE == 'gismo') {
		this.load = function() {
			var http = getHTTPObject();
			// Get the Layer Parameters
			var params = this.getParameters('gismo');
			// Create the Call based on the Template
			var call = processCallString(MAPSERVER_CALL, params);

			var mySelf = this;
			// Open up a connection in Asynchronous mode
			http.open(MAPSERVER_METHOD, call, true);
			logDebugMessage('Server', false, 'Called '+LayerName, processCallString(MAPSERVER_DISPLAY_CALL, params));

			http.onreadystatechange = function() {
				if(http.readyState == 4) {
					var xmlObj = http.responseXML;
					Attempts++;
					if(xmlObj) {
						mySelf.processLoad(xmlObj);
					} else if (Attempts < SERVER_MAXIMUM_ATTEMPTS) {
						logDebugMessage('Server', true, 'Error with '+LayerName+' Attempting Again ('+Attempts+')..');
						mySelf.load();
					} else {
						mySelf.onError(http);
					}
				}
			};
			http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			http.setRequestHeader('Content-length', params.length);
			http.setRequestHeader('Connection', 'close');

			http.send(params);
		}
	}

	/* 
	 * This version requires mode=browse and mode=nquery to be setup.
	 */

	if(CALL_SERVER_TYPE == 'standard') {
		var MapAttempts = 0;
		var NqueryAttempts = 0;

			var mySelf = this;

		function getMapFromServer(call, params, ignoreError) {
			var http = getHTTPObject();
			http.open(MAPSERVER_METHOD, call, true);
			http.onreadystatechange = function() {
				if(http.readyState == 4) {
					var xmlDoc = http.responseXML;
					if(xmlDoc) {
						var map = xmlDoc.getElementsByTagName('map');
						var legend = xmlDoc.getElementsByTagName('legend');
						var popups = xmlDoc.getElementsByTagName('popup');	
						
						if(map[0]) {
							if(!map[0].getAttribute('src').match(/html/)) {
								mySelf.onImageLoad(map[0]);
							}
						} else {
							logDebugMessage('Server/Standard', false, 'No Map Element For: '+LayerName);
						}

						if(legend[0]) {
							legendFound = true;
							if(!legend[0].getAttribute('src').match(/html/)) {
								mySelf.onLegendLoad(legend[0]);
							} else {
								logDebugMessage('Server/Standard', true, 'No Legend For: '+LayerName);
							}
						}

						var count = popups.length;
						if(count == 0) {
							logDebugMessage('Server/Standard', false, 'No Data to Load For: '+LayerName,processCallString(MAPSERVER_DISPLAY_CALL,params));	
						} else if(count <= LAYER_MAXIMUM_OBJECTS || dataOverride) {
							mySelf.onDataLoad(xmlDoc);
						} else {
							mySelf.onTooMuchData();
						}
					} else if(MapAttempts < SERVER_MAXIMUM_ATTEMPTS) {
						MapAttempts++;
						logDebugMessage('Server/Standard', true, 'Error with '+LayerName+' Attempting Again ('+MapAttempts+')...',processCallString(MAPSERVER_DISPLAY_CALL,params));	
						getMapFromServer(call, params, ignoreError);
					} else {
						if(!ignoreError) {
							mySelf.onError(http);
						}
					}
				}
			}
			http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			http.setRequestHeader('Content-length', params.length);
			http.setRequestHeader('Connection', 'close');

			http.send(params);
		}

		this.load = function() {
			var mapParams = this.getParameters('browse');
			var nqueryParams = this.getParameters('nquery');
			var mapCall = processCallString(MAPSERVER_CALL, mapParams);
			var nqueryCall = processCallString(MAPSERVER_CALL, nqueryParams);

			getMapFromServer(mapCall,mapParams, false);
			getMapFromServer(nqueryCall, nqueryParams, true);
		}
	}
}
