/**
 * WIYBY Enhancements 2008
 * 
 * WIYBY RELEASE 13.1
 *
 * Author : ESRI(UK) Stuart Mellanby
 * Version:		$Revision: 1.31 $
 * Date : 01/02/2008
 * 
 * Copyright Environment Agency 2008 - not to be distributed
 * or used without explicit permission from the Environment Agency
 *
 *
 * Copyright (c) 2006-2007 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/release-license.txt 
 * for the full text of the license. 
 *
 * 
 * @requires OpenLayers/Control.js
 * @requires OpenLayers/BaseTypes.js
 * @requires OpenLayers/Events.js
 *
 * Class: WiybyQueryControl
 * handles map clicks and query information
 * <WiybyQueryControl> constructor.
 *
 * Inerits from:
 *  - <OpenLayers.Control>
 */
WiybyQueryControl = OpenLayers.Class(OpenLayers.Control, {
   
	/**
     	 * Property: id
     	 * {String} For div.id
     	 */
    	id: "WiybyQueryControl",
	events: null,
	
	processMouseClick: function(evt) {
		//alert("x = " + evt.xy.x + ", y = " + evt.xy.y);
		if (map.getWiybyServerSideZoom() >= maxClickQueryScale) {
		
			if (topicName == "floodmap") {

				var lonLatPixel = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(evt.xy.x,evt.xy.y));
			
				// Layer groups added for layer toggling
				// Note that for all spatial query actions the queryWindowDiameter/Width/Height are now overridden on the server using layer configured values 
				var requestUrl = "http://" + sn + ":" + sp + "/" + wa + "/wiybyController?ep=mcquery&scale=" + map.getWiybyServerSideZoom(); 
				requestUrl += "&topic=" + topicName + "&queryWindowDiameter=" + queryWindowDiameter + "&lang=" + dojo.byId("lang").value + "&layerGroups=" + selectedLayerGroupsString;
				requestUrl += "&x=" + lonLatPixel.lon + "&y=" + lonLatPixel.lat;
				
				dojo.xhrGet({
					     url: requestUrl,
					     handleAs: "json",
					     load: this.nafraQueryCallback,
					     error: this.queryError,
					     timeout: 10000
					     });
		       
		       		var pixel = new OpenLayers.Pixel(evt.xy.x,evt.xy.y);
		       		lonLat = this.map.getLonLatFromPixel(pixel); 	
			}			
			else {				
				var lonLatPixel = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(evt.xy.x,evt.xy.y));
			
			    	// Layer groups added for layer toggling
				var requestUrl = "http://" + sn + ":" + sp + "/" + wa + "/wiybyController?ep=mcquery&scale=" + map.getWiybyServerSideZoom(); 
				requestUrl += "&topic=" + topicName + "&queryWindowDiameter=" + queryWindowDiameter + "&lang=" + dojo.byId("lang").value + "&layerGroups=" + selectedLayerGroupsString;
				requestUrl += "&x=" + lonLatPixel.lon + "&y=" + lonLatPixel.lat;
			
				dojo.xhrGet({
					     url: requestUrl,
					     handleAs: "json",
				             load: this.queryCallback,
				             error: this.queryError,
			        	     timeout: 10000
		        		     });
	       
		       		var pixel = new OpenLayers.Pixel(evt.xy.x,evt.xy.y);
		       		lonLat = this.map.getLonLatFromPixel(pixel);
		       
		       		var htmlString = "";
		       		htmlString += "<div class='map-click-popup'>";
		       		htmlString += "  <h2>Searching map</h2>";
		       		htmlString += "  <p class='image'><img src='images/loading.gif'/></p>";
		       		htmlString += "</div>";

				popup = new OpenLayers.Popup("mapPopup", lonLat, new OpenLayers.Size(200,120), htmlString, true);
				popup.setBorder("1px solid #669933");
	        		map.addPopup(popup, true); 
			}
       		}
       		else {

			var zoomDivSlide = dojo.byId("needToZoomInToQuery");
			zoomDivSlide.innerHTML = "<span class='greyBoldText'>Zoom in to query map</span>";
			zoomDivSlide.style.height = "30px";
			zoomDivSlide.style.lineHeight = "30px";
			zoomDivSlide.style.borderWidth = "1px"; 
			zoomDivSlide.style.borderStyle = "solid";
			zoomDivSlide.style.borderColor = "#628B1A";
			zoomDivSlide.style.backgroundColor = "#FFFFFF";

			dojo.fx.wipeIn({
					node: "needToZoomInToQuery", 
					duration: 1000,
					onEnd: function(){
			   				  zoomDivSlide.style.borderWidth = "0px"; 
							  zoomDivSlide.style.lineHeight = "0px";
							  zoomDivSlide.style.height = "0px";		
							  }
					}).play();
       		}
	},
	
	nafraQueryCallback: function(data, ioArgs) {
	
		var baseURI = "http://"+ sn + ":" + sp + "/" + wa + "/";
		baseURI += "wiybyController?" + "ep=query" + "&floodrisk=" + data.nafraValue + "&lang=" + data.lang + "&topic=" + data.topic + "&floodX=" + data.floodX + "&floodY=" + data.floodY;
		window.location = baseURI;
	
	},
	
	queryCallback: function(data,ioArgs) {
	
		var baseURI = "http://"+ sn + ":" + sp + "/" + wa + "/";

		var htmlString = "";
   		htmlString += "<div class='map-click-popup'>";
   		htmlString += "  <h2>Results for this location:</h2>";
   			
   		if (data.mapClickQueryResults.length == 1) {

			//WIYBY 12.1 CPH - changed to scaleStep in url
			window.location = baseURI + "wiybyController?latest=true&topic="+ data.topic + "&ep=query&lang="+ data.lang +"&x="+ data.X + "&y="+ data.Y + "&scale=" + data.scaleStep + "&layerGroups=" + data.mapClickQueryResults[0].layerId + "&queryWindowWidth=" + queryWindowDiameter + "&queryWindowHeight=" + queryWindowDiameter;
   		}	
        	else if ( data.mapClickQueryResults != null ) {
   			
   			if (data.mapClickQueryResults.length > 1) {
	   			
	   			for ( var i=0; i < data.mapClickQueryResults.length;i++ ) {

		   			//alert(data.mapClickQueryResults[i].layerId);
		   			//WIYBY 12.1 CPH - changed to scaleStep in url
	   				var genericURL = "wiybyController?latest=true&topic="+ data.topic + "&ep=query&lang="+ data.lang +"&x="+ data.X + "&y="+ data.Y + "&scale=" + data.scaleStep + "&layerGroups=" + data.mapClickQueryResults[i].layerId + "&queryWindowWidth=" + queryWindowDiameter + "&queryWindowHeight=" + queryWindowDiameter;
	
	   				if (data.mapClickQueryResults[i].numberResultsFound == '1') {
	   					//alert(data.mapClickQueryResults[i].layerName + ' ' + data.mapClickQueryResults[i].numberResultsFound);
	   					htmlString += "<p><a href='" + baseURI + genericURL + "'>" + data.mapClickQueryResults[i].layerName + "&nbsp;(" + data.mapClickQueryResults[i].numberResultsFound + " result)" + "</a></p>";
	   				}
	   				else {
						//alert(data.mapClickQueryResults[i].layerName + ' ' + data.mapClickQueryResults[i].numberResultsFound);
						htmlString += "<p><a href='" + baseURI + genericURL + "'>" + data.mapClickQueryResults[i].layerName + "&nbsp;(" + data.mapClickQueryResults[i].numberResultsFound + " results)" + "</a></p>";     						
					}		
	   			}
   			}
   			else {
	   			htmlString += "<p class='results'>There are no results for your mouse click</p>";
	   		}
	   		

	   		htmlString += "</div>";
	   			
	   		//only do if we have results
	        	popup = new OpenLayers.Popup(	"mapPopup", lonLat, new OpenLayers.Size(200,200), htmlString, true);
			popup.setBorder("1px solid #669933");
	        	map.addPopup(popup, true);
	        
	                    
            		//WIYBY 12.0 CPH
            		//resize the popup div to be the same size as the contained divs
            		popupContentDiv = popup.contentDiv;        
	        	contentHeight = 0;
	        
		    	for (i=0; i<popupContentDiv.childNodes.length; i++) {
		       		contentHeight = contentHeight + popupContentDiv.childNodes[i].offsetHeight;
		    	}
	        
	        	//alert(contentHeight);
	        	popupContentDiv.style.height = contentHeight + "px";
	        	popup.div.style.height = contentHeight + "px";

   		}     
	},  
            
     	queryError: function(data, ioArgs) {
        	alert('Error when retrieving data from the server.');
       	},
	   
    	CLASS_NAME: 'WiybyQueryControl'
});


