 /*
	Copyright (c) 2011 by Nop.
	Copying/reuse require explicit approval by the author.
 */

 // custom version of protocol that adds zoom parameter
 POIRequestProtocol = OpenLayers.Class(OpenLayers.Protocol.HTTP, {

    read: function(options) {
	        OpenLayers.Protocol.prototype.read.apply(this, arguments);
	        options = OpenLayers.Util.applyDefaults(options, this.options);
	        options.params = OpenLayers.Util.applyDefaults(
	            options.params, this.options.params);
			// add zoom level for server script
	        options.params = OpenLayers.Util.applyDefaults(
	            { zoom: map.getZoom() }, this.options.params );
	        if(options.filter) {
	            options.params = this.filterToParams(
	                options.filter, options.params);
	        }
	        var readWithPOST = (options.readWithPOST !== undefined) ?
	                           options.readWithPOST : this.readWithPOST;
	        var resp = new OpenLayers.Protocol.Response({requestType: "read"});
	        if(readWithPOST) {
	            resp.priv = OpenLayers.Request.POST({
	                url: options.url,
	                callback: this.createCallback(this.handleRead, resp, options),
	                data: OpenLayers.Util.getParameterString(options.params),
	                headers: {
	                    "Content-Type": "application/x-www-form-urlencoded"
	                }
	            });
	        } else {
	            resp.priv = OpenLayers.Request.GET({
	                url: options.url,
	                callback: this.createCallback(this.handleRead, resp, options),
	                params: options.params,
	                headers: options.headers
	            });
	        }
	        return resp;
	    },
		
	CLASS_NAME: "POIRequestProtocol"
});
 
		function showSearch()
		{
				hideLayer( "search.result" );
				showLayer( "searchPopup" );
				enableKeyboard( false );
		}


		function startSearch()
		{
			var url = "http://" + window.location.host + '/php/nominatim.php?place=' 
						+ document.getElementById('search.place').value;
			//alert(url);
			// search terms
			var txt = document.getElementById('search.street').value;
			if( txt != null && txt.length > 0 ) 
				url += "&street=" + txt;
			
			// search area
			/*if( document.getElementById('search.onmap').checked )
			{
				var area = map.getExtent();
				url += "&box=" + area.toBBOX();
			}*/
			
			// execute
			var fr = document.getElementById('search.result');
			fr.style.display = "block";
			fr.contentDocument.close();
			fr.contentDocument.open();
			fr.contentDocument.write( "Suche läuft...");
			fr.contentDocument.location = url;
		
		}
		
		function showResult( lon, lat, zoom, name )
		{
            var lonLat = new OpenLayers.LonLat(lon, lat).transform(
			new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());

			// Make coordinates visible as POI for external use
			//document.getElementById('search.street').value = parseInt(lonLat.lat) + "\t" + parseInt(lonLat.lon) + "\t" + name + "\tstatic/info_back.png\t24,24";
			
            //map.panTo(lonLat );
            //map.zoomTo ( zoom );
			map.setCenter( lonLat, zoom );
		}

		function showResultDirect( lon, lat, zoom )
		{
            var lonLat = new OpenLayers.LonLat(lon, lat);
			map.setCenter( lonLat, zoom );
		}

	// route list	
		
		var routeListType = 0;
		var routeListEndType = 0;
		
		function showList( type, endType )
		{
				routeListType = type;
				routeListEndType = endType;
				
				e = document.getElementById('route.subtitle');
				switch( type )
				{
					case 1:
						e.firstChild.nodeValue = "Wanderwege";
						break;
					case 2:
						e.firstChild.nodeValue = "Reitrouten";
						break;
					case 10:
						e.firstChild.nodeValue = "Wanderreitstationen";
						break;
					case 11:
						e.firstChild.nodeValue = "Gaststätten für Reiter";
						break;
					case 12:
						e.firstChild.nodeValue = "Reitbetriebe";
						break;
					case 20:
						e.firstChild.nodeValue = "Gaststätten";
						break;
					case 25:
						e.firstChild.nodeValue = "Berghütten";
						break;
					case 30:
						e.firstChild.nodeValue = "Burgen und Ruinen";
						break;
				}
				showLayer( "routeListPopup" );
				// search immediately
				updateRouteList();
		}
		
		function hideList()
		{
			hideLayer('routeListPopup');
		}

		function updateRouteList()
		{
			if( !isVisible( 'routeListPopup' ) )
				return;

		
//			var url = window.location.protocol + "//" + window.location.host + '/static/routelist.php?bbox=' 
			if( routeListType >= 10 )
				var url = "http://www.wanderreitkarte.de/php/poilist.php?bbox="
			else
				var url = "http://www.wanderreitkarte.de/php/routelist.php?bbox=";
				
			url += map.layers[0].getExtent().toBBOX() + "&dir=" + routeListType;
			
			if( routeListEndType > 0 )
				url += "&dirTo=" + routeListEndType;
			//alert(url);
			
			// execute
			updateFrame( 'route.result', url );
		}

		function updateFrame( target, url )
		{
			var fr = document.getElementById( target );
			fr.style.display = "block";
			fr.contentDocument.close();
			fr.contentDocument.open();
			fr.contentDocument.write( "Daten werden geladen...");
			fr.contentDocument.location = url;
		}
		
		function showRouteInfo( routeID )
		{
			// update info
			var url = "http://www.wanderreitkarte.de/php/routeinfo.php?osmid=" + routeID;

			// use open routelist if present
			/*if( isVisible( 'routeListPopup' ) )
			{
				updateFrame( 'route.result', url );
			}
			else
			{*/
				updateFrame( 'route_info_target', url );

				showLayer( 'routeInfo' );
			//}
		}
		
		function showPOIInfo( routeID )
		{
			// update info
			var url = "http://www.wanderreitkarte.de/php/poiinfo.php?osmid=" + routeID;

			// use open routelist if present
			// if( isVisible( 'routeListPopup' ) )
			// {
				// updateFrame( 'route.result', url );
			// }
			// else
			// {
				updateFrame( 'route_info_target', url );

				showLayer( 'routeInfo' );
			// }
		}

		function featureOver(feature) {
            showTooltip(feature.attributes.title, mouseX, mouseY);
        }

        function showTooltip(ttText, x, y) {
            var o = document.getElementById('tooltip');
            o.innerHTML = ttText;
            y = y - 16;
            x = x + 12;
		
            o.style.left = x + 'px';
            o.style.top = y + 'px';
            o.style.visibility = 'visible';
        }
        function hideTooltip() {
            document.getElementById('tooltip').style.visibility = 'hidden';
        }

        /*    function onPopupClose(evt) {
                // 'this' is the popup.
                selectControl.unselect(this.feature);
            }*/
			
		var currentRouteID = 0;	
			
		function onFeatureSelect(evt) {
			feature = evt.feature;
			/*feature.layer.drawFeature( feature, { 
				externalGraphic:"static/info_finder.png", 
				graphicHeight: 32, graphicWidth: 32, 
				graphicXOffset:-16, graphicYOffset: -16 } );*/
			currentRouteID = feature.attributes.osmid;
			if( feature.attributes.type == 0 )
				showRouteInfo( currentRouteID );
			else
				showPOIInfo( currentRouteID );
		}
		function onFeatureUnselect(evt) {
                feature = evt.feature;
			//feature.layer.drawFeature( feature, feature.style );
					hideLayer('routeInfo');
		}

	var highlightedFeature = null;
		
	function highlightFeature( osmid )
	{
		if( highlightedFeature )
			highlightOff();
			
		var layer = map.getLayersByName( "POIs" )[0];
		var featureList = layer.features;
		for( i=0; i<featureList.length; i++ )
		{
			if( featureList[i].attributes.osmid == osmid )
			{
				highlightedFeature = featureList[i];
				
				layer.drawFeature( highlightedFeature, { 
					externalGraphic:"static/info_finder.png", 
					graphicHeight: 32, graphicWidth: 32, 
					graphicXOffset:-16, graphicYOffset: -16 } );
				break;
			}
		}
	}

	function highlightOff( )
	{
		if( !highlightedFeature )
			return;
			
		if( highlightedFeature.layer )
			highlightedFeature.layer.drawFeature( highlightedFeature, highlightedFeature.style );
		highlightedFeature = null;
	}
		
	// track mouse position for popups		
			
		var mouseX = 0;
		var mouseY = 0;

	function getMouseXY(e) {
		tempX = e.pageX;
		tempY = e.pageY;
	    
	  // catch possible negative values in NS4
	  if (tempX < 0){tempX = 0;}
	  if (tempY < 0){tempY = 0;}  
	  // show the position values in the form named Show
	  // in the text fields named MouseX and MouseY
	  mouseX = tempX;
	  mouseY = tempY;
	  return true;
	}

	document.captureEvents(Event.MOUSEMOVE);
	document.onmousemove = getMouseXY;


