var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var markers = [];
var infoWindow;
var location_select;
var geocoder;



// DIRECTIONS MAP
//---------------------

function initializeMap() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  geocoder = new google.maps.Geocoder();
  end = ($('#toAddress').attr('value'));
  var myOptions = {
    zoom: 15,
    mapTypeControl: false,
    navigationControl: true,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
      
  if (geocoder) {
    geocoder.geocode( { 'address': end}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map = new google.maps.Map(document.getElementById("map"), myOptions);
        var contentString = '<div id="content">'+
          '<div>'+
          '<h5>Borland-Groover Clinic</h5>'+
          '<h3>'+($('#location_name').html())+'</h3>'+
          '<p>'+($('#toAddress').attr('value'))+'</p>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
        });

        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById("direction_list"));

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
}

function getDirections() {
  start = ($('#fromAddress').attr('value'));
  end = ($('#toAddress').attr('value'));
  url = '#map';

  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      window.location = url;
    }
  });
}

function handleErrors(){
  if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

  else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

  else alert("An unknown error occurred.");
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}



// NEAREST LOCATION MAP
//---------------------

function initializeDistanceMap() {
  map = new google.maps.Map(document.getElementById("distance_map"), {
// jax    center: new google.maps.LatLng(30.250604, -81.585352),
    center: new google.maps.LatLng(28.535631, -81.57486),
    zoom: 7,
    mapTypeId: 'roadmap',
    mapTypeControl: false,
    navigationControl: true,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  infoWindow = new google.maps.InfoWindow();
  
  
  
  
  
  
  
  var searchUrl = '/tools/phpsqlsearch_genxml.php?lat=30.250604&lng=-81.585352&location_type=&radius=500';
  downloadUrl(searchUrl, function(data) {
    var xml = parseXml(data);
    var markerNodes = xml.documentElement.getElementsByTagName("marker");
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markerNodes.length; i++) {
      var name = markerNodes[i].getAttribute("name");
      var location_type = markerNodes[i].getAttribute("location_type");
      var url_title = markerNodes[i].getAttribute("url_title");    
      var address = markerNodes[i].getAttribute("address");
      var distance = parseFloat(markerNodes[i].getAttribute("distance"));
      var latlng = new google.maps.LatLng(
          parseFloat(markerNodes[i].getAttribute("lat")),
          parseFloat(markerNodes[i].getAttribute("lng")));
  
      //createOption(name, location_type, distance, i);
      createMarker(latlng, name, location_type, url_title, address);
    }
  });
  
  
  
  
  
  location_select = document.getElementById("location_select");
  location_select.onchange = function() {
    var markerNum = location_select.options[location_select.selectedIndex].value;
    if (markerNum != "none"){
      google.maps.event.trigger(markers[markerNum], 'click');
    }
  };
  var tabs = document.getElementById('location_tabs');
  google.maps.event.addDomListener(tabs, 'click', refreshMap);
}

function searchLocations() {
  var error_display = document.getElementById("errors");
  var address = document.getElementById("address_input").value;
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({address: address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      error_display.style.display = "none";
      searchLocationsNear(results[0].geometry.location);
    } else {
      if (address == "") {
        error_display.style.display = "block";
        location_select.parentNode.style.display = "none";
        error_display.innerHTML = "Please enter an address to find the nearest location";
      } else {     
        error_display.style.display = "block";
        location_select.parentNode.style.display = "none";
        error_display.innerHTML = address + " not found";
      }
    }
  });
}

function clearLocations() {
  infoWindow.close();
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers.length = 0;

  location_select.innerHTML = "";
  location_select.setAttribute('tabindex', '6');
  var option = document.createElement("option");
  option.value = "none";
  option.innerHTML = "See all locations:";
  location_select.appendChild(option);
  location_select.style.visibility = "visible";
  location_select.parentNode.style.display = "block";
}

function searchLocationsNear(center) {
  clearLocations();

  var location_type_select = document.getElementById('location_type_select').value;
  var radius_select = document.getElementById('radius_select').value;
  var searchUrl = '/tools/phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&location_type=' + location_type_select + '&radius=' + radius_select;
  downloadUrl(searchUrl, function(data) {
  var xml = parseXml(data);
  var markerNodes = xml.documentElement.getElementsByTagName("marker");
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < markerNodes.length; i++) {
    var name = markerNodes[i].getAttribute("name");
    var location_type = markerNodes[i].getAttribute("location_type");
    var url_title = markerNodes[i].getAttribute("url_title");    
    var address = markerNodes[i].getAttribute("address");
    var distance = parseFloat(markerNodes[i].getAttribute("distance"));
    var latlng = new google.maps.LatLng(
        parseFloat(markerNodes[i].getAttribute("lat")),
        parseFloat(markerNodes[i].getAttribute("lng")));

    createOption(name, location_type, distance, i);
    createMarker(latlng, name, location_type, url_title, address);
    bounds.extend(latlng);
  }

  if (bounds == "((57.29577951308232, 180), (-57.29577951308232, -180))") {
    var show_location_type = "";
    var location_select = document.getElementById("location_select");
    var error_display = document.getElementById("errors");
    error_display.style.display = "block";
    location_select.parentNode.style.display = "none";
    if (location_type_select != "") {
      show_location_type = location_type_select + " ";
    }
    error_display.innerHTML = "There are no Borland-Groover Clinic " + show_location_type + "locations within the selected radius. Please try expanding your search radius.";
  }
  else {
    var location_label = document.getElementById("location_label");
    var location_count_plural = "";
    if (markerNodes.length != 1) {
      var location_count_plural = "s";
    }
    location_label.innerHTML = (markerNodes.length) + " Location" + location_count_plural + " in your area:";
    map.fitBounds(bounds);
  }
 });
}

function createMarker(latlng, name, location_type, url_title, address) {
  var show_location_type_for_office = "";
  if (location_type == "office") {
    show_location_type_for_office = " Office";
  }
  var html = "<div class=\"map_marker\"><h3>" + name + show_location_type_for_office + "</h3>" + address + "<br /> <a href=\"/locations/detail/" + url_title + "#map\" title=\"Get directions\">Get directions</a> | <a href=\"/locations/detail/" + url_title + "\" title=\"Learn more about this location\">Learn about this " + location_type + " location </a></div>";
  var marker = new google.maps.Marker({
    map: map,
    position: latlng
  });
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
  markers.push(marker);
}

function createOption(name, location_type, distance, num) {
  var show_location_type_for_office = "";
  if (location_type == "office") {
    show_location_type_for_office = " Office";
  }
  var option = document.createElement("option");
  option.value = num;
  option.innerHTML = name + show_location_type_for_office + " (about " + distance.toFixed(1) + " miles away)";
  location_select.appendChild(option);
}

function downloadUrl(url,callback) {
 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request.responseText, request.status);
   }
 };

 request.open('GET', url, true);
 request.send(null);
}

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
}

function doNothing() {}


// refresh map when clicking on geo tabs

function refreshMap(lat_setting, long_setting, zoom_setting) {
  //map = new google.maps.Map(document.getElementById("distance_map"));
  latlng = new google.maps.LatLng(lat_setting, long_setting); 
  map.setCenter(latlng );
  map.setZoom(zoom_setting);
}

$(document).ready(function() {
 if ($('ul#location_tabs').exists()) {
   $('ul#location_tabs li#location_tab_all').click( function() {
      refreshMap(28.535631, -81.57486, 7);
    });
    $('ul#location_tabs li#location_tab_north_florida').click( function() {
      refreshMap(30.250604, -81.585352, 10);
    });
    $('ul#location_tabs li#location_tab_central_florida').click( function() {
      refreshMap(29.431784, -81.264496, 9);
    });
    $('ul#location_tabs li#location_tab_south_florida').click( function() {
      refreshMap(26.555283, -80.136509, 10);
    });
  }
});

$(document).ready(function(){
  $("input#address_input").keypress(function (e) {
    if (e.which == 13 || e.charCode == 13) {
      searchLocations();
    }
  });
});

$(document).ready(function(){
  $("button#search_locations_button").click(function() {
    searchLocations();
  });
});