﻿Cwo.RegisterNamespace("Cwo.Search.ToLet");

Cwo.Search.ToLet = new function () {

    var tli = this;
    this.ResultSet = new Hashtable(); // Contains JS for sale listing objects with details of all our properties.
    this.TotalResults = 0; // Contains the total number of results available (at the server) for the current search.
    this.LocationString = ''; // Stores the string to be shown in the search box, and the results list summary
    this.CurrentPage = 1; // Stores the page which we are currently viewing (if a results list is present)
    this.ResultsPerPage = 10; // The number of items per page in the result list.
    this.NewInstructionThresholdDays = 8;  // The number of days before which a listing is considered "new"
    this.SuppressFormSubmission = false;
    this.IsMapRendered = false;
    this.ControlIDs = {};
    this.DidYouMeanExpanded = false;
    this.FullyQualifiedPlaceName = '';
    this.SearchPropertyTypeText = 'properties';
    this.controls = null;
    this.Template;
    this.GetTotalResults = function () {
        return tli.TotalResults;
    };

    this.GetResultsPerPage = function () {
        return tli.ResultsPerPage;
    };

    this.GetCurrentPage = function () {
        return tli.CurrentPage;
    };


    var SaveSearchButton;
    var SaveSearchButtonTwo;

    // Singleton object - stores criteria for form submissions
    this.Criteria = new function () {
        this.SearchString = $("#ctl00_ctl00_cphBody_ForSaleSearch").val();
        this.RentalPriceMin = 50000;
        this.RentalPriceMax = 300000;
        this.BedroomsMin = 0;
        this.BedroomsMax = 99;
        this.FurnishingTypeID = -1;
        this.OrderBy = 'Default';
        this.CurrentPage = 1;
        this.ResultsPageSize = 10;
        this.Latitude = '0.00';
        this.Longitude = '0.00';
        this.Radius = 5;
        this.PropertyTypeID = -1;
    };

    this.OrderBy = "";

    this.DiscoverSelectedSortOrder = function () {
        tli.OrderBy = Cwo.Search.ToLet.OrderBy;
    };

    // Functionality to discover settings/filters from the on-page form and validate those values.
    this.GetAndValidateUserInput = function () {
        this.ValidatedOK = true;
        this.ErrorMessage = "";

        var oldRadius = tli.Criteria.Radius,
            newRadius = $('#RadiusSlider').slider('value'),
            validates = true;

        tli.Criteria.SearchString = $('#ctl00_ctl00_cphBody_ForSaleSearch').val();
        tli.Criteria.Radius = $('#RadiusSlider').slider('value');
        tli.Criteria.BedroomsMin = (+document.getElementById(tli.ControlIDs.BedroomsMin).selectedValue());
        tli.Criteria.BedroomsMax = (+document.getElementById(tli.ControlIDs.BedroomsMax).selectedValue());
        tli.Criteria.RentalPriceMin = (+document.getElementById(tli.ControlIDs.RentalPriceMin).selectedValue());
        tli.Criteria.RentalPriceMax = (+document.getElementById(tli.ControlIDs.RentalPriceMax).selectedValue());
        tli.Criteria.FurnishingTypeID = (+document.getElementById(tli.ControlIDs.FurnishingTypeID).selectedValue());
        tli.Criteria.PropertyTypeID = (+document.getElementById(tli.ControlIDs.PropertyTypeID).selectedValue());

        // Update save search fields on the page.
        $("#SaveSearchString").val(tli.Criteria.SearchString);
        $("#SaveSearchFurnishingsTypeID").val(tli.Criteria.FurnishingTypeID);
        $("#SaveSearchMinAskingPrice").val(tli.Criteria.RentalPriceMin);
        $("#SaveSearchMaxAskingPrice").val(tli.Criteria.RentalPriceMax);
        $("#SaveSearchBedroomsMin").val(tli.Criteria.BedroomsMin);
        $("#SaveSearchBedroomsMax").val(tli.Criteria.BedroomsMax);
        $("#SaveSearchOrderBy").val(tli.OrderBy);
        $("#SaveSearchCurrentPage").val(tli.CurrentPage);
        $("#SaveSearchResultsPageSize").val(tli.Criteria.ResultsPageSize);
        $("#SaveSearchLatitude").val(tli.Criteria.Latitude);
        $("#SaveSearchLongitude").val(tli.Criteria.Longitude);
        $("#SaveSearchRadius").val(tli.Criteria.Radius);
        $("#SaveSearchPropertyTypeID").val(tli.Criteria.PropertyTypeID);
        tli.Criteria.SiteID = $("#CatSiteID").val();

        tli.BindSaveSearch(tli.Criteria);

        if (!this.IsMapRendered) {
            tli.DiscoverSelectedSortOrder();
        }

        // Carry out simple validation to ensure inputs, particularly valid numerical value pairs have been retrieved where required.

        if (tli.Criteria.SearchString.length < 1) {
            this.ValidatedOK = false;
            this.ErrorMessage += 'Please ensure you enter a location to search in.<br /><br />';
            validates = false;
        }
        if ((tli.Criteria.RentalPriceMin) > (tli.Criteria.RentalPriceMax)) {
            this.ValidatedOK = false;
            this.ErrorMessage += 'Please choose a maximum price greater than your chosen minimum.<br /><br />';
            validates = false;
        }
        if ((+tli.Criteria.BedroomsMin) > (+tli.Criteria.BedroomsMax)) {
            this.ValidatedOK = false;
            this.ErrorMessage += "Please ensure the selected maximum number of bedrooms is greater than or equal to the minimum.<br /><br />";
            validates = false;
        }

        if (validates) {
            // Fire the Filter changed events
            Cwo.Page.EventController.FireEvent("ToLetFilters.CriteriaChanged");
            if (oldRadius !== newRadius) {
                Cwo.Page.EventController.FireEvent("ToLetFilters.RadiusChanged");
            }
        }
    };

    this.BindSaveSearch = function (Criteria) {

        var saveSearchEvent = {};
        saveSearchEvent = function () {
            $("#SavedSearchNotification").show().html('<div class="FadedBackground"><h6>Your search has been saved</h6></div>');
            $("#SavedSearchNotification").delay(3000).slideUp('slow', function () { });
        };

        if (!SaveSearchButton) {
            SaveSearchButton = new Cwo.Form("SaveSearchButton", 15, false, null,
            "SaveSearchType:ToLet" +
            ",SaveSearchString:" + Criteria.SearchString +
            ",AskingPriceMin:" + Criteria.RentalPriceMin +
            ",AskingPriceMax:" + Criteria.RentalPriceMax +
            ",PropertyTypeID:" + Criteria.PropertyTypeID +
            ",Longitude:" + Criteria.Longitude +
            ",Latitude:" + Criteria.Latitude +
            ",OrderBy:" + Cwo.Search.ToLet.Criteria.OrderBy +
            ",CurrentPage:" + Cwo.Search.ToLet.Criteria.CurrentPage +
            ",Radius:" + Criteria.Radius +
            ",BedroomsMin:" + Criteria.BedroomsMin +
            ",BedroomsMax:" + Criteria.BedroomsMax +
            ",FunishingsTypeID:" + Criteria.FurnishingTypeID +
            ",CatSiteID:" + Criteria.SiteID,
            saveSearchEvent);
        }
        else {

            SaveSearchButton.Data = "SaveSearchType:ToLet" +
            ",SaveSearchString:" + Criteria.SearchString +
            ",AskingPriceMin:" + Criteria.RentalPriceMin +
            ",AskingPriceMax:" + Criteria.RentalPriceMax +
            ",PropertyTypeID:" + Criteria.PropertyTypeID +
            ",Longitude:" + Criteria.Longitude +
            ",Latitude:" + Criteria.Latitude +
            ",OrderBy:" + Cwo.Search.ToLet.Criteria.OrderBy +
            ",CurrentPage:" + Cwo.Search.ToLet.Criteria.CurrentPage +
            ",Radius:" + Criteria.Radius +
            ",BedroomsMin:" + Criteria.BedroomsMin +
            ",BedroomsMax:" + Criteria.BedroomsMax +
            ",FunishingsTypeID:" + Criteria.FurnishingTypeID +
            ",CatSiteID:" + Criteria.SiteID;
        }

        if (!SaveSearchButtonTwo) {
            SaveSearchButtonTwo = new Cwo.Form("SaveSearchButtonTwo", 15, false, null,
            "SaveSearchType:ToLet" +
            ",SaveSearchString:" + Criteria.SearchString +
            ",AskingPriceMin:" + Criteria.RentalPriceMin +
            ",AskingPriceMax:" + Criteria.RentalPriceMax +
            ",PropertyTypeID:" + Criteria.PropertyTypeID +
            ",Longitude:" + Criteria.Longitude +
            ",Latitude:" + Criteria.Latitude +
            ",OrderBy:" + Cwo.Search.ToLet.Criteria.OrderBy +
            ",CurrentPage:" + Cwo.Search.ToLet.Criteria.CurrentPage +
            ",Radius:" + Criteria.Radius +
            ",BedroomsMin:" + Criteria.BedroomsMin +
            ",BedroomsMax:" + Criteria.BedroomsMax +
            ",FunishingsTypeID:" + Criteria.FurnishingTypeID +
            ",CatSiteID:" + Criteria.SiteID,
            saveSearchEvent);
        }
        else {
            SaveSearchButtonTwo.Data = "SaveSearchType:ToLet" +
            ",SaveSearchString:" + Criteria.SearchString +
            ",AskingPriceMin:" + Criteria.RentalPriceMin +
            ",AskingPriceMax:" + Criteria.RentalPriceMax +
            ",PropertyTypeID:" + Criteria.PropertyTypeID +
            ",Longitude:" + Criteria.Longitude +
            ",Latitude:" + Criteria.Latitude +
            ",OrderBy:" + Cwo.Search.ToLet.Criteria.OrderBy +
            ",CurrentPage:" + Cwo.Search.ToLet.Criteria.CurrentPage +
            ",Radius:" + Criteria.Radius +
            ",BedroomsMin:" + Criteria.BedroomsMin +
            ",BedroomsMax:" + Criteria.BedroomsMax +
            ",FunishingsTypeID:" + Criteria.FurnishingTypeID +
            ",CatSiteID:" + Criteria.SiteID;
        }
    };

    this.Submit = function (page) {
        tli.GetAndValidateUserInput();
        if (tli.ValidatedOK) {
            tli.Criteria.CurrentPage = page;
            if (!tli.IsMapRendered) {
                tli.QueryWebService();
            }
        } else {
            new Cwo.Error.Popup("Please check your search criteria", tli.ErrorMessage);
        }
        return false;
    };

  
    this.SearchResult = function (searchResultValues) {
        this.ID = searchResultValues.InstructionId;
        this.Latitude = searchResultValues.Latitude;
        this.Longitude = searchResultValues.Longitude;
        var listingTemplate = tli.Template;
        if (searchResultValues.IsRooftopLatLongAvailable == "True") {
            this.IsRooftopLatLongAvailable = true;
        }
        else {
            this.IsRooftopLatLongAvailable = false;
        }

        $.each(searchResultValues, function (a, b) {
            listingTemplate = tli.ReplaceTemplateContext("\\$" + a + "\\$", b, listingTemplate);
        });

        this.GetListHTML = function () { return listingTemplate };
    }

    this.ReplaceTemplateContext = function (key, value, template) {
        var re = new RegExp(key, "g");
        template = template.replace(re, value);
        return template;
    }

    this.DeserializeToLetListing = function (data) {
        return new tli.SearchResult(data);
    };

    this.ReOrderResults = function (buttonValue, orderBy) {
        if (!tli.SuppressFormSubmission) {
            // We suppressing form submission, to prevent an infinite loop of onChanges.
            tli.SuppressFormSubmission = true;

            Cwo.Search.ToLet.Criteria.OrderBy = buttonValue + orderBy;
            tli.Criteria.CurrentPage = 1;
            tli.SuppressFormSubmission = false;
            tli.Submit(tli.Criteria.CurrentPage);
        }
    };

    // Renders the last filter with the appropriate CSS class to ensure rounded corners.
    this.RenderLastFilter = function () {
        var labelBox = $('li.hideable:last');
        if (labelBox.hasClass('Selected')) {
            labelBox.removeClass('Last');
            $('li.hideable:last ul li').addClass('Last');
        } else {
            labelBox.addClass('Last');
        }
    };
    Cwo.Page.EventController.Subscribe('ToLetFilters.PostVisibilityChange', tli.RenderLastFilter);

    // Saves the saved/loaded state of filters to cookie
    this.SaveFilterConfiguration = function () {
        var results = '',
            numfiltershidden = 0;
        $('#ToLetFilters .hideable').each(function () {
            if (!$('#' + this.id).hasClass('Selected')) {
                results += this.id + ' ';
                numfiltershidden += 1;
            }
        });
        // If all filters are hidden, we put the value 'All' in the cookie.
        Cwo.Common.SetCookie('ToLetFilterUnSelected', (numfiltershidden === $('#ToLetFilters .hideable').length) ? 'All' : results);
    };
    Cwo.Page.EventController.Subscribe('ToLetFilters.PostVisibilityChange', tli.SaveFilterConfiguration);

    // Saves the saved/loaded state of filters to cookie
    this.ApplyFilterConfiguration = function () {
        var filters = $('#ToLetFilters .hideable'), // Get list of hidden filters saved to cookie
            hiddenfilterlist = Cwo.Common.GetCookie('ToLetFilterUnSelected'),
            changeMade = false;

        if (hiddenfilterlist.length > 2) {
            filters.each(function () {
                // For each filter check if its' ID is in the hidden list, and if so remove the selected class.
                if ((hiddenfilterlist.indexOf(this.id) > -1) || (hiddenfilterlist === 'All')) {
                    $('#' + this.id).removeClass('Selected');
                    changeMade = true;
                }
            });
            if (changeMade) {
                // Fire event if changes were made to elements visibility.
                Cwo.Page.EventController.FireEvent("ToLetFilters.PostVisibilityChange");
            }
        }
    };

    // Adds listings to the search results list.
    this.RenderListingCollection = function (listingCollection) {
        var htmlToAdd = "";

        for (var i = 0; i < listingCollection.length; i++) {
            if (!tli.ResultSet.ContainsKey(listingCollection[i].ID)) {
                tli.ResultSet.Add(listingCollection[i].ID, listingCollection[i]);
            }
            htmlToAdd += listingCollection[i].GetListHTML();
        }

        $("#" + tli.ControlIDs.ResultsList).html(htmlToAdd);
        // Bind favourite buttons & minimap clicks
        Cwo.Favourites.BindResultsListClicks(); // TODO : Refactor this... we're going to end up including ALL favourites Javascript on the results page?
        for (i = 0; i < listingCollection.length; i += 1) {
            tli.BindContactAgentClicks(listingCollection[i]);
            tli.BindMiniMapClicks(listingCollection[i]);
        }
    };

    this.BindContactAgentClicks = function (listingItem) {
        new Cwo.Form("ContactAgent" + listingItem.ID, 1, false, "", "InstructionID: " + listingItem.ID + ", BranchID: " + listingItem.BranchID);
    };

    this.BindMiniMapClicks = function (listingItem) {
        new Cwo.Maps.Mini("GlobalListingResultsContainer",
            "PropertyListingButtons" + listingItem.ID,
            listingItem.Latitude,
            listingItem.Longitude,
            "Map" + listingItem.ID,
            "ShowMiniMap" + listingItem.ID,
            "HideMiniMap" + listingItem.ID,
            null,
            listingItem.IsRooftopLatLongAvailable);
    };

    if (Cwo.Page.Browser.IsIE6) {
        tli.SearchPredictive_Visible = function () {
            $('#GlobalFilterContainer ul li ul li ul li select').css('display', 'none');
            $('#GlobalFilterContainer ul li ul li ul li span').css('display', 'none');
        };
        Cwo.Page.EventController.Subscribe('SearchPredictiveBox.VisibilityChange.Visible', tli.SearchPredictive_Visible);
        tli.SearchPredictive_Invisible = function () {
            $('#GlobalFilterContainer ul li ul li ul li select').css('display', 'block');
            $('#GlobalFilterContainer ul li ul li ul li span').css('display', 'inline');
        };
        Cwo.Page.EventController.Subscribe('SearchPredictiveBox.VisibilityChange.Invisible', tli.SearchPredictive_Invisible);
    }

    // Handles the click on a given paging button to navigate to the required page.
    this.QueryWebService = function () {
        var distance,
            dlabel,
            pageSummary,
            Instructions,
            instructionInformation,
            i,
            AjajSequenceIndex = Cwo.Page.AjajCalls.CreateRequest("ToLetSearch"),
            thisCall = this;


        thisCall.previousHTML = $("#" + tli.ControlIDs.ResultsList).html();

        $("#Loading").css("height", $("#" + tli.ControlIDs.ResultsList).height());
        $("#Loading").css("display", "block");

        Cwo.AjaxCall("/webservices/toletsearch.asmx/GetPropertyListings", JSON.stringify(tli.Criteria), function (data, status) {


            if (Cwo.Page.AjajCalls.IsCurrentSequenceIndex("ToLetSearch", AjajSequenceIndex)) {

                document.Title = data.d.PageTitle;

                tli.FullyQualifiedPlaceName = data.d.ContentContainer.FullyQualifiedPlaceName;
                tli.SearchPropertyTypeText = data.d.ContentContainer.SearchPropertyTypeText;

                if (data.d.ContentContainer.TotalRecordsAvailable > 0) {
                    $(".RSSFeed").parent().removeClass("Hidden");
                    $(".RSSFeed").attr("href", data.d.ContentContainer.RssURL);
                } else {
                    $("RSSFeed").parent().addClass("Hidden");
                }

                if (data.d.ErrorMessage !== null) {
                    if (data.d.ErrorMessage === "LocationNotFound") {
                        $("#LocationNotFoundText").val(tli.Criteria.SearchString);
                        $("#location").text(tli.Criteria.SearchString);
                        $("#litLocation").hide();
                        $("#" + tli.ControlIDs.LocationNotFound).removeClass().addClass("One");
                        $("#" + tli.ControlIDs.NoResults).removeClass().addClass("Hidden");
                        $("#" + tli.ControlIDs.PropertyListings).removeClass().addClass("Hidden");
                        $("#" + tli.ControlIDs.ResultsOnMapButton).removeClass().addClass("Hidden");
                    } else if (data.d.ErrorMessage === "NoResults") {
                        $("#" + tli.ControlIDs.LocationNotFound).removeClass().addClass("Hidden");
                        $("#" + tli.ControlIDs.NoResults).removeClass().addClass("One");
                        $("#" + tli.ControlIDs.PropertyListings).removeClass().addClass("Hidden");
                    }

                    //$(".reorders-toletsearch").css("display", "none");
                    tli.TotalResults = data.d.ContentContainer.TotalRecordsAvailable;
                    Cwo.Page.EventController.FireEvent("ToLetResults.PostResultSetChange");
                } else {
                    // Success
                    Cwo.LogMIActivity(data.d.ContentContainer.SearchURL);
                    tli.SetHashURL(data.d.ContentContainer.SearchURL);
                    // Set maplink URL
                    $('#' + tli.ControlIDs.ResultsOnMapButton).attr({ href: data.d.ContentContainer.SearchURL.replace("/rent/search/", "/rent/mapsearch/") });
                    Instructions = [];
                    instructionInformation = data.d.ContentContainer.PropertySearchListings;
                    tli.TotalResults = data.d.ContentContainer.TotalRecordsAvailable;
                    for (i = 0; i < instructionInformation.length; i += 1) {
                        Instructions[Instructions.length] = tli.DeserializeToLetListing(instructionInformation[i]);
                    }
                    tli.RenderListingCollection(Instructions);
                    $("#" + tli.ControlIDs.LocationNotFound).removeClass().addClass("Hidden");
                    $("#" + tli.ControlIDs.NoResults).removeClass().addClass("Hidden");
                    $("#" + tli.ControlIDs.PropertyListings).removeClass().addClass("One");

                    //$(".reorders-toletsearch").css("display", "none"); // Enable the order drop downs
                    tli.CurrentPage = tli.Criteria.CurrentPage;
                    Cwo.Page.EventController.FireEvent("ToLetResults.PostResultSetChange");
                }
            }

            $("#Loading").css("display", "none");

            // Show summary info:
            tli.LocationString = tli.Criteria.SearchString;

            distance = $('#RadiusSlider').slider('value');
            dlabel = (+distance === 1) ? 'mile' : 'miles';

            if (distance === 0) {
                pageSummary = "<span>" + tli.TotalResults + "</span>" + " " + tli.SearchPropertyTypeText + " in <span>" + tli.FullyQualifiedPlaceName + "</span>";
            } else {
                pageSummary = "<span>" + tli.TotalResults + "</span>" + " " + tli.SearchPropertyTypeText + " within <span>" + distance + " " + dlabel + "</span> of <span>" + tli.FullyQualifiedPlaceName + "</span>";
            }

            $("#" + tli.ControlIDs.ResultsListTopSummary).html(pageSummary);
            $("#" + tli.ControlIDs.ResultsListBottomSummary).html(pageSummary);

        }, function (xhr, err, ex) {
            $("#" + tli.ControlIDs.ResultsList).html(thisCall.previousHTML);
            new Cwo.Error.Popup("Problem fetching list of properties.", "Sorry, we could not retrieve any results for your search - this could be a problem with your internet connection, or a problem with our website.<br><br>If you attempt to search again and receive the same error, please wait a few minutes and try again.");
        }, null);
    };

    this.SetHashURL = function (hashURL) {
        window.location.hash = '#' + hashURL;
    };

    this.EnforceHashURL = function () {
        if (window.location.hash.length > 14) {
            if (window.location.hash.substr(0, 14) === '#/rent/search/') {
                if (window.location.hash !== ('#' + window.location.pathname)) {
                    // Create loading screen, display it and redirect
                    var loadingHTML = $('<div>').append($('#Loading').eq(0).clone()).html(),
                        curLoc = window.location;

                    $('#body').html(loadingHTML);
                    $('#body').css('background-position', '0px -40px');
                    $('#Loading').css('display', 'block');
                    curLoc.href = curLoc.protocol + '//' + curLoc.host + curLoc.hash.substring(1);
                    // return true to the controlling process, so it knows not to execute anymore onload scripts while the page redirect occurs.
                    return true;
                }
            }
        }
    };

    this.DidYouMeanCollapse = function () {
        tli.DidYouMeanExpanded = false;
        window.setTimeout('$("#" + ctrls.DidYouMeanButton).removeClass("Selected");', 300);
        $('#' + Cwo.Search.ToLet.ControlIDs.DidYouMeanWrapper).slideUp(400);
        window.setTimeout('$("#" + Cwo.Search.ToLet.ControlIDs.DidYouMeanButton).removeClass("DidYouMeanButtonSelected");', 300);
    };

    this.DidYouMeanExpand = function () {

        tli.DidYouMeanExpanded = true;
        $('#' + Cwo.Search.ToLet.ControlIDs.DidYouMeanButton).addClass('DidYouMeanButtonSelected');

        $('#' + Cwo.Search.ToLet.ControlIDs.DidYouMeanWrapper).css('display', 'none').removeClass('Hidden').slideDown(400);

        $("#" + Cwo.Search.ToLet.ControlIDs.DidYouMeanButton).addClass('Selected');
    };

    this.DidYouMeanClick = function () {

        if (tli.DidYouMeanExpanded) {
            tli.DidYouMeanCollapse();
        } else {
            tli.DidYouMeanExpand();
        }
    };

    this.RefreshOrderBy = function (buttonValue, ordering) {

        // Loop through and force correct styling on each button.
        if (this.ControlIDs !== null) {


            $.each($("#" + this.ControlIDs.ToLetListOrderByContainer).children(), function (index, value) {
                // Get button object.
                var currentButton = $("#" + value.id),
                    currentCssClass;

                if (currentButton.attr("value") !== buttonValue) {
                    // We have got to a button that did not invoke the ordering; take away its selected styling.
                    currentCssClass = currentButton.attr("class");

                    if (currentCssClass === "SelectedAscending") {
                        currentButton.attr("class", "Ascending");
                    } else if (currentCssClass === "SelectedDescending") {
                        currentButton.attr("class", "Descending");
                    }
                }
            });
        }
    };
};

$(document).ready(function () {
    Cwo.Search.ToLet.OnStart = function () {

        var Controls = (this.ControlIDs);

        $("html").bind("click", function (event) {
            var display = (event.target.id === "SearchPredictiveText") ? "block" : "none";
            $("#SearchPredictive").css("display", display);
        });

        if (!Cwo.Search.ToLet.EnforceHashURL()) {
            // Setup dropdowns so we can access them with minimum code.
            $("select").each(function () {
                this.selectedValue = function () { return this.options[this.selectedIndex].value; };
            });
            $("a.CorrectTypoError").bind("click", function (e) {
                var d = {};
                d.SearchString = Cwo.Search.ToLet.Criteria.SearchString;
                d.CorrectedPlaceName = $(this).attr('title');
                Cwo.AjaxCall("/webservices/TypoCorrectionAudit.asmx/AuditItem", JSON.stringify(d), function (data, status) { });
            });
            $("li.hideable a").bind("click", function (e) {
                $(this).parent().toggleClass("Selected");
                Cwo.Page.EventController.FireEvent("ToLetFilters.PostVisibilityChange");
            });
            $("#ExpandAllFilters").bind("click", function (e) {
                $("li.hideable a").parent().addClass("Selected");
                Cwo.Page.EventController.FireEvent("ToLetFilters.PostVisibilityChange");
            });
            $("#CloseAllFilters").bind("click", function (e) {
                $("li.hideable a").parent().removeClass("Selected");
                Cwo.Page.EventController.FireEvent("ToLetFilters.PostVisibilityChange");
            });
            $(".submits-toletsearch").bind("change", function (e) {
                Cwo.Search.ToLet.Submit(1);
            });
            $(".reorders-toletsearch").bind("change", function (e) {
                Cwo.Search.ToLet.ReOrderResults(this);
            });
            $('#' + Cwo.Search.ToLet.ControlIDs.DidYouMeanButton).bind("click", function (e) {
                Cwo.Search.ToLet.DidYouMeanClick();
            });
            $('#DidYouMeanHideButton').bind("click", function (e) {
                Cwo.Search.ToLet.DidYouMeanCollapse();
            });
            if (!this.IsMapRendered) {
                // Write our buttons to change pagenumber - these will overwrite the static HTML links that will be scraped by search spiders
                var ButtonRegionIDs = [];
                ButtonRegionIDs[0] = Cwo.Search.ToLet.ControlIDs.ResultsListPagingTop;
                ButtonRegionIDs[1] = Cwo.Search.ToLet.ControlIDs.ResultsListPagingBottom;
                Cwo.Search.ToLet.PagingController = new Cwo.Search.PagingController(Cwo.Search.ToLet.GetCurrentPage, ButtonRegionIDs, Cwo.Search.ToLet.Submit, Cwo.Search.ToLet.GetTotalResults, Cwo.Search.ToLet.GetResultsPerPage, 'ToLetResults.PostResultSetChange');
                Cwo.Search.ToLet.PagingController.RenderButtons();
            }

            try {
                // ORDER BY BUTTONS  alert(ctrls);

                if (Controls !== undefined) {

                    $.each($("#" + Controls.ToLetListOrderByContainer).children(), function (index, value) {
                        // Get button object.
                        var currentButton = $("#" + value.id);

                        // Bind click event to button object.
                        currentButton.click(function () {
                            // Figure out asc/dsc/selected logic.
                            var isAsc = (currentButton.attr("class") === "Ascending"),
                                isDsc = (currentButton.attr("class") === "Descending"),
                                isSelectedAsc = (currentButton.attr("class") === "SelectedAscending"),
                                isSelectedDsc = (currentButton.attr("class") === "SelectedDescending"),
                            // Set default order by.
                                orderBy = "Descending",
                                buttonValue = "";

                            // Iterate through current list and refresh.
                            Cwo.Search.ToLet.RefreshOrderBy(currentButton.attr("value"), currentButton.attr("class"));


                            // Remove current class.
                            currentButton.removeClass();

                            // Check if selected ascending.
                            if (isSelectedAsc || isSelectedDsc) {
                                if (isSelectedAsc) {
                                    currentButton.addClass('SelectedDescending');
                                } else if (isSelectedDsc) {
                                    orderBy = "Ascending";
                                    currentButton.addClass('SelectedAscending');
                                }
                            } else {
                                if (isAsc) {
                                    orderBy = "Ascending";
                                    currentButton.addClass('SelectedAscending');
                                } else {
                                    orderBy = "Descending";
                                    currentButton.addClass('SelectedDescending');
                                }
                            }

                            if (document.documentMode) {
                                // Internet explorer.
                                if (document.compatMode === "CSS1Compat" && document.documentMode.toString() === "7") {
                                    // Compatibility mode; use currentButton[0].attributes["value"].nodeValue to get
                                    // the button value.
                                    buttonValue = currentButton[0].attributes["value"].nodeValue;
                                } else {
                                    // Not compatibility mode; use currentButton.attr("value") to get the value.
                                    buttonValue = currentButton.attr("value");
                                }
                            } else {
                                // Not Internet explorer; fetch the attribute using the standard JQuery logic.
                                buttonValue = currentButton.attr("value");
                            }

                            // Invoke the re-ordering of the results, passing in how we wish to re-order.
                            Cwo.Search.ToLet.ReOrderResults(buttonValue, orderBy);
                        });


                    });
                }
            } catch (e) {
            }

            // Initialise the slider
            $(function () { // TODO : Prototype code, can be refactored to be smaller and tidier


                function RadiusSliderValueChange(newVal, showHelper, submitForm) {
                    var label = $('#RadiusLabel'),
                    dynamiclabel = $('#SliderDynamicLabel');
                    label.html('Search Within <span>' + newVal + ' ' + ((+newVal > 1) ? 'Miles</span>' : 'Mile</span>'));
                    dynamiclabel.html(newVal);
                    if (showHelper) {
                        dynamiclabel.show();
                    } else {
                        dynamiclabel.hide();
                    }
                    if (submitForm) { Cwo.Search.ToLet.Submit(1); }
                }


                $('#RadiusSlider').slider({
                    range: 'min',
                    value: $('#SliderValuePreLoad').html(),
                    min: 0,
                    max: 30,
                    animate: false,
                    start: function (event, ui) {
                        RadiusSliderValueChange(ui.value, true);
                    },
                    stop: function (event, ui) {
                        RadiusSliderValueChange(ui.value, false, true);
                    },
                    slide: function (event, ui) {
                        RadiusSliderValueChange(ui.value, true);
                    }
                });

                Cwo.Search.ToLet.ApplyFilterConfiguration();
                Cwo.Search.ToLet.GetAndValidateUserInput();
                // Add the little dynamic label to the generated slider HTML
                $('#RadiusSlider .ui-slider-handle').append('<span id="SliderDynamicLabel"></span>');

                // Setup the initial radius label text
                RadiusSliderValueChange($('#RadiusSlider').slider('value'), false);


            });

        }
    };

    // Exception handling code to log exceptions to the event viewer
    if (window.navigator.userAgent.indexOf("MSIE") > -1) {
        Cwo.Search.ToLet.OnStart();
        return;
    }

    try {
        Cwo.Search.ToLet.OnStart();
    } catch (ex) {
        Cwo.Error.TrackError(ex); // re-throw ex if error should propergate
    }
});

