﻿if (!window.Bauer) { window['Bauer'] = {} }
if (!window.Bauer.Controls) { window['Bauer']['Controls'] = {} }
window['Bauer']['Controls']['Dialog'] = Class.create();

Bauer.Controls.Dialog.prototype = {

    options: {
        parentElement: null,
        html: null,
        dialogDisplayed: function() { }
    },

    initialize: function(options) {
        this.options = options;

        if ($('mask')) {
            this.setupDomReferences();
        } else {
            this.createDialogElements();
        }

        this.showDialog();
    },

    createDialogElements: function() {

        this.mask = document.createElement("div");
        Element.extend(this.mask);
        this.mask.setAttribute("id", "mask");
        this.mask.setOpacity(0);
        this.mask.observe('click', this.handleCloseClick.bindAsEventListener(this));
        this.options.parentElement.appendChild(this.mask);

        this.dialog = document.createElement("div");
        Element.extend(this.dialog);
        this.dialog.setAttribute("id", "jsdialog");
        this.dialog.setOpacity(0);
        this.options.parentElement.appendChild(this.dialog);

        var close = document.createElement("a");
        Element.extend(close);
        close.addClassName("close");
        close.setAttribute("href", "#");
        close.innerHTML = "Close";
        close.observe('click', this.handleCloseClick.bindAsEventListener(this));
        this.dialog.appendChild(close);

        this.inner = document.createElement("div");
        Element.extend(this.inner);
        this.inner.addClassName("inner");
        this.dialog.appendChild(this.inner);
    },

    setupDomReferences: function() {

        this.mask = $('mask');
        this.dialog = $('jsdialog');
        this.inner = this.dialog.down('div.inner');
    },

    showDialog: function() {

        this.dialog.setOpacity(0);
        this.mask.setOpacity(0);
        this.inner.update(this.options.html);

        this.options.parentElement.getElementsBySelector('object').invoke('setStyle', { visibility: 'hidden' });

        new Fx.Style(this.mask, 'opacity', {
            duration: 300,
            transition: Fx.Transitions.circIn,
            onComplete: this.maskDisplayed.bind(this)
        }).custom(0, 0.8);
    },

    maskDisplayed: function() {
        this.dialog.setOpacity(1);

        if (this.options.dialogDisplayed) {
            this.options.dialogDisplayed();
        }
    },

    handleCloseClick: function(event) {
        event.stop();
        this.dismissDialog();
    },

    dismissDialog: function() {
        this.dialog.remove();
        this.mask.remove();
        this.dialog = null;
        this.mask = null;

        this.options.parentElement.getElementsBySelector('object').invoke('setStyle', { visibility: 'visible' });
    }
};
