﻿///<reference path="transitController.js"/>
///<reference path="jquery-1.7.1.min.js"/>
///<reference path="jquery-1.7.1-vsdoc.js"/>
// UI Controller for IP FOO
// This script controls the actual interface of the site and
// makes things appear and disappear. It also interacts with the
// transitController.js file to send and receive data from the server.
(function () {
    var submitBtn;

    $(document).ready(function () {
        bind();
        loadGeoLocation();
    });

    function bind() {
        ///<summary>Binds the submission button to javascript. Otherwise it would perform a normal postback.</summary>
        submitBtn = $('#submitCommand');
        submitBtn.click(function () { return executeLookup(); });

        // This line is for Internet Explorer.
        $('form').submit(function () { return false; });
    }

    function loadGeoLocation() {
        ///<summary>Goes out to hostip.info and loads the geolocation data for the user</summary>

        $.ajax({
            url: 'http://api.hostip.info/get_html.php',
            type: 'GET',
            dataType: 'text',
            timeout: 1000,
            error: function () {
                $('#geoCountry').html('There was a problem loading your data. Try again later?');
                $('#geoCity').html('There was a problem loading your data. Try again later?');
            },
            success: function (response) {
                var fields = response.toString().replace('Country: ', '').replace('City: ', '').split('\n');
                $('#geoCountry').html(fields[0]);
                $('#geoCity').html(fields[1]);
            }
        });
    }

    function showLoading(bool) {
        ///<summary>Shows/hides the loading indicator.</summary>
        ///<param name="bool">Pass TRUE or FALSE here as a bool</param>
        var loadingBox = $('#loading');

        if (bool) {
            loadingBox.show();
        } else {
            loadingBox.hide();
        }
    }

    function executeLookup() {
        ///<summary>Executes a postback to the server (via transitController.js) to run the passed command.</summary>
        submitBtn.attr('disabled', true);

        // Check validation. If failed, exit.
        if (!validateForm()) {
            submitBtn.removeAttr('disabled');
            return false;
        }

        // Get our values
        var model = { lookup: $('#Lookup').val(),
            action: $('#ActionDiv :checked').val(),
            recaptcha_challenge_field: $('#recaptcha_challenge_field').val(),
            recaptcha_response_field: $('#recaptcha_response_field').val()
        };

        // If the response results box is visible, hide it now
        var pbBox = $('#postbackResultsBox');
        if (pbBox.is(':visible')) {
            pbBox.hide();
        }

        // Send the information off to the server!
        showLoading(true);
        var tnst = new Transit();
        tnst.send(model, resultsCallback);

        // Always going to return false to prevent any browser postback events
        return false;
    }

    function resultsCallback(responseModel) {
        ///<summary>Executed by transitController.js once a sucessful callback from the server has been completed.</summary>

        // First step: Reload the reCAPTCHA. Our past one is now invalid.
        window.Recaptcha.reload();
        showLoading(false);

        if (responseModel.IsValid) {
            var pbBox = $('#postbackResultsBox');
            var pbData = $('#postbackResults');

            pbData.html(responseModel.ExecutionResults);
            pbBox.fadeIn();

            // Scroll to our results box (weeeeeeeeeee!)
            $('html, body').animate({ scrollTop: pbBox.offset().top }, 2000);
        } else {
            validatePostback(responseModel);
        }

        submitBtn.removeAttr('disabled');
    }

    function validatePostback(model) {
        ///<summary>Checks the postback validation results and highlights the problem areas on the form</summary>
        var errorMessage = $('#errorsFoundMessage');

        var lookupBox = $('#LookupDiv');
        if (!model.ValidLookup) {
            lookupBox.addClass('error');
        }

        var actionBox = $('#ActionDiv');
        if (!model.ValidAction) {
            actionBox.addClass('error');
        }

        var recaptchaBox = $('#ValidateDiv');
        if (!model.ValidCaptcha) {
            recaptchaBox.addClass('error');
        }

        errorMessage.fadeIn();
    }

    function validateForm() {
        ///<summary>Checks the form fields to make sure all the inputs are filled out. If any are not, it will highlight those on the page and display an error.</summary>
        ///<returns>TRUE/FALSE</returns>
        var isValid = true;
        var errorMessage = $('#errorsFoundMessage');

        var lookup = $('#Lookup');
        var lookupBox = $('#LookupDiv');
        if ($.trim(lookup.val()) == '') {
            isValid = false;
            lookupBox.addClass('error');
        } else {
            lookupBox.removeClass('error');
        }

        var action = $('#ActionDiv :checked');
        var actionBox = $('#ActionDiv');
        if ($.trim(action.val()) == '') {
            isValid = false;
            actionBox.addClass('error');
        } else {
            actionBox.removeClass('error');
        }

        var recaptcha = $('#recaptcha_response_field');
        var recaptchaBox = $('#ValidateDiv');
        if ($.trim(recaptcha.val()) == '') {
            isValid = false;
            recaptchaBox.addClass('error');
        } else {
            recaptchaBox.removeClass('error');
        }

        // Display error message letting end user know about validation errors
        if (!isValid) {
            errorMessage.fadeIn();
        } else if (errorMessage.is(':visible')) {
            errorMessage.fadeOut();
        }

        return isValid;
    }
})();
