﻿// Closure for all code
(function() {
    function registerNS(ns) {

        var nsParts = ns.split(".");
        var root = window;

        for (var i = 0; i < nsParts.length; i++) {

            if (typeof root[nsParts[i]] === "undefined")
                root[nsParts[i]] = new Object();

            root = root[nsParts[i]];
        }
    };

    /* Register namespace */
    registerNS("SkyGolf.landingCourseSearch");

    /* Declare global variables */
    var IsFacilityClubNameSearch = false;
    var FacilityClubName;
    var Location;
    var FacilitySearchResultsJSON;
    var WorkingFacilitySearchResultsJSON;
    var SortItem;
    var CurrentPageSize = 10;
    var CurrentPageIndex = 1;
    var PageCount = 0;
    var RecordX = 0;
    var RecordY = 0;
    var RecordJ = 0;
    var SGM;
    var FacilitySearchType;
    var QueueList;
    var SelectedPushPinID;
    var InValidCountryList = new Array('US', 'CA');
    var Geocoder;
    var IsSinglePushPin = false;

    var PageTemplate = { "self": "<table id=\"courseresultstable\" cellpadding=\"0\" cellspacing=\"0\"><thead></thead><tbody>{$}</tbody></table>",
        "self[*]": "<tr class=\"courserow\"><td class=\"facility\"><h3>{@facilityName($)}</h3></td><td class=\"location\"><div>{@address($)} <a href=\"#\" class=\"mapLink\" lat=\"{$.Latitude}\" long=\"{$.Longitude}\" title=\"{$.FacilityName}\" primaryCity=\"{$.PrimaryCity}\"  state=\"{$.State}\"  countryRegion=\"{$.CountryRegion}\" distance=\"{$.Distance}\" starRating=\"{$.StarRating}\" greenContourFlag=\"{$.GreenContourFlag}\">[ {@map($)} ]</a></div></td><td class=\"courses\" >{@courseList($.Courses)}</td><td class=\"coursefeatures\" width=\"175px\"><!--div>{@mapRating($)} </div--><!--div class=\"popularitystars{$.StarRating}\"--></div>{@courseFeatures($)}</td></tr><!--tr class=\"promo\"><td colspan=\"4\">{@downloadCoursePromo($)}</td></tr-->",
        "facilityName": function(data) {
            var name = '';
            if (facilityClubSGLink != '')
                name += '<a href="' + facilityClubSGLink + data.ID + '">';
            name += data.FacilityName;
            if (facilityClubSGLink != '')
                name += '</a>';
            return name;
        },
        "address": function(data) {
            var html = "";
            if (!!data.PrimaryCity && !!data.State && !!data.CountryRegion)
                html += data.PrimaryCity + ", " + data.State + " " + data.CountryRegion;
            else {
                if (!!data.State && !!data.CountryRegion)
                    html += data.State + " " + data.CountryRegion;
                else {
                    if (!!data.CountryRegion)
                        html += data.CountryRegion;
                }
            }
            // Display distance for multiple course results
            if (isMultipleCourseResult()) {
                // Check whether to display distance in metrics or US System
                var localeSetting = SG.getCookie("LocaleSetting");
                if (!!localeSetting) {
                    if (localeSetting.toUpperCase() === "EN-US")
                        html += " (" + data.Distance + ")mi";
                    else
                        html += " (" + Math.round((data.Distance * 1.609344) * 10) / 10 + ")km";
                }
                else {
                    html += " (" + data.Distance + ")mi";
                }
            }
            return html;
        },
        "courseList": function(courses) {
            var html = "";
            if (courses) {
                for (var i = 0; i < courses.length; i++) {
                    // Check if the CourseName is blank
                    if (courses[i].CourseName.length === 0) {
                        html += "<div>" + courses[i].NumberOfHoles + " " + $("input[name$='FacilitySearchHoles']").val() + "</div>";
                    } else {
                        html += "<div>" + courses[i].CourseName + ": " + courses[i].NumberOfHoles + " " + $("input[name$='FacilitySearchHoles']").val() + "</div>";
                    }
                }
            }
            return html;
        },
        "popularity": function(popularity) {
            return $("input[name$='FacilitySearchPopularity']").val() + " " + popularity;
        },
        "map": function(data) {
            // Retrieve localized content
            return $("input[name$='Map']").val();
        },
        "mapRating": function(data) {
            // Retrieve localized content
            return $("input[name$='FacilitySearchMapRating']").val();
        },

        "courseFeatures": function(data) {
            var html = "<div>";
            if (data.NextScheduledMappingDate != null && data.NextScheduledMappingDate != '') {
                html += '<span style=\"float:right;margin-top:10px;\"><span class=\"strong\">' + $("input[name$='FacilityNextScheduledMaintenance']").val() + ': </span>' + Date.Format(data.NextScheduledMappingDate, 'mm/yyyy') + '</span>';
            }
            // Check to see which course features to display
            // Professionally Mapped
            if (!!data.ProMapped) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html += '<a href=\'/support/course%20features/truegroundinfo.aspx\'><img class=\"promapped\" src=\"/images/icons/truegroundpromappedcourse.gif\" title=\"TrueGround&trade; Professionally-Mapped Courses | ' + SG.courseFeaturesToolTipContent[2] + '\" /></a>';
                html += '<a href=\'/support/course%20features/truegroundinfo.aspx\'><img class=\"promapped\" src=\"/images/icons/truegroundpromappedcourse.gif\" title=\"TrueGround&trade; Professionally-Mapped Courses ... Click here\" /></a>';
            }
            // Member Mapped
            if (!!data.MemberMapped) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html += '<a href=\'/support/course%20features/membermappedcourseinfo.aspx\'><img class=\"membermapped\" src=\"/images/icons/membermappedcourse.gif\" title=\"Member-Mapped Courses | ' + SG.courseFeaturesToolTipContent[3] + '\" /></a>';
                html += '<a href=\'/support/course%20features/membermappedcourseinfo.aspx\'><img class=\"membermapped\" src=\"/images/icons/membermappedcourse.gif\" title=\"Member-Mapped Courses ... Click here\" /></a>';
            }
            //Intelligreen
            if (!!data.Intelligreen) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html = '<a href=\'/support/course%20features/intelligreeninfo.aspx\'><img class=\"intelligreen\" src=\"/images/icons/igreen.gif\" title=\"IntelliGreen&reg; | ' + SG.courseFeaturesToolTipContent[1] + '\" /></a>';
                html += '<a href=\'/support/course%20features/intelligreeninfo.aspx\'><img class=\"intelligreen\" src=\"/images/icons/igreen.gif\" title=\"IntelliGreen&reg; ... Click here\" /></a>';
            }
            // Fairway Target
            if (!!data.FairwayTarget) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html += '<a href=\'/support/course%20features/virtualholeinfo.aspx\'><img class=\"fairwaytarget\" src=\"/images/icons/quickvue.gif\" title=\"SkyCaddie QuickVue&trade; | ' + SG.courseFeaturesToolTipContent[5] + '\" /></a>';
                html += '<a href=\'/support/course%20features/virtualholeinfo.aspx\'><img class=\"fairwaytarget\" src=\"/images/icons/quickvue.gif\" title=\"SkyCaddie QuickVue&trade; ... Click here\" /></a>';
            }
            // Intelligreen Pro - Display both Intelligreen and Intelligreen Pro icons
            if (!!data.GreenContour && ($("input[name$='DisplayGreenContour']").val() === "true")) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html = '<a href=\"/support/course%20features/intelligreenproinfo.aspx\"><img class=\"greencontour\" src=\"/images/icons/igreenpro.gif\" title=\"IntelliGreen&reg; PRO&trade; (Beta) | ' + SG.courseFeaturesToolTipContent[0] + '\" /></a><a href=\'/support/course%20features/intelligreeninfo.aspx\'><img class=\"intelligreen\" src=\"/images/icons/igreen.gif\" title=\"IntelliGreen&reg; | ' + SG.courseFeaturesToolTipContent[1] + '\" /></a>';
                html += '<a href=\"/support/course%20features/intelligreenproinfo.aspx\"><img class=\"greencontour\" src=\"/images/icons/igreenpro.gif\" title=\"IntelliGreen&reg; PRO&trade; (Beta) ... Click here\" /></a>';
            }
            // Hole Image
            if (!!data.HoleImage) {
                //TODO: Commenting out until FB #3829 is fixed
                //            html += '<a href=\'/support/course%20features/fullgraphicholevueinfo.aspx\'><img class=\"holeimage\" src=\"/images/icons/holevue.gif\" title=\"HoleVue&trade; | ' + SG.courseFeaturesToolTipContent[4] + '\" /></a>';
                html += '<a href=\'/support/course%20features/fullgraphicholevueinfo.aspx\'><img class=\"holeimage\" src=\"/images/icons/holevue.gif\" title=\"HoleVue&trade; ... Click here\" /></a>';
            }
            if (data.MappedFlag == false) {
                html = '<div class=\"strong\" style=\"width:100%;margin-top:2px;margin-bottom:4px;\">' + $("input[name$='FacilityNotMapped']").val();
            }
            if (data.NotMappedReasonCode != null && data.NotMappedReasonCode != '' && data.NotMappedReasonCode.toLowerCase() != 'none') {
                var notMappedReason = null;
                for (var reasonCodeKey in unmappedReasonCodes.items) {
                    var reasonCode = unmappedReasonCodes.items[reasonCodeKey];
                    if (reasonCode.reasonCodeId == data.NotMappedReasonCode) {
                        notMappedReason = reasonCode;
                        break;
                    }
                }
                if (notMappedReason != null) {
                    html += '</div>';
                    html += '<div style=\"margin-bottom:4px;\"><span>' + notMappedReason.reasonCodeText + '</span>';
                    if ((notMappedReason.callToActionText != null && notMappedReason.callToActionText != '') &&
                    (data.NextScheduledMappingDate == null || data.NextScheduledMappingDate == '')) {
                        html += '<div style=\"align:right;padding-bottom:4px;\"><a href=\"javascript:SG.showMessage(\'' + notMappedReason.callToActionText + '\');\">' + notMappedReason.callToActionLinkText + '</a></div>';
                    }
                    if (data.NextScheduledMappingDate != null && data.NextScheduledMappingDate != '') {
                        html += '</div>';
                        if (notMappedReason.callToActionText != null && notMappedReason.callToActionText != '') {
                            html += '<span style=\"float:right;padding-bottom:4px;\"><a href=\"javascript:SG.showMessage(\'' + notMappedReason.callToActionText + '\');\">' + notMappedReason.callToActionLinkText + '</a></span>';
                        }
                        html += '<div ';
                        if (notMappedReason.callToActionText != null && notMappedReason.callToActionText != '')
                            html += 'style=\"display:inline\"';
                        else
                            html += 'style=\"padding-bottom:4px;\"';
                        html += '><span class=\"strong\">' + $("input[name$='FacilityNextScheduledMaintenance']").val() + ': </span>' + Date.Format(data.NextScheduledMappingDate, 'mm/yyyy');
                    }
                }
                else if (data.MappedFlag == false && data.NextScheduledMappingDate != null && data.NextScheduledMappingDate != '') {
                    html += '</div><div style=\"padding-bottom:4px;\"><span class=\"strong\">' + $("input[name$='FacilityNextScheduledMaintenance']").val() + ': </span>' + Date.Format(data.NextScheduledMappingDate, 'mm/yyyy');
                }
            }
            else if (data.MappedFlag == false && data.NextScheduledMappingDate != null && data.NextScheduledMappingDate != '') {
                html += '</div><div style=\"padding-bottom:4px;\"><span class=\"strong\">' + $("input[name$='FacilityNextScheduledMaintenance']").val() + ': </span>' + Date.Format(data.NextScheduledMappingDate, 'mm/yyyy');
            }
            html += "</div>";
            return html;
        },
        "downloadCoursePromo": function(data) {
            return $("input[name$='FacilitySearchDownloadCoursePromo']").val() + "? " + "<a href=\"../membership/owners.aspx\">[ " + $("input[name$='ClickHere']").val() + " ]</a>";
        }
    };

    var MapTemplate = { "self": "<div class=\"mappopupcontainer\"><div>{@address($)}</div></div>",
        "address": function(data) {
            var html = "";
            if (!!data.PrimaryCity && !!data.State && !!data.CountryRegion)
                html += data.PrimaryCity + ", " + data.State + " " + data.CountryRegion;
            else {
                if (!!data.State && !!data.CountryRegion)
                    html += data.State + " " + data.CountryRegion;
                else {
                    if (!!data.CountryRegion)
                        html += data.CountryRegion;
                }
            }
            // Display distance for multiple course results
            if (isMultipleCourseResult()) {
                // Check whether to display distance in metrics or US System
                var localeSetting = SG.getCookie("LocaleSetting")
                if (!!localeSetting) {
                    if (localeSetting.toUpperCase() === "EN-US")
                        html += " (" + data.Distance + ")mi";
                    else
                        html += " (" + Math.round((data.Distance * 1.609344) * 10) / 10 + ")km";
                }
                else {
                    html += " (" + data.Distance + ")mi";
                }
            }
            return html;
        },
        "popularity": function(popularity) {
            return $("input[name$='FacilitySearchPopularity']").val() + " " + popularity;
        },
        "courseFeatures": function(data) {
            var html = "";
            // Check to see which course features to display
            if (!data.GreenContour && ($("input[name$='DisplayGreenContour']").val() === "true")) {
                html = '<img src=\"/images/icons/greencontour.gif\" title="' + $("input[name$='GreenContourToolTip']").val() + '"/>';
            }
            return html;
        }
    };

    /* Setup global click handler functions */
    SG.clickHandler.events =
    {
        searchSubmit: function($e) {
            executeSearch();
        },
        mapViewedCourses: function($e) {
            IsSinglePushPin = false;
            // Add light box layer
            $.blockUI({ message: $('.lightbox'), css: { width: '700px', left: getWindowLeftPosition() }, fadeOut: 0 });
            // Add light box click event
            $('.lightbox_close').click(function() {
                $.unblockUI({ onUnblock: SG.unblockIE, fadeOut: 0 });
                return false;
            });
            // Check if Virtual Earth Map control has been loaded
            if (SG.IsUndefinedOrNull(SGM)) {
                if (SG.IsUndefinedOrNull(CurrentPageSize))
                    CurrentPageSize = Number($("input:radio[name$='results_limit']:checked").val());
                SGM = new SkyGolfMap({ mapID: 'myMap', json: FacilitySearchResultsJSON.slice(RecordX - 1, RecordJ - 1), itemTemplate: MapTemplate,
                    onLoadFunction: onMapLoaded
                });
            }
            else {
                // map already exists, refresh the pushpin data
                // Call the add push pin method in this file.
                if (SG.IsUndefinedOrNull(CurrentPageSize))
                    CurrentPageSize = Number($("input:radio[name$='results_limit']:checked").val());
                SGM.setPushPinData(FacilitySearchResultsJSON.slice(RecordX - 1, RecordJ - 1), MapTemplate);
                addPushPins(FacilitySearchResultsJSON.slice(RecordX - 1, RecordJ - 1));
            }
            return true;
        },
        mapLink: function($e) {
            IsSinglePushPin = true;
            // instantiate the json object full of map data
            var link = $e;
            var data = { items: [{ Title: link.attr('title'), Latitude: parseFloat(link.attr('lat')),
                Longitude: parseFloat(link.attr('long')), PrimaryCity: link.attr('primaryCity'), State: link.attr('state'),
                CountryRegion: link.attr('countryRegion'), Distance: link.attr('distance'), StarRating: link.attr('starRating'),
                GreenContourFlag: parseInt(link.attr('greenContourFlag'))}]
            };
            // Add light box layer
            $.blockUI({ message: $('.lightbox'), css: { width: '700px', left: getWindowLeftPosition() }, fadeOut: 0 });
            // Add light box click event
            $('.lightbox_close').click(function() {
                $.unblockUI({ onUnblock: SG.unblockIE, fadeOut: 0 });
                return false;
            });
            // Check if Virtual Earth Map control has been loaded
            WorkingFacilitySearchResultsJSON = data;
            CurrentPageSize = WorkingFacilitySearchResultsJSON.length;
            if (SG.IsUndefinedOrNull(SGM)) {
                SGM = new SkyGolfMap({ mapID: 'myMap', json: data, itemTemplate: MapTemplate,
                    onLoadFunction: onMapLoaded
                });
            }
            else {
                // map already exists, refresh the pushpin data
                // Call the add push pin method in this file.
                SGM.setPushPinData(data, MapTemplate);
                addSinglePushPin(data);
            }
            return true;
        },
        lightbox_close: function($e) {
            $.unblockUI({ onUnblock: SG.unblockIE, fadeOut: 0 });
            return true;
        },
        closeMsgBox: function($e) {
            $.unblockUI({ onUnblock: SG.unblockIE, fadeOut: 0 });
            return false;
        }
    };

    var isRequiredFieldSet = function() {
        FacilityClubName = $("input[name$='FacilityCourseName']").val().ltrim().rtrim();
        Location = $("input[name$='Location']").val().ltrim().rtrim();
        if (FacilityClubName.length === 0 && Location.length === 0) {
            return false;
        }
        // Check if Facility Club Name search
        if (FacilityClubName.length > 0 && Location.length === 0)
            IsFacilityClubNameSearch = true;
        else
            IsFacilityClubNameSearch = false;
        return true;
    };

    var isValidCountrySearch = function() {
        // Get Search Type
        FacilitySearchType = $("input[name$='Type']").val();
        var locationCountryISO2 = $("input[name$='CountryISO2']").val();
        // Check if country search for either USA, Canada or United Kingdom was requested
        if (FacilitySearchType && FacilitySearchType.toUpperCase() === "COUNTRY" && locationCountryISO2 && jQuery.inArray(locationCountryISO2, InValidCountryList) > -1) {
            showMessage($("input[name$='FacilitySearchCountryErrMsg']").val());
            // Clear out hidden search parameters
            clearHiddenFields();
            return false;
        }
        return true;
    };

    var executeSearch = function() {
        if (isRequiredFieldSet()) {
            // Check if performing a Facility Club Name based search
            if (IsFacilityClubNameSearch) {
                // Submit search request
                submitSearchRequest();
            } else {
                // Check if search request was submitted without auto-complete data
                var locationLatitude = $("input[name$='Latitude']").val();
                var locationLongitude = $("input[name$='Longitude']").val();
                if ((locationLatitude === "" || locationLatitude === "0") && (locationLongitude === "" || locationLongitude === "0") && SG.browserSupportsGoogleMaps()) {
                    // Create new geocoding object
                    if (typeof Geocoder === "undefined" || Geocoder === null) {
                        Geocoder = new GClientGeocoder();
                    }
                    // Retrieve location information and pass it location and pointer to callback function
                    // Note: This is an asynchronous call, so all resulting logic should be executed within callback function
                    Geocoder.getLocations(Location, getLocationInfo);
                    return;
                }
                // Check if valid country search
                if (isValidCountrySearch()) {
                    // Submit search request
                    submitSearchRequest();
                } else {
                    // Hide loading grahic
                    $(".loader").hide();
                    $("#scTxtCoursesPromoText").show();
                }
            }
        } else {
            // Hide loading grahic
            $(".loader").hide();
            $("#scTxtCoursesPromoText").show();
        }
    };

    var getLocationInfo = function(response) {
        // check for valid responses
        if (response.Status.code === G_GEO_SUCCESS) {
            // Retrieve the object
            place = response.Placemark[0];
            // Check Accuracy
            switch (place.AddressDetails.Accuracy) {
                case 1: // Country
                    // set facility search type hidden variable
                    $("input[name$='Type']").val("country");
                    // set country code
                    $("input[name$='CountryISO2']").val(place.AddressDetails.Country.CountryNameCode);
                    break;
                case 2: // State
                    var countryISO2 = place.AddressDetails.Country.CountryNameCode;
                    // check  if AdministrativeArea is defined and CountryNameCode is "US"
                    if (place.AddressDetails.Country.AdministrativeArea && countryISO2 && countryISO2.toUpperCase() === "US") {
                        // check if AdministrativeArea is an accurate 2 character state code
                        if (place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName.length === 2) {
                            // set facility search type hidden variable
                            $("input[name$='Type']").val("state");
                            // set state code
                            $("input[name$='StateCode']").val(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
                        } else {
                            // TODO: This is a temporary hack for launch on 02/03/2009.  This will need to be re-architect after launch.
                            // Check if AdministrativeAreaName is either of the following states
                            switch (place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName.toUpperCase()) {
                                case "N CAROLINA":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("NC");
                                    break;
                                case "S CAROLINA":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("SC");
                                    break;
                                case "N DAKOTA":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("ND");
                                    break;
                                case "S DAKOTA":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("SD");
                                    break;
                                case "W VIRGINIA":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("WV");
                                    break;
                                case "RHODE ISL":
                                    // set facility search type hidden variable
                                    $("input[name$='Type']").val("state");
                                    // set state code
                                    $("input[name$='StateCode']").val("RI");
                                    break;
                                default:
                                    // set facility search type hidden variable to unknow to execute a radius search
                                    $("input[name$='Type']").val("unknown");
                                    break;
                            }
                        }
                    } else if ((place.AddressDetails.Country && countryISO2 && countryISO2.toUpperCase() === "GB")) {  // check  if CountryNameCode is "GB"
                        var UnitedKingdomCountryZones = new Array(4);
                        for (i = 0; i < UnitedKingdomCountryZones.length; ++i) {
                            UnitedKingdomCountryZones[i] = new Array(1);
                        }
                        // populate array
                        UnitedKingdomCountryZones[0][0] = "england";
                        UnitedKingdomCountryZones[0][1] = "EN";
                        UnitedKingdomCountryZones[1][0] = "scotland";
                        UnitedKingdomCountryZones[1][1] = "SC";
                        UnitedKingdomCountryZones[2][0] = "wales";
                        UnitedKingdomCountryZones[2][1] = "WA";
                        UnitedKingdomCountryZones[3][0] = "northern ireland";
                        UnitedKingdomCountryZones[3][1] = "NI";
                        // set facility search type hidden variable to unknown to execute a radius search
                        $("input[name$='Type']").val("unknown");
                        // loop through array to see which country was specified
                        for (var i = 0; i < UnitedKingdomCountryZones.length; i++) {
                            var regexp = new RegExp(UnitedKingdomCountryZones[i][0], "gi");
                            if (regexp.test(place.AddressDetails.Country.AddressLine[0])) {
                                // set facility search type hidden variable
                                $("input[name$='Type']").val("zone");
                                // set zone code
                                $("input[name$='StateCode']").val(UnitedKingdomCountryZones[i][1]);
                                break;
                            }
                        }
                    } else {
                        // set facility search type hidden variable to unknown to execute a radius search
                        $("input[name$='Type']").val("unknown");
                    }
                    // set country code
                    $("input[name$='CountryISO2']").val(countryISO2);
                    break;
                default:
                    // set facility search type hidden variable to unknown to execute a radius search
                    $("input[name$='Type']").val("unknown");
                    break;
            }
            // set location latitude and longitude
            $("input[name$='Latitude']").val(place.Point.coordinates[1]);
            $("input[name$='Longitude']").val(place.Point.coordinates[0]);
        }
        // Clear place object
        place = null;
        // Check if valid country search request
        if (isValidCountrySearch()) {
            // Submit search request
            submitSearchRequest();
        } else {
            // Hide loading grahic
            $(".loader").hide();
            $("#scTxtCoursesPromoText").show();
        }
    };

    var submitSearchRequest = function() {
        // Show loading graphic
        $("#scTxtCoursesPromoText").hide();
        $(".loader").css("display", "block");
        // Call WCF service to execute search
        var locationLatitude = $("input[name$='Latitude']").val().toString();
        var locationLongitude = $("input[name$='Longitude']").val().toString();
        var locationSubdvisionCode = $("input[name$='StateCode']").val();
        var locationCountryISO2 = $("input[name$='CountryISO2']").val();
        SG._sendRequest({
            url: '/services/facilitysearchservice.svc/ExecuteSearch',
            data: '{"facilityClubName":\"' + FacilityClubName + '\","location":\"' + Location + '\","locationLatitude":\"' + locationLatitude + '\","locationLongitude":\"' + locationLongitude + '\","locationSubdivisionCode":\"' + locationSubdvisionCode + '\","locationCountryISO2":\"' + locationCountryISO2 + '\","locationType":\"' + FacilitySearchType + '\"}',
            success: function(d, s) {
                // Check if any data was returned
                if (!!d && !!d.length) {
                    displaySearchResults(d);
                } else {
                    FacilitySearchResultsJSON = "";
                    // Display no records found content
                    displayNoRecordsFoundContent();
                }
            },
            error: function(x, s, e) {
                var error = s;
                // Display no records found content
                displayNoRecordsFoundContent();
            }
        });
        // Clear out hidden search parameters
        clearHiddenFields();
    };

    var displayNoRecordsFoundContent = function() {
        // Hide loading grahic
        $(".loader").hide();
        $("#scTxtCoursesPromoText").show();
        // Hide the search results items
        $("#courseresultscontainer, #nosearch, .courseresultpaging").hide();
        // Display no records message
        $("#norecords").show();
        $(".courseresultscontrols").show().css("border-bottom", "");
    };

    var displaySearchResults = function(d) {
        FacilitySearchResultsJSON = d;
        CurrentPageIndex = 1;
        // Check whether any courses were returned
        if (!(!!FacilitySearchResultsJSON) || FacilitySearchResultsJSON.length === 0) {
            displayNoRecordsFoundContent();
        } else {
            // Show the search results items
            $("#courseresultscontainer, .courseresultpaging").show();
            // Hide no records found content
            $("#norecords").hide();
            $(".courseresultscontrols").css("border-bottom", "1px solid #c4c8cd");
            // Display HTML Content
            displayShowOptions();
            displaySortOptions();
            displayPagingContent();
            buildHTMLContent();
        }
    };

    var displayShowOptions = function() {
        var totalRecords = FacilitySearchResultsJSON.length;
        // Set the default show options
        $("#results_limit50").attr("checked", "true");
        CurrentPageSize = Number($("#results_limit50").val());
        // Check which Show options radio buttons to display
        if (totalRecords < 50) {
            $("#results_limit100").parent("li").css("display", "none");
        } else {
            $("#results_limit100").parent("li").css("display", "inline");
        }
    };

    var displaySortOptions = function() {
        // Do not execute sorting if only one results is returned
        if (!(!!FacilitySearchResultsJSON) || FacilitySearchResultsJSON.length > 1) {
            // Show sort options
            $("#results_sort").parent("li").show();
            // Check if performing a Facility Club Name based search
            if (IsFacilityClubNameSearch) {
                // Execute FacilityClubNameRank sort
                SortItem = "FacilityClubNameRank";
            } else {
                // Execute FacilityClubNameASC sort
                SortItem = "FacilityClubNameASC";
            }
            FacilitySearchResultsJSON.sort(sortCallBack);
        } else {
            // Hide sort options
            $("#results_sort").parent("li").hide();
        }
    };

    var sortCallBack = function(a, b) {
        switch (SortItem.toUpperCase()) {
            case "DISTANCE":
                return (a.Distance - b.Distance);
            case "FACILITYCLUBNAMEASC":
                if (a.FacilityName === b.FacilityName) {
                    return 0;
                }
                return (a.FacilityName < b.FacilityName) ? -1 : 1;
            case "FACILITYCLUBNAMEDESC":
                if (b.FacilityName === a.FacilityName) {
                    return 0;
                }
                return (b.FacilityName < a.FacilityName) ? -1 : 1;
            case "FACILITYCLUBNAMERANK":
                // Check if records have the same ranking
                if (a.Rank === b.Rank) {
                    // Sort by Facility Rank ascending
                    if (a.FacilityRank === b.FacilityRank)
                        return 0;
                    return (a.FacilityRank - b.FacilityRank);
                } else {
                    // Sort by Rank descending
                    return (b.Rank - a.Rank);
                }
            default:
                if (a.FacilityName === b.FacilityName) {
                    return 0;
                }
                return (a.FacilityName < b.FacilityName) ? -1 : 1;
        }
    };

    var displayPagingContent = function() {
        var newContent;
        RecordX = ((CurrentPageIndex - 1) * CurrentPageSize) + 1;
        RecordY = (RecordX + CurrentPageSize) - 1;
        RecordJ = RecordY + 1;
        // Check if on the last page?
        if (RecordY > FacilitySearchResultsJSON.length) {
            RecordY = FacilitySearchResultsJSON.length;
        }
        newContent = RecordX + " - " + RecordY + " of " + FacilitySearchResultsJSON.length;
        $(".current").text(newContent);
        createPageList();
    };

    //the list of pages for direct selection as well as forward/next and first/last
    var createPageList = function() {
        var txtHTML = "";
        var j = 0;
        var displayDotPlaceHolder = true;
        PageCount = Math.ceil(FacilitySearchResultsJSON.length / CurrentPageSize);
        if (CurrentPageIndex != 1) {
            txtHTML = "<a href='#1'>&lt;&lt;</a> <a href='#prev'>&lt;</a>";
        }
        for (i = 1; i <= PageCount; i++) {
            j++;
            // Only display the previous page and 1st page 
            if (i >= CurrentPageIndex - 1) {
                // Display "..."
                if ((j >= CurrentPageIndex + 10) && (i != PageCount)) {
                    if (displayDotPlaceHolder) {
                        displayDotPlaceHolder = false;
                        txtHTML += " <span>...</span>";
                    }
                } else {
                    txtHTML += " <a href='#" + i + "'";
                    if (i === CurrentPageIndex) {
                        txtHTML += " class='active'";
                    }
                    txtHTML += ">" + i + "</a>";
                }
            }
        }
        if (CurrentPageIndex != PageCount) {
            txtHTML += " <a href='#next'>&gt;</a> <a href='#last'>&gt;&gt;</a>";
        }
        $(".pagelist").html(txtHTML);
        $(".pagelist a").click(function(e) {  //this is the click event for the page list anchor tags 
            e.preventDefault();
            var target = $(e.target).attr("href"); //HREF attribute is a hash and “prev", “last" or a number
            target = target.replace(document.location, "");
            target = target.replace("#", "");  //strip the hash
            changePage(target); //trigger the page changer
        })
    };

    //clicking on a page number, forward/back or first/last
    var changePage = function(target) {
        var newPage = 0;
        switch (target) {
            case "last": //double arrows on the right – go to last page
                newPage = PageCount
                break;
            case "next": //single arrow on the right – next page
                newPage = CurrentPageIndex + 1;
                break;
            case "prev":  //single arrow to the left – previous page
                newPage = CurrentPageIndex - 1;
                break;
            default: //all other HREFs have numerical values that are indicative of page index
                newPage = target;
                break;
        }
        newPage = Math.abs(newPage);
        CurrentPageIndex = newPage;
        // Render paged HTML content
        displayPagingContent();
        buildHTMLContent();
    };

    var buildHTMLContent = function() {
        var json;
        // Check if on the last records
        if (RecordY === FacilitySearchResultsJSON.length) {
            json = FacilitySearchResultsJSON.slice(RecordX - 1);
        } else {
            json = FacilitySearchResultsJSON.slice(RecordX - 1, RecordJ - 1);
        }
        // Hide the default map and show the search results containers
        $('#nosearch').hide();
        $('#courseresultscontainer, .courseresultscontrols, .courseresultscontrolsbottom').show();
        $('#topcontentcourses').css('height', 'auto');
        // Bind HTML to element
        $("#courseresultscontainer").html("");
        $("#courseresultscontainer").html(jsonT(json, PageTemplate));
        // Stype first row
        $("tr:first", $("#courseresultstable")).addClass("first");
        // Hide loading grahic
        $(".loader").hide();
        $("#scTxtCoursesPromoText").show();
        /* Check whether browser supports Virtual Earth Map Control */
        if (SG.browserSupportsVirtualEarthMaps()) {
            $(".mapViewedCourses").show();
            $(".mapLink").show();
        }
        else {
            $(".mapViewedCourses").hide();
            $(".mapLink").hide();
        }
        // Wireup Tooltips
        //        activateToolTips();
    };

    var clearHiddenFields = function() {
        $("input[name$='Latitude']").val("");
        $("input[name$='Longitude']").val("");
        $("input[name$='StateCode']").val("");
        $("input[name$='CountryISO2']").val("");
        $("input[name$='Type']").val("");
    };

    var isMultipleCourseResult = function() {
        if (!!FacilitySearchResultsJSON && FacilitySearchResultsJSON.length > 1)
            return true;
        else
            return false;
    };

    var getWindowLeftPosition = function() {
        var w = $("body").width();
        w = Math.round((w - 700) / 2);
        w = w + "px";
        return w;
    };

    var onMapLoaded = function() {
        // Add mouse over event to each shape
        SGM.getMap().AttachEvent("onmouseover", getShapeInfo);
        if (IsSinglePushPin) {
            // Add a single push pin
            addSinglePushPin(WorkingFacilitySearchResultsJSON);
        } else {
            // Add push pins
            addPushPins(FacilitySearchResultsJSON.slice(0, CurrentPageSize));
        }
    };

    var getShapeInfo = function(mapEvent) {
        SelectedPushPinID = mapEvent.elementID;
    };

    var addPushPins = function(json) {
        var json = SGM.getData();               // pull the data from the map.  It should have been stored there
        var template = SGM.getTemplate();       // pull the data from the map...
        if (!SG.IsUndefinedOrNull(json) && !SG.IsUndefinedOrNull(template)) {
            // Sort data by distance
            SortItem = "Distance";
            json.sort(sortCallBack);
            // Add all the pushpins
            SGM.addPushPins();
            // Check for only one pushpin
            if (json.length === 1) {
                // Pan, Center and Zoom onto the first pushpin
                SGM.pan(json[0].Latitude, json[0].Longitude);
                SGM.centerAndZoom(json[0].Latitude, json[0].Longitude, 1);
            } else {
                // Check if Facility Club Name based search
                if (IsFacilityClubNameSearch) {
                    // Pan, Center and Zoom onto the Equator
                    SGM.pan(0.0, 0.0);
                    SGM.centerAndZoom(0.0, 0.0, json[json.length - 1].Distance);
                } else {
                    // Pan, Center and Zoom onto the first pushpin
                    SGM.pan(json[0].Latitude, json[0].Longitude);
                    SGM.centerAndZoom(json[0].Latitude, json[0].Longitude, json[json.length - 1].Distance);
                }
            }
        }
    };

    var addSinglePushPin = function(json) {
        var json = SGM.getData();               // pull the data from the map.  It should have been stored there
        var template = SGM.getTemplate();       // pull the data from the map...

        if (!SG.IsUndefinedOrNull(json) && !SG.IsUndefinedOrNull(template)) {
            // add all the pushpins
            SGM.addPushPin();
            if (!!json && !!json.items && json.items.length > 0) {
                // center and zoom onto the first pushpin.
                SGM.pan(json.items[0].Latitude, json.items[0].Longitude);
                SGM.centerAndZoom(json.items[0].Latitude, json.items[0].Longitude, 1);
            }
        }
    };

    var setupPageEvents = function() {
        /* Setup click event handlers */
        SG.clickHandler.globalEvents = {};
        SG.clickHandler.activate();
        /* Set auto complete data for Facility Locations */
        if ($("input[name$='Location']").length > 0) {
            $("input[name$='Location']").autocomplete("/services/facilitylocationservice.svc/GetFacilityLocations", {
                delay: 400,
                minChars: 3,
                matchSubset: true,
                matchContains: true,
                cacheLength: 10,
                maxItemsToShow: 10,
                max: 50,
                scrollHeight: 220,
                selectFirst: false,
                autoFill: false,
                width: 303,
                dataType: "json",
                formatItem: function(row) {
                    return row.Name;
                }
            });
            $("input[name$='Location']").result(function(event, data, formatted) {
                $("input[name$='Latitude']").val(data.Latitude);
                $("input[name$='Longitude']").val(data.Longitude);
                $("input[name$='StateCode']").val(data.StateCode);
                $("input[name$='CountryISO2']").val(data.CountryISOCode);
                $("input[name$='Type']").val(data.LocationType);

                if (SkyGolf.landingCourseSearch.executeSearchAfterAutoComplete == true) {
                    executeSearch();
                }
            });
        }
        /* Set auto complete data for Facility Names */
        if ($("input[name$='FacilityCourseName']").length > 0) {
            $("input[name$='FacilityCourseName']").autocomplete("/services/facilitylocationservice.svc/GetFacilityNames", {
                delay: 400,
                minChars: 4,
                matchSubset: true,
                matchContains: true,
                extraParams: { blacklistlength: 4 },
                cacheLength: 10,
                maxItemsToShow: 10,
                max: 1000,
                scrollHeight: 220,
                selectFirst: false,
                autoFill: false,
                width: 303,
                dataType: "json",
                formatItem: function(row) {
                    var displayValue = "";
                    if (!!row.FacilityName) {
                        displayValue = row.FacilityName;
                        if (!!row.State && !!row.CountryRegion)
                            displayValue += " (" + row.State + ", " + row.CountryRegion + ")";
                        else {
                            if (!!row.CountryRegion)
                                displayValue += " (" + row.CountryRegion + ")";
                        }
                    }
                    return displayValue;
                }
            });
            $("input[name$='FacilityCourseName']").result(function(event, data, formatted) {
                // Overwrite "formatted" value with FacilityName
                $("input[name$='FacilityCourseName']").val(data.FacilityName);
                // Enable Search button
                $(".btn").removeClass("disabled");
                var location = "";
                if (!!data.PrimaryCity && !!data.State) {
                    location += data.PrimaryCity + ", " + data.State;
                    $("input[name$='Type']").val("radius");
                }
                else {
                    if (!!data.State && !!data.CountryRegion) {
                        location += data.State + ", " + data.CountryRegion;
                        $("input[name$='Type']").val("state");
                    }
                    else {
                        if (!!data.CountryRegion) {
                            location += data.CountryRegion;
                            $("input[name$='Type']").val("country");
                        }
                    }
                }
                $("input[name$='Latitude']").val(data.Latitude);
                $("input[name$='Longitude']").val(data.Longitude);
                $("input[name$='StateCode']").val(data.State);
                $("input[name$='CountryISO2']").val(data.CountryISOCode);

                // Display Search Results
                executeSearch();
                if ($('#txtLocation').length > 0) { $('#txtLocation').focus(); $('#txtLocation').focus(); }
            });
        }

        /* Setup other event handlers */
        $("input[name$='FacilityCourseName']").bind("mouseleave", function() {
            if ($("input[name$='FacilityCourseName']").val().ltrim().rtrim().length === 0 &&
                $("input[name$='Location']").val().ltrim().rtrim().length === 0) {
                $(".btn").addClass("disabled");
            } else {
                $(".btn").removeClass("disabled");
            }
        });
        $("input[name$='Location']").bind("mouseleave", function() {
            if ($("input[name$='Location']").val().ltrim().rtrim().length === 0 &&
                $("input[name$='FacilityCourseName']").val().ltrim().rtrim().length === 0) {
                $(".btn").addClass("disabled");
            } else {
                $(".btn").removeClass("disabled");
            }
        });
        $("input").keypress(function(e) {
            // Execute search if enter was pressed
            if (e.which === 13) {
                // Execute search if on the Facility Search page
                executeSearch();
                return false;
            }
        });
        $("#results_sort").change(function() {
            if (this.selectedIndex > 0) {
                // Show loading graphic
                $("#scTxtCoursesPromoText").hide();
                $(".loader").css("display", "block");
                // Get the value of the selected item and execute sort
                SortItem = this.options[this.selectedIndex].value;
                // Sort results
                FacilitySearchResultsJSON.sort(sortCallBack);
                // Set selected sort option
                $("#results_sort").val(SortItem);
                // Display HTML Content
                CurrentPageSize = Number($("input:radio[name='results_limit']:checked").val());
                buildHTMLContent();
            }
        });
        $("label[for=results_limit10],#results_limit10").click(function(e) {
            showOptionsClick();
        });
        $("label[for=results_limit50],#results_limit50").click(function(e) {
            showOptionsClick();
        });
        $("label[for=results_limit100],#results_limit100").click(function(e) {
            showOptionsClick();
        });
    };

    var showOptionsClick = function() {
        // Show loading graphic
        $("#scTxtCoursesPromoText").hide();
        $(".loader").css("display", "block");
        // Get the value of the selected item
        CurrentPageSize = Number($("input:radio[name='results_limit']:checked").val());
        // Set selected sort option to default
        $("#results_sort").val("");
        // Set the current page index to default
        CurrentPageIndex = 1;
        // Display HTML Content
        displayPagingContent();
        buildHTMLContent();
    };

    var showMessage = function(msg) {
        if (!!msg && msg.toString().length > 0) {
            var $message = $('.MessageBox').find('.message').html(msg).end();
            $.blockUI({ message: $message, css: { width: '700px', left: getWindowLeftPosition() }, fadeOut: 0 });
            $(".MessageBox").css("left", getWindowLeftPosition());
            $message = null;
        }
    };

    var activateToolTips = function() {
        $('.greencontour').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 315, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
        $('.intelligreen').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 315, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
        $('.promapped').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 395, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
        $('.membermapped').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 315, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
        $('.holeimage').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 315, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
        $('.fairwaytarget').cluetip({ cluetipClass: 'rounded', splitTitle: '|', dropShadow: false, sticky: true, ajaxCache: false, arrows: true, waitImage: true, positionBy: 'mouse', leftOffset: 15, width: 335, mouseOutClose: true, closeText: '<img src=\"/images/common/queue_x.gif\" />' });
    };

    SkyGolf.landingCourseSearch.init = function() {
        // Show the map and hide the search results containers
        $("#courseresultscontainer, .courseresultscontrols, .courseresultscontrolsbottom, #norecords").hide();
        $("#topcontentcourses").css("height", "1000px");
        // Setup page Events
        setupPageEvents();
        /* Check whether browser supports Google Maps Control */
        if (SG.browserSupportsGoogleMaps()) {
            // Load Google Maps Control
            $.getScript("http://www.google.com/maps?file=api&v=2&async=2&key=ABQIAAAABQfZZFn45uKQ2Ek_y4fBOxRA4W3WWxV73DaMA-Dqa3wZgNud6BRWbPAVw8ZRf0Z61Rnp-BpbiiVzBQ", "", true);
        }

        $("input[name$='FacilityCourseName']").bind(($.browser.opera ? "keypress" : "keydown"), function(event) {
            if (event.keyCode == 9) {
                setTimeout('$("#txtLocation").focus().focus();', 500);
                if ($("input[name$='FacilityCourseName']").val().length > 2) {
                    $(".btn").removeClass("disabled");
                }
            }
        });

        var name = gup('name');
        var location = gup('location');
        if (name != '') {
            $('#txtFacilityCourseName').val(name);
            $('#txtFacilityCourseName').trigger('onchange');
            if (location != '') {
                SkyGolf.landingCourseSearch.executeSearchAfterAutoComplete = true;
                $('#txtLocation').val(location);
                $('#txtLocation').search();
            }
            else {
                SkyGolf.landingCourseSearch.executeSearchAfterAutoComplete = false;
                executeSearch();
            }
        }
    };
})();

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1].replace(/%20/g, ' ');
}
$(document).ready(SkyGolf.landingCourseSearch.init);