﻿///<reference path="../jquery-1.3.2-vsdoc.js" />
///<reference path="nmls.js" />
///<reference path="nmls.turingTest.js" />
///<reference path="nmls.entityDetail.js" />

(function($)
{
    nmls.branchLocations = function(baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    nmls.branchLocations.prototype.get = function(companyId, page, success, error)
    {
        // Execute ajax call to check if the search has been authenticated.
        $.ajax({
            url: this.baseUrl + "EntityDetails.aspx/BranchLocations",
            type: "GET",
            data: { companyId: companyId, page: page },
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.branchLocationsRedirect = function(baseUrl, options)
    {
        var _turingTestRedirect = new nmls.turingTestRedirect(baseUrl, options.turingTestOptions);

        this.turingTestRedirect = _turingTestRedirect;
        this.bind = function()
        {
            $("table.branchLocations td a.goToBranch").bind("click", function(e)
            {
                var branchLocationId = $.trim($(this).parent().prev().text());
                _turingTestRedirect.redirect(baseUrl + "EntityDetails.aspx/Branch/" + branchLocationId);
                return false;
            });
        }
    }

    nmls.branchLocationsUI = function(baseUrl, options)
    {
        var _self = this,
            _$statesJurisdiction = $("#statesJurisdiction"),
            _$statesLocation = $("#statesLocation"),
            _$branchLocTable = $("table.branchLocations tbody"),
            _$branchLocRows = _$branchLocTable.find("tr"),
            _currentPage = 1,
            _errorCount = 0,
            _options =
            {
                recordsPerPage: 25,
                errorAttempts: 3,
                cull: false, // Specifies whether to cull filtered results (true) instead of filtering from the base results (false).
                startRecord: 5 // For display purposes only.  The first page on the server should always start with the fifth record.
            },
            _spinner,
            _branchLocations = new nmls.branchLocations(baseUrl),
            _branchLocationsRedirect = new nmls.branchLocationsRedirect(baseUrl, options);

        $.extend(_options, options);

        function _totalRecords()
        {
            var val = $("#branchLocationCount").val();
            return val === undefined ? 0 : parseInt(val);
        }

        function _pageCount()
        {
            return Math.ceil((_totalRecords() - _options.startRecord) / _options.recordsPerPage);
        }

        function _enableFilters(enable)
        {
            var _disabled = "disabled";
            if (enable)
            {
                _$statesJurisdiction.removeAttr(_disabled);
                _$statesLocation.removeAttr(_disabled);
            }
            else
            {
                _$statesJurisdiction.attr(_disabled, _disabled);
                _$statesLocation.attr(_disabled, _disabled);
            }
        }

        function _filter(stateLocation, stateJurisdiction)
        {
            var filterJurisdictions = true,
                filterLocation = stateLocation !== "ALL";
            if (stateJurisdiction === "ALL")
            {
                _$branchLocRows.show();
                filterJurisdictions = false;
            }

            if (!filterJurisdictions && !filterLocation)
                return;

            _$branchLocRows.each(function(i, name)
            {
                var $this = $(this);
                if (filterJurisdictions)
                {
                    // Filter (show or hide) by jurisdictions first since they can span multiple states.
                    var $jurisdictions = $this.find("td > input[type=hidden]");
                    if ($jurisdictions[0] !== undefined)
                    {
                        var found = false,
                            stateVals = $jurisdictions.val().split(",");
                        for (var i = 0; i < stateVals.length; ++i)
                        {
                            if ($.trim(stateVals[i]).toUpperCase() === stateJurisdiction)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                            $this.show();
                        else
                            $this.hide();
                    }
                }
                if (filterLocation)
                {
                    // Filter (hide only) by location.
                    var $state = $this.find("td > span.state");
                    if ($state[0] !== undefined)
                    {
                        if ($.trim($state.text()).toUpperCase() !== stateLocation)
                            $this.hide();
                    }
                }
            });
        }

        function _filterByLocation(state)
        {
            _$branchLocRows.each(function(i, name)
            {
                var $this = $(this);
                if ($this.css("display") !== "none")
                {
                    var $state = $this.find("td > span.state");
                    if ($state[0] !== undefined)
                    {
                        if ($.trim($state.text()).toUpperCase() !== state)
                            $this.hide();
                    }
                }
            });
        }

        function _filterByJurisdiction(state)
        {
            _$branchLocRows.each(function(i, name)
            {
                var $this = $(this);
                if ($this.css("display") !== "none")
                {
                    var $jurisdictions = $this.find("td > input[type=hidden]");
                    if ($jurisdictions[0] !== undefined)
                    {
                        var found = false,
                        stateVals = $jurisdictions.val().split(",");
                        for (var i = 0; i < stateVals.length; ++i)
                        {
                            if ($.trim(stateVals[i]).toUpperCase() === state)
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                            $this.hide();
                    }
                }
            });
        }

        function _getBranchesSuccess(result, textStatus)
        {
            _spinner.stop();
            _$branchLocTable.find("#spinnerRow").remove();

            if (result.Errors)
            {
                ++_errorCount;
                if (_errorCount <= _options.errorAttempts)
                    nmls.alertJsonError(result);
                else
                {
                    _enableFilters(true);
                    alert("Failed to retrieve all branch locations after " + _options.errorAttempts + " attempts.");
                }
            }
            else
            {
                ++_currentPage;
                _$branchLocTable.append(nmls.parseTemplate($("#branchesTemplate").html(), { Model: result.Data }));
            }

            _self.getBranchLocations();
        }

        function _getBranchesError(xmlHttpReq, textStatus, errorThrown)
        {
            _spinner.stop();
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
        }

        this.getBranchLocations = function(refresh)
        {
            if (refresh)
            {
                _currentPage = 1;
                _errorCount = 0;
                _$branchLocTable.find("tr:gt(" + _options.startRecord + ")").remove();
            }

            if (_currentPage === 1)
                _enableFilters(false);

            if (_currentPage > _pageCount() || _errorCount === _options.errorAttempts)
            {
                _$branchLocRows = _$branchLocTable.find("tr");
                _enableFilters(true);
                return;
            }

            _$branchLocTable.append("<tr id='spinnerRow'><td colspan='7'><div id='spinner'></div></td></tr>");

            var startRecord = (_currentPage - 1) * _options.recordsPerPage + _options.startRecord + 1,
                endRecord = startRecord + _options.recordsPerPage, totalRecords = _totalRecords();
            if (endRecord > totalRecords)
                endRecord = totalRecords;
            if (_spinner)
                _spinner.stop();
            _spinner = new nmls.spinner(
            {
                elemId: "spinner",
                animateText: "Retrieving branches " + startRecord + " - " + endRecord + " of " + totalRecords + "...",
                spinnerClass: "nmls_branchesSpinner"
            });
            _spinner.start();

            _branchLocations.get($("#entityId").val(), _currentPage, _getBranchesSuccess, _getBranchesError);
        }

        this.type = "BRANCHES";
        this.turingTestRedirect = _branchLocationsRedirect.turingTestRedirect;
        this.bind = function()
        {
            _$statesJurisdiction = $("#statesJurisdiction");
            _$statesLocation = $("#statesLocation");
            _$branchLocTable = $("table.branchLocations tbody");
            _$branchLocRows = _$branchLocTable.find("tr");
            _branchLocationsRedirect.bind();
            _$statesJurisdiction.bind("change", function(e)
            {
                var stateJurisdiction = $(this).val().toUpperCase(),
                    stateLocation = _$statesLocation.val().toUpperCase();
                if (!_options.cull)
                    _filter(stateLocation, stateJurisdiction);
                else
                {
                    // Show all rows.
                    if (stateJurisdiction === "ALL" && stateLocation === "ALL")
                        _$branchLocRows.show();
                    else if (stateJurisdiction !== "ALL")
                        _filterByJurisdiction(stateJurisdiction);
                }
            });

            _$statesLocation.bind("change", function(e)
            {
                var stateLocation = $(this).val().toUpperCase(),
                    stateJurisdiction = _$statesJurisdiction.val().toUpperCase();
                if (!_options.cull)
                    _filter(stateLocation, stateJurisdiction);
                else
                {
                    // Show all rows.
                    if (stateLocation === "ALL" && stateJurisdiction == "ALL")
                        _$branchLocRows.show();
                    else if (stateLocation !== "ALL")
                        _filterByLocation(stateLocation);
                }
            });

            $("#ttOtherTradeNamesBranchLocations").tooltip({ content: $("#ttOtherTradeNamesBranchLocationsText").html(), delay: 500, offsetPosition: "vt-hc" });
            this.getBranchLocations();
        }

        nmls.entityDetailUI(baseUrl, this);
        this.bind();
    }

})(jQuery);