var MerixMap24Tools = {
	//Geocoding
	map : null,
	
	//route generator
	startGeocoded : null,
	desitnationGeocoded : null,	
	
	//html object creation 
	_objectIdCounter : 0,
	_zoom : 5000,
	
	init : function(map){
		this.map = map;
		return this;
	},
	geocode : function ( address, onGeoFunc ){
		this.map.Webservices.sendRequest(
			new Map24.Webservices.Request.MapSearchFree(this.map, {
				SearchText: address,
				MaxNoOfAlternatives: 50
			})
    	);
  
  		if (typeof onGeoFunc == 'function') {
			this.map.onMapSearchFree = function( event ){
				var geoRes = new Object();
				geoRes.Alternatives = event.Alternatives;
				geoRes.firstResult = geoRes.Alternatives[0];
				onGeoFunc( geoRes );
			}
		}
	},
	//center map on given coordinate
	centerMapOnGivenCoordinate : function(latitude, longitude){
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl();
        mrcContainer.push(
          new Map24.Webservices.MRC.SetMapView({
            Coordinates: new Map24.Coordinate( latitude, longitude ),
            ClippingWidth: new Map24.Webservices.ClippingWidth(
              { MinimumWidth: 10000 }              
            )
          })
        );
        this.map.Webservices.sendRequest( mrcContainer );
    },
	//turn in 3D control
	show3DView : function (){
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( this.map );
        mrcContainer.push( 
          new Map24.Webservices.MRC.ControlComponent({
            Component: "M3D",
            Control: 'SHOW'
          }) 
        );
        mrcContainer.push( 
          new Map24.Webservices.MRC.ControlComponent({
            Component: "SHOWM3D",
            Control: 'SHOW'
          }) 
        );
        this.map.Webservices.sendRequest( mrcContainer );
    },
	
	calculateRouteAddr : function ( start, destination ){
        if( Map24.isNull( start ) ) return;
        if( Map24.isNull( destination ) ) return;
 
        this.geocodeStartAndDestination( start, destination );
        return;
    },
      
    geocodeStartAndDestination : function ( start, destination ){
		
        //1. Geocode the start address
        this.geocode( start, onGeocodeStart )
 
        //2. When start address has been geocoded, then geocode destination address
        function onGeocodeStart( geoRes ){
          MerixMap24Tools.startGeocoded = geoRes.firstResult;
          MerixMap24Tools.geocode( destination, onGeocodeDest );
        }
        //3. When both start and dest address have been geocoded, then start route calculation
        function onGeocodeDest( geoRes ){
          MerixMap24Tools.destinationGeocoded = geoRes.firstResult;
          MerixMap24Tools.calculateRouteCoord( MerixMap24Tools.startGeocoded, MerixMap24Tools.destinationGeocoded );
        }
    },
      
    //Calculate a route between two addresses
    calculateRouteCoord : function ( startGeocoded, destinationGeocoded ){
		
		
        if( Map24.isNull( startGeocoded ) ) return;
        if( Map24.isNull( destinationGeocoded ) ) return;
	  
        var routeRequest = new Map24.Webservices.Request.CalculateRoute( this.map );
        routeRequest.Start = new Map24.Webservices.Request.CalculateRoute.CoordinateAndAddress();
        routeRequest.Start.Coordinate = new Map24.Coordinate( startGeocoded.Coordinate.Longitude,
                                                              startGeocoded.Coordinate.Latitude );
        routeRequest.Destination = new Map24.Webservices.Request.CalculateRoute.CoordinateAndAddress();
        routeRequest.Destination.Coordinate = new Map24.Coordinate( destinationGeocoded.Coordinate.Longitude,
                                                                    destinationGeocoded.Coordinate.Latitude );
        this.map.Webservices.sendRequest( routeRequest );
      
	  	this.addLocation(startGeocoded.Coordinate.Latitude, startGeocoded.Coordinate.Longitude, {});
		this.addLocation(destinationGeocoded.Coordinate.Latitude, destinationGeocoded.Coordinate.Longitude, {symbolId : 20956});
		
       //This listener is called when the route calculation has finished
        this.map.onCalculateRoute = function( event ){
          var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( MerixMap24Tools.map );

          mrcContainer.push( 
            new Map24.Webservices.MRC.DeclareMap24RouteObject({
              MapObjectID: "actualRoute",
              Map24RouteID: event.Info.RouteID,
              Color: new Map24.Color( 255, 0, 0, 180 )
            }) 
          );
          //Center the map view on the route visualization
          mrcContainer.push( MerixMap24Tools.genSetMapView( 0, 70, null, null, "actualRoute" ) );
          
          //Enable the visibility of the route 
          mrcContainer.push( MerixMap24Tools.genControlMapObject( "ENABLE", "actualRoute" ) );
          
          MerixMap24Tools.map.Webservices.sendRequest( mrcContainer );
        }
      },
      
    
      
      //Factory functions
      genSetMapView : function ( ClippingWidth, ClippingPercent, lon, lat, objID ){
        //Hashtable Clip { MinimumWidth: ClippingWidth, ViewPercentage: ClippingPercent } is created
        var Clip = new Array();
        if( !Map24.isNull( ClippingWidth ) ) 
          Clip['MinimumWidth'] = ClippingWidth;
        if( !Map24.isNull( ClippingPercent ) )
          Clip['ViewPercentage'] = ClippingPercent;
        
        if( !Map24.isNull( lon ) && !Map24.isNull( lat ) )
        {
          var SetMapView = new Map24.Webservices.MRC.SetMapView({
            ClippingWidth: new Map24.Webservices.ClippingWidth( Clip ),
            Coordinates: new Map24.Coordinate( lon, lat )
          });
        } 
        else if( !Map24.isNull( objID ) )
        {
          var SetMapView = new Map24.Webservices.MRC.SetMapView({
            ClippingWidth: new Map24.Webservices.ClippingWidth( Clip ),
            MapObjectIDs: objID 
          });
        }	
        return SetMapView;	
      },
		
	  genControlMapObject : function( Control, objID ){
        var ControlObject = new Map24.Webservices.MRC.ControlMapObject({
          Control: Control,
          MapObjectIDs: objID
        });
        return ControlObject;
      },
	  
	  //create html and place it on map	
      addHTMLObject : function(latitude, longitude, htmlContent, objectId) {
	  	if (typeof objectId == 'undefined') {
			var objectId = "HTMLObject"+this._objectIdCounter;
			this._objectIdCounter++;
		}
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( this.map );
        mrcContainer.push(
          new Map24.Webservices.MRC.DeclareMap24HTMLObject({
            MapObjectID: objectId,
            Coordinate: new Map24.Coordinate( latitude, longitude ),
            HTML: htmlContent
          })
        );
        mrcContainer.push( this.genControlMapObject( 'ENABLE', objectId ) );
        this.map.Webservices.sendRequest( mrcContainer );
      },
	  
	  addMultipleLocations : function (locations) {
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( this.map );
		
		for(i=0;i < locations.length;i++)
		{
			var loc = locations[i];
			if (typeof loc.objectId == 'undefined') {
				loc.objectId = "myLocation"+this._objectIdCounter;
				this._objectIdCounter++;
			}
			
			if (typeof loc.symbolId == 'undefined') {
				loc.symbolId = 20950;
			}
	
	        mrcContainer.push(
	          new Map24.Webservices.MRC.DeclareMap24Location({
	            MapObjectID: loc.objectId,
	            Coordinate: new Map24.Coordinate( loc.longitude, loc.latitude  ),
	            SymbolID: loc.symbolId
	          })
	        );
	        mrcContainer.push(
	          new Map24.Webservices.MRC.ControlMapObject({
	            Control: "ENABLE",
	            MapObjectIDs: loc.objectId
	          })
	        );
			 
	        mrcContainer.push(
	          new Map24.Webservices.MRC.SetMapView({
	            Coordinates: new Map24.Coordinate( loc.longitude, loc.latitude ),
	            ClippingWidth: new Map24.Webservices.ClippingWidth(
	              { MinimumWidth: 5000 }            
	            )
	          })
	        );
			
			//center on item on click
			if (typeof loc.trigger != "undefined") {
				$('#'+loc.trigger).attr("longitude", loc.longitude);
				$('#'+loc.trigger).attr("latitude", loc.latitude);

			
				$('#'+loc.trigger).click(function(){ 
					MerixMap24Tools.centerMapOnGivenCoordinate($(this).attr("longitude"), $(this).attr("latitude")) ;
				});
			}
		}
        this.map.Webservices.sendRequest( mrcContainer );	  	
	  },
	  addLocation : function(latitude, longitude, options) {
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( this.map );
		
		if (typeof options.objectId == 'undefined') {
			options.objectId = "myLocation"+this._objectIdCounter;
			this._objectIdCounter++;
		}
		
		if (typeof options.symbolId == 'undefined') {
			options.symbolId = 20950;
		}

        mrcContainer.push(
          new Map24.Webservices.MRC.DeclareMap24Location({
            MapObjectID: options.objectId,
            Coordinate: new Map24.Coordinate( longitude, latitude  ),
            SymbolID: options.symbolId
          })
        );
        mrcContainer.push(
          new Map24.Webservices.MRC.ControlMapObject({
            Control: "ENABLE",
            MapObjectIDs: options.objectId
          })
        );
        
        if (typeof options.zoom == 'undefined') {
        	options.zoom = this._zoom;
        }
        
        mrcContainer.push(
          new Map24.Webservices.MRC.SetMapView({
            Coordinates: new Map24.Coordinate( longitude, latitude ),
            ClippingWidth: new Map24.Webservices.ClippingWidth(
              { MinimumWidth: options.zoom }            
            )
          })
        );
        this.map.Webservices.sendRequest( mrcContainer );
      },
	  //add location from address
	  addLocationFromAddress : function(address, options) {
	  	if (typeof options == 'undefined') {
			var options = {};
		}
	  	this.geocode(address, function(loc){
			loc = loc.firstResult;
			MerixMap24Tools.addLocation(loc.Coordinate.Latitude,loc.Coordinate.Longitude, options); 
		});
	  },
	/*This function controls the visibility of a map layer.*/
  	ControlLayer : function( cmd, layerid ) {
  		var mrc = new Map24.Webservices.Request.MapletRemoteControl( this.map );
  		mrc.push( new Map24.Webservices.MRC.ControlLayer(cmd, layerid, true) );
  		this.map.Webservices.sendRequest( mrc );
  	}	  
};

var MerixMap24 = {
	tools : null,
	init : function() {
	  	var map = Map24.Webservices.getMap24Application({
		  AppKey : MAP24_API_KEY,
	  	  MapArea:document.getElementById("map"),
	      Maptype: "JAVA",
	  	  MapWidth: 560,
	  	  MapHeight: 400
	  	});
		
		this.tools = MerixMap24Tools.init(map);
		
		
		//serwis		
		var html = "<div style=\"width:235px;background-color: #ffffff; border: 2px; border-color:#aaaaaa; font-family: Verdana, sans-serif;\">"+
		  "<p style=\"margin:0px; padding: 5x;\">"+
		  "<b>Serwis Auto Wache</b><br />"+
          "ul. Rolna 29<br />"+
          "62-081 Przezmierowo<br />"+
					"Mitsubishi - &nbsp;&nbsp;&nbsp;Tel. 61 664 77 90,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax 61 664 77 99<br />"+
					"Suzuki - &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tel. 61 664 77 91,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax 61 664 77 99<br />"+
					"Mazda, Kia - &nbsp;Tel. 61 664 77 92,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax 61 814 23 33<br />"+
					"Części - &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tel. 61 664 77 94<br />"+
          "</p>"+
          "</div>";

		this.tools.addHTMLObject(1006.59, 3146.295, html);
		this.tools.addLocation(3146.21, 1006.79, { "zoom" : 750 });
		
		
		//salon
		var html = "<div style=\"width:235px;background-color: #ffffff; border: 2px; border-color:#aaaaaa; font-family: Verdana, sans-serif;\">"+
		  "<p style=\"margin:0px; padding: 5x;\">"+
		  "<b>Salon Auto Wache</b><br />"+
          "ul. Poznanska 10<br />"+
          "62-081 Przezmierowo<br />"+
          "Mitsubishi - &nbsp;&nbsp;Tel. 61 816 23 23,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax: 61 816 23 24<br />"+
					"Suzuki - &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Tel. 61 816 23 23,		<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax: 61 816 23 24<br />"+
					"Mazda, Kia - Tel. 61 664 77 55,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax 61 816 16 30<br />"+
          "</p>"+
          "</div>";

		this.tools.addHTMLObject(1007.045, 3146.13, html);
		this.tools.addLocation(3146.18310546875, 1006.83447265625, { "zoom" : 750 });
		
		//disable other car services
		this.tools.ControlLayer("DISABLE","3003");
		
		//search
		$('#mapSearchForm').html("<form method=\"get\" action=\"#\" id=\"map24searchSubmit\"><p><label for=\"map24search\">Podaj adres, z którego chciałbyś dojechać do naszej firmy:</label> <input type=\"text\" id=\"map24search\" name=\"map24search\" /> <input type=\"submit\" value=\"rysuj trasę\" /></p></form>");
		$('#map24searchSubmit').submit(function(e) { 
			e.preventDefault();
			MerixMap24Tools.calculateRouteAddr($('#map24search').val(), 'Tarnowo Podgorne, Rolna 10 62-081');
		});
		

		var self = this;
		$('#bus01,#bus02').click(function(e){
			e.preventDefault();
			self.tools.calculateRouteAddr("Poznan, Nowina 10","Tarnowo Podgorne, Rolna 10 62-081");
			self.tools.centerMapOnGivenCoordinate(1012.7554321289062, 3144.982177734375);
		});
	}
};


$(document).ready(function(){
//	MerixMap24.init();

});