var ws = {};
var client_id = 0;
var userlist = {};
var GET = getRequest();
var face_count = 19;
var send_user_list = Array();
var allHistoryList = Array();
var HistoryList = Array();


$(document).ready(function () {
    //使用原生WebSocket
    if (window.WebSocket || window.MozWebSocket) {
        ws = new WebSocket(webim);
    }
    //使用flash websocket
    else if (webim.flash_websocket) {
        WEB_SOCKET_SWF_LOCATION = "/static/flash-websocket/WebSocketMain.swf";
        $.getScript("/static/flash-websocket/swfobject.js", function () {
            $.getScript("/static/flash-websocket/web_socket.js", function () {
                ws = new WebSocket(webim);
            });
        });
    }
    //使用http xhr长轮循
    else {
        ws = new Comet(webim);
    }
    initRemote();
    listenEvent();
});
function sendHeardMessage(){
    var msg = "?";
    ws.send(msg);
}
function listenEvent() {
    /**
     * 连接建立时触发
     */
    ws.onopen = function (e) {a
        console.log(e.data);
        var msg = {"method":"join","key":key};
        ws.send($.toJSON(msg));
    };

    //有消息到来时触发
    ws.onmessage = function (e) {
       // var message = $.evalJSON(e.data);
        console.log(e.data);
        if(e.data!='!'){
            var message =JSON.parse(e.data);
            // console.log(message);
            var cmd = message.method;
            if (cmd == 'connection')
            {
                if(message.data.status == 1)
                {
                    //alert('connection ok');
                }
            }
            else if (cmd == 'fromMsg')
            {
                showNewMsg(message.data);
            }
        }


    };

    /**
     * 连接关闭事件
     */
    ws.onclose = function (e) {
        $(document.body).html("<h1 style='text-align: center'>连接已断开，请刷新页面重新登录。</h1>");
    };

    /**
     * 异常事件
     */
    ws.onerror = function (e) {
        $(document.body).html("<h1 style='text-align: center'>服务器[" + webim +
            "]: 拒绝了连接. 请检查服务器是否启动. </h1>");
        console.log("onerror: " + e.data);
    };
}
var down=0;   //设置全局变量down，用来记录ctrl是否被按下；
document.onkeydown = function (e) {
    e = e || window.event;
    if(e.keyCode==17){
        down=1;      //ctrl按下
    }
    if(e.keyCode==13){
        if(down==1){
            document.getElementById("msg_content").value+= '\r\n';
            down=0;     //换行后记得将全局变量置为1，否则enter将变成换行，失去发送功能
        }else{
            sendMsg($('#msg_content').val(),'text')    //执行按钮发送的功能
        }

    }

    //var ev = document.all ? window.event : e;
    //if (ev.keyCode == 13) {
    //    sendMsg($('#msg_content').val(), 'text');
    //    return false;
    //} else {
    //    return true;
    //}
};
function getActiveId() {
    var active_id = $('.active:eq(0)').attr('id');
    return active_id;
}
function getActiveFd() {
    var fd = $('.active:eq(0)').attr('fd');
    return fd;
}
function getActiveUserid() {
    var userid = $('.active:eq(0)').attr('userid');
    return userid;
}
function getAvatar(){
    var active_id = $('.active:eq(0)').attr('id');
    if(active_id=='inroom_0'){
        return avatarleadermessage;
    }else{
        var src=$('.active:eq(0) img').attr('src');;
        return src;
    }
}
/**
 *
 *  Base64 encode / decode
 *
 *  @author haitao.tu
 *  @date   2010-04-26
 *  @email  tuhaitao@foxmail.com
 *
 */

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;
    }
}
function addHistoryList(meg, useridType) {
    var userid = meg[useridType];
    if (HistoryList[userid] == undefined) {
        HistoryList[userid] = new Object();
        HistoryList[userid]['history'] = new Array();
        // HistoryList[dataObj.history[i]['to_userid']]=new Object();
    }
    HistoryList[userid]['history'].push(meg);
}
var activeMessageUsers = Array();
function addSend_user_list(userid) {
    var user = new Object();
    user['userid'] = userid;
    user['fd'] = $('#inroom_' + userid).attr('fd');
    user['username'] = $('#inroom_' + userid).attr('username');
    send_user_list.push(user);
}
function seeMessage(userid) {
    $("#inroom_" + userid + "  img").attr('src', avatarworkermessage);
    $("#inroom_" + userid).addClass('not_read');
    initRemote();
}
function initRemote(){
    var notReadCount=$('.not_read').size();
    if(notReadCount>0){
        $('.top_hide .r_p_common_extent').addClass('r_p_kefu');
      // parent.onShowMsg(1);
    }else{
        $('.top_hide .r_p_common_extent').removeClass('r_p_kefu');
     //   parent.onShowMsg(0);
    }
}
function removeMessage(userid) {
    $useridSrc = $("#inroom_" + userid + " img").attr('src');
    ;
    if ($useridSrc == avatarleadermessage) {
        $("#inroom_" + userid + " img").attr('src', avatarleaderonline);
    }
    if ($useridSrc == avatarworkermessage) {
        $("#inroom_" + userid + " img").attr('src', avatarworkeronline);
    }
    if ($useridSrc == avatarofflinemessage) {
        $("#inroom_" + userid + " img").attr('src', avataroffline);
    }
    $("#inroom_" + userid).removeClass('not_read');
    initRemote();
    ws.send($.toJSON({cmd: 'updateMessage', to_userid: userid, from_userid: user.userid}));
}
var sendUser=new Object();
function selectUser(user){
    var sendData=new Object();
    sendUser=user;
    if(user.fromId==memberId){
        sendData={
            data:{
                fromType:user.fromType,
                toId:user.toId,
                toType:user.toType
            }
        };
    }else{
        sendData={
            data:{
                fromType:user.toType,
                toId:user.fromId,
                toType:user.fromType
            }
        };
    }
    sendData.data.key=key;
    $.ajax({
        type:"POST",
        url:"/message/get", //路径
        data:sendData,
        dataType:"json",
        success:function(data){
            console.log(data);
            if(data.status=='fail'){
                console.log(data.shortMessage);
            }
            console.log(data.responseContent.messages.list);
            for (var i = 0; i < data.responseContent.messages.list.length; i++) {
                if(data.responseContent.messages.list[i]['fromId']==memberId){
                    data.responseContent.messages.list[i]['fromUserName']=data.responseContent.fromUserName;
                    data.responseContent.messages.list[i]['fromAvatar']=data.responseContent.fromAvatar;
                    data.responseContent.messages.list[i]['toUserName']=data.responseContent.toUserName;
                    data.responseContent.messages.list[i]['toAvatar']=data.responseContent.toAvatar;
                }else{
                    data.responseContent.messages.list[i]['fromUserName']=data.responseContent.toUserName;
                    data.responseContent.messages.list[i]['fromAvatar']=data.responseContent.toAvatar;
                    data.responseContent.messages.list[i]['toUserName']=data.responseContent.fromUserName;
                    data.responseContent.messages.list[i]['toAvatar']=data.responseContent.fromAvatar;
                }
                showNewMsg(data.responseContent.messages.list[i]);
            }
        }
    });
    return false;
}

/**
 * 显示所有在线列表
 * @param dataObj
 */
function showOnlineList(dataObj) {
    for (var i = 0; i < dataObj.list.length; i++) {
        $('#inroom_' + dataObj.list[i].userid).attr('fd', dataObj.list[i].fd);
        $('#inroom_' + dataObj.list[i].userid).addClass('online');
        $('#inroom_' + dataObj.list[i].userid).attr('userid', dataObj.list[i].userid);
        $('#inroom_' + dataObj.list[i].userid + ' img').attr('src', avatarworkeronline);
        $('#inroom_' + dataObj.userid).parent().find('h2').after($('#inroom_' + dataObj.userid));
        //$('#left-userlist').preappend($('#inroom_' + dataObj.list[i].userid));
        //$('#left-userlist h2:eq(0)').after($('#inroom_' + dataObj.list[i].userid));
        userlist[dataObj.list[i].userid] = dataObj.list[i].name;
    }
    childrenLength=0;
    var childrenLength=$('.online').length;
    $('#children_count').html(childrenLength);
    // $('#left-userlist').prepend(li);
    // $('#userlist').html(option);
    //for (var i = 0; i < dataObj.list.length; i++) {
    //    li = li + "<li id='inroom_" + dataObj.list[i].fd + "'>" +
    //    "<a href=\"javascript:selectUser('"
    //    + dataObj.list[i].fd + "')\">" + "<img src='" + dataObj.list[i].avatar
    //    + "' title='" + dataObj.list[i].name + "' width='50' height='50'></a></li>";
    //
    //    userlist[dataObj.list[i].fd] = dataObj.list[i].name;
    //
    //    if (dataObj.list[i].fd != client_id) {
    //        option = option + "<option value='" + dataObj.list[i].fd + "' id='user_" + dataObj.list[i].fd + "'>"
    //            + dataObj.list[i].name + "</option>"
    //    }
    //}
    //$('#left-userlist').html(li);
    //$('#userlist').html(option);
}
function initUsersHistory(dataObj) {
    var msg;
    if (debug) {
        console.dir(dataObj);
    }
    for (var i = 0; i < dataObj.history.length; i++) {
        if (HistoryList[dataObj.history[i]['to_userid']] == undefined) {
            HistoryList[dataObj.history[i]['to_userid']] = new Object();
        }
        if (HistoryList[dataObj.history[i]['from_userid']] == undefined) {
            HistoryList[dataObj.history[i]['from_userid']] = new Object();
        }
        if (dataObj.history[i]['to_userid'] != user.userid) {
            if (HistoryList[dataObj.history[i]['to_userid']].hasOwnProperty('history')) {
                HistoryList[dataObj.history[i]['to_userid']]['history'].push(dataObj.history[i]);
            } else {
                HistoryList[dataObj.history[i]['to_userid']]['history'] = Array();
                HistoryList[dataObj.history[i]['to_userid']]['history'].push(dataObj.history[i]);
            }

        }
        if (dataObj.history[i]['from_userid'] != user.userid) {

            if (HistoryList[dataObj.history[i]['from_userid']].hasOwnProperty('history')) {
                HistoryList[dataObj.history[i]['from_userid']]['history'].push(dataObj.history[i]);
            } else {
                HistoryList[dataObj.history[i]['from_userid']]['history'] = Array();
                HistoryList[dataObj.history[i]['from_userid']]['history'].push(dataObj.history[i]);
            }
        }
    }

}

function showLastMessage(msg){
        if (msg.time) {
                time_str = GetDateT(dataObj.time)
         }else {
                time_str = GetDateT();
        }
        var content='';
        if(msg.type='image'){
            content='图片';
        }else{
            content=msg.data;
        }
        var minicontent=content.substr(0,6);
        minicontent=minicontent+'...';
        $('#inroom_'+msg.userid+" p:eq(1)").html(minicontent);
        $('#inroom_'+msg.userid+" span:eq(0)").html(time_str);
}
/**
 * 显示所有在线列表
 * @param dataObj
 */
function showHistory(dataObj) {
    var msg;
    if (debug) {
        console.dir(dataObj);
    }
    for (var i = 0; i < dataObj.history.length; i++) {
        msg = dataObj.history[i]['msg'];
        if (!msg) continue;
        msg['time'] = dataObj.history[i]['time'];
        msg['user'] = dataObj.history[i]['user'];
        if (dataObj.history[i]['type']) {
            msg['type'] = dataObj.history[i]['type'];
        }
        if (msg['channal'] < 10) {
            msg['channal'] = 3;
        }
        msg['to_username'] = dataObj.history[i]['to_username'];
        showNewMsg(msg);
    }
}
function changeChildrenCount(count,type){
    var chilcount=$('#children_count').html();
    chilcount=parseInt(chilcount);
    if(type=='add'){
        $('#children_count').html(chilcount+count);
    }
    if(type=='reduce'){
        $('#children_count').html(chilcount-count);
    }
}
/**
 * 当有一个新用户连接上来时
 * @param dataObj
 */
function showNewUser(dataObj) {
    userlist[dataObj.userid] = dataObj.name;
    changeChildrenCount(1,'add');
    $('#inroom_' + dataObj.userid + " a").css('color', 'yellowgreen');
    $('#inroom_' + dataObj.userid).attr('fd', dataObj.fd);
    $('#inroom_' + dataObj.userid).parent().find('h2').after($('#inroom_' + dataObj.userid));
   // $('#left-userlist h2:eq(0)').after($('#inroom_' + dataObj.userid));
    // $('#left-userlist').prepend($('#inroom_' + dataObj.userid));
    var src = $('#inroom_' + dataObj.userid + " img:eq(0)").attr('src');
    if (src != undefined && src == avatarofflinemessage) {
        $('#inroom_' + dataObj.userid + " img:eq(0)").attr('src', avatarworkermessage);
    } else {
        $('#inroom_' + dataObj.userid + " img:eq(0)").attr('src', avatarworkeronline);
    }
    for (useri in send_user_list) {
        if (dataObj.userid == send_user_list[useri]['userid']) {
            send_user_list[useri]['fd'] = dataObj.fd;
        }
    }
    //$('#left-userlist').prepend(
    //    "<li id='inroom_" + dataObj.fd + "'>" +
    //        '<a style="color:yellowgreen;" href="javascript: selectUser(\'' + dataObj.fd + '\')">' + dataObj.name+"</a></li>");

}
var lasttime='';
/**
 * 显示新消息
 */
function showNewMsg(dataObj) {
    console.log(dataObj);
    var content;
    var contentLeftBegin = dataObj.fromUserName+'说：<div class="message_accept clear" style="border-radius: 10px;"><img style="border-radius: 40px;width:80px;height: 80px;" class="left" src="'+dataObj.fromAvatar+'" alt=""><p class="message_text left">';
    var contentEnd = '</p> </div>';
    var contentRightBegin='<div class="message_send clear" style="text-align: right"><img style="border-radius: 40px;width:80px;height: 80px;" class="right" src="'+dataObj.fromAvatar+'"  alt=""> <p class="message_text right">"'+dataObj.fromUserName+'"说：';
    content = xssFilter(dataObj.message.content);

    var fromId = dataObj.fromId;


    content = parseXss(content);

    var time_str;

    if (dataObj.time) {
        time_str = GetDateT(dataObj.time)
    } else {
        time_str = GetDateT();
    }
    time_str='<p class="history_time">'+time_str+'</p>';
    $("#msg-template .msg-time").html(time_str);
    if (fromId == 0) {
        $("#msg-template .userpic").html("");
        $("#msg-template .content").html(
            "<span style='color: green'>【系统消息】</span> " + content);
    }
    else {
       var allContent=contentLeftBegin;
        if(dataObj.fromId==memberId){
            allContent=contentRightBegin;
        }
        allContent+=content;
        allContent+=contentEnd;
        //var html=allContent;
        //$("#msg-template .content").html(html);
    }

    if(time_str!=lasttime){
        lasttime=time_str;
        $("#chat-messages").append(time_str);
    }

    $("#chat-messages").append(allContent);
    $('#chat-messages')[0].scrollTop = 1000000;
}

function xssFilter(val) {
    val = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\x22/g, '&quot;').replace(/\x27/g, '&#39;');
    return val;
}

function parseXss(val) {
    for (var i = 1; i < 20; i++) {
        val = val.replace('#' + i + '#', '<img src="/data/src/images/face/' + i + '.gif" />');
    }
    val = val.replace('&amp;', '&');
    return val;
}

function GetDateT(time_stamp) {
    var d;
    d = new Date();

    if (time_stamp) {
        d.setTime(time_stamp * 1000);
    }
    var h, i, s;
    h = d.getHours();
    i = d.getMinutes();
    s = d.getSeconds();

    h = ( h < 10 ) ? '0' + h : h;
    i = ( i < 10 ) ? '0' + i : i;
    s = ( s < 10 ) ? '0' + s : s;
    return h + ":" + i + ":" + s;
}

function getRequest() {
    var url = location.search; // 获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);

        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            var decodeParam = decodeURIComponent(strs[i]);
            var param = decodeParam.split("=");
            theRequest[param[0]] = param[1];
        }

    }
    return theRequest;
}

//function selectUser(userid) {
//    $('#userlist').val(userid);
//}

function delUser(fd, userid) {
    //$('#user_' + fd).remove();
    $('#inroom_' + userid).attr('fd', -1);
    $('#inroom_' + userid + " a").removeAttr('style');
    $("#inroom_" + userid + "  img").attr('src', avataroffline);
    var parent_id= $('#inroom_' + userid).parent().attr('id');
    if(parent_id=='left-userlist'){
        changeChildrenCount(1,'reduce');
    }
    delete (userlist[fd]);
}
//群发信息
function addMessage(msg) {
    msg.channal = 11;
    var curentMessage = JSON.parse(JSON.stringify(msg));
    var active_id = getActiveId();
    if (active_id == ("inroom_" + msg.to_userid)||active_id==("inroom_0")) {
        showNewMsg(msg);
    } else {
        var oneHistory = new Object();
        oneHistory['from_userid'] = user.userid;
        oneHistory['msg'] = curentMessage;
        oneHistory['time'] = Date.parse(new Date());
        oneHistory['to_userid'] = msg.to_userid;
        oneHistory['to_username'] = msg.to_username;
        oneHistory['type'] = msg.type;
        oneHistory['user'] = user;
        oneHistory['username'] = user.username;
        addHistoryList(oneHistory, 'to_userid');
    }
}
function sendMsg(content, type){
    var msg = {};
    if (typeof content == "string") {
        content = content.replace(" ", "&nbsp;");
    }
    if (!content) {
        return false;
    }
    msg.key=key;
    if(memberId==sendUser.fromId){
        msg.fromId=sendUser.fromId;
        msg.fromUserName = sendUser.fromUserName;
        msg.fromType=sendUser.fromType;
        msg.fromUserId=sendUser.fromUserId;
        msg.fromAvatar=sendUser.fromAvatar;
        msg.message = {
            type:1,
            title:content,
            content:content,
        };
        msg.toId = sendUser.toId;
        msg.toUserId = sendUser.toUserId;
        msg.toUserName = sendUser.toUserName;
        msg.toType=sendUser.toType;
        msg.toAvatar=sendUser.toAvatar;
    }else{
        msg.fromId=sendUser.toId;
        msg.fromUserName = sendUser.toUserName;
        msg.fromType=sendUser.toType;
        msg.fromUserId=sendUser.toUserId;
        msg.fromAvatar=sendUser.toAvatar;
        msg.message = {
            type:1,
            title:content,
            content:content,
        };
        msg.toId = sendUser.fromId;
        msg.toUserId = sendUser.fromUserId;
        msg.toUserName = sendUser.fromUserName;
        msg.toType=sendUser.fromType;
        msg.toAvatar=sendUser.fromAvatar;
    }
    msg.messageType=msg.message.type;
    msg.messageTitle=msg.message.title;
    msg.messageContent=msg.message.content;
    msg.messageThumb="";
    msg.messageUrl="";
    msg.messageHref="";
    msg.messagePrice=1;
console.log(msg);
    showNewMsg(msg);
    var sendData=Object();
     sendData.data=msg;
    sendData.data.key=key;
    sendData.method='sendMsg';
    //console.log(sendData);
    ws.send($.toJSON(sendData));
    $('#msg_content').val('');
    return false;
}

function sendMsg_qf(content, type) {
    var msg = {};

    if (typeof content == "string") {
        content = content.replace(" ", "&nbsp;");
    }

    if (!content) {
        return false;
    }
    msg.cmd = 'message';
    msg.from = client_id;
    // msg.to = $('#userlist').val();
    msg.channal = 1;
    msg.data = content;
    msg.users = send_user_list;
    msg.type = type;
    msg.userid = user.userid;
    msg.username = user.username;
    msg.avatar = avatarworkeronline;
    ws.send($.toJSON(msg));
    for (useri in send_user_list) {
        msg.to = send_user_list[useri]['userid'];
        msg.to_username = send_user_list[useri]['username'];
        addMessage(msg);
        //showNewMsg(msg);


    }

    //if ($('#userlist').val() == 0) {
    //    msg.cmd = 'message';
    //    msg.from = client_id;
    //    msg.channal = 0;
    //    msg.data = content;
    //    msg.users=send_user_list;
    //    msg.type = type;
    //    ws.send($.toJSON(msg));
    //}
    //else {
    //    msg.cmd = 'message';
    //    msg.from = client_id;
    //    msg.to = $('#userlist').val();
    //    msg.channal = 1;
    //    msg.data = content;
    //    msg.users=send_user_list;
    //    msg.type = type;
    //    ws.send($.toJSON(msg));
    //}

    $('#msg_content').val('')
}

$(document).ready(function () {
    var a = '';
    for (var i = 1; i < 20; i++) {
        a = a + '<a class="face" href="#" onclick="selectFace(' + i + ');return false;"><img src="/data/src/images/face/' + i + '.gif" /></a>';
    }
    $("#show_face").html(a);
});

(function ($) {
    $.fn.extend({
        insertAtCaret: function (myValue) {
            var $t = $(this)[0];
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            }
            else if ($t.selectionStart || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                this.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
            }
            else {
                show_face
                this.value += myValue;
                this.focus();
            }
        }
    })
})(jQuery);

function selectFace(id) {
    var img = '<img src="/data/src/images/face/' + id + '.gif" />';
    $("#msg_content").insertAtCaret('#' + id + '#');
    closeChatFace();
}

function showChatFace() {
    $("#chat_face").attr("class", "chat_face chat_face_hover");
    $("#show_face").attr("class", "show_face show_face_hovers");
}

function closeChatFace() {
    $("#chat_face").attr("class", "chat_face");
    $("#show_face").attr("class", "show_face");
}

function toggleFace() {
    $("#chat_face").toggleClass("chat_face_hover");
    $("#show_face").toggleClass("show_face_hovers");
}

