﻿var map = null;
var address = null;
var visitorLatLong = null;

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

function pageLoad() {
    if ($get("BallyLocationsMap") != null) {
        doLoadMap();
    }
}

function endRequestHandler(sender, eventArgs) {
    if (eventArgs.get_error() != undefined && eventArgs.get_error().httpStatusCode == '500') {
        var errorMessage = eventArgs.get_error().message;
        eventArgs.set_errorHandled(true);
        alert(errorMessage);
    } else {
        if ($get("BallyLocationsMap") != null) {
            doLoadMap();
        }
    }
}

function doLoadMap() {
    map = new VEMap('BallyLocationsMap');
    map.SetDashboardSize(VEDashboardSize.Small);
    map.LoadMap();
    GetClubListByAddress();
}

function GetClubListByAddress() {
    address = $get(zipCodeClientID).value;
    if (address.length > 60) {
        address = address.substring(1, 60);
    }

    if (address.length != 0 && address != null) {
        //DeleteAllMapShapes();
        //InfoBox(true, "Searching. Please wait...");
        PageMethods.GetClubs(address, onSuccess, onFail);
    }
}

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);
        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 onFail(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);
    alert("Fail!");
}

function AddPushpin(clubInfo, counter) {
    var clubLatLong = new VELatLong(clubInfo.ClubLatitude, clubInfo.ClubLongitude);
    var shp = new VEShape(VEShapeType.Pushpin, clubLatLong);

    var displayCounter = counter + 1;
    var title = displayCounter + ': ' + clubInfo.ClubName;
    shp.SetTitle(title);

    var icon = "Controls/Images/bally-icon-small.gif";
    shp.SetCustomIcon(icon);

    //    var clubPhotosynthURL = clubInfo.PhotosynthURLs[0];
    //    synthContent = '<iframe frameborder=0 src="' + clubPhotosynthURL + '" width="400" height="300"></iframe>';

    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);
}

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;
}


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();
    }
}

