﻿/// <reference path="../jquery-1.4.1-vsdoc.js" />
/// <reference path="../MicrosoftAjax.js" />
/// <reference path="nmls.js" />
/// <reference path="nmls.turingTest.js" />

(function ($)
{
    nmls.searchParams = function (searchText, entityType, state, page)
    {
        this.searchText = searchText;
        this.entityType = entityType === undefined ? "" : entityType;
        this.state = state === undefined ? "" : state;
        this.page = page === undefined ? 1 : page;
    }

    nmls.searchEngine = function (baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    nmls.searchEngine.prototype.validateSearchParams = function (searchParams)
    {
        if (searchParams.searchText === undefined || $.trim(searchParams.searchText) === "" ||
            searchParams.searchText == "Enter a Name, Company, City, State, Zip Code, NMLS ID, and/or License Number")
            throw new Error("Search text must be specified.");
    }

    nmls.searchEngine.prototype.search = function (searchParams, success, error)
    {
        $.ajax({
            url: this.baseUrl + "Home.aspx/SubSearch",
            type: "GET",
            data: searchParams,
            contentType: "application/json",
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.searchUI = function ()
    {
        var _$searchButton = $("#searchButton"),
            _disabled = "disabled",
            _self = this;

        this.searching = function (searching)
        {
            if (searching)
                _$searchButton.attr(_disabled, _disabled);
            else
                _$searchButton.removeAttr(_disabled);
        }
        this.isSearching = function ()
        {
            return _$searchButton.attr(_disabled) === true;
        }

        $(document).bind("nmls_modalDialogClosed", function (e)
        {
            _self.searching(false);
        });
    }

    nmls.mainSearchUI = function (baseUrl, options)
    {
        var _$searchForm = $("#searchForm"),
            _searchEngine = new nmls.searchEngine(baseUrl),
            $viewLearnMoreButton = $("#learnMoreButton"),
            $viewMoreExamplesButton = $("#moreExamplesButton"),
            $viewMoreExamples = $("#moreExamples");

        $viewMoreExamples.bind("click", function (e)
        {
            var imgPlus = baseUrl + "img/icon-plus-background.gif";

            if ($viewMoreExamplesButton.attr("src") === imgPlus)
            {
                $viewMoreExamplesButton.attr("src", baseUrl + "img/icon-minus-background.gif");
                $viewMoreExamples.text("Hide search tips...");
            }
            else
            {
                $viewMoreExamplesButton.attr("src", imgPlus);
                $viewMoreExamples.text("Search tips...");
            }

            return false;
        });

        $("#learnMore").bind("click", function (e)
        {
            var imgPlus = baseUrl + "img/but-LearnMore.gif";

            if ($viewLearnMoreButton.attr("src") === imgPlus)
                $viewLearnMoreButton.attr("src", baseUrl + "img/but-LearnMore-minus.gif");
            else
                $viewLearnMoreButton.attr("src", imgPlus);

            return false;
        });

        _$searchForm.bind("submit", function (e)
        {
            var searchParams = new nmls.searchParams($("#searchText").val());
            try
            {
                _searchEngine.validateSearchParams(searchParams);
            }
            catch (ex)
            {
                alert(ex.message);
                return false;
            }

            return true;
        });

        $(".swap_value").swapValues();
        nmls.toggleSlide("#learnMore", "#mydiv");
        nmls.toggleSlide("#moreExamples", "#myExamples");
    }

    nmls.subSearchUI = function (baseUrl, options)
    {
        var _self = this,
            _spinner,
            _redirectUrl,
            _searchEngine = new nmls.searchEngine(baseUrl),
            _turingTestUI = new nmls.turingTestUI(baseUrl, options.turingTestUIOptions),
            _searchUI = new nmls.searchUI(),
            _$searchText = $("#searchText"),
            _$searchResults = $("#searchResults"),
            _$searchResultsExceeded = $("#searchResultsExceeded"),
            _$pagingTop = $("#pagingTop"),
            _$pagingBottom = $("#pagingBottom"),
            _$filterTotal = $("#filterTotal"),
            _$filterIndividual = $("#filterIndividual"),
            _$filterCompany = $("#filterCompany"),
            _$states = $("#states"),
            _$hiddenSearchString = $("#hiddenSearchString"),
            _$hiddenEntityType = $("#hiddenEntityType"),
            _$hiddenState = $("#hiddenState"),
            _$hiddenPage = $("#hiddenPage"),
            _$searchForm = $("#searchForm"),
            $viewMoreExamplesButton = $("#moreExamplesButton"),
            $viewMoreExamples = $("#moreExamples"),
            _options =
            {
                spinnerId: "filterTotal",
                entityNameDisplayLength: 27
            };

        $($viewMoreExamples).bind("click", function (e)
        {
            var imgPlus = baseUrl + "img/icon-plus-background.gif";

            if ($viewMoreExamplesButton.attr("src") === imgPlus)
            {
                $viewMoreExamplesButton.attr("src", baseUrl + "img/icon-minus-background.gif");
                $viewMoreExamples.text("Hide search tips...");
            }
            else
            {
                $viewMoreExamplesButton.attr("src", imgPlus);
                $viewMoreExamples.text("Search tips...");
            }

            return false;
        });

        $("#searchForm").bind("submit", function (e)
        {
            return hideApplyFilter(e);
        });

        $("#searchText").bind("change", function (e)
        {
            return hideApplyFilter(e);
        });

        function hideApplyFilter(e)
        {
            var $applyFilterArea = $("#applyFilterArea");

            _$filterCompany[0].checked = false;
            _$filterIndividual[0].checked = false;
            _$states[0].value = "ALL";
            $applyFilterArea.slideUp();

            return true;
        }

        $.extend(_options, options);
        delete _options.turingTestUIOptions;

        function _searchParamsFromUI()
        {
            var entityType;
            var states = _$states[0].value;

            if (_$filterIndividual[0].checked)
                entityType = "INDIVIDUAL";
            else if (_$filterCompany[0].checked)
                entityType = "COMPANY";

            if (_$states[0].value === "ALL")
                states = "";

            return new nmls.searchParams(_$searchText.val(), entityType, states);
        }

        function _searchParamsFromHidden()
        {
            return new nmls.searchParams(_$hiddenSearchString.val(), _$hiddenEntityType.val(), _$hiddenState.val(), _$hiddenPage.val());
        }

        function _searchParamsFromQueryString()
        {
            return new nmls.searchParams(
                    nmls.getQueryStringParam("searchText"),
                    nmls.getQueryStringParam("entityType"),
                    nmls.getQueryStringParam("state"),
                    nmls.getQueryStringParam("page"));
        }

        function showApplyFilter(e)
        {
            var $applyFilterArea = $("#applyFilterArea");

            if (_$filterIndividual[0].checked ||
                _$filterCompany[0].checked ||
                _$states[0].value !== "ALL")
                $applyFilterArea.slideDown();
            else
                $applyFilterArea.slideUp();
        }

        function _pageSearchSuccess(result, textStatus)
        {
            _spinner.stop();
            _searchUI.searching(false);

            if (result.Exception)
                document.location.href = baseUrl + "Error.aspx/Index";
            else if (result.Errors)
                nmls.alertJsonError(result);
            else if (result.Data.redirectToHome)
                document.location.href = baseUrl;
            else if (typeof result.Data.authenticated !== "undefined" && !result.Data.authenticated)
            {
                if (!result.Data.clientSideTuringTest)
                    document.location.href = result.Data.redirectUrl;
                else
                {
                    _redirectUrl = result.Data.redirectUrl;
                    _turingTestUI.show(result.Data.hideTerms);
                }
            }
            else
            {
                var countTxt;
                if (result.Data.MaxRowsExceeded)
                    countTxt = "Too many results to display!";
                else if (result.Data.RowCount == 0)
                    countTxt = "No matches found!";
                else if (result.Data.RowCount == 1)
                    countTxt = "1 match found!";
                else
                    countTxt = result.Data.RowCount + " matches found!";

                _$filterTotal.html(countTxt);
                _$filterTotal.show();

                var obj = { Model: result.Data };
                var html = "";

                if (result.Data.MaxRowsExceeded)
                {
                    _$searchResults.fadeOut();
                    _$searchResultsExceeded.fadeIn();
                }
                else
                {
                    if (result.Data.RowCount > 0)
                    {
                        html = nmls.parseTemplate($("#searchItemTemplate").html(), obj);
                        _$searchResults.html(html);

                        if (result.Data.RowCount > result.Data.RecordsPerPage)
                        {
                            html = nmls.parseTemplate($("#pagingTemplate").html(), obj);
                            _$pagingTop.html(html).fadeIn();
                            _$pagingBottom.html($(html).clone(true)).fadeIn();
                        }
                    }
                    else
                    {
                        html = nmls.parseTemplate($("#searchNoResultsTemplate").html(), obj);
                        _$searchResults.html(html);
                    }

                    _$searchResultsExceeded.fadeOut();
                    _$searchResults.fadeIn();

                    for (var i = 0; i < result.Data.Entities.length; ++i)
                    {
                        var entity = result.Data.Entities[i];
                        if ((entity.EntityName && entity.EntityName.length > _options.entityNameDisplayLength) ||
                            (entity.PriorNames && entity.PriorNames.length > 0) ||
                            (entity.OtherNames && entity.OtherNames.length > 0) ||
                            (entity.PriorOtherNames && entity.PriorOtherNames.length > 0))
                            $("#nameArea_" + entity.EntityId).tooltip(
                            {
                                content: $("#otherNamesTooltip_" + entity.EntityId).html(),
                                offsetPosition: "vt-hc"

                            });
                        if (entity.RegisteredLocations.split("|").length > 2)
                            $("#allLocations_" + entity.EntityId).tooltip(
                            {
                                content: $("#allLocationsTooltip_" + entity.EntityId).html(),
                                offsetPosition: "vc-hr"
                            });
                    }
                }
            }
        }

        function _pageSearchError(xmlHttpReq, textStatus, errorThrown)
        {
            _spinner.stop();
            _searchUI.searching(false);
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
        }

        this.search = function (searchParams)
        {
            if (_searchUI.isSearching())
                return;

            try
            {
                _searchEngine.validateSearchParams(searchParams);
            }
            catch (ex)
            {
                alert(ex.message);
                return;
            }

            _$hiddenSearchString.val(searchParams.searchText);
            _$hiddenEntityType.val(searchParams.entityType);
            _$hiddenState.val(searchParams.state);
            _$hiddenPage.val(searchParams.page);

            this.pageSearch(_$hiddenPage.val(), false);
        }

        this.pageSearch = function (page, paging)
        {
            if (_searchUI.isSearching())
                return;

            _searchUI.searching(true);

            var displayText = paging ? "Paging..." : "Searching...";

            _$searchResults.hide();
            _$filterTotal.html(displayText);
            _$pagingTop.hide();
            _$pagingBottom.hide();

            _spinner = new nmls.spinner({ elemId: _options.spinnerId, animateText: displayText });
            _spinner.start();

            searchParams = _searchParamsFromHidden();
            searchParams.page = page;
            _$hiddenPage.val(page);
            _searchEngine.search(searchParams, _pageSearchSuccess, _pageSearchError);
        }

        this.init = function ()
        {
            // A search has not occurred.
            if (_$hiddenSearchString.val() === "")
            {
                var searchParams = _searchParamsFromQueryString();
                // Update the UI from the query string.
                _$searchText.val(searchParams.searchText);
                if (searchParams.entityType !== undefined && searchParams.entityType.toUpperCase() === "INDIVIDUAL")
                    _$filterIndividual[0].checked = true;
                else if (searchParams.entityType !== undefined && searchParams.entityType.toUpperCase() == "COMPANY")
                    _$filterCompany[0].checked = true;
                if (searchParams.state)
                    _$states.val(searchParams.state);
                // Perform the search.
                _self.search(searchParams);
            }
            // For the case when a search has occurred and user navigates to this page by pressing the back button.
            else
            {
                var page = _$hiddenPage.val();
                if (page === "")
                    _self.search(_searchParamsFromHidden());
                else
                    _self.pageSearch(page, true);
            }
        }

        this.redirect = function (url)
        {
            document.location.href = url;
        }

        $(".swap_value").swapValues();
        nmls.toggleSlide("#moreExamples", "#myExamples");
        $("#searchForm").bind("submit", function (e)
        {
            _self.search(new nmls.searchParams(_$searchText.val()));
            return false;
        });

        _$filterIndividual.bind("click", function (e)
        {
            if (this.checked)
            {
                _$filterCompany[0].checked = false;
                showApplyFilter(e);
            }
        });
        _$filterCompany.bind("click", function (e)
        {
            if (this.checked)
            {
                _$filterIndividual[0].checked = false;
                showApplyFilter(e);
            }
        });
        _$states.bind("change", function (e)
        {
            if (_$states[0].value !== "ALL")
            {
                showApplyFilter(e);
            }
        });
        $(".applyFilter").bind("click", function (e)
        {
            _self.search(_searchParamsFromUI());
            showApplyFilter(e);
        });

        $(document).bind("turingAuthenticated", function (event)
        {
            document.location.href = _redirectUrl;
        });
    }
} (jQuery));
