(function () {
    var guid = 0;
    
    $.fn.upload = function (options) {
        var defaults = {
            before: null,
            complete: null,
            debug: false
        };
        
        var settings = $.extend({}, defaults, options);
        
        return this.each(function (i) {
            if (this.nodeName != 'FORM') {
                throw new Error("upload plugin only works against forms");
            }
            
            var $$ = $(this);
            var frameId = 'uploadFrame' + guid;
            
            this.target = frameId;
            
            $$.submit(function () {
                $('body').css('cursor', 'wait');
                if (settings.before) {
                    settings.before.call(this);
                }
                
                $('body').append('<iframe id="' + frameId + '" name="' + frameId + '" style="' + (settings.debug ? '' : 'display: none;') + '"></iframe>');
                
                $('#' + frameId).bind('load', function () {
                    $('body').css('cursor', 'auto');
                    if (settings.complete) {
                        settings.complete.call($$[0], $('body', this.contentWindow.document).html());
                    }
                    if (!settings.debug) setTimeout(function () {$('#' + frameId).remove();}, 50);
                });
                
                return true;                
            });
            
            guid++;
        });        
    };
})(jQuery);