//IMPORTANT: To load the correct version of the Google API
google.load("maps", "2");

//IMPORTANT: To initialize the Google API
google.setOnLoadCallback(googleInit);

/* Store locator support */
var map = null;
//var geocoder = new google.maps.ClientGeocoder();
var facility = null;
var address = null;
var html_address = null;
var storesArray = Array();
var streetviewClient = null;
var streetMarker = null;
var panorama = null;
var latlng = null;
var bearing = 0;
var firstPoint = null;
var firstTime = true;
var trafficOverlay = null;   
var trafficShowing = false;
var direction_map = null;
var directions = null;
var streetShowing = false;
var streetTitle = '';

//Google Init
function googleInit() {
    
    geocoder = new google.maps.ClientGeocoder();
    
//  trafficOverlay = new google.maps.TrafficOverlay();
//  streetviewOverlay = new google.maps.StreetviewOverlay();
//  streetviewClient = new GStreetviewClient();
}

function getAddress(address, city, state, postal_code) {
  html_address = address + '<br/>' + city + (city && state ? ', ' : ' ') + state + ' ' + postal_code;
  return address + ' ' + city + ((city && state) ? ', ' : ' ') + state + ' ' + postal_code;
}

function getGoogleMap(facility_name, address, city, state, postal_code) {
  facility = facility_name;
  geocoder.getLatLng(getAddress(address, city, state, postal_code), processGeocodeResults);
  nextDisplayInit();   
       
}

function getGoogleMapMobile(facility_name, address, city, state, postal_code) {
  facility = facility_name;
  geocoder.getLatLng(getAddress(address, city, state, postal_code), processGeocodeResultsMobile);
  nextDisplayInit();
  
}

function getGoogleMapMobile2(facility_name, address, city, state, postal_code) {
  facility = facility_name;
  geocoder.getLatLng(getAddress(address, city, state, postal_code), processGeocodeResultsMobile2);
  nextDisplayInit();
}

function getGoogleMapMobile2ClientPortal(facility_name, address, city, state, postal_code) {
  facility = facility_name;
  geocoder.getLatLng(getAddress(address, city, state, postal_code), processGeocodeResultsMobileClientPortal);
  nextDisplayInit();
}

function getGoogleWidgetLarge(facility_name, address, city, state, postal_code) {
  facility = facility_name;
  geocoder.getLatLng(getAddress(address, city, state, postal_code), processGeocodeResultsWL);
  nextDisplayInit();
}

function processGeocodeResultsWL(point) {
  firstPoint = point;
  if (point) {
    if (!map) {
      $('maps_container').show();
      map = new google.maps.Map2($('map_canvas'),{
             size: new google.maps.Size(500, 250) });
    }
    //Clear any pre-existing markers and sidebar entries
    map.clearOverlays();
    //$('sidebar').innerHTML = '';
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    //Center the map and create a marker for the source address
    map.setCenter(new google.maps.LatLng(point.lat(), point.lng()), getZoomLevelBasedOnRadius('5'));

    //var home_icon = new google.maps.Icon(G_DEFAULT_ICON);
    //home_icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    map.addOverlay(createMarker(point, facility, address, html_address, G_DEFAULT_ICON));

    //map.addControl(new TrafficStreetControl());
    //map.addControl(new ExtMapTypeControl2({showTraffic: true, showTrafficKey: true}));
    //map.addControl(new ExtMapTypeControl({showStreet: true, showStreetKey: true}));
    map.setMapType(G_NORMAL_MAP);

    //Ask for the nearest stores.
    /* new Ajax.Request('http://'+location.host+'/GoogleStoreLocator/calculateNearestStoreDistances', {method: 'get',
                     parameters: 'lat=' + point.latRadians() + '&long=' + point.lngRadians() + '&radius=' + $F('radius') + '&brand=' + $F('brand'),
                     onComplete: function(transport){displayResults(eval(transport.responseText))},
                     onException: function(caller, exc){if (exc){alert(exc)}}
                     });
     */
  } else {
    alert("The location that you specified could not be located.  Please enter a valid address.");
  }
}

function processGeocodeResults(point) {
  firstPoint = point; 
  if (point) {
    if (!map) {
      $('maps_container').show();
      map = new google.maps.Map2($('map_canvas'),{
             //size: new google.maps.Size(300, 130)
             //size: new google.maps.Size(555, 320) 
             //size: new google.maps.Size(200, 200)
             });
      //map.addControl(new google.maps.LargeMapControl());
      //map.addControl(new google.maps.MapTypeControl());
      //map.addControl(new google.maps.ScaleControl());       
    }
    //Clear any pre-existing markers and sidebar entries
    map.clearOverlays();   
    //$('sidebar').innerHTML = '';
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    //Center the map and create a marker for the source address
    map.setCenter(new google.maps.LatLng(point.lat(), point.lng()), getZoomLevelBasedOnRadius('5'));
   
    //var home_icon = new google.maps.Icon(G_DEFAULT_ICON);
    //home_icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    map.addOverlay(createMarker(point, facility, address, html_address, G_DEFAULT_ICON));
   
    //map.addControl(new TrafficStreetControl());
    //map.addControl(new ExtMapTypeControl2({showTraffic: true, showTrafficKey: true}));
    //map.addControl(new ExtMapTypeControl({showStreet: true, showStreetKey: true}));   
    map.setMapType(G_NORMAL_MAP);
    
    //Ask for the nearest stores.   
    /* new Ajax.Request('http://'+location.host+'/GoogleStoreLocator/calculateNearestStoreDistances', {method: 'get',
                     parameters: 'lat=' + point.latRadians() + '&long=' + point.lngRadians() + '&radius=' + $F('radius') + '&brand=' + $F('brand'),
                     onComplete: function(transport){displayResults(eval(transport.responseText))},
                     onException: function(caller, exc){if (exc){alert(exc)}}
                     }); 
     */                 
  } else {
    alert("The location that you specified could not be located.  Please enter a valid address.");
  }      
}

function processGeocodeResultsMobile(point) {
  firstPoint = point;
  if (point) {
    if (!map) {
      $('maps_container').show();
      map = new google.maps.Map2($('map_canvas'),{
             //size: new google.maps.Size(300, 130)
             size: new google.maps.Size(300, 220) });
      //map.addControl(new google.maps.LargeMapControl());
      //map.addControl(new google.maps.MapTypeControl());
      //map.addControl(new google.maps.ScaleControl());
    }
    //Clear any pre-existing markers and sidebar entries
    map.clearOverlays();
    //$('sidebar').innerHTML = '';
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    //Center the map and create a marker for the source address
    map.setCenter(new google.maps.LatLng(point.lat(), point.lng()), getZoomLevelBasedOnRadius('5'));

    //var home_icon = new google.maps.Icon(G_DEFAULT_ICON);
    //home_icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    map.addOverlay(createMarker(point, facility, address, html_address, G_DEFAULT_ICON));

    //map.addControl(new TrafficStreetControl());
    //map.addControl(new ExtMapTypeControl2({showTraffic: true, showTrafficKey: true}));
    //map.addControl(new ExtMapTypeControl({showStreet: true, showStreetKey: true}));
    map.setMapType(G_NORMAL_MAP);

    //Ask for the nearest stores.
    /* new Ajax.Request('http://'+location.host+'/GoogleStoreLocator/calculateNearestStoreDistances', {method: 'get',
                     parameters: 'lat=' + point.latRadians() + '&long=' + point.lngRadians() + '&radius=' + $F('radius') + '&brand=' + $F('brand'),
                     onComplete: function(transport){displayResults(eval(transport.responseText))},
                     onException: function(caller, exc){if (exc){alert(exc)}}
                     });
     */
  } else {
    alert("The location that you specified could not be located.  Please enter a valid address.");
  }
}

function processGeocodeResultsMobileClientPortal(point) {
  firstPoint = point;
  if (point) {
    if (!map) {
      $('maps_container').show();
      map = new google.maps.Map2($('map_canvas'),{
            size: new google.maps.Size(190, 190) });
    }
    //Clear any pre-existing markers and sidebar entries
    map.clearOverlays();
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    map.setCenter(new google.maps.LatLng(point.lat(), point.lng()), getZoomLevelBasedOnRadius('5'));
    map.addOverlay(createMarker(point, facility, address, html_address, G_DEFAULT_ICON));
    map.setMapType(G_NORMAL_MAP);
  } else {
    alert("The location that you specified could not be located.  Please enter a valid address.");
  }
}


function processGeocodeResultsMobile2(point) {
  firstPoint = point;
  if (point) {
    if (!map) {
      $('maps_container').show();
      map = new google.maps.Map2($('map_canvas'),{
             //size: new google.maps.Size(300, 130)
             size: new google.maps.Size(224, 200) });
      //map.addControl(new google.maps.LargeMapControl());
      //map.addControl(new google.maps.MapTypeControl());
      //map.addControl(new google.maps.ScaleControl());
    }
    //Clear any pre-existing markers and sidebar entries
    map.clearOverlays();
    //$('sidebar').innerHTML = '';
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    //Center the map and create a marker for the source address
    map.setCenter(new google.maps.LatLng(point.lat(), point.lng()), getZoomLevelBasedOnRadius('5'));

    //var home_icon = new google.maps.Icon(G_DEFAULT_ICON);
    //home_icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    map.addOverlay(createMarker(point, facility, address, html_address, G_DEFAULT_ICON));

    //map.addControl(new TrafficStreetControl());
    //map.addControl(new ExtMapTypeControl2({showTraffic: true, showTrafficKey: true}));
    //map.addControl(new ExtMapTypeControl({showStreet: true, showStreetKey: true}));
    map.setMapType(G_NORMAL_MAP);

    //Ask for the nearest stores.
    /* new Ajax.Request('http://'+location.host+'/GoogleStoreLocator/calculateNearestStoreDistances', {method: 'get',
                     parameters: 'lat=' + point.latRadians() + '&long=' + point.lngRadians() + '&radius=' + $F('radius') + '&brand=' + $F('brand'),
                     onComplete: function(transport){displayResults(eval(transport.responseText))},
                     onException: function(caller, exc){if (exc){alert(exc)}}
                     });
     */
  } else {
    alert("The location that you specified could not be located.  Please enter a valid address.");
  }
}

//

function displayResults(stores) { 
 log('displayResults'); 
 storesArray = stores;
  para = document.createElement('p');
  para.style.fontSize = '1.10em';
  var msg = '<b>THERE ' + ((stores.length == 1) ? 'IS ' : 'ARE ');
  msg = msg + ((stores.length == 0) ? 'NO' : stores.length);
  msg = msg + ' '+$F('brand') + ' STORE' + ((stores.length == 1) ? '' : 'S') + ' WITHIN ' + $F('radius') + ' MILES OF:</b><br/>';
  msg += $F('address')+' '+$F('city')+' '+$F('stateProvince')+', '+$F('postalCode');
  para.innerHTML = msg;
  $('sidebar').appendChild(para);
 
  stores.each(function (store){
              var point = new google.maps.LatLng(store.latitude, store.longitude);
             var store_address = getAddress(store.addressLine1, null, store.city, store.stateCode, store.postalCode);
             var formatted_store_address = getHTMLFormattedAddress(store.addressLine1, store.addressLine2, store.city, store.stateCode, store.postalCode);
            
             //Create a marker on the map for this store
             marker = createMarker(point, store.name, store_address, formatted_store_address);
             map.addOverlay(marker);
            
             //Create an enty in the sidebar for this store
             $('sidebar').appendChild(createSidebarEntry(marker, store.name, store.addressLine1,
                                                         store.city, store.stateCode, store.postalCode, store.distanceFromOrigin,
                                                         store.hours, store.storeId, store.phone, store.monFriHrs, store.satHrs, store.sunHrs));
             var rule = document.createElement('hr');
             rule.style.width = '95%';                            
             $('sidebar').appendChild(rule);                            
             });
}

function getZoomLevelBasedOnRadius(radius) {
 log('getZoomLevelBasedOnRadius');
  switch (radius) {
  case '5': return 15;
  case '10': return 12;
  case '30': return 11;
  case '60': return 10;
  case '100': return 9;
  };
}

function createMarker(point, name, address, formattedAddress, customIcon) {
  log('createMarker');
  var markerOptions = customIcon ? {icon: customIcon} : {};
  var marker = new google.maps.Marker(point, markerOptions); 
  var html = '<b>' + name + '</b><br/>' + formattedAddress + '<br/>';
  //WG - No driving directions for now
  //html += getDrivingDirectionsLink(address);
  //html += getDrivingDirectionsLink(getAddress(address));
  //html += showDrivingDirections(address);
  google.maps.Event.addListener(marker, 'click', function(){
                                marker.openInfoWindowHtml(html);
                               });
 
  return marker;
}

function createSidebarEntry(marker, name, address, city, state, postalCode, distance, hours, storeId, phone, monFriHrs, satHrs, sunHrs) {
 log('createSidebarEntry');
  if (monFriHrs == 0) monFriHrs = "N/A";
  if (satHrs == 0) satHrs = "N/A";
  if (sunHrs == 0) sunHrs = "N/A";
  var div = document.createElement('div');
  var div1 = div.appendChild(document.createElement('div'));
  var html = '<b>' + name + '</b> (' + new Number(distance).toFixed(1) + ' miles)<br/>' + address + '<br/>'
  + city + ', ' + state + '<br/>' + hours;
  var location = '<b>' + name + '</b> (' + new Number(distance).toFixed(1) + ' miles)<br/>' + address + '<br/>'
  + city + ', ' + state + ' ' + postalCode + '<br>'+phone;
  var storeInfo = "<b>Open:</b>&nbsp;M-F:&nbsp;"+monFriHrs+"<br>SAT:&nbsp;&nbsp;"+satHrs+"<br>SUN:&nbsp;"+sunHrs;
  storeInfo += "<br><b>Store&nbsp;ID:</b>&nbsp;"+storeId+"<br><b>Retail&nbsp;Sales&nbsp;Available</b><br><b>Tuxedo&nbsp;Rental&nbsp;Available</b>";
  html = "<table width='100%'><tr><td align='left' valign='top'>"+location+"</td><td align='right' valign='top'>"+storeInfo+"</td></tr></table>";
  div1.innerHTML = html;
  div1.style.cursor = 'pointer';
 
  google.maps.Event.addDomListener(div1, 'click', function(){
                                   google.maps.Event.trigger(marker, 'click');
                                  });
                                 
  google.maps.Event.addDomListener(div1, 'mouseover', function(){
                                   google.maps.Event.trigger(marker, 'click');
                                  });
 
  google.maps.Event.addDomListener(div1, 'mouseover', function(){
                                   div1.style.backgroundColor = '#eee';
                                  });
 
  google.maps.Event.addDomListener(div1, 'mouseout', function(){
                                   div1.style.backgroundColor = '#fff';
                                  });
 
  var div2 = div.appendChild(document.createElement('div'));
  div2.innerHTML = getDrivingDirectionsLink(getAddress(address, null, city, state, postalCode));
  div2.style.margin = '15px 0 5px 0';    
 
  return div;
}
//
function nextDisplayInit(){ 
 trafficShowing = false;
 direction_map = null;
 directions = null;
 streetShowing = false;
 firstTime = true;
 streetMarker = null;
}
//
function initializeTraffic() {
 log('initializeTraffic');
  if (trafficShowing) {
    direction_map.addOverlay(trafficOverlay);
    $('traffic_link').innerHTML = "Hide traffic information";
    trafficShowing = true;
  };
}
//
function toggletraffic(){
 log('toggletraffic');
  if (trafficShowing) {
    map.removeOverlay(trafficOverlay);
    trafficShowing = false;
  } else {
   map.addOverlay(trafficOverlay);
   trafficShowing = true;
 };
}
//
function togglestreet() {
 log('togglestreet');
  if (streetShowing) {
    map.removeOverlay(streetviewOverlay);         
    streetShowing = false;    
  } else {   
    streetShowing = true;   
    var pano = new google.maps.StreetviewPanorama(document.getElementById("panDiv"));   
    GEvent.addListener(pano, "error", handleNoFlash);
    map.addOverlay(streetviewOverlay);
    GEvent.addListener(map,"click", function(overlay,latlng){
                       pano.setLocationAndPOV(latlng);});
         
    createStreetMarker();
  };
}
//
function createStreetMarker() {
 log('createStreetMarker');
 var len = storesArray.length;
 log('array length'+len);
 latlng = new google.maps.LatLng(storesArray[0].latitude, storesArray[0].longitude);
 log('createStreetMarker' + latlng);
 updateMarker(); 
 } 
//
function updateMarker() {
 log('updateMarker');
 if (!streetMarker) {
   // Create Street View Marker (Once only)
   var icon = new GIcon();
   var imageNum = Math.round(bearing/22.5) % 16;
   var imageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + imageNum + ".png";
   icon.image = imageUrl;
   icon.iconSize = new GSize(49,52);
   icon.iconAnchor =  new GPoint(25,36);
   icon.infoWindowAnchor = new GPoint(25,6);
   streetMarker = new GMarker(latlng, {"icon":icon, "draggable":true});
   GEvent.addListener(streetMarker, "dragstart", function() {
                        map.closeInfoWindow();
                      }
                     );
   GEvent.addListener(streetMarker, "dragend", function() {
                        latlng = streetMarker.getPoint();
                        initPanorama(latlng);
                      }
                     );
   GEvent.addListener(streetMarker, "click", function() {
                        displayStreetInfoWindow();
                      }
                     );
   map.addOverlay(streetMarker);
   if (!firstTime) {
     displayStreetInfoWindow();     
   }
   firstTime = false;
 } else {
   // Update Street View Title
   var titleDiv = eID("titleDiv");
   log('updateMarker305:'+ latlng);
   if (titleDiv) {
     titleDiv.innerHTML = streetTitle;
   }
   // update marker image
   var imageNum = Math.round(bearing/22.5) % 16;
   var imageUrl = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + imageNum + ".png";
   streetMarker.setImage(imageUrl);
   // update marker location
   streetMarker.setPoint(latlng);
  
   // move info window to current marker location
   //This caused a BFP
   // map.getInfoWindow().reposition(latlng, new GSize(0,-30));  
 }
}
// find nearest panorama
function initPanorama(point) { 
  log('initPanorama' + point);
  map.closeInfoWindow();
  streetviewClient.getNearestPanorama(point, initPanorama2);
}
//
function initPanorama2(param) {
  log('initPanorama2');
  // validate new location
  var valid = true;
  if (param == null) {
      valid = false;
  } else {
      var location = param.location;
      if (location == null) {
          valid = false;
      }
  }
  if (!valid) {
      // No Street View Available
      streetTitle = "";
      return;
  }
  // store streetview location and title
  latlng = location.latlng;
  streetTitle = location.description;
  updateMarker();
  displayStreetInfoWindow();
}
//Display popup window
function displayStreetInfoWindow() {
 log('displayStreetInfoWindow');
 var smallStreetviewWidth = 400;
  var smallStreetviewHeight = 200;
  streetviewWidth = smallStreetviewWidth;
  streetviewHeight = smallStreetviewHeight;
  var html = "";  
 
  if (streetTitle == "") {
    html = "Street View Unavailable";
  } else {
      html =
      "<table cellspacing=0 cellpadding=0 style='width:" + streetviewWidth + "px'><tr style='height:24px'><td style='width:" + (streetviewWidth-100) + "px'>" +
      "<div id='titleDiv' style='font-weight:bold'>" + streetTitle + "</div>" +
      "</td><td align=right style='width:100px'>" +
      "<div id='sizeDiv'>" + "</div>" +
      "</td></tr><tr><td colspan='2' align='center'>" +
      "<div id='panDiv' style='width:" + streetviewWidth + "px;height:" + streetviewHeight + "px' ></div>" +
      "</td></tr></table>";
  }
  // NOTE: neither open infowindow function below opens a correct size info window
  // maximum size apppears to be 670px
  streetMarker.openInfoWindowHtml(html, {"maxWidth":1000});
  //marker.openInfoWindowHtml(html);
  // delay loading panorama until info window is visible
  setTimeout("displayStreetInfoWindow2()", 500);
}
//
function displayStreetInfoWindow2() {
 log('displayStreetInfoWindow2');
 var panDiv = eID("panDiv");
 panorama = new GStreetviewPanorama(panDiv);
 log('displayStreetInfoWindow2 made it2' + latlng + bearing);
 panorama.setLocationAndPOV(latlng, {"yaw":bearing});
 // listen for changes in bearing and latlng and update marker accordingly
 
 GEvent.addListener(panorama,"yawchanged",function(a)
      {
         bearing = parseFloat(a);
         updateMarker();
      });
 
 GEvent.addListener(panorama,"initialized",function(a)
      {
         latlng = a.latlng;
         streetTitle = a.description;
         updateMarker();
      });
 log('displayStreetInfoWindow2 the end');
}
//
function eID(id) {
 log('eID');
 return document.getElementById(id);
}
//       
function log(data) {
  //GLog.write(data);
}
//
function showStreetViewTrafficButtons(){
 log('showStreetviewTrafficButtons');
  //document.getElementById('toggleTraffic').style.display='block';
  //document.getElementById('toggleStreet').style.display='block';
  return true;
}
//
function handleNoFlash(errorCode) {
 log('handleNoFlash' + errorCode);
  if (errorCode == 603) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
} 
//
function getDrivingDirections(queryParamString) {
 log('getDrivingDirections');
  theParams = queryParamString.toQueryParams();
  from = theParams['home_address'];
  to = theParams['store_address'];
 
  direction_map = new google.maps.Map2($('directions_map'),{size: new google.maps.Size(425, 400)});
  direction_map.addControl(new google.maps.LargeMapControl());
  direction_map.addControl(new google.maps.MapTypeControl());
  direction_map.addControl(new google.maps.ScaleControl());                  
  directions = new google.maps.Directions(direction_map, $('directions_text'));      
  directions.load("from: " + from + " to: " + to);
 
  initializeTraffic();
}
//
function showDrivingDirections(address) {
 log('showDrivingDirecetions');
  queryString = '?home_address=' + escape(home_address) + '&store_address=' + escape(address);
  directionsWindow = window.open('directions.jsp' + queryString, 'directions_window',
                                 'height=600, width=925, resizable=yes, scrollbars=yes, top=100, titlebar=no', true);            
}
//
function getDrivingDirectionsLink(address) {
 log('getDrivingDirectionsLink');
  return '<a href="#" onclick="showDrivingDirections(\'' + address + '\')\; return false;">Get driving directions to this facility<a>';
}


