    /**
     * @date 2015-11-15
     * @author liangh
     * @name 直播私聊
     *
     */

    // 静态域
MT.STATIC_HOST = window.MT.STATIC_HOST || "http://static-fast.talk-fun.com";

// 自定义表情包
var basePath = "http://"+window.document.domain+"/cooperation/default/live-pc/css/img/emotions",
    SD_EMOTIONS_PACKAGE = {
        '[fd]': basePath+'/emotion.fd.gif',
        '[gz]': basePath+'/emotion.gz.gif',
        '[hx]': basePath+'/emotion.hx.gif',
        '[jy]': basePath+'/emotion.jy.gif',
        '[kl]': basePath+'/emotion.kl.gif',
        '[lg]': basePath+'/emotion.laugh.gif',
        '[qu]': basePath+'/emotion.question.gif',
        '[tx]': basePath+'/emotion.tx.gif',
        '[ag]': basePath+'/feedback.agreed.png',
        '[fl]': basePath+'/rose.up.png'
    };

    // 加载模版
    var tplLoadState = false;
    (function(){
        var tplURL = "http://"+window.document.domain+"/open/cooperation/default/live-pc/tpl/modules.html?"+Math.random();//"http://open."+window.document.domain.split(".")[1]+".com/open/maituo_v2/js/vod/tpls/base.html";
        $("#template_loader").load(tplURL, function(){
            tplLoadState = true;
            var data={};
            var html =template('private_mod_chat',data);
            $("body").append(html);
            PT.privateChat.init(); 
        });
    })(window);

    // vars
    var $ = window.jQuery,
        __Event = "click",
        PT = window.PT || {};

    /**
     * @初始化执行
     */
    PT.privateChat = {

           // 默认值
        defaults: {
            curTab: 0, //当前tab的指针 0/1...
            chatCount: 0, //聊天计数
            maxChatSize: 150, //聊天区信息限制
            sendTimeLimit: 2000, //聊天时间限制
            canSend: true //是否可发送信息
        },
       // 目标元素
       $target: $(".private_chat"),
        /*初始化*/
        init:function(){
            var that=this;
            that.userListClick();
            that.bindEvents();
            that.closeBox();
           /* that.roleStyle();*/

        },
        // 渲染聊天信息
        renderChat: function(ret){
            // process...
            var that = this,
                d = ret,
                status = " "+d.role,
                isMe = d.xid === MT.me.xid,
                isHide = "block",
                avatar = HTSDK.room.setAvatar(d),
                chatMsg = "",
                isSuper = HTSDK.room.isAdmin(d.role),
                tpl = '';


            // 自己
            if(isMe){
                if(d.role !== "admin" && d.role !== "spadmin"){
                    status = " self";
                }else{
                    status = " self_"+d.role;
                }
            }else{
                status = " "+d.role;
            }
            // 是否显示聊天
            if(!isSuper && that.defaults.showAdminonly){
                isHide = "none";
            }
            // 表情替换{表情包 key: value, 聊天内容}
            var renderMsg = HTSDK.tools.ubb2img(window.SD_EMOTIONS_PACKAGE, d.msg);
            // 管理员添加链接
            var role="admin";
            if(role === "admin" || role === "spadmin"){
                chatMsg = HTSDK.tools.text2link(renderMsg);
            }else{
                chatMsg = renderMsg;
            }
            // 模版数据
            var chatData = {
                isShow: isHide,
                d: d,
                time: HTSDK.tools.convertTimestamp(d.time),
                avatar: avatar,
                status: status,
                chatMsg: chatMsg
            };
            // render
            if(HTSDK.room.templateLoad){
                tpl = template("private_chat_infor", chatData);
            }
            // exports
            return tpl;
        },
          // 发送聊天
        emitChat: function(){
            var that = this,
                _HT = HTSDK.room._HT,
                tools = HTSDK.tools,
                action = MT.getLiveState(),
                $chat = $('#chat_send_bottom'),
                $chatCon = $("#private_text"),
                $chatVal = $.trim($chatCon.val());
            // 直播未开始
            if(action !== "start"){
                tools.showComtip($chatCon, "还没上课哟...");
                return false;
            }
            // 禁止为空
            if($chatVal.length === 0){
                HTSDK.tools.showComtip($chatCon, "请输入内容...");
                return false;
            }
            // 过滤回车
            $chatCon.val($chatVal.replace(/\r/g, ""));
            // 检查字数
            if(tools.charLength($chatVal) > 150){
                tools.showComtip($chatCon, "不能超过150个字符");
                return false;
            }
            // 发表时间限制
            if(!this.defaults.canSend){
                tools.showComtip($chatCon, "请在2秒后发言...");
                return false;
            }
            // clear content
            $chatCon.val("");
            $chatCon.focus();

            // send chat post
            _HT.emit("chat:send", {msg: $chatVal}, function(retval){
                if(retval.code === 0){
                    var chatRender = that.onPrivateChat(retval.data);
                    //$btnCloseUlist.click();
                }else{
                    tools.showComtip($chatCon, retval.msg);
                }
                that.defaults.canSend = false;
                setTimeout(function(){
                    that.defaults.canSend = true;
                }, that.defaults.sendTimeLimit);
            });
        },

         // 检查聊天DOM数据
       checkChatSize: function(){
        var chatSize = $("#right_center > div").size();
        if(chatSize > this.defaults.maxChatSize){
            $("#right_center > div").eq(0).remove();
         }
        },
        // 接收聊天信息
        onPrivateChat: function(ret){
            // 截取聊天信息
            var that = this,
                $chatHall = $("#right_center"),
                _tpl = this.renderChat(ret);
            // append
            $chatHall.append(_tpl);
            if(that.role=="user"){
                 $(".uname").show();            
            }else if(that.role=="admin") {
                 $(".chat_detail").removeClass("s_detail");
                 $(".chat_detail").addClass("t_detail");
                 $(".uinfo").each(function(index, val) {
                   var role=$(this).data("role");
                   if(role=="admin") {
                      $(this).find('img').removeClass("savatar_right"); 
                      $(this).find('img').addClass("tavatar_left");
                      $(this).find('.uname').show(); 
                      $(this).next(".chat_con").find('p').removeClass("sright_p");
                      $(this).next(".chat_con").find('p').addClass("tleft_p");
                      $(this).next(".chat_con").find('em').removeClass("sarrow_right");
                      $(this).next(".chat_con").find('em').addClass("tarrow_left");
                      $(this).find('.uname span').removeClass("suname_right");
                      $(this).find('.uname span').addClass("tuname_left");
                   }else if(role=="student") {
                       $(this).find('.uname').hide();   
                       $(this).find('img').addClass("savatar_right"); 
                       $(this).find('img').removeClass("tavatar_left");
                       $(this).next(".chat_con").find('p').addClass("tright_p");
                       $(this).next(".chat_con").find('p').removeClass("sleft_p");
                       $(this).next(".chat_con").find('em').removeClass("sarrow_left");
                       $(this).next(".chat_con").find('em').addClass("tarrow_right");                      
                   }
                });  
            }


            /*// 统计未读信息
            that.checkNew();*/
            // 滚动底部
            $chatHall.scrollTop($(".private_right").height());
            // 检查DOM
            that.checkChatSize();
        },

        /*不同的角色弹出对应的弹出框 */
        roleStyle:function(role){
            var that=this;
            that.role=role;
            if(role=="admin"){
                $(".private_chat").removeClass('schat');
                $(".private_chat").addClass('tchat');
                $(".private_left").removeClass("s_left");
                $(".private_left").addClass("t_left");
                $(".private_right").removeClass("s_right");
                $(".private_right").addClass("t_right");
                $(".right_center").removeClass("s_center");
                $(".right_center").addClass("t_center");
                $("#private_text").removeClass("s_textarea");
                $("#private_text").addClass("t_textarea");
                $("#user_list li").removeClass("s_li"); 
                $("#user_list li").addClass("t_li"); 
            }else{
                $(".uname").show();
            }
        },
        
        /*左侧栏点击列表*/
        userListClick:function(){
            $("#user_list li").each(function(index, val) {
                $(this).click(function(event) {
                   $("#user_list li").removeClass('click_bg');
                   $(this).addClass('click_bg'); 
                   var username=$(this).find('.username').text();
                   $(".chat_user").html(username);
                });
            });
        },
        /*关闭私聊弹框*/
        closeBox:function(){
            $(".close_icon").click(function(){
                  $(".private_chat").hide();  
            });
        },

        /*事件绑定*/
        bindEvents:function(){
            var that=this,
                __Event="click",
                $emoticon= that.$target.find(".emoticon"),
                $privateText=$("#private_text"),
                $privateSendBtn=$("#private_sendBtn"),
                $popEmo =$("#pop_emotis");
                // 表情绑定
                $(".emoticon").on(__Event,function(){
                    that.showEmoti(this);
                });
             
               $popEmo.on(__Event, "li", function(){
                    that.bindEmotiEvents(this);
                });

               $(window).on(__Event, function(e){
                    if($(e.target).hasClass("emoticon") || $(e.target).hasClass("emotion_btn")){
                        return false
                    }else{
                        $('#pop_emotis').removeClass("show");

                    };
                });

                  // 发送聊天(回车事件)
                $privateText.on("keydown", function(e){
                    if(e.keyCode === 13){
                        that.emitChat();
                        e.preventDefault();
                        return false;
                    }
                });
                // 发送聊天(点击按钮)
                $privateSendBtn.on(__Event, function(){
                    that.emitChat();
                });
        },
         // 显示表情
        showEmoti: function(e){
            var $t = $(e),
                that = this,
                _li = '',
                _ul = '',
                $eitems = $('#eitem'),
                $econ = $('#pop_emotis');
            // reset
            $econ.css({
                "left": $t.offset().left - 9,
                "top": $t.offset().top - 78
            });
            if($econ.hasClass("show")){
                $econ.removeClass("show");
            }else{
                $econ.addClass("show");
            }
            //items
            if($eitems.find("li").size() > 0){
                return false;
            }
            //插入表情库
            var $emtg = $('#pop_emotis'),
                face = window.SD_EMOTIONS_PACKAGE;
            for (var emoti in face) {
                _li += '<li data-eid="'+emoti+'"><img src="'+face[emoti]+'"/></li>';
            };
            $eitems.append(_li);
            $econ.addClass("show");
            setTimeout(function(){
                that.eisShow = true;
            },1000);
        },
             // 绑定表情事件
        bindEmotiEvents: function(emo){
            var that = this,
                $tg = $(emo);
            //UBB2string
            var _val = $tg.data('eid'),
                _el = document.getElementById("private_text");
            MT.tools.insertPosition(_el, _val);     
            $("#pop_emotis").removeClass("show");
            $(_el).focus();
        },

};

