
/*
 * This performs two functions:
 * 1: Creates the necessary HTML/Form for a given service
 * 2: Builds the Required URL
 */

function Service(serviceXMLObj, resultsWindow) {
	var serviceTitle = serviceXMLObj.getAttribute('title');
	var serviceDialog = new Dialog(600,300, serviceTitle);
	serviceDialog.createEmptyControlBar();
	serviceDialog.getControlBar().style.height = '30px';

	var serviceForm = serviceDialog.getContent();

	var serviceType = serviceXMLObj.getAttribute('type');

	this.setForm = function(form) {
		serviceForm = form;
	}

	this.createURL = function() {
		var inputs = serviceForm.getElementsByTagName('input');
		var selects = serviceForm.getElementsByTagName('select');
		var url;

		var serviceURL = serviceXMLObj.getElementsByTagName('url')[0];
		if(serviceURL) {
			var servURLValue = serviceURL.firstChild.nodeValue;
			if(servURLValue) { url = servURLValue+'?'; }
		}
		for(var i = 0; i < inputs.length; i++) {
			var subType = new String(inputs[i].getAttribute('subtype'));
			if(subType.match(/user/i)) {
				url += inputs[i].name;
				url += '=';
				url += escape(inputs[i].value);
				url += '&';
			}
		}


		for(var i = 0; i < selects.length; i++) {
			var subType = new String(selects[i].getAttribute('subtype'));
			if(subType.match(/area/i)) {
				url += selects[i].name;
				url += '=';

				var selectedBuffer = '';

				var options = selects[i].getElementsByTagName('option');
				selectedBuffer = options[selects[i].selectedIndex].value;

				var elementString = '';
				logDebugMessage('Service',false,'Buffer: '+selectedBuffer);

				var layerSelector = null;
				var subSelects = selects[i].parentNode.getElementsByTagName('select');
				for(var s = 0; s < subSelects.length && layerSelector == null; s++) {
					var st = new String(subSelects[s].getAttribute('subtype'));
					if(st.match(/layer/i) && subSelects[s].name == selects[i].name) {
						layerSelector = subSelects[s];
					}
				}
				var selectedLayer = 'ANY';
				if(layerSelector != null) {
					options = layerSelector.getElementsByTagName('option');
					selectedLayer = options[layerSelector.selectedIndex].value;
				}
				
				var elements = getSetFromBuffer(selectedBuffer, selectedLayer); 
								
				var uniqueIds = new Array();
				for(var e = 0; e < elements.length; e++) {
					uniqueIds[elements[e].getId()]=0;
				}
				
				for(var uId in uniqueIds) {
					elementString = elementString + uId + ',';
				}
				elmementString = elementString.substring(0,elementString.length-1);
				url += elementString;
				url += '&';

				var layer = elements[0].getParent();
				layerObjs[layer].setParameter('selected', elementString);
				layerObjs[layer].getImageMapMaster(false,false);
			} else if(subType.match(/shape/i)) {
				url += selects[i].name;
				url += '=';
				var selectedBuffer = '';
				var options = selects[i].getElementsByTagName('option');
				selectedBuffer = options[selects[i].selectedIndex].value;
				var buffer = getSelectedBuffers(selectedBuffer)[0];
				logDebugMessage('Service',false,'Selected Shape: '+selectedBuffer);
				url += buffer.toString(',');
			} else if (subType.match(/layer/)) {
				// do nothing.  "layer-selector" type is a place holder in order to select
				// a specific layer to search for a polygon
			} else {
				var options = selects[i].getElementsByTagName('option');
				url += selects[i].name +'='+ options[selects[i].selectedIndex].value;
			}
		}

		return url;
	}

	this.createForm = function() {
		var inputs = serviceXMLObj.getElementsByTagName('input');

		var inputsTable = document.createElement('table');
		var inputsTbody = document.createElement('tbody');
		inputsTable.appendChild(inputsTbody);

		var hiddenInputs = new Array();
		for(var i = 0; i < inputs.length; i++) {
			var newRow = document.createElement('tr');
			var newTitleCell = document.createElement('th');
			var titleContent = inputs[i].getAttribute('title');
			if(!titleContent) {
				titleContent = ' ';
			}
			newTitleCell.appendChild(document.createTextNode(titleContent));
			newRow.appendChild(newTitleCell);
			var newInputCell = document.createElement('td');
			newRow.appendChild(newInputCell);
			if(inputs[i].getAttribute('type').match(/user/i)) {
				var inputObj = document.createElement('input');
				if(inputs[i].getAttribute('value')) {
					inputObj.value = inputs[i].getAttribute('value');
				}

				inputObj.name = inputs[i].getAttribute('name');
				inputObj.setAttribute('subtype', 'user');

				newInputCell.appendChild(inputObj);
				inputsTbody.appendChild(newRow);
			} else if (inputs[i].getAttribute('type').match(/area/i) || inputs[i].getAttribute('type').match(/shape/i)) {	
				var selectObj = document.createElement('select');
				selectObj.name = inputs[i].getAttribute('name');
				selectObj.setAttribute('subtype', 'shape');

				var bType = inputs[i].getAttribute('shape');
				
				var buffers;

				if(!bType || bType == '' || bType.match(/any/i)) {
					buffers = AllBuffers();
				} else {
					buffers = buffersWithType(bType);
				}

				for(var b = 0; b < buffers.length; b++ ) {
					var buff = buffers[b];
					var option = document.createElement('option');
					option.value = buff;
					option.appendChild(document.createTextNode(buff));
					selectObj.appendChild(option);
				}
				newInputCell.appendChild(selectObj);

				// "Areas" select objects, "Shapes" Send Coordinates
				if(inputs[i].getAttribute('type').match(/area/i)) {
					selectObj.setAttribute('subtype', 'area');
					newInputCell.appendChild(document.createElement('br'));

					var layerSelector = document.createElement('select');
					layerSelector.name = inputs[i].getAttribute('name');
					layerSelector.setAttribute('subtype', 'layer-selector');
					
					var layersWithData = getLayersWithData();
					layersWithData[layersWithData.length] = layersWithData[0];
					layersWithData[0] = 'ANY';
					for(var l = 0; l < layersWithData.length; l++) {
						var opt = document.createElement('option');
						opt.value = layersWithData[l];
						opt.appendChild(document.createTextNode(layersWithData[l]));
						layerSelector.appendChild(opt);
					}
					newInputCell.appendChild(layerSelector);
				}
				inputsTbody.appendChild(newRow);
			} else if(inputs[i].getAttribute('type').match(/select/i)) {
				var selectObj = document.createElement('select');
				selectObj.name = inputs[i].getAttribute('name');
				selectObj.setAttribute('subtype', 'select');
				var options = inputs[i].getElementsByTagName('option');
				for(var o = 0; o < options.length; o++ ) {
					var option = document.createElement('option');
					option.value = options[o].getAttribute('value');
					option.appendChild(document.createTextNode(options[o].firstChild.nodeValue));
					selectObj.appendChild(option);
				}
				newInputCell.appendChild(selectObj);
				inputsTbody.appendChild(newRow);

			} else if(inputs[i].getAttribute('type').match(/hidden/i)) {
				var newInput = document.createElement('input');
				newInput.type = 'hidden';
				newInput.name = inputs[i].getAttribute('name');
				newInput.value = inputs[i].getAttribute('value');
				newInput.setAttribute('subtype','user');
				inputsTable.appendChild(newInput);
			} 
		}

		var cancelBtn = document.createElement('input');
		cancelBtn.type = 'button';
		cancelBtn.value = 'Cancel';
		cancelBtn.onclick = serviceDialog.closeDialog;
		cancelBtn.style.position = 'absolute';
		cancelBtn.style.left = '3px';
		cancelBtn.style.top = '3px';
		
		var startBtn = document.createElement('input');
		startBtn.type = 'button';
		startBtn.value = 'Start';
		startBtn.style.position = 'absolute';
		startBtn.style.top = '3px';
		startBtn.style.right = '3px';

		var myself = this;
		startBtn.onclick = function () {
			var url = myself.createURL();
			logDebugMessage('Service',false,'Started Service.');
			logDebugMessage('Service',false,url);
			if(!serviceType || serviceType.match(/default/i)) {
				window.open(url);
			} else if(serviceType.match(/search/i)) {
				myself.getResults();
			}
			cancelBtn.onclick();
		}

		var controls = serviceDialog.getControlBar();
		controls.appendChild(cancelBtn);
		controls.appendChild(startBtn);		
		serviceForm.appendChild(inputsTable);
		return serviceDialog.getDialog();
	}


	this.displayResults = function(resultsXML) {
		var rows = resultsXML.getElementsByTagName('row');

		logDebugMessage('Service',false,serviceTitle+': Got '+rows.length+' Rows!');

		var resultsContainer = document.createElement('div');
		resultsContainer.className = 'ResultsContainer';

		var resultsTable = document.createElement('table');
		var resultsBody = document.createElement('tbody');
		resultsTable.appendChild(resultsBody);

		var header = resultsXML.getElementsByTagName('header')[0];
		if(header) {
			var headerElms = header.getElementsByTagName('col');
			
			var headerRow = document.createElement('tr');
			var headerSpace = document.createElement('td');
			headerSpace.className='RowId';
			headerRow.appendChild(headerSpace);
			for(var i = 0; i < headerElms.length; i++) {
				var val = headerElms[i].getAttribute('value');
				var cell = document.createElement('th');
				cell.appendChild(document.createTextNode(val));
				headerRow.appendChild(cell);
			}
			resultsBody.appendChild(headerRow);
		}
		for(var i = 0; i < rows.length; i++) {
			var resultsRow = document.createElement('tr');

			var rowTitle = rows[i].getAttribute('value');
			if(!rowTitle) {
				rowTitle = i+1;
			}
			var rowId = document.createElement('td');
			rowId.className = 'RowId';
			rowId.appendChild(document.createTextNode(rowTitle));

			resultsRow.appendChild(rowId);

			var cols = rows[i].getElementsByTagName('col');
			for(var c = 0; c < cols.length; c++) {
				var resultsCell = document.createElement('td');
				var cellType = cols[c].getAttribute('type');
				var valueParent = resultsCell;
				if(!cellType) {
					valueParent.appendChild(document.createTextNode(cols[c].getAttribute('value')));
				} else if(cellType.match(/pan/i) || cellType.match(/zoomto/i)) {
					var panLink = document.createElement('a');
					var panX = cols[c].getAttribute('x');
					var panY = cols[c].getAttribute('y');
					var pVal = cols[c].getAttribute('label');
					if(pVal == null) { pVal = 'Point of Interest'; }
					panLink.href = 'javascript:jumpToXY("'+pVal+'",'+panX+','+panY+');';
					panLink.appendChild(document.createTextNode(cols[c].getAttribute('value')));
					valueParent.appendChild(panLink);
				} else if(cellType.match(/link/i)) {
		 			var panLink = document.createElement('a');
					panLink.target = "_blank";
					panLink.href = unescape(cols[c].getAttribute('href'));
					panLink.appendChild(document.createTextNode(cols[c].getAttribute('value')));
					valueParent.appendChild(panLink);
				} else if(cellType.match(/internal/i)) {
					var panLink = document.createElement('a');
					panLink.href = 'javascript:'+cols[c].getAttribute('command');
					panLink.appendChild(document.createTextNode(cols[c].getAttribute('value')));
					valueParent.appendChild(panLink);
				} else if(cellType.match(/image/i)) {
					var w = cols[c].getAttribute('width');
					var h = cols[c].getAttribute('height');
					var src = cols[c].getAttribute('src');
					var href = cols[c].getAttribute('href');

					var newImg = document.createElement('img');
					if(w) { newImg.width = w; }
					if(h) { newImg.height = h; }
					newImg.src = src;
					if(href) {
						var link = document.createElement('a');
						link.href = href;
						link.target = "_blank";
						link.appendChild(newImg);
						valueParent.appendChild(link);
					} else {
						valueParent.appendChild(newImg);
					}
				} else {
					valueParent.appendChild(document.createTextNode(cols[c].getAttribute('value')));
				}
				resultsRow.appendChild(valueParent);
			}
			resultsBody.appendChild(resultsRow);
		}
			
		resultsContainer.appendChild(resultsTable);


		AllResults.resetTabContent(serviceTitle);
		var resultsElm = AllResults.getResultsContent(serviceTitle);
		resultsElm.appendChild(resultsContainer);
		logDebugMessage('Service', true, 'Got Results from: '+serviceTitle);
		
		ResultsWindow.showWindowPane();
	}

	this.getResults = function() {
		var http = getHTTPObject();

		var mySelf = this;

		http.open("GET", mySelf.createURL());
		http.onreadystatechange = function () { 
			if(http.readyState == 4) {
				mySelf.displayResults(http.responseXML);
			}
		};

		http.send(null);
	}

}
