﻿// Based on this pattern: 
// http://www.learningjquery.com/2007/10/a-plugin-development-pattern
(function($) {

    var $dialogs = new Array(0);

    $dialogs.current = function() {
        return this[this.length - 1];
    }

    $dialogs.hide = function() {
        for (var i = 0; i < this.length; i++) {
            this[i].hide();
        }
    }

    var o;
    var $this;

    // Dialog called like: $(selector).ModalDialog({width: 300, height: 200}); see all options below
    $.fn.ModalDialog = function(options) {

        // build main options before element iteration
        var opts = $.extend({}, $.fn.ModalDialog.Defaults, options);

        $this = this.first();
        $this.addClass('modal-d');
        o = $.meta ? $.extend({}, opts, $this.data()) : opts; // Only here if the meta data plugin is being used

        if ($dialogs.length < 1) $.fn.ModalDialog.AppendOverlay();
        if (!o.deferredDisplay) $.fn.ModalDialog.Show();

    };

    function getViewPortHeight() {
        if (typeof (window.innerWidth) != 'undefined')
            return window.innerHeight;

        if (typeof (document.documentElement) != 'undefined'
                   && typeof (document.documentElement.clientWidth) != 'undefined'
                   && document.documentElement.clientWidth != 0)
            return document.documentElement.clientHeight;

        return document.getElementsByTagName('body')[0].clientHeight;
    }

    function createDialog() {
        $('#dialog-' + o.id).remove();
        $(o.attachTo).append('<div id="dialog-' + o.id + '" class="' + o.dialogClass + '"></div>');
        var $d = $('#dialog-' + o.id);
        $d.html(o.template);
        return $d;
    }

    function addTitle($d) {
        $d.find('h3.dialog-title').text(o.title);
    }

    function setDialogCSS($d) {
        if (o.height == 0)
            o.height = $d.height();

        var topMargin;
        var top = '50%';
        var leftMargin = -Math.ceil((o.width)  / 2);

        if (o.height > getViewPortHeight() || o.position == 'absolute' || ($.browser.msie && $.browser.version == 6.0)) {
            if (o.height > getViewPortHeight())
                topMargin = 30;
            else
                topMargin = Math.ceil(getViewPortHeight() / 2 - (o.height + 12) / 2);

            top = $('html').scrollTop();
            o.position = 'absolute';
        } else {
            topMargin = -Math.ceil((o.height + 12) / 2);
        }

        $d.css({ 'margin-left': leftMargin,
            'margin-top': topMargin,
            'position': o.position,
            'width': o.width,
            'height': o.height,
            'left': '50%',
            'top': top
        });
    }
    
    function escapeToClose(e) {
        if (e.keyCode == '27') $.fn.ModalDialog.Close();
    }

    $.fn.ModalDialog.AppendOverlay = function() {
        $('body').append('<div id="overlay-' + o.id + '" class="' + o.overlayClass + '"></div>');
        $('#overlay-' + o.id).click($.fn.ModalDialog.Close);
        $('#overlay-' + o.id).show();
        //$('select').hide();
    };

    $.fn.ModalDialog.Show = function() {
        $('#overlay-' + o.id).css('background-image', 'none');
        $dialogs.hide();
        $dialogs.push(createDialog());
        addTitle($dialogs.current());

        $dialogs.current().find(o.insertIntoSelector).append($this.show());
        //$this.find('select').show();
        $dialogs.current().undelegate(o.closeSelector, 'click');
        $dialogs.current().delegate(o.closeSelector, 'click', $.fn.ModalDialog.Close);
        $('body').unbind('keypress', escapeToClose);
        $('body').keypress(escapeToClose);
        setDialogCSS($dialogs.current());
        $dialogs.current().show();
    };

    $.fn.ModalDialog.Close = function() {
        if ($dialogs.length == 1) $('.dialog-overlay').remove();
        if (o.reattachContent) $(o.attachTo).append($dialogs.current().find('.modal-d').hide());
        $dialogs.current().remove();
        $dialogs.pop();
        if ($dialogs.length) $dialogs.current().show(); 
        //$('select').show();
        if (o.onClose) o.onClose();
        return false;
    };

    $.fn.ModalDialog.Defaults = {
        width: 350,
        height: 0,
        title: '',
        id: '',
        position: 'fixed', // or absolute
        template: '<a href="#" id="close-dialog"></a><div class="top"></div><div class="middle"><h3 class="dialog-title"></h3><hr /></div><div class="bottom"></div>',
        closeSelector: '#close-dialog, .cancel-button',
        overlayClass: 'dialog-overlay',
        dialogClass: 'dialog',
        insertIntoSelector: '.middle',
        attachTo: 'body',
        reattachContent: false,
        deferredDisplay: false,
        onClose: false
    };
})(jQuery);
