; (function ($, window, document, undefined) {
    "use strict";

    var $win = $(window),
        $doc = $(document),
        $body = $(document.body);

    function isNullOrWhiteSpace(str) {
        if (typeof str === "undefined" ||
            !str ||
            str.length === 0 ||
            !/[^\s]/.test(str) ||
            /^\s*$/.test(str) ||
            str.replace(/\s/g, "") === "") {
            return true;
        } else {
            return false;
        }
    }

    var _options = {};

    $.llpgLookup = function () {
        var self = this;
        return self;
    };

    $.llpgLookup.prototype.name = 'llpgLookup';

    $.llpgLookup = {
        init: init
    };

    $.llpgLookup.reformatPostcode = function (value) {
        var postcodeValue = value.toUpperCase();
        var result = postcodeValue;

        postcodeValue = postcodeValue.replace(/\s/g, "");

        if (postcodeValue.length >= 5 && postcodeValue.length <= 7) {
            result = postcodeValue.substring(0, postcodeValue.length - 3) + " " + postcodeValue.substring(postcodeValue.length - 3);
        }

        return result;
    };

    function init(options) {
        _options = $.extend({}, $.llpgLookup.defaultOptions, options);

        $("#" + _options.rowId).hide();
        $("#" + _options.errorMessageContainerId).hide();

        $(document).on("keypress", "#" + _options.postcodeId, function (args) {
            if (args.keyCode === 13) {
                $("#" + _options.buttonId).click();
                return false;
            }
        });

        $("#" + _options.selectAddressButtonId).on("click", function (ev) {
            ev.preventDefault();

            var address = $("#" + _options.fieldIdentifier).val();

            if (address.length > 0) {
                $("#" + _options.formId).submit();
            }
        });

        $("#" + _options.changeAddressButtonId).on("click", function(ev) {
            ev.preventDefault();

            var url = _options.resetLocationUrl;

            if (isNullOrWhiteSpace(url) === false) {
                document.location.href = url;
                return;
            }

            var row = $("#" + _options.rowId);
            var errorContainer = $("#" + _options.errorMessageContainerId);
            var addressContainer = $("#" + _options.addressContainerId);

            $("#" + _options.postcodeId).val("");

            row.hide();
            errorContainer.hide();
            addressContainer.show();

        });

        $("#" + _options.buttonId).click(function (ev) {
            ev.preventDefault();
            var row = $("#" + _options.rowId);
            var button = $("#" + _options.buttonId);
            var postcode = $("#" + _options.postcodeId);
            var errorContainer = $("#" + _options.errorMessageContainerId);
            var errorMessage = $("#" + _options.errorMessageId);

            $(row).hide();
            $(button).prop("disabled", true);
            $(postcode).removeClass("ErrorFormField");
            $(errorContainer).hide();
            $(postcode).val($.llpgLookup.reformatPostcode($(postcode).val()));

            $.ajax
                (
                    {
                        contentType: "application/json; charset=utf-8",
                        url: "/llpg/lookup",
                        data: { postcode: $(postcode).val(), classification: _options.classification },
                        dataType: "jsonp"
                    }
                )
                .done(function (data) {
                    if (data === null || typeof data == "undefined" || data.length === 0) {
                        $(postcode).addClass("ErrorFormField");
                        $(errorMessage).text(_options.noResultsMessage);
                        $(errorContainer).show();
                        return;
                    }

                    var selectBox = $("#" + _options.fieldIdentifier);
                    var options = selectBox.find("option").remove().end().append('<option value=""> - SELECT YOUR ADDRESS - </option>');

                    $.each(data, function (i, val) {
                        options.append('<option value="' + val.Uprn + '">' + val.AddressLine1 + '</option>');
                    });

                    $(row).show();
                })
                .fail(function (jqXHR, textStatus, errorThrown) {
                    $(postcode).addClass("ErrorFormField");
                    var msg = (errorThrown === null || typeof errorThrown === "undefined" || errorThrown.length === 0) ? _options.defaultErrorMessage : errorThrown;
                    $(errorMessage).text(msg);
                    $(errorContainer).show();
                })
                .always(function () {
                    $(button).prop("disabled", false);
                });
        });
    }

    $.llpgLookup.defaultOptions = {
        formId: "",
        fieldIdentifier: "",
        rowId: "",
        buttonId: "",
        selectAddressButtonId: "",
        changeAddressButtonId: "",
        resetLocationUrl: "",
        addressContainerId: "",
        postcodeId: "",
        errorMessageContainerId: "",
        errorMessageId: "",
        classification: "",
        callbackUrl: "/llpg/lookup",
        noResultsMessage: "Sorry, that does not appear to be a Southwark postcode",
        defaultErrorMessage: "There was a problem looking up this postcode, please try again later"
    };

})(jQuery, window, document);
