(function ($) {
    // 鼠标滚轮扩展插件
    $.event.special.mousewheel = {
        setup: function () {
            var handler = $.event.special.mousewheel.handler;

            // Fix pageX, pageY, clientX and clientY for mozilla
            if ($.browser.mozilla)
                $(this).bind('mousemove.mousewheel', function (event) {
                    $.data(this, 'mwcursorposdata', {
                        pageX: event.pageX,
                        pageY: event.pageY,
                        clientX: event.clientX,
                        clientY: event.clientY
                    });
                });

            if (this.addEventListener)
                this.addEventListener(($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
            else
                this.onmousewheel = handler;
        },

        teardown: function () {
            var handler = $.event.special.mousewheel.handler;

            $(this).unbind('mousemove.mousewheel');

            if (this.removeEventListener)
                this.removeEventListener(($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
            else
                this.onmousewheel = function () { };

            $.removeData(this, 'mwcursorposdata');
        },

        handler: function (event) {
            var args = Array.prototype.slice.call(arguments, 1);

            event = $.event.fix(event || window.event);
            // Get correct pageX, pageY, clientX and clientY for mozilla
            $.extend(event, $.data(this, 'mwcursorposdata') || {});
            var delta = 0, returnValue = true;

            if (event.wheelDelta) delta = event.wheelDelta / 120;
            if (event.detail) delta = -event.detail / 3;
            if ($.browser.opera) delta = -event.wheelDelta;

            event.data = event.data || {};
            event.type = "mousewheel";

            // Add delta to the front of the arguments
            args.unshift(delta);
            // Add event to the front of the arguments
            args.unshift(event);

            return $.event.handle.apply(this, args);
        }
    };

    $.fn.extend({
        mousewheel: function (fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function (fn) {
            return this.unbind("mousewheel", fn);
        }
    });
})(jQuery);
var cImg = null;
var psouId = '';
var p = '';
var pid = '';
var point = {
    x: 0,
    y: 0
};

function rDivClick(e) {
    pid = $(e).attr('id');    
    return false;
}

function rImgClick(e) {
    p = $(e).attr('src');
	cImg = $("<div>"+$(e)[0].outerHTML+"</div>");
    return false;
}

function ContextMenu() {

    var pStr = '';
    if (p != "") {
        pStr += "<Item k='img' v='" + p + "'/>";
    }else{
		cImg = null;
	}

    if (pid != "") {
        pStr += "<Item k='div' v='" + pid + "'/>";
    }

    var rangeStr = document.selection.createRange().htmlText;
    var isSelect = false;
    if (rangeStr.length > 0) {
        isSelect = true;
    }
//alert("t="+pStr);
    window.external.RightClickMenu(pStr, isSelect, point.x, point.y);
    p = "";
    pid = "";

    return false;
}

(function ($) {
    $.extend({
        createScrollBar: function (settings) {
            var scrollBar = $.extend({
                scrollBlock: null,   //  滚动块
                scrollRange: null,   //  滚动条
                scrollPage: null,    //  滚动的内容页面
                parentMain: null,    //  滚动内容页面的父节点
                goToBottomBtn: null, //  到底按钮
                onScrollToTop: function () { }, //  滚动到顶部时触发
                onScrollNotTop: function () { },
                onScrollInit: function () { }
            }, settings);

            //  滚动条
            var rangeTop, rangeHeight, blockHeight, maxY, currentBlockTop, dragPostion, isScrollShow = false;
            //  内容
            var pageViewHeight, contentHeight, currentContentTop;
            //  鼠标滚动
            var mouseWheelMultiplier;

            // 记得上次改变滚动条的数据，以减少操作dom的次数
            var lastParWidth, lastParHeight;

            //            scrollBar.scrollPage.css({ 'top': '0' }); //初始位置
            //            scrollBar.scrollBlock.css({ 'margin-top': '0' }); //初始位置
            //            scrollBar.goToBottomBtn.bind("click",function(){
            //                positionDrag(maxY);
            //            });

            function initScrollbar(bolStain) {// 参数:是否要保持原始的位置，一些初始化之后会直接定位滚动条位置传false

                pageViewHeight = scrollBar.parentMain.height();
                var parWidth = scrollBar.parentMain.width();

                if (lastParWidth != parWidth)  //  窗口改变了宽度
                {
                    scrollBar.scrollPage.width(parWidth);
                }
                var pageHeight = scrollBar.scrollPage.outerHeight();
                contentHeight = pageHeight - pageViewHeight;// + 12;

                if (contentHeight <= 0) {
                    scrollBar.scrollBlock.unbind("mousedown");
                    scrollBar.scrollRange.unbind('mousedown');
                    scrollBar.parentMain.unbind('mousewheel');
                    $("html").unbind('keydown');
                    $("html").unbind('mousemove');
                    scrollBar.scrollRange.hide();
                    scrollBar.goToBottomBtn.hide();
                    isScrollShow = false;
                    scrollBar.isShow = false;

                    scrollBar.scrollPage.css({ 'top': '0' }); //初始位置
                    scrollBar.scrollBlock.css({ 'margin-top': '0' }); //初始位置
                }
                else {
                    if (isScrollShow === false) {
                        scrollBar.scrollRange.show();
                        isScrollShow = true;
                        scrollBar.isShow = true;

                        scrollBar.scrollPage.width(parWidth - scrollBar.scrollRange.width());

                        pageHeight = scrollBar.scrollPage.outerHeight();
                        contentHeight = pageHeight - pageViewHeight;

                        scrollBar.scrollBlock.unbind("mousedown").bind("mousedown", onStartDrag);
                        scrollBar.scrollRange.unbind('mousedown').bind('mousedown', onTrackClick);
                        scrollBar.parentMain.unbind('mousewheel').bind('mousewheel', onMouseWheel);
                        $("html").unbind('keydown').bind('keydown', onHtmlKeyDown);
                        $("html").unbind('mousemove').bind('mousemove', onHtmlMouseMove);
                    }
                    //scrollBar.goToBottomBtn.hide();

                    //  滚动条

                    // 比例
                    var toppercent = currentBlockTop / maxY;
                    if (!toppercent && toppercent != 0) {
                        toppercent = 1;
                    }

                    if (lastParHeight != pageViewHeight || !rangeTop)  // 如果高度改变或者rangeTop还没赋值
                    {
                        rangeTop = scrollBar.scrollRange.offset().top;
                        rangeHeight = scrollBar.scrollRange.outerHeight();
                    }

                    if (!blockHeight || blockHeight > 50)  // 滚动条长度大于50时才调整滚动块的长度
                    {
                        blockHeight = Math.floor(rangeHeight * pageViewHeight / pageHeight);
                        if (blockHeight < 50) {
                            blockHeight = 50;
                        }
                        scrollBar.scrollBlock.children("em.c").height(blockHeight - 10);
                        // scrollBar.scrollBlock.children("em.c").height(blockHeight-scrollBar.scrollBlock.children("em.t").height()-scrollBar.scrollBlock.children("em.b").height());
                        // mouseWheelMultiplier = 36 * maxY / contentHeight;
                        mouseWheelMultiplier = blockHeight / 10;
                    }

                    maxY = rangeHeight - blockHeight;
                    dragPostion = 0;

                    if (bolStain) {
                        currentBlockTop = toppercent * maxY;
                        if (currentBlockTop > maxY) {
                            currentBlockTop = maxY;
                        }
                        currentContentTop = contentHeight * currentBlockTop / maxY;
                        scrollBar.scrollPage.css("top", -1 * currentContentTop + "px");
                        scrollBar.scrollBlock.css("margin-top", currentBlockTop + "px");
                    }

                }
                lastParWidth = parWidth;
                lastParHeight = pageViewHeight;
                scrollBar.onScrollInit();
            }

            var ignoreNativeDrag = function () { return false; };

            // 页面全选拖动内容
            var onHtmlMouseMove = function (e) {

                var winH = $(window).height();

                if (e.button == 1) {   //  如果左键是按下的
                    var delData = 0;
                    if (e.clientY > winH) {
                        delData = -1;
                    } else if (e.clientY < 0) {
                        delData = 1;
                    }
                    if (delData != 0) {
                        onMouseWheel(e, delData);
                    }
                }
            }

            // 键盘下箭头控制滚动条
            var onHtmlKeyDown = function (e) {

                var delta = 0;
                if (e.keyCode == 38) {  //up
                    delta = 1;

                } else if (e.keyCode == 40) {  // down
                    delta = -1;
                }
                if (delta != 0) {
                    return onMouseWheel(e, delta);
                }
                return true;
            }

            // 开始拖动滚动块的事件
            var onStartDrag = function (event) {

                dragPostion = event.pageY - scrollBar.scrollBlock.offset().top;
                $(document.documentElement).bind('mouseup', onStopDrag).bind('mousemove', updateScroll).bind("losecapture", onStopDrag);
                $(window).bind("blur", onStopDrag);
                scrollBar.scrollBlock[0].setCapture();
                event.stopPropagation();
                event.preventDefault();

            };

            var onStopDrag = function (event) {
                $(document.documentElement).unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll).unbind("losecapture");
                $(window).unbind("blur", onStopDrag);
                scrollBar.scrollBlock[0].releaseCapture();
            };


            // 拖动滚动块ing的事件（处理滚动条和显示内容的比例）
            var positionDrag = function (destY) {
                var isEnd = false; var isTop = false;
                currentBlockTop = destY < 0 ? 0 : destY;

                if (currentBlockTop >= maxY) {
                    currentBlockTop = maxY;
                    isEnd = true;
                } else if (currentBlockTop == 0) {
                    isTop = true;
                }
                if (destY == 33.5) {
                    isTop = true;
                }
                scrollBar.scrollBlock.css("margin-top", currentBlockTop + "px");

                currentContentTop = currentBlockTop * (contentHeight / maxY);
                scrollBar.scrollPage.css("top", -1 * currentContentTop + "px");

                //                if (isEnd) {
                //                    scrollBar.goToBottomBtn.hide();
                //                    
                //                }else{
                //                    scrollBar.goToBottomBtn.show();
                //                    
                //                }

                if (isTop) {
                    scrollBar.onScrollToTop();
                } else {
                    scrollBar.onScrollNotTop();
                }

            };
            var updateScroll = function (e) {
                if (e.which === 1 && e.shiftKey == false) {
                    positionDrag(e.pageY - rangeTop - dragPostion);
                } else {
                    onStopDrag();
                }
                e.preventDefault();
                e.stopPropagation();

            };

            //// 滚动区域的单击事件
            var trackScrollInterval;
            var trackScrollInc;
            var trackScrollMousePos;

            var doTrackScroll = function () {
                // if (trackScrollInc > 2 || trackScrollInc % 2 == 0) {
                positionDrag((currentBlockTop - ((currentBlockTop - trackScrollMousePos) / 2)));
                // }
                trackScrollInc++;
            };

            var onStopTrackClick = function () {
                clearInterval(trackScrollInterval);
                $('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
            };

            var onTrackMouseMove = function (event) {
                trackScrollMousePos = event.pageY - rangeTop - blockHeight / 2;
            };

            var onTrackClick = function (event) {
                onTrackMouseMove(event);
                trackScrollInc = 0;
                $('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
                trackScrollInterval = setInterval(doTrackScroll, 100);
                doTrackScroll();
            };

            var onMouseWheel = function (event, delta) {

                var d = currentBlockTop;
                positionDrag(currentBlockTop - delta * mouseWheelMultiplier);
                var dragOccured = d != currentBlockTop;
                return !dragOccured;
            }

            // 对外提供的方法，置顶之前必须重新初始化
            scrollBar.resetScrollToTop = function () {

                initScrollbar(false);

                if (isScrollShow) {
                    positionDrag(0);
                }
            }
            // 对外提供的方法，置底之前必须重新初始化，因为可以是追加了一条消息，这时滚动条长短等各种状态都要重新计算
            scrollBar.resetScrollToBottom = function () {

                initScrollbar(false);

                if (isScrollShow) {
                    positionDrag(maxY);
                }
            }

            scrollBar.resetScrollPostion = function () {
                initScrollbar(true);
            }

            //  加载历史记录之后，保持当前窗口内容
            scrollBar.resetScrollPreserve = function (addHeight) {

                initScrollbar(false);

                if (isScrollShow) {
                    positionDrag(((contentHeight - addHeight) * currentBlockTop / maxY + addHeight) * maxY / contentHeight);
                }

            }

            initScrollbar();

            return scrollBar;
        },

        anim_progressbar: function (aOptions) {
            // def values
            var iCms = 1000;
            var iMms = 60 * iCms;
            var iHms = 3600 * iCms;
            var iDms = 24 * 3600 * iCms;

            // def options
            var aDefOpts = {
                start: new Date(), // now
                finish: new Date().setTime(new Date().getTime() + 60 * iCms), // now + 60 sec
                interval: 100,
                bar: null
            }
            var aOpts = jQuery.extend(aDefOpts, aOptions);
            var vPb = $("div[id='" + aOpts.bar + "']");

            // each progress bar
            return $("div[id='" + aOpts.bar + "']").each(
            function () {
                var iDuration = aOpts.finish - aOpts.start;

                // calling original progressbarde
                vPb.children('.pbar').progressbar();

                // looping process
                var vInterval = setInterval(
                    function () {

                        if (vPb.children('.pbar').children().length == 0) {
                            clearInterval(vInterval);
                        }

                        var iLeftMs = aOpts.finish - new Date(); // left time in MS
                        var iElapsedMs = new Date() - aOpts.start, // elapsed time in MS
                            iDays = parseInt(iLeftMs / iDms), // elapsed days
                            iHours = parseInt((iLeftMs - (iDays * iDms)) / iHms), // elapsed hours
                            iMin = parseInt((iLeftMs - (iDays * iDms) - (iHours * iHms)) / iMms), // elapsed minutes
                            iSec = parseInt((iLeftMs - (iDays * iDms) - (iMin * iMms) - (iHours * iHms)) / iCms), // elapsed seconds
                            iPerc = (iElapsedMs > 0) ? iElapsedMs / iDuration * 100 : 0; // percentages                                                    

                        // display current positions and progress
                        vPb.children('.percent').html('<b>' + iPerc.toFixed(1) + '%</b>');
                        vPb.children('.elapsed').html(iDays + ' days ' + iHours + 'h:' + iMin + 'm:' + iSec + 's</b>');
                        vPb.children('.pbar').children('.ui-progressbar-value').css('width', iPerc + '%');

                        // in case of Finish
                        if (iPerc >= 100) {

                            clearInterval(vInterval);
                            vPb.children('.pbar').children('.ui-progressbar-value').css('width', 0 + '%');
                            vPb.parent().find('INPUT').removeClass().addClass('ready_btn_0');
                            //                            vPb.children('.percent').html('<b>0%</b>');
                            //                            vPb.children('.elapsed').html('Finished');
                        }
                    }, aOpts.interval
                );


            }
        );
        }
    });
})(jQuery);

(function($) {

    function Base64() {

        // private property   
        _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding   
        this.encode = function(input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
			   _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
			   _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }

        // public method for decoding   
        this.decode = function(input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }

        // private method for UTF-8 encoding   
        _utf8_encode = function(string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        }

        // private method for UTF-8 decoding   
        _utf8_decode = function(utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }

    var base64Coder = new Base64();

    // 缩略图片最小宽度，小于此宽度的图片不缩略
    var minWinWidth = 300;
    var minGroupWidth = 300;

    // 输出内容和其外部table差值
    var tableOffset = 18;
    // 外框宽度和图片实际宽度的差值
    var imgOffset = 18;
    var groupImgOffset = 18;
    // 放大镜高度
    var magHeight = 24;
    // 缩略图最大宽度和高度
    var maxImgWidth = 100;
    var maxImgHeight = 50;

    // 全局变量，拖到上方是否显示历史按钮
    var isShowHistory = false;
    //  是否历史记录加载中
    var isHisLoading = false;

    //  是否第一次追加历史记录时
    var isFirstAppHis = true;

    // 背景设置
    var prevSrc, prevPosX, prevPosY;
    var bgPositionType = "left";
    var bgposOffsetX = "0";
    var bgposOffsetY = "0";


    var chatInfo = $(".fx_webagent_d_mes");

    var mainPage = $(".main_page");
    var isBubble = false;
    // 气泡id
    var bubId = '';

    var lastWinWidth = $(window).width();
    var lastWinHeight = $(window).height();

    mainPage.height(lastWinHeight);

    var lastInfoWidth = chatInfo.width();
    var lastInfoHeight = chatInfo.height();

    var scrollBar = $(".scrollbar");

    var histroyBtn = $(".load_oldmsg2");
    var bottomBtn = $(".load_newmsg");

    // 默认不显示
    histroyBtn.hide();
    var histroyBtnSrc = 0;

    // 匹配只有换行的消息
    var regBr = /<font[^>]+><br>+<\/font>|<br>+/i;
    // 匹配只有空格的信息，此空格就指空白格，不是&nbsp;
    var regBk = /(^\s*$)|<font[^>]+>\s*<\/font>/i;

    var boxID = function(n) {
        var Str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0, r = ""; i < n; i++) {
            r += Str.charAt(Math.floor(Math.random() * 62));
        };
        return r;
    };

    String.prototype.Trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }

    // 对于只有换行的消息，在第一个换行之前加个&nbsp;和对于只有空格的信息替换成&nbsp;
    function replaceBr(msg) {
        if (regBr.test(msg)) {
            var brIndex = msg.indexOf("<br>");
            return msg.substring(0, brIndex) + "&nbsp;" + msg.substring(brIndex);
        } else if (regBk.test(msg)) {
            return msg.replace(regBk, "&nbsp;");
        } else {
            return msg;
        }
    }

    function ResetRightAlignBkg(curWidth, curHeight) {
        if (bgPositionType == "right") {
            xpos = curWidth - 675 + parseInt(bgposOffsetX);
            //ypos = bgposOffsetY;
            //alert(curWidth + "   " + bgposOffsetX + "   " + xpos.toString());
            mainPage.css({ "background-position-x": xpos.toString() + "px", "background-position-y": -bgposOffsetY + "px" });
        }
    }

    var jScrollBar = $.createScrollBar({
        scrollBlock: $(".scrollbar span"),   //  滚动块
        scrollRange: scrollBar,   //  滚动条
        scrollPage: chatInfo,    //  滚动的内容页面
        parentMain: mainPage,    //  内容的包括元素
        goToBottomBtn: bottomBtn, //  到底按钮
        //  滚动到顶部时触发
        onScrollToTop: function() {

            if (isShowHistory) {
                if (histroyBtnSrc == 0) {
                    histroyBtnSrc = 1;
                    histroyBtn.find("a").css({ "background-image": "url(img/old_msg_loading.gif)" });
                    // histroyBtn.find("a").text('');
                }

                histroyBtn.show();

                if (isHisLoading === false) {
                    isHisLoading = true;
                    //然后去加载20条消息，应产品需求，延迟300毫秒钟发起请求
                    //setTimeout(function(){histroyBtn.hide();},1500);
                    fxInter.getLastMsgRecord(20);
                }

            }

        },

        onScrollNotTop: function() {
            histroyBtn.hide();
        },

        onScrollInit: function() {
            lastInfoWidth = chatInfo.width();
            lastInfoHeight = chatInfo.height();
        }

    });

    $(window).bind("resize", function() {

        var curWinWidth = $(this).width();
        var curWinHeight = $(this).height();
        if (curWinWidth != lastWinWidth || curWinHeight != lastWinHeight) {

            ResetRightAlignBkg(curWinWidth, curWinHeight);
            mainPage.height(curWinHeight);
            jScrollBar.resetScrollPostion();

            fBrowserHelper.showHistroyBtn(isShowHistory, true);

            lastWinWidth = curWinWidth;
            lastWinHeight = curWinHeight;
        }

    });

    chatInfo.bind("resize", function() {

        var curInfoWidth = $(this).width();
        var curInfoHeight = $(this).height();

        if (curInfoWidth != lastInfoWidth || curInfoHeight != lastInfoHeight) {
            jScrollBar.resetScrollPostion();

            //fBrowserHelper.showHistroyBtn(isShowHistory,true);
        }
    });

    //  内容私用的帮助方法集合
    var fBrowserHelper = {

        //  组织2人会话的html
        buildChatHtml: function(msg, time, nickName, isLeft, isSms) {

            var strMsg = '<div class="chat_box selfbuddy ' + (isLeft == 1 ? "buddy_msg" : "my_msg") + '">';

            strMsg += '<div class="msg_hd" isRight=' + (isLeft == 1 ? "0" : "1") + '><span class="name">' + nickName;
            strMsg += '</span><span class="date">' + time + '</span>';
            if (isSms == 1) {
                strMsg += '<span class="name"><label class="icon"></label></span>';
            }
            else if (isSms == 4) {
            strMsg += '<span class="name"><label class="schedulesmsicon"></label></span>';
            }
            strMsg += '</div><div id=' + boxID(15) + ' class="msg_bd"  ><div class="dot"></div><table class="logtable" oncontextmenu="javascript:rDivClick(this.parentNode)"><tr><td class="tl"></td><td class="tc"></td><td class="tr"></td></tr>';

            strMsg += '<tr><td class="cl"></td>';
            if (isSms == 3) {
                strMsg += msg;
            } else {
                strMsg += '<td class="cc"><p class="pChatContent">' + replaceBr(msg) + '</p></td>';
            }
            strMsg += '<td class="cr"></td></tr><tr><td class="bl"></td><td class="bc"></td><td class="br"></td></tr></table></div></div><div class="clear"></div>';
            return strMsg;

        },

        buildGroupHtml: function(msg, time, nickName, portrait, isLeft, isSms) {

            var strMsg = '<div class="chat_box selfbuddy ' + (isLeft == 1 ? "buddy_msg" : "my_msg") + '">';

            strMsg += '<div class="msg_hd" isRight=' + (isLeft == 1 ? "0" : "1") + '><span class="name">' + nickName;
            strMsg += '</span><span class="date">' + time + '</span>';
            if (isSms == 1) {
                strMsg += '<span class="name"><label class="icon"></label></span>';
            }
            else if (isSms == 4) {
                strMsg += '<span class="name"><label class="schedulesmsicon"></label></span>';
            }
            strMsg += '</div><div id=' + boxID(15) + ' class="msg_bd"  ><div class="dot"></div><table class="logtable" oncontextmenu="javascript:rDivClick(this.parentNode)"><tr><td class="tl"></td><td class="tc"></td><td class="tr"></td></tr>';

            strMsg += '<tr><td class="cl"></td>';
            if (isSms == 3) {
                strMsg += msg;
            } else {
                strMsg += '<td class="cc"><p class="pChatContent">' + replaceBr(msg) + '</p></td>';
            }
            strMsg += '<td class="cr"></td></tr><tr><td class="bl"></td><td class="bc"></td><td class="br"></td></tr></table></div></div><div class="clear"></div>';
            return strMsg;

        },

        //  updateImage(id,src)
        //  测试字符串函数能调用不

        //  对聊天内容里需要特殊处理的元素进行处理，如图片、链接等
        handleImgs: function(logMsgBox, minWidth) {

            var imgss = logMsgBox.find("img");

            if (imgss.length > 1) {
                //  处理多张图片没有间隙的，添加空格
                imgss.not(":last").after("<span class='spanSpace'>&nbsp; &nbsp;</span>");
            }


            var appImgs = imgss.filter(".orgimg");

            if (appImgs && appImgs.length > 0) {

                appImgs.each(function() {

                    var curImg = $(this);

                    var maxWidth = parseInt(curImg.css("max-width"));
                    var maxHeight = parseInt(curImg.css("max-height"));

                    curImg.unbind().bind("dblclick", function() {

                        fetionInter.OpenPicture(curImg.attr("src"));

                    });

                    if (maxWidth <= minWidth) {
                        curImg.width(maxWidth).height(maxHeight);
                    } else {
                        // 如果图片大小比最小对话框所允许的最大图片大即有可能产生缩放，就在图片后追加一个放大镜图片

                        var magnifier = $('<img class="magnifier" src="img/Magnifier_Normal.png" />');

                        magnifier.unbind().bind("mouseover", function() {

                            var pecent = curImg.width() / maxWidth;

                            $(this).attr("title", "缩放比例：" + Math.floor(pecent * 100) + "%");

                        }).bind("click", function() {
                            fetionInter.OpenPicture(curImg.attr("src"));
                        });

                        curImg.after(magnifier);
                    }

                });
            }
        },
        //  聊天内容追加到页面之后，必须做的一些初始化工作：如图片的放大镜图片是否显示
        //  根据实际内容的宽度和图片宽度比较，来决定是不是要缩放
        handleMagnifiers: function(logMsgBox, imgOffset, tableOffset) {

            var magnifiers = logMsgBox.find("img.magnifier");
            var logTable = logMsgBox.find("table.logtable");
            var logCon = logMsgBox.find("p.pChatContent");

            var outWidth = $(document).width() - 40;

            //  最小宽度
            if (logMsgBox.width() < 36) {
                logMsgBox.width(36);
            }
            else if (magnifiers && magnifiers.length > 0) {  // 如果需要处理缩放

                var isSet = false; var isAuto = false; // 存在多张图片时，标识以减少dom操作次数

                magnifiers.each(function() {
                    var magnifier = $(this);
                    var curImg = magnifier.prev();

                    var maxWidth = parseInt(curImg.css("max-width"));

                    if (outWidth < maxWidth) {
                        curImg.width(outWidth);
                        if (isSet == false) {
                            isSet = true;
                            logCon.width(outWidth + 2);
                            //logTable.width(outWidth + tableOffset);
                        }
                        if ($.browser.version < 8) {
                            magnifier.css("margin-top", curImg.height() - magHeight + "px");
                        }
                        magnifier.show();
                    } else {
                        magnifier.hide();
                        curImg.width(maxWidth);
                        if (isSet == false && isAuto == false) {
                            isAuto = false;
                            logCon.css({ "width": "auto" });
                            //logTable.css({ "width": "auto" });
                        }

                    }
                });
            }

            //  此处用于处理有连续空格存在时不能自动换行
            if (logCon.width() > outWidth + 4) {
                logCon.attr("maxwidth", logCon.width());
                logCon.width(outWidth);
            }

            // 针对IE6对right样式控制不正常问题
            if ($.browser.version == 6) {
                var dot2 = logMsgBox.find("div.dot2");
                if (dot2.length > 0 && dot2.position().left != 2) {
                    dot2.css("left", logMsgBox.width() + 3 + "px");
                }
            }

            // 给该气泡绑定事件
            var lastCurSize;
            logMsgBox.bind("resize", function() {

                var curSize = $(document).width() - 40;
                if (!lastCurSize || lastCurSize != curSize) {
                    lastCurSize = curSize;
                    // 处理图片缩放
                    if (magnifiers && magnifiers.length > 0) {
                        var isSet = false; var isAuto = false; // 存在多张图片时，标识以减少dom操作次数
                        magnifiers.each(function() {

                            var magnifier = $(this);
                            var curImg = magnifier.prev();

                            var maxImgWidth = parseInt(curImg.css("max-width"));

                            if (curSize < maxImgWidth) {
                                curImg.width(curSize);
                                if (isSet == false) {
                                    isSet = true;
                                    logCon.width(curSize + 2);
                                    //logTable.width(curSize + tableOffset);
                                }

                                if ($.browser.version < 8) {
                                    magnifier.css("margin-top", curImg.height() - magHeight + "px");
                                }
                                magnifier.show();
                            } else {
                                magnifier.hide();
                                curImg.width(maxImgWidth);
                                if (isSet == false && isAuto == false) {
                                    isAuto = false;
                                    logCon.css({ "width": "auto" });
                                    //logTable.css({ "width": "auto" });
                                }

                            }

                        });
                    }

                    // 处理连续空格的换行问题
                    if (logCon.width() > curSize + 4) {
                        if (!logCon.attr("maxwidth")) {
                            logCon.attr("maxwidth", logCon.width());
                        }
                        logCon.width(curSize);
                    } else {
                        var mwidth = logCon.attr("maxwidth");

                        if (mwidth) {
                            if (parseInt(mwidth) > curSize + 4) {
                                logCon.width(curSize + 4);
                            } else {
                                logCon.width(mwidth);
                            }
                        }
                    }

                    // 针对IE6对right样式控制不正常问题
                    if ($.browser.version == 6) {
                        var dot2 = logMsgBox.find("div.dot2");
                        if (dot2.length > 0 && dot2.position().left != 2) {
                            dot2.css("left", logMsgBox.width() + 3 + "px");
                        }
                    }

                }

            });

        },

        //  图片需要下载时间，下载完之后的替换掉占位符
        updateImage: function(imgid, src, style, minWidth, imgOffset, tableOffset, parentClass) {

            var appImgs = $("img[imgid='" + imgid + "']");

            if (appImgs && appImgs.length > 0) {

                appImgs.attr("src", src).attr("style", style); //.removeAttr("imgid");

                appImgs.each(function() {

                    var curImg = $(this);

                    if ($.browser.version == 6&& curImg.width()==39) {
						setTimeout(function(){
							var maxWidth = parseInt(curImg.css("max-width"));
							var maxHeight = parseInt(curImg.css("max-height"));

							curImg.unbind().bind("dblclick", function() {
								fetionInter.OpenPicture(curImg.attr("src"));
							});

							var logMsgBox = curImg.parents("div." + parentClass);
							var logCon = logMsgBox.find("p.pChatContent");
							var logTable = logMsgBox.find("table.logtable");
							logMsgBox.unbind("resize");
							var outWidth = logMsgBox.width() - imgOffset;
							if (maxWidth <= minWidth) {
								curImg.width(maxWidth).height(maxHeight);
							} else {

								var magnifier = $('<img class="magnifier" src="img/Magnifier_Normal.png" />');

								magnifier.unbind().bind("mouseover", function() {

									var pecent = curImg.width() / maxWidth;

									$(this).attr("title", "缩放比例：" + Math.floor(pecent * 100) + "%");

								}).bind("click", function() {
									fetionInter.OpenPicture(curImg.attr("src"));
								});

								curImg.after(magnifier);

								if (outWidth < maxWidth) {
									curImg.width(outWidth);
									if (logCon.width != outWidth + 2) {
										logCon.width(outWidth + 2);
										logTable.width(outWidth + tableOffset);
									}
									if ($.browser.version < 8) {
										magnifier.css("margin-top", curImg.height() - magHeight + "px");
									}
									magnifier.show();
								} else {
									magnifier.hide();
									curImg.width(maxWidth);
									if (logCon.width != outWidth + 2) {
										logCon.css({ "width": "auto" });
										logTable.css({ "width": "auto" });
									}
								}
							}

							if (logCon.width() > outWidth + 4) {
								logCon.attr("maxwidth", logCon.width());
								logCon.width(outWidth);
							}
							var lastCurSize;
							logMsgBox.bind("resize", function() {
								
								var curSize = $(this).width() - imgOffset;
								if (!lastCurSize || lastCurSize != curSize) {
									lastCurSize = curSize;
									var isSet = false; var isAuto = false; // 存在多张图片时，标识以减少dom操作次数
									$(this).find("img.magnifier").each(function() {

										var magnifier = $(this);
										var curImg = magnifier.prev();

										var maxImgWidth = parseInt(curImg.css("max-width"));

										if (curSize < maxImgWidth) {
											curImg.width(curSize);
											if (isSet == false) {
												isSet = true;
												logCon.width(curSize + 2);
												logTable.width(curSize + tableOffset);
											}

											if ($.browser.version < 8) {
												magnifier.css("margin-top", curImg.height() - magHeight + "px");
											}
											magnifier.show();
										} else {
											magnifier.hide();
											curImg.width(maxImgWidth);
											if (isSet == false && isAuto == false) {
												isAuto = false;
												logCon.css({ "width": "auto" });
												logTable.css({ "width": "auto" });
											}

										}

									});

									if (logCon.width() > curSize + 4) {
										if (!logCon.attr("maxwidth")) {
											logCon.attr("maxwidth", logCon.width());
										}
										logCon.width(curSize);
									} else {
										var mwidth = logCon.attr("maxwidth");

										if (mwidth) {
											if (parseInt(mwidth) > curSize + 4) {
												logCon.width(curSize + 4);
											} else {
												logCon.width(mwidth);
											}
										}
									}

									// 针对IE6对right样式控制不正常问题
									if ($.browser.version == 6) {
										var dot2 = logMsgBox.find("div.dot2");
										if (dot2.length > 0 && dot2.position().left != 2) {
											dot2.css("left", logMsgBox.width() + 3 + "px");
										}
									}
								}

							});////////end///////////////////////
						},50);
					}else{
						var maxWidth = parseInt(curImg.css("max-width"));
						var maxHeight = parseInt(curImg.css("max-height"));

						curImg.unbind().bind("dblclick", function() {
							fetionInter.OpenPicture(curImg.attr("src"));
						});

						var logMsgBox = curImg.parents("div." + parentClass);
						var logCon = logMsgBox.find("p.pChatContent");
						var logTable = logMsgBox.find("table.logtable");
						logMsgBox.unbind("resize");
						var outWidth = logMsgBox.width() - imgOffset;
						if (maxWidth <= minWidth) {
							curImg.width(maxWidth).height(maxHeight);
						} else {

							var magnifier = $('<img class="magnifier" src="img/Magnifier_Normal.png" />');

							magnifier.unbind().bind("mouseover", function() {

								var pecent = curImg.width() / maxWidth;

								$(this).attr("title", "缩放比例：" + Math.floor(pecent * 100) + "%");

							}).bind("click", function() {
								fetionInter.OpenPicture(curImg.attr("src"));
							});

							curImg.after(magnifier);

							if (outWidth < maxWidth) {
								curImg.width(outWidth);
								if (logCon.width != outWidth + 2) {
									logCon.width(outWidth + 2);
									logTable.width(outWidth + tableOffset);
								}
								if ($.browser.version < 8) {
									magnifier.css("margin-top", curImg.height() - magHeight + "px");
								}
								magnifier.show();
							} else {
								magnifier.hide();
								curImg.width(maxWidth);
								if (logCon.width != outWidth + 2) {
									logCon.css({ "width": "auto" });
									logTable.css({ "width": "auto" });
								}
							}
						}

						if (logCon.width() > outWidth + 4) {
							logCon.attr("maxwidth", logCon.width());
							logCon.width(outWidth);
						}
						var lastCurSize;
						logMsgBox.bind("resize", function() {

							var curSize = $(this).width() - imgOffset;
							if (!lastCurSize || lastCurSize != curSize) {
								lastCurSize = curSize;
								var isSet = false; var isAuto = false; // 存在多张图片时，标识以减少dom操作次数
								$(this).find("img.magnifier").each(function() {

									var magnifier = $(this);
									var curImg = magnifier.prev();

									var maxImgWidth = parseInt(curImg.css("max-width"));

									if (curSize < maxImgWidth) {
										curImg.width(curSize);
										if (isSet == false) {
											isSet = true;
											logCon.width(curSize + 2);
											logTable.width(curSize + tableOffset);
										}

										if ($.browser.version < 8) {
											magnifier.css("margin-top", curImg.height() - magHeight + "px");
										}
										magnifier.show();
									} else {
										magnifier.hide();
										curImg.width(maxImgWidth);
										if (isSet == false && isAuto == false) {
											isAuto = false;
											logCon.css({ "width": "auto" });
											logTable.css({ "width": "auto" });
										}

									}

								});

								if (logCon.width() > curSize + 4) {
									if (!logCon.attr("maxwidth")) {
										logCon.attr("maxwidth", logCon.width());
									}
									logCon.width(curSize);
								} else {
									var mwidth = logCon.attr("maxwidth");

									if (mwidth) {
										if (parseInt(mwidth) > curSize + 4) {
											logCon.width(curSize + 4);
										} else {
											logCon.width(mwidth);
										}
									}
								}

								// 针对IE6对right样式控制不正常问题
								if ($.browser.version == 6) {
									var dot2 = logMsgBox.find("div.dot2");
									if (dot2.length > 0 && dot2.position().left != 2) {
										dot2.css("left", logMsgBox.width() + 3 + "px");
									}
								}
							}

						});
					}

                });

            }
        },
        updateSoundById: function(souid) {

            var souId = $("span[id='" + souid + "']");

            if (souId.length > 1) {
				souId.each(function() {
                if ($(this).attr("updated")== undefined) {
						souId = $(this);
						return true;
					}
				})
				//souId = $("span[id='" + souid + "'][updated='true']");
            }
			souId.attr("updated","true");
            var boxId = boxID(6);

            sbId = souid + boxId;
            var sec = parseInt(souId.attr('time'));
            var souDiv = souId.parent();
            var pWidth = sec * 2 + 27;

            if (souDiv.attr('class') == 'pChatContent  fs1 pd02') {
                souDiv.append('<div class="chat_jd_bg" id="prg' + sbId + '"><div class="pbar" style="width:' + pWidth + 'px;margin:0"><div class="chat_jd_bg_l"></div><div class="chat_jd_bg_r"></div></div></div>');
            } else {
                souDiv.append('<div class="chat_jd_bg" id="prg' + sbId + '"><div class="pbar" style="width:' + pWidth + 'px"><div class="chat_jd_bg_l"></div><div class="chat_jd_bg_r"></div></div></div>');
            }
            souDiv.find('.load_img').replaceWith('<var id= ' + sbId + ' boxId=' + boxId + ' sec=' + sec + ' souId = ' + souid + ' class="sound_1"><input type="button" onFocus="this.blur()" class="ready_btn_0"></var>');
            var ry_btn = $("var[id='" + sbId + "']").find(".ready_btn_0");

            var prg = souDiv.find('.chat_jd_bg');
            ry_btn.click(function() {

                if ($(this).attr('class') == 'ready_btn_0') {
                    $(this).removeClass().addClass('go_btn_0');
                    var varBtn = $(this).parent();
                    fetionInter.OperateSoundMsg(varBtn.attr('souId'), varBtn.attr('boxId'), parseInt(varBtn.attr('sec')), 1);

                } else {
                    $(this).parent().parent().find('.pbar').children().remove();
                    var varBtn = $(this).parent();
                    fetionInter.OperateSoundMsg(varBtn.attr('souId'), varBtn.attr('boxId'), parseInt(varBtn.attr('sec')), 2);
                    $(this).removeClass().addClass('ready_btn_0');
                }
            });

            prg.click(function() {
                ry_btn.click();
            });
        },
        handleSounds: function(soundDivs) {

            if (soundDivs && soundDivs.length > 0) {
                soundDivs.each(function() {
                    var souDiv = $(this).find('span');
                    fBrowserHelper.updateSound(souDiv);
                });
            };

            //            if (soundDivs && soundDivs.length > 0) {

            //                soundDivs.each(function() {
            //                    var souDiv = $(this);
            //                    var souid = souDiv.find('span').eq(0).attr('id');

            //                    fBrowserHelper.updateSound(souid);
            //                });
            //            };
        },
        updateHistoySound: function(souidObj) {

            var souid = souidObj.attr("id"); // $("span[id='" + souid + "']");

            var boxId = boxID(6);

            sbId = souid + boxId;
            var sec = parseInt(souidObj.attr('time'));
            var souDiv = souidObj.parent();
            var pWidth = sec * 2 + 27;

            if (souDiv.attr('class') == 'pChatContent  fs1 pd02') {
                souDiv.append('<div class="chat_jd_bg" id="prg' + sbId + '"><div class="pbar" style="width:' + pWidth + 'px;margin:0"><div class="chat_jd_bg_l"></div><div class="chat_jd_bg_r"></div></div></div>');
            } else {
                souDiv.append('<div class="chat_jd_bg" id="prg' + sbId + '"><div class="pbar" style="width:' + pWidth + 'px"><div class="chat_jd_bg_l"></div><div class="chat_jd_bg_r"></div></div></div>');
            }
            souDiv.find('.load_img').replaceWith('<var id= ' + sbId + ' boxId=' + boxId + ' sec=' + sec + ' souId = ' + souid + ' class="sound_1"><input type="button" onFocus="this.blur()" class="ready_btn_0"></var>');
            var ry_btn = $("var[id='" + sbId + "']").find(".ready_btn_0");

            var prg = souDiv.find('.chat_jd_bg');
            ry_btn.click(function() {

                if ($(this).attr('class') == 'ready_btn_0') {
                    $(this).removeClass().addClass('go_btn_0');
                    var varBtn = $(this).parent();
                    fetionInter.OperateSoundMsg(varBtn.attr('souId'), varBtn.attr('boxId'), parseInt(varBtn.attr('sec')), 1);

                } else {
                    $(this).parent().parent().find('.pbar').children().remove();
                    var varBtn = $(this).parent();
                    fetionInter.OperateSoundMsg(varBtn.attr('souId'), varBtn.attr('boxId'), parseInt(varBtn.attr('sec')), 2);
                    $(this).removeClass().addClass('ready_btn_0');
                }
            });

            prg.click(function() {
                ry_btn.click();
            });
        },
        handleHistoySounds: function(soundDivs) {

            if (soundDivs && soundDivs.length > 0) {

                soundDivs.each(function() {
                    var souDiv = $(this).find('span');
                    fBrowserHelper.updateHistoySound(souDiv);
                });
            };
        },
        showHistroyBtn: function(isshow, ishide) {
            if (isshow && !jScrollBar.isShow) {
                histroyBtn.show();
                histroyBtn.unbind("click").bind("click", function() {
                    histroyBtn.unbind("click");
                    fxInter.getLastMsgRecord(20);
                    histroyBtn.hide();
                });
            } else if (ishide === true) {
                histroyBtn.hide();
            }
        }
    };

    //  飞信客户端提供的接口
    var fetionInter = {
        getLastMsgRecord: function(count) {
            window.external.GetLastMsgRecord(count);
        },
        OpenPicture: function(src) {
            window.external.OpenPicture(src);
        },
        SetClipbrd: function(str1, str2, str3, str4) {
            window.external.SetClipbrdData(str1, str2, str3, str4);
        },
        GetSelectedText: function(str) {
            window.external.SetSelectedText(str);
        },
        InBubble: function(str) {
            window.external.InBubble(str);
        },
        HasContent: function(bool) {
            window.external.HasContent(bool);
        },
        CanCopy: function(str) {
            window.external.CanCopy(str);
        },
        IsSingleObject: function(bool) {
            window.external.IsSingleObject(bool);
        },
        GetObjectUrl: function(src) {
            window.external.SetObjectUrl(src);
        },
        OperateSoundMsg: function(pId, pJSID, pWidth, operation) {//高红飞 2013年9月26日添加 开始
            window.external.OperateSoundMsg(pId, pJSID, pWidth, operation);
        }
    };

    window.fxInter = fetionInter;

    //  对客户端公开的方法集合
    var fetionBrowser = {

        //  组织2人会话窗口的聊天记录
        logMsg: function(msg, time, nickName, isLeft, isSms) {

            //var logItem = $(fBrowserHelper.buildChatHtml(msg, time, nickName, isLeft, isSms));//高红飞 2014年2月14日删除 
		var chatHtml = fBrowserHelper.buildChatHtml(msg, time, nickName, isLeft, isSms);
			chatHtml = chatHtml.replace(/=\'\)>/gi, "=//')>");
            var logItem = $(chatHtml);
            var logItemCon = logItem.find("div .logtable");
            logItemCon.mouseenter(function() {
                isBubble = true;
                bubId = $(this).parent().attr('id');
            }).mouseleave(function() {
                isBubble = false;
            });

            //  追加前内容处理
            fBrowserHelper.handleImgs(logItem, minWinWidth);

            // 追加到页面
            chatInfo.append(logItem);

            //  追加后内容初始化处理
            fBrowserHelper.handleMagnifiers(logItem.filter(".chat_box"), imgOffset, tableOffset);

            //  重置滚动条到底部
            if (isLeft == 1) {
                jScrollBar.resetScrollPostion();
            } else {
                jScrollBar.resetScrollToBottom();
            }

        },

        // 群组消息
        logGroupMsg: function(msg, time, nickName, portrait, isLeft, isSms) {

            var chatHtml = fBrowserHelper.buildGroupHtml(msg, time, nickName, portrait, isLeft, isSms);
			chatHtml = chatHtml.replace(/=\'\)>/gi, "=//')>");
            var logItem = $(chatHtml);

            var logItemCon = logItem.find("div .logtable");
            logItemCon.mouseenter(function() {
                isBubble = true;
                bubId = $(this).parent().attr('id');
            }).mouseleave(function() {
                isBubble = false;
            });

            //  追加前内容处理
            fBrowserHelper.handleImgs(logItemCon, minGroupWidth);

            // 追加到页面
            chatInfo.append(logItem);

            //  追加后内容初始化处理
            fBrowserHelper.handleMagnifiers(logItemCon, groupImgOffset, tableOffset);

            //  重置滚动条到底部
            if (isLeft == 1) {
                jScrollBar.resetScrollPostion();
            } else {
                jScrollBar.resetScrollToBottom();
            }
        },

        // 提示类型0成功1失败2感叹提示3红心提示
        fileType: ["succeed", "fail", "prompt", "redheart"],

        // 组装文件提示的html
        // 参数type:提示类型，数值对应fileType的索引
        // des:描述;time:时间；icon:图标路径； reason：原因； 
        // other：其它操作；
        logBaseTip: function(type, des, time, icon, reason, other) {

            var dlStr = '<dl class="file_msg"><dt class="' + this.fileType[type] + '"><i></i>' + des;

            dlStr += '<span>' + time + '</span></dt><dd>';

            if (icon != "") {
                dlStr += '<img src="' + icon + '" alt="" />';
            }

            dlStr += reason + other + '</dd></dl>';

            return dlStr;
        },
        logBaseTip_Right: function(type, des, time, icon, reason, other) {

            var dlStr = '<dl class="file_msg_right"><dt class="' + this.fileType[type] + '"><i></i>' + des;

            dlStr += '<span>' + time + '</span></dt><dd>';

            if (icon != "") {
                dlStr += '<img src="' + icon + '" alt="" />';
            }

            dlStr += reason + other + '</dd></dl>';

            return dlStr;
        },
        // 文件提示
        // 参数type:提示类型，数值对应fileType的索引
        // des:描述;time:时间；icon:图标路径； reason：原因； 
        // other：其它操作；
        logTip: function(type, des, time, icon, reason, other) {

            var dlStr = fetionBrowser.logBaseTip(type, des, time, icon, reason, other);

            chatInfo.append(dlStr);

            //  重置滚动条到底部
            jScrollBar.resetScrollToBottom();
        },
        logTip_Right: function(type, des, time, icon, reason, other) {

            var dlStr = fetionBrowser.logBaseTip_Right(type, des, time, icon, reason, other);

            chatInfo.append(dlStr);

            //  重置滚动条到底部
            jScrollBar.resetScrollToBottom();
        },
        logTipWithImage: function(des, time, src, width, height, other) {

            var dlStr = $(fetionBrowser.logBaseTip(2, des, time, src, "", other));
            var broImg = dlStr.find("img").css({ 'max-width': width, 'max-height': height });
            //alert(dlStr);
            chatInfo.append(dlStr);

            //  重置滚动条到底部
            jScrollBar.resetScrollToBottom();

        },
        //  发送图片失败
        //  原因，时间，图片路径，图片宽度，图片高度，其它操作
        sendImgFail: function(reason, time, src, width, height, other) {

            var dlStr = $(fetionBrowser.logBaseTip(1, reason, time, src, "", other));
            dlStr.find("img").css({ 'max-width': maxImgWidth, 'max-height': maxImgHeight });
            var broImg = dlStr.find("img"); //.css({ 'max-width': maxImgWidth, 'max-height': maxImgHeight });
            broImg.attr("src", broImg.attr("src").replace('file:///', 'fetionres:///'));
            chatInfo.append(dlStr);
            //alert(dlStr.html());
            //ie6下修复不支持max-width max-height的问题
            if ($.browser.version == 6) {
                if (width > height * maxImgWidth / maxImgHeight)
                    $(broImg).width(maxImgWidth);
                else
                    $(broImg).height(maxImgHeight);
            }
            //  重置滚动条到底部
            jScrollBar.resetScrollToBottom();

        },

        //  加载2人会话历史记录
        //参数:要展示的历史记录 格式如[{"msg":"123", "time":"2012-10-10", "nickName":"feng", "isLeft":1,"isSms":1},{"msg":"123", "time":"2012-10-10", "nickName":"feng", "isLeft":1,"isSms":1}]
        //是否还有更多历史记录 1有0无
        logHistoryMsg: function(arrMsg, isMore) {

            var jsonMsg = '';
            if (arrMsg) {
                jsonMsg = eval("(" + arrMsg + ")");
            }

            isShowHistory = isMore == 1 ? true : false;
            if (jsonMsg && jsonMsg.length > 0) {

                setTimeout(function() {


                    var strMsg;
                    for (var i = 0; i < jsonMsg.length; i++) {
                        strMsg += fBrowserHelper.buildChatHtml(base64Coder.decode(jsonMsg[i].msg), jsonMsg[i].time, base64Coder.decode(jsonMsg[i].nickName), jsonMsg[i].isLeft, jsonMsg[i].isSms);
                    }
					strMsg = strMsg.replace(/=\'\)>/gi, "=//')>");
                    if (isFirstAppHis) {
                        strMsg += '<div class="line">以上是最近消息记录</div>';
                        isFirstAppHis = false;
                    }

                    setTimeout(function() {

                        var logItem = $(strMsg);

                        //  对图片做处理
                        fBrowserHelper.handleImgs(logItem, minWinWidth);

                        var logItemCon = logItem.find("div .logtable");
                        logItemCon.mouseenter(function() {
                            isBubble = true;
                            bubId = $(this).parent().attr('id');
                        }).mouseleave(function() {
                            isBubble = false;
                        });

                        // 追加到页面,历史记录，追加到当前页面的最前面
                        chatInfo.prepend(logItem);

                        var logItemSou = logItem.find("div .fs1");
                        // 对语音的处理
                        //fBrowserHelper.handleSounds(logItemSou);
                        fBrowserHelper.handleHistoySounds(logItemSou);

                        setTimeout(function() {
                            //  内容初始化
                            // logItem.filter(".chat_box").each(function(){
                            // fBrowserHelper.handleMagnifiers($(this),imgOffset,tableOffset);   
                            // });
                            var logItemss = logItem.filter(".chat_box");
                            var allLength = logItemss.length;
                            var allHeight = 0;
                            function handleImg(i) {
                                setTimeout(function() {
                                    fBrowserHelper.handleMagnifiers($(logItemss[i]), imgOffset, tableOffset);
                                    allHeight += $(logItemss[i]).outerHeight();
                                    i--;
                                    if (i >= 0) {
                                        handleImg(i);
                                    } else {
                                        setTimeout(function() {

                                            //重置滚动条
                                            jScrollBar.resetScrollPreserve(allHeight);

                                            fBrowserHelper.showHistroyBtn(isShowHistory, false);

                                            isHisLoading = false;

                                        }, 10);
                                    }

                                }, 10);
                            }
                            handleImg(allLength - 1);


                        }, 50);

                    }, 50);

                }, 50);

            } else {

                if (isMore) {
                    fBrowserHelper.showHistroyBtn(isShowHistory, true);
                } else {
                    fBrowserHelper.showHistroyBtn(isShowHistory, false);
                }

                isHisLoading = false;
            }

        },
        logGroupHistory: function(arrMsg, isMore) {

            var jsonMsg = '';
            if (arrMsg) {
                jsonMsg = eval("(" + arrMsg + ")");
            }

            isShowHistory = isMore == 1 ? true : false;

            if (jsonMsg && jsonMsg.length > 0) {

                var strMsg;

                setTimeout(function() {

                    for (var i = 0; i < jsonMsg.length; i++) {
                        strMsg += fBrowserHelper.buildGroupHtml(base64Coder.decode(jsonMsg[i].msg), jsonMsg[i].time, base64Coder.decode(jsonMsg[i].nickName), jsonMsg[i].portrait, jsonMsg[i].isLeft, jsonMsg[i].isSms);
                    }
					strMsg = strMsg.replace(/=\'\)>/gi, "=//')>");
                    if (isFirstAppHis) {
                        strMsg += '<div class="line">以上是最近消息记录</div>';
                        isFirstAppHis = false;
                    }
                    setTimeout(function() {

                        var logItem = $(strMsg);
                        var logItemCon = logItem.find("div .logtable");
                        //  对图片做处理
                        fBrowserHelper.handleImgs(logItemCon, minGroupWidth);

                        var logItemCon = logItem.find("div .logtable");
                        logItemCon.mouseenter(function() {
                            isBubble = true;
                            bubId = $(this).parent().attr('id');
                        }).mouseleave(function() {
                            isBubble = false;
                        })

                        // 追加到页面,历史记录，追加到当前页面的最前面
                        chatInfo.prepend(logItem);

                        var logItemSou = logItem.find("div .fs1");
                        // 对语音的处理
                        fBrowserHelper.handleSounds(logItemSou);

                        setTimeout(function() {
                            //  内容初始化
                            logItemCon.each(function() {
                                fBrowserHelper.handleMagnifiers($(this), groupImgOffset, tableOffset);
                            });

                            var allLength = logItemCon.length;
                            var allHeight = 0;

                            function handleImg(i) {

                                setTimeout(function() {

                                    fBrowserHelper.handleMagnifiers($(logItemCon[i]), groupImgOffset, tableOffset);
                                    allHeight += $(logItemCon[i]).outerHeight();
                                    i--;
                                    if (i >= 0) {
                                        handleImg(i);
                                    } else {
                                        setTimeout(function() {

                                            //重置滚动条
                                            jScrollBar.resetScrollPreserve(allHeight);
                                            fBrowserHelper.showHistroyBtn(isShowHistory, false);

                                            isHisLoading = false;

                                        }, 10);
                                    }

                                }, 10);
                            }
                            handleImg(allLength - 1);

                        }, 50);
                    }, 50);
                }, 50);
            } else {
                if (isMore) {
                    fBrowserHelper.showHistroyBtn(isShowHistory, true);
                } else {
                    fBrowserHelper.showHistroyBtn(isShowHistory, false);
                }

                isHisLoading = false;

            }

        },

        updateImage: function(imgid, src, style) {

            fBrowserHelper.updateImage(imgid, src, style, minWinWidth, imgOffset, tableOffset, "chat_box");

            jScrollBar.resetScrollPostion();
        },

        updateGroupImage: function(imgid, src, style) {
            //改成跟二人一样，暂时，后期优化
            //fBrowserHelper.updateImage(imgid, src, style, minWinWidth, imgOffset, tableOffset, "chat_box");

            //jScrollBar.resetScrollPostion();
			if ($.browser.version == 6) {
                         fBrowserHelper.updateImage(imgid, src, style, minGroupWidth, groupImgOffset, tableOffset, "msg_bd");
             }else{
						fBrowserHelper.updateImage(imgid, src, style, minGroupWidth, groupImgOffset, tableOffset, "chat_box");
			 }
                         jScrollBar.resetScrollPostion();
        },

        updateSound: function(souid) {

            fBrowserHelper.updateSoundById(souid);

            jScrollBar.resetScrollPostion();
        },

        playSound: function(souid, boxId, sec) {

            var sbId = souid + boxId;
            if (psouId && psouId != sbId) {
                var play_btn = $("var[id='" + psouId + "']").find('input');

                if (play_btn.attr('class') == 'go_btn_0') {
                    $("div[id='prg" + psouId + "']").children('.pbar').children().remove();
                    play_btn.removeClass().addClass('ready_btn_0');
                }
            }
            psouId = sbId;

            var pWidth = sec * 2 + 27;
            var prgBtn = $("div[id='prg" + sbId + "']");
            if (prgBtn.parent().attr('class') == 'pChatContent  fs1 pd02') {
                prgBtn.html('<div class="pbar" style="width:' + pWidth + 'px;margin:0"></div>');
            } else {
                prgBtn.html('<div class="pbar" style="width:' + pWidth + 'px"></div>');
            }


            // from second #0 till 15
            var iNow = new Date().setTime(new Date().getTime()); // now plus 0 secs
            var iEnd = new Date().setTime(new Date().getTime() + sec * 1000); // now plus 15 secs             
            $.anim_progressbar({ bar: 'prg' + sbId, start: iNow, finish: iEnd, interval: 100 });


        },

        closeSound: function(souid, boxid) {

            var sbId = souid + boxid;
            var play_btn = $("var[id='" + sbId + "']").find('input');
            if (play_btn.attr('class') == 'go_btn_0') {
                play_btn.removeClass().addClass('ready_btn_0');
                $("div[id='prg" + sbId + "']").children('.pbar').children().remove();
            }
        },

        cancelLink: function(linkId) {
            var objLinks = $("a[linkid='" + linkId + "']");

            if (objLinks.length > 0) {
                objLinks.each(function() {
                    $(this).after("<label>" + $(this).text() + "</label>");
                    $(this).remove();
                });
            }
        },

        setBgOffset: function(offsetX, offsetY) {
            if (bgPositionType == "right") {
                bgposOffsetX = offsetX;
                bgposOffsetY = offsetY;
                var curWinWidth = lastWinWidth;
                var curWinHeight = lastWinHeight;

                //ResetRightAlignBkg(curWinWidth, curWinHeight);
                prevPosX = offsetX;
                prevPosY = offsetY;
                xpos = curWinWidth - 675 + parseInt(bgposOffsetX);
                ypos = bgposOffsetY;
                //alert(curWinWidth + "   " + bgposOffsetX + "   " + xpos.toString());
                mainPage.css({ "background-position-x": xpos.toString() + "px", "background-position-y": -ypos + "px" });

            }
        },
        //  设置背景
        setBg: function(src, posX, posY, bgcolor, position) {
            bgPositionType = position;
            //alert(bgPositionType);
            bgposOffsetX = posX;
            bgposOffsetY = posY;
            setTimeout(function() {
                if (prevSrc != src) {
                    if (position == "right") {
                        //mainPage.css({ "background-image": "url(" + src + ")", "background-position-x": "100%", "background-position-y": -posY + "px" });
                        prevSrc = src;
                        prevPosX = posX;
                        prevPosY = posY;
                        var curWinWidth = lastWinWidth;
                        var curWinHeight = lastWinHeight;
                        xpos = curWinWidth - 675 + parseInt(bgposOffsetX);
                        ypos = bgposOffsetY;
                        mainPage.css({ "background-image": "url(" + src + ")", "background-position-x": xpos.toString() + "px", "background-position-y": -ypos + "px" });

                    }
                    else {
                        mainPage.css({ "background-image": "url(" + src + ")", "background-position-x": -posX + "px", "background-position-y": -posY + "px" });
                        prevSrc = src;
                        prevPosX = posX;
                        prevPosY = posY;
                    }
                    prevAlign = position;

                }
                if (prevPosX != posX || prevPosY != posY || position != prevAlign) {

                    if (position == "right") {
                        //mainPage.css({ "background-position-x": "100%", "background-position-y": -posY + "px" });
                        prevPosX = posX;
                        prevPosY = posY;
                        var curWinWidth = lastWinWidth;
                        var curWinHeight = lastWinHeight;
                        xpos = curWinWidth - 675 + parseInt(bgposOffsetX);
                        ypos = bgposOffsetY;
                        mainPage.css({ "background-position-x": xpos.toString() + "px", "background-position-y": -ypos + "px" });

                    }
                    else {
                        mainPage.css({ "background-position-x": -posX + "px", "background-position-y": -posY + "px" });
                        prevPosX = posX;
                        prevPosY = posY;
                    }
                    prevAlign = position;

                }
                if (bgcolor) {
                    mainPage.css({ "background-color": bgcolor });
                    prevColor = bgcolor;
                }

            }, 10);

        },
        ScrollToBottom: function() {

            jScrollBar.resetScrollToBottom();
        },
        // update 1210
        // add copy selection range for pulico only in ie
        CopyRage: function() {
            //alert("CopyRage: function");
            var selection = document.selection;
            var sel = document.selection.createRange();
            if (sel.htmlText.lastIndexOf("fetionres") == -1) {
                //alert("add by public");
                var enbleCopy = sel.queryCommandEnabled("Copy");
                if (enbleCopy == true)
                    sel.execCommand("Copy");
            }
            else {
                //alert("add by fetion");
                fetionBrowser.DoCustomCopy();
            }
            return true;
            //alert(1);
            // var temp = document.createElement("div");
            // var text;
            // try
            // {
            // temp.innerText = sel.htmlText;	
            // text = temp.innerHTML;
            // //alert(text);
            // }
            // catch(e)
            // {
            // //alert(e);
            // }
            // chatInfo.append(text);
            //alert(4);
            //document.append(sel.htmlText);
        },

        // add copy img for pulico only in ie
        CopyImg: function(src) {
            //alert("CopyImg: function : " + src);
            var imgs = document.getElementsByTagName("img");
            for (var i = 0; i < imgs.length; i++) {
                //alert("find " + imgs[i].getAttribute('src'));
                if (src == imgs[i].getAttribute('src')) {
                    //alert("finded " + imgs[i].getAttribute('src'));
                    if (imgs[i].getAttribute('src').lastIndexOf("fetionres") == -1) {
                        var range = document.body.createTextRange();
                        range.moveToElementText(imgs[i]);
                        var b = range.execCommand("Copy");
                    }
                    else {
                        //alert("add by fetion");
                        fetionBrowser.DoCustomCopy();
                    }
                    break;
                }
            }
        },
        // end        
		DoCustomCopy: function() {
            var fetionhtml="",bitmap="",text="",html="";
            var rangeStr = document.selection.createRange().htmlText;
            
            //预处理rangeStr
            if (rangeStr == "" && cImg != null)
                rangeStr = cImg.html();
            var rangedom = $('<div id="showDiv" >'+rangeStr+'</div>');
            rangedom.find('.spanSpace').remove();
            var imgItems = rangedom.find('img');
            if (imgItems.length > 0) {
                for (var i = 0; i < imgItems.length; i++) {
                    imgItems.eq(i).removeAttr('title').removeAttr('class').removeAttr('style').removeAttr('oncontextmenu');
                }
            }
            rangeStr = rangedom.html();
            
            //处理html
            html = rangeStr.replace(/(<\/?(?!br|img)[^>\/]*)\/?>/gi,"")
            .replaceAll("fetionres:///","file:///")
            .replace(/\r[\r|\n]*\n/g, '<br>').Trim();    //去除多余空行  
           
            //处理feitionformat
            fetionhtml = html.replaceAll('imgid', 'ID')
            .replace(/<img/gi, "<OBJECT").replace(/img>/gi, "OBJECT>")
            .replace(/<br>/gi,"\r")
            .replaceAll('&nbsp;', ' ').Trim();
           
            //处理bitmap
            var htmlstr = rangeStr.replace(/<\/?(FONT|P|TABLE)[^>]*>/gi, "");
            var isImg = htmlstr.Trim().substring(0, 4) == ('<IMG');
            bitmap = (isImg == true) ? $(htmlstr).attr("src").replace('fetionres:///', '') : '';
            bitmap = decodeURIComponent(bitmap).replace(/\+/g," ");
            //处理text
            text = fetionhtml.replace(/<[^>]*>/gi,"").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").Trim();
            
            //处理html格式适配剪切板
            var htmllength = html.GetLength();
            
            html = "<!doctype html><html><body>\r\n"+
            "<!--StartFragment --><DIV>\r\n"+
            html+
            "\r\n</DIV><!--EndFragment-->\r\n"+
            "</body>\r\n"+
            "</html>";

            var numberfomat = "00000000";
            EndHTML = 112+htmllength+88;
            EndFragment = 126+htmllength+36;
            EndHTML = numberfomat.substring(0,8-EndHTML.toString().length)+EndHTML.toString();
            EndFragment = numberfomat.substring(0,8-EndFragment.toString().length)+EndFragment.toString();

            var header = "Version:0.9\r\n"+
            "StartHTML:00000112\r\n"+
            "EndHTML:"+EndHTML+"\r\n"+
            "StartFragment:00000126\r\n"+
            "EndFragment:"+EndFragment+"\r\n";

            html = header+html;
            
            fetionInter.SetClipbrd(html, text, bitmap, fetionhtml);
        },
        InBubble: function() {
            fetionInter.InBubble(isBubble);
        },
        HasContent: function() {
            var isHas = false;
            if (chatInfo.find('.file_msg').length > 0 || chatInfo.find('.msg_bd').length > 0) {
                isHas = true;
            }

            fetionInter.HasContent(isHas);
        },
        CanCopy: function() {
            var rangeStr = document.selection.createRange().htmlText;
            var isSelect = false;
            if (rangeStr.length > 0) {
                isSelect = true;
            }

            fetionInter.CanCopy(isSelect);
        },
        IsSingleObject: function() {

            var rangeStr = document.selection.createRange().htmlText;
            var htmlstr = rangeStr.replace(/<\/?(DIV|FONT|P|TD|TABLE|SPAN|TBODY|TR)[^>]*>/gi, "").replaceAll('&nbsp;', '').Trim();
            var htmlItem = $(htmlstr);
            var isImg = htmlItem.is('IMG') && (htmlItem.length == 1 || (htmlItem.length == 2 && htmlItem.eq(1).attr('class') == "magnifier")) && htmlstr.Trim().substring(0, 4) == ('<IMG') && (htmlstr.charAt(htmlstr.length - 1) == ">");

            fetionInter.IsSingleObject(isImg);
        },
        SelectAll: function() {
            var divObj = document.getElementById("content"); //document.body;
            var range = document.body.createTextRange();
            range.moveToElementText(divObj)
            //range.moveEnd('character', -1);
            //range.moveStart('character', -1);
            range.select();
        },
        SelectCurrentBubble: function() {
            if (bubId) {
                var divObj = document.getElementById(bubId);
                var range = document.body.createTextRange();
                range.moveToElementText(divObj)
                range.moveEnd('character', -1);
                range.moveStart('character', -1);
                range.select();
            }
        },
        GetSelectedText: function() {
            var rangeStr = document.selection.createRange().htmlText;
            var showDiv = $('<div id="showDiv" style="display:none"></div>');
            $('body').append(showDiv);
            showDiv.html(rangeStr)

            var imgItems = showDiv.find('img');

            if (imgItems.length > 0) {
                for (var i = 0; i < imgItems.length; i++) {
                    var st = imgItems.eq(i).attr('shortcut');

                    imgItems.eq(i).replaceWith(st);
                }
            }

            var selText = $('#showDiv').text();
            $('#showDiv').remove();

            fetionInter.GetSelectedText(selText);
        },
        GetObjectUrl: function() {
            var rangeStr = document.selection.createRange().htmlText;
            var htmlstr = rangeStr.replace(/<\/?(DIV|FONT|P|TD|TABLE|SPAN|TBODY|TR)[^>]*>/gi, "").replaceAll('&nbsp;', '').Trim();

            var htmlItem = $(htmlstr);
            var isImg = htmlItem.is('IMG') && (htmlItem.length == 1 || (htmlItem.length == 2 && htmlItem.eq(1).attr('class') == "magnifier")) && htmlstr.Trim().substring(0, 4) == ('<IMG') && (htmlstr.charAt(htmlstr.length - 1) == ">");

            var urlStr = (isImg == true) ? $(htmlItem).attr("src").replace('fetionres:///', '') : '';

            if (isImg && htmlItem.length == 1) {
                urlStr = $(htmlItem).attr("src").replace('fetionres:///', '')
            } else if (isImg && htmlItem.length == 2) {
                urlStr = htmlItem.eq(0).attr("src").replace('fetionres:///', '')
            }

            urlStr = decodeURIComponent(urlStr.replace(/\+/g, " "));
            fetionInter.GetObjectUrl(urlStr);
        },
        ClearAll: function() {
            chatInfo.children().remove();
            jScrollBar.resetScrollPostion();
            histroyBtn.remove();
        }
    };

    window.fxBrowser = fetionBrowser;


})(jQuery);

$(document).ready(function () {

    // 禁止右键
    //    $(document).bind("contextmenu", function () {
    //        return false;
    //    });
    var ctrlKey = false;  //  是否按下ctrl键
    //禁止F5刷新
    document.onkeydown = function (e) {
        e = e || event;
        if (e.keyCode == 116) {

            e.keyCode = 0;
            e.cancelBubble = true;

            return false;
        }

        if (ctrlKey && e.keyCode == 67) {
				try
				{
					window.fxBrowser.CopyRage();
				}
				catch(e)
				{
					alert(e);
				}
				return false;
        }
		
		if (e.ctrlKey && e.keyCode == 65) {
				try
				{
				window.fxBrowser.SelectAll();
					//window.fxBrowser.CopyRage();
				}
				catch(e)
				{
					alert(e);
				}
				return false;
        }

        if (e.ctrlKey) {
            ctrlKey = true;
        }
    };
	document.onmousewheel = function(e)
    {
        e=e || window.event; 
        if(e.wheelDelta && event.ctrlKey){//IE/Opera/Chrome 
			event.returnValue=false;
        }
    };
    document.onkeyup = function (e) {
        e = e || event;
        if (e.ctrlKey) {
            ctrlKey = false;
        }
    };

    String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
    };

	    //计算字符串字节长度
    String.prototype.GetLength = function () {
        var str = this;
        var i, sum = 0;
        for (i = 0; i < str.length; i++) {
            if ((str.charCodeAt(i) >= 0) && (str.charCodeAt(i) <= 255))
                sum = sum + 1;
            else
                sum = sum + 3;
        }
        return sum;
    };
	
    document.body.oncontextmenu = ContextMenu;

    document.onmousemove = function (ev) {

        ev = ev || window.event;
        if (typeof window.pageYOffset != 'undefined') {
            point.x = window.pageXOffset;
            point.y = window.pageYOffset;
        }
        else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
            point.x = document.documentElement.scrollLeft;
            point.y = document.documentElement.scrollTop;
        }
        else if (typeof document.body != 'undefined') {
            point.x = document.body.scrollLeft;
            point.y = document.body.scrollTop;
        }

        point.x += ev.clientX;
        point.y += ev.clientY;
    }
});

