﻿/*
a dialog plugin based on jquery
lyan 2011-5-3
lyan 2011-12-19 new apperence
*/
/**
* @fileOverview 弹出窗口
* @author lyan
*/

/**
* @class $.fn.dialog  弹窗类
*/
(function ($) {
    $.fn.dialog = function (opts) {
        var dialog = false;
        if (this[0]) {
            dialog = new $.dialog(opts, this[0]);
        }
        return dialog;
    };

    $.dialog = function (opts, elem) {
        var top = window, doc, cover, ZIndex;
        var ie6 = ($.browser.msie && $.browser.version < 7) ? true : false;

        var iframeTpl = ie6 ? '<iframe hideFocus="true" frameborder="0" src="about:blank" class="dialog-plugin-ie6-frame"></iframe>' : '';

        var compat = function (doc) {
            d = doc || document;
            return d.compatMode == 'CSS1Compat' ? d.documentElement : d.body;
        };

        var getZIndex = function () {
            if (!ZIndex) {
                var dlgs = $(".dialog-plugin", doc);
                if (dlgs.length > 0) {
                    ZIndex = parseInt(dlgs.eq(dlgs.length - 1).css("zIndex"));
                }
                else {
                    ZIndex = 9999;
                }
            }
            return ++ZIndex;
        };

        var getEvent = function (w) {
            if ($.browser.msie) {
                try {
                    return window.event || top.event || w.event;
                } catch (e) { return null; }
            }

            var func = getEvent.caller;
            while (func != null) {
                var arg = func.arguments[0];
                if (arg && (arg + '').indexOf('Event') >= 0) {
                    return arg;
                }
                func = func.caller;
            }
            return null;
        };

        var getScrSize = function () {
            if ('pageXOffset' in top) {
                return {
                    x: top.pageXOffset || 0,
                    y: top.pageYOffset || 0
                };
            }
            else {
                var d = compat(doc);
                return {
                    x: d.scrollLeft || 0,
                    y: d.scrollTop || 0
                };
            }
        };

        var getDocSize = function () {
            var d = compat(doc);

            return {
                w: d.clientWidth || 0,
                h: d.clientHeight || 0
            };
        };

        var reSizeHdl = function () {
            var rel = compat(doc);
            $(cover).css({
                width: Math.max(rel.scrollWidth, rel.clientWidth || 0) + 'px',
                height: Math.max(rel.scrollHeight, rel.clientHeight || 0) + 'px'
            });
        };

        var genRndId = function () {
            var rndId = "";
            for (var i = 1; i <= 16; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                rndId += n;
            }
            return rndId;
        };

        // get the most top window
        while (top.parent && top.parent != top) {
            try {
                if (top.parent.document.domain != document.domain)
                    break;
            } catch (e) {
                break;
            }
            top = top.parent;
        }

        if (top.document.getElementsByTagName('frameset').length > 0) {
            top = window;
        }

        doc = top.document;


        var S = this, loadObj, inboxObj, xbtnObj, dragObj, btnBarObj, headBarObj, bodyObj, regWindow;
        var opt = S.opt = $.extend({
            title: '新窗口', // text show on title
            loadingText: '加载中...', // loading text
            skinName: null,
            cover: false, // is show mask
            btnBar: true, // is show buttons
            headBar: true, // is show head Bar
            width: 400, // the width of the window
            height: null, // auto height
            id: null,
            SetTopWindow: null, // set the target window the window will show
            link: false, // is outsite link
            page: null, // the link url
            html: null, // the text of html will append to body
            cancelBtn: { show: false, text: "取消", disabled: false }, // cancel button
            okayBtn: { show: true, text: "确定", disabled: false }, // cancel button
            onCancel: null, // when cancl click do
            onOkay: null,
            onLoad: null, // after onload do
            onClose: null, // when close click do
            fixed: false, // scroll with window srcoll?
            fullScreenShow: false, // this will hide the scroll(if has), this will only used when cover set to true.
            top: 'center',
            left: 'center',
            drag: true
        }, opts || {});

        if (!opt.id) {
            opt.id = genRndId();
        }

        if (opt.SetTopWindow) {
            top = opt.SetTopWindow;
            doc = top.document;
        }

        var SetFixed = function (elem) {
            var style = elem.style,
    			dd = compat(doc),
    			left = parseInt(style.left) - dd.scrollLeft,
    			top = parseInt(style.top) - dd.scrollTop;

            style.removeExpression('left');
            style.removeExpression('top');

            style.setExpression('left', 'this.ownerDocument.documentElement.scrollLeft' + left);
            style.setExpression('top', 'this.ownerDocument.documentElement.scrollTop + ' + top);
        },

    	SetIFramePage = function () {
    	    var innerDoc = '';
    	    var ifCss = '';
    	    if (opt.page) {
    	        innerDoc = '<iframe id="frm_' + opt.id + '" frameborder="0" src="' + opt.page + '" scrolling="auto" style="display:none;width:100%;height:100%;"><\/iframe>';
    	        ifCss = " dpIframe";
    	        if (!opt.height) {
    	            opt.height = 150; // default height of iframe
    	        }
    	    } else if (opt.html) {
    	        innerDoc = opt.html;
    	    }
    	    var innerHeightStyle = '';
    	    if (opt.height) {
    	        innerHeightStyle = 'style="height:' + opt.height + 'px;"';
    	    }

    	    var dlg = ['<div class="dialog-plugin' + ifCss + '" id="' + opt.id + '" style="width:' + opt.width + 'px;left:0;top:0;" >',
                           opt.headBar ? ['<div class="head" id="head_' + opt.id + '">',
                                '<span class="title" id="title_' + opt.id + '">' + opt.title + '</span>',
                                '<a class="close" id="close_' + opt.id + '"></a>',
                            '</div>'].join('') : '',
                            '<div class="body" id="body_' + opt.id + '">',
                                '<div class="inner" id="inner_' + opt.id + '"' + innerHeightStyle + '>' + innerDoc + '<div class="load" id="load_' + opt.id + '">' + opt.loadingText + '</div></div>',
                            '</div>',
                            opt.btnBar ? '<div class="foot" id="foot_' + opt.id + '"></div>' : '',
                        '</div>'
                      ].join('');
    	    return dlg;
    	},
        /**
        * @function
        * @description 显示遮罩
        */
    	ShowCover = function () {
    	    cover = $('#cover_' + opt.id, doc)[0];
    	    if (!cover) {
    	        var html = '<div id="cover_' + opt.id + '" style="position:absolute;top:0px;left:0px;background-color:#fff;">' + iframeTpl + '</div>';
    	        cover = $(html, doc).css('opacity', 0).appendTo(doc.body)[0];
    	    }
    	    reSizeHdl();
    	    $(cover).css({ display: '', zIndex: getZIndex() });
    	},
        /**
        * @function
        * @description 设置窗口位置
        * @param {Dialog} dg  弹出窗口
        * @param {String} tp 设置top位置
        * @param {String} lt 设置left位置
        * @param {Boolean} fix 是否固定位置显示
        */
    	iPos = function (dg, tp, lt, fix) {
    	    var cS = getDocSize(),
    		    sS = getScrSize(),
    			dW = dg.offsetWidth,
    			dH = dg.offsetHeight, x, y,
    			lx, rx, cx, ty, by, cy;

    	    if (fix) {
    	        lx = ie6 ? sS.x : 0;
    	        rx = ie6 ? cS.w + sS.x - dW : cS.w - dW;
    	        cx = ie6 ? (rx + sS.x - 20) / 2 : (rx - 20) / 2;

    	        ty = ie6 ? sS.y : 0;
    	        by = ie6 ? cS.h + sS.y - dH : cS.h - dH;
    	        cy = ie6 ? (by + sS.y - 20) / 2 : (by - 20) / 2;
    	    }
    	    else {
    	        lx = sS.x;
    	        cx = sS.x + (cS.w - dW - 20) / 2;
    	        rx = sS.x + cS.w - dW;

    	        ty = sS.y;
    	        cy = sS.y + (cS.h - dH - 20) / 2;
    	        by = sS.y + cS.h - dH;
    	    }

    	    switch (lt) {
    	        case 'center':
    	            x = cx;
    	            break;
    	        case 'left':
    	            x = lx;
    	            break;
    	        case 'right':
    	            x = rx;
    	            break;
    	        default:
    	            if (fix && ie6) {
    	                lt = lt + sS.x;
    	            }
    	            x = lt; break;
    	    }

    	    switch (tp) {
    	        case 'center':
    	            y = cy;
    	            break;
    	        case 'top':
    	            y = ty;
    	            break;
    	        case 'bottom':
    	            y = by;
    	            break;
    	        default:
    	            if (fix && ie6) {
    	                tp = tp + sS.y;
    	            }
    	            y = tp; break;
    	    }

    	    x = x < 0 ? 0 : x;
    	    y = y < 0 ? 0 : y;

    	    $(dg).css({ top: y + 'px', left: x + 'px' });

    	    if (fix && ie6) {
    	        SetFixed(dg);
    	    }
    	},
        /**
        * @function
        * @description 设置窗口
        * @param {Dialog} dg 弹出窗口
        */
    	SetDialog = function (dg) {
    	    S.topWin = top;
    	    S.topDoc = doc;

    	    S.curWin = window;
    	    S.curDoc = document;

    	    $(dg).bind('contextmenu', function (ev) {
    	        ev.preventDefault();
    	    }).bind('mousedown', S.SetIndex);

    	    if (opt.html && opt.html.nodeType)
    	        $(inboxObj).append(opt.html);

    	    regWindow = [window];

    	    if (top != window)
    	        regWindow.push(top);

    	    if (opt.page) {
    	        S.dgFrm = $('#frm_' + opt.id, doc)[0];

    	        if (!opt.link) {
    	            S.dlgWin = S.dgFrm.contentWindow;
    	            S.dgFrm.dlgFrm = S; // all the methods and attributes of S can be get from the new window
    	        }

    	        $(S.dgFrm).bind('load', function () {
    	            this.style.display = 'block';

    	            if (!opt.link) {
    	                var indw = $.browser.msie ?
    					    S.dlgWin.document : S.dlgWin;

    	                $(indw).bind('mousedown', S.SetIndex);

    	                regWindow.push(S.dlgWin);
    	                S.dlgDoc = S.dlgWin.document;
    	                $.isFunction(opt.onLoad) && opt.onLoad.call(S);
    	            }

    	            loadObj.style.display = 'none';
    	        });
    	    }
    	    else {
    	        S.dlgDoc = doc;
    	    }

    	    $(xbtnObj).bind('click', opt.onClose);

    	},
    	initDrag = function (elem) {
    	    var lacoor, maxX, maxY, curpos, regw = regWindow, cS, sS;

    	    function moveHandler(ev) {
    	        var curcoor = { x: ev.screenX, y: ev.screenY };
    	        curpos =
    		    {
    		        x: curpos.x + (curcoor.x - lacoor.x),
    		        y: curpos.y + (curcoor.y - lacoor.y)
    		    };
    	        lacoor = curcoor;

    	        if (curpos.x < sS.x) curpos.x = sS.x;
    	        if (curpos.y < sS.y) curpos.y = sS.y;
    	        if (curpos.x > maxX) curpos.x = maxX;
    	        if (curpos.y > maxY) curpos.y = maxY;


    	        S.dg.style.top = opt.fixed && !ie6 ? curpos.y - sS.y + 'px' : curpos.y + 'px';
    	        S.dg.style.left = opt.fixed && !ie6 ? curpos.x - sS.x + 'px' : curpos.x + 'px';
    	    };

    	    function upHandler(ev) {
    	        for (var i = 0, l = regw.length; i < l; i++) {
    	            $(regw[i].document).unbind('mousemove', moveHandler);
    	            $(regw[i].document).unbind('mouseup', upHandler);
    	        }

    	        lacoor = null; elem = null;

    	        if (opt.fixed && ie6) SetFixed(S.dg);
    	        if ($.browser.msie) S.dg.releaseCapture();
    	    };

    	    $(elem).bind('mousedown', function (ev) {
    	        if (ev.target.id === 'close_' + S.opt.id) return;

    	        cS = getDocSize();
    	        sS = getScrSize();

    	        var lt = S.dg.offsetLeft,
    			    tp = S.dg.offsetTop,
    			    dW = S.dg.clientWidth,
    			    dH = S.dg.clientHeight;

    	        curpos = opt.fixed && !ie6 ?
    			    { x: lt + sS.x, y: tp + sS.y} : { x: lt, y: tp };

    	        lacoor = { x: ev.screenX, y: ev.screenY };

    	        maxX = cS.w + sS.x - dW;
    	        maxY = cS.h + sS.y - dH;

    	        S.dg.style.zIndex = parseInt(ZIndex, 10) + 1;

    	        for (var i = 0, l = regw.length; i < l; i++) {
    	            $(regw[i].document).bind('mousemove', moveHandler);
    	            $(regw[i].document).bind('mouseup', upHandler);
    	        }

    	        ev.preventDefault();

    	        if ($.browser.msie) S.dg.setCapture();
    	    });
    	},

    	initSize = function (elem) {
    	    var lacoor, dH, dW, curpos, regw = regWindow, dialog, cS, sS;

    	    function moveHandler(ev) {
    	        var curcoor = { x: ev.screenX, y: ev.screenY };
    	        dialog = {
    	            w: curcoor.x - lacoor.x,
    	            h: curcoor.y - lacoor.y
    	        };

    	        if (dialog.w < 200) dialog.w = 200;
    	        if (dialog.h < 100) dialog.h = 100;

    	        S.dg.style.top = opt.fixed ? curpos.y - sS.y + 'px' : curpos.y + 'px';
    	        S.dg.style.left = opt.fixed ? curpos.x - sS.x + 'px' : curpos.x + 'px';
    	    };

    	    function upHandler(ev) {
    	        for (var i = 0, l = regw.length; i < l; i++) {
    	            $(regw[i].document).unbind('mousemove', moveHandler);
    	            $(regw[i].document).unbind('mouseup', upHandler);
    	        }

    	        lacoor = null; elem = null;

    	        if ($.browser.msie) S.dg.releaseCapture();
    	    };

    	    $(elem).bind('mousedown', function (ev) {
    	        dW = S.dg.clientWidth;
    	        dH = S.dg.clientHeight;

    	        dialog = { w: dW, h: dH };

    	        cS = getDocSize();
    	        sS = getScrSize();

    	        var lt = S.dg.offsetLeft,
    			    tp = S.dg.offsetTop;

    	        curpos = opt.fixed ?
    			    { x: lt + sS.x, y: tp + sS.y} : { x: lt, y: tp };

    	        lacoor = { x: ev.screenX - dW, y: ev.screenY - dH };

    	        S.dg.style.zIndex = parseInt(ZIndex, 10) + 1;

    	        for (var i = 0, l = regw.length; i < l; i++) {
    	            $(regw[i].document).bind('mousemove', moveHandler);
    	            $(regw[i].document).bind('mouseup', upHandler);
    	        }

    	        ev.preventDefault();

    	        if ($.browser.msie) S.dg.setCapture();
    	    });
    	},

    	removeDG = function () {
    	    if (S.dgFrm) {
    	        if (!opt.link) {
    	            $(S.dgFrm).unbind('load');
    	        }
    	        S.dgFrm.src = 'about:blank';
    	        S.dgFrm = null;
    	    }
    	    regWindow = [];
    	    $(S.dg).remove();

    	    S.dg = null;
    	    loadObj = inboxObj = xbtnObj = dragObj = btnBarObj = headBarObj = bodyObj = null;
    	};

        S.ShowDialog = function () {
            if ($('#' + opt.id, doc)[0])
                return S;

            if (opt.cover) {
                ShowCover();
            }

            var fixpos = opt.fixed && !ie6 ? 'fixed' : 'absolute', html = SetIFramePage();

            S.dg = $(html, doc).css({
                position: fixpos, zIndex: getZIndex()
            }).appendTo($("body", doc))[0];
            if (opt.link) {
                var innwin = $("#frm_" + opt.id, doc)[0].contentWindow;
                innwin.focus();
            }

            loadObj = $('#load_' + opt.id, doc)[0];
            inboxObj = $('#inner_' + opt.id, doc)[0];
            xbtnObj = $('#close_' + opt.id, doc)[0];
            dragObj = $('#head_' + opt.id, doc)[0];

            btnBarObj = $('#foot_' + opt.id, doc)[0];
            headBarObj = $('#head_' + opt.id, doc)[0];

            bodyObj = $('#body_' + opt.id, doc)[0];

            iPos(S.dg, opt.top, opt.left, opt.fixed);
            SetDialog(S.dg);

            if (opt.drag) {
                initDrag(dragObj);
            }




            if (opt.html && $.isFunction(opt.onLoad)) {
                opt.onLoad.call(S);
            }

            if (!opt.page) {
                loadObj.style.display = 'none'; // colse loading of not a page
            }

            if (opt.btnBar && opt.okayBtn.show) {
                S.addBtn('okay', opt.okayBtn.text, opt.onOkay);
                if (opt.okayBtn.disabled) {
                    $('#btn_' + opt.id + '_okay', doc).addClass("disabled");
                }
            }
            if (opt.btnBar && opt.cancelBtn.show) {
                S.addBtn('cancel', opt.cancelBtn.text, opt.onCancel);
                if (opt.cancelBtn.disabled) {
                    $('#btn_' + opt.id + '_cancel', doc).addClass("disabled");
                }
            }
        };

        S.addBtn = function (id, txt, fn) {
            if (opt.btnBar) {
                if ($('#btn_' + opt.id + '_' + id, doc)[0]) {
                    $('#btn_' + opt.id + '_' + id, doc).html(txt).click(fn);
                }
                else {
                    var btn = '<a class="btn bigger" href="javascript:;" id="btn_' + opt.id + '_' + id + '" onclick="return false;">' + txt + '</a>';
                    $('#foot_' + opt.id, doc).append(btn);
                    $("#" + "btn_" + opt.id + "_" + id, doc).click(function () {
                        if (!$(this).hasClass("disabled")) {
                            fn.call(this);
                        }
                    });
                }
            }
        };

        S.getOkayBtn = function () {
            var btn = $('#btn_' + opt.id + '_okay', doc);
            return btn;
        };

        S.removeBtn = function (id) {
            if ($('#btn_' + opt.id + '_' + id, doc)[0])
                $('#btn_' + opt.id + '_' + id, doc).remove();
        };

        S.SetIndex = function () {
            S.dg.style.zIndex = parseInt(ZIndex, 10) + 1;
            ZIndex = parseInt(S.dg.style.zIndex, 10);

            var ev = getEvent(S.dlgWin);

            ev.stopPropagation ? ev.stopPropagation() : (ev.cancelBubble = true);
        };

        S.cancel = function () {
            removeDG();

            if (cover) {

                $('#cover_' + opt.id, doc).remove();
                cover = null;
            }
            var ev = getEvent(S.dlgWin);

            if (!ev) return;

            ev.preventDefault ? ev.preventDefault() : (ev.returnValue = false);
        };

        S.cleanDialog = function () {
            if (S.dg) {
                removeDG();
            }
            if (cover) {
                $(cover).remove();
                cover = null;
            }
        };

        opt.onCancel = opt.onCancel || S.cancel;
        opt.onOkay = opt.onOkay || S.cancel;
        opt.onClose = opt.onClose || S.cancel;

        if (elem) {
            $(elem).bind('click', S.ShowDialog);
        }

        $(window).bind('unload', S.cleanDialog);
    };

})(jQuery);

// alert and comfirm easy use
var ShowMsgTip = function (options) {
    var settings = $.extend({
        width: 300,
        cover: true,
        title: "Message",
        tip: "tips",
        icon: "diInfo" // supported icons: diInfo,diWarning,diQuestion,diError,diOK,redInfo
    }, options);

    var html = ['<table class="layout"><tbody><tr>',
                '<th><div class="dlgIco ' + settings.icon + '"></div></th>',
                '<td>', settings.tip, '</td>',
                '</tr></tbody></table>'].join('');
    settings.html = html;
    var dg = new $.dialog(settings);
    dg.ShowDialog();
    return dg;
};

var ShowSelectUtil = function (options) {
    var settings = $.extend({
        width: 300,
        height: 160,
        cancelBtn: { show: true, text: "cancel", disabled: false },
        okayBtn: { show: true, text: "OK", disabled: true },
        cover: true,
        title: "Select",
        page: "/pages/util/PersonInCharge.aspx"
    }, options);
    switch (settings.util) {
        case "person":
            settings.page = "/pages/util/PersonInCharge.aspx";
            break;
        case "folder":
            settings.page = "/pages/util/MessageFolder.aspx";
            break;
        case "orderg":
            settings.page = "/pages/util/NameGroup.aspx?q=order";
            break;
        case "productg":
            settings.page = "/pages/util/NameGroup.aspx?q=product";
            break;
    }
    var dg = new $.dialog(settings);
    dg.ShowDialog();
    return dg;
};

var ContactForAssistant = function (options) {
    var settings = $.extend({
        width: 600,
        height: 450,
        cover: true,
        title: 'window',
        page: '/Pages/ContactUsIframe.aspx',
        btnBar: false
    }, options);
    var dg = new $.dialog(settings);
    dg.ShowDialog();
    return dg;
};
