


var map = null;
var credentials = "AubQDzAM5Ka6lJHqmitC9AbxRwe8yWnYmZqOuJT5Y2XQH5vOQPrCefXJs31wMdZx" ;
var storesAddress = new Array();
var storesDistance = new Array();
var storesLocationLatitude = new Array();
var storesLocationLongitude = new Array();
var pushpin = new Array(); // = new Array();

var routeshape;
			

var routing = {
  
  route_finder      : null, // setin callRoute()
  $tbody            : null, // set in viewDirectionsFor()
  counter_requested : null, // set in viewDirectionsFor()
  inRoutingState    : false, // used to determine state. set right before external call fired. cleared in timeout timer.
  objAddress 		: {}
};


// route is a global. 

routing.viewDirectionsFor = function(elem){
	
  $('#dir-address-origin').val( $('#map-address').val() );
  $('#dir-country-origin').val(RBK.i18n.retailLocator.countryCode.toUpperCase());
  
  if (RBK.i18n.retailLocator.locale == 'en_US'){RBK.i18n.retailLocator.languageCode = 'us'};
  if (RBK.i18n.retailLocator.locale == 'en_GB'){RBK.i18n.retailLocator.languageCode = 'gb'};
    
  $('#lang-origin').val( RBK.i18n.retailLocator.languageCode  );
   
 
  
  routing.$tbody = $(elem).parents('tbody:first');
  
  $('#oldTbody').removeAttr('id');
  
  $('tr#directions-destination').appendTo(routing.$tbody).show();
  $.scrollTo( '+=' + $('#directions-destination').height() , 500 );
  
  return false;
}

routing.callRoute = function() {
            
        $('#bing-result-error').hide();
            
        var storeIndex = $('#directions-destination').closest('tr').prev().children('td.StoreLocator_Number').text();
        var storeAddress = $('#directions-destination').closest('tr').prev().children('td.StoreLocator_AdressDetails').text();
            
    	$('tr#directions-destination').parent().attr('id','oldTbody');
      
    	$('tr#directions-destination').hide().appendTo('#directions-destination-table tbody'); // move it so we can get it back.
       	$('#geo-error,#error,#timeout-error').hide();
    	$('#mapresults').hide(); 
    
    	var startAddress = $('#dir-address-origin').val() + " " + $('#dir-country-origin').val();
		var address_line = new Array();
		address_line = storeAddress.split(",");
		var destinationAddress = address_line[1] + " " + address_line[2];
		
		var language = $('#lang-origin').val();
					
		routing.language = language;
		
		RouteRestServiceCall(startAddress, destinationAddress, language);
		 
		var ending = storesAddress[storeIndex - 1];
		var starting = $('#dir-address-origin').val();

		objAddress = {};
		objAddress.startAddress = startAddress,
		objAddress.destinationAddress = destinationAddress,
		objAddress.storeAddress = ending,
		objAddress.direction = true;
		
		routing.objAddress = objAddress;
		
		var dirhtml = '<label class="searchPageTextBold">'+RBK.i18n.retailLocator.routeStartLoc+'</label><blockquote style="margin:8px 0px 10px 0px;">' + starting + '</blockquote>' +
		 '<label class="searchPageTextBold">'+RBK.i18n.retailLocator.routeEndLoc+'</label><blockquote style="margin:8px 0px 10px 0px;">' + ending + '</blockquote>';

		$('<div id="dir-summary">').html(dirhtml).prependTo('#search-config');
		$('#map-search').hide();

		$('table#results').hide();            
            
}

function RouteRestServiceCall(startAddress, destinationAddress, language)
{	
	var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + startAddress + "&wp.1=" + destinationAddress + "&c=" + language + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
	CallRestService(routeRequest);
}

function RouteCallback(result) {

	if (result.statusCode == 200 &&
		result &&
		result.resourceSets &&
		result.resourceSets.length > 0 &&
	   	result.resourceSets[0].resources &&
	   	result.resourceSets[0].resources.length > 0) {

		 // Set the map view
		 var bbox = result.resourceSets[0].resources[0].bbox;
		 var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
		 map.setView({ bounds: viewBoundaries});

		 // Draw the route
		 var routeline = result.resourceSets[0].resources[0].routePath.line;
		 var routepoints = new Array();
		 for (var i = 0; i < routeline.coordinates.length; i++) {

			 routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
		 }	 

		 // Draw the route on the map
		 routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
		 map.entities.push(routeshape);
		 
		 //Populating the route table
		 
		 //var route = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems;
		 var route = new Array (); 
		 route = result.resourceSets[0].resources;//.routeLegs[0].itineraryItems;
		 
		 
		 routing.displayStages(route);

		 }
	else if (result.statusCode != 200)
	{
		 $('table#results').show(); 
		 $('#directions-destination').hide();
		 $('#mapresults').show();
		 $('div#dir-summary').remove();
		 $('form#map-search').show();
		 $('#bing-result-error').html(result.statusDescription);
		 $('#bing-result-error').show();
		
	}
	
 }


function CallRestService(request)
{
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", request);
	document.body.appendChild(script);
}

routing.displayStages = function(route) {

	var curr_step = 1;
    
    var container = document.getElementById('routeSteps');

    var summary = '<label class="searchPageTextBold">'+RBK.i18n.retailLocator.routeETT+'</label><blockquote style="margin:8px 0px 10px 0px;">';
    //if (route.duration.days > 0) { summary += route.duration.days + RBK.i18n.retailLocator.routeDays; }
    //if (route.duration.hours > 0) { summary += route.duration.hours + RBK.i18n.retailLocator.routeHours; }
    //if (route.duration.minutes > 0) { 
    var travelTimeinSeconds = route[0].travelDuration;
    var travelTimeinMinutes = Math.ceil(travelTimeinSeconds/60) ;
    summary += travelTimeinMinutes + RBK.i18n.retailLocator.routeMin; 
    //}
    
    //if (RBK.i18n.retailLocator.isKm) {
    if(RBK.i18n.retailLocator.countryCode.toUpperCase() =="US" || RBK.i18n.retailLocator.countryCode.toUpperCase() =="GB")
        summary += RBK.i18n.retailLocator.routeFor + roundNumber(route[0].travelDistance/1.6,2) + ' ' + RBK.i18n.retailLocator.miles;
    else
    	 summary += RBK.i18n.retailLocator.routeFor + roundNumber(route[0].travelDistance,2) + ' ' + RBK.i18n.retailLocator.kilometers;
    // } else { // probably mi
   //     summary += RBK.i18n.retailLocator.routeFor + route[0].travelDistance + ' ' + RBK.i18n.retailLocator.routeMiles;
    //}     
    
    summary += '</blockquote><br/><br/><div ><a href="#" onclick="return routing.reverseDirs();" ><button class="bubblebuttons"><span style="font-size:11px;text-transform:capitalize;">'+RBK.i18n.retailLocator.routeRevDir+'</span></button></a></div>';
   	summary += '<br><br>';
    summary += '<div ><a href="#" onclick="return routing.getOtherDirs();" ><button class="bubblebuttons"><span style="font-size:11px;text-transform:capitalize;">'+RBK.i18n.retailLocator.routeAddRet+'</span></button></a></div>';
        
    $("<div/>").html(summary).appendTo('#dir-summary');
    //var steps = stages[0].steps; // only one stage! hardcoded. stage example here: http://www.multimap.com/share/documentation/api/1.2/demos/routing.htm

    // Now we will display each step instruction within this stage:
    
    
    for (var stepCount=0; stepCount < route[0].routeLegs[0].itineraryItems.length; stepCount++) {
    	
    	// Label the current marker with the step number:
        var text = curr_step;
                       
        // Create a written 'instruction' using the roadname and/ or roadnumber:
        
        var instruction = route[0].routeLegs[0].itineraryItems[stepCount].instruction.text;
        if(RBK.i18n.retailLocator.countryCode.toUpperCase() =="US" || RBK.i18n.retailLocator.countryCode.toUpperCase() =="GB")
        {
        	 var distance = route[0].routeLegs[0].itineraryItems[stepCount].travelDistance;
             distance=distance/1.6;
        }
        else
        var distance = route[0].routeLegs[0].itineraryItems[stepCount].travelDistance;	
        
        var TDcount = document.createElement('td');
        TDcount.innerHTML = curr_step;
        
        var TDinstr = document.createElement('td');
        var TDdist = document.createElement('td');
                     
        TDinstr.innerHTML = instruction;
        TDdist.innerHTML = roundNumber(distance,1);
        var rowTR = document.createElement('tr');
        rowTR.appendChild(TDcount);
        rowTR.appendChild(TDinstr);
        rowTR.appendChild(TDdist);
        document.getElementById('direction-steps-tbody').appendChild(rowTR);
        // Create the step marker, using the instruction and marker text we previously created:
        //routing.createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
       
        ++curr_step;
    }

    $('#direction-steps').show();
    $('#routeSteps').show();
    //$('mapviewer').hide();
      
}

routing.reverseDirs = function(){              
              $('#bing-result-error').hide();
              $('#loading').show();
              $('tbody#direction-steps-tbody').empty();              
              objAddress = routing.objAddress;              
              var startAddress, destinationAddress;
              if (objAddress.direction) {
                        startAddress = objAddress.destinationAddress;
                        dispStartAddress = objAddress.storeAddress;
                        dispDestAddress = destinationAddress = objAddress.startAddress;
              }
              else {
                        dispStartAddress = startAddress = objAddress.startAddress;
                        destinationAddress = objAddress.destinationAddress;
                        dispDestAddress = objAddress.storeAddress;
              }
              
              routing.objAddress.direction = !routing.objAddress.direction;           
              
              $('#dir-summary').remove();              
              map.entities.remove(routeshape);              
              routeshape = {};              
              RouteRestServiceCall(startAddress, destinationAddress, routing.language);              
              $('#loading').hide();
              
              var dirhtml = '<label class="searchPageTextBold">'+RBK.i18n.retailLocator.routeStartLoc+'</label><blockquote style="margin:8px 0px 10px 0px;">' + dispStartAddress + '</blockquote>' +
                         '<label class="searchPageTextBold">'+RBK.i18n.retailLocator.routeEndLoc+'</label><blockquote style="margin:8px 0px 10px 0px;">' + dispDestAddress + '</blockquote>';

              $('<div id="dir-summary">').html(dirhtml).prependTo('#search-config'); 
              return false;
}


routing.getOtherDirs = function(){
	  
	  $('table#results').show(); 
	  $('div#routeSteps').hide();
	  $('tbody#direction-steps-tbody').empty();
	  $('#directions-destination').hide();
	  
	  $('#mapresults').show();
	   
	  $('div#dir-summary').remove();
	  $('form#map-search').show();
	  
	  map.entities.remove(routeshape);

	  //locator.mapviewer.goToPosition ( locator.mapviewer.getAutoScaleLocation( locator.markers ) );  // center the map
	  
	  return false;
}


// onload events
$( function(){
    
  $('#mapviewer').hide();
  $('#mapimage').show();
//  $('#map-country').val( RBK.i18n.retailLocator.countryCode.toUpperCase() ); // set default country
  var SL = RBK.i18n.retailLocator;
  if (SL.languageCode == 'en_us'){SL.languageCode = 'us'};
  if (SL.languageCode == 'en_gb'){SL.languageCode = 'gb'};
  $('#lang').val(SL.languageCode);
  
  $('#directions-destination a.cancel').click(function(){
    $('tr#directions-destination').hide();
  });
  
  
  /* $('#map-country').change(function(){
		   
		   for(var i=0; i<cityBasedSearchCountriesList.length; i++) 
		   {     
			   if (cityBasedSearchCountriesList[i] == $('#map-country').val())
			   {
				   	var loc = document.location.href;
					var modifiedloc =loc.replace(RBK.i18n.retailLocator.countryCode.toUpperCase(),$('#map-country').val());
					document.location.href = modifiedloc;	
			   } 
	   		} 		
  });
  */
  
  
  $('#directions-destination form').submit( function(){
    $('#loading').show();
    
    routing.callRoute();
	$('#loading').hide();
    return false;
  });
  
  $('#directions-destination a.submit').click( function(){
	
    $(this).parents('form:first').submit();
  });
  
});


		/***************************************************************/
		/* Add support for pop-up info boxes.
		/***************************************************************/

		  // InfoBox class
		  function InfoBox(html) 
		  {
			   this.div;  // Container div element
			   this.html = html; // HTML to display inside the infobox 
		  }

		  // Add the infobox div to the page
		  InfoBox.prototype.show = function(e) {
		   if (this.div == undefined) {
				// Create the container div.
				this.div = document.createElement("div");
				this.div.className = "StoreLocator_infobox";
				this.div.innerHTML = this.html;
				var mapDiv = document.getElementById('mapviewer');
				mapDiv.appendChild(this.div);
		   	}

		   // Calculate the pixel position of the pushpin relative to the map control
		   var pinLocation = map.tryLocationToPixel(e.target.getLocation(), Microsoft.Maps.PixelReference.control);
			   // Display the infobox at the correct pixel coordinates
			   this.div.style.left = pinLocation.x + "px";
			   this.div.style.top = pinLocation.y + "px";
			   this.div.style.visibility = "visible";
		  };

		  // Hide the infobox
		  InfoBox.prototype.hide = function(e) {
		   if (this.div != undefined)
			this.div.style.visibility = "hidden";
		  };

		  // Extend the Pushpin class to add an InfoBox object
		  Microsoft.Maps.Pushpin.prototype.setInfoBox = function(infoBox) {
		   if (typeof this.infoBox != undefined && this.infoBox != undefined && this.infoBox != null) {
			this.removeInfoBox();
		   }
		   // Assign the infobox to this pushpin
		   this.infoBox = infoBox;

		   // Add handlers for mouse events
		   this.mouseoverHandler = Microsoft.Maps.Events.addHandler(this, 'mouseover',
			function(e) { infoBox.show(e); }
		   );
		   this.mouseoutHander = Microsoft.Maps.Events.addHandler(this, 'mouseout',
			function(e) { infoBox.hide(e); }
		   );
		  }

		  // Extend the Pushpin class to remove an existing InfoBox object
		  Microsoft.Maps.Pushpin.prototype.removeInfoBox = function() {
		   this.infoBox = null;

		   // Remove handlers for mouse events
		   Microsoft.Maps.Events.removeHandler(this.mouseoverHandler);
		   Microsoft.Maps.Events.removeHandler(this.mouseoutHander);
		  }

		  //***************************************************************/
		  
		  
		  //******************** Round Decimals ********************//
		  
		function roundNumber(num, dec) {
				var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
				return result;
		} 


		 function GetMap()
         {
            $('#mapimage').hide();
			$('#mapviewer').show();
			map = new Microsoft.Maps.Map(document.getElementById("mapviewer"),
										{credentials:credentials,
										mapTypeId:"r", 
										zoom:14,
										enableSearchLogo: false,
										enableClickableLogo : false
										});			
         }

        function getStoreData()
        {
        		
				document.getElementById("loading").style.display='block';    			
				var baseURL = "${contextPath}/${userLocale.country.ISO}";
				if(cityBasedSearchCountry == "true")
				{
					var searchString = encodeURIComponent(document.getElementById("map-city").value);
					
				}
				else
				{
					var searchString = encodeURIComponent(document.getElementById("map-address").value);
				}
				var country = RBK.i18n.retailLocator.countryCode.toUpperCase();
				var radius = document.getElementById("map-radius").value;
				var params = "searchString="+searchString+"&country="+country+"&radius="+radius +"&storeType="+storeType+"&isCitySearch="+cityBasedSearchCountry;
				xmlHttp = getXMLHttpRequest();
				
				var url = baseURL+"/retailLocatorGetStores.do?"+params;
	  			if(xmlHttp)
	  		     {	  		     	
					xmlHttp.open("POST", url, true);
			    	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  				xmlHttp.setRequestHeader("Content-length", params.length);
	  				xmlHttp.setRequestHeader("Connection", "close");
					xmlHttp.onreadystatechange=showStoreFinderTable;
			        xmlHttp.send(params);					
	  		     }
				
	     }
		 
		 function showStoreFinderTable()
		{
			if (xmlHttp.readyState == 4 ){
			
				if(xmlHttp.status == 200) {
					document.getElementById("loading").style.display='none';
					document.getElementById("search-results").style.display='block';
					document.getElementById("mapresults").style.display='block';
					document.getElementById("mapresults").innerHTML=xmlHttp.responseText;
					if(cityBasedSearchCountry != "true"){
						loadStoresData();
						showStoresOnMap();
					}
					
				}
			}
		}
		
		function loadStoresData()
		{
			var iterator;
			var storesTableObject = document.getElementById('results');
			storesAddress = [];
			storesDistance = [];
			storesLocationLatitude = [];
			storesLocationLongitude = [];
			for (iterator=0; iterator<storesTableObject.rows.length; iterator++)
			{
				storesAddress[iterator] = storesTableObject.rows[iterator].cells[1].innerHTML;
				storesDistance[iterator] = storesTableObject.rows[iterator].cells[3].childNodes[0].data;
				storesLocationLatitude[iterator] = storesTableObject.rows[iterator].cells[4].childNodes[0].data;
				storesLocationLongitude[iterator] = storesTableObject.rows[iterator].cells[5].childNodes[0].data;
			}						
		}
		
		
		
		function removePushPins()
		{			
			if (pushpin != null){
				for(var i = 0; i<=pushpin.length-1; i++)
				{
					map.entities.remove(pushpin[i]);					
				}
				pushpin = []; 
			}
		}
		
		
		function showStoresOnMap()
        {
			GetMap();
			removePushPins();
    					
			if (storesAddress &&
				storesLocationLatitude && 
				storesLocationLongitude && 
				storesAddress.length > 0 &&
				storesLocationLatitude.length > 0 &&
                storesLocationLongitude.length > 0)
            {  
				
				// Add a pushpin at the store location
				var i = 0;
				var locations = new Array();
				
				for (i=0; i<= storesLocationLatitude.length -1 ; i++ )
				{
					var pushpinIndex = i + 1+ "";
               		locations[i] = new Microsoft.Maps.Location(storesLocationLatitude[i],storesLocationLongitude[i]);
               		pushpin[i] = new Microsoft.Maps.Pushpin( locations[i], {text: pushpinIndex});
					//pushpin[i].setInfoBox(new InfoBox(storesAddress[i]));
               		if(RBK.i18n.retailLocator.countryCode.toUpperCase() =="US" || RBK.i18n.retailLocator.countryCode.toUpperCase() =="GB")
					pushpin[i].setInfoBox(new InfoBox(storesAddress[i]+"<br><br>"+RBK.i18n.retailLocator.distance+":"+storesDistance[i]+ " " +RBK.i18n.retailLocator.miles));
               		else
               		pushpin[i].setInfoBox(new InfoBox(storesAddress[i]+"<br><br>"+RBK.i18n.retailLocator.distance+":"+storesDistance[i]+ " " + RBK.i18n.retailLocator.kilometers));	
               		map.entities.push(pushpin[i]);
				}
				
				
				if (storesLocationLatitude.length == 1)
				{
					map.setView({center: locations[0]});
				}
				else
				{
					var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(locations);
					map.setView({ bounds: viewBoundaries});
				}
                                
            }
        }	    

		function viewThisStore(storeIndex)
		{
			//removePushPins();
			var location = new Microsoft.Maps.Location(storesLocationLatitude[storeIndex-1],storesLocationLongitude[storeIndex-1]);
			map.setView({center: location});		
			return false;
		}
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * http://plugins.jquery.com/project/scrollto/ 
 * usage: $.scrollTo( '#target-examples', 800, {easing:'elasout'} );
 * or $.scrollTo( '+=100', 500 );
  * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 */
(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


