﻿var txtAddressSearchID = null;
var map = null;
var visitorLatLong = null;
var mapHeaderHTML = null;
var amenitiesListHTML = null;
var clubListHTML = null;
var address = null;
var driveFrom = null;
var driveTo = null;
var driveToClubName = null;


function pageLoad() {
    map = new VEMap('BallyLocationsMap');
    map.LoadMap();
}


/* Implement as needed */
function GetClubListByGeocode() {
    var lat;
    var lon;
    BTF.Web.UI.ClubLocator.ClubService.GetClubsByLocation(lat, lon, onSuccess, onFailed);
}


function GetClubListByAddress() {
    address = document.getElementById(txtAddressSearchID).value;
    if (address.length > 60) {
        address = address.substring(1, 60);
    }
    
    if (address.length != 0 && address != null) {
        DeleteAllMapShapes();
        InfoBox(true, "Searching. Please wait...");
        BTF.Web.UI.ClubLocator.ClubService.GetClubsByAddress(address, onSuccess, onFailed);
    }
}


function onSuccess(jsonData) {
    var clubData = Sys.Serialization.JavaScriptSerializer.deserialize(jsonData);

    if (clubData.nearestClubs && clubData.nearestClubs.length > 0) {
        address = clubData.searchLocName;
        mapHeaderHTML = '<label>Bally Total Fitness clubs in or near ' + address + '.</label>';
        SetMapHeader(mapHeaderHTML);
        InitializeCommon();
        visitorLatLong = new VELatLong(clubData.mapCenterLoc.Latitude, clubData.mapCenterLoc.Longitude);
        BuildAreaAmenitiesList(clubData.Amenities);
        BuildClubResultsTable(clubData.nearestClubs);
        if (clubData.IsStateSearch) {
            map.SetCenterAndZoom(visitorLatLong, 6);
        }
        else {
            map.SetCenterAndZoom(visitorLatLong, 9);
        }
        Array.forEach(clubData.nearestClubs, AddPushpin);
    }
    else {
        if (clubData.searchStatus == "Error") {
            mapHeaderHTML = '<label style="color: red">Unable to retrieve search results. We apologize for any inconvenience. Please try this feature again later.</label>';
        }
        else {
            mapHeaderHTML = '<label style="color: red">No Bally Total Fitness clubs found near this location. Please try another address.</label>';
        }
        SetMapHeader(mapHeaderHTML);
        Initialize();        
    }
    
    InfoBox(false);
}


function onFailed(jsonData) {
    address = clubData.searchLocName;
    mapHeaderHTML = '<label style="color: red">Unable to retrieve search results. We apologize for any inconvenience. Please try this feature again later.</label>';
    SetMapHeader(mapHeaderHTML);
    Initialize();
    InfoBox(false);
}


function SetMapHeader(mapHeaderHTML)
{
    $get("map-header").innerHTML = mapHeaderHTML; 
}


function Initialize() {
    $get('club-amenities').innerHTML = '';
    $get('search-result-section').innerHTML = '';
    InitializeCommon();
}

function InitializeCommon() {
    driveFrom = null;
    driveTo = null;
    driveToClubName = null;
    visitorLatLong = null;
}


function DeleteAllMapShapes() {
    map.DeleteAllShapes();
    DeleteRoute();
}


function BuildAreaAmenitiesList(amenities) {
    amenitiesListHTML = '';
    if (amenities && amenities.length > 0) {
        amenitiesListHTML = amenitiesListHTML + '<label>AMENITIES IN THIS AREA</label><ul>';
        for (var i = 0; i < amenities.length; i++) {
            amenitiesListHTML = amenitiesListHTML + '<li>' + amenities[i] + '</li>';
        }
        amenitiesListHTML = amenitiesListHTML + '</ul>';
        $get('club-amenities').innerHTML = amenitiesListHTML;
    }
}


function AddPushpin(clubInfo, counter) {
    var clubLatLong = new VELatLong(clubInfo.ClubLatitude, clubInfo.ClubLongitude);
    var shp = new VEShape(VEShapeType.Pushpin, clubLatLong);

    var title = clubInfo.ClubName;
    shp.SetTitle(title);

    var icon = "images/bally-icon-medium.gif";
    shp.SetCustomIcon(icon);

    var clubPhotosynthURL = clubInfo.PhotosynthURLs[0];
    synthContent = '<iframe frameborder=0 src="' + clubPhotosynthURL + '" width="400" height="300"></iframe>';

    var endAddr = clubInfo.ClubAddress + ' ' + clubInfo.ClubCity + ', ' + clubInfo.ClubState + ' ' + clubInfo.ClubZip;

    storeContent = '<b>' + clubInfo.ClubName + '</b><br/>';
    storeContent += clubInfo.ClubAddress + '<br \>' + clubInfo.ClubCity + ', ' + clubInfo.ClubState + ' ' + clubInfo.ClubZip + '<br \>' + clubInfo.ClubPhone + '<br \><br \>';
    storeContent += GetDrivingDirectionsURL(address, visitorLatLong.Latitude, visitorLatLong.Longitude, clubInfo);

    hoursContent = '<b>Club Hours</b><br/><br/>';
    for (var i = 0; i < clubInfo.ClubHours.length; i++) {
        hoursContent += clubInfo.ClubHours[i] + '<br/>';
    }

    amenitiesContent = '<b>Club Amenities</b><br/><ul>';
    for (var i = 0; i < clubInfo.ClubAmenities.length; i++) {
        amenitiesContent += '<li>' + clubInfo.ClubAmenities[i] + '</li>'
    }
    amenitiesContent += '</ul>';
    

    if (clubPhotosynthURL && clubPhotosynthURL.length > 0) {
        markerDesc = createTabs(counter, ['Photos', 'Location', 'Hours', 'Amenities'], [synthContent, storeContent, hoursContent, amenitiesContent]);
    }
    else {
        markerDesc = createTabs(counter, ['Location', 'Hours', 'Amenities'], [storeContent, hoursContent, amenitiesContent]);
    }
    

    shp.SetDescription(markerDesc);
    
    map.AddShape(shp);
}


/* Popup menu tabs */
function createTabs(count, tabnames, tabcontent) {
    var content = '';
    var tabheadstring = '';
    var tabcontentstring = '';
    for (var i = 1; i < tabnames.length + 1; i++) {
        tabheadstring += '<li id="tabhead' + count + '_' + i + '" class="';
        if (i == 1) {
            tabheadstring += 'tabheadon ';
        } else {
            tabheadstring += 'tabheadoff ';
        }
        if (i == tabnames.length) {
            tabheadstring += 'lasttab';
        } else {
            tabheadstring += 'notlasttab';
        }
        tabheadstring += '"><a href="#" onclick="setTabActive(\'' + count + '\',\'' + i + '\');return false;">' + tabnames[i - 1] + '</a></li>';
    }
    for (var j = 1; j < tabcontent.length + 1; j++) {
        tabcontentstring += '<div class="';
        if (j == 1) {
            tabcontentstring += 'tabon';
        } else {
            tabcontentstring += 'taboff';
        }
        tabcontentstring += '" id="tab' + count + '_' + j + '">' + tabcontent[j - 1] + '</div>';
    }
    content += '<div class="tabwrapper">';
    content += '<ul id="navigation' + count + '" class="navigation">';
    content += tabheadstring;
    content += '</ul>';
    content += '</div><br/><br/>';
    content += '<div id="tabcontainer' + count + '" class="tabcontainers">';
    content += tabcontentstring;
    content += '</div>';

    return content;

}


function setTabActive(box, tab) {

    // Get correct info box content:
    var myInfoBoxTabContainer = document.getElementById('tabcontainer' + box);
    var myInfoBoxTabHeadContainer = document.getElementById('navigation' + box);

    var activeTab = document.getElementById('tab' + box + '_' + tab);
    var activeTabHead = document.getElementById('tabhead' + box + '_' + tab);
    var myTabs = myInfoBoxTabContainer.getElementsByTagName('div');
    var myTabHeads = myInfoBoxTabHeadContainer.getElementsByTagName('li');

    // Hide all inactive tabs
    for (var i = 0; i < myTabs.length; i++) {
        myTabs[i].style.display = "none";
    }
    // Show clicked tab:
    activeTab.style.display = "block";

    // Unbold all inactive tabheads:
    for (var i = 0; i < myTabHeads.length; i++) {
        var lastClass;
        if (i < myTabHeads.length - 1) {
            lastClass = " notlasttab";
        } else {
            lastClass = " lasttab";
        }
        myTabHeads[i].className = "tabheadoff" + lastClass;

    }
    // Bold clicked tabhead:
    var activeLastClass;
    if (tab == myTabHeads.length) {
        activeLastClass = " lasttab";
    } else {
        activeLastClass = " notlasttab";
    }
    activeTabHead.className = "tabheadon" + activeLastClass;
}




/* Display info box on VE map */
function InfoBox(show, message, timeout) {
    var mapInfoBox = $get('infoBox');
    if (!show) {
        mapInfoBox.innerHTML = '';
        mapInfoBox.style.opacity = '0.0';
        mapInfoBox.style.filter = 'Alpha(Opacity = 0)';
        mapInfoBox.style.visibility = 'hidden'; 
    }
    else {
        mapInfoBox.innerHTML = message;
        mapInfoBox.style.opacity = '.7';
        mapInfoBox.style.filter = 'Alpha(Opacity = 70)';
        mapInfoBox.style.visibility = 'visible';
        if (timeout)
            setTimeout('InfoBox(false)', timeout);
    }
}


/* Build club search results grid */
function BuildClubResultsTable(clubList){

    clubListHTML = '';
    if (clubList && clubList.length > 0) {
        
        clubListHTML += '<div class="results-section">';
        clubListHTML +=    '<div class="section-top"></div>';
        clubListHTML +=         '<div class="section-content">';
        clubListHTML +=             '<div id="DrivingDirections"></div>';
        clubListHTML +=             '<div class="clearfix">';

        clubListHTML +=                 '<h3>Clubs near ' + address + '</h3>';
        
        if (clubList.length > 5) 
        {            
            clubListHTML +=            '<div id="results-count">';
            clubListHTML +=                 '<label style="padding-right: 10px;">View</label>';
            clubListHTML +=                 '<select onchange="UpdateResultsListTable(this.options[this.selectedIndex].value)">';
            clubListHTML +=                 '<option selected="selected" value="5">5 per page</option>';

            if (clubList.length > 5)
                clubListHTML +=                 '<option  value="10">10 per page</option>';
            if (clubList.length > 10)
                clubListHTML +=                 '<option  value="15">15 per page</option>';
            /* Limit view all option if too many results */    
            if (clubList.length > 15 && clubList.length <= 30)
                clubListHTML +=                 '<option  value="All">View all</option>';
            
            clubListHTML +=                '</select>';
            clubListHTML +=            '</div>';
        }

        clubListHTML +=             '</div>';
        
        clubListHTML +=                '<div id="club-search-results">';

        clubListHTML +=                     '<table id="results-table" class="gridview">';

        for (var i = 0; i < clubList.length; i++) 
        {
            clubListHTML +=                     BuildClubResultsTableRow(i, clubList[i]);
        }

        clubListHTML +=                     '</table>';
        
        clubListHTML +=                '</div>';

        clubListHTML += '<div id="gridview-paging" class="clearfix">';
        if (clubList.length > 5)
            clubListHTML +=                     BuildClubResultsPaging(clubList.length, 5, 1);
        clubListHTML +=                '</div>';

        clubListHTML +=         '</div>';                        

                    
        clubListHTML +=    '<div class="section-bottom"></div>';
        clubListHTML += '</div>';
        

        $get('search-result-section').innerHTML = clubListHTML;
    }

}

function BuildClubResultsTableRow(idx, clubDetails) {
    var clubRowHTML = '';
    if (idx % 2 == 0) 
    {
        clubRowHTML += '<tr valign="top" class="nth-child-odd"';
    }
    else 
    {
        clubRowHTML += '<tr valign="top"';
    }
    if (idx > 4) 
    {
        clubRowHTML += ' style="display: none"';
    }
    
    clubRowHTML += '>';

    clubRowHTML = clubRowHTML + '<td style="text-align:center; vertical-align: middle; margin-left: auto; margin-right: auto ">';
    clubRowHTML = clubRowHTML + '<div class="result-number">' + (idx + 1) + '</div>';
    clubRowHTML = clubRowHTML + '<div class="result-distance">' + Math.round(clubDetails.ClubDistance) + ' ' + clubDetails.ClubDirection + '</div></td>';
    
    clubRowHTML = clubRowHTML + '<td><div class="details">';
    clubRowHTML = clubRowHTML + '<h4><a href="/discover-bally/our-clubs/club-amenities-hours/club' + clubDetails.ClubIDFriendly + '.aspx">' + clubDetails.ClubName + '</a></h4>';
    clubRowHTML = clubRowHTML + '<address>' + clubDetails.ClubAddress + '<br />' + clubDetails.ClubCity + ' ' + ((clubDetails.ClubState) ? (clubDetails.ClubState + ', ') : '') + clubDetails.ClubZip + '</address>';
    clubRowHTML = clubRowHTML + '<p>' + clubDetails.ClubPhone + '</p>';
    clubRowHTML = clubRowHTML + '</div></td>';

    clubRowHTML = clubRowHTML + '<td><h4>Hours</h4>';
    if (clubDetails.ClubHours && clubDetails.ClubHours.length > 0) {
        for (var i = 0; i < clubDetails.ClubHours.length; i++) {
            clubRowHTML = clubRowHTML + '<div class="clearfix"><span class="hours">' + clubDetails.ClubHours[i] + '</span></div>';
        }
    }
    clubRowHTML = clubRowHTML + '</td>';
    
    clubRowHTML = clubRowHTML + '<td>';
    clubRowHTML = clubRowHTML + '<a href="/discover-bally/our-clubs/club-amenities-hours/club' + clubDetails.ClubIDFriendly + '.aspx">Class Schedule</a><br />';
    clubRowHTML = clubRowHTML + '<a href="/get-started/visit-club/schedule-club-tour.aspx">Schedule a Club Tour</a><br />';
    clubRowHTML = clubRowHTML + '<a href="/get-started/guest-pass/free-guest-pass.aspx">FREE Guest Pass</a><br />';
    clubRowHTML = clubRowHTML + '<a href="/get-started/become-member/become-member.aspx">Become a Member</a><br />';
    clubRowHTML += GetDrivingDirectionsURL(address, visitorLatLong.Latitude, visitorLatLong.Longitude, clubDetails);
    clubRowHTML = clubRowHTML + '</td>';

    clubRowHTML = clubRowHTML + '</tr>';
    return clubRowHTML;
}


function BuildClubResultsPaging(resultsCount, resultsPerPage, activeIndex) {

    var pagingHTML = '';
    var j = 0;
    for (var i = 1; i <= resultsCount; i = i + resultsPerPage) {
        j++;
        if (activeIndex >= i && activeIndex < i + resultsPerPage) {
            if (i == 1)
                pagingHTML += '<a href="#" class="first-child current">' + j + '</a>';
            else
                pagingHTML += '<a href="#" class="current">' + j + '</a>';
        }
        else {
            pagingHTML += '<span><a href="#" onclick="ShowHideResultsTableRows(' + i + ',' + (i + resultsPerPage -1) + '); return false;">' + j + '</a></span>';
        }
    
    }
    return pagingHTML;
}


function UpdateResultsListTable(sel) {
    switch (sel) {
        case '5':
            ShowHideResultsTableRows(1, 5);
            break;
        case '10':
            ShowHideResultsTableRows(1, 10);
            break;
        case '15':
            ShowHideResultsTableRows(1, 15);
            break;
        case 'All':
            ShowHideResultsTableRows(1, $get("results-table").rows.length);
            break;
        default:
            break;
    }
    
}


function ShowHideResultsTableRows(startIndex, endIndex) {
    var tbRows = $get("results-table").rows;
    var pageResultsCount = endIndex - startIndex + 1
    try {
        if (endIndex > tbRows.length) {
            endIndex = tbRows.length;
        }
        for (var i = 0; i < tbRows.length; i++) {
            if (i >= (startIndex - 1) && i < endIndex) {
                tbRows[i].style.display = '';
            }
            else {
                tbRows[i].style.display = 'none';
            }
        }
        $get("gridview-paging").innerHTML = BuildClubResultsPaging(tbRows.length, pageResultsCount, startIndex);
    }
    catch (err)
    { }
    
    
}


function GetDrivingDirectionsURL(startAdr, startLat, startLong, clubInfo) {
    var endAddr = clubInfo.ClubAddress + ' ' + clubInfo.ClubCity + ', ' + clubInfo.ClubState + ' ' + clubInfo.ClubZip + '<br/>' + clubInfo.ClubPhone;

    var drivingDirectionsURL = '<a href="#DrvDir" onclick="GetDrivingDirections(&quot;';
    drivingDirectionsURL += startAdr + '&quot;,&quot;' + endAddr + '&quot;,&quot;' + startLat + '&quot;,&quot;' + startLong + '&quot;,&quot;' + clubInfo.ClubLatitude + '&quot;,&quot;' + clubInfo.ClubLongitude + '&quot;,&quot;' + clubInfo.ClubName + '&quot;);return false">Get Directions</a>';
    
    return drivingDirectionsURL;
}


function GetDrivingDirections(startAddress, endAddress, startLat, startLong, endLat, endLong, clubName) {

    driveFrom = startAddress;
    driveTo = endAddress;
    driveToClubName = clubName;
    
    var startPoint = new VELatLong(startLat, startLong);
    var endPoint = new VELatLong(endLat, endLong);

    var rtOptions = new VERouteOptions();
    rtOptions.RouteCallback = onGotRoute;

    map.GetDirections([startPoint, endPoint], rtOptions);
}


function onGotRoute(route) {
    // Unroll route
    var legs = route.RouteLegs;
    var turns = '<div id="PrintableDirections"><div class="directions-details"><h3>Driving Directions</h3>';

    turns += '<table><tr><td><b>Start:</b></td><td>' + driveFrom + '</td></tr>';
    turns += '<tr><td><b>End:</b></td><td>Bally Total Fitness - ' + driveToClubName + '<br/>' + driveTo + '</td></tr></table>';
    

    turns += '<p>Total driving distance: ' + route.Distance.toFixed(1) + ' mi </p>';
    var numTurns = 0;
    var leg = null;
    // 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];
        // Leg is a VERouteLeg object
        // Unroll each intermediate leg               
        var turn = null;  
        // The itinerary leg                                 
        for (var j = 0; j < leg.Itinerary.Items.length; j++) {
            turn = leg.Itinerary.Items[j];
            // turn is a VERouteItineraryItem object                 
            numTurns++;
            turns += '<p>' + numTurns + '.\t' + turn.Text + ' (' + turn.Distance.toFixed(1) + ' mi) </p>';
        }
    }
    turns = turns + '</div></div><a href="#" onclick="printDirections();return false;">Print Directions</a><br/><br/>';
    $get('DrivingDirections').innerHTML = turns;
    $get('DrivingDirections').focus();
}


function DeleteRoute() {

    try {
        map.DeleteRoute();
    }            
   catch (err)
   { }
}


function printDirections() {
    
        vAutoPrint = false;

        var newWinHtml = '<html>\n<head>\n <style type="text/css" media="print"> {.doNotPrint { display: none; }}</style>\n';
        newWinHtml += '\n</head>\n<body>\n';
        newWinHtml += '<div style="text-align: left;width: 640px; margin-left: 40px;margin-right: auto;">\n';
        newWinHtml += '<form><input type="button" class="doNotPrint" onClick="window.print();" value="Send to Printer" /></form><br/><div style="padding: 15px;border: solid 1px;">';

        var printableElement = $get("PrintableDirections");

        if (printableElement != null)
        {
            newWinHtml += printableElement.innerHTML;
        }

        newWinHtml += '\n</div>\n</div>\n</body>\n</html>';

        var printWin = window.open("","printSpecial"); 
        printWin.document.open();
        printWin.document.write(newWinHtml);
        printWin.document.close();

        if (vAutoPrint)
        {
            printWin.print();
        }
}


function LoadNationalMap() {
    Initialize();
    SetMapHeader('');
    map.LoadMap();
}