/**
 * JS Dialog
 *
 * This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 *
 * @copyright Copyright (c) 2010, ecto.lt
 * @author    Benas Valančius <benas@ecto.lt>
 * @url       http://ecto.lt
 * @version   0.8
 *
 * $Id: jquery.dialog.js 646 2010-07-01 06:38:04Z noen $
 */

(function($){
$.fn.dialog = function(options, callback)
{
   
    switch(options)
    {
        case 'open':
        case 'show': // alias
            return this.each(function()
            {
                var obj = $(this);
                var data = $(this).data('dialog.data');

                if($('.ui-background').length == 0)
                {
                    $('<div class="ui-background" />').css({
                        width  : $(document).width(),
                        height : $(document).height()
                    }).appendTo('body');
                }

                var maxHeight = data.options.height ? data.options.height : $(window).height() - 190;

                if(maxHeight < 100)
                    maxHeight = 100;

                obj.find('.ui-dialog-content').css({'max-height':maxHeight});

                if(!data.options.top)
                    var top = ($(window).height() - obj.outerHeight(true)) / 3 + $(window).scrollTop();
                else
                    var top = data.options.top;

                obj.css({
                    top  : (top < 40 ? 40 : top),
                    left : ($(window).width() - obj.outerWidth(true)) / 2
                });

                if(!obj.is(':visible'))
                {
                    //html = decodeURIComponent(obj.html());
                    //obj.html(html);
                    obj.show();

                    $('.ui-background').css({
                        width  : $(document).width(),
                        height : $(document).height()
                    });

                    $('body').data('dialogs', parseInt($('body').data('dialogs')) + 1);
                }
                
                if(typeof(callback) == 'string')
                    eval(callback);
                else if(typeof(callback) != 'undefined')
                    callback();
            });

        case 'close':
        case 'hide': // alias
            return this.each(function()
            {
                if($(this).is(':visible'))
                {
                    var data = $(this).data('dialog.data');
                    $(this).hide();
                    $('#'+ $(this).attr('id') +' .ui-dialog-content').html(data.html); // Resetinam html
                    $('body').data('dialogs', parseInt($('body').data('dialogs')) - 1);

                    if(parseInt($('body').data('dialogs')) <= 0)
                    {
                        $('.ui-background').remove();
                        $('body').data('dialogs', 0);
                    }
                }
                
                if(typeof(callback) == 'string')
                    eval(callback);
                else if(typeof(callback) != 'undefined')
                    callback();
            });

        case 'remove':
        case 'delete': // alias
            return this.each(function()
            {
                if($(this).is(':visible'))
                {
                    $(this).remove();
                    $('body').data('dialogs', parseInt($('body').data('dialogs')) - 1);

                    if(parseInt($('body').data('dialogs')) <= 0)
                    {
                        $('.ui-background').remove();
                        $('body').data('dialogs', 0);
                    }
                }
                
                if(typeof(callback) == 'string')
                    eval(callback);
                else if(typeof(callback) != 'undefined')
                    callback();
            });

        default:
            var defaults = {
                close       : 'hide',
                closeButton : true,
                closeText   : 'Close',
                width       : 'auto',
                height      : false,
                top         : false,
                template    : false,
                loading     : false,
                buttons     : false,
                /*tplBody     : '<div id="{$itemId}" class="ui-dialog ui-corner-all ui-draggable">\
                                <div class="ui-dialog-titlebar {$classTitle}"><span class="ui-dialog-title">{$title}</span><a class="ui-dialog-titlebar-close" href="#"><span>{$closeText}</span></a></div>\
                                <div class="ui-dialog-content ui-resizable">{$body}</div>\
                              </div>',*/
                tplBody     : '<div id="{$itemId}" class="ui-dialog ui-corner-all ui-draggable">{$tplContent}</div>',
                tplTitle    : '<div class="ui-dialog-titlebar {$classTitle}"><span class="ui-dialog-title">{$title}</span><a class="ui-dialog-titlebar-close" href="#"><span>{$closeText}</span></a></div>',
                tplContent  : '<div class="ui-dialog-content ui-resizable">{$body}</div>',
                tplButton   : '<button type="button" class="theButton smallButton {$className}">{$title}</button>'
            };

            if($('body').data('dialog.template.body') !== undefined)
                defaults.tplBody = $('body').data('dialog.template.body');

            if($('body').data('dialog.template.buttons') !== undefined)
                defaults.tplButton = $('body').data('dialog.template.buttons');

            var options = $.extend(defaults, options);

            if(this.length == 0)
                alert('element not found');

            if(this.length > 1)
                alert('duplicate');

            if($('body').data('dialogs') === undefined)
                $('body').data('dialogs', 0);
            
            return this.each(function()
            {
                var obj = $(this);

                var title  = obj.attr('title');
                var itemId = obj.attr('id');
                var html   = obj.html();
                var templateBody = options.tplBody;
                
                templateBody = templateBody.replace('{$tplContent}', (title ? options.tplTitle : '<a class="ui-dialog-titlebar-close" href="#"><span>{$closeText}</span></a>') + options.tplContent);

                templateBody = templateBody.replace('{$itemId}',     itemId);
                templateBody = templateBody.replace('{$classTitle}', (options.template !== undefined && options.template.classTitle !== undefined ? ' '+ options.template.classTitle : ''));
                templateBody = templateBody.replace('{$title}',      title);
                templateBody = templateBody.replace('{$closeText}',  options.closeText);
                templateBody = templateBody.replace('{$body}',       html);

                obj.remove();

                $(templateBody).hide().appendTo($('body'));

                if(!options.closeButton)
                    $('#'+ itemId +' .ui-dialog-titlebar-close').remove();

                $('#'+ itemId).data('dialog.data', {
                    options : options,
                    html    : html
                });

                $('#'+ itemId +' .ui-dialog-content').css({
                    width : options.width
                });

                $('#'+ itemId +' .ui-dialog-titlebar-close').click(function(){
                    $('#'+ itemId).dialog(options.close);
                    return false;
                });

                if(options.buttons !== undefined && options.buttons.length > 0)
                {
                    $('<div class="ui-dialog-buttons blockLinks buttonsRight" />').appendTo($('#'+ itemId));

                    if(options.loading !== undefined && options.loading)
                        $('<span class="ui-dialog-loading"><img src="'+ options.loading +'" alt="Loading..." /></span>').appendTo($('#'+ itemId +' .ui-dialog-buttons'));

                    for(var x in options.buttons)
                    {
                        var templateButton = options.tplButton;

                        templateButton = templateButton.replace('{$className}', (options.buttons[x].template !== undefined && options.buttons[x].template.className !== undefined ? options.buttons[x].template.className : ''));
                        templateButton = templateButton.replace('{$title}',     options.buttons[x].title);
                        
                        $(templateButton).click(options.buttons[x].action).appendTo($('#'+ itemId +' .ui-dialog-buttons'));
                    }
                }

                $('.ui-draggable').draggable({handle:'.ui-dialog-titlebar',containment:'.ui-background'});
                // TODO: resizable?
                /*$('#'+ itemId +' .ui-resizable').resizable({
                    minHeight  : 50,
                    minWidth   : 150
                });*/
                $('.ui-dialog-title').disableSelection();
            });
    }
};
})(jQuery);
