(function($) {
    var defaults = {};

    $.fn.applet = function(url, options) {
        var setOptions = function(el) {
            options = $.extend({}, defaults, el.data('gbook_request:options'), options);
            el.data('gbook_request:options', options);
        }

        var getJSON = function(el, data) {
            $.post(url, data, function(data) {
                el.html(data.html);
                el.find("#request-form").submit(function() {
                    var postData = {};
                    var formData = $(this).find(":input").serializeArray();
                    var command;
                    $.each(formData, function (i, field) {
                        if (i == 0) command = field.value;
                        postData[field.name] = field.value;
                    });
                    if (command.match(/^sfcp:requestAction/)) {
                        return true;
                    } else {
                        getJSON(el, postData);
                        return false;
                    }
                });
            }, "json");
        };

        this.each(function(el) {
            el = $(this);
            setOptions(el);
            getJSON(el, {});
        });

        return this;
    }
})(jQuery);
