﻿// Example header text. Can be configured in the options.
var pinInfobox;
var customInfobox;
 var map = null;
 var boxes = new Array();
 var directionsManager = null;
 var pushpins;
 var myLayer;  
 var data;
 var myCluster;
 var mouseoverHandler;
 var mouseoutHandler;
   
function GetMap() 
 {
    var mapOptions = { credentials: myCredentials,
                       center: new Microsoft.Maps.Location(initial_latitude,initial_longitude),
                       mapTypeId: Microsoft.Maps.MapTypeId.road,
                       zoom: 12 }
    map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
    Microsoft.Maps.registerModule("CustomInfoboxModule", "js/V7CustomInfoBox.js");
    Microsoft.Maps.loadModule("CustomInfoboxModule", {callback: function() { customInfobox = new CustomInfobox(map,  { orientation: 1, color: '#ffffff', arrowColor: '#ffffff', borderColor: '#transparent', tether: true, arrowWidth: 20 });
     }
   });
     myLayer = new ClusteredEntityCollection(map,
                                    { singlePinCallback: createPin,
                                      clusteredPinCallback: createClusteredPin,
                                      callback: showLeftHandMenu});
    myLayer.SetOptions({ gridSize : 130});
    show_direction_results(false);
}

 function ShowMap()
    {
       map.getCredentials(MakeGeocodeRequest); 
    
    }

 function MakeGeocodeRequest()
            {
              //var geocodeRequest = geocodeRequestURL + "/REST/v1/Locations/" + txt_location.value + "&countryRegion=" + current_country_code + "&ouput=json&jsonp=GeocodeCallback&key=" + myCredentials;
              var geocodeRequest = geocodeRequestURL + "/REST/v1/Locations/" + current_country_code + "/" +  txt_location.value +  "?ouput=json&jsonp=GeocodeCallback&key=" + myCredentials;
              CallRestService(geocodeRequest);
            }

            function CallRestService(request)
            {
                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", request);
                document.body.appendChild(script);
            }

  function submit_on_enter(myfield,e,command)
	{
	    
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;

		if (keycode == 13)
		{
		  var ver = checkVersion();
		   if (ver >= 8.0 || ver == -1)
		   {
             e.preventDefault();
            }

            
			eval(command);
			
			return false;
		}
		else
			return true;
	}
	
	
	
	
      function GeocodeCallback(result)
            {
             
             if(result && result.resourceSets &&  result.resourceSets.length > 0 &&
                                                    result.resourceSets[0].resources &&
                                                    result.resourceSets[0].resources.length > 0)
              {

                  var lat = result.resourceSets[0].resources[0].point.coordinates[0];
                  var long =  result.resourceSets[0].resources[0].point.coordinates[1];
                
                  var requestStr = spatialRequestURL + '/REST/v1/data/' + myAccessID + '/XpartStoreLocator/XPartStoreLocator?spatialFilter=nearby(' + lat + ',' + long + ', 50)&$select=EntityID,AddressLine,Name,DisplayName,Locality,PostalCode,AdminDistrict,Latitude,Longitude,__Distance,Phone,mg_rover,mg_rover_all_makes,new_mini&$top=10&$format=json&key=' + myCredentials + '&Jsonp=MapResults';
                  if (filter_field_name != '')
                  {
                    requestStr  = requestStr + '&$filter=' + filter_field_name + ' Eq true';
                  }
                  	
                   
                   CallRestService(requestStr);                                    
            }
              else
              {

                document.getElementById('results_print_div').style.display = 'none';
               	var no_results_div = document.getElementById('no_results');
               	no_results_div.style.display = 'block';
              }
              
              
             }

               //Show results (up to 10) and put them on the map
        function MapResults(response) {
          
            
            
            //Display list of results
            if (myLayer != null)
            {
             
                document.getElementById("recordListDiv").innerHTML = "";
                document.getElementById("recordListDiv").style.display = 'block';
                var get_directions_div = document.getElementById('get_directions');
                get_directions_div.style.display = 'block';
                var output = document.getElementById("recordListDiv");
                var resultsList = document.createElement('table');
                var num = 1;
                output.appendChild(resultsList); 
               
                //Create pushpin collection to display on the map
                pushpins =   new Microsoft.Maps.EntityCollection();
                var showinfoBoxes = new Microsoft.Maps.EntityCollection();
                var allLocs = new Array();
                var thisLocs = new Array();
                //Check if there are results
                if (response.d.results.length != 0) {
                 document.getElementById('results_print_div').style.display = 'block'
                   //Get the search results
                   var results = response.d.results;

                 for (var i = 0; i < results.length; ++i)
                    {
                    
                         num =  i + 1;
                       
                             
                                //initialize bounds for map area 
                                var minLatitude = results[0].Latitude; var maxLatitude = results[0].Latitude; ;
                                var minLongitude = results[0].Longitude; var maxLongitude = results[0].Longitude; 

                                 output.style.visibility = "visible";
                                // Display results header
                             
                                var resultsListItem = null;
                                var resultStr = "";
                                // Show the name and record ID in our records list. When the name is clicked, open
		                        //  our info box:
		                        var newTR = document.createElement('tr');
		                        var newTD = document.createElement('td');
		                        var anchor = document.createElement ( 'a' );
		                        var record_table = document.createElement ( 'table' );
		                        var record_tbody = document.createElement ( 'tbody' );
		                        var inner_tr = document.createElement ( 'tr' );
		                        var inner_td = document.createElement ( 'td' );
    
                                    inner_td.align='left';
		                            inner_td.vAlign='top';
		                            inner_td.className='resultsNumber';
		                            inner_td.innerHTML =  num;
		                            inner_tr.appendChild(inner_td);
                		
		                            inner_td = document.createElement ( 'td' );
		                            inner_td.width="22";
		                            inner_tr.appendChild(inner_td);
                		
		                            inner_td = document.createElement ( 'td' );
		                            inner_td.align='left';
		                            inner_td.vAlign='top';
		                            inner_td.width="215"
		                            var address_data = '';
		                            address_data = '<span class="blueText"><strong>' + results[i].Name + '</strong></span><br />';
                		
                               
                                    //Display each entity and create a pushpin for the map
                                      address_data = address_data + results[i].AddressLine + "<br/>"
                                            + results[i].Locality + "<br/>"
                                            + results[i].AdminDistrict + "<br/>"
                                            + results[i].PostalCode + "<br/>";
                                            + results[i].Phone + "<br/><br />";
                                      inner_td.innerHTML = address_data;



                                      var next_row = '';
                                      var lat,lon;
                                      lat = results[i].Latitude;
                                      lon = results[i].Longitude;
                                      next_row += '<td align="right" valign="top"><strong>'
		                             if (distance_unit == 'miles')
			                                next_row += results[i].__Distance.toFixed(2) + ' ' + "miles";
		                               else if (distance_unit == 'km')
			                              next_row += results[i].__Distance.toFixed(2) + ' ' + km_text;
                			
		                                next_row += '</strong></td></tr></table><input type="hidden" id="destination_pc_l' + num + '" value="' + results[i].PostalCode + '" /><input type="hidden" id="destination_lat_l' + num + '" value="' + lat + '" /><input type="hidden" id="destination_lon_l' + num + '" value="' + lon + '" /><input type="hidden" id="name_l' + num + '" value="' + results[i].Name + '" />';			
                		
		                                inner_td.innerHTML += next_row;
		                                inner_tr.appendChild(inner_td);
                		
		                                record_tbody.appendChild(inner_tr);
		                                record_table.appendChild(record_tbody);
                		
    		                         
                                   	    set_directions_destination(results[i].Name, results[i].PostalCode, results[i].Latitude, results[i].Longitude);
                                        
                                    
                                       
                                        var thisLoc = new Microsoft.Maps.Location(results[i].Latitude, results[i].Longitude);
                                        thisLocs.push(thisLoc);
                                        allLocs.push(thisLoc);


                                        //Determine bounds that display all pushpins
                                        if (results[i].Latitude > maxLatitude) 
                                        {maxLatitude = results[i].Latitude; }
                                        else if (results[i].Latitude < minLatitude)
                                        { minLatitude = results[i].Latitude; }

                                        if (results[i].Longitude > maxLongitude)
                                        { maxLongitude = results[i].Longitude; }
                                        else if (results[i].Longitude < minLongitude)
                                        { minLongitude = results[i].Longitude; }
                                        
                                    //  resultsList.appendChild(newTR);
                                      //  output.appendChild(resultsList);
                                 }
                               
                    //Add padding to map area so that pushpins are not on the edge
                    minLatitude -= 0.0001;
                    maxLatitude += 0.0001;
                    minLongitude -= 0.0001;
                    maxLongitude += 0.0001;
                    
                    
                    //var mapArea = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(minLatitude,minLongitude),new Microsoft.Maps.Location(maxLatitude,maxLongitude));
                    //map.setView({ bounds: mapArea });
                    map.setView({ bounds: Microsoft.Maps.LocationRect.fromLocations(allLocs) });
                   
                   
                    myLayer.SetData(response.d.results);
                    data = response.d.results;
                    document.getElementById('geocodestatus').style.display  = 'none';
                }
                else { //No results were returned
                     document.getElementById('results_print_div').style.display = 'none';
               	    var no_results_div = document.getElementById('no_results');
               	    no_results_div.style.display = 'block';
                    document.getElementById('geocodestatus').style.display = 'none';
                    
                }
            }
        }

    function createPin(data)
    {
        var pinText = data.Index;
        var pin = new Microsoft.Maps.Pushpin(data._LatLong,{ text: + '' + pinText + ''});
        pin.title = '<img src="images/icon_XPartLogo.gif" height="27" width="57" align="top" alt="XPart Logo" />';
        pin.postalcode = data.PostalCode;
        pin.name = data.Name;
        if(data.fromClustered != null)
        {
         pin.fromClustered = data.fromClustered;
        }
        var i = data.EntityID;
        
        var infoBoxHtml;
      
        infoBoxHtml = '<b>' + data.Name + '</b><br />';
        infoBoxHtml += data.DisplayName + '<br /><br />';
        infoBoxHtml += '<b> Phone:</b>' + data.Phone + '<br />';
        infoBoxHtml += '<b>' + data.__Distance.toFixed(2) + ' ' + "miles"; + '</b><br />';
        infoBoxHtml += '<br /><a href="#" onclick="if (document.getElementById(\'div_m' + i + '\').style.display == \'none\') { document.getElementById(\'div_m' + i + '\').style.display = \'block\'; document.getElementById(\'source_m' + i + '\').focus(); } else { document.getElementById(\'source_m' + i + '\').value = \'\'; document.getElementById(\'div_m' + i + '\').style.display = \'none\'; } return false;">' + directions_text  + '</a>';
        infoBoxHtml += '<div id="div_m' + i + '" style="display:none">';
         infoBoxHtml += 'from <br />';
         infoBoxHtml += '<input type="text" id="source_m' + i + '" wisth="100px" onKeyPress="submit_on_enter(this,event, \'calculate_directions_from_info_box(' + i + ')\');" />';
         infoBoxHtml += '<img src="images/' + go_small_button_image_name + '" onclick="calculate_directions_from_info_box(' + i + ');" />';
         infoBoxHtml += '</div>'
    
        infoBoxHtml += '</div>';
        pin.description = infoBoxHtml;  
        pin.shortDescription = data.AddressLine + ' (' + data.PostalCode + ')';
        
       
      //  mouseoverHandler = Microsoft.Maps.Events.addHandler(pin,'mouseover', displaySummaryInfobox);
       // mouseoutHandler = Microsoft.Maps.Events.addHandler(pin,'mouseout', closeInfoBox);
        Microsoft.Maps.Events.addHandler(pin,'click', displayInfobox);
        pushpins.push(pin);
        return pin;
    }
    
    function createClusteredPin(cluster, latlong)
    {
       var pin = new Microsoft.Maps.Pushpin(latlong, { 
          icon: 'images/clusteredpin.png',width: 27,
	            height: 42});
        pin.title =  "Cluster of " + cluster.length + " markers";
      
        //'<img src="images/icon_XPartLogo.gif" height="27" width="57" align="top" alt="XPart Logo" />';
        pin.postalcode = cluster[0].PostalCode;
        pin.name = cluster[0].Name;
        myCluster = cluster;
        var infoBoxHtml = '';
        for(var i = 0; i < cluster.length; i++)
         {
          if(infoBoxHtml == '')
           {
            infoBoxHtml = "<hr />";
            infoBoxHtml += '<a href="#" onclick="displayInfoBoxFromCluster(' + cluster[i].GridKey + ',' + cluster[i].EntityID + ')">' +  (i + 1) + " " + cluster[i].Name +  " (" + cluster[i].PostalCode + ")</a>";
           }
          else
           {
            infoBoxHtml += "<hr />";
            infoBoxHtml += '<a href="#" onclick="displayInfoBoxFromCluster(' + cluster[i].GridKey + ',' + cluster[i].EntityID + ')">' +  (i + 1) + " " + cluster[i].Name +  " (" + cluster[i].PostalCode + ")</a>";
           }
         }
 

        pin.description = infoBoxHtml; 
        pushpins.push(pin); 
        Microsoft.Maps.Events.addHandler(pin,'click', displayInfobox);
     //   mouseoverHandler = Microsoft.Maps.Events.addHandler(pin,'mouseover', displaySummaryInfobox);
     //   mouseoutHandler = Microsoft.Maps.Events.addHandler(pin,'mouseout', closeInfoBox);
       
        return pin;
    }
    
	function set_directions_destination(text, pc, lat, lon)
	{
		var destination_span = document.getElementById('destination_span');
		var destination_lat = document.getElementById('destination_lat');
		var destination_lon = document.getElementById('destination_lon');
		var destination_postcode = document.getElementById('destination_postcode');
	
		if (((destination_span != null) && (destination_lat != null)) && (destination_lon != null))
		{
			destination_span.innerHTML = text + ' (' + pc + ')';
			destination_lat.value = lat;
			destination_lon.value = lon;
			destination_postcode.value = pc;
		}
	}
	
	        function calculate_directions_from_left_panel()
	        {
	       
	         var dir_stat = document.getElementById("get_directions_status");
                  dir_stat.style.display = 'block';
        	  //var source = document.getElementById('directions_source');
        	//  map.getCredentials(MakeRouteRequest(source)); 
        	  
        	   if (!directionsManager)

                {
                  
                  Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute});

              }

                else

                {

                  createDrivingRoute();

                }
               



	        }
	        
	 function createDirectionsManager()

      {

          var displayMessage;

//          if (!directionsManager) 

//          {
 
           //   GetMap();
              directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

              displayMessage = 'Directions Module loaded\n';

              displayMessage += 'Directions Manager loaded';

        //  }

         // alert(displayMessage);

          directionsManager.resetDirections();

          directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function(arg) { alert(arg.message) });

          directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function() {  });

      }

      function createDrivingRoute()

      {
        closeInfoBox();
        if (directionsManager)
         {
          directionsManager.clearDisplay();
         } 
         var source;
          document.getElementById('get_directions_results').innerHTML = '';
         source = document.getElementById('directions_source');
        
        
         var waypoint1lat = document.getElementById("destination_lat");
         var waypoint1lon = document.getElementById("destination_lon");
       
         
        createDirectionsManager(); 

        directionsManager.resetDirections();
        var distanceUnit;
        // Set Route Mode to driving 
        if(current_country_code == "uk")
        {
           directionsManager.setRequestOptions({  distanceUnit: Microsoft.Maps.Directions.DistanceUnit.miles, routeMode: Microsoft.Maps.Directions.RouteMode.driving });
        }
        else
        {
           directionsManager.setRequestOptions({ distanceUnit: Microsoft.Maps.Directions.DistanceUnit.kilometers, routeMode: Microsoft.Maps.Directions.RouteMode.driving });
          
        }
        

        var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: source.value });

        directionsManager.addWaypoint(seattleWaypoint);

        var tacomaWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(waypoint1lat.value,waypoint1lon.value) });

        directionsManager.addWaypoint(tacomaWaypoint);

        // Set the element in which the itinerary will be rendered
        //document.getElementById('get_directions_results').style.display = 'block';
        show_direction_results(true);
        directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('get_directions_results') });
        Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
        
        var output = document.getElementById("recordListDiv");
		 output.style.display = 'none';
		  document.getElementById('results_print_div').style.display = 'none';
     //  alert('Calculating directions...');

        directionsManager.calculateDirections();
        var dir_stat = document.getElementById("get_directions_status");
        dir_stat.style.display = 'none';
        deletePushpin();
      }

function displayError(e)
         {
           // Display the error message
            alert(e.message);

            // If the error is a disambiguation error, display the results.
            if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation)
            {
               DisplayDisambiguation();
            }
         }
         
    function DisplayDisambiguation()
         {
            var results = "";

            var waypoints = directionsManager.getAllWaypoints();

            var i = 0;
            for (i=0; i<waypoints.length; i++)
            {
               var disambigResult = waypoints[i].getDisambiguationResult();

               if (disambigResult != null)
               {
                  results = results + "Address matches for " + waypoints[i].getAddress() + ":\n";

                  if(disambigResult.businessSuggestions.length != 0)
                  {
                     var j = 0;
                     for (j=0; j<disambigResult.businessSuggestions.length; j++)
                     {
                        results = results + disambigResult.businessSuggestions[j].name + ", " + disambigResult.businessSuggestions[j].address + "\n";
                     }
                  }
                  else if (disambigResult.locationSuggestions.length != 0)
                  {
                     var k = 0;
                     for (k=0; k<disambigResult.locationSuggestions.length; k++)
                     {
                        results = results + disambigResult.locationSuggestions[k].suggestion + "\n";
                     }
                  }
                  {
                     results = results + disambigResult.headerText + "\n";
                  }
               }                              
            }
            
           
            var output = document.getElementById("display_addresses_div");
		    output.style.display = 'block';
		    var res = document.getElementById('display_addresses_table_div');
		    res.style.display = 'block';
		    res.innerHTML = results;
	      	  
     
         }
	        
            function calculate_directions_from_info_box(num)
             {
                 
                  var dir_stat = document.getElementById("get_directions_status");
                  dir_stat.style.display = 'block';
         
                   //num = num - 1;
                   source = document.getElementById('source_m' + num );
                   document.getElementById("directions_source").value = source.value
        
                customInfobox.hide();
                //  map.getCredentials(MakeRouteRequest(source)); 
                  if (!directionsManager)

                {
              
                  Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute});

                }

                else

                {

                  createDrivingRoute();

                }
               
             }

            function displaySummaryInfobox(e)
            {
               var pin = e.target;
                if (pin != null) 
                {
                 
                  customInfobox.setOptions({offset: {x:0,y:25}, showCloseButton: false, showPointer: false });
                  renderSummaryInfobox(pin.getLocation(), pin);
                   
                 
                 }
            }
         
          function displayInfobox(e)
            {
               var pin = e.target;
                if (pin != null) 
                {
                   Microsoft.Maps.Events.removeHandler(mouseoutHandler);
                  Microsoft.Maps.Events.removeHandler(mouseoverHandler);
                  map.setView({center: pin.getLocation()});
                  customInfobox.setOptions({ showCloseButton: true, showPointer: true });
                  renderInfobox(pin.getLocation(), pin);
                   
                 
                 }
            }
           
         function renderInfobox(latlong,pin) {
	        if (customInfobox != null) {
	         
	            //Define the layout contents in the infobox
	            var html = [];
                html.push("<div style='padding:10px'>");
     
	            //Add title
	            html.push("<b>", pin.title, "</b><br />");

	            //Add discription
	            html.push(pin.description);

                if(pin.isClustered != true)
                {    
	                 //Add a custom button to zoom to location
	                 html.push("<span style='padding-left:10px;padding-bottom:5px;padding-top:-5px;'><b><a href='javascript:void(0);' onclick='map.setView({zoom : 17, center:new Microsoft.Maps.Location(")
                     html.push(latlong.latitude, ",", latlong.longitude, ")});'>" + go_to_this_location_text + "</a></b></span>");
               
                }
                
               
                
                if( pin.fromClustered == true)
                {
                 html.push("<span style='padding-left:100px;padding-bottom:5px;padding-top:-5px;'><a href='javascript:void(0);' onclick='showClustered()'>");
                 html.push("back to list</a></span>");
                }
                
                 html.push("</div>");
	            

                //Render Infobox
	            customInfobox.show(latlong, html.join(''));
	            set_directions_destination(pin.name,pin.postalcode,latlong.latitude,latlong.longitude);
	            map.setView({center: latlong});
            }
	    }
	    
	     function renderSummaryInfobox(latlong,pin) 
	     {
	        if (customInfobox != null) {
	         
	            //Define the layout contents in the infobox
	            var html = ["<div style='padding:2px'>"];

               if(pin.isClustered != true)
                {  
	             //Add title
	             html.push(pin.shortDescription);

	             
                }
              else
                {
                 html.push(pin.title);
                }
	            html.push("</div>");

                //Render Infobox
	            customInfobox.show(latlong, html.join(''));
//	            set_directions_destination(pin.name,pin.postalcode,latlong.latitude,latlong.longitude);
//	            map.setView({center: latlong, zoom:10});
            }
	    }
	    
            function showClustered()
            {
                          
               var mypin = createClusteredPin(myCluster,myCluster[0]._LatLong);
               mypin.isClustered  = true;
               customInfobox.setOptions({offset: {x:0,y:27} });
               renderInfobox(mypin.getLocation(), mypin);          
               map.setView({center:mypin.getLocation(), zoom: 10});
            }

            function displayInfoBoxLeftMenuClick(GridKey,EntityID, e)
            {
             var pin;
        
              if(GridKey == -1 && myCluster != null)
                  {
                    pin = e.GetDataByGridKey(GridKey,true);
         
                   for(var i =0; i < pin.length; i++)
                   {
                    if(pin[i].EntityID == EntityID)
                    {
                      if(pin.length > 1)
                      {
                       pin[i].fromClustered = true;
                      }
                      else
                      {
                       pin[i].fromClustered = false;
                      }
                      var mypin =   createPin(pin[i]);
                      customInfobox.setOptions({offset: {x:0,y:27} });
                      renderInfobox(mypin.getLocation(), mypin);
                   }
                  }
                 }
                else if(myCluster != null)
                {
                   pin = e.GetDataByGridKey(GridKey,true);
         
                   for(var i =0; i < pin.length; i++)
                   {
                    if(pin[i].EntityID == EntityID)
                    {
                      if(pin.length > 1)
                      {
                       pin[i].fromClustered = true;
                      }
                      else
                      {
                       pin[i].fromClustered = false;
                      }
                      var mypin =   createPin(pin[i]);
                      customInfobox.setOptions({offset: {x:0,y:27} });
                      renderInfobox(mypin.getLocation(), mypin);
                     }
                   }
                }
                else
                {
                   myLayer.SetData(data);
                   pin = e.GetData();
                   for(var i =0; i < pin.length; i++)
                   {
                    if(pin[i].EntityID == EntityID)
                    {
                      pin[i].fromClustered = false;
                      
                      var mypin =   createPin(pin[i]);
                      customInfobox.setOptions({offset: {x:0,y:27} });
                      renderInfobox(mypin.getLocation(), mypin);
                     }  
                   }
               }
               // hide all boxes
                
               
              
                
            }
            
            function displayInfoBoxFromCluster(GridKey,EntityID)
            {
               var pin = myLayer.GetDisplayedData();
                
               for(var i =0; i < pin.length; i++)
               {
                if(pin[i].EntityID == EntityID)
                {
                  pin[i].fromClustered = true;
                  var mypin =   createPin(pin[i]);
                  

                  customInfobox.setOptions({offset: {x:0,y:27} });
                  renderInfobox(mypin.getLocation(), mypin);
                  
                }
               
               }
               // hide all boxes
                
               
              
                
            }
            function hideInfobox(e)
            {
               var pin = e.target;
                if(pin != null)
               {
                 boxes[pin.getText()].setOptions({visible: false });
               }
           }
           function initSearch(search_radius, page_size)
	        {
	        if(current_country_code != 'uk')
	         {
	           distance_unit = 'km';
	         }
	        document.getElementById('geocodestatus').style.display  = 'block';
	        document.getElementById('no_results').style.display = 'none';
	        if(myCluster != null)
	         { 
	          myCluster = null;
	         }
	         
	         //   GetMap();
	         if(directionsManager)
	         { 
	          
	           directionsManager.clearDisplay();
	         }
		        var txt_location;
		        txt_location = document.getElementById('txt_location')
		        show_direction_results(false);
		        if (txt_location != null)
		        {
			        if (txt_location.value == '')
			        {
				        alert(search_text);
			        }
			        else
			        {
			        var geocodeRequest;
			        
			          
			           if(current_country_code == 'uk')
			           {
			            geocodeRequest = geocodeRequestURL + "/REST/v1/Locations/" + current_country_code + "/" +  txt_location.value +  "?ouput=json&jsonp=GeocodeCallback&key=" + myCredentials;
			           }
			           else
			           {
				        //var geocodeRequest = geocodeRequestURL + "/REST/v1/Locations?locality=" + txt_location.value + "&countryRegion=" + current_country_code + "&ouput=json&jsonp=GeocodeCallback&key=" + myCredentials;
				        geocodeRequest = geocodeRequestURL + "/REST/v1/Locations/" + country_name + "/" +  txt_location.value +  "?ouput=json&jsonp=GeocodeCallback&key=" + myCredentials;
				       }
				       
                        CallRestService(geocodeRequest); 

                     
			        }
		        }
	        }
	        
	function show_direction_results(show)
	{
		var get_directions_results = document.getElementById('get_directions_results')
		var directions_print = document.getElementById('directions_print')
		if (show == true)
		{
			get_directions_results.style.display = 'block';
			directions_print.style.display = 'block';
			var dir_stat = document.getElementById("get_directions_status");
              dir_stat.style.display = 'none';
		}
		else if (show == false)
		{
			get_directions_results.style.display = 'none';
			directions_print.style.display = 'none';
		}
	}
	
	function deletePushpin()
      {                   
            myLayer.SetData(null);
       
        
      }
     function showLeftHandMenu()
     {
       if(data != null)
       {
           var output = [];
            var num = 1;
            
		                    
	            for (var i = 0; i < data.length; i++) {
	              num =  i + 1;
	                 // anchor.className = 'rollOverArea';
		                  var address_data = '';
		                     address_data = '<span class="resultsNumber">' + num + '</span>&nbsp;<span class="blueText"><strong>' + data[i].Name + '</strong></span><p></p>';
                		if(current_country_code == 'de')
                		{
                		 address_data = address_data + data[i].AddressLine + "<br/>"
                		        + data[i].PostalCode + "<br/>"
                                + data[i].Locality + "<br/>"
                                + data[i].AdminDistrict + "<br/>"
                                + data[i].Phone + "<br/>";
                		}
                        else
                         {
                        //Display each entity and create a pushpin for the map
                          address_data = address_data + data[i].AddressLine + "<br/>"
                                + data[i].Locality + "<br/>"
                                + data[i].AdminDistrict + "<br/>"
                                + data[i].PostalCode + "<br/>"
                                + data[i].Phone + "<br/>";
                         }            



                                   
                                      var lat,lon;
                                      lat = data[i].Latitude;
                                      lon = data[i].Longitude;
		                               if (distance_unit == 'miles')
			                                address_data += '<b>' + data[i].__Distance.toFixed(2) + ' ' + "miles</b>";
		                                else if (distance_unit == 'km')
			                               address_data += '<b>' + data[i].__Distance.toFixed(2) + ' ' + km_text + '</b>';
                			
		        
                if ((((current_country_code != 'uk') && (current_country_code != 'gg')) && (current_country_code != 'je')) && (current_country_code != 'im'))
		                {
		                 address_data += '<br />';
			            var spacer;
			            spacer = false;
			            if (data[i].mg_rover_all_makes == true)
			            {
				            address_data += '<img src="images/' + icon_xpart_auto_centre_image_name + '" alt="' + mg_rover_all_makes_alt + '" title="' + mg_rover_all_makes_alt + '" />';
				            spacer = true;
			            }
			            if (data[i].new_mini == true)
			            {
				           if (spacer == true)
				           {
				            address_data += '&nbsp;';
				           }
				            address_data += '<img src="images/' + icon_new_mini_image_name + '" alt="' + new_mini_alt + '" title="' + new_mini_alt + '"/>';
				            spacer = true;
			            }
			            if (data[i].mg_rover == true)
			            {
				           if (spacer == true)
				           {
				            address_data += '&nbsp;';
				           }
				            address_data += '<img src="images/' + icon_mg_rover_image_name + '" alt="' + mg_rover_alt + '" title="' + mg_rover_alt + '" />';
			            }            
                                       
                       }                 
	                output.push("<a class='rollOverArea' href='javascript:void(0);' onclick='displayInfoBoxLeftMenuClick(", data[i].GridKey + "," + data[i].EntityID, ",myLayer);'>");
	                output.push(address_data, "</a><br/>");
	            }
           //    output.appendChild(resultsList);
	            document.getElementById("recordListDiv").innerHTML = output.join('');
       }
     
     
     }
     
       function displayEventInfo(e) {
	        if (e.targetType == "pushpin") {
	            ShowInfobox(e.target);
	        }
	    }
	    
     function ShowInfoboxByGridKey(gridKey) {
            var pin = myLayer.GetPinByGridKey(gridKey);
	        ShowInfobox(pin);
	    }
	    
	    function ShowInfobox(pin) {
	    
	     
            customInfobox.setOptions({offset: {x:0,y:25} });
               renderInfobox(pin.getLocation(), pin);


	    }
	
	function closeInfoBox() {
	       customInfobox.hide();
	    }
	    
	    function print_results()
	{
		print_divs('recordListDiv','');
	}
	
	function print_map()
	{
 
	
		print_divs('mapDiv','');
		
	}
	
	function PrintMap(result)
	{
	  var res = result;
	
	}
	
	
	function print_results_and_map()
	{
		print_divs('mapDiv,recordListDiv','');
	}
	
	function print_directions()
	{
		var from_to_text;
		from_to_text = get_from_to_text();
		print_divs('get_directions_results',from_to_text);
	}
	
	function print_directions_and_map()
	{
		var from_to_text;
		from_to_text = get_from_to_text();
		print_divs('mapDirDiv,get_directions_results',from_to_text);
	}
	
	function get_from_to_text()
	{
		var from_to_text;
		from_to_text = '<strong>';
		from_to_text += document.getElementById('from_text').innerHTML + '<br/>';
		from_to_text += document.getElementById('directions_source').value + '<br/>';
		from_to_text += document.getElementById('to_text').innerHTML + ' ';
		from_to_text += document.getElementById('destination_span').innerHTML + '<br/>';
		from_to_text += '</strong><br />';
		return from_to_text;
	}
	
	function print_divs(div_ids, extra_text)
{
	
         
		var div_ids_array = div_ids.split(',');
		var i;
		var new_window = window.open('','','left=0,top=0,width=750,height=750,toolbar=2,scrollbars=1,status=0');
		var div_style_value;
		var height_value;
		height_value = '350px';
		new_window.document.write('<html>\n<head>\n<style>\n a, a:visited{font-family: arial, helvetica, sans-serif !important; text-decoration: none !important; display: block; color: #000 !important;} html, body{font-family: arial, helvetica, sans-serif !important; text-decoration: none !important; display: block;}\n</style>\n </head>\n<body>\n');
		new_window.document.write('<table cellpadding="0" cellspacing="0" border="0" height="100%" width="910px">\n')
		
		if (div_ids_array.length > 1)
		{
			if (div_ids_array[1] == 'get_directions_results')
			{
				height_value = '350px'
			}
		}
		
		for (i = 0 ; i < div_ids_array.length ; i++)
		{		
			if (navigator.appName == 'Netscape')
			{
				if ((div_ids_array[i] == 'mapDiv') && (div_ids_array.length > 1))
				{
					new_window.document.write('<tr><td height="' + height_value + '"></td></tr>');
				}
			}
			
			if (div_ids_array[i] != 'mapDiv')
			{
				if (extra_text != '')
				{
//					new_window.document.write('<tr><td align="left" width="100%">\n');
//					new_window.document.write(extra_text);
//					new_window.document.write('</td></tr>\n');
				}
			}
		
		    
               
			var div_content = document.getElementById(div_ids_array[i]);
			new_window.document.write('<tr><td align="left" width="100%"');
			if (div_ids_array[i] == 'mapDiv')
			{
			    var pin = myLayer.GetDisplayedData();
                var grdKey = '';
                var mypin = []; 
                var grdOldKey = '';
                var index = [];
                var pincount = 0;
                var count = 0;
                for(var j =0; j < pin.length; j++)
                   {

                    grdKey = pin[j].GridKey
                   
                    if(grdKey != grdOldKey)
                     {
                       mypin.push(myLayer.GetPinByGridKey(grdKey));
                       if(mypin[count].isClustered == false)
                       {
                        index.push(pin[j].Index);
                        mypin[count].title = pin[j].Index;
                       }
                       pincount += 1;
                       count += 1;
                     }               
                    grdOldKey = grdKey;
                   }
        			
			
			
				new_window.document.write(' height="513px" ');
				new_window.document.write('>\n');
				new_window.document.write('<div  id="' + div_ids_array[i] + '">\n');
				if(pincount > 0)
				{
				 var pp = '';
				 for(var c =0; c < mypin.length; c++)
				 {
				  if(pp == '')
				  {
				   pp = 'pp=' + mypin[c]._location.latitude + ',' + mypin[c]._location.longitude + ';23;1';
				  }
				  else
				  {
				   if(mypin[c].isClustered == true)
				   {
				   pp += '&pp=' + mypin[c]._location.latitude + ',' + mypin[c]._location.longitude + ';23;';
				   }
				   else
				   {
				    pp += '&pp=' + mypin[c]._location.latitude + ',' + mypin[c]._location.longitude + ';23;' + (c + 1);
				   }
				   
				  }
			
				 }
			     new_window.document.write('<img src="' + geocodeRequestURL + '/REST/V1/Imagery/Map/Road?mapArea=' + map.getBounds().getSouth() + ',' + map.getBounds().getWest() + ',' + map.getBounds().getNorth() + ',' + map.getBounds().getEast() + '&' + pp + '&&mapSize=500,500&format=jpeg&key=' + myCredentials + '" />');
			    }
			    else
			    {
			     new_window.document.write('<img src="' + geocodeRequestURL + '/REST/V1/Imagery/Map/Road?mapArea=' + map.getBounds().getSouth() + ',' + map.getBounds().getWest() + ',' + map.getBounds().getNorth() + ',' + map.getBounds().getEast() + '&&mapSize=500,500&format=jpeg&key=' + myCredentials + '" />');
			    }
			    
			    new_window.document.write('\n</div>');
				
			}
			else if(div_ids_array[i] == 'mapDirDiv')
			{
			  var source;
              source = document.getElementById('directions_source');
        
        
           
              var waypoint1 = document.getElementById('destination_postcode');
       
				new_window.document.write(' height="513px" ');
				new_window.document.write('>\n');
				new_window.document.write('<div  id="' + div_ids_array[i] + '">\n');
			
			  new_window.document.write('<img src="' + geocodeRequestURL + '/REST/V1/Imagery/Map/Road/Routes?wp.0=' + source.value + '&wp.1=' + waypoint1.value + '&&mapSize=500,500&key=' + myCredentials + '" />');
			//  new_window.document.write('<img src="http://dev.virtualearth.net/REST/V1/Imagery/Map/Road/Routes?wp.0=Corby&wp.1=Grimsby&&key=' + myCredentials + '" />');
			  new_window.document.write('\n</div>');
			
			}
			else
			{
			 new_window.document.write('>\n');
			 new_window.document.write('<div  id="' + div_ids_array[i] + '">\n');
			 new_window.document.write(div_content.innerHTML);
			 new_window.document.write('\n</div>');
			 new_window.document.write('\n</td></tr>');
			}
		}
		new_window.document.write('\n</table>')
	    new_window.document.write('\n</body>\n</html>');
		new_window.document.close();
	    new_window.print();
		new_window.close();
	new_window.innerHTML='';
		
	}
	
	function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
function checkVersion()
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 8.0 ) 
      msg = "You're using a recent copy of Internet Explorer."
    else
      msg = "You should upgrade your copy of Internet Explorer.";
  }
  return ver
}
