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

/* 
 *
 * This is the "Parent" function for managing popups.
 * Requires: polygon.js , Popup.js
 *
 */

function Popups(Parent) {
	var allPopups = new Array();
	
	function removePopupsMaster(active, all) {
		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].showClose == active || all) {
				allPopups[i].removePopup();
			}
		}
	}


	function ManagedPoint(x,y) {
		var point = new Point(x,y);
		var popups = new Array();
	
		this.rendered = false;
	
		this.addPopup = function(popup) {
			popups[popups.length] = popup;
		}

		this.removePopupsMaster = function(active, all) {
			if(this.rendered) { // Don't bother with the loop if it ain't rendered!
				for(var i = 0; i < popups.length; i++) {
					if(popups[i].showClose == active || all) {
						popups[i].removePopup();
					}
				}
			}
		}

		this.removePopups = function() {
			this.removePopupsMaster(false,true);
		}

		this.removeActivePopups = function() {
			this.removePopupsMaster(true, false);
		}
	
		this.removeInactivePopups = function() {
			this.removePopupsMaster(false, false);
		}

		this.getPoint = function() {
			return point;
		}

		this.countPopups = function() {
			return popups.length;
		}
	
		this.getPopups = function() {
			return popups;
		}
	}

	var myPopups = new Array();
	
	this.addPopup = function(shape,popup) {
		popup.Shape = shape;
		allPopups[allPopups.length] = popup;

		popup.onunload = function () {
			allPopups[allPopups.length-1].rendered = false;
		}
		popup.ondrag = function () {
			this.showClose = true;
			this.renderKillBox();
			for(var i = 0; i < allPopups.length; i++) {
				if(allPopups[i].showClose == false && allPopups[i].isRendered()) {
					allPopups[i].removePopup();
				}
			}
		}
	}

	this.findAllPopupsInClass = function(layerClass) {
		var arr = new Array();
		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].getClass() == layerClass) {
				arr[arr.length] = allPopups[i];
			}
		}
		return arr;
	}

	this.findAllPopupsInPolygon = function(polygon,searchArr) {
		var retArr = new Array(); // Will hold the list of popups that return valid;
		var c = 0;
			for(var i = 0; i < searchArr.length; i++) {
			if(!searchArr[i].found && polygon.isMember(searchArr[i].GroundShape)) {
				retArr[retArr.length] = searchArr[i];
				searchArr[i].found = true;
				c++;
			}
		}
		logDebugMessage('Find in Poly', false, 'Found '+c+' Popups.');
		return retArr;
	}


	this.findAllPopups = function(polygons, layerClass) {
		if(!polygons.length) {
			var poly  = polygons;
			polygons = new Array();
			polygons[0] = poly;
		}

		var domainMinX = 1000000, domainMaxX = -1000000;
		var domainMinY = 1000000, domainMaxY = -1000000;

		// Find the Search Domain
		var boxTest = new Array();
		for(var i = 0; i < polygons.length; i++) {
			if(domainMinX > polygons[i].minX()) {
				domainMinX = polygons[i].minX();
			}
			if(domainMaxX < polygons[i].maxX()) {
				domainMaxX = polygons[i].maxX();
			}
			if(domainMinY > polygons[i].minY()) {
				domainMinY = polygons[i].minY();
			}
			if(domainMaxY < polygons[i].maxY()) {
				domainMaxY = polygons[i].maxY();
			}
			boxTest[i] = new Array();
		}
		logDebugMessage('Find All',false,'Domain: '+domainMinX+' - '+domainMaxX);


		// Find Elements Inside of the Domain to search
		// Also, Eliminate those not in the correct class
		var searchLength;
		for(var i = 0; i < allPopups.length; i++) {
			var shp = shapeToGISShape(allPopups[i].Shape);
			allPopups[i].GroundShape = shp;
			if(layerClass == 'ANY' || (layerClass != null && allPopups[i].getParent() == layerClass)) {
				for(var p = 0; p < polygons.length; p++) {
					if(shp.maxX() >= polygons[p].minX() && shp.minX() <= polygons[p].maxX() && shp.maxY() >= polygons[p].minY() && shp.minY() <= polygons[p].maxY()) {
						boxTest[p][boxTest[p].length] = allPopups[i];
						boxTest[p][boxTest[p].length-1].found = false;
						searchLength++;
					}
				}
			}
		}

		logDebugMessage('Find All', false, 'Number found to search '+searchLength);
		var retArr = new Array();

		for(var i = 0; i < polygons.length; i++) {
			var indivRet = this.findAllPopupsInPolygon(polygons[i],boxTest[i]);
			for(var x = 0; x < indivRet.length; x++) {
				retArr[retArr.length] = indivRet[x];
			}
		}
		logDebugMessage('Find All', false, 'Total Popups Found: '+retArr.length);
		return retArr;
	}
	
	function createFrame(popups) {
		var frameDiv = document.createElement('div');
		frameDiv.className = 'MultiplePopups';
		frameDiv.appendChild(document.createTextNode('Multiple Objects'));
		var y = 20;
		for(var i = 0; i < popups.length; i++) {
			frameDiv.appendChild(popups[i].getPopup(0,y));
			y+=y;
		}
		return frameDiv;
	}

	this.clearPopups = function() {
		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].isRendered()){ 
				allPopups[i].removePopup();
			}
		}
		delete allPopups;
		allPopups = new Array();
		logDebugMessage('Popups', false, 'Cleared All Popups.');
	}

	this.removePopup = function(popup) {
		if(typeof popup == "number") {
			delete myPopups[popup];
		} else {
			for(var i = 0; i < myPopups.length; i++) {
				if(myPopups[i] == popup) {
					delete myPopups[i];
					break;
				}
			}
		}
	}

	function findManagedPoint(x,y) {
		var newPoint = new Point(x,y);
		for(var i = 0; i < myPopups.length; i++) {
			var testline = new LineSegment(newPoint, myPopups[i].getPoint());
			if(testline.getLength() < 7) {
				return myPopups[i];
			} else {
				myPopups[i].removeInactivePopups();
			}

		}
		return null;
	}

	this.removeVisiblePopups = function () {
		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].isRendered() && allPopups[i].showClose == false) {
				allPopups[i].removePopup();
			}
		}
	}
	
	this.getPopupsUsingShape = function(event) {
		if(window.event) { event = window.event; }
		var myPoint = new Point(event.clientX+1, event.clientY);

		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].showClose == false && allPopups[i].isRendered()) {
				allPopups[i].removePopup();
			}
		}

		
		var retArr = new Array();
		for(var i = 0; i < allPopups.length; i++) {
			if(allPopups[i].Shape.isMember(myPoint)) {
				retArr[retArr.length] = allPopups[i];
			}
		}

		var shiftY = 0;
		for(var i = 0; i < retArr.length; i++) {
			if(!retArr[i].isRendered()) {
				retArr[i].showClose = false;
				var renderedPopup = retArr[i].getPopup(event.clientX, event.clientY+shiftY,new Point(event.clientX, event.clientY));
				Parent.appendChild(renderedPopup);
				shiftY+=20;
			}
		}
	/*	if(retArr.length == 1) {
			retArr[0].PopupObj.style.left = (event.clientX+1)+'px';
			retArr[0].PopupObj.style.top = event.clientY+'px';
		}*/
	}
	
	this.getPopups = function(event) {
		if(window.event) { event = window.event; }
		var x = event.clientX;
		var y = event.clientY;
		var managedPoint = findManagedPoint(x,y);
		if(managedPoint != null) {
			if(!managedPoint.rendered) {
				managedPoint.rendered = true;
				var popupObjs = managedPoint.getPopups();
				var closeBox = true;
				if(popupObjs.length > 1) {
					closeBox = false;
				}
				var shiftY = 0;
				for(var i = 0; i < popupObjs.length; i++) {
					if(!popupObjs[i].isRendered()) {
						popupObjs[i].showClose = false;
						var renderedPopup = popupObjs[i].getPopup(x,y+shiftY);
						Parent.appendChild(renderedPopup);	
						shiftY+=20;
					}
				}
			}
		}		
	}

	this.countManagedPoints = function() {
		return myPopups.length;
	}
}

