YUI().use('event-key', 'node', 'gallery-bitly', function(Y) {
    /*
        To use the bit.ly module, you must have a bit.ly username and apiKey.
        If you do not have an apiKey, sign up for a bitly account and go to
        your Account page to get your apiKey.
    */
    var bitly = new Y.bitly({
        username: username,
        key: key
    }),
    exp = Y.one('#expand'),
    short = Y.one('#shorten'),
    createElm = function(par, url) {
        var item = '';
        if (par.one('em')) {
            item = par.one('em');
        } else {
            item = Y.Node.create('<em></em>');
            par.append(item);
        }
        item.set('innerHTML', '<a href="' + url + '">' + url + '</a>');
        return item;
    },
    shorten = function(node) {
        bitly.shorten(short.get('value'), function(r) {
            var par = node.get('parentNode'),
                item = createElm(par, r.shortUrl);

            exp.set('value', r.shortUrl);
        });
    },
    expand = function(node) {
        bitly.expandByURL(exp.get('value'), function(r) {
            var par = node.get('parentNode'),
                item = createElm(par, r.longUrl);

            short.set('value', r.longUrl);
        });
    };


    Y.on('click', function(e) {
        shorten(e.target);
    }, '#do_shorten');

    Y.on('click', function(e) {
        expand(e.target);
    }, '#do_expand');

    Y.on('blur', function(e) {
        shorten(e.target);
    }, '#shorten');

    Y.on('blur', function(e) {
        expand(e.target);
    }, '#expand');

    short.on('key', function(e) {
        shorten(e.target);
    }, 'enter');

    exp.on('key', function(e) {
        expand(e.target);
    }, 'enter');

});
