﻿// Global Variables
var Map = null;
var StopUpdate = false;
var HitCount = 0;
var ReZoom = false;
var AddCount = 0;
var SelectedID = "";
var CurAddress = "";
var ClubList = new Array();
var MainCount = 0;
var IsDefaultSelect = false;

// Run when Document Ready
$(document).ready(function() {

    // Pull value from URL into textbox
    var il = document.location.toString().indexOf("/search/");
    if (il > 0 && (il + 8) < document.location.toString().length) {
        document.getElementById('searchloc').value = decodeurl(trim(unescape(document.location.toString()).substring(il + 8, document.location.toString().length)));
    }

    // Initialize the Map

    Map = new VEMap('themap');
    Map.LoadMap(StartLat, 10, 'r', false);

    // Attach to Events
    Map.AttachEvent("onendpan", UpdateLocations);
    Map.AttachEvent("onendzoom", CancelZoomIn);

    // Perform Initial Search
    if (document.getElementById('searchloc').value) {
        ReZoom = true;
        Map.Find(null, LocationReplace(document.getElementById('searchloc').value) + BaseCountry, null, null, null, null, null, null, false, true, UpdateLocations);

        // Safari Shim
        if ($.browser.safari) {
            setTimeout('UpdateLocations()', 1000);
        }
    }
    else {
        Map.SetZoomLevel(4);
        //        // Find "Best Guess" location based on IP
        //        var s = document.createElement('script');
        //        s.src = "http://maps.live.com/WiFiIPService/locate.ashx";
        //        document.body.appendChild(s);
        //        ReZoom = true;
        //        
        //        // Safari Shim
        //        if($.browser.safari)
        //        {
        //            setTimeout('UpdateLocations()', 1000);        
        //        }
    }


    $('#searchloc').keyup(function(e) {
        if (e.keyCode == 13) {
            if (document.getElementById('searchloc').value) {
                ReZoom = true;
                Map.Find(null, LocationReplace(document.getElementById('searchloc').value) + BaseCountry, null, null, null, null, null, null, false, true, UpdateLocations);
            }

        }
    });
});

function LocationReplace(loc)
{
    if(loc.toLowerCase() == 'walker, la' || loc.toLowerCase() == 'walker la')
    {
        return '70785';
    }
    else
    {
        return loc;
    }
}

// Set Zoom Limits
function CancelZoomIn()
{
    var z = Map.GetZoomLevel();
    if(z>18)
    {
        Map.SetZoomLevel(18);
    }
    else if (z< 2)
    {
        Map.SetZoomLevel(9);
    }
}
        
        
// Start New Search        
function NewSearch()
{
     if (document.getElementById('searchloc').value)
     {
        ReZoom = true;
        Map.Find(null, LocationReplace(document.getElementById('searchloc').value) + BaseCountry, null, null, null, null, null, null, false, true, UpdateLocations);
        
     }        
}

// Update Screen after VE Returns Data    
function UpdateLocations()
{
    if(StopUpdate == false)
    {
        var center = Map.GetCenter();
         
        if (ReZoom == true)
        {
            Map.SetZoomLevel(13);
        }
               
        ShowMessage();
        $("#message").html("<img src=\"content/images/ajax-loader.gif\" alt=\"\" style=\"vertical-align: middle;\" height=\"24\" width=\"24\" />Loading nearby Anytime Fitness locations, please wait...");
    
        if(center)
        {
            // Search ATF Locations
            $.post("locate/find", { latitude: center.Latitude.toString(),
                longitude: center.Longitude.toString()
            }, function(xml) {
                // format and output result
                if (xml.toString().length > 50) {
                    AddCount = 0;
                    MainCount = 0;
                    //Map.Clear();
                    ClearMapWorkAround();


                    ClubList = new Array();
                    $("#otherclubs").html("<span style=\"font-size: 13px; font-weight: bold; color: #4d1d77;\">Other Clubs :</span>");
                    $("#comingsoon").html("<span style=\"font-size: 13px; font-weight: bold; color: #4d1d77;\">Coming Soon :</span>");
                    $("#otherclubs").hide();
                    $("#comingsoon").hide();
                    $("#mapresults").html("<script>" + xml + "</scr" + "ipt>");

                    setTimeout('HideMessage()', 2050);
                }
                else {
                    $("#message").html("No Anytime Fitness locations found nearby.");
                    setTimeout('HideMessage()', 2050);
                }

            });
         }
     }
     
     StopUpdate = false;
 }
 
 

 function ClearMapWorkAround() {

     Map.DeleteAllShapes();

     Map.DeleteRoute();

     Map.DeleteAllShapeLayers();

 }   
 
 
 
 
    
// Setup Hover CSS
function HoverSetup()
{
    $("#mapresults").children("div").hover(function() 
    {
        $(this).removeClass("maphoveroptionoff");         
        $(this).addClass("maphoveroption");
        
    }, function()
       {
           if($(this).attr("id") != SelectedID)
           {
               $(this).removeClass("maphoveroption");        
               $(this).addClass("maphoveroptionoff"); 
           }
       }
    );
        
    $("#mapresults").children("div").bind("click", function()
    {
        var s = $(this).attr("id");
        SelectClub(s);
    });
        
    $("#otherclubs").children("div").hover(function() 
    {
        $(this).removeClass("maphoveroptionsideoff");         
        $(this).addClass("maphoveroptionside");
    }, function()
       {
           if($(this).attr("id") != SelectedID)
           {
               $(this).removeClass("maphoveroptionside");        
               $(this).addClass("maphoveroptionsideoff"); 
           }
       }
    );
        
    $("#otherclubs").children("div").bind("click", function()
    {
        var s = $(this).attr("id");
        SelectClub(s);
    });
}
           
// Club Selection 
function SelectClub(id)
{
    for(i=1; i < ClubList.length; i++) 
    { 
        // Reset Hover/Selected Status (CSS)
        
        if(ClubList[i].placed == 1)
        {
            $("#location" + i).removeClass("maphoveroption");         
            $("#location" + i).addClass("maphoveroptionoff"); 
        }
        
        if(ClubList[i].placed == 2 || ClubList[i].placed == 3)
        {
            $("#location" + i).removeClass("maphoveroptionside");         
            $("#location" + i).addClass("maphoveroptionsideoff");  
        }
    
        if(ClubList[i].ID == id)
        {
            SelectedID = "location" + i;

            if(ClubList[i].placed == 1)
            {
                $("#location" + i).removeClass("maphoveroptionoff");         
                $("#location" + i).addClass("maphoveroption"); 
            }
            
            if(ClubList[i].placed == 2 || ClubList[i].placed == 3)
            {
                $("#location" + i).removeClass("maphoveroptionsideoff");         
                $("#location" + i).addClass("maphoveroptionside");  
            }
        
            // Build HTML for Information Area
            var s = "<table style=\"width: 500px; font-size:13px;\">";
            
            s = s + "<tr>";
            s = s + "<td colspan=\"2\">";
            s = s + "<h1>Anytime Fitness " + ClubList[i].name + "</h1>";
            s = s + "</td>"
            s = s + "</tr>"
            
            s = s + "<tr>";
            s = s + "<td style=\"width: 75px; text-align:right; vertical-align:top;\"><strong>Address :</strong></td>";
            s = s + "<td style=\"width: 425px\">" + ClubList[i].infoaddress + "</td>";
            s = s + "</tr>";
            
            s = s + "<tr>";
            s = s + "<td style=\"width: 75px; text-align:right;\"><strong>Phone :</strong></td>";
            s = s + "<td style=\"width: 425px\">" + ClubList[i].phone + "</td>";
            s = s + "</tr>";
            
            if ( ClubList[i].email != '')
            {
                s = s + "<tr>";
                s = s + "<td style=\"width: 75px; text-align:right;\"><strong>Email :</strong></td>";
                s = s + "<td style=\"width: 425px\"><a href=\"mailto:" + ClubList[i].email + "\">" + ClubList[i].email + "</a></td>";
                s = s + "</tr>";
            }
        
            if ( ClubList[i].website != '')
            {
                s = s + "<tr>";
                s = s + "<td style=\"width: 75px; text-align:right;\"><strong>Website :</strong></td>";
                s = s + "<td style=\"width: 425px\"><a href=\"" + ClubList[i].website + "\">Click Here!</a></td>";
                s = s + "</tr>";
            }
            
            s = s + "<tr>";
            s = s + "<td style=\"width: 75px; text-align:right;\">&nbsp;</td>";
            s = s + "<td style=\"width: 425px\">&nbsp;</td>";
            s = s + "</tr>";
            
            s = s + "<tr>";
            s = s + "<td colspan=\"2\"><h2>Get Directions</h2></td>";
            s = s + "</tr>";
            
            s = s + "<tr>";
            s = s + "<td colspan=\"2\">Starting Address: <br /> <input type=\"text\" id=\"directstart\" style=\"width:400px;\" value=\"" + document.getElementById('searchloc').value + "\" /> <input type=\"button\" value=\"Go\" onclick=\"UpdateDirections()\" /></td>";
            s = s + "</tr>";
            
            s = s + "</table>";

            $("#info").html(s);          
        
            if(IsDefaultSelect == false)
            {
                StopUpdate = true;
                $('html').animate({scrollTop:106}, 'slow'); 
                Map.PanToLatLong(new VELatLong(ClubList[i].latitude, ClubList[i].longitude));
            }   
            
            IsDefaultSelect = false;
            
            // Get Directions for Selected Club
//            if (document.getElementById('searchloc').value)
//            {
//                var locations = new Array(LocationReplace(document.getElementById('searchloc').value), ClubList[i].address);
//                CurAddress = ClubList[i].address;

//                var options = new VERouteOptions;
//                options.DrawRoute = false;
//                options.SetBestMapView = false;
//                options.RouteCallback = ShowDetail;
//                options.DistanceUnit = VERouteDistanceUnit.Mile;
//                options.ShowDisambiguation = false;

//                // Get Directions from VE
//                Map.GetDirections(locations, options);            
//           }            
        }
    }
}
        
// Update Directions based on new starting point
function UpdateDirections()
{
    if (document.getElementById('directstart').value)
    {
        for(i=1; i < ClubList.length; i++)
        { 
            if(ClubList[i].ID == SelectedID)
            {     
                var locations = new Array(LocationReplace(document.getElementById('directstart').value), ClubList[i].address);
                CurAddress = ClubList[i].address;

                var options = new VERouteOptions;
                options.DrawRoute      = false;
                options.SetBestMapView = false;
                options.RouteCallback  = ShowDetail;
                options.DistanceUnit   = VERouteDistanceUnit.Mile;
                options.ShowDisambiguation = false;

                // Get Directions from VE
                Map.GetDirections(locations, options);
            }
        }
    }
}

// Build Direction HTML        
function ShowDetail(route)
{
    var turns = "<h2>Turn-by-Turn Directions</h2>";

    turns += "<b>Time:</b> " + GetTime(route.Time) + "</p>";

    // Unroll route and populate DIV
    var legs = route.RouteLegs;
    var leg = null;
    var turnNum = 0;

    // Get intermediate legs
    for(var i = 0; i < legs.length; i++)
    {
        // Get this leg so we don't have to derefernce multiple times
        leg = legs[i];
        var legNum = i + 1;
  
        // Unroll each intermediate leg
        var turn = null; 
        var legDistance = null;       
      
        for(var j = 0; j < leg.Itinerary.Items.length; j ++)
        {
            turnNum++;
         
            turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
            turns += "<b>" + turnNum + "</b>\t" + turn.Text;
            legDistance    = turn.Distance;

            // So we don't show 0.0 for the arrival
            if(legDistance > 0)
            {
                // Round distances to 1/10ths
                turns += " (" + legDistance.toFixed(1) + " miles";

                // Append time if found
                if(turn.Time != null)
                {
                    turns += "; " + GetTime(turn.Time);
                }

                turns += ")<br/>";
            }
        }

        turns += "<br/>";
      
       // Populate DIV with directions
       $("#directions").html(turns + "<br /><strong><a href=\"http://Maps.live.com/default.aspx?Rtp=adr." + document.getElementById('directstart').value + "~adr." + CurAddress + "\" target=\"_blank\">Click for Detailed Directions & Printing </a></strong>");  
    }
}
       
// returns a formatted string
function GetTime(time)
{
   if(time == null)
   {
      return("");
   }

   if(time > 60)
   {      
       var seconds = time % 60;      
       var minutes = time - seconds; 
       minutes = minutes / 60;   

       if(minutes > 60)
       {                             
           var minLeft = minutes % 60;    
           var hours = minutes - minLeft;
           hours = hours / 60;

           return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
       }
       else
       {
          return(minutes + " minutes, " + seconds + " seconds");
       }
   }
   else
   {
       return(time + " seconds");
   }
}

// Callback to Allow Updates
function AllowUpdate()
{
    StopUpdate = false;
}

// Club Item Object
function ClubItem()
{
    this.ID = '';
    this.latitude = 0.000;
    this.longitude = 0.000;
    this.distance = 0.000;
    this.name = '';
    this.street1 = '';
    this.street2 = '';
    this.city = '';
    this.state = '';
    this.zip = '';
    this.phone = '';
    this.status = 0;
    this.email = '';
    this.website = '';
    this.address = '';
    this.placed = 0;
}      
        
// Adds Club/Pin to Map       
function AddClub(latitude, longitude, distance, name, street1, street2, city, state, zip, phone, status, website, email)
{
    AddCount++;
              
    var club = new ClubItem();
    
    club.ID = 'location' + AddCount;
    club.latitude = latitude;
    club.longitude = longitude;
    club.distance = distance;
    club.name = name;
    club.street1 = street1;
    club.street2 = street2;
    club.city = city;
    club.state = state;
    club.zip = zip;
    club.phone = phone;
    club.status = status;
    club.email = email;
    club.website = website;
    
    ClubList[AddCount] = club;
    
    saddress = street1 + '<br />';
    if (street2 != '') 
    { saddress = saddress + street2 + '<br />' }
        
    ClubList[AddCount].infoaddress = saddress + city + ', ' + state + ' ' + zip;
    
    saddress = saddress + city + ', ' + state + ' ' + zip + '<br />' + phone;

    ClubList[AddCount].address = street1 + '<br />';
    if (street2 != '') 
    { ClubList[AddCount].address = ClubList[AddCount].address + street2 + '<br />' }
                
    ClubList[AddCount].address = ClubList[AddCount].address + city + ', ' + state + ' ' + zip;
    
    if(club.status > 1)
    {
        var latlon = new VELatLong(latitude, longitude);
        var shape = new VEShape(VEShapeType.Pushpin, latlon);
        shape.SetTitle(name);     
        if (club.status == 2)
        {
            shape.SetCustomIcon("<img id=\"pin" + AddCount + "\" style=\"position: relative; top: -8px; \"src=\"content/images/public/pingreen.gif\" onclick=\"SelectClub('location" + AddCount + "');\"/>");     
        }
        else
        {
            shape.SetCustomIcon("<img id=\"pin" + AddCount + "\" style=\"position: relative; top: -8px; \"src=\"content/images/public/pin.gif\" onclick=\"SelectClub('location" + AddCount + "');\"/>");     
        }
                        
        shape.SetDescription(saddress);                  
        Map.AddShape(shape);
    }

}

// Update Screen after all clubs loaded    
function LastClubSent()
{
   if (ClubList.length > 0)
   {
       // Zipcode Shim
       if (document.getElementById('searchloc').value)
       {
           if(IsNumeric(document.getElementById('searchloc').value) && document.getElementById('searchloc').value.length == 5)
           {
               if(ClubList.length > 1)
               {
                   if(ClubList[1].zip != document.getElementById('searchloc').value && ClubList[2].zip == document.getElementById('searchloc').value)
                   {
                       var c1 = ClubList[1];
                       var c2 = ClubList[2];
                       
                       ClubList[1] = c2;
                       ClubList[2] = c1;
                   }
               }
           }
       }
   
       StopUpdate = true;

       var ipre = 1;
       var imain = 0;
       var iother = 0;
       var isoon = 0;
       var firstselected = false;
       var selectednumber = 0;
       
       // Loop and Create Buttons
       for(ilist = 1; ilist < ClubList.length; ilist++)
       {
           var itemadded = false;
       
           if(firstselected == false && ClubList[ilist].status > 1)
           {
               SelectedID = ClubList[ilist].ID;
               IsDefaultSelect = true;
               selectednumber = ilist;
               firstselected = true;
               SelectClub(SelectedID);
           }
           
           // Top 4 Clubs
           if( imain < 4)
           {
               if(ClubList[ilist].status > 1)
               {
                   var cs = "maphoveroption";
                   if(imain > 0)
                   { cs = "maphoveroptionoff"; }
                    
                   var idx = ClubList[ilist].name.indexOf(", ");
                   var clubname = ClubList[ilist].name; //.substring(0, idx + 5);
              
                   var s = '<div id="location' + ilist.toString() + '" class="' + cs + '" style="float: left; width: 206px;  padding: 12px; padding-right:5px; height: 86px; display: none;">';
                       s = s + '<div style="float: left; padding-right: 5px; border-right: solid 1px #4e1d77; height:80px; text-align:center; font-size:16px;"><span style="font-weight:bold;">' + ClubList[ilist].distance + '</span><br /><span style="font-size: 10px; font-weight:bold;">miles</span><br /><img src="content/images/public/anytimeicon.gif" style="padding-top:15px;" /></div>';
                       s = s + '<div style="float: left; padding-left: 5px; width:155px; font-size:11px;"><span style="font-weight: bold; font-size:14px; padding-bottom: 4px; display: block">' + clubname + '</span><span style="font-size: 12px; display:block; font-weight:bold; padding-bottom:4px;">' + ClubList[ilist].phone + '</span>' + ClubList[ilist].address + '</div>';
                       s = s + '</div>';
               
                   $("#mapresults").append(s);
                   setTimeout("ShowNewItem('location" + ilist.toString() + "')", 100 * ilist);
                   itemadded = true;
                   ClubList[ilist].placed = 1;
                   imain++;
               }                    
           }
           
           // Other Close Clubs
           if(itemadded == false && ClubList[ilist].status > 1 && iother < 3)
           {
               var idx = ClubList[ilist].name.indexOf(", ");
               var clubname = ClubList[ilist].name.substring(0, idx + 4);
              
               var s = '<div id="location' + ilist.toString() + '" style="float: left; width: 199px;  padding: 12px; padding-right:5px; height: 86px; display: none;">';
                   s = s + '<div style="float: left; padding-right: 5px; border-right: solid 1px #4e1d77; height:80px; text-align:center; font-size:16px;"><span style="font-weight:bold;">' + ClubList[ilist].distance + '</span><br /><span style="font-size: 10px; font-weight:bold;">miles</span><br /><img src="content/images/public/anytimeicon.gif" style="padding-top:15px;" /></div>';
                   s = s + '<div style="float: left; padding-left: 5px; width:150px; font-size:11px;"><span style="font-weight: bold; font-size:14px; padding-bottom: 4px; display: block">' + clubname + '</span><span style="font-size: 12px; display:block; font-weight:bold; padding-bottom:4px;">' + ClubList[ilist].phone + '</span>' + ClubList[ilist].address + '</div>'
                   s = s + '</div>';
                   
               $("#otherclubs").show();
               $("#otherclubs").append(s);
               setTimeout("ShowNewItem('location" + ilist.toString() + "')", 100 * ilist);
               itemadded = true;
               ClubList[ilist].placed = 2;
               iother++;
                                   
           }
           
           // Coming Soon Clubs
           if(itemadded == false && ClubList[ilist].status == 1 && isoon < 4)
           {
               var idx = ClubList[ilist].name.indexOf(", ");
               var clubname = ClubList[ilist].name.substring(0, idx + 4);
               
               $("#comingsoon").show();
               var s = '<div id="location' + ilist.toString() + '" style="float: left; width: 199px;  padding-left: 12px; padding-right: 12px;  padding-top: 5px; padding-bottom: 5px; height: 40px; display: none;">';
                   s = s + '<div style="float: left; padding-right: 5px; border-right: solid 1px #4e1d77; height:20px; width: 33px; text-align:center; font-size:16px;"><span style="font-weight:bold;">' + ClubList[ilist].distance + '</span><br /><span style="font-size: 10px; font-weight:bold;">miles</span></div>';
                   s = s + '<div style="float: left; padding-left: 5px; width:140px;"><span style="font-weight: bold">' + clubname + '</span><br />' + ClubList[ilist].phone + '</div>';
                   s = s + '</div>';
            
               $("#comingsoon").append(s);
               setTimeout("ShowNewItem('location" + ilist.toString() + "')", 100 * ilist);
               itemadded = true;
               ClubList[ilist].placed = 3;
               isoon++;                                            
           }                
       }
       
       if(ReZoom)
       {
          if (selectednumber > 0)
          {
              setTimeout('PanTo(' + ClubList[selectednumber].latitude + ', ' + ClubList[selectednumber].longitude + ')', 500);
          }
       }
   }
              
   if(ReZoom)
   {
       Map.SetZoomLevel(13);
       ReZoom = false;
   }    
   
   setTimeout('AllowUpdate()', 2000);
   HoverSetup();
}

// Pan Callback         
function PanTo(lat, lon)
{
    Map.PanToLatLong(new VELatLong(lat, lon));
}

// Auto Locate Callback    
function SetAutoLocateViewport(latitude, longitude, lvl, bl, msg)
{
    Map.SetCenterAndZoom(new VELatLong(latitude, longitude), 10);
    setTimeout('UpdateLocations()', 250);
}

// Show Div Callback
function ShowNewItem(div)
{
    $("#" + div).show()
}

// Show Message Callback
function ShowMessage()
{
    $("#message").animate({ height: '24', paddingTop: '4', top: '417' }, 'fast');
}

// Hide Message Callback
function HideMessage()
{
    $("#message").html("<img src=\"content/images/spacer.gif\" height=\"1\" width=\"1\" alt=\"\" style=\"width: 1px; height: 1px\" />");
    $("#message").animate({ height: '1',  paddingTop: '0', top: '444', paddingBottom: '0' }, 'slow');
    
}
      
// List Functions 
function GoToList() {

    if(document.getElementById('state').value != "") 
    {
        if (document.getElementById('state').value.length > 10) {
            document.location = document.getElementById('state').value;
        }
        else
        {
            document.location = BaseURL + "/locate/list/" + document.getElementById('state').value;
        }
    }
}

// Check for Numeric
function IsNumeric(sText)
{
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
    
    return IsNumber;
}