﻿//NDM Default routing of loctions to be used by maps
function locationRouting(clubId) {
	switch (clubId) {
		case '42':
		case '47':
			//'redirect to Geoff Clubs
		    window.location = "http://www.lff.com/east-columbus-hillard.aspx";
			break;
        case '40':
        case '41':
        case '43':
        case '44':
        case '45':
        case '46':
        case '48':
        case '49':
        case '50':
        case '51':
        case '52':
        case '53':
        case '57':
        case '58':
        case '60':
        case '61':
        case '64':
        case '67':
			//redirect to another place
		    window.location = "http://www.lifetimefitness.com/lifestyle";
			break;
		default:
			//Bypass redirect
	}
}


var _earthRadius = 3963;            //Radius of earth in miles
var _zoomLevel = 10;                //Default zoom level
var _numberOfLinksOnScreen = 5;     //Number of links to display on the screen (right side of the screen)
var _clubsMapInfo = new Array();    //Array of clubs
var _onEnterSubmitForm = false;     //Flag used to submit userInfo form when the enter key is pressed.
var _originName = "";               //Origin location

//Constructor
function ClubMapInfo(name, address, longitude, latitude, distanceFromOrigin, shapeIndex, clubId) {
    this.Name = name;
    this.Address = address;
    this.Longitude = longitude;
    this.Latitude = latitude;
    this.DistanceFromOrigin = distanceFromOrigin;
    this.ShapeIndex = shapeIndex;
    this.ClubId = clubId;
}

//Find location specified by the user
function FindLocation() {
    try {
        //Clean previous error messages, if any
        $("#reqSearchDiv").html("");
        //Clean previous location, if any
        _originName = "";
        if (document.getElementById("txtWhere").value != "") {
            map.Find(null, document.getElementById('txtWhere').value, null, null, 0, 20, false, false, false, false, FindNearestLocation);
        }
        else {
            $("#reqSearchDiv").append(" Please enter a location");
            HideNearestClubs();
        }
    } catch (e) {
        alert(e.message);
    }
}

//Callback method that finds, and shows the closest club to the location specified by the user.
function FindNearestLocation(layer, resultsArray, places, hasMore, veErrorMessage) {
    var origin;
    var nearestClub;
    var distance = 0;
    var tempDistance = 0;
    valLoc = new Boolean(true);

    //Set original location to...
    if (places != null && places.length > 0) {
        //... most popular matching location
        origin = new VELatLong(places[0].LatLong.Latitude, places[0].LatLong.Longitude);
        _originName = places[0].Name;
    }
    else {
        //... center of the map        
        $("#reqSearchDiv").append(" Unable to find location.");
        HideNearestClubs();
        valLoc = false;
    }

    if (valLoc && _clubsMapInfo.length > 0) {
        $("#nearestFiveSplash").hide();
        nearestClub = new VELatLong(_clubsMapInfo[0].Latitude, _clubsMapInfo[0].Longitude);
        distance = HaversineDistance(origin, nearestClub);
        _clubsMapInfo[0].DistanceFromOrigin = distance;

        for (var i = 1; i < _clubsMapInfo.length; i++) {
            tempDistance = HaversineDistance(origin, new VELatLong(_clubsMapInfo[i].Latitude, _clubsMapInfo[i].Longitude));
            _clubsMapInfo[i].DistanceFromOrigin = tempDistance;  //set club's distance from origin

            if (tempDistance < distance) {
                nearestClub = new VELatLong(_clubsMapInfo[i].Latitude, _clubsMapInfo[i].Longitude);
                distance = tempDistance;
            }
        }

        //Built-in sort method in javascript (if you pass in a function name, that function name is used to compare elements in the array for sorting purposes).
        _clubsMapInfo.sort(SortByDistance);
        DisplayClubsListOnScreen(_originName, false);
        SetMapView(nearestClub);
    }
}

function HideNearestClubs() {
    $("#nearestFiveSplash").show();
    $("#fromClubDiv").hide();
    $("#fromClubText").html("");
    $("#nearestClubsDiv").html("");
    $("#showHideDivClubs").html("");
    $("#clubListing").hide();
    $("#ulNearestClub").hide();
}

//This function returns -1, 0, or +1 as a value.
//-1 will put the first value before the second in the sorted array, 
//+1 will put the second value before the first, 
//0 means the values are equal.
function SortByDistance(a, b) {
    var x = a.DistanceFromOrigin;
    var y = b.DistanceFromOrigin;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function RoundDistance(distance) {
    return Math.round(distance * 100 / 100);
}

//The haversine formula calculates the shortest distance between 
//two points on a sphere from their longitudes and latitudes    
function HaversineDistance(location1, location2) {
    var lat1 = DegtoRad(location1.Latitude);
    var lon1 = DegtoRad(location1.Longitude);

    var lat2 = DegtoRad(location2.Latitude);
    var lon2 = DegtoRad(location2.Longitude);

    var dLat = lat2 - lat1;
    var dLon = lon2 - lon1;

    var cordLength = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dLon / 2), 2);
    var centralAngle = 2 * Math.atan2(Math.sqrt(cordLength), Math.sqrt(1 - cordLength));

    return _earthRadius * centralAngle;
}

function DegtoRad(x) {
    return x * Math.PI / 180;
}

function DisplayClubsListOnScreen(fromName, showAll) {
    //Clear div's content
    $("#fromClubDiv").show();
    $("#fromClubText").html("");
    $("#nearestClubsDiv").html("");
    $("#showHideDivClubs").html("");

    //From location
    $("#fromClubText").append("Distance nearest to farthest<br /><b>" + fromName + "</b>");

    //Set number of links to be displayed on the screen
    var numberOfLinks = _numberOfLinksOnScreen;
    if (showAll) {
        numberOfLinks = _clubsMapInfo.length; //all links
    }
    //The dinamically created links look like:
    //<a id='nearestClub0' class='showinfobox' href='' long='0' lati='0' shapeIndex='0'>ClubName (0 miles)</a><br />

    for (var i = 0; i < numberOfLinks; i++) {
    	var OnlineSalesButton = "";
    	var requestFrom = $("#requestFromPage").val();
        if (requestFrom == "OnlineSalesPage") {
            OnlineSalesButton +=
                "<div class='clubInfoImg'>" +
                    "<a class='OnlineSalesFooter' href='#' clubId='" + _clubsMapInfo[i].ClubId + "'>" +
                        "<img src='../images/Join-Now/btn-select-club-sm.gif' alt='Select Club' />" +
                    "</a>" +
                "</div>"
        }
        var link = "<li>" +
                    "<a id='clubDistance" + i +
                        "' href='' class='clubDistance' style='text-decoration: none;'" + //text-decoration must be inline so it doesn't get overwritten
                        "long='" + _clubsMapInfo[i].Longitude +
                        "' lati='" + _clubsMapInfo[i].Latitude +
                        "' shapeIndex='" + _clubsMapInfo[i].ShapeIndex + "'>" +
                            "<p class='clubDistanceText'>" +
                                RoundDistance(_clubsMapInfo[i].DistanceFromOrigin) + "<br />Miles" +
                            "</p></a>" +
                    "<div class='clubInfo'>" +
		                "<p class='clubInfoText' tabindex='10" + _clubsMapInfo[i].ShapeIndex + "'>" +
                            "<a id='nearestClub" + i +
                               "' href='' long='" + _clubsMapInfo[i].Longitude +
                               "' lati='" + _clubsMapInfo[i].Latitude +
                               "' shapeIndex='" + _clubsMapInfo[i].ShapeIndex + "'>"
                               + _clubsMapInfo[i].Name +
                            "</a><br />" + _clubsMapInfo[i].Address +
                         "</p>" +
                    "</div>" +
                    OnlineSalesButton
                    "</li>";
        //append elements to div
        $("#nearestClubsDiv").append(link);
    }

    $("#clubListing").show();
    $("#ulNearestClub").show();

    if (!showAll) {
        //Show all clubs link
        $("#showHideDivClubs").append("<span id='showAllSpan' class='spanLink' fromName='" + fromName + "'>Show all</span>");
    }
    else {
        $("#showHideDivClubs").append("<span id='hideAllSpan' class='spanLink' fromName='" + fromName + "'>Only show top 5</span>");
    }
}

function PopulateShape(elementId, clubName, clubDescription) {
    var shape = map.GetShapeByID(elementId);
    shape.SetTitle(clubName);
    shape.SetDescription(clubDescription);
    map.ShowInfoBox(shape);
}

function SetMapView(nearestClub) {
    map.SetMapView([nearestClub]);
    map.SetZoomLevel(_zoomLevel);
}

$(document).ready(function() {
	//Function created in code behind
	GetMap();

	//Attaches 'click' event to 'span' tags to show (or hide) all clubs
	$("#showHideDivClubs span").live("click", function(event) {
		if ($(this).attr("id") == "showAllSpan") {
			//show all
			DisplayClubsListOnScreen($(this).attr("fromName"), true);
		}
		else {
			//hide all
			DisplayClubsListOnScreen($(this).attr("fromName"), false);
		}
	});

	//Attaches 'click' event to club-links to reset map's view
	$("a").live("click", function(event) {
		if ($(this).parent().attr("class") == "clubInfoText" || $(this).attr("class") == "clubDistance") {
			//reset map view
			var nearestClub = new VELatLong($(this).attr("lati"), $(this).attr("long"));
			SetMapView(nearestClub);

			//By default, the base layer always has index 0
			//The layer that contains our pushpins is layer index 1
			var layer = map.GetShapeLayerByIndex(1);

			//retrieve shape
			var shapeIndex = parseInt($(this).attr("shapeIndex"));
			var shape = layer.GetShapeByIndex(shapeIndex);

			//display popup tabs with club description
			DisplayClubInfo(shape);
			return false;

		} else {
			if ($(this).attr("class") == "GuestPassPageFooter") {
				$("#hiddenClubId").val($(this).attr("clubId"));

				//NDM default location routing
				//get selected clubId
				locationRouting($(this).attr("clubId"));

				$(".GuestPassPageFooter").colorbox(
                {
                	width: "750px",
                	height: "400px",
                	inline: true,
                	href: "#ContactInfoDiv",
                	open: true,
                	onOpen: function() { _onEnterSubmitForm = true; ClearFields(); $('#txtFirstName').focus(); },
                	onClosed: function() { _onEnterSubmitForm = false; }
                });
				$("#colorbox").show();
				return false;
			}
			else if ($(this).attr("class") == "OnlineSalesFooter") {
				//save "search criteria" in hidden field so that the value can be 
				//stored in server side; in that way we will be able to "remember" the 
				//search criteria if the user decides to come back to the page.
				$("#" + _searchCriteriaFieldId).val(document.getElementById("txtWhere").value);
				//get selected clubId
				var clubId = $(this).attr("clubId");

				//NDM default location routing
				//get selected clubId
				locationRouting(clubId);
				
				__doPostBack('OnHomeClubSelection', clubId);
			}
			else {
				return true;
			}
		}
	});
});

function ClearFields() {
    $("#txtFirstName").val('');
    $("#txtLastName").val('');
    $("#txtEmail").val('');
    $("#txtPhone").val('');

    $("#requiredFirstName").html('');
    $("#requiredLastName").html('');
    $("#requiredEmail").html('');
    $("#requiredPhone").html('');
}

/* NEW AJAX FUNCTIONALITY */
function OnMouseOverDisplayClubInfo(e) {
    if (e.elementID != null) {
        //Get shape associated to elementId
        var shape = map.GetShapeByID(e.elementID);
        DisplayClubInfo(shape);
    }
}

function DisplayClubInfo(shape) {
    //Get shape's title
    var shapeTitle = shape.GetTitle();
    var shapeTitle2 = shapeTitle.replace('<span style=\'display:none;\'>', '');
    var clubTitle = shapeTitle2.replace('</span>', '');

    //If title is still a number (the number would be clubId)
    if (clubTitle == parseInt(clubTitle)) {
        //Find out where the request is coming from
        var requestFrom = $("#requestFromPage").val();
        //Get info associated to clubId
        GetClubDataFromServer(clubTitle, shape.GetID(), requestFrom);
    }
    else {
        //If title is alphanumeric, it means that we already have the club info.        
        map.ShowInfoBox(shape);
    }
}


function GetClubDataFromServer(clubId, elementId, requestFrom) {
    var data = "{clubId: \"" + clubId + "\", requestFrom:\"" + requestFrom + "\"}";
    $.ajax({
        type: "POST",
        url: "../Join-Now/GetClubInfoAsync.aspx/GetClubInfo",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            PopulateShape(elementId, response.d.ClubDescription, response.d.ClubDetailText);
        }
    });
}

$(document).ready(function () {
    $('#txtWhere').focus();

    //Switch popup description tabs
    $('#tabs a.infotab').live('click', function() {
        // Get the tab name
        var contentname = $(this).attr("id") + "Content";

        // hide all other tabs
        $("#tabsContent p").hide();
        $("#tabs li").removeClass("current");

        // show current tab
        $("#" + contentname).show();
        $(this).parent().addClass("current");
    });
});		
	


