// Create global map variables
var map = null;
var geocoder = null;

// Setup icons
var icon = new GIcon(G_DEFAULT_ICON);
var arrowIcon = new GIcon(G_DEFAULT_ICON);
arrowIcon.image = arrowIconImage;
arrowIcon.shadow = arrowIconShadow;
arrowIcon.iconSize = new GSize(arrowIconHeight,arrowIconWidth);
arrowIcon.shadowSize = new GSize(arrowIconHeight,arrowIconWidth);
arrowMarker = { icon:arrowIcon };

/**
 * Draws the google map.
 */
function initializeMap() {
  map = new GMap2(document.getElementById("map-canvas"));
  map.setUIToDefault();

  geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode("US");
}
/**
 * This function gets the long and latitude of typed in location and then runs
 * the storeLocatorFunction.
 */
function storeLocator() {
	 if (searchTerm == 'nosearch') {
		 $('#store-info').html("<p class=\"store_location\">" + enterSearchLabel + "<\p>");
	 } else {
		 geocoder.getLocations(searchTerm, storeLocatorFunction);
	 }
}
/**
 * This function will compare the distance between the entered location and the
 * complete lists of stores. It will mark and display the stores that fall within the defined
 * max distance.
 */
function storeLocatorFunction(response) {

  if (!response || response.Status.code != 200) {
    // See if error div exists; if not, create it
    $('.locatorForm').prepend("<div class=\"errorMessage\">Please enter a valid address.</div>");

    // set map to US center
    map.setCenter(new GLatLng(39.83, -97.42), 3);
  } else {
    place = response.Placemark[0];
    searchPoint = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    marker = new GMarker(searchPoint, arrowMarker);
    map.addOverlay(marker);
    if (parseInt(distance) < 35) {
      map.setCenter(searchPoint,9);
    } else if (parseInt(distance) < 65) {
      map.setCenter(searchPoint,8);
    } else if (parseInt(distance) < 130) {
      map.setCenter(searchPoint,7);
    } else {
      map.setCenter(searchPoint,6);
    }
    var innerHtml = "";

    var retailStores = new Array();

    // calculate and store all distances to use for sorting
    for (var i in storeList) {

      var store = storeList[i];
      if (store["posn"][0] != 0 || store["posn"][1] != 0) {
        var storePosn = new GLatLng(store["posn"][0], store["posn"][1]);
        storeDistance = calculateDistance(searchPoint,storePosn);

        // only stores within limit need to be sorted
        if (parseInt(storeDistance) <= parseInt(distance)) {
          store["distance"] = storeDistance;
          store["latlng"] = storePosn;
          retailStores.push(store);
        }
      }
    }
    // ensure there are results before continuing
    if (retailStores.length > 0) {
      // sort remaining stores by distance
      retailStores = retailStores.sort(distanceSort);

      var count = 0;
      var divOpen = false;

      var letter = "A";

      do {
          store = retailStores.shift();
          count++;
          addMarker(store,letter);
          innerHtml += buildStoreHeader(letter);
          innerHtml += addStoreHTML(store,letter);
          letter = nextLetter(letter);
        } while(count < maxSeachResults && retailStores.length > 0)

    }
    else {
            innerHtml = "<p class=\"store_location\">" + noResultsFoundLabel + "<\p>";

    }
    $('#store-info').html(innerHtml);
  }
}

function buildStoreHeader(letter) {
    var image = letteredMarkerPrefix + letter + letteredMarkerExt;
    var header="";
    header+="<table cellspacing=\"0\" class=\"storeLocations\">";
    header+="<thead>";
    header+="<tr>";
    header+="<th class=\"store_location\"><img src=\""+image+"\"/>Store Location</th>";
    header+="<th class=\"distance\">Distance</th>";
    header+="<th class=\"store_hours\">Store Hours</th>";
    header+="</tr>";
    header+="</thead>";
    return header;
}
function addStoreHTML(store,letter) {
    var storeHTML = "";
    storeHTML += "<tbody>";
    storeHTML += "<tr>";
    storeHTML += "<td class=\"store_location\">";
    storeHTML += "<h4>"+store["city"]+", "+store["state"]+" "+store["number"]+"</h4>";
    storeHTML += "<p>"+store["addr1"]+"</p>";
    if (store["addr2"]!='&nbsp;') {
    	storeHTML += "<p>"+store["addr2"]+"</p>";
    }
    storeHTML += "<p>"+store["city"]+"</p>";
    storeHTML += "<p>"+store["state"]+" "+store["zip"]+"</p>";
    storeHTML += "<p>"+store["phone"]+"</p>";
    storeHTML += "<p>"+store["fax"]+"</p>";
    storeHTML += "<p><a target=\"_blank\" href=\""+mapDDLink(store)+"\">Driving Directions & Map</a></p>";
    storeHTML += "</td>";
    storeHTML += "<td class=\"distance\">";
    storeHTML += "<p>"+store["distance"]+" miles</p>";
    storeHTML += "</td>";
    storeHTML += "<td class=\"store_hours\">";
    storeHTML += "<p>"+store["hoursMF"]+"</p>";
    storeHTML += "<p>"+store["hoursSat"]+"</p>";
    storeHTML += "<p>"+store["hoursSun"]+"</p>";
    storeHTML += "</td>";
    storeHTML += "</tr>";
    storeHTML += "</tbody>";
    storeHTML += "</table>";
    return storeHTML;
}
/**
 * Calculate distance between two lat/longs.
 */
function calculateDistance(location1, location2) {
  try {
    return location1.distanceFrom(location2,3959).toFixed(2);
  }
  catch (error) {
  }
}
/*
 * Sort distances.
 */
function distanceSort(a,b) {
 return a["distance"] - b["distance"];
}
/**
 * Gets next letter for marker.
 */
function nextLetter(letter) {
  return String.fromCharCode(letter.charCodeAt(0) + 1);
}

/**
 * Returns a link to google maps that brings up driving directions map.
 */
function mapDDLink(store) {
  return directionsPrefix+store["geo"]+"&z="+calcDDZoom(distance);
}

/**
 * Calculate zoom level.
 */
function calcDDZoom(distance) {
  return String(12 - Math.floor((parseInt(distance)/26)));
}
/**
 * Add store marker to map.
 */
function addMarker(store,letter) {
  icon.image = letteredMarkerPrefix + letter + letteredMarkerExt;
  letteredMarker = { icon: icon };

  marker = new GMarker(store["latlng"], letteredMarker);
  marker.ID = store["ID"];
  map.addOverlay(marker);

  //GEvent.addListener(marker, "click", function () { storeDetails(this.ID); });
}
/**
 * Function called when store marker is clicked.
 */
function storeDetails(id) {

}
