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

/*
 * (c) 2006 City of Saint Paul, by Dan Little
 *
 * This library provides the functionality for the "Add Objects"
 * dialog box.
 */

function AddDialogBox() { /** xmlObj - MapBook to render as a file dialog **/
	var self = this;
	var FilePanes = new Array();
	var DialogDiv;
	var PaneGroup;

	var ActiveSelectionList;

	this.onadd = function() { alert('On Add Callback not Set!'); }


	this.add = function(xmlObj) {
		return addObjectDialog(xmlObj);
	}

	function filePaneWidth() {
		var w = 0;
		for(var i = 0; i < FilePanes.length; i++) {
			w += FilePanes[i].offsetWidth; //clientWidth;
		}
		return w;
	}

	function addFilePane(obj, depth) {
		var newDiv = document.createElement('div');
		newDiv.className = 'FilePane';
		newDiv.appendChild(buildTree(obj,depth));

		var NewPanes = new Array();
		if(FilePanes[depth] != null) {
			for(var d = FilePanes.length; d >= depth; d--) {
				if(FilePanes[d] != null) {
					var parent = FilePanes[d].parentNode;
					parent.removeChild(FilePanes[d]);
				}
			}
		}

		for(var i = 0; i < depth; i++) {
			NewPanes[i] = FilePanes[i];
		}
		FilePanes = NewPanes;
		FilePanes[depth] = newDiv;
		var w = filePaneWidth();
		newDiv.style.left = w + 'px';

		return newDiv;
	}

	function doClose() {
		var p = DialogDiv.parentNode;
			p.removeChild(DialogDiv);			
			resetActives();
	}

	var DialogObject = new Dialog(600,340, 'Add Layer or Tool');

	function addObjectDialog(obj) {
		var dialog = DialogObject.getDialog();
		DialogObject.createEmptyControlBar();

		var Controls = DialogObject.getControlBar();
		var closeButton = document.createElement('input');

		closeButton.type = 'button';
		closeButton.onclick = function() {
			doClose();
		};
		closeButton.value = 'Close';
		closeButton.style.position = 'absolute';
		closeButton.style.bottom = '5px';
		closeButton.style.right = '5px';
		closeButton.style.width = '50px';
		Controls.appendChild(closeButton);

		var openButton = document.createElement('input');
		openButton.type = 'button';
		openButton.value = 'Add';
		openButton.style.position = 'absolute';
		openButton.style.right = '5px';
		openButton.style.bottom = '30px';
		openButton.style.width = '50px';
		openButton.onclick = function () { self.onadd(ActiveElements); doClose(); };

		Controls.appendChild(openButton);

		var openItemsList = document.createElement('input');
		openItemsList.value = '';
		openItemsList.style.position = 'absolute';
		openItemsList.style.bottom = '30px';
		openItemsList.style.width = '340px';
		openItemsList.style.right = '60px';
		Controls.appendChild(openItemsList);

		Controls.style.height='55px';
		ActiveSelectionList = openItemsList;

		var paneGroup = DialogObject.getContent();
//		paneGroup = DialogObject.resetContent();
		
		paneGroup.className = 'FilePaneGroup';
		logDebugMessage('add dialog', false, paneGroup.className);
		var root = addFilePane(obj, 0);	
		paneGroup.appendChild(root);
		PaneGroup = paneGroup;
	
		DialogObject.resetContentHeight();

		DialogDiv = dialog;
		return DialogObject.getDialog();
	}
		
	function getLeaf(obj, depth) {
		var newLi = document.createElement('span');
		var imgIcon = document.createElement('img');
		newLi.onmousedown = clearSelection;
		
		if(obj.tagName == 'group') {
			newLi.onclick = function () {
				if(this.parentNode.className == 'Selected') {
					alert('Add All Children of '+this.parentNode.id);
				}
				PaneGroup.appendChild(addFilePane(obj, depth+1));
				if(filePaneWidth() >= PaneGroup.clientWidth) {		
					PaneGroup.scrollLeft = filePaneWidth()-PaneGroup.clientWidth;
				}
				changeSelected(this.parentNode);
			}

			imgIcon.src = 'folder.gif';
		} else {
			var iconUrl = UNKNOWN_DEFAULT_ICON;
			/* If no custom icon is specified - then use a default one */
			if(obj.getAttribute('icon')) {
				iconUrl = obj.getAttribute('icon');
			} else if(obj.tagName.match(/map/)) {
				iconUrl = MAP_DEFAULT_ICON;
			} else if(obj.tagName.match(/service/)) {
				iconUrl = SERVICE_DEFAULT_ICON;
			} else if(obj.tagName.match(/view/)) {
				iconUrl = VIEW_DEFAULT_ICON;
			}
			imgIcon.src = iconUrl;
			newLi.onclick = function(event) {
				if(window.event) {
					event = window.event;
				}
				if(this.parentNode.className == 'Active') {
					if(ActiveElements.length == 1 && !(event.ctrlKey || event.shiftKey)) {
						self.onadd(ActiveElements);
						doClose();
					} else {
						if(event.ctrlKey) {
							removeFromActives(this.parentNode);		
						} else {
							resetActives();
							ActiveElements[ActiveElements.length] = this.parentNode;
						}
					}
				} else {

					if(event.ctrlKey) {
						clearSelection();
					} else if(event.shiftKey) {
						clearSelection();
						var theParent = this.parentNode.parentNode;
						var divs = theParent.getElementsByTagName('div');
						var startSelecting = false;
						for(var i = 0; i < divs.length; i++) {
							if(divs[i].className == 'Active' || divs[i] == this.parentNode) {
								startSelecting = !startSelecting;
							}
							if(startSelecting && divs[i].className != 'Active') {
								ActiveElements[ActiveElements.length] = divs[i];
							}
						}
					} else {
						resetActives();
					}
					ActiveElements[ActiveElements.length] = this.parentNode;
				}
				renderActives();
			}
		}
		newLi.appendChild(imgIcon);
		var titleText = obj.getAttribute('title');
		//newLi.appendChild(document.createTextNode(titleText));
		newLi.innerHTML = newLi.innerHTML + titleText;
		var wrapper = document.createElement('div');
		wrapper.id = obj.tagName+':'+titleText;
		wrapper.style.position = 'relative';
		wrapper.style.width = '200px';
		wrapper.style.overflow = 'hidden';
		wrapper.style.height = '25px';

		wrapper.onstartselect = clearSelection;
		wrapper.onmousedown = clearSelection;
		wrapper.appendChild(newLi);
	//	newLi.appendChild(document.createElement('br'));
		return wrapper;
	}

	function buildTree(xmlObj, depth) {
		var newUl = document.createElement('span');
		for(var i = 0; i < xmlObj.childNodes.length; i++) {
			if(xmlObj.childNodes[i].tagName != null && xmlObj.childNodes[i].getAttribute('title') != null) {
				newUl.appendChild(getLeaf(xmlObj.childNodes[i], depth));
			}	
		}

		newUl.onstartselect = doNadda;
		newUl.onmousedown = clearSelection;
		return newUl;
	}


	function changeSelected(obj) {
		var parent = obj.parentNode;
		var links = parent.getElementsByTagName('div');
		for(var i = 0; i < links.length; i ++) {
			if(links[i] == obj) {
				links[i].className = 'Selected';
			} else {
				links[i].className = '';
			}
		}
	}

	var ActiveElements = new Array();

	function renderActives() {
		var activeString = new String();
		for(var i = 0; i < ActiveElements.length; i++) {
			ActiveElements[i].className = 'Active';
			activeString = activeString + ActiveElements[i].id +',';
		}
		activeString = activeString.substring(0,activeString.length-1);
		ActiveSelectionList.value = activeString;
	}

	function resetActives() {
		for(var i = 0; i < ActiveElements.length; i++) {
			ActiveElements[i].className = '';
		}
		ActiveElements = new Array();
	}

	function removeFromActives(elm) {
		var newActives = new Array();
		for(var i = 0; i < ActiveElements.length; i++) {
			if(ActiveElements[i] != elm) {
				newActives[newActives.length] = ActiveElements[i];
			} else {
				ActiveElements[i].className = '';
			}
		}
		ActiveElements = newActives;
	}


}
