var OUT, RL;
$(document).ready(function () {
    RL = $('#the-url');
    OUT = $('#the-output');

    RL.focus();

    $('#the-form').submit(function () {
        OUT.hide(100);
        var url = RL.val();
        if (url.length) {
            $.ajax({
                url: '/generate/',
                type: 'GET',
                data: 'url='+encodeURI(url),
                dataType: 'json',
                success: function (json) {
                    if (json.errors) {
                        var errs = '';
                        $.each(json.errors, function (key, val) {
                                errs += 'The following error occurred while processing <strong>' + key + '</strong>:<br />';
                                errs += '<code>' + val + '</code>';
                            });
                        show(errs, true);
                        return false;
                    }

                    var itty;
                    for (var key in json.urls) { itty = json.urls[key]; break; }
                    show("Here's your shortened URL:<br /><input style=\"width: 90%\" type=\"text\" value=\"" + itty.shortcut + "\" /><br />The URL was compressed by <strong>" + itty.compression + "</strong>!!!  Enjoy!!", false);
                },
                error: function (xhr, status, err) {
                    show('An error occurred: ' + err, true);
                }
            });
            return false;
        } else {
            show('Please enter a URL to shorten!', true);
        }
        return false;
    });
});

function show(msg, iserr) {
    OUT.toggleClass('error', iserr);
    OUT.html(msg);
    OUT.show(200);
}