// Javascript Behavior for Location screen.
// © MunchAway Systems, Inc.

// =========================
// = Behavior: SelectState =
// =========================
var stateContainers;
var cityContainers;
var stateHeaders;

stateHeaders    = $$('#locationdetails h2')
stateContainers = $$('#locationdetails div.state');
cityContainers  = $$('#locationdetails div.locationdetail');

function hideStates() {
  stateContainers.each(function (e) {e.hide(); });
}
function showStates() {
  $('search_city_box').hide();
  stateHeaders.each(function (e) { e.show(); });

  if (collapseLocations) {
    stateContainers.each(function (e) { e.hide(); });
    cityContainers.each(function (e) { e.hide(); });
  } else {
    stateContainers.each(function (e) { e.show(); });
    cityContainers.each(function (e) { e.show(); });
  }
}

SelectState = Behavior.create({
  onchange: function(e) {
    clearError();
    resetSearchResults();
    var source = Event.element(e);
    if (source.value != undefined && source.value != "") {
      if (!state_city_map) {
        alert("TEMPLATE ISSUE: Verify the index.liquid template {{ subscriber | states_and_cities_map }} must be included.")
        return
      }
      stateHeaders.each(function(e) {e.hide();});
      showState(source.value, true)
    } else {
      showStates();
    }
    return true;
  }
});

function showState(stateId, hideOthers) {
  if (hideOthers) hideStates();
  $('header_'+stateId).show();
  $('state_'+stateId).show();
  $('search_city_box').show();

  var cities = state_city_map[stateId];
  loadCitySelect(cities);

  cityContainers.each(function (e) {e.show(); });

  // only show map markers for locations in selected state
  var state_locations = map_marker_groups[stateId.toLowerCase().replace(/\s/, '_')];
  var locations = $H(state_locations).values().flatten();
  if ($('map_spinner')) $('map_spinner').show();
  window.setTimeout(function() { window.setTimeout(function() { showMapMarkers(locations) }, 1); }, 1);
}

function loadCitySelect(values) {
  var selectElement = $('search_city');
  var options = selectElement.options;
  options.length = 0; //clear current values
  options[0] = new Option("", "");
  for (var i=0, v; v = values[i]; i++) {
    options[i+1] = new Option(v, v);
  }
}

// ========================
// = Behavior: SelectCity =
// ========================
SelectCity = Behavior.create({
  onchange: function(e) {
    clearError();
    resetSearchResults();
    var source = Event.element(e);
    var stateId = $('search_state').value;
    var cityId = $('search_city').value;
    if (cityId != undefined  && cityId != "") {
      this.showCity(stateId, cityId)
    } else {
      this.showCities(stateId);
    }
    return false;
  },
  showCity: function(stateId, cityId) {
    this.hideCities(stateId);
    // using div[id=] instead of div# as stateId can have spaces and div# style selector doesn't work.
    $$('div[id="state_'+stateId+'"] div[city="'+cityId+'"]').each(function (e) {e.show(); });

    // only show map markers for locations in selected state
    var locations = map_marker_groups[stateId.toLowerCase().replace(/\s/, '_')][cityId.toLowerCase().replace(/\s/, '_')];
    if ($('map_spinner')) $('map_spinner').show();
    window.setTimeout(function() { window.setTimeout(function() { showMapMarkers(locations) }, 1); }, 1);
  },
  hideCities: function(stateId) {
    $$('div[id="state_'+stateId+'"] div[city]').each(function (e) {e.hide(); });
  },
  showCities: function(stateId) {
    $$('div[id="state_'+stateId+'"] div[city]').each(function (e) {e.show(); });
  }
});


// ==============================
// = Behavior: SearchPostalCode =
// ==============================
SearchPostalCode = Remote.Form({
  onLoading : function() {
    $('search_postal_code_spinner').show();
  },
  onComplete : function(e) {
    $('search_postal_code_spinner').hide();
    $('search_state').value = "";
    $('search_city_box').hide();
  }
});

function resetSearchResults() {
  $('searchresults').innerHTML = "<h2>Search Results</h2>";
  $('searchresults').hide();
}
function showLocations(location_list) {
  hideStates();
  var processed = {};
  for (var idx = 0, loc; loc = location_list[idx]; idx++) {
    if (!processed[loc.state]) {
      processed[loc.state] = true;
      $('state_'+loc.state).show();               // showState
      $$('div[id="state_'+loc.state+'"] div[city]').each(function (e) {e.hide(); });  // hide cities
    }
    $('location_'+loc.id).show();           // showLocation
  }
}

function numericSort(a, b) {
  return a - b;
}
var balloonTemplate = '<div><dl style="margin:0px"><dd class="description">--DESC--</dd><dd class="address">--ADDRESS1--</dd><dd class="phone">--PHONE1--</dd></dl></div>';

// given a JSON list of locations, clear current markers and add a new marker set
function showMapMarkers(location_list, origin) {
  if ($('map_spinner')) $('map_spinner').show();

  Try.these (
    // HACK : find a better way?
    function() { map.clearOverlays(); },
    function() { map.clearOverlays(); }
  );

  var markers = {};
  var location_distances = {};

  for (var idx = 0, loc; loc = location_list[idx]; idx++) {
    var m = new GMarker(new GLatLng(loc.latitude,loc.longitude),{title: loc.desc})
    m.info_url = '/locations/'+loc.id+';site_details'
    GEvent.addListener(m, "click", function() {
      new Ajax.Request(this.info_url, {method:'get',asynchronous:true, evalScripts:true})
    });

    var balloonContent = balloonTemplate.replace('--DESC--','<div style="color:#333333;">' + loc.desc + '</div>').replace('--ADDRESS1--','<div style="color:#333333;">' + loc.address1 + '</div>').replace('--PHONE1--','<div style="color:#333333;">' + loc.phone1 + '</div>');
    markers['location'+loc.id] = addInfoWindowToMarker(m, balloonContent, {});

    if (loc.distance) {
      location_distances[loc.distance] = loc.id;
      $('distance_from_location_'+loc.id).innerHTML = "distance: "+parseFloat(loc.distance).toFixed(1)+" miles";
    }
  }

  // re-arrange locations based on distance from origin
  var distances = $H(location_distances).keys();
  if (distances.size() > 0) {
    var location_nodes = [];
    distances.sort(numericSort).each(function(d) {
      try { location_nodes.push($('location_'+location_distances[d]).cloneNode(true)); } catch(e) {  }
    });
    hideStates();
    location_nodes.each(function(n) {
      n.innerHTML = n.innerHTML.replace(/top_middle_/g, 'lower_middle_');
      $('searchresults').appendChild(n);
    });
    $('searchresults').show();
  }
  
  if (origin) {
    var o = new GMarker(new GLatLng(origin[0],origin[1]),{title: "You are here", icon: origin_icon});
    markers['origin'] = o;
  }

  mgLocations = new GMarkerGroup(true,[],markers);
  map.addOverlay(mgLocations);
  mgLocations.centerAndZoomOnMarkers();
  // zoom out a bit if there is only one location
  if (idx == 1) {
    var loc = location_list[0];
    map.setCenter(new GLatLng(loc.latitude,loc.longitude), 14);
  }
  if ($('map_spinner')) $('map_spinner').hide();
}

function clearError() {
  $('search_postal_code').removeClassName('error');
  $('address_search_error').hide();
  $('address_search_error').innerHTML = '';
}

function ShowLocationInformation(loc_id){
    map.clearOverlays();
    url = '/locations/' + loc_id + ';site_details';
    new Ajax.Request(url, { 
        method: 'get',
        onSuccess: function(response) {
            new Ajax.Request(url, {asynchronous:true,evalScripts:true,method:'get'});
            mgLocations.showMarker('location'+loc_id);
            loc = locationData(loc_id);
            if (loc)
             var point = new GLatLng(loc.latitude,loc.longitude);
             map.addOverlay(new GMarker(point));
            map.setCenter(new GLatLng(loc.latitude,loc.longitude), 14);
             document.getElementById("site_details").style.display = '';
        },
        onFailure: function(response) {
            alert("Something went wrong while displaying the Location Details!");
        }
    })
}

function ShowLocationDirectionCheckout(loc_lat,loc_long,user_lat,user_long){
   var to = loc_lat + "," + loc_long
   var from = user_lat + "," + user_long
   gdir = new GDirections(map);
   setDirections(from, to, "en_US");
    document.getElementById("map_canvas").style.display = '';
}

function ShowLocationDirection(loc_id, latitude, longitude){
   loc = locationData(loc_id);
            if (loc){
                var to = loc.latitude + "," + loc.longitude
            }
            var from = latitude + "," + longitude
   gdir = new GDirections(map);
   setDirections(from, to, "en_US");
   document.getElementById("site_details").style.display = 'none';
}

 function setDirections(fromAddress, toAddress, locale) {
     map.clearOverlays();
     gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }
ShowLocationMapAndDetails = Behavior.create({
  onclick : function(e) {
    var link = Event.element(e);
    new Ajax.Request(link.href, {asynchronous:true,evalScripts:true,method:'get'});
    var location_id = link.href.split('/').last().split(';').first();
    mgLocations.showMarker('location'+location_id);
    loc = locationData(location_id);
    if (loc)
      map.setCenter(new GLatLng(loc.latitude,loc.longitude), 14);
    Event.stop(e);
  }
});

function locationData(id) {
  for (var state_key in map_marker_groups) {
    for (var city_key in map_marker_groups[state_key]) {
      for (var idx = 0, loc; loc = map_marker_groups[state_key][city_key][idx]; idx++) {
        if (loc.id == id)
          return loc;
      }
    }
  }
  return null;
}

function showAllLocationMarkers() {
  if (!map) {
    setTimeout(showAllLocationMarkers, 1000);
  } else {
    location_list = [];
   
    for (var state_key in map_marker_groups) {
      for (var city_key in map_marker_groups[state_key]) {
        var loc = map_marker_groups[state_key][city_key];
        
        location_list.push(loc);
      }
    }
  
    showMapMarkers(location_list.flatten());
  }
}

function showAllLocationWithCount() {
  if (!map) {
    setTimeout(showAllLocationMarkers, 1000);
  } else {
    var location_lst = [];
     var location;
  
    for (var state_key in map_marker_groups) {
        location_lst = [];
          for (var city_key in map_marker_groups[state_key]) {
            var loc = null;
            location = map_marker_groups[state_key][city_key];
            loc =  map_marker_groups[state_key][city_key];
            location_lst.push(loc);
          }
 
        var newIcon = MapIconMaker.createLabeledMarkerIcon({addStar: false, label: location_lst.flatten().length.toString(), primaryColor: "#00ff00"});
        var m = new GMarker(new GLatLng(location[0].latitude,location[0].longitude), {icon: newIcon})
        var balloonContent = balloonTemplate.replace('--DESC--', '<div style="color:#333333;"><b>Locations in ' + location[0].state +': ' + location_lst.flatten().length).replace('--ADDRESS1--','</b></div><a style="color:#0000FF;" href="/locations/display_locations?order_mode=other&locations_in_state=' + location[0].state + '"><u>View</u></a>'  ).replace('--PHONE1--', '');
       addInfoWindowToMarker(m, balloonContent, {});
      map.addOverlay(m);
    }
  }

}



function clearError() {
  $('search_postal_code').removeClassName('error');
  $('address_search_error').hide();
  $('address_search_error').innerHTML = '';
}

function ShowLocationInformation(loc_id){
    map.clearOverlays();
    url = '/locations/' + loc_id + ';site_details';
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(response) {
            new Ajax.Request(url, {asynchronous:true,evalScripts:true,method:'get'});
            mgLocations.showMarker('location'+loc_id);
            loc = locationData(loc_id);
            if (loc)
             var point = new GLatLng(loc.latitude,loc.longitude);
             map.addOverlay(new GMarker(point));
            map.setCenter(new GLatLng(loc.latitude,loc.longitude), 14);
             document.getElementById("site_details").style.display = '';
        },
        onFailure: function(response) {
            alert("Something went wrong while displaying the Location Details!");
        }
    })
}

function ShowLocationDirectionCheckout(loc_lat,loc_long,user_lat,user_long){
   var to = loc_lat + "," + loc_long
   var from = user_lat + "," + user_long
   gdir = new GDirections(map);
   setDirections(from, to, "en_US");
    document.getElementById("map_canvas").style.display = '';
}

function ShowLocationDirection(loc_id, latitude, longitude){
   loc = locationData(loc_id);
            if (loc){
                var to = loc.latitude + "," + loc.longitude
            }
            var from = latitude + "," + longitude
   gdir = new GDirections(map);
   setDirections(from, to, "en_US");
   document.getElementById("site_details").style.display = 'none';
}

 function setDirections(fromAddress, toAddress, locale) {
     map.clearOverlays();
     gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }
ShowLocationMapAndDetails = Behavior.create({
  onclick : function(e) {
    var link = Event.element(e);
    new Ajax.Request(link.href, {asynchronous:true,evalScripts:true,method:'get'});
    var location_id = link.href.split('/').last().split(';').first();
    mgLocations.showMarker('location'+location_id);
    loc = locationData(location_id);
    if (loc)
      map.setCenter(new GLatLng(loc.latitude,loc.longitude), 14);
    Event.stop(e);
  }
});

function locationData(id) {
  for (var state_key in map_marker_groups) {
    for (var city_key in map_marker_groups[state_key]) {
      for (var idx = 0, loc; loc = map_marker_groups[state_key][city_key][idx]; idx++) {
        if (loc.id == id)
          return loc;
      }
    }
  }
  return null;
}


var mapObserver = {
  timer: null,
  found: false,
  ticks: 0
};

function waitForMap() {
  if (mapObserver.timer) {
    if (map) {
      window.clearInterval(mapObserver.timer);
      onMapLoaded();
    } else {
      mapObserver.ticks += 1;
      if (mapObserver.ticks > 10) {
        window.clearInterval(mapObserver.timer);
        window.map = {}; // alert here?
      }
    }
  } else {
    if (!staticMap) {
      if (!map) {
        mapObserver.timer = window.setInterval(function() { waitForMap() }, 1000);
      } else {
        onMapLoaded();
      }
    }
  }
}

function onMapLoaded() {
 
  if (searchParams) {
    showLocations(queryResults);
    showMapMarkers(queryResults, origin);
  } else {
       if(display_location_count)
           {
               showAllLocationWithCount();
           }
        else
            {
                showAllLocationMarkers();
            }
    
}
}

StateHeader = Behavior.create({
  onclick : function(e) {
    var element = Event.element(e);
    var state_id = element.id.replace('header_', '');
    $('search_state').selectedIndex = $A($('search_state').options).map(function(o) { return o.value }).indexOf(state_id);
    if ($('state_'+state_id).visible()) {
      showStates();
    } else {
      showState(state_id, false);
    }
  }
});


// ====================
// = Add All Behaviors =
// ====================
Event.addBehavior({
  '.sitedetailslink': ShowLocationMapAndDetails,
  '#search_state': SelectState,
  '#search_city': SelectCity,
  '#search_postal_code_form': SearchPostalCode,
  '#locationdetails h2' : StateHeader
});

Event.onReady(function() {


 if(display_all) {
      showStates();
      $('stateAndCitySearchButton').hide();
      $('search_state').value = "" // Clear search_state on page reload as all states are displayed by default
      Event.observe('search_state_and_city_form', 'submit', function(e) {
        return false; // Disable form submission as handled by SelectState and SelectCity
      });
  }
  if (staticMap) {
    window.setTimeout(function() { if ($('map_spinner')) $('map_spinner').hide(); }, 300);
  } else { waitForMap(); }
}); // onReady


function validate_ordermode_selection(){
   if (document.getElementById('delivery').checked == true || document.getElementById('takeout').checked == true ||  document.getElementById('all').checked == true) {
      return true;
   } else {
     alert("Please select from the options");
     return false;
   }
}

function enhanced_search_options(selected_mode,csr_mode) {
    if(selected_mode == 1 || selected_mode == 4 ){
        document.getElementById('takeout').checked = true;
        document.getElementById("user_address").style.display = "";
        document.getElementById("user_address_delivery").style.display = "none";
        document.getElementById("user_address_takeout").style.display = "";
    }else if(selected_mode == 2 || selected_mode == 5 ){
        document.getElementById('delivery').checked = true;
        document.getElementById("user_address").style.display = "";
        document.getElementById("user_address_delivery").style.display = "";
        document.getElementById("user_address_takeout").style.display = "none";
    }else{
      if (csr_mode == 1) {
        document.getElementById('all').checked = false;
      } else {
        document.getElementById('all').checked = true;
      }
    }
}

