if (typeof(WF) == 'undefined') var WF = {};

// A stack to hold all of the created dialogs
WF.dialogs = [];

WF.Dialog = function() {
    var self = this,
        args = arguments;
    
    self.init.apply(self, args);
};

WF.Dialog.prototype = {
    init: function (options) {
        var self = this;
        
        /*
        ** Default parameters for all dialogs. Not very elaborate right now, 
        ** unfortunatley most of the dialogs appear to have no similar 
        ** formatting/style. Some heavy duty callbacks for sure.
        */
        var defaults = {
            title: 'Please Supply a Title',
            content: '<p>Please supply content for this dialog, in a string '+
                     'format, jQuery object, or array of strings.</p>',
        };
        
        
        if (!$('#dialog-overlay').size()) {
            $('body').prepend('<div id="dialog-overlay" />');
        }
        self.dialog_overlay = $('#dialog-overlay');
        
        self.options = jQuery.extend(defaults, options);
        
        /*
        ** Get a new id... dialog objects should be auto-appended 
        ** to a global array called WF.dialogs, which helps with this count.
        */
        self.id = WF.dialogs.length;
        
        // Create the initial dialog wrapper
        self.dialog = $('<div/>')
                      .attr({ 'class': 'dialog', 'id': 'dialog-'+self.id })
                      .prependTo('body');
        
        if (self.options.width) {
            self.dialog.width(self.options.width)
        };
        
        // Table wrapper, this goes inside of the dialog and does the shadow
        var table_html = Array(
            '<tr class="outlineCanada">',
                '<td class="west">&nbsp;</td>',
                '<td class="center"><h3 class="dialogHeaderTitle"></h3></td>',
                '<td class="east">&nbsp;</td>',
            '</tr>',
            '<tr class="outlineUSA">',
                '<td class="west">&nbsp;</td>',
                '<td class="center"><div id="dialogInnerBody" class="clearfix"></div></td>',
                '<td class="east">&nbsp;</td>',
            '</tr>',        
            '<tr class="outlineMexico">',
                '<td class="west">&nbsp;</td>',
                '<td class="center"><div class="buttons" id="dialogFooterButtons"></div></td>',
                '<td class="east">&nbsp;</td>',
            '</tr>');
        
        self.dialog_table = $('<table/>')
                            .addClass('dialogTableWrapper')
                            .html(table_html.join(""))
                            .appendTo(self.dialog)
        
        // Close button
        self.close_button = $('<a/>')
                            .attr('class', 'dialogCloseButton')
                            .text('CLOSE')
                            .click(function() {
                                self.close(); })
                            .appendTo(self.dialog);
        
        // Build the content
        self.dialog_content = $('<div/>').attr('class', 'dialogBody');
        
        var dialog_body;
        if (typeof(self.options.content) == 'string') {
            // Let's make sure this isn't ajax content first...
            dialog_body = (self.options.content[0] == '/') ? 'AJAX' : self.options.content;
        } else if (!(self.options.content.constructor.toString().indexOf("Array") == -1)) {
            dialog_body = self.options.content.join("");
        } else if (self.options.content instanceof jQuery) {
            dialog_body = false;
        }
        
        if (dialog_body && (dialog_body != 'AJAX')) {
            self.dialog_content.html(dialog_body);
        } else if (dialog_body == 'AJAX') {
            self.dialog_content.load(self.options.content, function() {
                self.display();
            });
        } else {
            self.options.content.appendTo(self.dialog_content);
        }
        
        self.dialog_content.appendTo('#dialogInnerBody');
        
        // Dialog Title
        self.dialog_title = $('h3.dialogHeaderTitle').text(self.options.title);
        
        // Dialog Footer Buttons
        self.dialog_footer = $('#dialogFooterButtons')
        if (self.options.actions) {
            for (var i=0; i < self.options.actions.length; i++) {
                self.options.actions[i].setDialog(self);
                self.dialog_footer.append(self.options.actions[i].renderButton());
            };
        };
        
        // Display the dialog
        if (dialog_body != 'AJAX') {
            self.display();
        };
        
        // If there is a callback, handle that now
        $('a.dialogClose').click(function() {
            self.close();
        });
        
        // Finally, add the dialog to the stack
        WF.dialogs.push(self);
    },
    
    display: function() {
        var self = this;
        
        if (self.options.width) {
            self.dialog.css({ marginLeft: -self.options.width/2 })
        };
        
        // Animate the dialog into place, setting the correct properties to vertically center it
        // self.dialog.animate({ top: '100px' }, 600);
        self.dialog.animate({ top: '50%', marginTop: -(self.dialog.height()/2) }, 600);
        
        if (self.options.callback) {
            self.options.callback.call(self);
        }
        
        self.dialog_overlay.fadeIn('fast').click(function() {
            self.close();
        });
    },
    
    close: function() {
        var self = this;
        
        // Slide the dialog out of the window
        self.dialog.animate({ top: '150%' }, 500);
        
        // Fade out the dialog overlay, and when that is finished, remove the actual dialog from the DOM
        self.dialog_overlay.fadeOut('fast', function () {
            self.dialog.remove();
        });
        
    },
    
    displayError: function(error) {
        var self = this;
        // self.error = $('<div/>').attr('class', 'dialogError').text(error).prependTo(self.dialog_content).slideDown('fast');
        console.log(error);
    },
    
    clearErrors: function() {
        var self = this;
        if (self.error)
            self.error.slideUp('fast');
        
        $('span.msg.error').slideUp('fast', function() {
            $(this).remove();
        });
    },
    
    reposition: function(speed) {
        var self = this,
            height = self.dialog.height();
        
        speed = (speed) ? speed : 400;
            
        self.dialog.animate({ marginTop: -(height/2) }, speed);
    }
};


// Called with the context that this = the button.
WF.Dialog.CANCEL_BUTTON = function(){
    this.close();
}

// Called with the context that this = the button.
WF.Dialog.SUBMIT_FORM = function(){
    this.dialog_content.find('form').submit();
}

WF.DialogButton = function() {
    var self = this,
        args = arguments;
        
    self.init.apply(self, args);
};

WF.DialogButton = Class.$extend({
    __init__: function (label, callback) {
        var self = this;
        
        self.label = label || 'WF.NoLabel';
        self.callback = callback || false;
        
        return self;
    },
    
    renderButton: function() {
        var self = this;
        
        var button = $('<button/>').addClass('btn small').html('<span>'+self.label+'</span>');
        
        button.click(function() {
            self.callback.call(self.dialog);
        });
        
        return button;
    },
    
    setDialog: function(dialog) {
        var self = this;
        self.dialog = dialog;
    }
});

WF.DialogURLButton = WF.DialogButton.$extend({
    __init__: function(label, url) {
        var self = this;
        
        self.label = label || 'WF.NoLabel';
        self.url = url || null;
        
        return self;
    },
    
    renderButton: function() {
        var self = this;
        
        var button = $('<a/>').addClass('btn small').html('<span>'+self.label+'</span>');
            button.attr('href', self.url);
        
        return button;
    }
});

