﻿/// <reference path="../jquery-1.3.2-vsdoc.js" />
/// <reference path="nmls.js" />

(function($)
{
    nmls.turingTest = function(baseUrl)
    {
        this.baseUrl = baseUrl;
    }

    nmls.turingTest.prototype.getImage = function(success, error)
    {
        // Execute ajax call to get the new turing image.
        $.ajax({
            url: this.baseUrl + "TuringTest.aspx/GetImage",
            type: "GET",
            dataType: "text",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.turingTest.prototype.authenticate = function(turingText, success, error)
    {
        // Execute ajax call to test the number that was input.
        $.ajax({
            url: this.baseUrl + "TuringTest.aspx/Authenticate",
            type: "GET",
            data: { turingText: turingText },
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.turingTest.prototype.authenticateKey = function(userTestingText, success, error)
    {
        // Execute ajax call to test the number that was input.
        $.ajax({
            url: this.baseUrl + "TuringTest.aspx/AuthenticateKey",
            type: "GET",
            data: { authenticationText: userTestingText },
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.turingTest.prototype.canSearch = function(success, error)
    {
        // Execute ajax call to check if the search has been authenticated.
        $.ajax({
            url: this.baseUrl + "Home.aspx/CanSearch",
            type: "GET",
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.turingTest.prototype.isAuthenticated = function(success, error)
    {
        // Execute ajax call to check if the search has been authenticated.
        $.ajax({
            url: this.baseUrl + "Home.aspx/CheckAuthenticated",
            type: "GET",
            dataType: "json",
            cache: false,
            error: error,
            success: success
        });
    }

    nmls.turingTestRedirect = function(baseUrl, options)
    {
        var _self = this,
            _redirectUrl,
            _turingTestUI = new nmls.turingTestUI(baseUrl, options.turingTestUIOptions);

        function _authenticateSuccess(result, textStatus)
        {
            if (result.Data.redirectToHome)
                document.location.href = baseUrl;
            else if (result.Data.authenticated)
            {
                _onAuthenticated();
            }
            else
                _turingTestUI.show(result.Data.hideTerms);
        }

        function _onAuthenticated()
        {
            if (_redirectUrl)
                document.location.href = _redirectUrl;
            else if (_self.authenticatedCallback)
                _self.authenticatedCallback();
        }

        function _authenticateError(xmlHttpReq, textStatus, errorThrown)
        {
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
        }

        $(document).bind("turingAuthenticated", function(event, data)
        {
            _onAuthenticated();
        });

        this.redirect = function(url)
        {
            _redirectUrl = url;
            _turingTestUI.turingTest().canSearch(_authenticateSuccess, _authenticateError);
        }

        this.isAuthenticated = function()
        {
            _turingTestUI.turingTest().isAuthenticated(_authenticateSuccess, _authenticateError);
        }

        this.show = function(hideTerms)
        {
            _turingTestUI.show(hideTerms);
        }
    }

    nmls.turingTestUI = function(baseUrl, options)
    {
        var _shown = false,
            _defaultText = "Enter the number shown above",
            _failCount = 0,
            _turingTest = new nmls.turingTest(baseUrl),
            _$terms = $("#terms"),
            _$agreeCheck = $("#agreeCheckbox"),
            _$turingText = $("#turingText"),
            _$continueBtn = $("#continueBtn"),
            _$turingImage = $("#turingImage"),
            _$authErrMsg = $("#authErrMsg"),
            _$userTestingAuthErrMsg = $("#userTestingAuthErrMsg"),
            _$userTesting = $("#userTesting"),
            _$userTestingText = $("#userTestingText"),
            _$agreeToTerms = $("#agreeToTerms"),
            _$authentication = $("#authentication"),
            _$authenticateBox = _$authentication.find(".authenticateBox"),
            _userTestingText = "Enter the authorization key.",
            _dialog = new nmls.modalDialog("turingTest", { imageUrl: baseUrl + "img/dialogX.png" }),
            _options =
            {
                maxAttempts: 5,
                userTesting: false
            };

        $.extend(_options, options);

        function _enableContinueButton()
        {
            if (_canContinue())
            {
                _$continueBtn.removeAttr("disabled");
                _$continueBtn.attr("src", baseUrl + "img/but-continue.gif");
            }
            else
            {
                _$continueBtn.attr("disabled", "disabled");
                _$continueBtn.attr("src", baseUrl + "img/but-continue-dis.gif");
            }
        }

        function _isTermsVisible()
        {
            var display = _$terms.css("display");
            return display !== undefined && display !== "none";
        }

        function _canContinue()
        {
            return !_isTermsVisible() || (_isTermsVisible() && _$agreeCheck[0].checked);
        }

        function _getImageSuccess(result, textStatus)
        {
            // Added a fake query string string parameter to force an execute call on the handler on the server.
            if ($.browser.msie && $.browser.version <= 7)
                _$turingImage[0].src = baseUrl + "Handlers/ImageHandler.ashx?imageId=" + Math.random();
            else
                _$turingImage[0].src = "data:image/jpeg;base64," + result;

            _enableContinueButton();
        }

        function _getImageError(xmlHttpReq, textStatus, errorThrown)
        {
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
            _enableContinueButton();
        }

        function _newImage()
        {
            _enableContinueButton();
            _turingTest.getImage(_getImageSuccess, _getImageError);
        }

        function _authenticateSuccess(result, textStatus)
        {
            if (result.Data)
            {
                _enableContinueButton();
                _dialog.close();
                $(document).trigger("turingAuthenticated");
            }
            else
            {
                if (++_failCount === _options.maxAttempts)
                    document.location.href = baseUrl;
                else
                {
                    _$authErrMsg.show();
                    _$turingText.focus();
                    _$turingText.select();
                    _newImage();
                    _enableContinueButton();
                }
            }
        }

        function _authenticateError(xmlHttpReq, textStatus, errorThrown)
        {
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
            _enableContinueButton();
        }

        function _authenticateKeySuccess(result, textStatus)
        {
            if (!result.Data)
                _$userTestingAuthErrMsg.show();
            else
            {
                _$userTestingAuthErrMsg.hide();
                _$userTesting.hide();
                if (!_isTermsVisible())
                    _$turingText.focus();
                else
                {
                    _$agreeToTerms.show();
                    _$agreeCheck.focus();
                }
                _$authentication.show();
                _$authenticateBox.show();
                _options.userTesting = false;
            }
        }

        function _authenticateKeyError(xmlHttpReq, textStatus, errorThrown)
        {
            nmls.alertAjaxError(xmlHttpReq, textStatus, errorThrown);
            _enableContinueButton();
        }

        this.turingTest = function()
        {
            return _turingTest;
        }

        this.show = function(hideTerms)
        {
            _failCount = 0;

            if (hideTerms)
                _$terms.hide();
            else
                _$terms.show();

            _$authErrMsg.hide();
            _$userTestingAuthErrMsg.hide();

            // If terms are hidden, this will not be defined.
            if (_$agreeCheck[0])
                _$agreeCheck[0].checked = false;

            _enableContinueButton();

            _$turingText.val(_defaultText);
            _$userTestingText.val(_userTestingText)

            if (_shown)
                _newImage();
            else
                _shown = true;

            _dialog.show();

            if (_options.userTesting)
            {
                _$agreeToTerms.hide();
                _$authentication.hide();
                _$userTesting.show();
                _$userTestingText.focus();
                // In IE7 this is necessary because of a CSS bug.  Even though the authentication div is hidden, due to this bug 
                // the background image for the turing text textbox still appears.
                _$authenticateBox.hide();
            }
            else
            {
                _$authentication.show();
                _$userTesting.hide();
                _$turingText.focus();

                if (_isTermsVisible())
                    _$agreeCheck[0].focus();
                else
                    _$agreeToTerms.show();
            }
        }

        _$turingText.css("maxLength", 6);
        _$turingText.addClass("field");
        _$turingText.swapValues();

        _$userTestingText.css("maxLength", 10);
        _$userTestingText.addClass("field");
        _$userTestingText.swapValues();

        _$agreeCheck.bind("click", function(e)
        {
            _enableContinueButton();
        });

        _$continueBtn.click(function()
        {
            _$authErrMsg.hide();
            _turingTest.authenticate(_$turingText.val(), _authenticateSuccess, _authenticateError);
        });

        _$userTestingText.bind("change", function(e)
        {
            _turingTest.authenticateKey(_$userTestingText.val(), _authenticateKeySuccess, _authenticateKeyError);
        });

        _$turingText.bind("keypress", function(e)
        {
            if (e.which === 13 && _canContinue())
            {
                _$continueBtn.click();
                return false;
            }
        });

        _$userTestingText.bind("keypress", function(e)
        {
            if (e.which === 13)
                _$userTestingText.change();
        });
    }
})(jQuery);