// jQuery Simple Modal Dialogs Plugin
//
// Version 1.0
//
// Lord LoriK
// Nov 26, 2009
//
(function($) {
    var _currentDialog = false;

    $.simpleModal = {
        overlayOpacity: .5,
        overlayColor: '#fff',
        okButton: '&nbsp;OK&nbsp;',
        cancelButton: '&nbsp;Cancelar&nbsp;',
        defaultAlertTitle: 'Alerta',
        defaultConfirmTitle: 'Confirmaci&oacute;n',
        defaultPromptTitle: 'Pregunta',
        jQueryDataKey: '$SimpleModalDialog$',

        _show: function(title, message, value, type, callback) {
            var $content = $('<table class="popup-content">' +
				'<tr><td><span class="' + type + '">&#160;</span></td><td><div class="popup-message"></div></td></tr>' +
				'<tr><td colspan="2"><div class="popup-panel"></div></td></tr>' +
				'</table>'),
				$message = $content.find('.popup-message'),
				$panel = $content.find('.popup-panel');

            $('body').append($content);
            $message.text(message);
            $message.html($message.text().replace(/\n/g, '<br />'));
            switch (type) {
                case 'alert':
                    $panel.append('<input class="button" type="button" value="' + $.simpleModal.okButton + '" id="popup-ok" />');
                    $("#popup-ok").click(function() {
                        _currentDialog.hide();
                        callback && callback(true);
                    });
                    $("#popup-ok").focus().keypress(function(e) {
                        if (e.keyCode == 13 || e.keyCode == 27) $("#popup-ok").trigger('click');
                    });
                    break;
                case 'confirm':
                    $panel.append('<input class="button" type="button" value="' + $.simpleModal.okButton + '" id="popup-ok" /> <input class="button" type="button" value="' + $.simpleModal.cancelButton + '" id="popup-cancel" />');
                    $("#popup-ok").click(function() {
                        _currentDialog.hide();
                        callback && callback(true);
                    });
                    $("#popup-cancel").click(function() {
                        _currentDialog.hide();
                        callback && callback(false);
                    });
                    $("#popup-ok").focus();
                    $("#popup-ok, #popup-cancel").keypress(function(e) {
                        if (e.keyCode == 13) $("#popup-ok").trigger('click');
                        if (e.keyCode == 27) $("#popup-cancel").trigger('click')
                    });
                    break;
                case 'prompt':
                    $message.append('<br /><input class="text" type="text" size="30" id="popup-prompt" />');
                    $panel.append('<input class="button" type="button" value="' + $.simpleModal.okButton + '" id="popup-ok" /> <input class="button" type="button" value="' + $.simpleModal.cancelButton + '" id="popup-cancel" />');
                    $("#popup-prompt").width($message.width());
                    $("#popup-ok").click(function() {
                        var val = $("#popup-prompt").val();
                        _currentDialog.hide();
                        callback && callback(val);
                    });
                    $("#popup-cancel").click(function() {
                        _currentDialog.hide();
                        callback && callback(null);
                    });
                    $("#popup-prompt, #popup-ok, #popup-cancel").keypress(function(e) {
                        if (e.keyCode == 13) $("#popup-ok").trigger('click');
                        if (e.keyCode == 27) $("#popup-cancel").trigger('click')
                    });
                    if (value) $("#popup-prompt").val(value);
                    $("#popup-prompt").focus().select();
                    break
            }
            $content.data($.simpleModal.jQueryDataKey, { internal: true });
            $content.simpleModal({ title: title });
            $content.find('#popup-content td:first').width('1px');
        },

        alert: function(message, title, callback) {
            if (typeof title == 'function') {
                callback = title;
                title = '';
            }
            $.simpleModal._show(title || $.simpleModal.defaultAlertTitle, message, null, 'alert', function(r) {
                callback && callback(r);
            })
        },

        confirm: function(message, title, callback) {
            if (typeof title == 'function') {
                callback = title;
                title = '';
            }
            $.simpleModal._show(title || $.simpleModal.defaultConfirmTitle, message, null, 'confirm', function(r) {
                callback && callback(r);
            })
        },

        prompt: function(message, value, title, callback) {
            if (typeof title == 'function') {
                callback = title;
                title = '';
            }
            $.simpleModal._show(title || $.simpleModal.defaultPromptTitle, message, value, 'prompt', function(r) {
                callback && callback(r);
            })
        }
    };

    function _handleOverlay(cmd) {
        switch (cmd) {
            case 'show':
                _handleOverlay('hide');
                $('body').append('<div id="popup-overlay"></div>');
                $('#popup-overlay').css({
                    position: 'absolute',
                    zIndex: 99998,
                    top: '0px',
                    left: '0px',
                    width: '100%',
                    height: $(document).height(),
                    background: $.simpleModal.overlayColor,
                    opacity: $.simpleModal.overlayOpacity
                });
                break;
            case 'hide':
                $("#popup-overlay").remove();
                break
        }
    };

    function SimpleModalDialog($elem, options) {
        var that = this;

        this._options = options || {};
        this._elem = $elem;

        this.show = function() {
            var opts = this._options,
				elem = this._elem,
				isInternal = elem.data($.simpleModal.jQueryDataKey).internal,
				$parent = elem.parents(isInternal ? 'body' : 'form');

            if (_currentDialog) _currentDialog.hide();
            _currentDialog = this;
            _handleOverlay('show');

            (this._parent = $($parent.length ? $parent[0] : 'body')).append('<div id="popup-container"><h1 id="popup-title"></h1><div></div></div>');

            var $cont = $("#popup-container"),
				$title = $("#popup-title"),
				pos = ($.browser.msie && parseInt($.browser.version) <= 6) ? 'absolute' : 'fixed';

            if (opts.dialogClass) $cont.addClass(opts.dialogClass);
            $cont.css({
                position: pos,
                zIndex: 99999,
                padding: 0,
                margin: 0
            });
            $title.html(opts.title || '&#160;');
            $title.next().append(elem.show());

            var $panel = $cont.find('.popup-panel');

            if (opts.cancelable) {
                $('#popup-container, #popup-container *').keypress(function(e) {
                    if (e.keyCode == 27) that._elem.simpleModal('close');
                });
            }
            if (isInternal) {
                $panel.find('.button:first').focus();
            }
            else {
                ($panel.length ? $panel.find('.button:first:visible') : $cont.find('.button:last:visible')).focus().each(function() {
                    var $b = $(this);

                    setTimeout(function() {
                        $b.hide();
                        setTimeout(function() {
                            $b.show();
                        }, 0);
                    }, 0);
                });
            }

            var w = 0;

            $("#popup-container > *").css({
                padding: 0,
                margin: 0
            }).each(function() {
                w = Math.max($(this).outerWidth(true), w);
            });

            $cont.css({
                minWidth: w,
                maxWidth: w,
                width: w
            });
            this.reposition();
            this.maintainPosition(true);

            if (opts.draggable) {
                try {
                    $cont.draggable({
                        handle: $title
                    });
                    $title.css({
                        cursor: 'move'
                    });
                } catch (e) { }
            }
        };

        this.hide = function() {
            var d = that._elem.data($.simpleModal.jQueryDataKey);

            _currentDialog = false;
            if (!d.internal) {
                $(this._parent).append(that._elem.hide());
            }
            that._elem.data($.simpleModal.jQueryDataKey, null);
            $("#popup-container").remove();
            _handleOverlay('hide');
            that.maintainPosition(false);
        };

        this.reposition = function() {
            var $wnd = $(window),
				$cont = $("#popup-container"),
				top = (($wnd.height() / 2) - ($cont.outerHeight() / 2)) + that._options.verticalOffset,
				left = (($wnd.width() / 2) - ($cont.outerWidth() / 2)) + that._options.horizontalOffset;

            if (top < 0) top = 0;
            if (left < 0) left = 0;
            if ($.browser.msie && parseInt($.browser.version) <= 6) top = top + $wnd.scrollTop();
            $cont.css({
                top: top + 'px',
                left: left + 'px'
            });
            $("#popup-overlay").height($(document).height())
        };

        this.maintainPosition = function(status) {
            if (that._options.repositionOnResize) {
                if (status) {
                    $(window).bind('resize', that.reposition);
                }
                else {
                    $(window).unbind('resize', that.reposition);
                }
            }
        };
    };

    $.fn.simpleModal = function(options) {
        if (this.length == 0) return this;

        if (typeof (options) == 'string') {
            var d = this.data($.simpleModal.jQueryDataKey);

            switch (options) {
                case 'close':
                    if (d) d.elem.hide();
                    break;

                case 'center':
                    if (d) d.elem.reposition();
                    break;
            }
        }
        else {
            var defaults = {
                verticalOffset: -75,
                horizontalOffset: 0,
                repositionOnResize: true,
                overlayOpacity: .5,
                overlayColor: '#fff',
                draggable: true,
                title: null,
                dialogClass: null,
                cancelable: false
            };

            options = $.extend(defaults, options);

            var dlg = new SimpleModalDialog(this, options),
				data = $.extend({ elem: dlg, internal: false }, this.data($.simpleModal.jQueryDataKey));

            this.data($.simpleModal.jQueryDataKey, data);
            dlg.show();
        }
        return this;
    };

    jAlert = function(message, title, callback) {
        $.simpleModal.alert(message, title, callback)
    };
    jConfirm = function(message, title, callback) {
        $.simpleModal.confirm(message, title, callback)
    };
    jPrompt = function(message, value, title, callback) {
        $.simpleModal.prompt(message, value, title, callback)
    }
})(jQuery);