﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />


var DialogSettings = {
    pageContainerId: '#page'
};

var Dialog = function(dialogId, onShow, onHide) {
    var _instance = this;
    var _element = this.element = $('#' + dialogId);
    this.onShow = onShow;
    this.onHide = onHide;
    this.isVisible = false;

    if (_element.hasClass('shadow')) {
        jQuery.each(['t', 'l', 'r', 'b'], function() {
            _element.prepend('<div class="ds ' + this + '"></div>');
            var o = this;
            jQuery.each(['l', 'r'], function() {
                if (this.valueOf() == o.valueOf()) return true;
                _element.prepend('<div class="ds ' + o + this + '"></div>');
            });
        });
    }

    if (_element.hasClass('draggable')) {
        _element.draggable({ handle: '.handle' });        
    }

    _element.find('.close').click(function() {
        _instance.hide();
    });
}

Dialog.prototype.show = function() {
    if (!this.onShow || this.onShow.call(this) != false) {
        this.centerDialog();
        this.element.show();
        this.isVisible = true;
    }
};

Dialog.prototype.hide = function() {
    if (!this.onHide || this.onHide.call(this) != false) {
        this.element.hide();
        this.isVisible = false;        
    }
};

Dialog.prototype.toggle = function() {
    (this.isVisible ? this.hide : this.show).call(this);
}

Dialog.prototype.centerDialog = function() {
    var container = { width: this.element.outerWidth(), height: this.element.outerHeight() };
    var doc = {
        width: Math.min($(window).width(), $(DialogSettings.pageContainerId).width()),
        height: Math.min($(window).height(), $(DialogSettings.pageContainerId).height())
    };
    var windowScroll = { top: $(window).scrollTop(), left: $(window).scrollLeft() };

    this.element.css({
        top: (doc.height - container.height) / 2 + windowScroll.top,
        left: (doc.width - container.width) / 2 + windowScroll.left
    });
}