/**
 * @author Mapsolute GmbH
 */


/**
 * Definition of Namespace: M24
 */
var M24 = function (){};

// global vars in namespace
M24.localConn = null;
M24.remoteConn = null;
M24.map = null;
M24.mapClient = null;
M24.DEBUG = false;
M24.mapInited = false;
M24.STATIC_MAP_PANNING = true;

/**
 * Initialization of the API
 * @param {Object} _params
 * 		- MapType 			- Static, Applet, Auto
 * 		- StaticMapPanning 	- Defines if the map can be panned or not (value can be true or false).
 * 							  This will only work for the static map, not for the applet.
 * 		               		  Default value if not defined is true.
 * 		- every parameter allowed for M24.startMap (these will be passed on)
 */
M24.init = function(_params)
{
	var api_ready = false;
	var dom_ready = false;

	var apiReady = function ()
	{
		// setting API-ready-state
		api_ready = true;
		allReady();
	}

	var domReady = function ()
	{
		// setting DOM-ready-state
		dom_ready = true;
		allReady();
	}

	var allReady = function ()
	{
		// check DOM-ready- and API-ready-state
		if(api_ready === true && dom_ready === true)
		{
			// proceed with configuration and display of the map
			M24.startMap(_params);
		}
	}

	// load the API-packages
	if (_params.v)
	{
		Map24.loadApi(["core_api", "wrapper_api"], apiReady, _params.v);
	}
	else
	{
		Map24.loadApi(["core_api", "wrapper_api"], apiReady);
	}

	// this is checking the "document.ready"-state
	(function(i) {var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st =
	setTimeout;if(/webkit/i.test(u)){st(function(){var dr=document.readyState;
	if(dr=="loaded"||dr=="complete"){i()}else{st(arguments.callee,10);}},10);}
	else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){
	document.addEventListener("DOMContentLoaded",i,false); } else if(e){     (
	function(){var t=document.createElement('doc:rdy');try{t.doScroll('left');
	i();t=null;}catch(e){st(arguments.callee,0);}})();}else{window.onload=i;}})(domReady);
}



/**
 * Main function that initializes the MapClient, the Map-navigation-bar and the Geocoder-form
 * @param {Object} _params
 * 		- NodeName			- ID of DIV-element the map should be drawn into
 * 		- MapType 			- Static, Applet, Auto
 * 		- StaticMapPanning 	- Defines if the map can be panned or not (value can be true or false).
 * 							  This will only work for the static map, not for the applet.
 * 		               		  Default value if not defined is true.
 * 		- MapView 			- Hashtable with:
 * 								- Longitude
 * 								- Latitude
 * 								- MinimumWidth
 * 		- DisplayControls	- Defines if the tools below the map should be displayed or not (value can be true or false).
 * 							  Default value if not defined is true.
 * 		- HelpUrl 			- URL that should be called when clicking "Hilfe zur Kartensuche"
 */
M24.startMap = function (_params)
{
	if (_params.DEBUG === true){M24.DEBUG = true;}if(M24.DEBUG){Map24.Debug.enable(true,Map24.E_ALL);}else{Map24.Debug.enable(false);}

	// check if parameter for disabling the map-panning was given
	if (_params.StaticMapPanning === false)
	{
		M24.STATIC_MAP_PANNING = false;
	}



	/**
	 * Generate HTML for map-display
	 * including Map-Toolbar, Geocoding-Form and Map-Canvas
	 */

	var mapCanvas = document.getElementById(_params.NodeName);
	var totalWidth = mapCanvas.clientWidth;
	var totalHeight = mapCanvas.clientHeight;
	var controlHeight = 64;
	var controlDisplay = "block";

	// check if the tools (toolbar, geocoding, help-link) should be displayed or not
	if( (_params.DisplayControls == undefined) || (_params.DisplayControls === true) )
	{
		// ...
	}
	else if (_params.DisplayControls === false)
	{
		controlHeight = 24;
		controlDisplay = "none";
	}

	var mapHeight = totalHeight - controlHeight;
	var mapInnerHeight = mapHeight + 21;

	var html = '<div id="m24_maparea_container" style="width: 100%; height: '+mapHeight+'px; overflow: hidden;">\
				<div id="m24_maparea" style="width: 100%; height: '+mapInnerHeight+'px;"></div>\
			</div>\
			\
			<div id="m24_controls" style="display: '+controlDisplay+'; width: '+(totalWidth - 10)+'px; height: 30px; padding: 5px; background-color: #ecf0f3; overflow: hidden;">\
				<div id="m24_toolbar" style="width: 250px; height: 30px;"></div>\
				<div id="m24_geocode" style="position: relative; left: 275px; top: -30px; height: 30px;">\
					<form id="m24_geocode_form" action="#">\
						<input type="hidden" id="m24_geocode_address" style="width: 146px; height: 16px; offset: 0px; margin: 3px; padding: 2px 5px 2px 5px; font-weight: bold;" />&nbsp;\
						<input type="hidden" id="m24_geocode_submit" value="suchen" style="margin: 3px; padding: 2px 10px 2px 10px; overflow: visible; background-color: #014991; color: #fff; border-width: 0px; font-weight: bold;" />\
					</form>\
				</div>\
				<div id="m24_help" style="position: relative; left: 605px; top: -60px; height: 20px; padding-top: 9px; font-size: 11px;">\
					<a id="m24_help_link" href="#" target="_blank" style="color: #000; font-weight: bold; text-decoration: none;" alt="Hilfe zur Kartensuche" title="Hilfe zur Kartensuche"><img  style="margin-bottom: -2px; border-width: 0px;" src="'+M24.Helper.getImageUrl("arrow.gif")+'" />&nbsp;Hilfe zur Kartensuche</a>\
				</div>\
			</div>\
			\
			<div style="width: '+(totalWidth - 10)+'px; margin-top: 0px; padding: 4px 5px 6px 5px; background-color: #ecf0f3;  font-family: Arial; font-size: 9px; color: #000; overflow:hidden;">\
				Map24 Copyright &copy; 2010, NAVTEQ (DE) GmbH.\
				<a style="color: #000; text-decoration: none;" href="http://www.map24.com/eula" rel="@_blank" title="Link &ouml;ffnet in neuem Fenster" target="_blank">Nutzungsbedingungen der Map24-Anwendung</a>.\
			</div>\
	';

	document.getElementById(_params.NodeName).innerHTML = html;

	// check if a URL for the Help-Link was given
	if(!_params.HelpUrl)
	{
		// if not, hide the DIV
		document.getElementById("m24_help").style.display = "none";
	}
	else
	{
		// if so, set it for the anchor-tag
		document.getElementById("m24_help_link").href = _params.HelpUrl;
	}

	document.getElementById("m24_geocode_form").onsubmit= function (){
		M24.Geocoder.geocodeAddress();
		return false;
	}
	document.getElementById("m24_geocode_submit").onclick= function (){
		M24.Geocoder.geocodeAddress();
	}




	/**
	 * Initialize main API-objects and map
	 */

	// create Map-Object
	M24.map = new Map24.Map();

	// if static map should not be panable.
	// this has to be done right after the creation of the map-object
	if (M24.STATIC_MAP_PANNING === false)
	{
		// [API HACK]
		M24.map.removeListener("Map24.Event.MapClick", [M24.map, M24.map._defaultMapClickHandler]);
		M24.map._blockMapClickHandler = function(e){};
		M24.map.addListener("Map24.Event.MapClick", [M24.map, M24.map._blockMapClickHandler]);
	}

	M24.map.onMapViewChanged = function (e)
	{
		if(M24.mapInited===false)
		{
			M24.mapInited=true;
			return;
		}

		// Check if the mapview has moved beyond NRW-bounds and if so, set it back into bounds

		M24.d(e,"CHECK IF INSIDE OF NRW");
		var current_view = M24.getCurrentMapView();
		M24.d(current_view,"CURRENT VIEW");

		var out_of_bounds = false;
		var bounds = {
			TopLeft: {
				Longitude: 344,
				Latitude: 3170
			},
			LowerRight: {
				Longitude: 577,
				Latitude: 3010
			},
			Width: 400
		};
		var view = [];
		var width = null;

		if(current_view.TopLeft.Longitude > bounds.LowerRight.Longitude)
		{
			M24.d(1);
			view[0] = new Map24.WebServices.Coordinate({
				Longitude: (bounds.LowerRight.Longitude - 1),
				Latitude: current_view.TopLeft.Latitude
			});
			view[1] = new Map24.WebServices.Coordinate({
				Longitude: current_view.LowerRight.Longitude - (current_view.TopLeft.Longitude - (bounds.LowerRight.Longitude - 1) ),
				Latitude: current_view.LowerRight.Latitude
			});

			out_of_bounds = true;
		}
		else if(current_view.TopLeft.Latitude < 3010)
		{
			M24.d(2);
			view[0] = new Map24.WebServices.Coordinate({
				Longitude: current_view.TopLeft.Longitude,
				Latitude: (3010 + 1)
			});
			view[1] = new Map24.WebServices.Coordinate({
				Longitude: current_view.LowerRight.Longitude,
				Latitude: current_view.LowerRight.Latitude - (current_view.TopLeft.Latitude - (3010 + 1) )
			});

			out_of_bounds = true;
		}
		else if(current_view.LowerRight.Longitude < bounds.TopLeft.Longitude)
		{
			M24.d(3);
			view[0] = new Map24.WebServices.Coordinate({
				Longitude: (bounds.TopLeft.Longitude + 1),
				Latitude: current_view.LowerRight.Latitude
			});
			view[1] = new Map24.WebServices.Coordinate({
				Longitude: current_view.TopLeft.Longitude - (current_view.LowerRight.Longitude - (bounds.TopLeft.Longitude + 1) ),
				Latitude: current_view.TopLeft.Latitude
			});

			out_of_bounds = true;
		}
		else if(current_view.LowerRight.Latitude > 3170)
		{
			M24.d(4);
			view[0] = new Map24.WebServices.Coordinate({
				Longitude: current_view.LowerRight.Longitude,
				Latitude: (3170 - 1)
			});
			view[1] = new Map24.WebServices.Coordinate({
				Longitude: current_view.TopLeft.Longitude,
				Latitude: current_view.TopLeft.Latitude - (current_view.LowerRight.Latitude - (3170 - 1) )
			});

			out_of_bounds = true;
		}

		if (current_view.Width > bounds.Width)
		{
			view[0] = new Map24.WebServices.Coordinate({
				Longitude: (bounds.TopLeft.Longitude + 2),
				Latitude: (bounds.TopLeft.Latitude - 2)
			});
			view[1] = new Map24.WebServices.Coordinate({
				Longitude: (bounds.LowerRight.Longitude - 2),
				Latitude: (bounds.LowerRight.Latitude + 2)
			});
			out_of_bounds = true;
		}


		if(out_of_bounds === true)
		{
			M24.d(6);
			M24.d(view,"Correct Bounds");
			// set view back into bounds
			var params = {};
			if(view.length>0)
			{
				params.Coordinates = view;
			}

			M24.Mrc.setMapView(params);
			M24.Mrc.execute();
		}
	}

	// define a bounding box
	// map can not be navigated beyond these coordinates
	// works from API-version 2.1.1547
	M24.map.Session.MapClippingRect = new Map24.Rectangle(
		new Map24.Coordinate(289, 3187),
		new Map24.Coordinate(632, 2981)
	);

	// open connections
	M24.localConn = M24.map.Local.openConnection();
	M24.remoteConn = M24.map.WebServices.openConnection();

	// disable POI-layers
	// this will be send via remote-connection because of performance-reasons (otherwise the map-tiles for the static map would be catched twice just because of this command)
	M24.Mrc.controlLayer({
		Control: "DISABLE",
		LayerIDs: [
			//Kreise
			"130",
			//ExitNumbers
			"3052",
			//Intersections
			"3050",
			//POIs...
			"3001","3002","3003","3004","3005","3006","3007","3008","3009","3010","3011","3012","3013","3014"
		],
		Map24Layers: true
	});
	M24.Mrc.execute({ConnectionType: "remote"});

	// set start-view
	if(_params.MapView)
	{
		// set view to user-specified area
		var mapView = _params.MapView;
	}
	else
	{
		// set view to the middle of NRW
		var mapView = {
			Coordinates : [
				new Map24.WebServices.Coordinate({
					Longitude : 344,
					Latitude : 3170
				}),
				new Map24.WebServices.Coordinate({
					Longitude : 577,
					Latitude : 3010
				})
			]
		};

		M24.mapInited = true;
	}
	M24.Mrc.setMapView(mapView);
	M24.Mrc.execute();

	// Static-map-Toolbar-Workaround
	Map24.MapClient.Static.prototype.layoutPaintToolbar = function(){};

	// Initialize mapping client and show map.
	var mapParams = {};
	mapParams.NodeName="m24_maparea";
	if(_params.MapType)
	{
		mapParams.MapType = _params.MapType
	}
	else
	{
		mapParams.MapType = "Auto"
	}

	// check if there were applet-parameters given
	if(_params.AppletParameters)
	{
		mapParams.AppletParameters = _params.AppletParameters;
	}


	// create and add a mapclient to the page
	M24.addMapClient(mapParams);

	if(_params.DisplayControls !== false)
	{
		// Draw the toolbar for the map-navigation
		M24.Toolbar.addToolbar();
	}

	// Define objects and variables for Wrapper API compatibility
	Map24.MapApplication.Map = M24.map;
	Map24.MapApplication._StatusBox = new Object();
	Map24.MapApplication._LocalConnection = this.localConn;
	Map24.MapApplication._LocalConnection.disableCommandCloning();
	Map24.MapApplication._CommandContainer = [];
	Map24.MapApplication._ConnectionInt = self.setInterval( 'Map24.MapApplication._sendCommands();', 250 );

}


/**
 * Adds a mapclient into the application into defined dom-node.
 * this function also executes a javadetection by default.
 * @param {Object} _params
 */
M24.addMapClient = function (_params)
{
	M24.d("addMapClient");

	var appletParams = {};

	// check if a Canvas-Name was given
	if(_params.CanvasName && typeof _params.CanvasName == "string")
	{
		canvasName = _params.CanvasName;
	}

	// check if there are Appletparameters defined in the _params:
	if(_params.AppletParameters && _params.AppletParameters instanceof Object)
	{
		appletParams = _params.AppletParameters;
	}

	// TODO: this lets disappear all tooltips on the map - not only the ones from Map24. There will be something integrated into the Applet soon.
	appletParams.TTDELAY_MAP = "9999";
	// defines the maximum zoomlevel
	appletParams.canvasmaxzoom = "0.1";

	var canvas = new Map24.Canvas( { NodeName: _params.NodeName } );
	// Copyright-Workaround - step 2
	canvas.Widgets = {};
	M24.map.addCanvas( canvas, "c" );

	// if maptype is not set, set to "Auto" or "Applet", create static mapclient
	if( typeof _params.MapType != "string" || _params.MapType == "Static" || _params.MapType == "Auto")
	{
		M24.mapClient = new Map24.MapClient.Static();
		M24.map.addMapClient( M24.mapClient, "Static" );

		// if static map should not be panable.
		// this has to be done right after the creation of the static map-client
		if (M24.STATIC_MAP_PANNING === false)
		{
			// [API HACK]
			M24.map.MapClient.Static.onPanStart = function(e){};
			M24.map.MapClient.Static.onPanUpdate = function(e){};
			M24.map.MapClient.Static.onPanStop = function(e){};
			M24.map.MapClient.Static.onZoomRectStart = function(e){};
		}

		// display the static map
		M24.map.show( "Static", "c" );
	}

	// check if a applet is needed, too and if so load and display it.
	if( typeof _params.MapType != "string" || _params.MapType != "Static")
	{
		M24.mapClient = new Map24.MapClient.Applet(appletParams);
		M24.map.addMapClient( M24.mapClient, "Applet" );
		if(_params.MapType == "Applet")
		{
			M24.map.show( "Applet", "c" );
		}

		// execute MLC-commands to modify the components with the onMapClientReady-event
		M24.map.onMapClientReady = function( e )
		{
			if( e.MapClient.Class == "Applet") {

				M24.map.onMapClientReady = null;

				// change map-canvas
				M24.Mrc.controlComponent({
					Control		:	"SET",
					Component	:	"MAPLETPANEL",
					Properties 	:	[
						M24.Mrc.addProperty({Key: "canvasPadding", Value: "0,0,0,0"})
					]
				});
				// hide overview
				M24.Mrc.controlComponent({
					Control		:	"HIDE",
					Component	:	"SHOWOV"
				});
				// show tile-selector
				M24.Mrc.controlComponent({
					Component	:	"TILES",
					Control		:	"SHOW",
					Properties 	:	[
						M24.Mrc.addProperty({Key: "setstate", Value: "MAP"}),
						M24.Mrc.addProperty({Key: "canvasmaxzoom", Value: "0.1"})
					]
				});
				M24.Mrc.execute();

				// call setmaptype-function. This will also automatically set the MapView
				// to the one from the static map, if this was shown before already.
				M24.setMapType("Applet");
			}
		}
	}
}



/**
 *	Set the type of the map client.
 *  (in parts copied from wrapper-api)
 *
 *	@param {String} mapType
 *		Type of the map client. The possible values are "Applet" and "Static".
 *
 *	@return void
 */
M24.setMapType = function ( mapType )
{
	if( typeof mapType != "string" || (mapType != "Applet" && mapType != "Static" ) ) return;

	// get the current mapview of the current mapclient.
	var mapView = M24.getCurrentMapView();

	var switched = false;

	if( mapType == "Static" && M24.map.Canvas["c"].MapClient.Class != "Static" )
	{
		if( typeof M24.map.MapClient["Static"] == "undefined")
		{
			M24.mapInited = false;
			M24.addMapClient( {MapType: "Static", NodeName: "m24_maparea"} );
		}
		else
		{
			M24.map.show( "Static", "c" );
		}
		switched = true;
	}
	else if ( mapType == "Applet" && M24.map.Canvas["c"].MapClient.Class != "Applet" )
	{
		if( typeof M24.map.MapClient["Applet"] == "undefined")
		{
			M24.mapInited = false;
			M24.addMapClient( {MapType: "Applet", NodeName: "m24_maparea"} );
		}
		else
		{
			M24.map.show( "Applet", "c" );
		}
		switched = true;
	}

	if(switched === true)
	{
		M24.Mrc.setMapView({
			Coordinates: [
				new Map24.WebServices.Coordinate({
					Longitude: parseFloat( mapView.TopLeft.Longitude ),
					Latitude: parseFloat( mapView.TopLeft.Latitude )
				}),
				new Map24.WebServices.Coordinate({
					Longitude:  parseFloat( mapView.LowerRight.Longitude ),
					Latitude:  parseFloat( mapView.LowerRight.Latitude )
				})
			]
		});
		M24.Mrc.execute();
	}
}


/**
 * Returnes the coordinates of the current mapview of the currently active mapclient.
 */
M24.getCurrentMapView = function()
{
	return M24.map.Canvas["c"].MapClient.MapViewHistory.current();
}



/**
 * Dumps the given objects
 * @param {Object} dumpMe (mandatory) - the object to dump
 * @param {Object} name (optional) - description of what is dumped. will be dumped, too.
 */
M24.d = function (dumpMe,name)
{
	if(M24.DEBUG===true)
	{
		if(name)
		{
			Map24.dump(name);
			//console.debug(name);
		}
		// output to API console
		Map24.dump(dumpMe);
		// output to FIREBUG
		//console.debug(dumpMe);
	}
}



/**
 * Definition of Helper-functions
 */
M24.Helper = function (){};

/**
 * returns the path to an image
 * @param {Object} imagefile
 */
M24.Helper.getImageUrl = function(imagefile)
{
	var url = "http://img.customer.map24.com/wdr/";

	return url + imagefile;
}



/**
 * Definition of Toolbar-functions
 */
M24.Toolbar = function (){};
M24.Toolbar.CurrentPercent = 100;

/**
 * Adds the toolbar into the dom-node with id "m24_toolbar"
 */
M24.Toolbar.addToolbar = function ()
{
	M24.d("addToolbar");

	// create a new toolbar
	var doc = document;
	var win = window;

	var canvas = new Map24.Canvas( { NodeName: "m24_toolbar" } );

	// create toolbar
	var toolbar = new Map24.Gui.Toolbar({
		Win: win, Doc: doc,
		PosSize: new Map24.Rectangle( new Map24.Pixel(0,0), canvas.ViewportWidth, 30 ),
		SeparatorSpace: 5
	});
	toolbar.Node.style.zIndex = 50;
	toolbar.Node.style.backgroundColor = "#ecf0f3";
	toolbar.MapClient = M24.map.Canvas["c"].MapClient;

	// add minus button
	toolbar.MinusButton = new Map24.Gui.ImageButton({
		Win: win, Doc: doc,
		Url: M24.Helper.getImageUrl("minus.gif"),
		MouseOverUrl: M24.Helper.getImageUrl("minus_mo.gif"),
		MouseDownUrl: M24.Helper.getImageUrl("minus_mo.gif"),
		Width: 30, Height: 30
	});
	toolbar.MinusButton.onClick = function() {
		var toolbar = this.Parent;

		//M24.Toolbar.zoomRelative(5);
		M24.Mrc.CommandContainer[M24.Mrc.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
		({
			ModifyMapView: new Map24.WebServices.ModifyMapView({
				Control		:	"ZOOMOUT",
				percentage	:	10
			})
		});

		M24.Mrc.execute();

		if( toolbar.Slider.KnobPos.X > 0 )
			toolbar.Slider.setKnobTo( toolbar.Slider.KnobPos.X - 5, 0, false, false );
	}
	toolbar.addItem( toolbar.MinusButton );

	// add slider
	toolbar.Slider = new Map24.Gui.Slider({
		Win: win, Doc: doc,
		Knob: new Map24.Gui.ImageButton({
			Url: M24.Helper.getImageUrl("slider.gif"),
			MouseOverUrl: M24.Helper.getImageUrl("slider.gif"),
			StopMouseEvents: false,
			Width: 7, Height: 30
		}),
		InnerBounds: new Map24.Rectangle( new Map24.Pixel(0,15), 100, 1 ),
		Width: 100, Height: 30
	});
	toolbar.Slider.addBackgroundImage( M24.Helper.getImageUrl("slider_bg.gif"), {
		width: "100px", height: "30px"
	});
	toolbar.addItem( toolbar.Slider );
	toolbar.Slider.onSliderDragKnob = function( e ) {
		M24.d("ON SLIDER DRAG KNOB: "+e.Type);
		if(e.Type == "STOP") {
			var percent = 100 - e.KnobPos.X;

			// Special calculation for NRW-map-cutout:
			// (mapcutout starts with pixel 34 of the slider)
			percent = 66 * percent / 100;

			M24.Toolbar.zoom(percent);
		}
	}
	toolbar.Slider.onMapViewChanged = function (e){
		M24.d(e,"ONMAPVIEWCHANGED");
		var current_view = M24.map.Canvas["c"].MapClient.MapViewHistory.current();
		// TODO: why does it work so exactly with 142,... ???
		var percent = 142.535318764768334 - 100 * M24.map.Session.calculateViewPercentage(
			current_view,
			canvas.ViewportWidth,
			canvas.ViewportHeight
		);
		M24.Toolbar.CurrentPercent = 100 - percent;

		// Special calculation for NRW-map-cutout:
		// (mapcutout starts with pixel 34 of the slider)
		percent = percent - 34;
		percent = 100 * percent / 66;

		M24.d(percent,"Set Knob To:");

		toolbar.Slider.setKnobTo(percent, 0, false, false);
	}
	toolbar.Slider.onMapViewChanged({});
	M24.map.addListener( "MapViewChanged", [toolbar.Slider,toolbar.Slider.onMapViewChanged] );

	// add plus button
	toolbar.PlusButton = new Map24.Gui.ImageButton({
		Win: win, Doc: doc,
		Url: M24.Helper.getImageUrl("plus.gif"),
		MouseOverUrl: M24.Helper.getImageUrl("plus_mo.gif"),
		MouseDownUrl: M24.Helper.getImageUrl("plus_mo.gif"),
		Width: 30, Height: 30
	});
	toolbar.PlusButton.onClick = function() {
		var toolbar = this.Parent;

		//M24.Toolbar.zoomRelative(-5);
		M24.Mrc.CommandContainer[M24.Mrc.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
		({
			ModifyMapView: new Map24.WebServices.ModifyMapView({
				Control		:	"ZOOMIN",
				percentage	:	10
			})
		});
		M24.Mrc.execute();

		if( toolbar.Slider.KnobPos.X < (toolbar.Slider.InnerBounds.Width-1) )
			toolbar.Slider.setKnobTo( toolbar.Slider.KnobPos.X + 5, 0, false, false );

	}
	toolbar.addItem( toolbar.PlusButton );


	// add drag button
	var pan_action = canvas.getActionById("PAN");
	var drag_left = false;
	var default_url = M24.Helper.getImageUrl("drag.gif");
	if( (pan_action instanceof Map24.ActionDefinition) &&
		(pan_action.Status.MouseDown & Map24.Browser.LEFT_BUTTON) )
	{
		default_url = M24.Helper.getImageUrl("drag_active.gif");
		drag_left = true;
	}
	toolbar.DragButton = new Map24.Gui.ImageButton({
		Win: win, Doc: doc,
		Url: default_url,
		MouseOverUrl: M24.Helper.getImageUrl("drag_active.gif"),
		MouseDownUrl: M24.Helper.getImageUrl("drag_active.gif"),
		Width: 30, Height: 30
	});
	toolbar.DragButton.DragLeft = drag_left;
	toolbar.DragButton.onClick = function()
	{
		
		//var canvas = this.Parent.MapClient.Canvas;
		var canvas = M24.map.Canvas["c"];
		var pan_action = canvas.getActionById("PAN");
		var zoom_action = canvas.getActionById("ZOOM_RECT");
		if( this.DragLeft )
		{
			this.DragLeft = false;
			this.Url = M24.Helper.getImageUrl("drag.gif");
			pan_action.Status.MouseDown = Map24.Browser.RIGHT_BUTTON;
			zoom_action.Status.MouseDown = Map24.Browser.LEFT_BUTTON;
			/*M24.Mrc.controlComponent({
				Control: "HIDE",
				Properties: [
					M24.Mrc.addProperty({Key: "triggerAction", Value: "HAND"})
				]
			});
			M24.Mrc.execute();*/
		}
		else
		{
			
			this.DragLeft = true;
			this.Url = M24.Helper.getImageUrl("drag_active.gif");
			pan_action.Status.MouseDown = Map24.Browser.LEFT_BUTTON;
			zoom_action.Status.MouseDown = Map24.Browser.RIGHT_BUTTON;
			/*
			M24.Mrc.controlComponent({
				Control: "SHOW",
				Properties: [
					M24.Mrc.addProperty({Key: "triggerAction", Value: "HAND"})
				]
			});
			M24.Mrc.execute();*/
		}
		canvas.addAction( pan_action );
		canvas.addAction( zoom_action );
	}
	toolbar.addItem( toolbar.DragButton );

	// add the toolbar into the overlay
	//canvas.ViewportNode.appendChild( toolbar );
	var c = document.getElementById("m24_toolbar");
	c.appendChild(toolbar.Node);
}

M24.Toolbar.zoomRelative = function (changePercent)
{
	var percent = this.CurrentPercent + changePercent;
	this.zoom(percent);
}

M24.Toolbar.zoom = function (percent)
{
	if(!percent)
	{
		return;
	}
	else if(percent > 100)
	{
		percent = 100;
	}
	else if (percent < 0)
	{
		percent = 0;
	}

	this.CurrentPercent = percent;

	M24.d(this.CurrentPercent,"CURRENT ZOOM PERCENT");

	M24.Mrc.CommandContainer[M24.Mrc.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
	({
		ModifyMapView: new Map24.WebServices.ModifyMapView({
			Control		:	"ZOOM",
			percentage	:	100-percent
		})
	});

	M24.Mrc.execute();
}





/**
 * Definition of functions for the Geocoder
 */
M24.Geocoder = function(){};

M24.Geocoder.searchFree = function(_params)
{
	var geo = new Map24.GeocoderServiceStub();
	geo.geocode(_params);
}

M24.Geocoder.geocodeAddress = function()
{
	var address = document.getElementById("m24_geocode_address").value;

	if(address != "")
	{
		M24.Geocoder.searchFree({
			SearchText: address,
			MaxNoOfAlternatives: 10,
			//State: "Nordrhein-Westfalen",
			//Country: "DE",
			CallbackFunction: M24.Geocoder.onGeocodeAddress
		});
	}
}

M24.Geocoder.onGeocodeAddress = function (result)
{
	var validResult = false;
	if(result.length > 0)
	{
		// coordinates the result has to lay inside
		// (the bounds defined for the Map24ID, too)
		var geoBounds = {
			topleft:{
				x: 289,
				y: 3187
			},
			lowerright:{
				x: 632,
				y: 2981
			}
		};

		for(var i=0; i<result.length; i++)
		{
			var address = result[i];

			// check if the result has set "NRW" as state
			//if(address.getState()=="Nordrhein-Westfalen" && address.getCountry()=="DE")

			var x = address.getLongitude();
			var y = address.getLatitude();

			// check if result is inside of NRW or about 80km around
			if(
				geoBounds.topleft.x < x && geoBounds.lowerright.x > x &&
				geoBounds.topleft.y > y && geoBounds.lowerright.y < y
			){
				validResult = true;
				M24.Mrc.setMapView({
					Longitude: address.getLongitude(),
					Latitude: address.getLatitude(),
					MinimumWidth: 15000
				});
				M24.Mrc.execute();

				// as a matching result was found, break the loop now.
				break;
			}
		}
	}
	if(!validResult)
	{
		alert("Der gesuchte Ort liegt ausserhalb des WDR-Sendegebiets.");
	}
}



/**
 * Defintion of function for the MRC - MapletRemoteControl-commands
 */
M24.Mrc = function (){};
M24.Mrc.CommandContainer = [];

M24.Mrc.addProperty = function (_params)
{
	return new Map24.WebServices.Property(_params);
}

M24.Mrc.setMapView = function (_params)
{
	if(_params.Longitude && _params.Latitude)
	{
		_params.Coordinates = [
			new Map24.WebServices.Coordinate({
				Longitude : _params.Longitude,
				Latitude : _params.Latitude
			})
		];
		delete _params["Longitude"];
		delete _params["Latitude"];
	}
	if(_params.MinimumWidth)
	{
		_params.ClippingWidth = new Map24.WebServices.SetMapViewClippingWidth({
			MinimumWidth: _params.MinimumWidth
		});
		delete _params["MinimumWidth"];
	}
	this.CommandContainer[this.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
	({
		SetMapView: new Map24.WebServices.SetMapView(_params)
	});
}

M24.Mrc.setHomeView = function(_params)
{
	if(_params.Longitude && _params.Latitude)
	{
		_params.Coordinates = [
			new Map24.WebServices.Coordinate({
				Longitude : _params.Longitude,
				Latitude : _params.Latitude
			})
		];
		delete _params["Longitude"];
		delete _params["Latitude"];
	}
	if(_params.MinimumWidth)
	{
		_params.ClippingWidth = new Map24.WebServices.SetMapViewClippingWidth({
			MinimumWidth: _params.MinimumWidth
		});
		delete _params["MinimumWidth"];
	}

	this.CommandContainer[this.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
	({
		SetHomeView: new Map24.WebServices.SetHomeView(_params)
	});
}

M24.Mrc.controlComponent = function(_params)
{
	this.CommandContainer[this.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
	({
		ControlComponent: new Map24.WebServices.ControlComponent(_params)
	});
}

M24.Mrc.controlLayer = function(_params)
{
	this.CommandContainer[this.CommandContainer.length] = new Map24.WebServices.XMLCommandWrapper
	({
		ControlLayer: new Map24.WebServices.ControlLayer(_params)
	});
}

/**
 * Execute the current MRC-command via a local connection
 */
M24.Mrc.execute = function (_params)
{
	if(this.CommandContainer.length>=1)
	{
		if(_params && _params.ConnectionType && _params.ConnectionType == "remote")
		{
			var conn = M24.remoteConn;
		}
		else
		{
			var conn = M24.localConn;
		}

		conn.mapletRemoteControl(
			new Map24.WebServices.Message.mapletRemoteControlRequest({
				MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({
					Map24MRC: new Map24.WebServices.Map24MRC({
						Commands: this.CommandContainer
					})
				})
			})
		);

		this.CommandContainer = [];
	}
};

