  
 
  
  
  
  function get_near_locations( point )
  {
  	var params = {start_lat:point.lat(),start_lng:point.lng()};
  	gnl = new Ajax.Request('/locations.php?'+ Object.toQueryString(params), { onSuccess: get_near_locations_success });
  }
  function get_near_locations_success( response, ajx )
  {
  	locList = response.responseJSON;
  	update_loc_list( locList );
  }
  
  function update_loc_list( locs )
  {
  	// console.log('locs', locs);
    var listContainer = $('loc_list_container');
    var loclistHtmls = [];
    
    // bound is used to re-zoom/pan the map.
  	bound = new google.maps.LatLngBounds(startPlacemark.marker.getLatLng(), startPlacemark.marker.getLatLng());
  	
  	
  	for( var storeId in locs )
  	{
  		locs[storeId].iconLetter = iconLetters[locMarkers.length];
  		var loc = Object.clone(locs[storeId]);
  		
  		var icon = new google.maps.Icon(G_DEFAULT_ICON);
		icon.image = 'http://maps.google.com/intl/en_us/mapfiles/marker'+loc.iconLetter+'.png';
		loc.nonselected_img_src = icon.image;
		loc.selected_img_src = 'http://maps.google.com/intl/en_us/mapfiles/marker_green'+loc.iconLetter+'.png';
		
				
		loclistHtmls.push( storeLocTemplate.evaluate(loc) );
		var marker = new google.maps.Marker( new google.maps.LatLng(loc.latitude, loc.longitude), icon );
		marker.storeId = storeId;
		
		// google.maps.Event.addListener(marker, "click", pop_info_window_by_store_id.curry(storeId) );
		google.maps.Event.addListener(marker, "click", select_store_loc_by_id.curry(storeId) );
		
		locMarkers.push(marker);
		theMap.addOverlay(marker);
  		bound.extend(marker.getLatLng());
  	}
  	
  	
  	theMap.setZoom( theMap.getBoundsZoomLevel(bound) );
  	theMap.setCenter( bound.getCenter() );
  	listContainer.update( loclistHtmls.join(storeLocTemplateSeparator) ); 
  	listContainer.select('IMG[src$=.png]').each(fixIEPng);
  	listContainer.observe( 'tb:store_click', update_directions);
  	  	
  	attach_loc_choice_listeners();
  }
  
  function get_store_hours_html( loc )
  {
	  var html = '';
	  if( loc.hours )
	  {
		  var htypes = {DIN:'Dining Room',DRV:'Drive-thru'};
		  for(var loctype in loc.hours)
		  {
			  html += '<div class="hours_type_container"><span class="hours_type">' + htypes[loctype] + '</span>';
			  for(var hourlabel in loc.hours[loctype])
			  {
				  
				  html += '<br /><span class="hours_label">' + hourlabel+ ': </span>';
				  if( loc.hours[loctype][hourlabel].store_open_tm == loc.hours[loctype][hourlabel].store_close_tm )
				  {
					  html += '<span class="hours">Open 24 hours</span>'
				  }
				  else
				  {
					  html += '<span class="hours">' +
					  			format_time(loc.hours[loctype][hourlabel].store_open_tm) + ' - ' +
					  			format_time(loc.hours[loctype][hourlabel].store_close_tm) + '</span>';
				  }
			  }
			  html += '</div>';
		  }
	  }
	  html += '<a href="#" onclick="change_start_loc_from_info_window(this); return false;">Change Start location</a>';
	  return html;
  }
  function format_time( timeString )
  {
	  var timeParts = timeString.split(':');
	  var meridiem = 'am';
	  timeParts[0] = parseInt(timeParts[0],10);
	  if( timeParts[0] > 12 )
	  {
		  timeParts[0] = timeParts[0] - 12;
		  meridiem = 'pm';
	  }
	  else if( timeParts[0] == '00' )
	  {
		  timeParts[0] = '12';
		  meridiem = 'am';
	  }
	  return timeParts[0] + ':' + timeParts[1] + meridiem;
  }
  
  function select_store_loc_by_id(storeId)
  {
  	// console.trace();
  	var chks = $$('input.store_location[value=' +storeId+']' );
  	if( chks.length )
  	{
	  	chks[0].checked = true;
	  	chks[0].fire('tb:store_click');
	  	return true;
	}
	return false;
  }
  
  function hide_marker_by_store_id(storeId)
  {
  	var marker = locMarkers.find(function(m){return m.storeId == storeId});
  	if( marker )
  	{
  		marker.hide();
  	}
  }
  
  function attach_loc_choice_listeners()
  {
  	$$('input.store_location').invoke('observe', 'click', function(){ this.fire('tb:store_click');} );
  }
  function get_current_selected_location_id()
  {
  	var chked = $$('input.store_location:checked');
  	if( !chked.length )
  		return false;
  	else
  		return chked[0].value;
  }
  function update_directions()
  {
  	// console.trace();
  	locMarkers.invoke('show');
  	if( startPlacemark && startPlacemark.marker && !startPlacemark.marker.isHidden() )
  	{
  		startPlacemark.marker.closeInfoWindow();
  		startPlacemark.marker.hide();
  	}
  	var storeId = get_current_selected_location_id();
  	if( !storeId ) return false;
  	
  	enable_custom_start_loc();
  	
  	if( !theDirections )
  	{
  		theDirections = new google.maps.Directions(theMap, $('directions_panel') );
  		
  		list = google.maps.Event.addListener(theDirections, 'addoverlay', directions_added_listener);
  		
  	}
  	
  	
  	
  	var loc = locList[ storeId ];
  	var end = loc.addr_ln_1 + " " + loc.city_nm;
  	if( loc.country_subdiv_cd )
  	{
  		end += ", " + loc.country_subdiv_cd
  	}
  	end += " " + loc.postal_cd;
  	
  	
  	add_new_directions($F('start_loc'), end);
  	hide_marker_by_store_id( storeId );
  }
  
  function enable_custom_start_loc()
  {
	  var startLoc = $('start_loc');
	  if( startLoc.disabled )
	  {
		  startLoc.enable();
		  $('route_btn').enable().observe('click', update_directions);
	  }
  }
  
  function change_start_loc_from_info_window( link )
  {
	  var leftSibling = $(link).previous();
	  // $(link).replace('<form><input class="start_loc" type="text" value="'+$F('start_loc') +'" /><input type="submit" value="update" /></form>');
	  $(link).replace('<form><input class="start_loc" type="text" value="" /><input type="submit" value="update" /></form>');
	  var miniForm = leftSibling.next();
	  // console.log('miniForm', miniForm);
	  miniForm.observe('submit', function(evnt){
		  								Event.stop(evnt); 
	  									$('start_loc').value = $F(this.select('INPUT.start_loc').first());
	  									update_directions();
	  									} );
  }
 
  function pop_info_window_by_store_id( storeId )
  {
	  // console.trace();
	  var marker = locMarkers.find(function(m){return m.storeId == storeId});
	  
	  var time = theDirections.getDuration();
	  var distance = theDirections.getDistance();
	  
	  var html = 'Distance: ' + distance.html + ' (' + time.html + ')';
	  html += '<br />' + get_store_hours_html(locList[storeId]);
	  theMap.openInfoWindow(marker.getPoint(), '<div class="store_info_window">' + html + '</div>' );
  }
 
 function directions_added_listener()
 {
 	var storeId = get_current_selected_location_id();
 	var endImage = 'http://maps.google.com/intl/en_us/mapfiles/marker_green'+locList[storeId].iconLetter+'.png'
 	var endMarker = theDirections.getMarker(1);
 	endMarker.setImage(endImage);
 	toggle_loc_list_icon_selection(storeId);
 	/* var endDirectionMarker = $('directions_panel').select('IMG[src="http://maps.google.com/intl/en_us/mapfiles/icon_greenB.png"]').last();
 	if( endDirectionMarker )
 	{
 		endDirectionMarker.src = endImage;
 	} */
 	pop_info_window_by_store_id(storeId);
 }
 
 function toggle_loc_list_icon_selection( storeId )
 {
 	var non_selected_icon_img = $( 'loc_list_image_ns_' + storeId );
 	var selected_icon_img =  $( 'loc_list_image_s_' + storeId );
 	if( non_selected_icon_img && selected_icon_img)
 	{
 		$('loc_list_container').select('*[id^=loc_list_image_s_]').invoke('hide');
 		$('loc_list_container').select('*[id^=loc_list_image_ns_]').invoke('show');
 		non_selected_icon_img.hide();
 		selected_icon_img.show();
 	}
 }
  	
  function add_new_directions(start, end)
  {
  	var query = "from: " + start + " to: " + end;
  	query = query.replace(/#/, ' ');
  	query = query.replace(/expwy/i, 'expy');
  	// console.log('adding new directions', query);
  	var options = {'preserveViewport':true,
  				   'avoidHighways': $('avoid_highways').checked,
  				   'travelMode': ('car' == $F('travel_mode'))?G_TRAVEL_MODE_DRIVING:G_TRAVEL_MODE_WALKING }
  	// console.log('directions options', options);
    theDirections.load( query, options);
    
    if( !formChangesObserved )
    {
    	formChangesObserved = true;
    	$('avoid_highways').observe('change', update_directions);
    	$('travel_mode').observe('change', update_directions);
    }
    
  }
  
  function geocode_address( address, city, state, zip, callback )
  {
  	if(!window.theGeocoder )
  	{
  		theGeocoder = new google.maps.ClientGeocoder();
  	}
  	var addr = address;
  	
  	// console.info('start address search:"'+ addr+'"');
  	theGeocoder.getLocations(addr, function(placemark){
  	
  		// console.log('placemark', placemark);
  		if( placemark.Status.code != 200 )
  		{
  			alert("Could not find address: " + addr);
  		}
  		else
  		{
  			callback(placemark.Placemark[0]);
  		}
  	} );
  }
  
  function update_start_loc( address )
  {

	$('start_loc').value = address;
  }
  
  function init_plots()
  {
	  $('start_loc_container').show();
  	    // theGeocoder = new google.maps.ClientGeocoder();
	    geocode_address( start_req.address, start_req.city, start_req.state, start_req.zip, function(pm){
						if(!pm || !pm.Point)return false;
						
						 window.startPlacemark = pm;
						 var latlng = new google.maps.LatLng(startPlacemark.Point.coordinates[1], startPlacemark.Point.coordinates[0]);
						 
						 // Start finding the near by stores asyncronously.
					     get_near_locations( latlng );
						 
						 //draw the initial marker
						 theMap.setCenter(latlng, 13);
						 
						 update_start_loc(startPlacemark.address);
						 var icon = new google.maps.Icon(G_DEFAULT_ICON);
						 icon.image = 'http://maps.google.com/intl/en_us/mapfiles/marker_greenA.png';
						 insertPng($('start_loc_img').update('<span>&nbsp;</span>'),icon.image);
						 startPlacemark.marker = new google.maps.Marker( latlng, icon );
						 
						 
						 
						 theMap.addOverlay(startPlacemark.marker);
						 startPlacemark.marker.openInfoWindowHtml("<b>Your Address:</b><br />" + startPlacemark.address +"<br /> Choose a store location from the left to get directions.");

					});
  }

  function fixIEPng( ImgElement )
  {
	  /*@cc_on @*/
	  /*@if (@_jscript_version < 7)
		 var dim = ImgElement.getDimensions();
		 var id = ImgElement.id;
			 
		 var ieImg = ImgElement.insert({after:'<span style="display:'+ImgElement.getStyle('display') + ';width:'+dim.width +'px;height:'+dim.height+'px;">&nbsp;</span>'}).next();
		// var ieImg = ImgElement.insert({after:'<span>&nbsp;</span>'}).next();
		 
		// ieImg.setStyle(style.toObject());
		 ieImg.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + ImgElement.src + '", sizingMethod="scale");';
		 Element.remove(ImgElement);
		 ieImg.id = id;
	  /*@end @*/
  }
  /**
   * sets a png image (works around ie6's inability to handle
   * PNG transparency )
   */
   function insertPng(targetContainer, pngImageUrl) 
   {
	 targetContainer = $(targetContainer);
	 // console.log('applying image: ',  pngImageUrl);
	 // console.log('targetContainer',targetContainer);
	 var img = targetContainer.insert( {top:'<img src="' + pngImageUrl + '" style="visibility:hidden"; />'} ).firstDescendant();
	 var dim = img.getDimensions();
	 // console.log('X:',dim.width, 'Y', dim.height);
	 /*@cc_on @*/
     /*@if (@_jscript_version < 7)
		var ieImg = img.insert({after:'<span style="width:'+dim.width +'px;height:'+dim.height+'px;">&nbsp;</span>'}).next();
		Element.remove(img);
        ieImg.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + pngImageUrl + '", sizingMethod="scale");';
        return;
     /*@end @*/
	 img.setStyle({visibility:'visible'});
     return;
     
   }

