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

/*
 * Default Layers have a little more dimension in GISmo3 than they have in previous version
 * This file is here because G3 will also use a stored cookie in order to save default information.
 */

function loadDefaultsFromMapBook(xmlObj, sourceObj, EventManager, objMap, refreshMap) {
	var allMaps = xmlObj.getElementsByTagName('map');
	var allServices = xmlObj.getElementsByTagName('service');

	var interfaceElements = xmlObj.getElementsByTagName('interface');
	for(var i = 0; i < interfaceElements.length; i++) {
		var params = interfaceElements[i].getElementsByTagName('param');
		for(var p = 0; p < params.length; p++) {
			var name = params[p].getAttribute('name');
			var value = params[p].getAttribute('value');
			var type = params[p].getAttribute('type');
			var evalString;
			if(type && !type.match(/string/i)) {
				evalString = name+"="+value+";";
			} else {
				evalString = name+"='"+value+"';";
			}
			eval(evalString);
			logDebugMessage('Override Variable', true, evalString);
		}
	}
			

	var zoomTos = xmlObj.getElementsByTagName('zoomto');
	if(zoomTos.length > 0) {
		/* Zoom to the last one in the list */
		var zoomElement = zoomTos[zoomTos.length - 1];
		var zoomView = convertViewString(zoomElement.firstChild.nodeValue, objMap.getMapSize());
		EventManager.changePointScale(zoomView.Center, zoomView.Radius);
	}

	var selection = xmlObj.getElementsByTagName('selection');
	for(var s = 0; s < selection.length; s++) {
	//	DrawingArea[selection[s].getAttribute('title')] = selection[s].getAttribute('id');
		EventManager.triggerEvent('addselection', selection[s]);
	}

	var cgi = new CGI();
	var layersOff = new String(cgi.param('layersoff'));
	var layersOffArr = layersOff.split(',');

	var groupsOff = new String(cgi.param('groupsoff'));
	var groupsOffArr = groupsOff.split(',');
	
	var xmlGroups = xmlObj.getElementsByTagName('group');
	for(var g = 0; g < xmlGroups.length; g++) {
		var groupTitle = xmlGroups[g].getAttribute('title');
		for(var ga = 0; ga < groupsOffArr.length; ga++) {
			if(unescape(groupsOffArr[ga]) == groupTitle) {
				var layers = xmlGroups[g].getElementsByTagName('map');
				for(var l = 0; l < layers.length; l++) {
					layersOffArr.push(layers[l].getAttribute('title'));
				}
			}
		}
	}

	var layersToAdd = new Array();
	for(var m = 0 ; m < allMaps.length; m++) {
		var name = allMaps[m].getAttribute('title');
		var def = new String(allMaps[m].getAttribute('default'));
		if(def.match(/true/i)) {
			var addLayer = true;
			for(var i = 0; i < layersOffArr.length && addLayer; i++) {
				if(layersOffArr[i] == name) {
					addLayer = false;
				}
			}
			if(addLayer) {
				layersToAdd[name] = allMaps[m];
			}
		}
	}
	for(var l in layersToAdd) {
		EventManager.triggerEvent('addlayer', layersToAdd[l]);
		if(refreshMap) {
			objMap.refreshLayer([l]);
		}
	}


	var servicesToAdd = new Array();
	for(var s = 0; s < allServices.length; s++) {
		var def = new String(allServices[s].getAttribute('default'));
		var sel = new String(allServices[s].getAttribute('selected'));
		if(def.match(/true/i)) {
			var title = allServices[s].getAttribute('title');
			servicesToAdd[title] = allServices[s];
		}
	}
	for(var s in servicesToAdd) {
		EventManager.triggerEvent('addservice', servicesToAdd[s]);
		if(servicesToAdd[s].getAttribute('selected') && servicesToAdd[s].getAttribute('selected').match(/true/i)) {
			EventManager.triggerEvent('selecttool', s);
		}
	}

}

function loadDefaults(xmlObj, EventManager, objMap) {
/*	if(checkState()) {
		loadDefaultsFromMapBook(getState(), xmlObj);
	} else {*/
		loadDefaultsFromMapBook(xmlObj, xmlObj,EventManager,objMap);
/*	}*/
}



function downloadAndAppendMapbook(mapBook, parentDocument, parentGroup) {
	var http = getHTTPObject();
//	http.open("GET", mapBook, false);
	if(document.all) {
		http.open("GET", mapBook, false);
	} else {
		http.open("GET", mapBook);
	}

	http.onreadystatechange = function () { 
		if(http.readyState == 4) {
			if(http.responseXML) {
				try {
					var nGroup = importNode(parentDocument, http.responseXML.getElementsByTagName('mapbook')[0], true);
					var nodes = nGroup.childNodes;
					while(nodes[0]) {
						parentGroup.appendChild(nodes[0]);
					}
				} catch(e) {
					alert('There was an error importing "'+parentGroup.getAttribute('title')+'" ignoring and moving on.');
				}
			} else {
				alert('Mapbook '+mapBook+' failed to return valid XML!');
			}

		}
	}
	http.send(null);
}

function getMapbook(mapBook, EventManager, objMap, refreshMap) {
	var http = getHTTPObject();
	if(document.all) {
		http.open("GET", mapBook, false);
	} else {
		http.open("GET", mapBook);
	}
	http.onreadystatechange = function () { 
		if(http.readyState == 4) {
			xmlDoc = http.responseXML;
			if(xmlDoc) {
				var groups = xmlDoc.getElementsByTagName('group');
				//alert(groups.length);
				for(var g = 0; g < groups.length; g++) {
					if(groups[g].getAttribute('src')) { /* Include the contents of a foreign MapBook in this group */
						downloadAndAppendMapbook(groups[g].getAttribute('src'), xmlDoc, groups[g]);		
					}
				}
				groups = xmlDoc.getElementsByTagName('group');
				//alert(groups.length);

				if(MAP_MAPBOOK_ORDER) {
					var allMaps = xmlDoc.getElementsByTagName('map');
					for(var m = 0; m < allMaps.length; m++) {
						allMaps[m].setAttribute('zindex', m);
					}
				}
				EventManager.onLoadedMapbook(xmlDoc, objMap);
				/* Refresh the layers if requested */
				if(refreshMap) {
					objMap.refreshLayers();
				}
			} else {
				alert('Mapbook '+mapBook+' failed to return XML!');
			}
			return xmlDoc;
		}
	};
	http.send(null);
}

function getObjectByTitle(xmlDoc, objType, objTitle) {
	var objs = xmlDoc.getElementsByTagName(objType);
	for(var i = 0; i < objs.length; i++) {
		if(objs[i].getAttribute('title') && objs[i].getAttribute('title') == objTitle) {
			return objs[i];
		}
	}
	return null;
}


function getDefaultMapbook(EventManager,oMap) {
	var util = new CGI();
	var mapbookFromURL = util.param('mapbook');
	var MapBook = MAPBOOK_FILE;
	if(mapbookFromURL) {
		MapBook = mapbookFromURL;
	}



	getMapbook(MapBook,EventManager,oMap);
}


function mapbookLoadedEvents(xmlDoc) {
	var cgi = new CGI();

	var layers = new String(cgi.param('layers'));
	var layersArr = layers.split(',');

	var groups = new String(cgi.param('groups'));
	var groupsArr = groups.split(',');

	var xmlGroups = xmlDoc.getElementsByTagName('group');
	for(var g = 0; g < xmlGroups.length; g++) {
		var groupTitle = xmlGroups[g].getAttribute('title');
		for(var ga = 0; ga < groupsArr.length; ga++) {
			if(unescape(groupsArr[ga]) == groupTitle) {
				var layers = xmlGroups[g].getElementsByTagName('map');
				for(var l = 0; l < layers.length; l++) {
					layersArr.push(layers[l].getAttribute('title'));
				}
			}
		}
	}
	for(var i = 0; i < layersArr.length; i++) {
		var map = getObjectByTitle(xmlDoc, 'map', unescape(layersArr[i]));
		if(map) {
			Events.triggerEvent('addlayer',map);
		}
	}

	var title = cgi.param('call');
	if(title && title != 'null') {
		var services = xmlDoc.getElementsByTagName('service');
		var knownServices = new Array();
		for(var s = 0; s < services.length; s++) {
			knownServices[services[s].getAttribute('title')] = services[s];
		}
		var serviceXML = knownServices[title];
		if(serviceXML) {
			var inputs = serviceXML.getElementsByTagName('input');
			var url = serviceXML.getElementsByTagName('url')[0].firstChild.nodeValue;
			url = url + '?';
			for(var i = 0; i < inputs.length; i++) {
				var iType = inputs[i].getAttribute('type');
				var iName = inputs[i].getAttribute('name');
				/*if(iType.match(/user/i)) {*/
					if(cgi.param(iName)) {
						inputs[i].setAttribute('value', cgi.param(iName));
					}
				/*}*/
			}
			Events.addEventListener('servicereturn', 'StartupCallService', function () {
				Events.removeEventListener('servicereturn', 'StartupCallService');
				/* Resize the window */
				Events.triggerEvent('windowresize', null);
			});
			Events.triggerEvent('callservice', serviceXML);
		} else {
			alert('Cannot Find Service '+title);
		}
	} else {
		/* Call window resize after if there is no service to call */
		Events.triggerEvent('windowresize', null);
	}
}
