﻿// JScript File
      function getstorelist(URLString,ListXML)
        {
      var text    = URLString;
      var html1   = "";
      var xml     = null;
      var markers = null;
      var inzip   = getzip(text);
      
      if (!(inzip == 'htt')||(inzip == null))
        {
      // Download the store data from the xml and create the html for the infowindow
      GDownloadUrl("storeInfo.xml", function(data, responseCode)
        {
        var status=[];
        status[G_GEO_SUCCESS]            = "Success";
        status[G_GEO_MISSING_ADDRESS]    = "Missing Address";
        status[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address";
        status[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
        status[G_GEO_BAD_KEY]            = "Bad Key";
        status[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
        status[G_GEO_SERVER_ERROR]       = "Server Error";

        var geocoder = new GClientGeocoder();

        // Get the location for the entered zip code.
        geocoder.getLocations(inzip, function(result)
          { 
          if (result.Status.code == G_GEO_SUCCESS) 
            {
            var zipLat = result.Placemark[0].Point.coordinates[1];
            var zipLng = result.Placemark[0].Point.coordinates[0];

            if (zipLat < 72.0 && zipLat > 18.0 && zipLng < -66.0 && zipLng > -180.0)
              { 
              var zipPoint = new GLatLng(zipLat, zipLng);
              if (ListXML == "")
                {
                //alert("ListXML is empty!");
                xml              = GXml.parse(data);
                }
              else
                {
                //alert("ListXML is NOT empty!");
                xml              = GXml.parse(ListXML);	
                }	
              	
              markers          = xml.documentElement.getElementsByTagName("marker");
              var markerlength = markers.length;
              var nearby       = new Array();
              var nearbyPoint  = null;
              var minDist      = -1.0;
              var prevMin      = -1.0;
              var nearbyIndex  = -1;
              var nearbylength = 0;

              var indexed = [markerlength];
              
              //Keep track of already indexed stores 
              for(var loop = 0; loop < markerlength; loop++)
              {
                indexed[loop] = false;
              }
              
              if (markers)
                {
                
                var MAX_STORES_TO_DISPLAY = 5;
                var nStoresToDisplay;
                if(markerlength < MAX_STORES_TO_DISPLAY)
                {
                    nStoresToDisplay = markerlength * 3;
                }
                else
                {
                    nStoresToDisplay = MAX_STORES_TO_DISPLAY * 3;
                }

                // Find the 'nStoresToDisplay' nearest stores to the zip code.
                while (nearbylength < nStoresToDisplay)
                  {
                  for (var loop = 0; loop < markerlength; loop++)
                    {
                    
                    var storeLat = getmarkerflt(markers, "lat", loop);
                    var storeLng = getmarkerflt(markers, "lon", loop);
                    var storePoint = new GLatLng(storeLat, storeLng);
                    var Distance = zipPoint.distanceFrom(storePoint);

                    if (minDist < -0.5 && indexed[loop] == false)
                      {
                      minDist = Distance;
                      nearbyIndex = loop;
                      nearbyPoint = storePoint;
                      }
                    else if (Distance < minDist && Distance > prevMin) 
                      {
                      minDist = Distance;
                      nearbyIndex = loop;
                      nearbyPoint = storePoint;
                      }                      
                    }
                  
                  indexed[nearbyIndex] = true;   
                  nearby[nearbylength]     = nearbyIndex;
                  nearby[nearbylength + 1] = minDist;
                  nearby[nearbylength + 2] = bearing(zipPoint, nearbyPoint);
                  nearbylength = nearby.length;
                  prevMin = minDist;
                  minDist = -1;
                  }

                // List these 6 nearest stores.        
                for (var loop=0; loop<nearbylength; loop =loop+3)
                  {
                  var markerIndex = nearby[loop];
                  var dist        = roundNumber(nearby[loop+1] * 0.000621371192);
                  var direction   = nearby[loop+2];

                  // Variables for html from xml
                  // 10/1/2009 dh - some element names changed with the "new" store list style
                  // http://www.wholefoodsmarket.com/scripts/xml/export.php?style=new
                  var storeName = getmarkerstr(markers, "name",  markerIndex);
                  //var storeAbbr = getmarkerstr(markers, "storeabbr",    markerIndex);
                  var storeAbbr = getmarkerstr(markers, "tlc",    markerIndex);
                  //var address1  = getmarkerstr(markers, "addr1", markerIndex);
                  //var address2  = getmarkerstr(markers, "addr2", markerIndex);
                  var address1  = getmarkerstr(markers, "address", markerIndex);
                  var address2  = getmarkerstr(markers, "address2", markerIndex);
                  var city      = getmarkerstr(markers, "city",  markerIndex);
                  var fullState = getmarkerstr(markers, "state", markerIndex);
                  //var stateAbbr = getmarkerstr(markers, "abbr",  markerIndex);
                  var stateAbbr = getmarkerstr(markers, "state_code",  markerIndex);
                  //var code      = getmarkerstr(markers, "code",  markerIndex);
                  var code      = getmarkerstr(markers, "zipchar",  markerIndex);
                  //var country   = getmarkerstr(markers, "cntry", markerIndex);
                  var country   = getmarkerstr(markers, "country", markerIndex);
                  var phone     = getmarkerstr(markers, "phone", markerIndex);
                  var fax       = getmarkerstr(markers, "fax",   markerIndex);
                  //var url       = getmarkerstr(markers, "url",   markerIndex);
                  var url       = "http://www.wholefoodsmarket.com/stores/" + getmarkerstr(markers, "folder",   markerIndex) + "/index.php";
                  var canorder  = getmarkerstr(markers, "canorder", markerIndex);
                  var orderURL  = getmarkerstr(markers, "orderurl", markerIndex);
                  var region    = getmarkerstr(markers, "region", markerIndex);
                  var hrefStore = "";               
                  
                  if (storeName  != city)
                    {
                    hrefStore = city + "+%28" + storeName + "%29";
                    }
                  else
                    {
                    hrefStore = storeName;
                    }

                  while (fullState.indexOf(' ') != -1) fullState = fullState.replace(" ", "+");
                  while (hrefStore.indexOf(' ') != -1) hrefStore = hrefStore.replace(" ", "%20");

                  if (canorder == "1")
                    {
                      if (orderURL == '{null}') orderURL = "";
                      if (orderURL != "")
                        {
                        html1 += '<tr><td WIDTH="35%"><h3>' + storeName + '</h3></td><td WIDTH="35%">' + dist + ' miles ' + direction + '</td><td WIDTH="30%"><a href="' + orderURL + '" /><img src="images/Choose.gif" alt="' + storeName + '" border="0"></a></td></tr>';
                        }
                      else
                        {
                        html1 += '<tr><td WIDTH="35%"><h3>' + storeName + '</h3></td><td WIDTH="35%">' + dist + ' miles ' + direction + '</td><td WIDTH="30%"><a href="OrderEvent.aspx?StoreID=' + storeAbbr + '" /><img src="images/Choose.gif" alt="' + storeName + '" border="0"></a></td></tr>';
                        }
                    }
                  else
                    {
                    html1 += '<tr><td WIDTH="35%"><h3>' + storeName + '</h3></td><td WIDTH="35%">' + dist + ' miles ' + direction + '</td><td WIDTH="30%">Not yet available.</td></tr>';
                    }
                  if (address1 != '{null}') html1 += '<tr><td>' + address1 + '</td></tr>';
                  if (address2 != '{null}') html1 += '<tr><td>' + address2 + '</td></tr>';

                  if (code == '{null}') code = "";

                  if (country == "UK")
                    {
                    html1 += '<tr><td>' + city + ' ' + code + '</td></tr>';
                    }
                  else
                    {
                    html1 += '<tr><td>' + city + ', ' + stateAbbr + ' ' + code + '</td></tr>';
                    }

                  if (phone != '{null}') html1 += '<tr><td>Phone: ' + phone + '</td></tr>';
                  if (fax   != '{null}') html1 += '<tr><td>Fax: ' + fax + '</td></tr>';
                  if (url   != '{null}')
                    {
                    html1 += '<tr><td><a href="http://www.wholefoodsmarket.com/stores/StoreLocations.html?storeabbr=' + storeAbbr  + '&state=' + fullState + '&city=' + hrefStore + '&searchBtn=Search" target="_blank">View Map</a></td><td><a href="' + url + '" target="blank">More Store Info.</a></td></tr>';
                    }
                  else
                    {
                    html1 += '<tr><td><a href="http://www.wholefoodsmarket.com/stores/StoreLocations.html?storeabbr=' + storeAbbr  + '&state='+ fullState + '&city=' + hrefStore + '&searchBtn=Search" target="_blank">View Map</a></td></tr>';
                    }
                  html1 += '<tr><td></td></tr>';   
                  html1 += '<tr><td></td></tr>';      
                  }
                }
              html1 += '</table>';
              document.getElementById("storediv").innerHTML = '<table width=100%><tr><td colspan="3"><h3>Stores nearest to your Zip Code ' + inzip + ', listed by proximity.</h3></td></tr><tr><td>&nbsp;</td>' + html1;          
              }
            else
              {
              // Point returned by zip code entered isn't latitude/longitude in USA, return to the search page with the error.

              var newURL = 'OrderStart.aspx?error=notfound';
	      window.document.location = newURL;
              }
            }
          else
            {
            // Invalid zip code entered, return to the search page with the error.

            var newURL = 'OrderStart.aspx?error=invalidzip';
	    window.document.location = newURL;
            }
          });
        });
        }	


      // a function to return a string variable from xml.
      function getmarkerstr(myMarkers, tagName, counter)
        {
        var value = "{null}";

        try
          {
          if (myMarkers[counter].getElementsByTagName(tagName)[0])
            {
            if (myMarkers[counter].getElementsByTagName(tagName)[0].firstChild.nodeValue)
              {
              value = myMarkers[counter].getElementsByTagName(tagName)[0].firstChild.nodeValue;
                           
              // Check for five digit zip code missing it's preceeding 0. 
              if (tagName == "code" && value.length == 4)
                {
                value = "0" + value;
                }
                
             while (value.indexOf("\\n") > -1)
                {
                  value = value.substr(0, value.indexOf("\\n")) + "<br>" + value.substr(value.indexOf("\\n") + 2, value.length);
                }
              }
            }
          }
        catch(e)
          {
          alert("error parsing string");
          value = "{null}";
          }
        finally
          {
          return value;
          }
        }

      // A function to return the zip code from the document location string. 
      function getzip(str)
        {
        var returnstr = "";

        try
          {
          theleft   = str.indexOf("zip=") + 4;
          theright  = str.indexOf("&state=");
          returnstr = str.substring(theleft, theright);
          }
        catch(e)
          {
          returnstr = "";
          }
        finally
          {
          return returnstr;
          }
        }
        
      // A function to return a floating point variable from xml
      function getmarkerflt(myMarkers, tagName, counter)
        {
        var value = 0.0;

        try
          {
          if (myMarkers[counter].getElementsByTagName(tagName)[0])
            {
            if (myMarkers[counter].getElementsByTagName(tagName)[0].firstChild.nodeValue)
              {
              value = parseFloat(myMarkers[counter].getElementsByTagName(tagName)[0].firstChild.nodeValue);
              }
            }
          }
        catch(e)
          {
          value = 0;
          }
        finally
          {
          return value;
          }
        }

     // A function to round a number to 2 decimal places.
     function roundNumber(inNumber)
       {
	var rnum = inNumber;
	var rlength = 2; // The number of decimal places to round to.

	if (rnum > 8191 && rnum < 10485)
          {
	  rnum = rnum-5000;
	  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	  }
        else
          {
	  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	  }
	return newnumber;
       }
     
     // A function to derive the bearing between two points.
     function bearing( from, to )
       {
       // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
       // Convert to radians.
       var degreesPerRadian = 180.0 / Math.PI;
       var radiansPerDegree = Math.PI / 180.0;
 
       var lat1 = from.latRadians();
       var lon1 = from.lngRadians();
       var lat2 = to.latRadians();
       var lon2 = to.lngRadians();

       // Compute the angle.
       var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
       if ( angle < 0.0 )
	angle  += Math.PI * 2.0;

       // And convert result to degrees.
       angle = angle * degreesPerRadian;
       angle = angle.toFixed(1);

       var myBearing = "North";

       if (angle < 22.5)
         {
         myBearing = "North";
         }
       else if (angle < 67.5)
         {
         myBearing = "Northeast";
         }
       else if (angle < 112.5)
         {
         myBearing = "East";
         }
       else if (angle < 157.5)
         {
         myBearing = "Southeast";
         }
       else if (angle < 202.5)
         {
         myBearing = "South";
         }
       else if (angle < 247.5)
         {
         myBearing = "Southwest";
         }
       else if (angle < 292.5)
         {
         myBearing = "West";
         }
       else if (angle < 337.5)
         {
         myBearing = "Northwest";
         }
       else
         {
         myBearing = "North";
         }

       return myBearing;       
     }
     }

