﻿/**
* Dialog
*
* @author    caixw <http://www.caixw.com>
* @copyright Copyright (C) 2010, http://www.caixw.com
* @license   FreeBSD license
*/


/**
* jQuery的Dialog插件。
*
* @param object content
* @param object options 选项。
* @return 
*/
var rootImagePath = 'http://s.laoqianzhuang.com/Themes/Default/Images/';
function DialogBox(content, options) {
    var defaults = { // 默认值。 
        title: '标题',       // 标题文本，若不想显示title请通过CSS设置其display为none 
        showTitle: true,     // 是否显示标题栏。
        closeText: 'X', // 关闭按钮文字，若不想显示关闭按钮请通过CSS设置其display为none 
        draggable: true,     // 是否移动 
        modal: true,         // 是否是模态对话框 
        center: true,        // 是否居中。 
        fixed: true,         // 是否跟随页面滚动。
        time: 0,             // 自动关闭时间，为0表示不会自动关闭。 
        id: false,            // 对话框的id，若为false，则由系统自动产生一个唯一id。 
        height: 300,
        width: 400,
        opacity: 0,
        titleType:-1         //1普通标头  2 vip
    };
    var options = $.extend(defaults, options);
    options.id = options.id ? options.id : 'dialog-' + DialogBox.__count; // 唯一ID
    var overlayId = options.id + '-overlay'; // 遮罩层ID
    var timeId = null;  // 自动关闭计时器 
    var isShow = false;
    var isIe = $.browser.msie;
    var isIe6 = $.browser.msie && ('6.0' == $.browser.version);

    /* 对话框的布局及标题内容。*/
    var barHtml = "";
    if (options.showTitle) {
        switch (options.titleType) {
            case -1:
                barHtml = '<div class="bar"><div class="top_titlet" style="width:' + options.width + 'px;"><span>' + options.title + '</span><div class="t_title">  <div class="close"><a href="###"></a> </div></div></div></div>';
                break;        
            case 2:
                barHtml = '<div class="bar"><div class="top_title"><div class="close"><a href="###"></a></div></div></div>';
                break;
            case 3:
                barHtml = '<div class="bar"><div class="top_title2"><span>' + options.title + '</span><div class="close"><a href="###"></a></div></div></div>';
                break;           
            default:
                barHtml = '<div class="bar" style="border:0px;"><a class="close" href="javascript:void(0)" title="关闭"></a><h4 style="*width:' + options.width + 'px;">' + options.title + '</h4></div>';
                break;
        }
    }


    var dialog;
    switch (options.titleType) {
        case -1:
            dialog = $('<div id="' + options.id + '" class="dialog"><div class="containerts" style="width:' + options.width + ';overflow:hidden;">' + barHtml + '<div id="dialogcontent"></div></div></div>').hide();
            break;       
        case 2:
        case 3:
            dialog = $('<div id="' + options.id + '" class="dialog"><div class="wrap"><div class="container">' + barHtml + '<div id="dialogcontent"></div></div></div></div>').hide();
            break;
        default:
            dialog = $('<div id="' + options.id + '" class="dialog"><div class="win_note" style="width:' + options.width + ';overflow:hidden;">' + barHtml + '<div id="dialogcontent"></div></div></div>').hide();
            break;
    }
       
    $('body').append(dialog);


    /**
    * 重置对话框的位置。
    *
    * 主要是在需要居中的时候，每次加载完内容，都要重新定位
    *
    * @return void
    */
    var resetPos = function () {
        /* 是否需要居中定位，必需在已经知道了dialog元素大小的情况下，才能正确居中，也就是要先设置dialog的内容。 */
        if (options.center) {
            var left = ($(window).width() - options.width) / 2;
            var top = ($(window).height() - options.height) / 2;
            if (!isIe6 && options.fixed)
            { dialog.css({ top: top, left: left }); }
            else
            { dialog.css({ top: top + $(document).scrollTop(), left: left + $(document).scrollLeft() }); }
        }
    }

    /**
    * 初始化位置及一些事件函数。
    *
    * 其中的this表示Dialog对象而不是init函数。
    */

    var init = function () {
        /* 是否需要初始化背景遮罩层 */
        if (options.modal) {
            $('body').append('<div id="' + overlayId + '" class="dialog-overlay"></div>');
            $('#' + overlayId).css({ 'left': 0, 'top': 0, 'opacity': options.opacity,
                /*'width':$(document).width(),*/
                'width': '100%',
                /*'height':'100%',*/
                'height': $(document).height(),
                'z-index': ++DialogBox.__zindex,
                'position': 'absolute'
            })
                .hide();
        }

        dialog.css({ 'z-index': ++DialogBox.__zindex, 'position': options.fixed ? 'fixed' : 'absolute' });

        /*  IE6 兼容fixed代码 */
        if (isIe6 && options.fixed) {
            dialog.css('position', 'absolute');
            resetPos();
            var top = parseInt(dialog.css('top')) - $(document).scrollTop();
            var left = parseInt(dialog.css('left')) - $(document).scrollLeft();
            $(window).scroll(function () {
                dialog.css({ 'top': $(document).scrollTop() + top, 'left': $(document).scrollLeft() + left });
            });
        }

        /* 以下代码处理框体是否可以移动 */
        var mouse = { x: 0, y: 0 };
        var moveDialog = function (event) {
            var e = window.event || event;
            var top = parseInt(dialog.css('top')) + (e.clientY - mouse.y);
            var left = parseInt(dialog.css('left')) + (e.clientX - mouse.x);
            dialog.css({ top: top, left: left });
            mouse.x = e.clientX;
            mouse.y = e.clientY;
        };

        dialog.find('.bar').mousedown(function (event) {

            if (!options.draggable) { return; }

            var e = window.event || event;
            mouse.x = e.clientX;
            mouse.y = e.clientY;
            $(document).bind('mousemove', moveDialog);
        });
        $(document).mouseup(function (event) {
            $(document).unbind('mousemove', moveDialog);
        });

        /* 绑定一些相关事件。 */
        dialog.find('.close').bind('click', this.close);
        dialog.bind('mousedown', function () { dialog.css('z-index', ++DialogBox.__zindex); });

        // 自动关闭 
        if (0 != options.time) { timeId = setTimeout(this.close, options.time); }
    }


    /**
    * 设置对话框的内容。 
    *
    * @param string c 可以是HTML文本。
    * @return void
    */
    this.setContent = function (c) {
        var height = options.height - 20;
        var width = options.width - 20;
        var loadPanel = '<img id="dialogLoading" src="' + rootImagePath + 'loading.gif" />';
        var div = dialog.find('#dialogcontent');
        div.css("width", options.width);
        div.css("height", options.height);
        div.addClass("loadDialog");
        if (loadPanel != '') {
            div.html(loadPanel);
        }

        if ('object' == typeof (c)) {
            switch (c.type.toLowerCase()) {
                case 'id': // 将ID的内容复制过来，原来的还在。
                    div.html($('#' + c.value).html());
                    break;
                case 'img':
                    div.html('加载中...');
                    $('<img alt="" />').load(function () { div.empty().append($(this)); resetPos(); })
                    .attr('src', c.value);
                    break;
                case 'url':
                    $.ajax({ url: c.value,
                        success: function (html) {
                            div.removeClass("loadDialog");
                            div.css("height", "auto");
                            div.html(html);
                            resetPos();
                            if (undefined != options.loadFinish) {
                                options.loadFinish();
                            }
                        },
                        error: function (xml, textStatus, error) {
                            div.html('出错啦')
                        }
                    });
                    break;
                case 'iframe':
                    div.css("background", "white");
                    var iframeHtml = $('<iframe style="display:none" frameborder="0" width="' + options.width + '" height="' + options.height + '" scrolling="no" src="' + c.value + '" />');
                    div.append(iframeHtml);
                    var currentIF = iframeHtml[0];
                    if (currentIF.attachEvent) {
                        currentIF.attachEvent("onload", function () {
                            $("#dialogLoading").css("display", "none");
                            iframeHtml.css("display", "");

                        });
                    }
                    else {
                        currentIF.onload = function () {
                            $("#dialogLoading").css("display", "none");
                            iframeHtml.css("display", "");
                        };
                    }
                    break;
                case 'text':
                default:
                    div.html(c.value);
                    break;
            }
        }
        else
        { div.html(c); }
    }

    /**
    * 显示对话框
    */
    this.show = function () {
        if (undefined != options.beforeShow && !options.beforeShow())
        { return; }

        /**
        * 获得某一元素的透明度。IE从滤境中获得。
        *
        * @return float
        */
        var getOpacity = function (id) {
            if (!isIe)
            { return $('#' + id).css('opacity'); }

            var el = document.getElementById(id);
            return (undefined != el
                    && undefined != el.filters
                    && undefined != el.filters.alpha
                    && undefined != el.filters.alpha.opacity)
                ? el.filters.alpha.opacity / 100 : 1;
        }
        /* 是否显示背景遮罩层 */
        if (options.modal) {

            $('#' + overlayId).show();
            $('#' + overlayId).css({ 'opacity': getOpacity(overlayId) });
            $('#' + overlayId).fadeTo('slow', getOpacity(overlayId));
        }

        dialog.show(1, function () {
            if (undefined != options.afterShow) { options.afterShow(); }
            isShow = true;
        });
        dialog.css({ 'opacity': getOpacity(overlayId) });

        // 自动关闭 
        if (0 != options.time) { timeId = setTimeout(this.close, options.time); }

        resetPos();
    }


    /**
    * 隐藏对话框。但并不取消窗口内容。
    */
    this.hide = function () {
        if (!isShow) { return; }

        if (undefined != options.beforeHide && !options.beforeHide())
        { return; }

        dialog.hide(1, function () {
            if (undefined != options.afterHide) { options.afterHide(); }
        });
        if (options.modal)
        { $('#' + overlayId).hide('normal'); }

        isShow = false;
    }

    /**
    * 关闭对话框 
    *
    * @return void
    */
    this.close = function () {
        if (undefined != options.beforeClose && !options.beforeClose())
        { return; }

        dialog.hide(1, function () {
            $(this).remove();
            isShow = false;
            if (undefined != options.afterClose) { options.afterClose(); }
        });
        if (options.modal)
        { $('#' + overlayId).hide('normal', function () { $(this).remove(); }); }
        clearTimeout(timeId);
    }

    this.Confirm = function (callback) {
        dialog.find('.close,#btnDialogCancel').bind('click', this.close);
        var currentObj = this;
        dialog.find('#btnDialogOk').bind(
        'click',
        function () {
            currentObj.close();
            if (callback) { callback(); }
        }
       );
        this.show();


    }

    this.Alert = function () {
        dialog.find('.close,#btnDialogClose').bind('click', this.close);
        this.show();
    }

    init.call(this);
    this.setContent(content);

    DialogBox.__count++;
    DialogBox.__zindex++;
}
DialogBox.__zindex = 500;
DialogBox.__count = 1;
DialogBox.version = '1.0 beta';

function dialog(content, options) {
    var dlg = new DialogBox(content, options);
    dlg.show();
    return dlg;
}

