﻿function PopChat(userid, friendId) {
    new myPopChat(userid, friendId).show();
}


myPopChat = function(userid, friendid) {
    this.UserId = userid;
    this.FriendId = friendid;
    this.dialogId = "D_PopChat_Dialog";
    this.dialogTitleId = "D_PopChat_Title";
    this.dialogIdContentId = "D_PopChat_Content";
    this.smileyImages = ['0.gif', '1.gif', '2.gif', '3.gif', '4.gif', '5.gif', '6.gif', '7.gif', '8.gif', '9.gif', '10.gif', '11.gif', '12.gif', '13.gif', '14.gif', '15.gif', '16.gif', '17.gif', '18.gif', '19.gif', '20.gif', '21.gif', '22.gif', '23.gif', '24.gif', '25.gif', '26.gif', '27.gif', '28.gif', '29.gif', '30.gif', '31.gif', '32.gif', '33.gif', '34.gif', '36.gif', '38.gif', '39.gif', '41.gif', '43.gif', '44.gif', '45.gif', '46.gif', '47.gif', '48.gif', '49.gif', '50.gif', '51.gif', '52.gif', '53.gif', '54.gif', '55.gif', '56.gif', '60.gif', '61.gif', '62.gif', '63.gif', '64.gif', '65.gif', '66.gif', '67.gif', '68.gif', '69.gif', '70.gif', '71.gif', '74.gif', '75.gif', '76.gif', '77.gif', '79.gif', '80.gif', '81.gif', '82.gif', '83.gif', '84.gif', '85.gif', '86.gif', '87.gif', '88.gif', '89.gif', '90.gif', '100.gif', '101.gif', '103.gif', '104.gif', '105.gif', '106.gif', '107.gif', '108.gif', '109.gif'];
    this.smileyPath = '/fckeditor/editor/images/smiley/msn/';
    this.auto = null;
    this.domDoc = null;
    this.init();
};


myPopChat.prototype.init = function() {

    var sBox = '\
            <table class="pop_dialog_table" style="display: none" id="' + this.dialogId + '">\
                <tr>\
                    <td class="pop_topleft">\
                    </td>\
                    <td class="pop_border">\
                    </td>\
                    <td class="pop_topright">\
                    </td>\
                </tr>\
                <tr>\
                    <td class="pop_border">\
                    </td>\
                    <td class="pop_content">\
                        <div class="divMsgFrameCss">\
                            <div class="divMsgTitleCss" id="' + this.dialogTitleId + '"  style="cursor: move" onselectstart="return false" onmousedown="dragStart(\'' + this.dialogId + '\',event) "  ondragstart="return false">\
                                </div>\
                            <div class="divMsgMainCss" id="' + this.dialogIdContentId + '">\
                            </div>\
                        </div>\
                    </td>\
                    <td class="pop_border">\
                    </td>\
                </tr>\
                <tr>\
                    <td class="pop_bottomleft">\
                    </td>\
                    <td class="pop_border">\
                    </td>\
                    <td class="pop_bottomright">\
                    </td>\
                </tr>\
            </table>\  ';
    if (document.getElementById(this.dialogId) == null)
        $("body").append(sBox);
};

myPopChat.prototype.show = function() {
    $('#' + this.dialogId).css({ position: 'absolute', zIndex: '101' });
    $('#' + this.dialogId).css({ width: '550px' });
    $('#' + this.dialogId).show();
    this.setBG();
    this.Loading();
//    $(window).resize(this.center());
//    $(window).scroll(this.center());
    this.bulid();

};

myPopChat.prototype.bulid = function()
{
    var self = this;
    if (this.UserId == 0)
    {
        self.showMSG("-1");
        return false;
    }

    if (this.FriendId == 0)
    {
        self.showMSG("-2");
        return false;
    }
    
    $.get('/WS/PopChat.ashx', { 'UserId': this.UserId,
        'ObjectId': this.FriendId,
        'Action': 'init',
        'id': Math.random()
    },
    function(data)
    {
        self.innerContent(data);
        self.title('正在与' + $('#hiddenField_FriendName').val() + '聊天');
        self.filterTxt();
        self.setButtom();
        self.bindbehaviors();
    });

};

myPopChat.prototype.showMSG = function(result)
{
    var titlemsg = null;
    var xBox = null;
    var self = this;
    switch (result)
    {
        case '-1':
            titlemsg = "错误";
            xBox = '<span class="msgBigError">你尚未登录，不能使用此功能</span>';
            break;
        case '-2':
            titlemsg = "错误";
            xBox = '<span class="msgBigError">聊天对象不明确</span>';
            break;
        default:
            titlemsg = "完成";
            xBox = '<span class="msgBigError">' + result + '</span>';
    }

    var mBox = '';
    mBox = '<div class=\"divMsgBottomCss\">\
                  <input type="button" id="btnPopChatClose" value="关闭" class="inputaux"/>\
                   </div>';
    this.innerContent(xBox + mBox);
    this.title(titlemsg);

    if (parseInt(result) >= 0)
    {
        window.setTimeout(function() { self.close(); }, 1500);
    }
    else
        $('#btnPopChatClose').click(function()
        {
            self.close();
        });

};

myPopChat.prototype.save = function() {
    var self = this;

    //clearInterval(this.auto);
    var content = $(this.domDoc.body).html();
    if ($.trim(content) == '') {
        this.alertEmpty();
    }
    else {
        this.disable();
        $.post('/WS/PopChat.ashx', { 'UserId': this.UserId,
            'ObjectId': this.FriendId,
            'Action': 'Save',
            'Content': content,
            'id': Math.random()
        },
    function(data) {
        $(self.domDoc.body).html('').focus();
        self.enable();
        //$(Editor.document.body).focus();
        self.appendMsg();
        //self.auto = setInterval(function() { self.appendMsg(); }, 10000);
    });
    }
};

myPopChat.prototype.filterTxt = function() {
    $('#' + this.dialogId + ' #msgList a').attr('target', '_blank');
    $('#' + this.dialogId + ' #msgList a:not([@href*="fuwoo.com"])').unbind('click');
    $('#' + this.dialogId + ' #msgList a:not([@href*="fuwoo.com"])').click(function() { return confirm('你要打开的链接不是本网站内的链接，可能存在危险，是否继续？'); });
};

myPopChat.prototype.setButtom = function() {
//    //$('#' + this.dialogId + ' #msgList').height()
//    alert($('#' + this.dialogId + ' #msgList').height());
    $('#' + this.dialogId + ' #msgList').scrollTop(10000);
};

myPopChat.prototype.bindbehaviors = function() {
    var self = this;

    $('#' + this.dialogId + ' #smileImg').toggle(function(e) {
        if (document.getElementById("smilelayer") == null) {
            $('<div id="smilelayer"></div>').appendTo(document.body).hide();
        }
        $(this).addClass('clicked');
        var offset = $(e.toElement ? e.toElement : e.target).offset();

        var mouseX = offset.left;
        var mouseY = offset.top + 25;
        $('#smilelayer').css({ border: 'solid 1px #808080', width: '470px' });
        $('#smilelayer').css({ position: 'absolute', zIndex: '102' });
        $('#smilelayer').css({ left: mouseX + 'px', top: mouseY + 'px' });
        $('#smilelayer').css({ background: '#fff' });
        $('#smilelayer').css({ overflow: 'auto' })
        //style="height:1%;overflow:auto;"
        $('#smilelayer').show('slow');
        self.loadSmileImg();
    }, function() {
        $('#smilelayer').hide('slow');
        $(this).removeClass('clicked');
    });

    $('#' + this.dialogId + ' #btnCancel').click(function() { self.close(); });

    $('#' + this.dialogId + ' #btnSent').click(function() { self.save(); });

    $('#' + this.dialogId + ' .right .middle a').toggle(function(e) {
        $(this).addClass('clicked');
        if (document.getElementById("friendLayer") == null) {
            $('<div id="friendLayer">正在加载好友信息，请稍等...</div>').appendTo(document.body).hide();
        }
        var offset = $(e.toElement ? e.toElement : e.target).offset();

        var mouseX = offset.left-10;
        var mouseY = offset.top + 20;
        $('#friendLayer').css({ border: 'solid 1px #808080', width: '215px' });
        $('#friendLayer').css({ position: 'absolute', zIndex: '104' });
        $('#friendLayer').css({ left: mouseX + 'px', top: mouseY + 'px' });
        $('#friendLayer').css({ background: '#f7f7f7' });
        $('#friendLayer').css({ overflow: 'auto' })
        $('#friendLayer').show('slow');
        self.AjaxLoadFriendList();
    }, function() {
        $('#friendLayer').hide('slow');
        $(this).removeClass('clicked');
    });

    this.auto = setInterval(function() { self.appendMsg(); }, 10000);
    try {
        this.EditorEnable();
        //        if (Editor.document != null) {
        //            $(this.domDoc).click(function() {
        //                self.EditorEnable();
        //            });
        //        }
    }
    catch (err)
      { }

};

myPopChat.prototype.AjaxLoadFriendList = function() {
    var self = this;
    $.get('/WS/PopChat.ashx', { 'UserId': this.UserId,
        'ObjectId': this.FriendId,
        'Action': 'Friends',
        'id': Math.random()
    },
    function(data) {
        if (data != '') {
            $('#friendLayer').html($(data).hover(function() {
                $(this).addClass('friendListSelectioned');
            }, function() {
                $(this).removeClass('friendListSelectioned');
            }).click(function() {
                $('#friendLayer').hide();
                self.FriendId = $(this).find(':hidden').val();
                self.clearLayer;
                self.Loading();
                self.bulid();
            })
            );
        }
    });
};

myPopChat.prototype.EditorEnable = function() {
    var self = this;
    this.domDoc = $('#Editor').attr('contentWindow').document;
    this.domDoc.designMode = 'on';
    this.domDoc.open();
    this.domDoc.write($('#EditorValue').val());
    this.domDoc.close();
    this.domDoc.body.contentEditable = true;
    $(this.domDoc.body).css({ margin: '0px', padding: '3px', fontSize: '10.5pt' });
    $(this.domDoc).keydown(function(e) { self.quickSave(e); });
    $(this.domDoc.body).focus();
};

myPopChat.prototype.quickSave = function(e) {
    var evt = window.event ? window.event.keyCode : e.which;
//    if (evt == 13) {
//        var range = document.selection.createRange();
//        range.text = '\n';
//        range.select();
//    }
    if (e.ctrlKey && evt == 13) {
        $('#' + this.dialogId + ' #btnSent').click();
    }
};

myPopChat.prototype.appendMsg = function() {
    var self = this;
    $.get('/WS/PopChat.ashx', { 'UserId': this.UserId,
        'ObjectId': this.FriendId,
        'Action': 'New',
        'id': Math.random()
    },
    function(data) {
        if (data != '') {
            self.appendNewList(data);
        }
    });

};


myPopChat.prototype.appendNewList = function(txt) {
    $('#' + this.dialogId + ' #msgList').append(txt);
    this.setButtom();
    this.filterTxt();
};

myPopChat.prototype.disable = function() {
    $('#' + this.dialogId + ' #btnSent').attr('disabled', 'disabled');
    $('#' + this.dialogId + ' #btnSent').addClass('inputaux');
    $('#' + this.dialogId + ' #btnSent').val('正在发送...');

};

myPopChat.prototype.alertEmpty = function() {
    if (document.getElementById("alertBg") == null) {
        $("body").append('<div  id="alertBg" class="alertBg">发送内容不能为空，请重新输入。</div>');
    }

    var offset = $('#' + this.dialogId + ' #btnSent').offset();

    var mouseX = offset.left - 170;
    var mouseY = offset.top - 50;
    $('#alertBg').css({ position: 'absolute', zIndex: '105' });
    $('#alertBg').css({ left: mouseX + 'px', top: mouseY + 'px' });
    $('#alertBg').show();
    setTimeout(function() { $('#alertBg').hide('fast'); }, 2000);
};

myPopChat.prototype.enable = function() {

    $('#' + this.dialogId + ' #btnSent').removeAttr('disabled');
    $('#' + this.dialogId + ' #btnSent').removeClass('inputaux');
    $('#' + this.dialogId + ' #btnSent').val('发送(ctrl+回车)');
};

myPopChat.prototype.loadSmileImg = function() {
    var self = this;
    if ($('#smilelayer').html() == '') {
        $(this.smileyImages).each(function(index) {
            $('#smilelayer').append('<div><img src="' + self.smileyPath + this + '"></div');
        });

        $('#smilelayer div').addClass('imgdiv');
        $('#smilelayer div').hover(function() { $(this).addClass('imgdivHover') }, function() { $(this).removeClass('imgdivHover') });
        $('#smilelayer div img').click(function() { $(Editor.document.body).append('<img src=" ' + $(this).attr('src') + '"/>'); });
    }
};

myPopChat.prototype.Loading = function() {
    this.innerContent('<span class="msgBigError">正在加载数据，请等待...</span>');
    this.title('等待');
    this.center();
};

myPopChat.prototype.innerContent = function(content) {
    $('#' + this.dialogId + ' #' + this.dialogIdContentId).html(content);
    this.center();
};

myPopChat.prototype.title = function(msg) {
    $('#' + this.dialogId + ' #' + this.dialogTitleId).html(msg);

};

myPopChat.prototype.setBG = function() {
    if (document.getElementById("TB_HideSelect") == null) {
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div>");
    }
    this.overlaySize();

};

myPopChat.prototype.overlaySize = function() {
    if (window.innerHeight && window.scrollMaxY) {
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        yScroll = document.body.offsetHeight;
    }
    $("#TB_overlay").css("height", yScroll + "px");
};


myPopChat.prototype.center = function() {
    var pagesize = this.getPageSize();
    var arrayPageScroll = this.getPageScrollTop();
    var TB_WIDTH = $('#' + this.dialogId).width();
    var TB_HEIGHT = $('#' + this.dialogId).height();
    $('#' + this.dialogId).css({ left: ((pagesize[0] - TB_WIDTH) / 2) + "px", top: (arrayPageScroll[1] + ((pagesize[1] - TB_HEIGHT) / 2)) + "px" });
    this.overlaySize();

};


myPopChat.prototype.getPageSize = function() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;

    arrayPageSize = new Array(w, h)
    return arrayPageSize;
};


myPopChat.prototype.getPageScrollTop = function() {
    var yScrolltop;
    if (self.pageYOffset) {
        yScrolltop = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        yScrolltop = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScrolltop = document.body.scrollTop;
    }
    arrayPageScroll = new Array('', yScrolltop)
    return arrayPageScroll;
};

myPopChat.prototype.clearLayer = function() {
    clearInterval(this.auto);
    $('#smilelayer,#alertBg,#Editor,#friendLayer').remove();
};

myPopChat.prototype.close = function() {
    var self = this;
    $('#' + this.dialogId).fadeOut("fast",
    function() {
        clearInterval(self.auto);
        $('#' + this.dialogId + ',#TB_overlay,#TB_HideSelect,#smilelayer,#alertBg,#Editor,#friendLayer').remove();
    });
    return false;
};