(function ($) {

    var options = {};
    var modal;
    var dialogShown = false;
    function init() {
        if (!modal) {
            modal = $('<div class="modal">');
        }
    };

    $.postcodelookup = function (postcode, callback) {
        options.postcode = postcode;
        options.callback = callback;
        init();
        if (postcode == '') {
            showPostcodeInput();
            return;
        }
        modal.html($('<p class="loading">Loading...</p>'));
        showDialog();
        getResults();
    };

    function showPostcodeInput() {
        var form = $('<form id="postcode-form" class="formStyle"></form>').submit(function () {
            var postcode = $('input[name="postcode"]', this).val();
            if (postcode == '') {
                return false;
            }
            options.postcode = postcode;
            getResults();
            return false;
        });
        form.html($('<p><label for="postcode">Postcode:</label><input id="postcode" name="postcode" type="text" class="textfield"></p><p class="buttons"><input type="submit" value="Lookup"></p>'));
        modal.html(form);
        showDialog();
    };

    function showDialog() {
        if (dialogShown) {
            modal.dialog('open');
        } else {
            modal.dialog({
                draggable: false,
                resizable: false,
                title: 'Address Lookup',
                modal: true,
                bgiframe: true,
                width: 500,
                height: 300
            });
            dialogShown = true;
        }
    };

    function getResults() {
        $.post('/Postcode/Lookup', { postcode: options.postcode }, showResults, 'json');
    };

    function showResults(results) {
        if (results.length == 0) {
            var html = $('<p>No results found for that postcode, you can <a href="#" id="try-again">try again</a> or <a href="#" id="enter-manually">enter the address manually</a></p>');
            html.find('#try-again').click(showPostcodeInput);
            html.find('#enter-manually').click(function () {
                modal.dialog('close');
                return false;
            });
            modal.html(html);
            return;
        }
        var html = $('<ul>');
        $.each(results, function () {
            var address = this;
            var a = $('<a href="#">' + address.Address + '</a>');
            a.click(function () {
                modal.html('<p class="loading">Loading...</p>');
                getAddress(address.Id);
            });
            html.append($('<li>').append(a));
        });
        modal.html(html);
    };

    function getAddress(id) {
        $.post('/Postcode/GetAddress', { id: id }, function (result) {
            options.callback.call(window, result);
            modal.dialog('close');
        }, 'json');
    };

})(jQuery);
