﻿/// <reference path="GISMap.js" />
/// <reference path="GISHelperClasses.js" />
/// <reference path="countyApp.js" />

var map = null;
var bufferPopup = null;

function CountyApp() {}
CountyApp.Init = function(configFilename) {
	/// <summary>STATIC - Creates an automatic loader for this county map.</summary>
	/// <param name="configFile" type="String">Javascript file that contains configuration settings.  If this isn't provided then GISMap.DefaultConfiguration is used.</summary>
	/// <returns type="void" />

	// If a configuration file was provided then load it; otherwise, use the default configuration.
	if ((configFilename) && (typeof FileRequest !== 'undefined')) {
		var fileRequest = new FileRequest(configFilename + '?timestamp=' + new Date().getTime());

		if (fileRequest.load()) {
			// Warning: eval method being used.
			eval(fileRequest.receivedData);
		} else {
			throw new Error('CountyApp.Init() - Error loading client configuration file: ' + fileRequest.lastError + '.\r\n\r\nFilename: ' + configFilename);
		}
	}

	// Get the initial settings from the querystring, store them in the Config object.
	var initialSize = GISMap.GetQS('size');
	var initialParcelID = GISMap.GetQS('parcelid');
	if (initialParcelID) {
		CountyApp.Config.parcelID = initialParcelID;
	}
	if (initialSize) {
		CountyApp.Config.width = initialSize;
		CountyApp.Config.height = initialSize;
	}

	map = new GISMap(document.getElementById('map'), CountyApp.Config);

	map.mapNoteDiv = document.getElementById('mapNotes');
	map.legendImage = document.getElementById('legendImage');
	map.setInfoFrame(document.getElementById('infoFrame'), CountyApp.Config.infoFrame_xmlFile, CountyApp.Config.infoFrame_xslFile);
	map.onLoadComplete = new GISMapEvent(function() { ui_displayLayers.call(this, document.getElementById('layerListDiv')); });
	map.onSearchResultsReceived = new GISMapEvent(function(pageName, resultSet) { makeTabActive(document.getElementById('dataTab')); });
	map.onParcelDataReceived = new GISMapEvent(CountyApp.OnParcelDataReceived);
	map.onSelectedParcelIDReceived = new GISMapEvent(CountyApp.Config.OnSelectedParcelIDReceived);
	map.onHighlightedParcelsSet = new GISMapEvent(CountyApp.Config.onHighlightedParcelsSet);

	map.onInitializeMapSize = new GISMapEvent(function(mapSize) {
		var mapTD = document.getElementById('mapTD');
		if (mapTD) {
			mapTD.style.width = mapSize.width + 'px';
		}

		if (mapSize.width >= GISMap.size.large.width) {
			if (document.getElementById('mapSizeL')) {
				document.getElementById('mapSizeL').checked = true;
			}
		} else if (mapSize.width <= GISMap.size.small.width) {
			if (document.getElementById('mapSizeS')) {
				document.getElementById('mapSizeS').checked = true;
			}
		} else {
			if (document.getElementById('mapSizeM')) {
				document.getElementById('mapSizeM').checked = true;
			}
		}
	});

	map.onMapContextReset = new GISMapEvent(function() { ui_displayLayers.call(this, document.getElementById('layerListDiv')); });
	map.onBufferReceived = new GISMapEvent(CountyApp.BufferReceived);
	map.onInfoFrameUnsupportedMSXMLError = new GISMapEvent(function() { makeTabActive(document.getElementById('dataTab')); });

	// Funny construction, but debugging will be enabled if debugCommunications is in the querystring.
	map.communicationsHandler.ajaxRequest.debug(!!GISMap.GetQS('debugCommunications'));

	// Debugging is enabled by setting the 'debuggingConsole' querystring value.
	if ((GISMap.GetQS('debuggingConsole')) || (CountyApp.Config.debug_showConsole)) {
		document.getElementById('DebuggingConsoleLI').style.display = 'block';
		makeTabActive(document.getElementById('debuggingConsoleTab'));
		// Set the debugger.
		map.setDebugger(new GISDebugger(document.getElementById('debugWindow'), { height: CountyApp.Config.debug_consoleHeight || 200 }));
	}

	map.load();

	if (GISPopupBox) {
		bufferPopup = new GISPopupBox(document.getElementById('bufferPopup'), 'Buffer Search', { width: 250 }, { left: 15, top: 100 });
		bufferPopup.onAfterLoad = function() { document.getElementById('bufferRadiusPopup').focus(); };
		bufferPopup.innerBoxText = '<form method="post" action="#" style="margin:0px;" onsubmit="if (document.getElementById(\'submitBuffer\')) {document.getElementById(\'submitBuffer\').click()}; return false;">Buffer Radius in Feet (2,640ft Maximum):<br /><input type="text" class="text" id="bufferRadiusPopup" value="100" /></form>';
		bufferPopup.addButton(new GISPopupBoxButton('Display', function() { if (input_retrieveBuffer(map, document.getElementById('bufferRadiusPopup'))) { this.hide(); } }, 'submitBuffer'));
		bufferPopup.addButton(new GISPopupBoxButton('Cancel'));
	}
};

// Displays the buffer search results in a new window.
CountyApp.BufferReceived = function(parameters) {
	if (parameters.parcelList.length === 0) {
		// Don't open a new window, just alert the user.
		alert('No parcels were inside the buffer.');
	} else {
		// Maximum URL is 2048 characters.  If the parameter list is too long, switch to POST method.
		if (parameters.parcelList.length <= 1800) {
			// Use the GET method.
			//	For simplicity, let us just pass this Parcel ID list to another page which will access
			// the database and present a printer-friendly list.
			if (window.open('dispBufferResults.aspx?bufferDistance=' + parameters.bufferDistance + '&selectedParcelID=' + parameters.selectedParcelID + '&parcelList=' + parameters.parcelList +'','BufferResults','width=375,height=500,scrollbars=yes,resizable=yes,statusbar=yes') === null) {
				alert('The window was blocked by a popup blocker.\r\nPlease disable your popup blocker to see the buffer results, you will have to run the buffer search again.');
			}
		} else {
			// Fix for IE's inability to create named elements.
			document.createNamedElement = function(type, name) {
				var element;
				try {
					// This will only work in IE.
					element = document.createElement('<'+type+' name="'+name+'">');
				} catch (e) { }
				if (!element || !element.name) { // Not in IE, then
					element = document.createElement(type);
					element.name = name;
				}
				return element;
			};
	
			// Create a form element and then submit it.
			var thisForm = document.createElement('form');
			thisForm.method='post';
			thisForm.action='dispBufferResults.aspx';
			thisForm.target='_blank';
				
			var thisInput = document.createNamedElement('input', 'bufferDistance');
			thisInput.type='hidden';
			thisInput.value=parameters.bufferDistance;
			thisForm.appendChild(thisInput);
	
			thisInput = document.createNamedElement('input', 'selectedParcelID');
			thisInput.type='hidden';
			thisInput.value=parameters.selectedParcelID;
			thisForm.appendChild(thisInput);

			thisInput = document.createNamedElement('input', 'parcelList');
			thisInput.type='hidden';
			thisInput.value=parameters.parcelList;
			thisForm.appendChild(thisInput);

			document.body.appendChild(thisForm);
			thisForm.submit();
			document.body.removeChild(thisForm);
			thisForm = null;
		}
	}
};

CountyApp.OnParcelDataReceived = function(resultSet) {
	if (CountyApp.Config.OnParcelDataReceived) {
		if (CountyApp.Config.OnParcelDataReceived.call(this, resultSet) === false) {
			return false;
		}
	}

	makeTabActive(document.getElementById('dataTab'));
	
	return null;
};

// Use default settings, these can be overridden by a config file.
CountyApp.Config = new GISHelper.Clone(GISMap.DefaultConfiguration);