AT.Dialog = function(options) {
    options = AT.validateArguments({'arguments': options, 'defaults': {
        width: 600,
        minWidth: 100,
        maxInitialHeight: 500
    }});
    this.setupVariables(options);
    this.setupDialog(options);
    if (options.selector)
        this.setupLinks(options.selector);
};

AT.Dialog.prototype.setupVariables = function(options) {
    this.maxInitialHeight = options.maxInitialHeight;
};

AT.Dialog.prototype.setupDialog = function(options) {
    var thisDialog = this;
    this.$dialog = $('<div><div></div></div>').addClass('dialog').attr('title', options.title).appendTo('body').dialog({
        autoOpen: false,
        modal: true,
        minWidth: options.minWidth,
        width: options.width,
        show: 'fade',
        hide: 'explode',
        open: function() {
            thisDialog.load(options);
        },
        close: function() {
            if (typeof(options.close) === 'function') {
                options.close.call(this.$dialog);
            }
        }
    });
};

AT.Dialog.prototype.setupLinks = function(selector) {
    var $dialog = this.$dialog;
    $(selector).click(function(event) {
        event.preventDefault();
        $dialog.dialog('open');
    });
};

AT.Dialog.prototype.show = function() {
    this.$dialog.dialog('open');
};

AT.Dialog.prototype.hide = function() {
    this.$dialog.dialog('close');
};

AT.Dialog.prototype.destroy = function() {
    this.$dialog.dialog('destroy');
};

AT.Dialog.prototype.load = function(options) {
    if (!this.loaded) {
        if (options.content)
            this.loadContent(options);
        else
            this.loadUrl(options);
        this.loaded = true;
    }
};

AT.Dialog.prototype.loadUrl = function(options) {
    this.$dialog.children().css('maxHeight', this.maxInitialHeight).load(options.url, function() {
        $(this).parent().dialog('option', 'position', 'center');
        AT.showWatermarks(this);
        AT.createButtons('input:submit', this);
        if (options.load)
            options.load.call(this);
    });
};

AT.Dialog.prototype.loadContent = function(options) {
    this.$dialog.children().css('maxHeight', this.maxInitialHeight).append(options.content).children().css('display', 'block');
    this.$dialog.dialog('option', 'position', 'center');
    AT.showWatermarks(this.$dialog.children().children());
    AT.createButtons('input:submit', this.$dialog.children().children());
    if (options.load)
        options.load.call(this.$dialog);
};

