<script>
YUI().use("jsonp", "transition",function (Y) {

    var url = "http://yuilibrary.com/gallery/api/random?callback={callback}",
        outputDiv = Y.one("#out"),
        gallery;
        
    // Using the configuration object syntax
    gallery = new Y.JSONPRequest(url, {
        on: {
            success: function (response) {
                var module = response.modules[0],
                    author = module.owner;

                // Some users don't have a rank
                if (!author.rank) {
                    author.rank = "user";
                }

                // Format the author info and store as a property of the
                // module object for use by Y.Lang.sub
                // ('this' refers to the JSONPRequest object by default)
                module.authorHTML = Y.Lang.sub(this.authorTemplate, author);

                outputDiv.setHTML(Y.Lang.sub(this.moduleTemplate, module));

                // Add some flare to the poll interval by showing a "time left"
                // indicator via the header's border
                Y.one("#out h4")
                    .setStyle("borderRightWidth", "100px")
                    .transition({
                        borderRightWidth: 0,
                        duration: 7
                    }, function () {
                        if (gallery.polling) {
                            gallery.send();
                        }
                    });
            },

            failure: function () {
                gallery.polling = false;
                outputDiv.setHTML(this.failureTemplate);

                // Wire up the Try again button
                outputDiv.one("button").on("click", function () {
                    gallery.send();
                });
            }
        }
    });


    gallery.moduleTemplate =
        '<h4><a href="{url}">{title}</a></h4>' +
        '<p class="author">{authorHTML}</p>' +
        '<div>{summary}</div>';

    gallery.authorTemplate =
        '<img src="{icon}" height="30" width="30">' +
        ' {fullname} <span class="rank">({rank})</span>';

    gallery.failureTemplate =
        '<p class="error">Ack, I couldn\'t reach the Gallery web service! ' +
        'Would you like to <a href="?mock=true">try with mock data</a> or try again?</p>' +
        '<button>Try again</button>';

    gallery.polling = false;


    // Click the button to send the JSONP request
    Y.one("#start").on("click", function (e) {
        if (!gallery.polling) {
            gallery.polling = true;
            gallery.send();
        }
    });

    Y.one("#stop").on("click", function (e) {
        gallery.polling = false;
    });

});
</script>
