(function($) {
    $.fn.error = function(options) {
        var opts = $.extend({}, $.fn.error.defaults, options);
        return this.each(function(){
            $this = $(this);
            setupErrorContainer($this);
        });
    };

    function setupErrorContainer($this) {
        if ($($this).find('div#dialog').length == 0) {
            $($this).append('<div id="dialog"></div>');
        }

        setupListeners();
    }

    function setupListeners() {
        $('#dialog').bind('ajaxError', function(evt, request, error){
            try {
                responseText = $.parseJSON(request.responseText);
                errorBody = '<div>There was a fatal error during your request.<br /><br />';
                errorBody += '<div style="text-align:left;"><h3>Exception information:</h3><p><b>Message:</b><br />' + responseText.error.exception.message + '</p>';
                errorBody += '<h3>Request Parameters:</h3><pre>' + responseText.error.request + '</pre></div></div>';

                $.fn.error.displayError(responseText.error.exception.title, errorBody);
            } catch(e) {
                $.fn.error.displayError('Invalid Response', e);
            }
            // Call for form cleanup since there was an error
            $.fn.form.cleanUp();
        });
    }

    $.fn.error.displayError = function(title, content) {
        $("#dialog").clone().insertAfter('#dialog').attr('id', 'error-dialog');

        $("#error-dialog").dialog({
            resizable: $.fn.error.defaults.resizable,
            width: $.fn.error.defaults.width,
            height: $.fn.error.defaults.height,
            modal: $.fn.error.defaults.modal,
            title: title,
            buttons: {
                'Ok': function() {
                    $(this).dialog('destroy');
                    $(this).remove();
                }
            },
            open: function() {
                $(this).html(content);
            },
            close: function() {
                $(this).dialog('destroy');
                $(this).remove();
            }
        });
    }

    $.fn.error.defaults = {
        modal: true,
        height: 500,
        width: 500,
        resizable: false,
        data: {}
    };
})(jQuery);
$(function(){
  $('body').error();
});
