"use strict";

// 白名单
var whiteList = ["11279"];

/**
 * [HTSDK扩展对象]
 */
var HTSDK = window.HTSDK || {};

HTSDK.controller = {
    // 模块加载完成
    initModules: function(callback){
        // 模版辅助方法
        HTSDK.view.helper();
        // 聊天
        HTSDK.modChat.init();
        // 问答
        HTSDK.modQuestion.init();
        // 在线用户
        HTSDK.modOnlines.init();
        // 左侧
        HTSDK.modSider.init();
        // 播放器
        HTSDK.player.init();
        // 底部工具栏
        HTSDK.footer.init();
        //评分
        HTSDK.score.init();
        // 回调
        if(callback){
            // DOM执行后
            callback();
        }
    },
    // 白名单测试
    specialProcess: function(){
        if(MT.tools.in_array(window.partner_id, whiteList)){
            $("#live_tools").find(".help").remove();
            //document.title = "云讲堂-直播"
            var title = document.title;
            //var specialTitle = title.substring(2);
            var specialTitle = title.replace(title,"云讲堂-直播");
                document.title = specialTitle;
        }
    },
    // 房间(SDK)加载完成
    onRoomLoaded: function(){
        var MT = window.MT;
        // 公告
        HTSDK.modSider.notify(MT.announce.notice);
        
        // 问答
        HTSDK.modQuestion.getQuestionList();
        
        // set init.
        $(".live_uinfo .nickname").html(MT.me.nickname);
        HTSDK.room.liveDuration(0);
        if(MT.zhubo){
            $(".live_uinfo .roomname").html(MT.zhubo.nickname);
            HTSDK.modSider.authorCard(MT.zhubo);
        }
        
        // 插件
        HTSDK.plugins.init();
        
        // 设置默认滚动通知
        HTSDK.plugins.rollNotice(MT.announce.roll);
        
        // 管理员设置
        HTSDK.room.adminRender();
        
        // 设置工具
        HTSDK.tools.SDKTOOLS = MT.tools;
        HTSDK.room.checkFlash();
        
        // 白名单特殊设置
        this.specialProcess();
    }
};

// 聚合工具🔧
HTSDK.tools = {
    SDKTOOLS: MT.tools,
    // 字符字数检查
    charLength: function(string){
        var intLength = 0;
        for (var i = 0; i < string.length; i++) {
            if ((string.charCodeAt(i) < 0) || (string.charCodeAt(i) > 255)) 
                intLength = intLength + 2;
            else{
                intLength = intLength + 1;
            }   
        } 
        return intLength;
    },
    // 转换链接
    text2link: function(_string){
        var reg = /(http:\/\/[\w.\/]+)(?![^<]+>)/gi;
        _string = _string.replace(reg, '<a href="$1" target="_blank">$1</a>');
        return _string;
    },
    // 转换QQ
    text2QQ: function(_string){
        var reg = /(QQ:^(\d)*$)/gi;
        _string = _string.replace(reg, '<a href="$1" target="_blank">$1</a>');
        return _string;
    },
    // UBB转表情(img)
    ubb2img: function(_package, _string){
        return MT.tools.ubb2img(_package, _string);
    },
    // 聊天区公告
    chatNotify: function(notify, isDiy){
        var $tg = $("#mod_chat_hall"),
            msg = "";
        if(!isDiy){
            msg = '<span class="mod_notify">'+notify+'</span>';
        }else{
            msg = notify;
        }
        $tg.append(msg);
        HTSDK.tools.scrollToBottom("chat");
    },
    // 公共提示标签
    showComtip: function (e, msg){
        var $t = e,
            that = this,
            pubtimer = that.pubtimer,
            $econ = $('#pop_tips');
        clearTimeout(that.pubtimer);
        if(!$t){
            return;
        }
        // reset
        $econ.css({
            "left": $t.offset().left - 6,
            "top": $t.offset().top - 35
        });
        $econ.show();
        // 插入信息
        $econ.find("p").html(msg);
        // 隐藏
        that.pubtimer = setTimeout(function (argument) {
            $econ.find("p").html("");
            $econ.hide();
        }, 2000);
    },
    // 滚屏
    scrollToBottom: function(type, xid){
        var that = this,
            isMe = false,
            $chatHall = $("#mod_chat_scroller"),
            $quesHall = $("#mod_questions_con");
        if(xid){
            isMe = (MT.me.xid == xid);
        }
        if(type === "chat"){
            if(!HTSDK.modChat.chatScrollLock || isMe){
                $chatHall.scrollTop($("#mod_chat_hall").height());
            }
        }else if(type === "question"){
            if(!HTSDK.modQuestion.quesScrollLock || isMe){
                $quesHall.scrollTop($("#mod_ques_scroller").height());
            }
        }
        return false;
    },
    // 时间转换
    convertTimestamp: function(timestamp) {
        var d = new Date(timestamp * 1000),   // timestamp 2 milliseconds
            yyyy = d.getFullYear(),
            mm = ('0' + (d.getMonth() + 1)).slice(-2),  // Months are zero based. Add leading 0.
            dd = ('0' + d.getDate()).slice(-2),         // Add leading 0.
            hh = d.getHours(),
            h = hh,
            min = ('0' + d.getMinutes()).slice(-2),     // Add leading 0.
            ampm = 'AM',
            time;

        // ie: 2013-02-18, 8:35 AM  
        //time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
        time = h + ':' + min;
        return time;
    },
    // 转换时间格式
    dateFormat: function(date, format){
        // date
        date = new Date(date);
        var map = {
            "M": date.getMonth() + 1, //月份 
            "d": date.getDate(), //日 
            "h": date.getHours(), //小时 
            "m": date.getMinutes(), //分 
            "s": date.getSeconds(), //秒 
            "q": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        format = format.replace(/([yMdhmsqS])+/g, function(all, t){
            var v = map[t];
            if(v !== undefined){
                if(all.length > 1){
                    v = '0' + v;
                    v = v.substr(v.length-2);
                }
                return v;
            }
            else if(t === 'y'){
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    },
    // Fix firefox css:prosition
    fixFirefoxProsition: function(){
        var ua = navigator.userAgent.toLocaleString().toLocaleLowerCase();
        if(ua.indexOf("firefox") > 0){
        (function($) {
            var div = document.createElement('div'),  
                rposition = /([^ ]*) (.*)/;
            if(div.style.backgroundPositionX !== '') {  
                $(['X', 'Y']).each(function( i, letter ) {  
                    var property = 'backgroundPosition' + letter,  
                        isX = letter == 'X';  
                    $.cssHooks[property] = {  
                        set: function(elem, value) {  
                            var current = elem.style.backgroundPosition;  
                            elem.style.backgroundPosition = (isX? value + ' ' : '' ) + (current? current.match(rposition)[isX+1] : '0') + (isX? '' : ' ' + value);  
                        },  
                        get: function(elem, computed) {  
                            var current = computed?  
                                $.css(elem, 'backgroundPosition') :  
                                elem.style.backgroundPosition;  
                            return current.match(rposition)[!isX+1];  
                        }  
                    };  
                    $.fx.step[property] = function(fx) {  
                        $.cssHooks[property].set(fx.elem, fx.now + fx.unit);  
                    }  
                });  
            }
            div = null;
            })(jQuery);
        }
    }
};

// 播放器
HTSDK.player = {
    defaults: {
        player: null,
        camera: null,
        isShowCamera: false
    },
    // 重置
    resize: function(){

    },
    // 普通事件绑定
    bindEvents: function(){
        
    },
    // 清除切换
    clearToggle: function(){
        var that = this;
        //that.defaults.camera.setSize(280, 210);
        $(that.defaults.player).removeAttr("style");
        $(that.defaults.camera).removeAttr("style");
    },
    /*--xin 结构下的播放器区换位*/
    togglePlayerPosition: function(flag){
        var that = this,
            toggleName = "toggle_video_ppt",
            camera = this.defaults.camera,
            player = this.defaults.player;
        // 切换标志
        //that.defaults.toggled = flag;
        if(flag){
            that.defaults.toggled = true;
            $(".camera_warp").addClass(toggleName);
            $(".mod_main_player_wp").addClass(toggleName);
        }else{
            that.defaults.toggled = false;
            $(".camera_warp").removeClass(toggleName);
            $(".mod_main_player_wp").removeClass(toggleName);
        }
        that.clearToggle();
        that.setPlayerInit();
    },
    // 摄像头层
    cameraLayer: function(flag){
        this.defaults.isShowCamera = flag;
        this.isShowCamera();
    },
    isShowCamera: function(){
        var $camera = $(this.defaults.camera),
            flag = this.defaults.isShowCamera;
        if($camera){
            if(flag){
                $camera.addClass("show");
                $(".mod_sider_top").removeClass('show_author');
                if($(".mod_sider_top").hasClass("camera")){
                    $(".mod_sider_top").css("height",210);
                    $(".mod_question_wrap .mod_ques_hall").css("top",304);
                }
            }else{
                $camera.removeClass("show");
            }
        }
    },
    // 播放器事件绑定
    playerEvents: function(){
        var that = this,
            mainPlayer = that.defaults.player;
        // 重置高宽
        $(window).on("resize", function(){
            that.setPlayerInit();
        });
        that.setPlayerInit();
    },
    // 初始化设置播放器
    setPlayerInit: function(){
        var that = this,
            mainPlayer = that.defaults.player,
            el = document.getElementById("toggled_camera_center"),
            curChgObj = {},
            player = that.defaults.player,
            camera = that.defaults.camera,
            rataio = that.getRatio(el);
            that.clearToggle();
            HTSDK.view.roomView.toggleShow();
            // xin 重置播放器
            if(that.defaults.toggled){
                var _camleft = ($(el).width() - rataio.width) / 2,
                    _camtop = ($(el).height() - rataio.height) /2;
                // 切换后
                $(camera).css({
                    width: rataio.width,
                    height: rataio.height,
                    left: _camleft,
                    marginTop: _camtop
                });
                player.setSize(280, 210);
                camera.setSize(rataio.width, rataio.height);
            }else{
                camera.setSize(280, 210);
                player.setSize(rataio.width, rataio.height);
            }
        },
    // 获取比例
    getRatio: function(el){
        el = $(el).get(0) || document.getElementById("toggled_camera_center");
        var _fw = el.clientWidth,
            _fh = el.clientHeight,
            ratio = 4/3, //keep ratio of 4:3;
            _w = 0,
            _h = 0;
        // 大于正常比例
        if((_fw/_fh) > ratio){
            _w = _fh*ratio;
            _h = _fh;
        }else{
            _w = _fw;
            _h = _fw/ratio;
        }
        return {
            width: _w,
            height: _h
        };
    },
    // 渲染主播播放器
    mainPlayerView: function(){
        var $el = $("#toggled_camera_center"),
            rataio = this.getRatio($el);
    },
    
    // 渲染摄像头
    cameraView: function(){
        this.defaults.camera.setSize(280, 210);
    },

    // 声音设置
    setVolume: function(volume){
        var camera = this.defaults.camera,
            player = this.defaults.player;
        // 摄像头
        if(camera){
            camera.cameraSetVolume(volume);
        }
        // 大播放器
        if(player){
            player.setVolume(volume);
        }
    },

    // 设置主播播放器
    setPlayer: function(player,callback){
        this.defaults.player = player;
        this.syncLoad();
        // 自定义设置
        if(window.location.href.indexOf("&quite") > 0){
            player.setVolume(0);
        }

        if( typeof callback === "function"){
            callback();
        }
    },
    // 设置摄像头
    setCamera: function(camera){
        this.defaults.camera = camera;
        this.isShowCamera();
        this.syncLoad();
    },
    // 异步加载
    syncLoad: function(){
        var that = this,
            defaults = this.defaults;
        if(defaults.camera && defaults.player){
            that.setPptVideoToggle(); // 渲染二分屏
            that.mainPlayerView();
            that.cameraView();
            that.playerEvents(); // 渲染初始化事件
        }
    },
    //房间加载完二分屏初始化
    setPptVideoToggle: function(){
        // window.pptDisplay 二分屏变量
        // 0: 开启二分屏模式
        // 1: 关闭二分屏模式
        var pptDisplay = parseInt(window.pptDisplay, 10) === 0,
            $toggledCamera = $("#toggled_camera_center"),
            $toggledPPT = $(".mod_main_player_wp"),
            $toggledBtn = $(".tools_toggle_ppt");
        // 是否切换 & 渲染样式
        if(pptDisplay){
            this.defaults.toggled = true;
            $(".mod_sider_top").removeClass("show_author");
            $("#room").addClass("show_video");
            $("#live_tools .tools_toggle_ppt").remove();
            $("#live_tools .tools_toggle_camera").remove();
            $(".mod_main_player_wp").addClass('toggle_video_ppt');
            $("#toggled_camera_center").addClass('toggle_video_ppt');
            $("#mod_col_main .toggle_video_ppt").addClass("ppt_hidden");
        }else{
            $("#room").addClass('close_video');
        }
    },
    init: function(){
        // todo...
        this.bindEvents();
    }
};

// 模型层(数据)
HTSDK.mode = {
    // todo...
};

// 在线用户
HTSDK.modOnlines = {
    defaults: {
        isRender: false,
        gag_id: "" //被禁言的ID
    },
    robot: [],
    memberList: {},
    _count:'',
    // 在线人数
    total: function(count){
        var $member = $("#members"),
            isAdmin = HTSDK.room.isAdmin();
        if(isAdmin){
            //加特殊用户
                var _count = count+this.robot.length;
                $member.show().html("("+_count+")");
                HTSDK.modOnlines._count = _count;
        }else{
            $member.remove();
        }

    },
    // 渲染用户
    renderList: function(list){

        // 已渲染用户列表?
        if(this.defaults.isRender || !this.memberList){
            return false;
        }
        var ulist = {};
        if(list){
            ulist = list;
        }else{
            ulist = this.memberList;
        }
        // 插入
        var _tplData = {},
            tpl_userlist = "";
        for (var i = 0, j = ulist.length; i < j; i++) {
            _tplData = {
                me: MT.me.xid == ulist[i].xid ? "self" : "",
                d: ulist[i],
                avatar: HTSDK.room.setAvatar(ulist[i])
            };
            tpl_userlist += template("tpl_append_oneuser", _tplData);
        };
        // render
        $("#mod_member_list").html(tpl_userlist);
        
        this.defaults.isRender = true;  
        //初始化将被禁言用户的标识显示出来
        if( MT.me.role == "admin" || MT.me.role =="spadmin"){
            $("#mod_member_list").find('li').each(function(i,e){
                $(e).find('#grant').each(function(k,el){
                    if($(el).data("chat") == 0){
                        $(this).addClass("ban");
                    }
                });
            });
        }

        //xin -初始化语音加载后的处理用户
        if(this.defaults.isRender && $("#mod_col_right").hasClass('has_voice')){
            //处理初始化列表
            var val = HTSDK.voice.vmode;
            HTSDK.voice.resetStuViews(val);
            //初始化 - 多用户加入
            if( MT.me.role == "admin" || MT.me.role =="spadmin"){
                $("#mod_member_list").find('li').each(function(i,e){
                    $(e).find('#grant').each(function(k,el){
                        if($(el).data("chat") == 0){
                            $(this).addClass("ban");
                        }
                        if( $(el).data("voice") == 1){
                            $(el).parents().find("#voenable").addClass("voice_disable");
                        }
                    });
                });
            }
        }

    },
    // 插入用户排序
    // 
    // 
    sortUser: function(user, tpl){
        var $memberlist = $("#mod_member_list"),
            role = user.role;
        // 超级管理员
        if(role === "spadmin"){
            $memberlist.prepend(tpl);
            return false;
        }
        // 管理员
        else if(role === "admin"){
            if($memberlist.find(".role_spadmin").size() > 0){
                $memberlist.find(".role_spadmin").after(tpl);
            }else{
                $memberlist.prepend(tpl);
            }
        }
        //honorguest嘉宾
        /*else if (role === "honorguest") {
            if($memberlist.find(".role_admin").size() > 0){
                $memberlist.find(".role_admin").after(tpl);
            }else{
                $memberlist.prepend(tpl);
            }
        }*/
        else{
            $memberlist.append(tpl);
        }
    },
    // 用户离线
    memberLeave: function(user) {
        // 普通用户
        if($('#user_'+user.xid).size() > 0){
            $('#user_'+user.xid).remove();
        }
        // 语音用户
        if($("#voice_user_"+user.xid).size() > 0){
            $("#voice_user_"+user.xid).remove();
        }
    },

    // 禁止/允许发言
    chatAccess: function(flag, retval){
        // 是否本人
       /* if(MT.me.xid == retval.xid){
            //系统消息
            HTSDK.tools.chatNotify('通知：你已被管理员禁止文字聊天。');
        }*/
        // 管理员
        if(MTSDK.admin.isAdmin()){
            HTSDK.tools.chatNotify('通知：['+retval.nickname+']已被管理员禁止文字聊天。');
            //系统消息
        }
    },
    // 踢出房间
    memberkick: function(retval){
        //系统消息
        HTSDK.tools.chatNotify('通知：['+retval.nickname+'] 已经被管理员踢出房间。');
    },

    memberJoin: function(user) {

        var that = this,
            $mcr = $("#mod_col_right"),
            vmodeVal = HTSDK.voice.vmode,
            chatEnable = user.member.chat.grant,
            voiceEnable = user.member.voice.grant;

        // 普通用户
        if($("#user_"+user.member.xid).size() === 0){
            var _tplData = {
                d: user.member,
                avatar: HTSDK.room.setAvatar(user.member)
            };
            var tplMember = template("tpl_append_oneuser", _tplData);
            that.sortUser(user.member, tplMember);

            if(user.member.chat.enable ==0){
                $("#user_"+user.member.xid).find("#grant").addClass("ban");
            }
            
            // 插入语音用户
            if(MTSDK.admin.isAdmin(user.member.role) && vmodeVal == 1){
                var tplVoiceChairman = template("tpl_voice_chairman_addone", _tplData);
                $("#voice_list").append(tplVoiceChairman);
            }

            /*chat{
                enable: 0/1  {0: 默认状态, 1: 允许}
                grant:  0/1  {0: 正常状态, 1: 被禁}
            }*/
            //xin -处理语音模式下，加入人员给加上P的样式
            if( $mcr.hasClass('has_voice')){
                //自由
                if( vmodeVal == 0){
                    $(".mod_members li").find('p').addClass('voice_enable');     
                }
                //xin -主席、麦序、举手初始化加入时
                if( vmodeVal == 1 || vmodeVal == 2 || vmodeVal == 3){
                    $(".mod_members .role_user").find("p").addClass("default");
                }
                //xin -被禁言且管理员才加进去
                if( MT.me.role == "admin" || MT.me.role == "spadmin"){
                    //单用户-加入
                    if( chatEnable == 1){
                        $('#user_'+user.member.xid).find("#grant").addClass("ban").html("禁言");
                    }
                    if( voiceEnable == 1){
                        $('#user_'+user.member.xid).find("p").addClass('voice_disable');
                    }
                }
            }   
        }
    },

    broadcastSetRobot: function(list){
        var _num = this.robot.length,
            _all = this._count,
            _nownum = list.length;
        var count = _all - _num + _nownum;
        HTSDK.modOnlines._count = count;
        $('.robot_user').remove();
        $('#members').html("("+count+")");
        this.robot = list;
        this.setRobotlist();
    },
    setRobotlist: function(){
        var _front = '<li class="role_user robot_user" data-role="user"><img src="http://static-1.talk-fun.com/open/cooperation/default/live-pc/css/img/main/user.png" /><span',
            _front_2 = '<li class="role_user robot_user" data-role="user"><img src="',
            _front_3 = '"/><span',
            _back = '</span><em class="role_tip"></em><p></p><span data-chat="1"></span></li>';
        if(MTSDK.admin.isAdmin()){
             for(var i =0; i< this.robot.length;i++){
                if(this.robot[i].avatar){
                    $('#mod_member_list').append(_front_2+this.robot[i].avatar+_front_3+' class="admin_cur">'+this.robot[i].nickname+' - - R'+_back);
                }else {
                    $('#mod_member_list').append(_front+' class="admin_cur">'+this.robot[i].nickname+' - - R'+_back);
                }
            } 
        }else {
             for(var i =0; i< this.robot.length;i++){
                if(this.robot[i].avatar){
                    $('#mod_member_list').append(_front_2+this.robot[i].avatar+_front_3+' class="admin_cur">'+this.robot[i].nickname+_back);
                }else {
                    $('#mod_member_list').append(_front+'>'+this.robot[i].nickname+_back);
                }
                 
            }   
        }
    },

    init: function(list){
        this.memberList = list;
    }
};


// 左侧区(摄像头, 公告)
HTSDK.modSider = {
    $target: $("#mod_col_left"),
    // 事件绑定
    bindEvents: function(){
        // 信息卡
        var hidePop = function () {
            $(".popup").hide();
        },
        timer = null;

        $(".camera_warp").on("mouseover", function() {
            clearTimeout(timer);
            if(HTSDK.player.defaults.toggled){
                return false;
            }
            if($('.mod_sider_top').hasClass("camera")){
                return false;
            }
            $(".popup").fadeIn(200);
        });
        $(".camera_warp").on("mouseout", function() {
            timer = setTimeout(hidePop, 300);
        });

        /*$(".mod_sider_top").on("mouseover", ".popup", function(e) {
            clearTimeout(timer);
        });
        $(".mod_sider_top").on("mouseout", ".popup", function(e) {
            //hidePop();
        });*/
    },
    // 主播信息卡
    authorCard: function(zhubo){
        /*
        if(!zhubo.intro){
            //return false;
        }*/
        if(zhubo.intro.length === 0){
            zhubo.intro = "老师比较忙，暂未添加简介...";
        }
        var _tplAucard = template("author_card", zhubo);
        
        $(".camera_warp", "#mod_col_left").after(_tplAucard);
    },
    // 公告
    notify: function(notify){
        var _content = "";
        if(notify.content.length === 0){
            // 无消息5秒消失
            _content = "暂无内容...";
            setTimeout(function(){
                $("#mod_chat_hall").removeClass('has_notice');
                $("#mod_notify_con").fadeOut(200);
            }, 5000);
        }else{
            _content = notify.content;
        }
        if(typeof notify.content !== "undefined"){
            $("#mod_notify_con .notify_con").html(_content);
            $("#mod_chat_hall").addClass("has_notice");
            $("#mod_notify_con").fadeIn(200);
        }
    },
    init: function(){
        this.bindEvents();
    }
};

// 结构层
HTSDK.view = {
    defaults: {
        isFlex: {
            left: false,
            right: false
        }
    },
    $target: $("#room"),
    bindEvents: function () {
        var that = this,
            $room = this.$target;
        $room.on("click", ".carousel", function(){
            that.roomView.toggleFlex(this);
        });
    },
    // 注册Tmod模版方法
    helper: function(){
        // 时间转换
        window.template.helper("converTime", function(time){
            return HTSDK.tools.convertTimestamp(time);
        });

        // 获取头像
        window.template.helper("getAvatar", function(user){
            return HTSDK.room.setAvatar(user);
        });

        // 获取语音权限类
        window.template.helper("getVoicePower", function(voice){
            return HTSDK.voice.getVoicePower(voice);
        });

        return false;
    },
    roomView: {
        // 渲染结构
        renderModuls: function(callback){
            // fix FF Position
            HTSDK.tools.fixFirefoxProsition();
            // 左侧
            var left = template("tpl_left_side");
            $("#mod_col_left").html(left);

            // 右侧
            var right = template("tpl_right_side");
            $("#mod_col_right").html(right);

            // 中间
            var right = template("tpl_col_main");
            $("#mod_col_main").html(right);
            
            // pop插入
            var popLottery = template("tpl_lottery_render");
            $("body").append(popLottery);

            // DOM插入完成
            if(callback && typeof callback === "function"){
                callback();
            }
        },
        flexSet: {
            left: 0,
            right: 0
        },
        // 摄像头收缩
        toggleShow: function(){
            var $camera = $(HTSDK.player.defaults.camera),
                $player = $(HTSDK.player.defaults.player);
            if(HTSDK.player.defaults.toggled && HTSDK.view.defaults.isFlex.left){
                $player.addClass("hide");
            }else{
                $player.removeClass("hide");
            }
        },
        /*xin 左右收缩*/
        toggleFlex: function(el){
            var that = this,
                active = HTSDK.view.defaults.isFlex,
                $t = $(el),
                $room = $("#room"),
                $main = $("#mod_col_main"),
                $left = $("#mod_col_left"),
                $right = $("#mod_col_right"),
                $togCam = $(".toggle_carema");
            // change
            if($t.hasClass("left")){
                if($t.hasClass("active")){
                    $room.removeClass("close_left_side");
                    $t.removeClass("active");
                    active.left = false;
                }else{
                    $room.addClass("close_left_side");
                    $t.addClass("active");
                    active.left = true;
                }
                $main.stop().animate({
                    left: that.flexSet.left
                }, 200, function(){
                    HTSDK.player.setPlayerInit();
                    that.toggleShow();
                });
            }else if($t.hasClass("right")){
                if($t.hasClass("active")){
                    $right.show();
                    $room.removeClass("close_right_side");
                    $t.removeClass("active");
                    active.right = false;
                }else{
                    $right.hide();
                    $room.addClass("close_right_side");
                    $t.addClass("active");
                    active.right = true;
                }
                $main.stop().animate({
                    right: that.flexSet.right
                }, 200, function(){
                    HTSDK.player.setPlayerInit();
                });
            }
        }
    },
    init: function(callback) {
        this.roomView.renderModuls(callback);
        this.bindEvents();
    }
};

// 语音模块{自由，主席，麦序，举手}
HTSDK.voice = {
    // 默认语音模式
    vmode: -1,
    // 语音云音量
    vCloudVolume: {
        input: 50,
        output: 50
    },
    // 语音title标记
    sign: {
        // 语音云
        CLOUD_OPEN: "语音云打开",
        // 麦序
        QUEUE_MIC_CONTROL: "控麦",
        QUEUE_MIC_OPEN: "开麦",
        QUEUE_MIC_FORBID: "禁麦",
        QUEUE_MIC_ENABLE: "放麦",
        QUEUE_MIC_LOOT: "抢麦",
        QUEUE_MIC_LEAVE: "下麦",
        // 举手
        HAND_MIC_UP: "我要举手",
        HAND_MIC_LEAVE: "取消举手",
        HAND_MIC_CLEAR: "清空列表",
        HAND_MIC_REMOVE: "移除",
        HAND_MIC_ALLOW: "允许"
    },
    // 语音云启动步骤
    steps: function(step, times){
        var pop = $("#pop_voice_cloud"),
            cover = $("#pop_cover");
        // 只听模式
        if(step){
            $(".vc_tips").fadeIn(200);
        }
        // 强制模式
        else{
            // 启动次数
            if(times){
                times = parseInt(times, 10);
            }else{
                times = 0;
            }
            pop.find(".step").hide();
            
            // 成功启动一次
            if(times > 0){
                pop.find(".step_v1").show();
                pop.find(".top_hd .default").removeClass().addClass("listen");
            }
            // 只听模式
            else if(times < 0){
                pop.find(".step_v5").show();
            }
            // 默认模式
            else{
                pop.find(".step_v3").show();
            }
            cover.fadeIn(200);
            pop.fadeIn(200);
        }
        // if(step){
        //     $(".vc_control").fadeIn(200);
        // }else{
        //     cover.fadeIn(200);
        //     pop.fadeIn(200);
        //     pop.find(".step_v3").show();
        // }
    },
    // 语音云启动成功
    vCloudDone: function(){
        $(".vc_control").fadeIn(200);
        //$(".mod_voice_access_allow").fadeIn(200);
        //$(".mod_voice_access_forbid").hide();
    },
    // 设置语音云音量(客户端)
    setVolume: function(type, volume){
        switch(type){
            // 麦克风
            case "input":
                $("#input_slide").slider({
                    value: volume
                });
                break;
            // 扬声器
            case "output":
                $("#output_slide").slider({
                    value: volume
                });
                break;
        }
    },
    // 切换模式 取到模式的值
    switchVoiceMode: function(_mode, handle){
        // 选中当前
        _mode = parseInt(_mode, 10);
        if(_mode === this.vmode){
            return false;
        }
        // 语音标题
        var that = this,
            modeTitle = ["自由", "主席", "麦序", "举手"];
            $(".cur_mode").html(modeTitle[_mode]);
        // 语音切换提示
        if(handle){
            HTSDK.tools.chatNotify('你把语音模式切换为 ['+modeTitle[_mode]+'] 模式');
        }else{
            if(this.vmodeChange > 0){
                HTSDK.tools.chatNotify('管理员把语音模式切换为 ['+modeTitle[_mode]+'] 模式');
            }
        }

        // 切换模式结构
        var $voiceHd = $(".mod_voice_hd"),
            $voiceBd = $(".tab_voice_state"),
            // 初始化
            $vfree = $voiceBd.find(".vfree"),
            $vchair = $voiceBd.find(".vchair"),
            $vqueue = $voiceBd.find(".vqueue"),
            $vhand = $voiceBd.find(".vhand"),
            // 数据
            $queue = $voiceHd.find(".queue"),
            $hand = $voiceHd.find(".hand"),
            $free = $voiceHd.find(".freedom"),
            $chairman = $voiceHd.find(".chairman"),
            $mode = _mode;

        // 重设View
        that.resetViews($mode);
        switch ($mode){
            // 自由模式
            case 0:
                $free.show();
                $vfree.show();
                that.caseVoiceMode($mode);
                break;
            // 主席模式
            case 1:
                $chairman.show();
                $vchair.hide();
                that.caseVoiceMode($mode);
                break;
            // 麦序
            case 2:
                $vqueue.show();
                $queue.show();
                that.caseVoiceMode($mode);
                break;
            // 举手
            case 3:
                $vhand.show();
                $hand.show();
                that.caseVoiceMode($mode);
                break;
        };
        // 触发事件改变
        if(handle){
            that._HT.emit("voice:mode:change", _mode, function(ret){
                // TODO...
            });
        }
        // set cur vmode
        this.vmodeChange = 1;
        this.vmode = _mode;
    },

    //xin - 抽离一个方法，解决切换模式的类转换
    caseVoiceMode:function(_vmd){
            //xin 成员面板
        var $modList = $("#mod_member_list .role_user");
        if(_vmd == 0){
            //xin -自由
            $("#mod_member_list .role_spadmin").find('p').addClass('voice_enable');
            $("#mod_member_list .role_admin").find('p').addClass('voice_enable');
            $modList.find("p").each(function(i, e) {
                var voGrant = $(e).data("voice");
                    if( voGrant == 1){
                        $(e).addClass("voice_disable");
                    }else{
                        $(e).attr("class","voice_enable");
                    }
            });
        }
        if(_vmd == 1){
            //xin -主席
            $("#mod_member_list .role_spadmin").find('p').addClass('voice_enable');
            $("#mod_member_list .role_admin").find('p').addClass('voice_enable');
                $modList.find("p").each(function(i, e){
                var voGrant = $(e).data("voice");
                    if( voGrant == 1){
                        $(e).addClass("voice_disable");
                    }else{
                        $(e).attr("class","default");
                    }
                });
        }
        if(_vmd == 2 || _vmd == 3){
            $("#mod_member_list .role_spadmin").find('p').addClass('voice_enable');
            $("#mod_member_list .role_admin").find('p').addClass('voice_enable');
            //xin -麦序 ,举手
            $modList.find("p").each(function(i, e){
                var voGrant = $(e).data("voice");
                    if( voGrant == 1){
                        $(e).addClass("voice_disable");
                    }else{
                        $(e).attr("class","default");
                    }
            });
        }
    },

    //xin -取到mode 值初始化学生面板的语音标志样式
    resetStuViews:function(_mode){
            //自由模式
            if( _mode === 0){
                $("#mod_member_list li").find("p").addClass("voice_enable");
                $("#mod_member_list .role_admin").find('p').addClass("default");
                $("#mod_member_list .role_spadmin").find('p').addClass("default");
            }
            //主席模式
            if( _mode == 1 || _mode ==2 || _mode == 3){
                $("#mod_member_list .role_spadmin").find("p").addClass("voice_enable");
                $("#mod_member_list .role_admin").find("p").addClass("voice_enable");
                $("#mod_member_list .role_user").find("p").addClass("default");
            }
    },

    // 重置界面
    resetViews: function(mode){
        var that = this,
            $voice = $('.mod_voice_hd .voice'),
            $voiceHd = $(".mod_voice_hd"),
            $voiceBd = $(".tab_voice_state");

        $voiceHd.find(".voice").hide();
        $voiceBd.find("span").hide();
        $voiceBd.show();

        // 举手重置
        $voice.find(".rahand").html(that.sign.HAND_MIC_UP).removeClass("cur");
        if(MTSDK.admin.isAdmin() && mode == 3){
            $(".cls_hands").show();
        }
        
        // 麦序
        $voice.find(".select_mic .mic").removeClass("cur");
        // $voice.find(".mic_operation").html(that.sign.QUEUE_MIC_FORBID);
        // $voice.find(".mic_control").html(that.sign.QUEUE_MIC_CONTROL);
        $voice.find(".mic_knock").html(that.sign.QUEUE_MIC_LOOT);
    },
    // 改变用户权限
    // voice{
    //    enable: 0/1  {0: 默认状态, 1: 允许}
    //    grant:  0/1  {0: 正常状态, 1: 被禁}
    // }
    setVoicePower: function(xid, voice){
        // voice aceess
        var isME = (MT.me.xid == xid);
        // clear
        var $u = $("#voice_user_"+xid).find(".default");
        // 可说话
        if(voice.enable > 0){
            $u.addClass("voice_enable");
            if(isME){
                $(".mod_voice_access_allow").fadeIn(100);
                $(".mod_voice_access_forbid").hide();
            }
        }
        // 默认不能说话
        else{
            $u.removeClass("voice_disable");
            $u.removeClass("voice_enable");
            if(isME){
                $(".mod_voice_access_allow").hide();
                $(".mod_voice_access_forbid").show();
            }
        }

        // 强制(被禁)
        if(voice.grant > 0){
            $u.addClass("voice_disable");
            if(isME){
                $(".mod_voice_access_allow").hide();
                $(".mod_voice_access_forbid").show();
            }
        }

        // 管理权限
        if(MTSDK.admin.isAdmin()){
            $(".mod_voice_access_forbid").hide();
            $(".mod_voice_access_allow").fadeIn(100);
            return false;
        }
    },
    // 列表权限
    // voice{
    //    enable: 0/1  {0: 默认状态, 1: 允许}
    //    grant:  0/1  {0: 正常状态, 1: 被禁}
    // }
    getVoicePower: function(voice){
        var voiceCls = "";
        if(voice){
            if(voice.enable > 0){
                voiceCls = "voice_enable";
            }else if(voice.grant > 0){
                voiceCls = "voice_disable";
            }
        }
        return voiceCls;
    },
    // 全局
    voiceGlobal: {
        _parent: HTSDK,
        // 语音禁言
        forbidVoice: function(user){
            HTSDK.tools.chatNotify(user.nickname+' 已被管理员禁止语音说话。');
            HTSDK.voice.setVoicePower(user.xid, user.voice);
        },
        // 允许语音说话
        allowVoice: function(user){
            HTSDK.tools.chatNotify(user.nickname+' 已被管理员允许语音说话。');
            HTSDK.voice.setVoicePower(user.xid, user.voice);
        }
    },
    // 谁在说话
    whoSpeaking: function(list){
        var vmode = HTSDK.voice.vmode;
        $("#voice_list li em").removeClass("speaking");
        // 自由模式添加用户
        if(vmode === 0){
            if(list.length > 0){
                var l = {list: list},
                    speaklist = template("tpl_voice_who_speaking", l);
                $("#voice_list").html(speaklist);
                $(".vfree").hide();
                //xin - 成员语音跳动效果
                $("#user_"+list[0].xid).find("p").addClass('speaking');
            }else{        
                $(".vfree").show();
                $("#voice_list").html("");
                //xin
                $("#mod_member_list li p").removeClass('speaking');
            }
        }

        //xin -处理用户停止说话的状态
        if( vmode === 1 || vmode === 2 || vmode === 3){
            $("#mod_member_list li p").removeClass('speaking');
        }

        //xin  -改变当前状态
        for (var i = list.length - 1; i >= 0; i--) {
            if($("#voice_user_"+list[i].xid).size() > 0){
                $("#voice_user_"+list[i].xid).find(".default").addClass("speaking");
                //处理其他模式下的说话状态
                $("#user_"+list[i].xid).find(".voice_enable").addClass('speaking');
            }
        };
    },
    // 主席
    voiceChairman: {
        render: function(list){
            var _l = {
                list: list
            };
            var _tpls = template("tpl_voice_chairman_list", _l);
            $("#voice_list").html(_tpls);
            $(".vchair").hide();
        },
        init: function(list){
            if(list.length > 0){
                this.render(list);
            }
        }
    },
    // 麦序
    voiceQueue: {
        isInit: false,
        _parent: HTSDK,
        _vqhandel: 0,
        // 初始化
        init: function(data){
            if(!this.isInit){
                //this.isInit = true;
                this.control(data);
            }
        },
        // 加入
        join: function(user){
            if(user.code == 0){
                var _user = template("tpl_voice_queue_join_one", user);
                $("#voice_list").append(_user);
                //xin -抢麦
                $("#user_"+user.data.xid).find("p").addClass("voice_enable");
            }else{
                alert(user.msg);
            }
        },
        change: function(list){
            this._parent.voice.queuelist = list;
            if(list.length > 0){
                $(".tab_voice_state .vqueue").hide();
            }else{
                $(".tab_voice_state .vqueue").show();
            }
        },
        // 离开
        leave: function(user){
            if(user.data){
                $("#voice_user_"+user.data.xid).remove();
                //xin -下麦
                $("#user_"+user.data.xid).find("p").removeClass("voice_enable");
                if(user.data.xid == MT.me.xid){
                    $(".mic_knock").html(this._parent.voice.sign.QUEUE_MIC_LOOT).removeClass("cur");
                }
            }
        },
        // 清空
        clear: function(){
            // todo..
            $(".mic_knock").html(this._parent.voice.sign.QUEUE_MIC_LOOT).removeClass("cur");
            $(".tab_voice_state .vqueue").show();
            HTSDK.tools.chatNotify("管理员清空了麦序列表。");
        },
        // 控制
        control: function(retval){
            var that = this,
                sign = that._parent.voice.sign,
                sortAction = "",
                actionHtml = "",
                action = retval.action,
                memberState = retval.memberState;

            // 筛选
            switch(action){
                case "start":
                    sortAction = action;
                    HTSDK.tools.chatNotify("管理员放麦, 麦序首位可以说话。");
                    break;
                case "wait":
                    sortAction = action;
                    break;
                case "pause":
                    sortAction = action;
                    if(retval.current && retval.current.voice.enable === 1){
                        //系统消息
                        HTSDK.tools.chatNotify("管理员控麦。");
                    }else{
                        HTSDK.tools.chatNotify("管理员控麦，首位麦序上的人暂时不能说话。");
                    }
                    break;
                case "open":
                    memberState = action;
                    HTSDK.tools.chatNotify("管理员将频道设置为开启抢麦，可以点击抢麦按钮排队发言。");
                    break;
                case "close":
                    memberState = action;
                    HTSDK.tools.chatNotify("管理员将频道设置为禁止抢麦，暂时无法抢麦。");
                    break;
            };

            // 已禁(控麦, 放麦) [start:放麦 pause:控麦 / close:禁麦 open:开麦]
            if(sortAction){
                //控麦、放麦
                if(sortAction === "start" || sortAction === "wait"){
                    $(".mic_operation").html(sign.QUEUE_MIC_CONTROL).removeClass("cur");
                }else{
                    $(".mic_operation").html(sign.QUEUE_MIC_ENABLE).addClass("cur");
                }
            }

            // 已关(开麦, 禁麦)
            if(memberState){
                if(memberState === "close"){
                    $(".mic_control").html(sign.QUEUE_MIC_OPEN).addClass("cur");
                }else if(memberState === "open"){
                    $(".mic_control").html(sign.QUEUE_MIC_FORBID).removeClass("cur");
                }
            }

            // todo...
            that._vqhandel = 0;
        },
        // 列表
        list: function(list){
            var _l = {
                list: list
            }
            var _list = template("tpl_voice_queue_list", _l);
            $("#voice_list").html(_list);
        },
        // 重置
        reset: function(rlist){
            var _l = {
                list: rlist
            }
            var _list = template("tpl_voice_queue_list", _l);
            $("#voice_list").html(_list);
        },
        // 删除
        emitRemove: function(xid, callback){
            var _HT = this._parent.voice._HT;
            if (window.confirm("你确定要移除该用户？")) {
                _HT.emit('voice:queue:leave', xid, function(retval){
                    if(typeof callback === "function"){
                        callback(retval);
                    }
                });
            }
        },
        // 清空
        emitClear: function(callback){
            var _HT = this._parent.voice._HT;
            if (window.confirm("你确定要清空麦序列表？")) {
                _HT.emit('voice:queue:clear', function(retval){
                    if(typeof callback === "function"){
                        callback(retval);
                    }
                });
            }
        },
        // 加一倍时间
        emitAddtime: function(xid, callback){
            var _HT = this._parent.voice._HT;
            _HT.emit('voice:queue:time', {xid: xid, times: 1}, function(retval){
                if(typeof callback === "function"){
                    callback(retval);
                }
            });
        }
    },
    // 举手
    voiceHand: {
        _parent: HTSDK,
        resetView: function(){
            var size = $("#voice_list").find("li").size();
            if(size === 0){
                $(".vhand").show();
            }
        },
        join: function(user){
            var _user = template("tpl_voice_hand_join_one", user);
            $("#voice_list").append(_user);
        },
        change: function(list){
            if(list){
                if(list.length > 0){
                    $(".tab_voice_state .vhand").hide();
                }else{
                    $(".tab_voice_state .vhand").show();
                }
            }
        },
        leave: function(user){
            var that = this;
            var sign = that._parent.voice.sign;
            if(user.data){
                $("#voice_user_"+user.data.xid).remove();
                if(MT.me.xid == user.data.xid){
                    $(".rahand").removeClass("holding").html(sign.HAND_MIC_UP);
                }
                that.resetView();
            }
        },
        _remove: function(user){
            var that = this;
            var sign = this._parent.voice.sign;
            if(user.data){
                $("#voice_user_"+user.data.xid).remove();
                if(MT.me.xid == user.data.xid){
                    $(".rahand").removeClass("holding").html(sign.HAND_MIC_UP);
                }
                that.resetView();
            }
        },
        clear: function(){
            var that = this;
            var sign = this._parent.voice.sign;
            $(".rahand").removeClass("holding").html(sign.HAND_MIC_UP);
            that.resetView();
            HTSDK.tools.chatNotify("管理员清空了举手列表。");
        },
        reset: function(hlist){
            if(hlist){
                if(hlist.length > 0){
                    $(".tab_voice_state .vhand").hide();
                }
                var _l = {
                    list: hlist
                }
                var _list = template("tpl_voice_hand_list", _l);
                $("#voice_list").html(_list);
            }
        },
        allow: function(user){
            $("#voice_user_"+user.data.xid).find(".operation").addClass("allow");
            //xin -举手
            $("#user_"+user.data.xid).find("p").addClass("p").addClass("voice_enable");
        },
        forbid: function(user){
            $("#voice_user_"+user.data.xid).find(".operation").removeClass("allow");
            //xin -取消举手
            $("#user_"+user.data.xid).find("p").addClass("p").removeClass("voice_enable");
        }
    },
    setMode: function(mode){
        this.vmode = mode;
    },
    getMode: function(){
        return this.vmode;
    },
    getVoiceMenu: function(index){
        var opList = "";
        
        if(index === 0){
            opList += '<li><a data-op="addtime">加一倍时间</a></li>';
        }else{
            opList += '<li><a class="disable" data-op="none" href="javascript:void(0);">加一倍时间</a></li>';
        }

        /*var up = '<li><a data-op="up">上移</a></li>', 
            upHun = '<li><a class="disable" data-op="none" href="javascript:void(0);">上移</a></li>',

            down = '<li><a data-op="down">下移</a></li>',
            downHun = '<li><a class="disable" data-op="none" href="javascript:void(0);">下移</a></li>',

            top = '<li><a data-op="top">调整到2号</a></li>',
            topHun = '<li><a class="disable" data-op="none" href="javascript:void(0);">调整到2号</a></li>';

        if(index > 1){
            opList += up;
        }else{
            opList += upHun;
        }

        if(index > 0 && index < (this.queueSortLength-1)){
            opList += down;
        }else{
            opList += downHun;
        }

        if(index > 1){
            opList += top;
        }else{
            opList += topHun;
        }*/

        opList += '<li><a data-op="out">从麦序中移除</a></li>';
        opList += '<li><a data-op="clear">清空麦序</a></li>';

        // <li data-op="add_time">加一倍时间</li>
        // <li data-op="turn_up">上移</li>
        // <li data-op="trun_down">下移</li>
        // <li data-op="move_to_second">移到2号位置</li>
        // <li data-op="remove">移除</li>
        // <li data-op="clear">清空列表</li>
        // <li data-op="disable">禁止说话</li>

        return opList;
    },
    // [管理]语音操作菜单
    voiceMenu: function(target){
        var curVmode = this.getMode(),
            that = this,
            $parent = $(target),
            index = $parent.index();

        var renHtml = {
            html: that.getVoiceMenu(index)
        };

        $parent.off();

        if(curVmode !== 2){
            return false;
        }

        // toggle
        $parent.on("mouseout", function(){
            that.timer = setTimeout(function(){
                $("body").popboxCloseAll();
                $parent.removeClass("active");
            }, 200);
        });
        $parent.on("mouseover", function(){
            clearTimeout(that.timer);
        });

        // pop menu
        $parent.popBox({
            position: 'left',
            content: template("tpl_voice_pop_menu", renHtml),
            callback: function(){
                var top = $parent.offset().top;
                $(".admin_list").css({
                    top: top + 10
                });
                $(".admin_list").on("mouseover", function(){
                    clearTimeout(that.timer);
                });
                // 语音操作
                if($(".pop_side_operation").hasClass("voice")){
                    $(".pop_side_operation").on("click", "li", function(){
                        that.voiceOperation(this, $parent);
                    });
                }
            }
        });
    },
    // [管理]语音权限操作
    voiceOperation: function(target, parent){
        var curVmode = this.getMode(),
            that = this,
            $li = $(target),
            xid = parent.data("xid"),
            op = $li.find("a").data("op"),
            index = parent.index();

        // 操作
        switch(op){
            // 增加时间
            case "addtime":
                that.voiceQueue.emitAddtime(xid, function(){
                    $("body").popboxCloseAll();
                });
                break;
            // 剔除
            case "out":
                that.voiceQueue.emitRemove(xid, function(){
                    $("body").popboxCloseAll();
                });
                break;
            // 清空
            case "clear":
                that.voiceQueue.emitClear(function(){
                    $("body").popboxCloseAll();
                });
                break;
        };

    },
    // 设置语音云音量(type volume)
    setVcloudVolume: function(type, volume){
        var _HT = this._HT;
        if(type === "input"){
            _HT.get("voice:set:input:volume", function(callback){
                callback(volume, function(){
                    // todo...
                });
            });
        }else if(type === "output"){
            _HT.get("voice:set:output:volume", function(callback){
                callback(volume, function(){
                    // todo...
                });
            });
        }
    },
    // 事件绑定
    bindEvents: function(){
        var that = this,
            isVoiceFree = false,
            $voicePop = $("#pop_voice_cloud"),
            _HT = that._HT;

        //下拉选择
        $(".cur_mode").on("click",function(){
            if($(this).hasClass("admin")){
                $(".select_mode").toggle();
            }
        });

        // 语音权限管理
        $("#voice_list").on("click", "li", function(){
            if(!MTSDK.admin.isAdmin()){
                return false;
            }
            that.voiceMenu(this);
        });

        // 启动语音云
        $voicePop.find(".voice_lanuch").on("click", function(){
            _HT.get("open:voice", function(){
                $voicePop.find(".step").hide();
                $voicePop.find(".step_v2").show();
            });
        });

        // 启动只听模式
        $voicePop.find(".voice_lanuch_rtmp").on("click", function(){
            _HT.get("voice:set:listen", function(){
                $voicePop.hide();
                $("#pop_cover").hide();
                $(".mod_voice_control .vc_tips").fadeIn(100);
            });
        });

        // 关闭弹窗
        $voicePop.find(".voice_cls_btn").on("click", function(){
            $voicePop.hide();
            $("#pop_cover").hide();
            $(".mod_voice_control .vc_tips").fadeIn(100);
            // 关闭后默认进入只听模式
            _HT.get("voice:set:listen",function(){
                // todo...
            });
        });

        // 下载语音云
        $voicePop.find(".voice_down").on("click", function(){
            //$voicePop.hide();
            $voicePop.find(".step").hide();
            $voicePop.find(".step_v4").show();
            $voicePop.find(".top_hd .default").removeClass().addClass("down");
        });

        // 语音云提示弹窗
        $(".vc_tips_txt em").on("click", function(){
            HTSDK.voice.steps(false);
        });

        // 切换语音模式
        $(".voice_selector").on("click", "li", function(){
            var $title = $(this).data("title"),
                $mode = $(this).data("mode");
            // 模式
            $(".cur_mode").html($title);
            $(".select_mode").toggle();
            that.switchVoiceMode($mode, true);
            that.setMode($mode);
        });

        // 点击操作举手 
        $(".vhand .up").on("click", function(){
            $(".rahand").click();
        });
        //抢麦
        $(".vqueue .up").on("click", function(){
            $(".mic_knock").click();
        });
        

        // 模式隐藏
        $("body").on("click", function(e) {
            // body...
            if(!$(e.target).hasClass("cur_mode")){
                $(".select_mode").hide();
            }
        });

        // ==== @语音云控件 ====
        // Shift按下
        $(window).on("keydown", function(e){
            if(e.keyCode == 16){
                _HT.get("voice:speaker:press", function(){
                    $(".shift_say").html("松开结束").addClass("cur");
                });
            }
        });
        // Shift弹起
        $(window).on("keyup", function(e){
            if(e.keyCode == 16){
                _HT.get("voice:speaker:bounce", function(){
                    $(".shift_say").html("按住说话").removeClass("cur");
                });
            }
        });

        // shift说话[切换自由]
        $(".shift_say").on("click",function(){
            $(this).hide();
            // 开启自由说话
            _HT.get("voice:free", function(ret){
                $(".free_speak").show();
            });
        });

        // 自由[切换shift]
        $(".free_speak").on("click",function(){
            $(this).hide();
            // 开启shift说话
            _HT.get("voice:close", function(ret){
                $(".shift_say").show();
            });
        });

        // 设置
        $(".mod_voice_control .setting").on("click", function(){
            _HT.get("voice:setting", function(){
                // done
            });
        });

        /**
         * 麦序事件绑定
         */
        // 禁，控，抢
        // 抢麦
        var $queueMic = $(".select_mic");
        $queueMic.on("click", ".mic_knock", function(){
            var $that = $(this);
            // 10s 后才能操作
            if($that.hasClass("locking")){
                return false;
            }
            // 下
            if($(this).hasClass("cur")){
                _HT.emit("voice:queue:leave", "", function(user){
                    // todo...
                    MT.tools.debug("离开麦序");
                    $that.html(that.sign.QUEUE_MIC_LOOT).removeClass("cur");
                    that.voiceQueue.leave(user);
                });
            }else{
                // 10s 解锁
                $that.addClass("locking");
                setTimeout(function(){
                    $that.removeClass("locking");
                }, 10000);
                // 抢
                _HT.emit("voice:queue:join", function(ret){
                    // todo...
                    MT.tools.debug("加入麦序");
                    if(ret.code == 0){
                        that.voiceQueue.join(ret);
                        $that.html(that.sign.QUEUE_MIC_LEAVE).addClass("cur");
                    }else{
                        alert(ret.msg);
                    }
                });
            }
        });

        // 禁麦 & 开麦
        $queueMic.on("click", ".mic_control", function(){
            var $that = $(this);
            if($(this).hasClass("cur")){
                // 开
                _HT.emit("voice:queue:control", "open", function(ret){
                    // todo...
                    $that.html(that.sign.QUEUE_MIC_FORBID).removeClass("cur");
                });
            }else{
                // 禁
                _HT.emit("voice:queue:control", "close", function(){
                    // todo...
                    $that.html(that.sign.QUEUE_MIC_OPEN).addClass("cur");
                });
            }
        });

        // 控麦 & 放麦
        $queueMic.on("click", ".mic_operation", function(){
            var $that = $(this);
            if($(this).hasClass("cur")){
                // 控
                _HT.emit("voice:queue:control", "start", function(ret){
                    $that.html(that.sign.QUEUE_MIC_CONTROL).removeClass("cur");
                });
                
            }else{
                // 放
                _HT.emit("voice:queue:control", "pause", function(){
                    $that.html(that.sign.QUEUE_MIC_ENABLE).addClass("cur");
                });
            }
        });

        /**
         * 举手事件绑定
         */
        $(".rahand").on("click", function(){
            // 放下
            if($(this).hasClass("holding")){
                _HT.emit("voice:hand:leave", function(ret){
                    // alert(ret);
                });
                $(this).html(that.sign.HAND_MIC_UP).removeClass("holding");
            }else{
                // 举手
                _HT.emit("voice:hand:up", function(ret){
                    // alert(ret)
                });
                $(this).html(that.sign.HAND_MIC_LEAVE).addClass("holding");
            }
        });

        // 清空举手
        $(".cls_hands").on("click", function(){
            // 清空举手队列
            MTSDK.admin.adminDo.clearVoiceHands(_HT, function(){
                $("#voice_list").html("");
            });
        });

        $("#voice_list").on("click", ".operation", function(){
            var isAdmin = MTSDK.admin.isAdmin($(this).data("role"));
            if(isAdmin || !MTSDK.admin.isAdmin()){
                return false;
            }
            var $that = $(this),
                xid = $(this).data("xid");
            if($(this).hasClass("allow")){
                _HT.emit('voice:hand:forbid', xid, function(retval){
                    $that.removeClass("allow");
                });
            }else{
                _HT.emit('voice:hand:allow', xid, function(retval){
                    $that.addClass("allow");
                });
            }
        });

        // 伴奏[切换]
        $(".accomp").on("click",function(){
            var $me = $(this);
            // 关闭伴奏
            if($me.hasClass("active")){
                _HT.get("voice:accompany:stop", function(){
                    $me.removeClass("active");
                    $me.html("音乐伴奏");
                });
            }
            // 开启伴奏
            else{
                _HT.get("voice:accompany:open", function(){
                    $me.addClass("active");
                    $me.html("伴奏开启");
                });
            }
        });


        // 输入 & 输出音量
        var $input = $(".mod_voice_control .input"),
            $output = $(".mod_voice_control .output");

        // 麦音量显示
        $input.on("mouseover",function(){
            $("#mic_click").show();
        });
        // 麦音量隐藏
        $input.on("mouseout",function(){
            $("#mic_click").hide();
        });

        // 输出音量显示
        $output.on("mouseover",function(){
            $("#volunm_click").show();
        });
        // 输出音量隐藏
        $output.on("mouseout",function(){
            $("#volunm_click").hide();
        });

        // get:vCloudVolume
        // 音量toggle
        // Input Volume
        $input.on("click", function(e){
            // 开启
            if($(this).hasClass("mute")){
                $(this).removeClass("mute");
                $("#input_slide").slider({
                    value: that.vCloudVolume.input
                });
                that.setVcloudVolume("input", that.vCloudVolume.input);
            }
            // 静音
            else{
                $(this).addClass("mute");
                that.vCloudVolume.input = $("#input_slide").slider("value");
                $("#input_slide").slider({
                    value: 0
                });
                that.setVcloudVolume("input", 0);
            }
        });
        // Output Volume
        $output.on("click", function(e){
            // 开启
            if($(this).hasClass("mute")){
                $(this).removeClass("mute");
                $("#output_slide").slider({
                    value: that.vCloudVolume.output
                });
                that.setVcloudVolume("output", that.vCloudVolume.output);
            }
            // 静音
            else{
                $(this).addClass("mute");
                that.vCloudVolume.output = $("#output_slide").slider("value");
                $("#output_slide").slider({
                    value: 0
                });
                that.setVcloudVolume("output", 0);
            }
        });
        
        // 麦克风音量控制
        $("#input_slide").slider({
            orientation: "vertical",
            range: "max",
            min: 0,
            max: 100,
            step: 1,
            animate: true,
            value: 50,
            stop: function(e, res){
                var volume = res.value;
                if(volume === 0){
                    $(".mod_voice_control .input").addClass("mute");
                }else{
                    $(".mod_voice_control .input").removeClass("mute");
                }
                _HT.get("voice:set:input:volume", function(callback){
                    callback(volume, function(){
                        // todo...
                    });
                });
            }
            /*slide: function(e, res){
                var volume = res.value;
                _HT.get("voice:set:input:volume", function(callback){
                    callback(volume, function(){
                        // todo...
                    });
                });
            }*/
        });

        // 扬声器音量控制
        $("#output_slide").slider({
            orientation: "vertical",
            range: "max",
            min: 0,
            max: 100,
            step: 1,
            animate: true,
            value: 50,
            stop: function(e, res){
                var volume = res.value;
                if(volume === 0){
                    $(".mod_voice_control .output").addClass("mute");
                }else{
                    $(".mod_voice_control .output").removeClass("mute");
                }
                _HT.get("voice:set:output:volume", function(callback){
                    callback(volume, function(){
                        // todo...
                    });
                });
            }
            // slide: function(e, res){
            //     var volume = res.value;
            //     _HT.get("voice:set:output:volume", function(callback){
            //         callback(volume, function(){
            //             // todo...
            //         });
            //     });
            // }
        });
    },
    // 渲染
    render: function(){
        //$(".one_voice_funbtn").hide();
        $("#mod_col_right").addClass("has_voice");
        var tplVoice = template("tpl_mod_voice");
        $("#mod_col_right").prepend(tplVoice);
        $(".mod_voice_control").fadeIn(100);
        $("body").append(template("tpl_voice_cloud_pop"));
        // 模块渲染完成
        this.renderAll = true;
    },
    init: function(type){
        // 1: 强语音模式
        // 2: 弱互动
        // 3: 自由模式
        //var type = window.modetype;
        if(type == 1){
            if(this.renderAll){
                return false;
            }
            this.render();
        }
    }
};

// 聊天区
HTSDK.modChat = {
    // 默认值
    defaults: {
        curTab: 0, //当前tab的指针 0/1...
        chatCount: 0, //聊天计数
        showAdminonly: false, //只看老师聊天
        maxChatSize: 150, //聊天区信息限制
        sendTimeLimit: 2000, //聊天时间限制
        canSend: true //是否可发送信息
    },
    gagListUrl: 'http://'+window.location.host+'/live/member.php',//禁言列表
    // 目标元素
    $target: $("#mod_col_right"),
    // 事件绑定
    bindEvents: function(){
        var that = this,
            $tab = that.$target.find(".tab_change li"),
            $emitChat = $("#emit_chat_txt"),
            $postChatBtn = $("#post_chat_btn"),
            $emotionBtn = that.$target.find(".emotion_btn"),
            $popEmo = $("#pop_emotis"),
            $chatHall = $("#mod_chat_hall"),
            $chatScroll = $("#mod_chat_scroller"),
            $showAdmin = $(".show_adchat"),
            $notify = $("#mod_notify_con"),
            $chatTarget = $(".mod_chat_post textarea");

        var _robotend = true;

        // 聊天禁止滚动
        $chatScroll.scroll(function(){
            var scTop = (this.scrollHeight - $(this).scrollTop()) - $(this).height();
            if(scTop > 100){
                that.chatScrollLock = true;
            }else{
                that.chatScrollLock = false;
            }
        });

        // 清屏
        $chatScroll.on("mouseover", function(){
            $("#clear_chat").show();
        });

        $chatScroll.on("mouseout", function(){
            $("#clear_chat").hide();
        });

        $("#clear_chat").on("click", function(){
            $chatHall.html("");
        });
        
        // 聊天区tab切换
        $tab.on("click", function(){
            var $num = $(".tab_change .numbers");
            var index = $(this).index();
            // 如果当前选中“聊天:0”新信息隐藏
            if(index === 0){
                $num.hide();
                that.defaults.chatCount = 0;
                HTSDK.tools.scrollToBottom("chat");
            }else{
                var  memberlist = HTSDK.modOnlines.memberList;
                HTSDK.modOnlines.renderList();

                //设置特殊用户
                if(_robotend){
                    _robotend = false;
                    //todo
                    HTSDK.modOnlines.setRobotlist();
                }
                
                var _MT= HTSDK.room._HT;
                HTSDK.modChat.gagList();  
            }
            if(index === that.defaults.curTab){
                return false;
            }
            var $tabBox = that.$target.find('.chat_tab_box');
            $tab.removeClass("current").eq(index).addClass("current");
            $tabBox.hide().eq(index).fadeIn(100);
            that.defaults.curTab = index;
        });

        // 表情绑定
        $emotionBtn.on("click", function(){
            that.showEmoti(this);
        });
        $popEmo.on("click", "li", function(){
            that.bindEmotiEvents(this);
        });
        $(window).on('click', function(e){
            if($(e.target).hasClass("emoticon") || $(e.target).hasClass("emotion_btn")){
                return false
            }else{
                $('#pop_emotis').removeClass("show");

            };
        });

        // 发送聊天(回车事件)
        $emitChat.on("keydown", function(e){
            if(e.keyCode === 13){
                that.emitChat();
                e.preventDefault();
                return false;
            }
        });

        // 粘贴(截图预览)
        $emitChat.on("paste", function(event){
            // 非管理
            if(MTSDK.admin.isAdmin()){
                MT.chat.onpaste(event, function(photo){
                    var _photo = {
                        _imgUrl: photo
                    };
                    var _tplPhoto = template("tpl_clipboard_con", _photo);
                    $("body").append(_tplPhoto);
                    $("#pop_layer").show();
                });
            }
        });
        // 发送截图
        $("body").on("click", "#clip_btns a", function(e){ 
            var $clipBox = $("#mod_clip_con");
            // 取消
            if($(this).hasClass("btn_default")){
                $clipBox.remove();
                $("#pop_layer").hide();
            }
            // 发送
            if($(this).hasClass("btn_primary")){
                $("#clip_btns").html("发送中...");
                MT.chat.postClipPhoto(function(ret){
                    if(ret.code == 0){  
                        var _msg = "[IMG]"+ret.data.url+"[/IMG]";
                        HTSDK.room._HT.emit("chat:send", {msg: _msg}, function(retval){
                            if(retval.code === 0){
                                that.onChat(retval.data);
                                $clipBox.remove();
                                $("#pop_layer").hide();
                            }
                        });
                    }else{
                        alert(ret.data.msg);
                    }
                });
            }
        });
        // 聊天区预览
        $chatScroll.on("click", ".clip", function(){
            // 大图
            MT.chat.showImageFullSize(this.src, function(src){
                var imgEl = {clipurl: '<img src="'+src+'" />'};
                    $("body").append(template("tpl_clip_preview", imgEl));
            });
        });
        // 关闭截图
        $("body").on("click", "#cls_clip", function(){
            $("#mod_show_clip").remove();
        });

        // 发送按钮
        $postChatBtn.on("click", function(){
            that.emitChat();
        });

        // 绑定获取焦点事件
        $chatTarget.on("focus", function(event) {
            if($(this).val().length > 0){
                $postChatBtn.addClass("active");
            }else{
                $postChatBtn.removeClass("active");
            }
        });

        // 绑定失去焦点事件
        $chatTarget.on("blur", function(event) {
            if($(this).val().length > 0){
                $postChatBtn.addClass("active");
            }else{
                $postChatBtn.removeClass("active");
            }
        });

        // 键盘弹起
        $chatTarget.on("keyup", function (e) {
            if($(this).val().length > 0){
                $postChatBtn.addClass("active");
            }else{
                $postChatBtn.removeClass("active");
            }
        });

        // 只看老师发言
        $showAdmin.on("click", function(e){
            if($(this).hasClass("cur")){
                $(this).removeClass("cur");
                that.defaults.showAdminonly = false;
                that.showAdminChat("all");
            }else{
                $(this).addClass("cur");
                that.defaults.showAdminonly = true;
                that.showAdminChat(0);
            }
        });

        // 公告操作
        $notify.on("click", function(e) {
            var className = e.target.className,
                $that = $(e.target);
            if(className === "close_notice"){
                $(".notice_bg").slideUp(200, function(){
                    $("#mod_chat_hall").removeClass('has_notice');
                });
            }else if(className.indexOf("more") >= 0){
                if($that.hasClass("open")){
                    $that.removeClass("open").html("显示全部");
                    $(".notify_con").removeClass("detail");
                }else{
                    $that.addClass("open").html("收起");
                    $(".notify_con").addClass("detail");
                }
            }
        });
    },
    
    //禁言列表
    gagList: function(){
        var that = this;
        $.ajax({
            type: 'GET',
            data: 'access_token='+window.access_token+'&act=disableList',
            url: that.gagListUrl,
            dataType: "jsonp",
            success: function(ret){
                if(ret && ret.code){
                    if(ret.code == 0){
                        for(var i =0; i< ret.data.length;i++){
                            if(MT.me.role !="user"){
                                $("#user_"+ ret.data[i].xid).find('#grant').addClass('ban');
                            }
                       }   
                    }
                }
            }
        });
    },

    // 只看老师发言
    showAdminChat: function(type){
        var $chatHall = $("#mod_chat_hall");
        if(type === "all"){
            HTSDK.modChat.showAdminonly = false;
            $chatHall.find(".chat_list").show();
            HTSDK.tools.scrollToBottom("chat");
        }else{
            HTSDK.modChat.showAdminonly = true;
            $chatHall.find(".chat_list").hide();
            $chatHall.find('.chat_list').each(function(i, e){
                if($(e).hasClass("admin") || $(e).hasClass("spadmin") || $(e).hasClass("self_admin")){
                    $(e).show();
                }
            });
        }
    },
    // 检查聊天DOM数据
    checkChatSize: function(){
        var chatSize = $("#mod_chat_hall > div").size();
        if(chatSize > this.defaults.maxChatSize){
            $("#mod_chat_hall > div").eq(0).remove();
        }
        //处理聊天区管理功能
        if(MT.me.role === "user"){
            if($('.chat_list').hasClass("user")){
                $(".cp").hide();
            }
        }
    },
    // 显示表情
    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.HT_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("emit_chat_txt");
        MT.tools.insertPosition(_el, _val);
        $("#pop_emotis").removeClass("show");
        $(_el).focus();
    },
    // 渲染截图聊天
    renderClipChat: function(ret){
        var img = '<img src="'+ret.data.url+'" />';
        return img;
    },
    // 渲染聊天信息
    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),
            renderMsg = "",
            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, 聊天内容}
        renderMsg = HTSDK.tools.ubb2img(window.HT_EMOTIONS_PACKAGE, d.msg);
        // 管理员发送操作
        if(d.role === "admin" || d.role === "spadmin"){
            // UBB图片替换
            chatMsg = MT.chat.toHTML(renderMsg);
            //chatMsg = HTSDK.tools.text2link(renderMsg);
        }else{
            chatMsg = renderMsg;
        }
        // 是否显示管理员工具
        var _isShowTools = false;
            if(MTSDK.admin.isAdmin){
                if(d.role === "admin" || d.role === "spadmin"){
                    _isShowTools = false;
                }else{
                    _isShowTools = true;
                }
            }
        // 模版数据
        var chatData = {
            isShow: isHide,
            d: d,
            time: HTSDK.tools.convertTimestamp(d.time),
            avatar: avatar,
            status: status,
            isShowTools: _isShowTools,
            chatMsg: chatMsg
        };
        // render
        if(HTSDK.room.templateLoad){
            tpl = template("tpl_append_chat", chatData);
        }
        // exports
        return tpl;
    },
    // 发送聊天
    emitChat: function(){
        var that = this,
            _HT = HTSDK.room._HT,
            tools = HTSDK.tools,
            action = MT.getLiveState(),
            $chat = $('#mod_chat_post'),
            $chatCon = $("#emit_chat_txt"),
            $chatVal = $.trim($chatCon.val()),
            $btnCloseUlist = $(".btn_close_list"),
            $chatHall = $('#mod_chat_hall');
            //$chatHall = $("#chat_hall");
        
        /*// 直播未开始
        if(window.partner_id && MT.tools.in_array(window.partner_id, whiteList)){
            // 白名单支持不上课聊天
        }else if(action !== "start"){
            tools.showComtip($chatCon, "还没上课哟...");
            return false;
        }*/

        // check-FAQ
        var isMathKey = MTSDK.admin.bindKeywork.targetKey($chatVal);
        if(isMathKey){
            MTSDK.admin.bindKeywork.renderTargetKey();
        }
        // 禁止为空
        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.onChat(retval.data);
                //$btnCloseUlist.click();
            }else{
                tools.showComtip($chatCon, retval.msg);
            }
            /*if(MT.me.role === "user"){
                if($('.chat_list').hasClass("user")){
                    $(".cp").hide();
                }
            }*/
            that.defaults.canSend = false;
            setTimeout(function(){
                that.defaults.canSend = true;
            }, that.defaults.sendTimeLimit);
        });
    },
    // 接收聊天信息
    onChat: function(ret, type){
        // 截取聊天信息
        var that = this,
            $chatHall = $("#mod_chat_hall"),
            _tpl = "";
        
        // 普通聊天
        //_tpl = this.renderChat(ret);
         
        // append
        //$chatHall.append(_tpl);
        
        // match cmd.
        if(MTSDK.admin.isAdmin(ret.role)){
            var isShoot = MTSDK.admin.operation.specialCmd(ret.msg);
            if(isShoot){
                return false;
            }
        }
        // 插入聊天(公共方法)
        var appendChat = function(){
            var chatRender = that.renderChat(ret);
            $chatHall.append(chatRender);
            // 聊天区显示被禁言图标
            if(ret.chat.enable == 1){
                $(".ban_"+ret.xid).hide();
            }else if(ret.chat.enable == 0 && MT.me.role !="user"){
                $(".ban_"+ret.xid).show();
            }
            

            // 统计未读信息
            that.checkNew();
            // 滚动底部
            HTSDK.tools.scrollToBottom("chat");
            // 检查DOM
            that.checkChatSize();
        };
        
        // 关键词
        var isMathKeys = MTSDK.admin.bindKeywork.targetKey(ret.msg);

        // 是否屏蔽发言
        var isChatDisable = MTSDK.admin.operation.getChatAccess(ret);
        
        // 管理员不做任何屏蔽
        if(MTSDK.admin.isAdmin(ret.role) || MTSDK.admin.isAdmin()){
            appendChat();
        }else{
            // 屏蔽关键词 || 禁止发言
            if(isMathKeys || isChatDisable){
                if(ret.xid == MT.me.xid){
                    appendChat();
                }
            }else{
                appendChat();
            }
        }
    },
    // 聊天区未读信息
    checkNew: function(){
        var $num = $(".tab_change .numbers");
        if(this.defaults.curTab != 0){
            this.defaults.chatCount += 1;
            $num.show();
            $num.html(this.defaults.chatCount);
        }else{
            this.defaults.chatCount = 0;
            $num.hide();
        }
    },
    // 发送聊天信息
    chat_content:function(ret){
        var that = this,
        $chat_list = $("#chat_list"),
        chatRender = template("chat_content", ret);
    },
    init: function(){
        this.bindEvents();
    }
};

// 问答区
HTSDK.modQuestion = {
    $target: $("#mod_questions"),
    defaults:{
        canSend: true,
        sendTimeLimit: 2000,
        showMeOnly: false,
        quesRender: false
    },
    
    // 事件绑定
    bindEvents: function(){
        var that = this,
            $quesHall = $("#mod_chat_hall"),
            $queScoller = $("#mod_ques_scroller"),
            $queScHall = $("#mod_questions_con"),
            $showMebtn = $(".show_me_ques"),
            $quesBtn = $("#post_question_btn"),
            $postQues = $("#ques_post_txt");
        
        // 聊天问答滚动
        $queScHall.scroll(function(){
            var scTop = (this.scrollHeight - $(this).scrollTop()) - $(this).height();
            if(scTop > 100){
                that.quesScrollLock = true;
            }else{
                that.quesScrollLock = false;
            }
        });

        // 回复
        $queScoller.on("click", function(e) {
            var isAnswer = $(e.target).hasClass("answered");
            if(isAnswer){
                var $rid = $(e.target).data("rid"),
                    $nickname = $(e.target).data("nickname");
                $quesBtn.data("type", "reply");
                $quesBtn.data("rid", $rid);
                $postQues.attr("placeholder", "回答 "+$nickname+"的问题:");
                $postQues.focus();
            }else{
                $postQues.attr("placeholder", "请输入文字...");
                $quesBtn.data("rid", "0");
                $quesBtn.data("type", "ask");
            };
        });

        // 发表问题
        $postQues.on("keydown", function(e){
            if(e.keyCode === 13){
                that.emitQues();
                e.preventDefault();
                return false;
            }
        });
        $quesBtn.on("click", function () {
            that.emitQues();
        });

        // 只看自己提问
        $showMebtn.on("click", function() {
            if($(this).hasClass("cur")){
                $(this).removeClass("cur");
                that.defaults.showMeOnly = false;
                that.showMeQuesOnly("all");
            }else{
                $(this).addClass("cur");
                that.defaults.showMeOnly = true;
                that.showMeQuesOnly(MT.me.xid);
            }
        });

        // 绑定获取焦点事件
        $postQues.on("focus", function(event) {
            if($(this).val().length > 0){
                $quesBtn.addClass("active");
            }else{
                $quesBtn.removeClass("active");
            }
        });

        // 绑定失去焦点事件
        $postQues.on("blur", function(event) {
            if($(this).val().length > 0){
                $quesBtn.addClass("active");
            }else{
                $quesBtn.removeClass("active");
            }
        });

        // 键盘弹起
        $postQues.on("keyup", function (e) {
            if($(this).val().length > 0){
                $quesBtn.addClass("active");
            }else{
                $quesBtn.removeClass("active");
            }
        });

    },
    // 只看自己提问
    showMeQuesOnly: function(xid){
        var $quesHall = $("#mod_ques_scroller"),
            isAdmin = MTSDK.admin.isAdmin();
        // 如管理员身份全部可查看
        // 普通用户如回复数大于0显示
        if(xid === "all"){
            if(isAdmin){
                $quesHall.find(".ask_wrap").show();
            }else{
                $quesHall.find(".ask_wrap").each(function(i, e){
                    // data-replies 回复数大于0
                    var replies = parseInt($(e).data("replies"), 10);
                    if(replies > 0){
                        $(e).show();
                    }else{
                        $(e).hide();
                        $(".xid_"+MT.me.xid).show();
                    }
                });
            }
            HTSDK.tools.scrollToBottom("question");
            return false;
        }else{
            $quesHall.find(".ask_wrap").hide();
            $quesHall.find(".xid_"+xid).show();
        }
    },
    // 渲染问答列表
    renderQueslist: function(ret){
        var d = ret.data,
            tpl = "",
            avatar = "",
            isShow = "",
            curRole = MT.me.role,
            isAdmin = MTSDK.admin.isAdmin();
        // 列表
        for (var i in d) {
            var isMe = MT.me.xid == d[i].xid,
                replies = parseInt(d[i].replies, 10);
                avatar = HTSDK.room.setAvatar(d[i]);

            if(isAdmin || isMe){
                isShow = "";
            }else if(replies > 0){
                isShow = "";
            }else{
                isShow = " hidden";
            }
            // render 数据-model
            var questionData = {
                d: d[i],
                time: HTSDK.tools.convertTimestamp(d[i].time),
                isAdmin: isAdmin,
                replies: replies,
                avatar: avatar,
                isShow: isShow
            };
            // view
            tpl += template("list_question", questionData);
        };
        var $quesHall = $("#mod_ques_scroller");
        $quesHall.append(tpl);
        HTSDK.tools.scrollToBottom("question");
    },
    // 发表问题
    emitQues: function(){
        var $ques = $('#mod_question_post'),
            $quesCon = $("#ques_post_txt"),
            $quesVal = $.trim($quesCon.val()),
            $quesHall = $("#question_hall"),
            _HT = HTSDK.room._HT,
            action = MT.getLiveState(),
            that = this,
            type = $("#post_question_btn").data("type"),
            rid = $("#post_question_btn").data("rid"),
            _ques = HTSDK.room.roomSetMsg;
         
        if ( _ques.length == 0 || _ques.mod_beforeclass_live.enable != 1 ){
             // action
            if(action !== "start"){
                HTSDK.tools.showComtip($quesCon, "上课后才能提问哟...");
                return false;
            }
        }
        
        // 发表时间限制
        if(!this.defaults.canSend){
            HTSDK.tools.showComtip($quesCon, "请2秒后再提问...");
            // 2s后取消限制
            if(!that.defaults.canSend){
                setTimeout(function(){
                    that.defaults.canSend = true;
                }, that.defaults.sendTimeLimit);
            }
            return false;
        }
        // 禁止为空
        if($quesVal.length === 0){
            HTSDK.tools.showComtip($quesCon, "请输入内容...");
            return false;
        }
        that.defaults.canSend = false;
        $quesCon.focus();
        // send chat post
        if(type === "ask"){
            _HT.emit("question:ask", {msg: $quesVal}, function(retval){
                if(retval.code == 20){
                    // 重复
                    HTSDK.tools.showComtip($quesCon, "重复提问了～");
                    return false;
                }else if(retval.code == 21){
                    // 重复
                    HTSDK.tools.showComtip($quesCon, "提交过快哟～");
                    return false;
                }else if(retval.code == 0){
                    if(HTSDK.room.isAdmin()){
                        HTSDK.tools.showComtip($quesCon, "提交成功");
                    }else{
                        HTSDK.tools.showComtip($quesCon, "提问成功请等待老师回答");
                    }
                    // clear content
                    $quesCon.val("");
                    return false;
                }else{
                    // clear content
                    $quesCon.val("");
                    return false;
                }
            });
        }else if(type === "reply"){
            _HT.emit("question:reply", {msg: $quesVal, replyId: rid}, function(retval){
                if(retval.code !== 0){
                    HTSDK.tools.showComtip($quesCon, "提交错误哟～"+retval.code);
                }else{
                    $quesCon.val("");
                }
            });
        }
        // 取消限制
        setTimeout(function(){
            that.defaults.canSend = true;
        }, that.defaults.sendTimeLimit);
    },
    // 初始化获取问答列表
    getQuestionList: function(){
        var that = this;
        // 未上课不获取问答列表
        var action = MT.getLiveState();
        if(action !== "start"){
            return false;
        }
        var _HT = HTSDK.room._HT;
        // 获取问答列表
        _HT.getQuestion(function(retval){
            if(retval.code === 0 && typeof retval.data !== "undefined"){
                that.questionList = retval.data;
                that.defaults.quesRender = true;
                // 渲染模版
                that.renderQueslist(retval);
            }
        });
    },
    // 删除
    remove: function(qid){
        // todo...
    },
    // 提问
    ask: function(ret){
        // render 数据-model
        var d = ret,
            tpl = "",
            avatar = HTSDK.room.setAvatar(ret),
            isShow = (MT.me.xid == d.xid || MTSDK.admin.isAdmin()) ? "" : "hidden",
            isAdmin = MTSDK.admin.isAdmin();

        // quesdata
        var questionData = {
            d: ret,
            time: HTSDK.tools.convertTimestamp(d.time),
            isAdmin: isAdmin,
            replies: 0,
            avatar: avatar,
            isShow: isShow
        };
        // tpls
        var _tplAsk = template("mod_ques_ask", questionData);
        $("#mod_ques_scroller").append(_tplAsk);
        HTSDK.tools.scrollToBottom("question", d.xid);
    },
    // 回答
    reply: function(ret){

        var d = ret,
            tpl = "",
            $quesBtn = $("#post_question_btn"),
            $postQues = $("#ques_post_txt"),
            $reTarget = $("#que_"+d.replyId);
            // render
            var repData = {
                d: d,
                time: HTSDK.tools.convertTimestamp(d.time),
                avatar: HTSDK.room.setAvatar(d)
            };
            // render
            tpl = template("mod_ques_reply", repData);
            
            // 回答
            $reTarget.show().data("replies", "1");
            $reTarget.find(".re_list").append(tpl);

            // 如本人重置输入框
            if(d.xid === MT.me.xid){
                // reset
                $postQues.attr("placeholder", "请输入文字...");
                $quesBtn.data("rid", "0");
                $quesBtn.data("type", "ask");
                HTSDK.tools.scrollToBottom("question", d.xid);
            }
    },
    init: function(){
        this.bindEvents();
    }
};

// 插件
HTSDK.plugins = {
    // 默认
    defaults: {
        rollTime: null
    },
    cmdBroadCast:[],
    isGlobalLoad: false,
    // 简易弹框
    popBox: function(html){
        var $tg = $("#pop_box");
        $tg.show();
        $tg.html(html);
    },
    // 事件绑定
    bindEvents: function(){
        var that = this,
            $mqcls = $(".con_notice .cls_btn"),
            $marquee = $("#marquee"),
            $popBox = $("#pop_box"),
            $chat = $("#mod_chat_hall"),
            $flower = $("#mod_chat_post .flower_btn");

        // 关闭抽奖
        that.lottery.closeLottery();

        // 送鲜花
        $flower.on("click", function(e){
            if($(this).hasClass("disable")){
                return false;
            }
            var $e = $(this);
            that.flower.send($e);
        });

        // 关闭滚动
        $mqcls.on("click", function () {
            that.closeMarquee();
        });
        $marquee.hover(function (e) {
            this.stop();
        }, function (e) {
            this.start();
        });

        // 弹框绑定
        $popBox.on("click", ".cls", function(){
            $popBox.html("").hide();
        });

        // 盒子
        $("body").on("click", "#pop_upload .op_btn .cls", function(){
            $("#pop_upload").remove();
        });

        // 发表投票
        $popBox.on("click", ".selt_vote_option .vote_btn", function(e){
            HTSDK.plugins.vote.postVote(e);
        });

        // 投票选项
        $popBox.on("click", ".vote_selector input", function(e){
            HTSDK.plugins.vote.getOptions(e);
        });

        // 投票结果
        $chat.on("click", ".getvote", function(e){
            var vid = $(this).data("vid");
            HTSDK.plugins.vote.getVoteDetail(vid);
        });
    },
    // 滚动通知
    rollNotice: function(data){
        var $tg = $("#marquee"),
            $el = $(".con_notice"),
            d = data;
        clearTimeout(this.defaults.rollTime);
        if(d == "" || d.duration === 0){
            $el.hide();
            return false;
        }
        if(d.link.length>0){
            $tg.html('<p><a href="'+d.link+'" target="_blank">'+d.content+'</a></p>');    
        }else{
            $tg.html('<p>'+d.content+'</p>');   
        }
        
        $el.fadeIn();
        // 滚动时长
        this.defaults.rollTime = setTimeout(function(){
            $el.fadeOut(100);
        }, d.duration*1000);
    },
    //关闭滚动通知
    closeMarquee: function () {
        clearTimeout(this.defaults.rollTime);
        $(".con_notice").fadeOut(200);
    },
    // 鲜花
    flower: {
        // 是否初始化
        inited: false,
        // 初始化界面
        init: function(flag) {
            if(HTSDK.room._HT){
                if(!this.inited){
                    // 获取鲜花
                    HTSDK.room._HT.plugins("flower").getFlower();
                    this.inited = true;
                }
            }
            /*this.sendCallback({
                amount: 3, 
                nickname: "marko", 
                xid: 2219237,
                sendTime: 111
            });*/
        },
        // 送花
        send: function(target) {
            this.e = target;
            // 送花请求
            HTSDK.room._HT.plugins("flower").sendFlower();
        },
        // 送花回调
        sendCallback: function(retval) {
            var that = this,
                $tg = $("#mod_chat_hall"),
                _flower = {},
                d = retval,
                fcount = parseInt(d.amount, 10),
                _fw = [],
                _self = "",
                now = new Date();
            //items
            for (var i = 0; i < fcount; i++) {
                _fw.push(i+1);
            };
            // self
            if(MT.me.xid == d.xid){
                _self = "self";
            }
            // 是否显示管理员工具
            var _isShowTools = false;
            if(MTSDK.admin.isAdmin()){
                if(d.role === "admin" || d.role === "spadmin"){
                    _isShowTools = false;
                }else{
                    _isShowTools = true;
                }
            }
            // flower
            _flower = {
                data: d,
                time: HTSDK.tools.convertTimestamp(d.sendtime),
                amount: _fw,
                self: _self,
                isShowTools: _isShowTools,
                isShow: HTSDK.modChat.defaults.showAdminonly ? "hidden" : "show",
                avatar: HTSDK.room.setAvatar(d)
            };
            // 插入鲜花
            if(HTSDK.room.templateLoad){
                var tpl_flower = template("tpl_append_flower", _flower);
                $tg.append(tpl_flower);

                /*if(retval.chat.enable == 1){
                    $(".ban_"+retval.xid).hide();
                }else if(retval.chat.enable == 0 && MT.me.role !="user"){
                    $(".ban_"+retval.xid).show();
                }*/

                HTSDK.modChat.checkChatSize();
                HTSDK.tools.scrollToBottom("chat");
                // 统计未读信息
                HTSDK.modChat.checkNew();
            }
        },
        // 剩余时间
        flowerTimeleft: function (sec) {
            this.tips(sec);
        },
        // 鲜花自增
        autoIncrease: function (flower) {
            var fw = parseInt(flower, 10);
            if(fw > 0 && fw <= 3){
                $("#mod_chat_post .flower_btn .num").html(fw).fadeIn(100);
            }else{
                return;
            }
        },
        // 初始化鲜花
        flowerInit: function (ret) {
            this.tips(ret);
        },
        // 提示
        tips: function(data) {
            var $tg = $("#mod_chat_post .flower_btn"),
                $num = $tg.find(".num"),
                d = data,
                that = this,
                amount = d.amount;
            // 鲜花数提示
            if(d.code === 0){
                if(d.amount > 0){
                    $num.html(d.amount).fadeIn(200);
                }else{
                    $num.hide();
                }
            }else if(d.code === 15000){
                var leftTime = d.leftTime;
                if(leftTime > 0){
                    HTSDK.tools.showComtip(that.e, leftTime+"秒后可获一朵鲜花");
                }
                $num.hide();
            }else{
                //HTSDK.showComtip(that.e, "直播未开启");
            }
        }
    },
    // 投票
    vote: {
        curVote: {}, //当前投票对象
        opAry: [],//当前选项
        voteLetter: ["A","B","C","D","E","F","G","H","I","J"],
        // 显示投票选项
        showVote: function(ret){
            this.opAry.splice(0, this.opAry.length);
            this.curVote = ret;
            ret.letter = this.voteLetter;
            var _tpl_showVote = template("show_vote_options", ret);
                //HTSDK.plugins.popBox(_tpl_showVote);
            var notify = '管理员 <em>'+ret.info.nickname+'</em> 在'+ret.info.startTime+'发起了一个投票！';
            HTSDK.tools.chatNotify(notify);
            //普通用户投票
            if(!MTSDK.admin.isAdmin()){
               HTSDK.plugins.popBox(_tpl_showVote);
            }
        },
        // 自动关闭
        autoClose: function(duration){
            var $popBox = $("#pop_box"),
                that = this;
            setTimeout(function(){
                $popBox.html("").hide();
            }, duration);
        },
        // 显示投票结果
        showResult: function(ret){
            var isShow = parseInt(ret.isShow, 10);
            // 是否显示投票结果
            if(isShow > 0){
                ret.letter = this.voteLetter;
                var _tpl_showResult = template("show_vote_result", ret);
                HTSDK.plugins.popBox(_tpl_showResult);
                var notify = '管理员 <em>'+ret.info.nickname+'</em> 在'+ret.info.startTime+'结束了投票。<a class="getvote" data-vid="'+ret.info.vid+'">查看结果</a>';
                HTSDK.tools.chatNotify(notify);
                // 如果是管理员
                if(!MTSDK.admin.isAdmin()){
                    MTSDK.plugins.popBox(_tpl_showResult);
                }
            }
        },
        // 显示获取投票内容
        showGetVote: function(ret){
            ret.letter = this.voteLetter;
            var _tpl_showGetvote = template("show_vote_getvote", ret);
            HTSDK.plugins.popBox(_tpl_showGetvote);
        },
        // 投票TODO...
        postVote: function(el){
            var that = this,
                opt = that.curVote;
            var _options = that.opAry.sort().toString();
            var param = {
                vid: opt.vid,
                options: "["+_options+"]"
            };
            var check = that.checkItems();
            var _HT = HTSDK.room._HT;
            if(check){
                // 发送投票
                _HT.plugins("vote").postVote(param, function(retval){
                    HTSDK.plugins.vote.userVoteCallback(retval);   
                });
                this.autoClose(2000);
            }
        },
        // 获取投票详情
        getVoteDetail: function(vid){
            var _HT = HTSDK.room._HT;
            // 获取投票
            _HT.plugins("vote").getVoteDetail(vid,function(retval){
                HTSDK.plugins.vote.showGetVote(retval);
            });
        },
        // 验证选项
        checkItems: function(){
            var that = this,
                flag = false,
                opt = that.curVote,
                optional = parseInt(opt.optional, 10),
                len = that.opAry.length;
            // 判断选项长度
            if(parseInt(optional) === 1 && len === 1){
                flag = true;
            }else if(parseInt(optional) > 1 && len >= 1){
                flag = true;
            }else{
                $("#pop_box").find(".tips").show();
                setTimeout(function(){
                    $("#pop_box").find(".tips").hide();
                }, 1000);
                flag = false;
            }
            return flag;
        },
        // 获取投票选项
        getOptions: function(tsEl){
            var options = "",
                optional = this.curVote.optional,
                $target = $(tsEl.currentTarget),
                that = this,
                opv = parseInt($target.val(), 10),
                index = $target.index(),
                flag = $target[index].checked;
            // 多选操作
            if(optional > 1){
                if(flag){
                    //添加选项
                    that.opAry.push(opv);
                    if(that.opAry.length < optional){
                        //合并选项(多选)
                        that.opAry = $.unique(that.opAry);

                    }else if(that.opAry.length > optional){
                        //选择大于限制
                        $target.attr('checked', false);
                        that.opAry = MT.tools.without(that.opAry, opv);
                    }
                }else{
                    that.opAry = MT.tools.without(that.opAry, opv);
                }
            }
            // 单选操作
            else if(optional == 1){
                //单选
                if(flag){
                    that.opAry.splice(0, 1, opv);
                }
            }
            return that.opAry;
        },
        // 投票回调
        userVoteCallback: function(data){
            var ret = {
                code: data.code || 0,
                callback: true,
                msg: data.msg || ""
            };
            var _tpl_voteCallback = template("show_vote_callback", ret);
            HTSDK.plugins.popBox(_tpl_voteCallback);
        }
    },
    // 抽奖
    lottery: {
        timer: null,
        t1: null,
        t2: null,
        t3: null,
        // 关闭抽奖
        closeLottery: function(){
            $(".operation").on("click", function(){
                if($(this).hasClass("cur")){
                    return false;
                }else{
                    // 隐藏抽奖项
                    $("#mode_lottery").fadeOut(100);
                }
            });
        },
        // 开始抽奖(动画)
        startLottery: function(){
            if(MTSDK.admin.isAdmin()){
                return false;
            }
            var $lottery = $("#mode_lottery");
            $lottery.fadeIn(100);
            // 抽奖模块
            var duration = 5000,
                $it1 = $("#roller_con").find(".it_1"),
                $it2 = $("#roller_con").find(".it_2"),
                $it3 = $("#roller_con").find(".it_3");
            clearTimeout(this.timer);
            // 抽奖
            $("#roller_con").fadeIn(100);
            $(".award_user_info").fadeOut(100);
            $(".operation").addClass("cur");
            // 滚动速度(数字越大越快)
            var lotSpeed = [10, 10, 10],
                that = this;
            // 动作1
            var w_1 = function(){
                $it1.stop().animate({
                    backgroundPositionY: -252+(672*lotSpeed[0])+"px"
                }, duration, function(){
                    setTimeout(function(){
                        $it1.removeAttr("style");
                        w_1();
                    }, 50);
                });
            }
            w_1();
            // 动作2
            var w_2 = function(){
                $it2.stop().animate({
                    backgroundPositionY: -252-(672*lotSpeed[1])+"px"
                }, duration, function(){
                    setTimeout(function(){
                        $it2.removeAttr("style");
                        w_2();
                    }, 50);
                });
            }
            w_2();
            // 动作3
            var w_3 = function(){
                $it3.stop().animate({
                    backgroundPositionY: -252+(672*lotSpeed[2])+"px"
                }, duration, function(){
                    setTimeout(function(){
                        $it3.removeAttr("style");
                        w_3();
                    }, 50);
                });
            }
            w_3();
        },
        // 停止抽奖
        stopLottery: function(retval){
            var me = MT.me,
                meXid = me.xid,
                loXid = retval.result[0].xid,
                name = retval.result[0].nickname,
                launch_nickname = retval.result[0].launch_nickname,
                $lottery = $("#mode_lottery");
                //管理员
                if(MTSDK.admin.isAdmin()){
                    var notify = '通知：'+launch_nickname+' 发起了抽奖，恭喜 <em>'+name+'</em> 中奖！';
                    HTSDK.tools.chatNotify(notify);
                    return false;
                }

            $lottery.fadeIn(50);
            clearInterval(this.t1);
            clearInterval(this.t2);
            clearInterval(this.t3);
            // clear
            $("#roller_con").find(".it_1").stop().removeAttr("style");
            $("#roller_con").find(".it_2").stop().removeAttr("style");
            $("#roller_con").find(".it_3").stop().removeAttr("style");
            // 显示结果
            setTimeout(function(){
                if(loXid === meXid){
                    // 自己中奖
                    HTSDK.plugins.lottery.renderLottery(name, true);
                }else{
                    // 未中奖
                    HTSDK.plugins.lottery.renderLottery(name, false);
                }
                var notify = '通知：<em>'+launch_nickname+'</em> 发起了抽奖，恭喜 <em class="red">'+name+'</em> 中奖！';
                HTSDK.tools.chatNotify(notify)
            }, 200);
        },
        // 显示抽奖信息
        renderLottery: function(nickname, flag){
            // 抽奖模块
            var timer = this.timer,
                $it1 = $("#roller_con").find(".it_1"),
                $it2 = $("#roller_con").find(".it_2"),
                $it3 = $("#roller_con").find(".it_3");
            $("#roller_con").fadeIn(80);
            // 停止动作恢复默认
            $it1.removeAttr("style");
            $it2.removeAttr("style");
            $it3.removeAttr("style");
            $("#loter_info").html(nickname);
            $(".operation").removeClass("cur");
            $("#roller_con").fadeOut(100);
            $(".award_user_info").fadeIn(100);
            $(".award_user_info").removeClass("me");

            // 是否自己中奖
            if(flag){
                $(".award_user_info").addClass("me");
            }else{
                $(".award_user_info").removeClass("me");
            }
        }
    },
    // 插入公共广播
    renderBroadCast: function(){
        for (var i = 0; i < this.cmdBroadCast.length; i++) {
            var retval = this.cmdBroadCast[i];
            if(retval && retval.__auto == 1){
                var notify = '公共广播：'+retval.message+"; ("+retval.__auto+")";
                HTSDK.tools.chatNotify(notify);
            }
        };
    },
    // 监听自定义广播
    diyBroadcast: function(retval){
        var o = {
            message: retval.message,
            __auto: retval.__auto
        };
        // 单条插入
        if(this.isGlobalLoad){
            var notify = '公共广播：'+retval.message+"; ("+retval.__auto+")";
            HTSDK.tools.chatNotify(notify);
        }else{
            // 初始化渲染多条
            this.cmdBroadCast.push(o);
        }
    },
    
    overHover:function(){
        $('.admin_list li').mouseout(function(event) {
            $('.admin_list').remove();
        });
    },   
    //查看详情、T出房间、禁言
    popHover:function(){
        var $userLi = $('#mod_member_list');
            if(MT.me.role == "user"){
                return false;
            }
            $userLi.on('click', 'li', function(){
                if($(this).data('role') == "admin" || $(this).data('role') == "spadmin"){
                    return false;
                }
                var xid = $(this).data("xid");
                HTSDK.plugins._detail(this, xid);
            });
    },
    managerTimer: null,
    _detail:function(target,xid){
        var $that = $(target),
            that = this,
            _MT = HTSDK.room._HT;

        $that.off();
        $that.popBox({
            position: 'absolute',
            content: template("tpl_admin_pop_menu"), // _root/tpl_admin
            callback: function(){
                $('.admin_list').css({
                    'top': $that.offset().top + 26,
                    'left': $that.offset().left,
                });
                
                // 解绑事件
                $("#ht_pop_box").off();
                $(".pop_side_operation").off();

                // 踢出房，禁言、查看详情
                $(".pop_side_operation").find("li").on("click", function(){
                        //详情
                        if($(this).data('op') == "detail"){
                            MTSDK.admin.adminDo.detail(xid,$that);
                        }
                        //禁止聊天区发言
                        if($(this).data('op') == 'chatAccess'){
                            MTSDK.admin.adminDo.chatAccess(xid, _MT);
                            if($('#user_'+xid+' .ban').size() < 1){
                                 $("#user_"+xid).find('#grant').addClass('ban');
                                 $(".ban_" +xid).show()
                            }
                        }
                        //T出房间
                        if($(this).data('op') == 'kick'){
                            MTSDK.admin.adminDo.kick(xid,_MT);
                        }
                        // yun xu语音
                        if($(this).data('op') == 'venable'){
                            MTSDK.admin.adminDo.venable(xid, _MT, function(ret){
                                //HTSDK.voice
                            });
                            $("#user_"+xid).find("p").removeClass("voice_disable");
                            $("#user_"+xid).find('p').attr("data-voice",0);
                        }
                        // 禁止语音
                        if($(this).data('op') == 'vdisable'){
                            MTSDK.admin.adminDo.vdisable(xid, _MT, function(ret){
                            });
                            $("#user_"+xid).find("p").addClass("voice_disable");
                            $("#user_"+xid).find('p').attr("data-voice",1);
                        }
                        /*if($(this).data('op') == 'privateChat'){}*/
                        // 关闭
                        $that.popboxCloseAll();
                });
                
                // <弹出层> 进入/离开
                $("#ht_pop_box").on("mouseover", ".pop_side_operation", function(){
                    if(that.managerTimer){
                        clearTimeout(that.managerTimer);
                    }
                });

                $("#ht_pop_box").on("mouseout", ".pop_side_operation", function(){
                    var $that = this;
                    that.managerTimer = setTimeout(function(){
                        $(that).popboxCloseAll();
                    }, 200);
                });
            }
        });
        

        // <li> 元素进入/离开
        $that.on("mouseover", function(){
            clearTimeout(that.managerTimer);
        });

        $that.on("mouseout", function(){
            that.managerTimer = setTimeout(function(){
                $that.popboxCloseAll();
            }, 200);
        });
    },
    //聊天区admin/spadmin 管理功能
    _managerFun:function(){
        var $cp_fun = $('.mod_chat_hall');

            $cp_fun.on('click', '.cp', function(){
                var xid = $(this).parents(".chat_list").data('xid');
                HTSDK.plugins._detail(this,xid);
            });
    },
    //管理功能盒子
    /*_managBox:function(target,mxid){
        var $that = $(target),
            _MT = HTSDK.room._HT; 
        /*var manList = '<div class="admin_list"><ul class="pop_side_operation"><li data-op="kick">踢出房间</li><li data-op="chatAccess">禁止发言</li><li></</ul></div>';
            
            $that.popBox({
                position:'absolute',
                content: template("tpl_admin_pop_menu"),
                callback:function(){
                    $('.admin_list').css({
                        'top':$that.offset().top+20,
                        'left':$that.offset().left+20,
                    });
                    //踢出房间、禁言 查看详情
                    $(".pop_side_operation").find("li").on("click", function(){
                        if($(this).data('op') == 'chatAccess'){
                            MTSDK.admin.adminDo.chatAccess(mxid, _MT);
                        }
                        if($(this).data('op') == 'kick'){
                            MTSDK.admin.adminDo.kick(mxid,_MT);
                        }
                        // 关闭
                        $that.popboxCloseAll();
                    });
                }
            });
    },*/
    //关键字匹配
    init: function(){
        this.bindEvents();
        this.popHover();
        this._managerFun();
        this.flower.init();
    }
};

// 底部工具栏
HTSDK.footer = {
    target: $(".mod_footer"),
    // 事件绑定
    bindEvents: function(){
        //网络状态hover
        var $prompt = $('.tools_toggle_netprompt .focus_pro');

        $prompt.parent().hover(function(){
            $prompt.show();
        },function(){
            $prompt.hide();
        });

        var $opBtns = $("#live_tools");
        // 摄像开关
        $opBtns.on("click", ".tools_toggle_camera", function(event) {
            if($(this).hasClass('disable')){
                $(this).removeClass('disable');
                $(".mod_sider_top").removeClass('show_author');
                if($(".mod_sider_top").hasClass("camera")){
                    $(".mod_sider_top").css("height",210);
                    $(".mod_question_wrap .mod_ques_hall").css("top",304);
                }      
            }else{
                $(this).addClass('disable');
                $(".mod_sider_top").addClass('show_author');
                if($(".mod_sider_top").hasClass("camera")){
                    $(".mod_sider_top").css("height",0);
                    $(".mod_question_wrap .mod_ques_hall").css("top",90);
                }
            }
        });

        //助教PPT预览模块
        $opBtns.on('click','.preview_btn',function(){
            MTSDK.admin.adminBox.pptPreViewRender(function(ret){
                if(ret){
                    $('.assistant_ppt').show().css({
                        'margin-top': -$(window).height()*0.9 / 2-20+'px',
                        'margin-left': -$(window).width()*0.9 / 2-20+'px'
                    });
                    $('#pop_layer').show();
                }
            });
        });
        $(window).on("resize", function(){
            $('.assistant_ppt').css({
                'margin-top': -$(window).height()*0.9 / 2-20+'px',
                'margin-left': -$(window).width()*0.9 / 2-20+'px'
            });
        });
        $('.ass_ppt_close').on('click',function(){
            $('.assistant_ppt').hide();
            $('#pop_layer').hide();
        });

        // 网络选择
        $opBtns.on("click", ".tools_toggle_network", function(event){
            MTSDK.admin.chooseNetwork.init();
        });

        // 摄像头切换
        $opBtns.on("click", ".tools_toggle_ppt", function(event) {
            if($(this).hasClass('disable')){
                $(this).removeClass('disable');
                $(this).addClass('enable');
                HTSDK.player.togglePlayerPosition(true);
            }else{
                $(this).removeClass('enable');
                $(this).addClass('disable');
                $(".mod_main_player_wp").css("visibility","");
                HTSDK.player.togglePlayerPosition(false);
            }
        });
    },

    //助教ppt页
   pptPreView: function(retval){
        if(!retval){
            $('.preview_num').html("");
            $(".preview_btn").hide();
            return false;
        }
        $(".preview_btn").show();
        $('.preview_num').html(retval.page+'/'+retval.count);
    },

    init: function(){
        this.bindEvents();
    }
};

// 评分系统
HTSDK.score = {
    bindEvents: function(){
        var $pop_layer = $("#pop_layer"),
            $pop_score = $(".pop_score"),
            $close = $pop_score.find(".pop_close"),
            $dl_cont = $(".pop_socre_bd dl");
            var iStar = 0;
            $close.on("click",function(){
                $pop_score.hide();
                $pop_layer.hide();
            });
            //鼠标滑过
            $dl_cont.find(".socre_star").hover(function(){
                $(this).addClass('cur');
            },function(){
                $(this).removeClass('cur');
            });

    },
    //渲染
    loadTemp:function(){
        var tplScore = template("tpl_pop_score");
        $("#pop_score_contonet").prepend(tplScore);
    },
    //入口
    init: function(){
        this.loadTemp();
        this.bindEvents();
    } 
};

// 房间
HTSDK.room = {
    defaults: {
        avaBasePath: "",
        defaultAavtar: "http://static-1.talk-fun.com/open/cooperation/default/live-pc/css/img/main/user.png"
    },
    // SDK: _HT对象
    _HT: null,
    // 是否管理员
    isAdmin: function(role){
        var _role = role || MT.me.role;
        if(_role){
            if(_role === "admin" || _role === "spadmin"){
               
                return true;
            }else{
                return false;
            }
        }
    },
    //房间模块设置
    roomSetMsg: [],
    //课程信息
    courseMsg: [],
    // set volume
    setVolume: function(volume){
        HTSDK.player.setVolume(volume);
        HTSDK.oneToOne.setVolume(volume);
    },

    // 图片错误绑定
    imgError: function(img){
        img.src = this.defaults.defaultAavtar;
    },
    // 获取(设置)用户头像
    setAvatar: function(user){
       
        var that = this,
            _user = {},
            avaImgSrc = "",
            path = "http://static-1.talk-fun.com/open/cooperation/default/live-pc/css",
            imgSpadmin = path + "/img/main/spadmin.png",
            imgAdmin = path + "/img/main/admin.png",
            imgHonorguest = path+"/img/main/guest.png",
            defaultAavtar = that.defaults.defaultAavtar,
            basePath = that.defaults.avaBasePath;

        // 判断是否传入role信息
        if(typeof user === "object"){
            _user = user;
        }

        // 有头像
        if(_user.avatar){
            avaImgSrc = _user.avatar;
        }else{
            // spadmin.超级管理员
            if(_user.role === "spadmin"){
                // 管理员自定义头像
                if(user.avatar){
                    avaImgSrc = user.avatar;
                }else{
                    // avaImgSrc = defaultAavtar;
                    avaImgSrc = imgSpadmin;
                }
            }
            // Admin.普通管理员
            else if(_user.role === "admin"){
                // 管理员自定义头像
                if(user.avatar){
                    avaImgSrc = user.avatar;
                }else{
                    // avaImgSrc = defaultAavtar;
                    avaImgSrc = imgAdmin;
                }
            }
            /*// honorguest.嘉宾
            else if(_user.role === "honorguest"){
                // 管理员自定义头像
                if(user.avatar){
                    avaImgSrc = user.avatar;
                }else{
                    avaImgSrc = imgHonorguest;
                }
            }*/
            // Users.普通用户
            else{
                // 设置avatar
                if(user.avatar){
                    if(user.avatar.length > 0){
                        avaImgSrc = user.avatar;
                    }
                }else{
                    avaImgSrc = defaultAavtar;
                }
            }
        }
        // 头像列表src
        if(this.avatarloaded){
            if($(".avatar_"+user.uid).size() > 0){
                $(".avatar_"+user.uid).attr("src", avaImgSrc);
            }
        }
        
        return avaImgSrc;
    },
    // 管理员渲染
    // 嘉宾身份判断
    adminRender: function(){
        var isAdmin = (MT.me.role === "admin" || MT.me.role === "spadmin"),
            vip = MT.me.role === "honorguest";
        if(isAdmin){
            if(MT.me.role === "admin") {
                $('.ppt_preview').show();
            }else {
                $('.ppt_preview').hide();
            }
            $(".voice_selector .cur_mode").addClass("admin");
            //抽奖 #管理盒子
            $('.admin_box').show();
            //$('.adminSpeak').show();
        }/*else if(vip){
            // todo...
            // 添加一个按钮
            // 看下语音云初始化模式
            $('.guestSpeak').show();
        }*/
        else{
            $(".mic_control").remove();
            $(".mic_operation").remove();
            $(".cls_hands").remove();
        }
        $(".select_mic").fadeIn(100);
    },
    // 清除信息
    clearHall: function(){
        $("#mod_ques_scroller").html("");
    },
    // 直播状态改变
    liveChange: function(action, title){

        var _title = title || MT.title,
            _lvTxt = null,
            that = this,
            action = MT.getLiveState() || action,
            $preview = $("#mod_live_preview");
        // 鲜花初始化
        HTSDK.plugins.flower.init();
        
        // start
        if(action === "start"){
            $preview.fadeOut(100);
            $("#lv_state").hide();
            $("#live_title").html(_title).fadeIn(100);
            $("#live_title").fadeIn(100)
            this.liveDuration();
            //$('.tools_toggle_netprompt').show();
            // 加载问答
            if(!HTSDK.modQuestion.defaults.quesRender){
                that.clearHall();
                HTSDK.modQuestion.getQuestionList();
            }
            //开始课程的时候判断课程id是否一致
            
        }
        // wait
        else if(action === "wait"){
            _lvTxt = "已结束";
            $preview.fadeIn(100);
            $('.tools_toggle_netprompt').hide();
            $("#live_title").hide().html(_lvTxt);
            $("#lv_state").show().html(_lvTxt);
            this.liveDuration(-1);
        }
        // stop
        else if(action === "stop"){
            _lvTxt = "未开启";
            $preview.fadeIn(100);
            $("#lv_state").show().html(_lvTxt);
            $("#live_title").hide().html(_lvTxt);
            this.liveDuration(-1);
            $('.tools_toggle_netprompt').hide();
            //ppt 预览
            $('.ppt_preview').hide();
            //小班主播状态停止后
            HTSDK.oneToOne.liveStatus("stop");

            //结束30分钟后T人
            this.liveStopkick();
        }
    },
    // 广播指令
    instructionBroadcast: function(msg){
        
    },

    isCourseSame : function(){

    },
    //下课30分钟后T人
    liveStopkick : function(style){
        var _kict = null;
        if(style == 1){
            clearTimeout(_kict);
        }else {
             _kict = setTimeout(function(){
                window.location.href = 'http://open.talk-fun.com/error.html?var=1';
            }, 1800000);
        }
    },
    // 设置当前直播时间
    liveDuration: function(_time){
        var second = _time || MT.liveDuration,
            time = 0,
            $tg = $("#live_time"),
            timer = null;
        clearInterval(this.dtimer);
        if(typeof second !== "undefined" && second >= 0){
            this.dtimer = setInterval(function(){
                time = MT.tools.formatTime(second);
                $tg.html("已直播 "+time+" 分钟");
                second += 1;
            }, 1000);
        }else{
            MT.liveDuration = -1;
            $tg.html("");
            return false;
        }
    },
    // 检测是否安装Flash
    checkFlash: function(){
        var check = HTSDK.tools.SDKTOOLS.flashChecker(),
            $wrap = $(".mod_main_player_wp");
        if(check.flash){
            return;
        }else{
            $wrap.append('<p class="no_flash">直播课堂需要FLASH支持， 请<a target="_blank" href="http://www.adobe.com/go/getflashplayer">下载安装</a></p>');
        }
    },

    // 已创建房间.(SDK:_HT 对象创建完成)
    SDKReady: function(){
        // admin 加载器
        MTSDK.admin.init(this._HT);
        HTSDK.plugins.isGlobalLoad = true;
        HTSDK.plugins.renderBroadCast();
    },

    roomLoaded: false,
    
    // 获取sdk
    getSdk: function(){
        return this._HT;
    },
    
    // 房间加载完成执行
    roomLoadSucess: function(_HT){
        if(!this.roomLoaded){
            this._HT = _HT;
            HTSDK.voice._HT = _HT;
            this.SDKReady();
            HTSDK.controller.onRoomLoaded();
            this.roomLoaded = true;
            //sdk.live.modules模块设置渲染执行入口
            //HTSDK.live.init();
            // 语音云模块绑定
            HTSDK.voice.bindEvents();
            //小班事件
            HTSDK.oneToOne.bindEvent();
            // 网络状态
            HTSDK.room.networkStatus(0);
            
            //room suc 去掉遮罩
            HTSDK.room._alerror();
        }
    },

    _alerror:function(){
        // loading mask
        setTimeout(function(){
            $("#mod_mask").fadeOut();
        }, 300);
    },

    //页面关闭或者跳转方法
    closeWindow: function(){
        var userAgent = navigator.userAgent;
        if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("WebKit") != -1) {
            window.location.replace("about:blank");
            window.close(); 
        }else{
            window.opener = null;
            window.open("", "_self");
            window.close();
        }
    },

    // 加载模版
    loadTemplate: function(callback){
        // 优先加载
        (function(win){
            // 模版加载...
            var host = window.location.href.indexOf("rye-tech.com") > 0 || window.location.href.indexOf("talk-fun.com") > 0,
                tplSource = "";
            if(host){
                tplSource = '/KS_INC/live/tpl/modules.html';
            }else{
                tplSource = "/KS_INC/live/tpl/modules.html";
            }
            $("#template_loader").load(tplSource, null, function(){
                HTSDK.room.templateLoad = true;
                if(typeof callback === "function"){
                    callback(this);
                }
            });
        })(window);
    },


    //网络状态
    networkStatus: function(status){

        /**
         * == status ===
         * @0: 正常
         * @1: 一般
         * @2: 卡顿
         */

        var $prompt = $('.tools_toggle_netprompt .focus_pro');
        var curClass = "net_focus";

        // fortest
        var isDebug = HTSDK.tools.SDKTOOLS.isShowDebug();
        if(isDebug){
            $("#live_tools").find(".tools_toggle_netprompt").show();
        }

        $prompt.parent().hover(function(){
            $prompt.show();
        },function(){
            $prompt.hide();
        });

        if(status == 1){
            $prompt.text('网络一般，偶尔卡顿');
            curClass = 'net_focus'+' delay';
            $prompt.parent().attr('class',curClass);
        }else if(status == 2){
            $prompt.text('网络较差，卡顿频繁');
            curClass = 'net_focus'+' verydelay';
            $prompt.parent().attr('class',curClass);
        }else {
            $prompt.text('网络良好，观看流畅');
            curClass = "net_focus";
            $prompt.parent().attr('class',curClass);
        }

    },
    // 初始化执行
    init: function () {
        this.loadTemplate(function(tpl){
            // DOM加载结构 & 绑定模块
            HTSDK.view.init(function(){
                HTSDK.cmd();
            });
            //关键字查询
            MTSDK.admin.bindKeywork.init();
            HTSDK.controller.initModules();
            
        });
    }
};

// 小班模式
HTSDK.oneToOne = {
    //全局变量
    defaults:{
        player: null,
        mainPlayer: null,
        oneStatus: "", //初始化房间状态：start, stop, write
        checkState : false,
        dataObject: []
    },

    // 播放器初始化
    playerInit: function(player){
        this.defaults.player = player;
    },

    //隐藏主播放器的声音按钮
    voiceHide: function(){
        var player = HTSDK.oneToOne.defaults.mainPlayer;
            // 隐藏播放器音量按钮
            player.showVolumeBtn(false);
    },

    //设置小班声音
    setVolume: function(volume){
        var player = this.defaults.player;
        //var mainPlayer = HTSDK.oneToOne.defaults.mainPlayer;
            if(player){
                // 隐藏播放器音量按钮
                player.cameraSetVolume(volume);
            }
    },

    //bindEvent
    bindEvent: function(){
        var $go_desk = $("#go_desk"), //上讲台按钮
            $back_desk = $("#back_desk"), //下讲台按钮
            $go_confim = $(".go_confim"), //上讲台弹框确认键
            $down_confim = $(".down_confim"), //下讲台确认键
            $cancel = $(".cancel"), //弹框取消键
            $close = $(".close"), //关闭弹窗
            $fail_close = $(".fail_close"),
            $pop_text = $(".pop_text"); //点击上讲台后弹出的提示框
            
            var _HT = HTSDK.room._HT,
                xid = MT.me.xid,
                role = MT.me.role;
            //学生自主申请上讲台
            $go_desk.on("click", function(){
                _HT.emit("usercamera:check:state", function(retval){

                });
                $go_desk.addClass("emin");
                $(".mod_live_camera").addClass('show');
            });

            //学生自主下讲台
            $back_desk.on("click", function(){
                //下讲台提示框
                $pop_text.show().removeClass('go').addClass('down');
                $go_confim.removeClass('go_confim').addClass('down_confim');
            });

            //上讲台确认提示框
            $pop_text .on('click', ".go_confim", function(){

                $go_desk.hide();
                $pop_text.hide();
                $back_desk.show();
            });

            //下讲台确认提示框 
            $pop_text.on("click", ".down_confim",function(){
                //上了讲台后的下讲台
                if( $(".one_connent").hasClass('show_one_camera')){
                    //下讲台指令
                    _HT.emit("usercamera:down", function(retval){

                    });

                    $go_desk.removeClass("emin");

                    $(".down_text").html("您确定要下讲台吗");

                    $(".one_connent").removeClass('show_one_camera');
                }else{
                    //未得到老师允许的下讲台
                    _HT.emit("usercamera:cancel", function(){

                    });
                    $go_desk.removeClass("emin");
                }

                $(".down_text").html("确定取消上讲台的申请吗");

                $go_desk.show();
                $go_confim.removeClass('down_confim').addClass('go_confim');
                $pop_text.hide();
                $back_desk.hide();
            });

            //关闭提示框
            $close.on("click", function(){
                $pop_text.hide();
            });

            //关闭摄像头检测失败的情况
            $fail_close.on("click", function(){
               $(".user_camera_fail").hide(); 
               $(".mod_live_camera").removeClass('show');
            });

            //失败确认
            $(".fail_sure").on("click",function(){
               $(".user_camera_fail").hide(); 
               $(".mod_live_camera").removeClass('show');
            });

            $cancel.on("click", function(){
                $pop_text.hide();
            });

            //直接关闭声音
            $(".one_button").on("click", function(){
                if( $(this).hasClass('one_mute')){
                    $(this).removeClass('one_mute');
                    HTSDK.room.setVolume(0.5);
                    $(".ui-slider-range-max").css("height", "50%");
                    $(".ui-corner-all").css("bottom", "50%");
                }else{
                    $(this).addClass('one_mute');
                    $(".ui-slider-range-max").css("height", "100%");
                    $(".ui-corner-all").css("bottom", 0);
                    HTSDK.room.setVolume(0);
                }
            });

            // 输入音量
        var $input = $(".mod_live_tools .one_input");

            // 麦音量显示
            $input.on("mouseover",function(){
                $(".one_mic_bg").show();
            });

            // 麦音量隐藏
            $input.on("mouseout",function(){
                $(".one_mic_bg").hide();
            });

            //小班-总音量-音量控制
            $("#one_input_slide").slider({
                orientation: "vertical",
                range: "max",
                min: 0,
                max: 100,
                step: 1,
                animate: true,
                value: 50,
                stop: function(e, res){
                    var volume = res.value;
                        HTSDK.room.setVolume(volume/100);
                        if(volume === 0){
                            $(".mod_live_tools .one_input").addClass("one_mute");
                        }else{
                            $(".mod_live_tools .one_input").removeClass("one_mute");
                        }
                    }
            });
    },

    //用户摄像头开启是否成功
    operCameraState: function(retval){
        var _HT = HTSDK.room._HT,
            xid = MT.me.xid;

        var $go_confim = $(".go_confim"), //上讲台弹框确认键
            $pop_text = $(".pop_text"); //点击上讲台后弹出的提示框
        if( retval == "true"){
            //上讲台指令
            _HT.emit("usercamera:apply", {xid: xid}, function(retval){

                var notify = '<em>'+MT.me.nickname+'</em> 申请了上讲台';
                    HTSDK.tools.chatNotify(notify);
            });
            //检测返回true让swf层级减低
            $(".mod_live_camera").removeClass('show');
            //上讲台提示框
            $pop_text.show().removeClass('down').addClass('go');
            $go_confim.removeClass('down_confim').addClass('go_confim');
        }else{
            //错误的时候也要减低层级
            $(".user_camera_fail").show();
            $(".mod_live_camera").removeClass('show');
        }
    },

    //老师开启上讲台
    cameraStart: function(){
        var notify = '管理员<em>开启了讲台功能</em>，点击右上角的视频区域可申请上讲台';
            HTSDK.tools.chatNotify(notify);
        $("#mod_col_right").addClass("has_one_to_one");
        $(".one_connent").fadeIn(500);
        
        //突然关闭小班
        if( $("#mod_col_right").hasClass('has_one_to_one')){
            $(".one_connent .top").show();
            $("#go_desk").show();
            $("#back_desk").hide();
        }
    },

    //老师关闭上讲台
    cameraStop: function(){
        var notify = '管理员<em>关闭了讲台功能</em>';
            HTSDK.tools.chatNotify(notify);
        $("#mod_col_right").removeClass('has_one_to_one');
        $(".one_connent").removeClass("show_one_camera").fadeOut(500);
    },

    //老师允许上讲台
    allowUp: function(xid, nickname){
        $("#back_desk").show();
        $(".down_text").html("您确定要下讲台吗？");
        $(".one_connent").addClass('show_one_camera');
        if( !(MT.me.xid == xid)){
            $(".show_one_camera .top").hide();
            $("#go_desk").hide();
            $(".has_one_to_one").addClass('other');
        }
        var notify = '管理员允许学员<em>'+ nickname +'</em>上讲台';
            HTSDK.tools.chatNotify(notify);
    },

    //老师强制学生下讲台
    kickStu:function(xid,nickname){
        var applyList = HTSDK.oneToOne.defaults.dataObject;
        var that = this;

            $(".one_connent").removeClass('show_one_camera');
            
            if( xid == MT.me.xid){
                $("#go_desk").show();
                $("#back_desk").hide();
                $("#go_desk").removeClass("emin");
            }else{
                $("#go_desk").show();
                $("#back_desk").hide(); 
                $(".one_connent .top").show();
                $(".has_one_to_one").removeClass('other');
                if(applyList && applyList.length > 0){
                    for( var i = 0; i < applyList.length; i++){
                            if( MT.me.xid == applyList[i].xid){
                                $("#back_desk").show();
                                $("#go_desk").hide();
                            }
                    }
                }
            }

        var notify = '管理员强制<em>'+nickname+'</em>下讲台';
            HTSDK.tools.chatNotify(notify);
    },

    //学生申请上讲台
    stuApply: function(xid, nickname){
        //广播
        var notify = '学员 <em>'+nickname+'</em>申请上讲台';
            HTSDK.tools.chatNotify(notify);
    },

    //学生取消
    stuCancel: function(xid,nickname){
        //广播
        var notify = '学员 <em>'+nickname+'</em>取消上讲台的申请';
            HTSDK.tools.chatNotify(notify);
    },

    //学生主动下讲台
    stuDown: function(xid,nickname){
        //下讲台时，把其他没上讲台的同学位置调整
        if( !(xid == MT.me.xid)){
            $(".show_one_camera .top").show();
            $("#back_desk").hide();
            $("#go_desk").show();
            $(".one_connent").removeClass('show_one_camera');
            $(".has_one_to_one").removeClass('other');
        }

        //广播
        var notify = '学员 <em>'+nickname+'</em>已自行下讲台';
            HTSDK.tools.chatNotify(notify);
    },

    //初始化时房间是否讲台的状态
    initStatus: function(retval){
        var status =  retval.status,
            user = retval.user,
            applyList = retval.applyList;
        var that = this;

        // 已开启小班
        if( status == "start"){
            $(".down_text").html("确定取消上讲台的申请吗");
            $("#mod_col_right").addClass("has_one_to_one");
            $(".one_connent").fadeIn(500);
            if(applyList && applyList.length > 0){
                for( var i = 0; i < applyList.length; i++){
                        if( MT.me.xid == applyList[i].xid){
                            $("#back_desk").show();
                            $("#go_desk").hide();
                        }
                }
            }
        }

        //已有人在讲台
        if( status == "up"){
            $("#back_desk").show();
            $("#mod_col_right").addClass("has_one_to_one");
            $(".one_connent").addClass('show_one_camera');
            if( user != null){
                $(".show_one_camera").show();
                var xid =  user.xid,
                    nickname =  user.nickname;
                    that.allowUp(xid,nickname);
                if( !(MT.me.xid == xid)){
                    $(".show_one_camera .top").hide();
                    $(".has_one_to_one").addClass('other');
                }
            }   
        }
    },

    // 停止上课
    liveStatus: function(status){
        var _HT = HTSDK.room._HT;
        var $colRight = $(".col_right_side");
        if( status == "stop"){
            //window.location.reload();
            _HT.emit( "usercamera:force:out", function(retval){
                $("#back_desk").hide();
                $("#go_desk").show();
                $(".one_connent").removeClass('show_one_camera').hide();
                $(".col_right_side").removeClass('has_one_to_one');
                if( $colRight.hasClass('other')){
                    $colRight.removeClass('other');
                    $(".top").show();
                }
            });
        }
    },

    //渲染
    oneRender: function(){
            //$(".one_voice_funbtn").show();
        var tplOne = template("tpl_one_to_one");
            $("#mod_col_right").prepend(tplOne);
    },

    //入口
    init: function(type){
        var that = this;
        var roomType = parseInt(type);
        if( roomType === 5){
            //渲染
            that.oneRender();
        }
    }  
};

// 总入口
HTSDK.room.init();



