
var SERVER_TIME = 0; //服务器时间
var JUST_NOW = 3000; //3s内
var IN_SECOND = 1000 * 60; //一分钟
var IN_MINUTE = 1000 * 60 * 60; //一小时
var IN_HOUR = 1000 * 60 * 60 * 12; //12小时
var IN_DAY = 1000 * 60 * 60 * 24 * 1; //1天
var IN_MONTH = 1000 * 60 * 60 * 24 * 30; //1个月
var KS_Utils;
var KS_GetCompoents;
var SOURCE;
(function($) {
    
    /**
     * 计算服务器时间
     */
    var weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var params_schoolid = '';
    var schoolid = 0;
    getServerTime(function(time) {
        var serverDate = new Date(time);
        SERVER_TIME = serverDate.getTime();
        setInterval(function() {
            var month = serverDate.getMonth() + 1;
            var week = weekday[serverDate.getDay()];
            var day = serverDate.getDate();
            $('server-time').each(function() {
                this.outerHTML = month + '月' + day + '日 ' + week
            })
            SERVER_TIME += 100;
            
        }, 100);
    });
    
    /**
     * 服务器时间已获取到
     */
    function onServerTimeReady(fn) {
        if(SERVER_TIME === 0){
            setTimeout(function(){
                onServerTimeReady(fn);
            },100);
        }else if(typeof fn === 'function'){
            fn(SERVER_TIME);
        }
    }

    /**
     * 获取时间（仿微信消息格式）
     */
    function getHistoryTime(time){
        if(typeof time === 'string'){
            time = time.replace(/\-/g,'/');
        }
        var createTime = new Date(time);
        var diff = SERVER_TIME - createTime;
        if (diff <= JUST_NOW)
            return '刚刚';
        else if (diff <= IN_SECOND)
            return "1分钟内";
        else if (diff <= IN_MINUTE)
            return parseInt(diff / IN_SECOND) + '分钟前';
        else if (diff <= IN_MINUTE)
            return parseInt(diff / IN_MINUTE) + '小时前';
        else if (diff <= IN_HOUR * 2) {
            var list = createTime.toString().split(" ");
            var lastIndex = list[4].lastIndexOf(":")
            var realtime = list[4].toString().substring(0, lastIndex);
            return realtime;
        } else if (diff < IN_DAY * 7) {
            if (diff < IN_DAY) {
                return parseInt(diff / IN_HOUR) + '天前';
            }
            var t = createTime.toString().slice(0, 3);
            switch (t) {
            case "Mon":
                return '星期一';
            case "Tue":
                return '星期二';
            case "Wed":
                return '星期三';
            case "Thu":
                return '星期四';
            case "Fri":
                return '星期五';
            case "Sat":
                return '星期六';
            case "Sun":
                return '星期日';
            }
        } else if (diff < IN_MONTH*24) {
            var list = createTime.toString().split(" ");
            var month = list[1];
            var realtime = "";
            if (diff < IN_MONTH) {
            realtime += getNumberMonth(month);
            } else {
            realtime = list[3] + "-" + getNumberMonth(month);
            }
            return realtime + "-" + list[2];
        }
    }
    function getNumberMonth(month) {
        switch (month) {
            case "Jan":
            return "1";
            case "Feb":
            return "2";
            case "Mar":
            return "3";
            case "Apr":
            return "4";
            case "May":
            return "5";
            case "June":
            return "6";
            case "July":
            return "7";
            case "Aug":
            return "8";
            case "Sept":
            return "9";
            case "Oct":
            return "10";
            case "Nov":
            return "11";
            case "Dec":
            return "12";
        }
    }
    
    /**
     * 弹窗插件（兼容移动端）
     */
    var popup = (function(){
        var popupID = 0;
        var popupMaskID = 'ks-popup-mask';
        var popupMaskFunctions = [];
        var popupSpeed = 200;
        /**点击灰色窗口遮罩层触发 */
        $('body').on('click','#'+popupMaskID,function(){
            var info = popupMaskFunctions[popupMaskFunctions.length-1];
            if(info.type !== 'msg'){
                var $popup = $('#ks-popup'+info.popupID);
                $popup.animate({
                    marginTop:-$popup.height()/2-10,
                    opacity:0
                },popupSpeed,function(){
                    $(this).remove();
                    if(typeof info.function === 'function'){
                        info.function();
                    }
                    closePopupMask(info.popupID);
                });
            }
        });
        /**
         * 关闭灰色遮罩层
         */
        function closePopupMask(popupID){
            domap(popupMaskFunctions,function(item,i){
                if(item.popupID == popupID){
                    popupMaskFunctions.splice(i,1);
                }
            });
            if(popupMaskFunctions.length){
                var info = popupMaskFunctions[popupMaskFunctions.length-1];
                var zIndex = 9999 + info.popupID;
                $('#'+popupMaskID).attr('class','ks-popup-mask ks-popup-mask--'+info.type).css({
                    zIndex:zIndex
                });
            }else{
                $('#'+popupMaskID).fadeOut(popupSpeed);
            }
        }
        /**弹窗 */
        function Popup(params){
            var that = this;
            popupID++;
            this.popupID = popupID;
            params = params || {};
            params.popupID = popupID;
            params.title  = params.title || '';
            if(params.type === 'alert' || params.type === 'confirm'){
                params.width  = params.width || '320px';
                params.height = params.height || 'auto';
                params.cancelButtonText = params.cancelButtonText || '取消';
                params.confirmButtonText = params.confirmButtonText || '确定';
            }else if(params.type === 'msg'){
                params.width = 'auto';
                params.height = 'auto';
            }else{
                params.width  = params.width || '800px';
                params.height = params.height || '400px';
            }
            this.params = params;
            this.$body = $('body');
            getArtTemplate(function(art){
                that.art = art;
                that.open();
            })
        }
        /**
         * 打开灰色遮罩层
         */
        Popup.prototype.showMask = function(){
            if(!document.getElementById(popupMaskID)){
                this.$body.append('<div id="'+popupMaskID+'"></div>');
            };
            var zIndex = 9999+this.popupID;
            $('#'+popupMaskID).attr('class','ks-popup-mask ks-popup-mask--'+this.params.type).css({
                zIndex:zIndex
            }).fadeIn(popupSpeed);
            popupMaskFunctions.push({
                type:this.params.type,
                popupID:this.popupID,
                function:this.params.cancel
            });   
        }
        
        /**
         * 关闭 popup
         */
        Popup.prototype.close = function(fn){
            var that = this;
            var $popup = $('#ks-popup'+this.popupID);
            $popup.animate({
                marginTop:-$popup.height()/2-10,
                opacity:0
            },popupSpeed,function(){
                $(this).remove();
                if(typeof fn === 'function'){
                    fn();
                };
                closePopupMask(that.popupID);
            });
        }
        /**
         * 显示popup
         */
        Popup.prototype.show = function(result){
            var that = this;
            this.$body.prepend(result);
            setTimeout(function(){
                
                var $popup = $('#ks-popup'+that.popupID);
                if(that.params.type === 'msg'){
                    $popup.css({
                        marginLeft:-$popup.width()/2,
                        marginTop:-$popup.height()/2-10
                    }).animate({
                        opacity:1,
                        marginTop:-$popup.height()/2
                    },popupSpeed,function(){
                        setTimeout(function(){
                            $popup.animate({
                                marginTop:-$popup.height()/2-10,
                                opacity:0
                            },popupSpeed,function(){
                                $(this).remove();
                                if(typeof that.params.cancel === 'function'){
                                    that.params.cancel();
                                }
                            });
                        },that.params.time || 3000);
                    });

                }else{
                    that.showMask();
                    $popup.css({
                        marginLeft:-$popup.width()/2,
                        marginTop:-$popup.height()/2-10
                    }).animate({
                        opacity:1,
                        marginTop:-$popup.height()/2
                    },popupSpeed);
                    var closeIconButton = document.getElementById('ks-popup-close'+that.popupID);
                    if(closeIconButton){
                        closeIconButton.onclick = function(){
                            that.close(that.params.cancel);
                        }
                    }
                    if(that.params.type === 'alert' || that.params.type === 'confirm'){
                        var confirmButton = document.getElementById('ks-popup-confirm-button'+that.popupID);
                        if(confirmButton){
                            confirmButton.onclick = function(){
                                if(typeof that.params.confirm === 'function'){
                                    that.params.confirm();
                                }
                                that.close();
                            }
                        }
                        if(that.params.type === 'confirm'){
                            var cancelButton = document.getElementById('ks-popup-cancel-button'+that.popupID);
                            if(cancelButton){
                                cancelButton.onclick = function(){
                                    that.close(that.params.cancel);
                                }
                            }
                        }
                    }
                }
            },100);
        }
        
        /**
         * 打开 popup
         */
        Popup.prototype.open = function(){
            var code = '<div class="ks-popup ks-popup--{{type}}" id="ks-popup{{popupID}}" style="width:{{width}};height:{{height}};z-index:{{10000+popupID}};opacity: 0;border-radius:{{radius}};">'+
                    '    {{if(type != \'msg\')}}'+
                    '    <div class="ks-popup-head">'+
                    '        <div class="ks-popup-head__close" id="ks-popup-close{{popupID}}"></div>'+
                    '        <div class="ks-popup-head__title">{{title}}</div>'+
                    '    </div>'+
                    '    {{/if}}'+
                    '    <div class="ks-popup-body">'+
                    '        {{if (type == \'open\')}}'+
                    '            {{if url}}'+
                    '            <iframe src="{{url}}" class="ks-popup-body__iframe"></iframe>'+
                    '            {{else}}'+
                    '            <div class="ks-popup-content" style="padding:{{contentPadding}}">'+
                                    this.params.content+
                                    '</div>'+
                    '            {{/if}}'+
                    '        {{else if(type == \'msg\')}}'+
                    '            <div class="ks-popup-content">{{content}}</div>'+
                    '        {{else}}'+
                    '            <div class="ks-popup-content{{icon ? \' ks-popup-content--takeicon\' : \'\'}}">'+
                    '                {{if icon}}'+
                    '                <img class="ks-popup-content__icon" src="/ks_inc/static/edu/images/popup/{{icon}}.png" />'+
                    '                {{/if}}'+
                                        this.params.content+
                    '            </div>'+
                    '            <div class="ks-popup-footer">'+
                    '                <div class="ks-button ks-button--primary ks-button--small" id="ks-popup-confirm-button{{popupID}}">{{confirmButtonText}}</div>'+
                    '                {{if(type == \'confirm\')}}'+
                    '                <div class="ks-button ks-button--small" id="ks-popup-cancel-button{{popupID}}">{{cancelButtonText}}</div>'+
                    '                {{/if}}'+
                    '            </div>'+
                    '        {{/if}}'+
                    '    </div>'+
                    '</div>';
            var render = this.art.compile(code);
            var result = render(this.params);
            this.show(result);
        }
        return Popup;
    })();
    var KS_Popup = {
        open:function(params){
            params = params || {};
            params.type = 'open';
            new popup(params);
        },
        alert:function(content,params){
            params = params || {};
            params.type = 'alert';
            params.content = content;
            params.title = params.title || '提示';
            new popup(params);
        },
        confirm:function(content,params){
            params = params || {};
            params.type = 'confirm';
            params.content = content;
            params.title = params.title || '提示';
            new popup(params);
        },
        msg:function(msg,params){
            params = params || {};
            params.type = 'msg';
            params.content = msg;
            new popup(params);
        }
    }
    var userLoginState = 0;
    var userInfo = {};
    updateUserInfo();
    /**
     * 更新用户信息
     */
    function updateUserInfo(){
        userLoginState = 0;
        $.get('/plus/ajaxs.ashx?a=checkislogin&json=1' + params_schoolid, function(res) {
            var isLogin = res.islogin === 'true';
            if (isLogin) {
                userLoginState = 1;
                userInfo = res;
            } else {
                userLoginState = 2;
                userInfo = res;
            }
        }, 'json');
    }
    /**
     * 获取用户信息
     * @param {Function} 已登录回调函数
     * @param {Function} 未登录回调
     * res 返回用户信息json
     */
    function getUserInfo(resolve, fail) {
        if(userLoginState > 0){
            if(userLoginState == 1){
                typeof resolve === 'function' && resolve(userInfo);
            }else{
                typeof fail === 'function' && fail(userInfo);
            }
        }else{
            setTimeout(function(){
                getUserInfo(resolve, fail);
            },500);
        }
    }

    /**
     * 获取用户id
     * @param resolve 回调函数 
     */
    function getUID(resolve) {
        if(userLoginState == 2){
            resolve();
        }else if (userLoginState == 1) {
            resolve(userInfo.userid,userInfo.apptoken);
        } else {
            setTimeout(function () {
                getUID(resolve);
            }, 500);
        }
    }

    /**
     *  获取用户appToken
     *  @param {Function} 回调函数
     */
    function getUserAppToken(resolve) {
        if(userLoginState === 2){
            resolve();
        }else if (userLoginState == 1) {
            resolve(userInfo.apptoken,userInfo.userid);
        } else {
            setTimeout(function() {
                getUserAppToken(resolve);
            }, 500);
        }
    }

    /**
     * 获取服务器时间
     */
    function getServerTime(resolve) {
        $.get('/plus/ajaxs.ashx?a=gettime', function(res) {
            typeof resolve === 'function' && resolve(res)
        })
    };
    
    /**
     * 加载artTemplate
     * @param resolve 回调函数
     */
    var isArtTemplateLoaded = false;
    var isArtCreateLoad = true;
    function getArtTemplate(resolve){
        if(isArtCreateLoad){
            isArtCreateLoad = false;
            var script = document.createElement('script');
            script.src = '/ks_inc/static/js/template-web.js';
            script.onload = function(){
                this.outerHTML = '';
                isArtTemplateLoaded = true;
                resolve(template)
            }
            document.body.appendChild(script);
            
            
        }else{
            if(isArtTemplateLoaded){
                resolve(template)
            }else{
                setTimeout(function(){
                    getArtTemplate(resolve)
                },100)
            }
        }
    }

    /**
     * 结束倒计时
     */
    function setCountdown(el) {
        var beginTime = $(el).attr('begin-time');
        if (beginTime) {
            beginTime = new Date($(el).attr('begin-time')).getTime();
            if (beginTime > SERVER_TIME) {
                $(el).html('未开始.');
                return false
            }
        }
        var endTime = new Date($(el).attr('end-time'))
        var type = $(el).attr('type') || 0;
        var nMS = endTime.getTime() - SERVER_TIME;
        var myD = Math.floor(nMS / (1000 * 60 * 60 * 24));
        var myH = Math.floor(nMS / (1000 * 60 * 60)) % 24;
        var myM = Math.floor(nMS / (1000 * 60)) % 60;
        var myS = Math.floor(nMS / 1000) % 60;
        var myMS = Math.floor(nMS / 100) % 10;
        var str = '';
        if (myD >= 0) {
            if (myD > 0) {
                if (type == 0) {
                    str += "<span><font class='d'>" + myD + "</font>天</span>";
                } else {
                    str += "<span class='d'>" + myD + "</span>:";
                }
            }
            if (type == 0) {
                str += "<span><font class='h'>" + myH + "</font>小时</span><span><font class='m'>" + myM + "</font>分</span><span><font class='s'>" + myS + "." + myMS + "</font>秒</span>";
            } else {
                str += "<span class='h'>" + myH + "</span>:<span class='m'>" + myM + "</span>:<span class='s'>" + myS + "</span>";
            }
        } else {
            str = "已结束.";
        }
        $(el).html(str);
    }

    /**
     * 创建轮播图
     * @param {Object} 
     */
    function creatCarouse(obj,Swiper) {
        var $obj = $(obj)
        var parameter = $obj.attr('drag-carousel').split(',');
        var params = {
            
        };
        var interval = 0;
        var pagination = '';
        var navigation = '';
        var width,height
        for (i = 0; i < parameter.length; i++) {
            var nodeName = parameter[i].split(':')[0];
            var nodeContent = parameter[i].split(':')[1];
            switch(nodeName){
                case 'width':
                    width = nodeContent
                    break
                case 'height':
                    height = nodeContent
                    break
                case 'speed':
                    params[nodeName] = Number(nodeContent)
                    break
                case 'interval':
                    interval = Number(nodeContent)
                    break
                case 'axis':
                    nodeName = 'direction' 
                    nodeContent = nodeContent === 'X' ? 'horizontal' : 'vertical'
                    params[nodeName] = nodeContent
                    break
                case 'autoPlay':
                    params['autoplay'] = nodeContent === 'true'
                    break
                case 'dots':
                    if(nodeContent == 1){
                        pagination = '<div class="swiper-pagination"></div>'
                    }
                    break
                case 'arrow':
                    if(nodeContent === 'true'){
                        navigation = '<div class="swiper-button-prev"></div><div class="swiper-button-next"></div>'
                    }
                    break
            }
        }
        if(params.autoplay){
            params.autoplay = {
                delay: interval || 3000,
                stopOnLastSlide: false,
                disableOnInteraction:false
            }
        }
        var swiperSlides = '';
        $obj.find('li').each(function(){
            var a = $(this).find('a');
            var link = ''
            if(a.length){
                link = a[0].outerHTML
            }
            swiperSlides += '<div class="swiper-slide" style="'+$(this).attr('style')+'">'+link+'</div>'
        })
        var swiperWrapper = '<div class="swiper-wrapper">'+swiperSlides+'</div>'+pagination+navigation
        $obj.addClass('swiper-container').html(swiperWrapper).removeAttr('drag-carousel')
        var initSize = function(){
            var $swiperSlide = $obj.find('.swiper-slide')
            if(width === 'window.innerWidth'){
                $obj.css('width',window.innerWidth)
                $swiperSlide.css('width',window.innerWidth)
            }else{
                $obj.width(width)
                $swiperSlide.width(width)
            }
            if(height === 'window.innerHeight'){
                $obj.css('height',window.innerHeight)
                $swiperSlide.css('height',window.innerHeight)
            }else{
                $obj.height(height)
                $swiperSlide.height(height)
            }
        }
        if(navigation){
            params.navigation = {
                nextEl: $obj.find('.swiper-button-next'),
                prevEl: $obj.find('.swiper-button-prev')
            }   
        }
        if(pagination){
            params.pagination = {
                el:$obj.find('.swiper-pagination'),
                clickable:true
            }
        }
        initSize()
        var swiper = new Swiper(obj,params)
        $(window).resize(function(){
            initSize()
            swiper.updateSize()
        })
    }

    /**
     * 获取购课车数量
     * <course-cart-num></course-cart-num>
     */
    function getCourseCartNum(resolve) {
        $.get('/index.aspx?c=course&a=shopcart&action=num' + params_schoolid, function(num) {
            $('course-cart-num').each(function() {
                this.innerHTML = num
            });
            typeof resolve === 'function' && resolve(num)
        })
    };

    var swiperLoaded = false;
    /**
     * 异步加载swiper
     * @param {Function} 加载完成回调函数
     */
    function getSwiper(resolve) {
        if (typeof Swiper === 'function') {
            resolve(Swiper)
        } else {
            if (swiperLoaded === false) {
                swiperLoaded = true;
                var swiperCss = document.createElement('link');
                swiperCss.rel = 'stylesheet';
                swiperCss.href = '/ks_inc/static/swiper/css/swiper.min.css';
                document.head.appendChild(swiperCss);

                var swiperJs = document.createElement('script');
                swiperJs.src = '/ks_inc/static/swiper/js/swiper.min.js';
                swiperJs.addEventListener('load', function() {
                    resolve(Swiper)
                });
                document.body.appendChild(swiperJs);
                
            } else {
                setTimeout(function() {
                    getSwiper(resolve)
                }, 500)
            }
        }
    }
    /**
     * 获取课程资料
     * <course-data course-id="{{Number}}"></course-data>
     */
    function getCourseData(el,props){
        var $el = $(el);
        var target = props.target;
        $.post("/WebApi/course/GetCosZLCourseID",{
            schoolid:schoolid,
            courseid: props.courseId
        },function(res){
            res.CosZLlist = res.CosZLlist || [];
            res.CosZLlist.map(function(item){
                switch(item.DocType){
                     case 'jpg':
                     case 'jpeg':
                     case 'gif':
                     case 'png':
                         item.$fileIco = 'jpg';
                         break
                     case 'pdf':
                         item.$fileIco = 'pdf';
                         break
                     case 'txt':
                         item.$fileIco = 'txt';
                         break
                     case 'ppt':
                         item.$fileIco = 'ppt';
                         break
                     case 'doc':
                     case 'docx':
                         item.$fileIco = 'word';
                         break
                     case 'mp4':
                     case 'mpg':
                     case 'avi':
                     case 'wmv':
                     case 'rmvb':
                     case 'flv':
                         item.$fileIco = 'video';
                         break
                     case 'mp3':
                     case 'wav':
                         item.$fileIco = 'mp3';
                     case 'rar':
                     case 'zip':
                         item.$fileIco = 'zip';
                         break
                     case 'xls':
                     case 'xlsx':
                         item.$fileIco = 'excel';
                         break
                     default:
                         item.$fileIco = 'white';   
                } 
             });
             getArtTemplate(function(art){
                 var code =  '<div class="ks-course-data">'+
                             '   {{if list.length > 0}}'+
                             '   {{each list item i}}'+
                             '   <div class="ks-course-data__item" data-url="{{item.view_url}}">'+
                             '       <div class="ks-course-data__name">'+
                             '           <img src="/ks_inc/static/edu/images/data/{{item.$fileIco}}.png" />'+
                             '           {{item.ZLName}}'+
                             '       </div>'+
                             '   </div>'+
                             '   {{/each}}'+
                             '   {{else}}'+
                             '   <div class="empty">没有找到任何资料！</div>'+
                             '   {{/if}}'+
                             '</div>';
                 var render = art.compile(code);
                 var renderRes = render({
                     list:res.CosZLlist
                 });
                 $el.html(renderRes).on('click','.ks-course-data__item',function(){
                    var url = $(this).attr('data-url');
                    KS_Utils.open(url,target)
                    
                 });
            });
        });
    }

    /**
     * 获取课程试卷
     * <course-exam course-id="{{Number}}"></course-exam>
     */
    function getCourseExam(el,props){
        var $el = $(el);
        var target = props.target;
        KS_Utils.getUserAppToken(function(apptoken,uid){
            $.post('/WebApi/course/GetPaper',{
                apptoken:apptoken,
                courseid:props.courseId,
                userid:uid,
                schoolid:schoolid,
            },function(res){
                getArtTemplate(function(art){
                    var code =  '<div class="ks-course-exam">'+
                                '   {{if !HasCoursePower}}'+
                                '   <div class="ks-alert ks-alert--warning" style="margin-bottom:10px;">你需要购买课程才能参与考试！</div>'+
                                '   {{/if}}'+
                                '   {{if list.length > 0}}'+
                                '   {{each list item i}}'+
                                '   <div class="ks-course-exam__item {{item.AllowExam && HasCoursePower ? \'\' : \'ks-course-exam__item--disabled\'}}" data-url="{{item.AllowExam && HasCoursePower ? item.PaperUrl : \'\'}}">'+
                                '       {{if item.AllowExam && HasCoursePower}}'+
                                '	    <div class="ks-button ks-button--mini">'+
                                '		    做题'+
                                '	    </div>'+
                                '       {{else}}'+
                                '	    <div class="ks-course-exam__lock"></div>'+
                                '       {{/if}}'+
                                '       <div class="ks-course-exam__name">'+
                                '	        {{item.PaperTitle}}'+
                                '       </div>'+
                                '       {{if !item.AllowExam}}'+
                                '       <div class="ks-course-exam__alert">'+
                                '           {{item.$text}}'+
                                '       </div>'+
                                '       {{/if}}'+
                                '   </div>'+
                                '   {{/each}}'+
                                '   {{else}}'+
                                '   <div class="empty">没有找到任何试卷！</div>'+
                                '   {{/if}}'+
                                '</div>';
                    var render = art.compile(code);
                    res.Paperlist.map(function(item){
                        if(!item.AllowExam){
                            var limit = item.Limit;
                            if(limit && limit.isexamlimit == 1){
                                if(limit.limit_type == 0){
                                    item.$text = '需要课程学习进度达到'+limit.learn_percent+'%才可以考试';
                                }else if(limit.limit_type == 1){
                                    item.$text = '需要所属课时学习进度达到'+limit.learn_percent+'%才可以考试';
                                }
                            }
                        }
                    });
                    var renderRes = render({
                        HasCoursePower:res.HasCoursePower,
                        list:res.Paperlist
                    });
                    $el.html(renderRes).on('click','.ks-course-exam__item',function(){
                        var url = $(this).attr('data-url');
						if(url){
							KS_Utils.open(url,target,{
								title:'试卷介绍'
							})
						}
                       
                    });
                });
            },'json');
        });
    }
    
    /**
     * 获取评论列表
     * 
     */
    function getEvaluationList(el,props){
        var $el = $(el);
        $el.html('<div class="ks-evaluation">'+
                '   <div class="ks-evaluation-comment"></div>'+
                '   <div class="ks-evaluation-list"></div>'+
                '</div>');
        this.$el = $el;
        this.cmttype = -1;
        this.infoid = props.infoId;
        if(!this.infoid){
            console.error('evaluation-list component missing infoid parameter')
            return
        }
        this.channelid = props.channelId || 10002;
        var ordertype = props.orderType;
        var unitName = (this.channelid == 4 && '商品') || (this.channelid == 10001 && '班级') || (this.channelid == 10002 && '课程') || (this.channelid == 10003 && '教师') || '内容';
        var that = this;
        getUserAppToken(function(apptoken){
            $.post('/webapi/user/DoUserComment',{
                apptoken:apptoken,
                channelid:that.channelid,
                id:that.infoid,
                ordertype:ordertype,
                schoolid:schoolid
            },function(res){
                var $comment = $el.find('.ks-evaluation-comment');
                if(!res.result){
                    if(res.msg.indexOf('还未学习过') !== -1){
                        $comment.html('<div class="ks-alert ks-alert--warning" style="margin-bottom:20px;">你需要参与学习才能评价课程！</div>')
                    }
                    return
                }
                var code =  '<div class="ks-evaluation-comment__head">'+
                            '     给该'+unitName+'打分'+
                            '     <div class="ks-evaluation-comment__score">'+
                            '         <div class="ks-evaluation-comment__star"></div>'+
                            '         <div class="ks-evaluation-comment__star"></div>'+
                            '         <div class="ks-evaluation-comment__star"></div>'+
                            '         <div class="ks-evaluation-comment__star"></div>'+
                            '         <div class="ks-evaluation-comment__star"></div>'+
                            '         <div class="ks-evaluation-comment__scoretext"></div>'+
                            '     </div>'+
                            '</div>'+
                            '<div class="ks-input-limit">'+
                            '    <div class="ks-input-limit__text">'+
                            '       0/200'+
                            '    </div>'+
                            '    <textarea class="ks-input" maxlength="200"></textarea>'+
                            '</div>'+
                            '<div class="ks-evaluation-comment__foot">'+
                            '    <div class="ks-button ks-button--primary ks-button--medium">'+
                            '       发表评价'+
                            '    </div>'+
                            '</div>';
                
                $comment.html(code);
                var $textarea = $comment.find('textarea');
                $comment.on('mouseenter','.ks-evaluation-comment__star',function(){
                    var index = $(this).index();
                    $(this).parent().find('.ks-evaluation-comment__star').each(function(i){
                        if(i <= index){
                            $(this).addClass('ks-evaluation-comment__star--on');
                        }else{
                            $(this).removeClass('ks-evaluation-comment__star--on');
                        }
                    });
                    var $scoretext = $el.find('.ks-evaluation-comment__scoretext');
                    if(index < 2){
                        $scoretext.text('差评');
                    }else if(index == 2){
                        $scoretext.text('中评');
                    }else if(index > 2){
                        $scoretext.text('好评');
                    }
                }).on('keyup','textarea.ks-input',function(){
                    $(this).prev('.ks-input-limit__text').text(this.value.length + '/200');
                }).on('click','.ks-button',function(){
                    var starLength = $comment.find('.ks-evaluation-comment__star--on').length;
                    if(!starLength){
                        KS_Popup.msg('请先打分！',{
                            time:2000
                        });
                        return
                    }
                    if(!$.trim($textarea.val())){
                        KS_Popup.msg('请先输入评论内容！',{
                            time:2000
                        });
                        $textarea.focus();
                        return
                    }
                    
                    $.post('/webapi/user/SaveUserComment',{
                        apptoken:apptoken,
                        channelid:that.channelid,
                        id:that.infoid,
                        orderid:res.orderid,
                        content:$textarea.val(),
                        ordertype:ordertype,
                        star:starLength
                    },function(res){
                        if(res.result){
                            KS_Popup.alert('评论成功',{
                                icon:'success',
                                confirm:function(){
                                    that.cmttype = -1;
                                    that.getCommentList();
                                    $comment.remove();
                                },
                                cancel:function(){
                                    that.cmttype = -1;
                                    that.getCommentList();
                                    $comment.remove();
                                }
                            });
                            
                        }else{
                            KS_Popup.alert(res.msg,{
                                icon:'error'
                            });
                        }
                    },'json');
                });
            },'json');
        });
        this.getCommentList();
        
    }
    getEvaluationList.prototype.getCommentList = function(p){
        p = p || 1;
        var $el = this.$el;
        var that = this;
        $.post('/webapi/user/GetUserCommentList',{
            cmttype:this.cmttype,
            page:p,
            pagesize:10,
            channelid:this.channelid,
            infoid:this.infoid,
            schoolid:schoolid
        },function(res){
            
            getArtTemplate(function(art){
                var render = art.compile('<div class="ks-evaluation-head">'+
                                        '       <div class="ks-button ks-button--small{{cmttype == -1 ? \' ks-button--primary\' : \'\'}}" data-cmttype="-1">全部</div>'+
                                        '       <div class="ks-button ks-button--small{{cmttype == 0 ? \' ks-button--primary\' : \'\'}}" data-cmttype="0">好评 ({{goodnum}})</div>'+
                                        '       <div class="ks-button ks-button--small{{cmttype == 1 ? \' ks-button--primary\' : \'\'}}" data-cmttype="1">中评 ({{averagenum}})</div>'+
                                        '       <div class="ks-button ks-button--small{{cmttype == 2 ? \' ks-button--primary\' : \'\'}}" data-cmttype="2">差评 ({{badnum}})</div>'+
                                        '</div>'+
                                        ' {{if(data.length)}}'+
                                        '   {{each data item i}}'+
                                        '   <div class="ks-evaluation__item">'+
                                        '       <div class="ks-evaluation__avatar ks-image">'+
                                        '           <img src="{{item.userface}}" onerror="KS_Utils.replaceDefaultImg(this)" type="user" />'+
                                        '       </div>'+
                                        '       <div class="ks-evaluation__name">{{item.username}}</div>'+
                                        '       <div class="ks-evaluation__satr">'+
                                        '            <div class="ks-evaluation__satr--on" style="width:{{item.$star_percentage}}%"></div>'+
                                        '       </div>'+
                                        '       <div class="ks-evaluation__comment">{{item.content}}</div>'+
                                        '   </div>'+
                                        '   {{/each}}'+
                                        '   <div class="ks-page-box"><div class="ks-page"></div></div>'+
                                        '   {{else}}'+
                                        '   <div class="empty">没有找到任何评论！</div>'+
                                        '   {{/if}}');
                                        
                res.cmttype = that.cmttype;
                domap(res.data,function(item){
                    item.$star_percentage = item.starnum / 5 * 100;
                });
                var code = render(res);
                $el.find('.ks-evaluation-list').html(code).find('.ks-evaluation-head .ks-button').click(function(){
                    var cmttype = $(this).attr('data-cmttype');
                    that.cmttype = cmttype;
                    that.getCommentList();
                });
                $el.find(".ks-page").sPage({
                    page:p,
                    pageSize:10,
                    total:res.totalcount,
                    prevPage:'<i class="icon-prev"></i>',
                    nextPage:'<i class="icon-next"></i>',
                    backFun:function(page){
                       that.getCommentList(page);
                    }
                });
            });
        });
    }


    /**
     * 将秒数转换 mm:ss 格式
     * @param ss 秒
     */
    function secondsConversion(ss) {
        var time = Number(ss);
        var hour = Math.floor(time / 3600);
        var minute = Math.floor((time - hour * 3600) / 60);
        var second = time - hour * 3600 - minute * 60
        hour = hour.toString().length < 2 ? '0' + hour : hour
        minute = minute.toString().length < 2 ? '0' + minute : minute
        second = second.toString().length < 2 ? '0' + second : second
        return hour === '00' ? minute + ':' + second : hour + ':' + minute + ':' + second
    }
    
    /**
     * 获取课时目录
     * <course-keshi course-id="{Number}" course-type="{String}" current="{Number}"></course-keshi>
     * @param el dom对象
     */
    function getCourseCatalog(el,props,isupdate){
        
        var $el = $(el);
        var target = props.target;
        var courseType = props.courseType;
        var styleType = props.styleType || 'default';
        var url = courseType === 'face' ? '/plus/ajaxs.ashx?a=getcosInfo&isface=1' + params_schoolid : '/plus/ajaxs.ashx?a=getcosInfo' + params_schoolid;
        var courseid = props.courseId;
        var current = props.current;
        var bindloaded = props.bindloaded;
        var bindchange = props.bindchange;
		
        if (courseid === undefined) {
            return false
        }
        $.get(url+'&courseid='+courseid,function(data){
            var coursebuyurl = data.Course.coursebuyurl;
            var teachway = data.Course.teachway;
            /**课程购买情况*/
            var specialPermission = false;
            var buyallcos_isCanLearn = false;
            var myPeriodids = [];
            var Pay = data.Pay;
			var isloginplay = data.isloginplay;
            var ispower = data.ispower;
          
            /**判断是否有特殊权限*/
            if (ispower == 1) {
                specialPermission = true

            } else if (Pay) {

                /**是否购买了整个课程*/
                var isbuyallcos = Pay.isbuyallcos;
                var shixian = Pay.shixian;
                if (isbuyallcos == 1) {
                    if (shixian == 0) {
                        /**该课程未限制时间*/
                        buyallcos_isCanLearn = true;
                    } else {
                        /**限制了时间，检查课程是否已过期*/
                        var enddate = new Date(Pay.enddate).getTime();
                        if (enddate > SERVER_TIME) {
                            buyallcos_isCanLearn = true
                        }
                    }

                } else {
                    var periodlist = Pay.periodlist;
                    domap(periodlist, function(period_item) {
                        var enddate = period_item.enddate ? new Date(period_item.enddate).getTime() : null;
                        var ids = period_item.periodids.split(',');
                        for (var p = 0; p < ids.length; p++) {
                            myPeriodids.push({
                                id: ids[p],
                                shixian: period_item.shixian,
                                enddate: enddate
                            });
                        }
                    });
                }
            }
            /**
             * 课程学习情况
             */
            var periodlist = data.Course.periodlist || [];
            var periods = [];
            var periodArr = [];
            var chapterIndex = 0;
            var sectionIndex = 0;
            var periodIndex = 0;
            /*重新构造目录结构*/
            domap(periodlist,function(item){
                var addtype = Number(item.addtype);
                var parentid = item.parentid;
                switch(addtype){
                    case 0:
                        /**章*/
                        chapterIndex++;
                        item.$id = chapterIndex;
                        item.$unit = '第 '+chapterIndex+' 章';
                        item.$textID = '第 '+chapterIndex+' 章';
                        item.$enname = 'chapter';
                        periods.push(item);
                        break
                    case 2:
                        /**节*/
                        item.$enname = 'section';
                        if(parentid == 0){
                            sectionIndex++;
                            item.$id = sectionIndex;
                            item.$unit = '第 '+sectionIndex+' 节';
                            item.$textID = '第 '+sectionIndex+' 节';
                            periods.push(item);
                        }else{
                            domap(periods,function(cpt,i){
                                if(cpt.periodid == parentid){
                                    if(!cpt.$childs){
                                        cpt.$childs = [];
                                    }
                                    item.$id = (i+1)+'.'+(cpt.$childs.length + 1);
                                    item.$unit = '第 '+(cpt.$childs.length + 1)+' 节';
                                    item.$textID = '第'+(i+1)+'章 '+ (cpt.$childs.length + 1) + '节';
                                    cpt.$childs.push(item);
                                }
                            })
                        }
                        break
                    case 1:
                    case 4:
                        /**
                         * isCanLearn
                         * 0 不可观看
                         * 1 可观看
                         * 2 已过期
                         * 3 可试听
                         */
                        item.$enname = 'period';
                        var isCanLearn = 0;
                        if (specialPermission || item.isfree == 0 || buyallcos_isCanLearn) {
                            /**该课时免费*/
                            isCanLearn = 1
                        } else if (item.islistening == 1) {
                            isCanLearn = 3
                        } else if (Pay) {
                            if (Pay.isbuyallcos == 1 && buyallcos_isCanLearn) {
                                /**
                                 * 购买了整个课程，并且课程未到期
                                 */
                                isCanLearn = 1;
                            } else {
                                /**
                                 * 按课时购买
                                 * 遍历当前课时是否存在购买队列，并且课时未到期
                                 */
                                for (var p = 0; p < myPeriodids.length; p++) {
                                    var period_item = myPeriodids[p];
                                    if (period_item.id == item.periodid) {
                                        if (period_item.shixian == 0) {
                                            isCanLearn = 1;
                                            break
                                        } else {
                                            if (period_item.enddate > SERVER_TIME) {
                                                /**课时未到期，已满足学习条件，直接跳出循环*/
                                                isCanLearn = 1;
                                                break
                                            } else {
                                                /**
                                                 * 当前课时已过期，但不跳出循环，继续查找是否有重复购买同课时并且满足学习条件
                                                 */
                                                if (period_item.islistening == 1) {
                                                    isCanLearn = 3
                                                } else {
                                                    isCanLearn = 2
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        
                        switch(Number(item.type)){
                            case 0:
                                item.$type_name = '视频';
                                break
                            case 1:
                                item.$type_name = '音频';
                                break
                            case 2:
                                item.$type_name = '图文';
                                break
                            case 3:
                                item.$type_name = 'PDF';
                                break
                            default:
                                item.$type_name = '';
                        }
                        /**课时时间处理 */
                        if(item.type > 1){
                            item.$duration = '';
                        }else if (item.timecount) {
                            var time = secondsConversion(item.timecount);
                            item.$duration = time;
                        }
                        /**直播时间 */
                        if(teachway == 5 && item.livetime && item.invaliddate){
                            var timestamp_liveTime = new Date(item.livetime);
                            var timestamp_invaliddate = new Date(item.invaliddate);
                            if(timestamp_liveTime > SERVER_TIME){
                                item.$liveStateText = '直播未开始';
                                item.$liveState = 0;
                            }else if(timestamp_liveTime < SERVER_TIME && timestamp_invaliddate > SERVER_TIME){
                                item.$liveStateText = '正在直播';
                                item.$liveState = 1;
                            }else if(timestamp_invaliddate < SERVER_TIME){
                                item.$liveStateText = '直播已结束';
                                item.$liveState = 2;
                            }
                            item.$livetime = timestamp_liveTime.getFullYear() + '/' + (timestamp_liveTime.getMonth() + 1) + '/' + timestamp_liveTime.getDate() + ' ' + timestamp_liveTime.getHours() + ':' + timestamp_liveTime.getMinutes();
                            
                            if(timestamp_liveTime.getFullYear() === timestamp_invaliddate.getFullYear() && timestamp_liveTime.getMonth() === timestamp_invaliddate.getMonth() && timestamp_liveTime.getDate() === timestamp_invaliddate.getDate()){
                                item.$invaliddate = timestamp_invaliddate.getHours() + ':' + timestamp_invaliddate.getMinutes()
                            }else{
                                item.$invaliddate = timestamp_invaliddate.getFullYear() + '/' + (timestamp_invaliddate.getMonth() + 1) + '/' + timestamp_invaliddate.getDate() + ' ' + timestamp_invaliddate.getHours() + ':' + timestamp_invaliddate.getMinutes();
                            }
                            item.$showLiveTime = true;
                        }

                        /**课时状态*/
                        var stateText = '去购买';
                        
                        switch(isCanLearn){
                            case 1:
                                if(teachway == 5){
                                    stateText = '进入直播';
                                }else{
                                    if(item.haslearnpercent > 0){
                                        stateText = '继续学习';
                                    }else{
                                        stateText = '开始学习';
                                    }
                                }
                                break
                            case 2:
                                stateText = '已过期';
                                break
                            case 3:
                                if(teachway == 5){
                                    stateText = '进入直播';
                                }else{
                                    stateText = '免费观看';
                                }
                                break
                        }
                        item.$stateText = stateText;
                        item.$isCanLearn = isCanLearn;
                        /**更多按钮 */
                        var btns = [];
                        /**课时存在题库 */
                        if(item.haspapertk){
                            btns.push({
                                text:'题库练习',
                                url:item.exerciseinfo.exercise_url,
                                className:'ks-catalog-title__btn-lx',
                                type:0
                            },{
                                text:'练习记录',
                                url:item.exerciseinfo.exercise_record_url,
                                className:'ks-catalog-title__btn-record',
                                type:1
                            });
                        }
                        /**课时存在资料 */
                        if(item.hasmaterial){
                            var obj = {
                                text:'课时资料',
                                url:item.zlurl,
                                className:'ks-catalog-title__btn-down',
                                type:2
                            };
                            btns.push(obj);
                        }
                        item.$btns = btns;
                        item.$state = (isCanLearn === 1 || isCanLearn === 3) ? true : false;
                        var url = (isCanLearn === 1 || isCanLearn === 3) ? item.url : coursebuyurl;
                        if(item.periodlock !== 'true'){
                            item.$url = url;
                        }
                        if(item.money){
                            item.$money = parseFloat(item.money) ? parseFloat(item.money).toFixed(2) : false;
                        }
                        if(parentid == 0){
                            periodIndex++;
                            item.$unit = '课时 '+periodIndex;
                            item.$textID = '课时 '+periodIndex;
                            periods.push(item);
                        }else{
                            domap(periods,function(cpt,c){
                                if(cpt.periodid == parentid){
                                    if(!cpt.$childs){
                                        cpt.$childs = [];
                                    }
                                    var _unit = cpt.addtype == 0 ? '章' : '节';
                                    item.$unit = '课时 '+(cpt.$childs.length+1);
                                    item.$textID = '第'+(c+1)+_unit;
                                    cpt.$childs.push(item);
                                }else if(cpt.$childs){
                                    domap(cpt.$childs,function(sec,s){
                                        if(sec.periodid == parentid){
                                            if(!sec.$childs){
                                                sec.$childs = [];
                                            }
                                            item.$unit = '课时 '+(sec.$childs.length+1);
                                            item.$textID = '第'+(c+1)+'章 第'+(s+1)+'节';
                                            sec.$childs.push(item);
                                        }
                                    });
                                }
                            });
                        }
                        periodArr.push(item);
                        break
                }
            });
            getArtTemplate(function(art){
                var commonCode = function(objname){
                    return  '<div class="ks-catalog-title">'+
                            '   <div class="ks-catalog-title__th{{'+objname+'.$url ? \' ks-catalog-title__th--pointer\' : \'\'}}" data-url="{{'+objname+'.$url}}" data-periodid="{{'+objname+'.periodid}}">'+
                            '       {{if('+objname+'.$enname == \'period\')}}'+
                            '           {{if '+objname+'.periodlock == \'true\' }}'+
                            '           <div class="ks-catalog-title__lock"></div>'+
                            '           {{/if}}'+
                            '           {{if '+objname+'.$btns.length > 0 && styleType == \'default\'}}'+
                            '           <div class="ks-catalog-title__more"></div>'+
                            '           {{/if}}'+
                            '           {{if('+objname+'.periodlock != \'true\' && courseType != \'face\')}}'+
                            '               {{if('+objname+'.$state)}}'+
                            '               <a class="ks-button ks-button--small ks-button--success" href="javascript:;" data-periodid="{{'+objname+'.periodid}}" data-url="{{'+objname+'.$url}}"'+target+'>{{'+objname+'.$stateText}}</a>'+
                            '               {{else}}'+
                            '               <a class="ks-button ks-button--small ks-button--warning" href="{{'+objname+'.$url}}" '+target+'>{{'+objname+'.$stateText}}</a>'+
                            '               {{/if}}'+
                            '           {{/if}}'+
                            '           {{if('+objname+'.$showLiveTime)}}'+
                            '           <div class="ks-catalog-title__time ks-catalog-title__type-live ks-catalog-title__live-state{{'+objname+'.$liveState}}">{{'+objname+'.$liveStateText}}{{if styleType == \'default\'}}<span> - {{'+objname+'.$livetime}} ~ {{'+objname+'.$invaliddate}}{{/if}}</span></div>'+
                            '           {{else if(courseType == \'face\')}}'+
                            '               {{if '+objname+'.isfree == 1}}'+
                            '               <div class="ks-catalog-title__money"></div>'+
                            '               {{else if '+objname+'.$money}}'+
                            '               <div class="ks-catalog-title__money">¥{{'+objname+'.$money}}</div>'+
                            '               {{/if}}'+
                            '               {{if '+objname+'.starttime}}'+
                            '               <div class="ks-catalog-title__time">开课时间：{{'+objname+'.starttime}} - {{'+objname+'.endtime}}</div>'+
                            '               {{/if}}'+
                            '           {{else}}'+
                            '           <div class="ks-catalog-title__time ks-catalog-title__type{{'+objname+'.type}}">{{'+objname+'.$duration}}</div>'+
                            '           {{/if}}'+
                            '       {{/if}}'+
                            '       {{if('+objname+'.$childs && styleType == \'default\')}}'+
                            '       <div class="ks-catalog-title__arrow"></div>'+
                            '       {{/if}}'+
                            '       <span class="ks-catalog-title__periodname">{{'+objname+'.$unit}}：{{'+objname+'.periodname}}</span>'+
                            '       {{if('+objname+'.$isCanLearn == 3)}}'+
                            '       <div class="ks-catalog-title__try ks-tag ks-tag--small ks-tag--primary">试看</div>'+
                            '       {{/if}}'+
                            '   </div>'+
                            '   {{if('+objname+'.$enname == \'period\' && '+objname+'.$btns.length)}}'+
                            '   <div class="ks-catalog-title__btns">'+
                            '       {{each '+objname+'.$btns bt b}}'+
                            '       <a class="ks-catalog-title__btn {{bt.className}}" href="javascript:;" data-url="{{bt.url}}" data-periodid="{{'+objname+'.periodid}}" data-type="{{bt.type}}">{{bt.text}}</a>'+
                            '       {{/each}}'+
                            '   </div>'+
                            '   {{if '+objname+'.haslearnpercent > 0 && styleType == \'default\'}}'+
                            '   <div class="ks-catalog-schedule">'+
                            '       <div class="ks-catalog-schedule__learned" style="width: {{'+objname+'.haslearnpercent}}%;"></div>'+
                            '   </div>'+
                            '   {{/if}}'+
                            '   {{/if}}'+
                            '   {{if(styleType == \'axis\')}}'+
                            '       {{if('+objname+'.$enname == \'period\')}}'+
                            '       <div class="ks-catalog-schedot">'+
                            '           <div class="ks-catalog-schedot__learned" style="height:{{'+objname+'.haslearnpercent}}%;"></div>'+
                            '       </div>'+
                            '       {{else}}'+
                            '       <div class="ks-catalog-title__id ks-catalog-title__id--{{'+objname+'.$enname}}">{{'+objname+'.$id}}</div>'+
                            '       {{/if}}'+
                            '   {{/if}}'+
                            '</div>'+
                            '{{if('+objname+'.$enname == \'period\' && styleType == \'axis\')}}'+
                            '<div class="ks-catalog-period-info">'+
                            '   {{'+objname+'.$unit}}：{{'+objname+'.periodname}}'+
                            '</div>'+
                            '{{/if}}';
                }
                var code =  '<div class="ks-catalog ks-catalog--{{styleType}}">'+
                            '   {{if(periods.length)}}'+
                            '   {{each periods chapter c}}'+
                            '   <div class="ks-catalog-{{chapter.$enname}}{{current == chapter.periodid ? \' active\' : \'\'}}">'+
                                    commonCode('chapter')+
                            '       {{if(chapter.$childs)}}'+
                            '       {{each chapter.$childs section s}}'+
                            '       <div class="ks-catalog-{{section.$enname}}{{current == section.periodid ? \' active\' : \'\'}}">'+
                                        commonCode('section')+
                            '           {{if(section.$childs)}}'+
                            '           {{each section.$childs period p}}'+
                            '           <div class="ks-catalog-period{{current == period.periodid ? \' active\' : \'\'}}">'+
                                            commonCode('period')+
                            '            </div>'+
                            '           {{/each}}'+
                            '           {{/if}}'+
                            '        </div>'+
                            '       {{/each}}'+
                            '       {{/if}}'+
                            '    </div>'+
                            '   {{/each}}'+
                            '   {{else}}'+
                            '   <div class="empty">老师正在筹备内容，敬请期待！</div>'+
                            '   {{/if}}'+
                            '</div>';
                if(styleType === 'slide'){
                    code =  '<div class="ks-catalog ks-catalog--{{styleType}}">'+
                            '   <div class="swiper-wrapper">'+
                            '       {{each periodArr period i}}'+
                            '       <div class="swiper-slide{{current == period.periodid ? \' active\' : \'\'}}">'+
                            '           <div class="ks-catalog-period" data-lock="{{period.periodlock}}" data-url="{{period.$url}}" data-periodid="{{period.periodid}}">'+
                            '               <div class="ks-catalog-period__type">{{period.$type_name}}</div>'+
                            '               <div class="ks-catalog-title">{{i+1}}.{{period.periodname}}</div>'+
                            '               {{if period.periodlock == \'true\' }}'+
                            '               <div class="ks-catalog-period__lock"></div>'+
                            '               {{/if}}'+
                            '           </div>'+
                            '       </div>'+
                            '       {{/each}}'+
                            '   </div>'+
                            '</div>'
                }
                var render = art.compile(code);
                var catalog = render({
                    courseType:courseType,
                    current:current,
                    isperiodlock:data.Course.isperiodlock,
                    periodunlockpercent:data.Course.periodunlockpercent,
                    styleType:styleType,
                    periods:periods,
                    periodArr:periodArr
                });
                
                var closePeriosBtns = function(btns){
                    $el.find(btns).animate({
                        marginTop:'-10px',
                        opacity:0
                    },200,function(){
                        $(this).hide();
                    });
                }
                
                if(styleType === 'slide'){
                    $el.html(catalog).on('click','.ks-catalog-period',function(){
                        var lock = $(this).attr('data-lock');
                        if(lock === 'true'){
                            KS_Utils.popup.alert('该课时需要上个课时学习达到'+data.Course.periodunlockpercent+'%才能开启');
                            return
                        }
                        var url = $(this).attr('data-url');
                        if(!url){
                            return
                        }
                        
                        if (bindchange && typeof window[bindchange] === 'function') {
                         
                            var periodid = $(this).attr('data-periodid');
                            domap(periodlist,function(item){
                                if(item.periodid == periodid){
                                    window[bindchange](url,item,isloginplay);
                                }
                            });
                        }else if(url){
                            if(target === '_blank'){
                                window.open(url);
                            }else{
                                location.href = url;
                            }
                        }
                    });
                    var _initialSlide = 0;
                    domap(periodArr,function(period,i){
                        if(period.periodid == current){
                            _initialSlide = i;
                        }
                    });
                    getSwiper(function(Swiper){
                        new Swiper($el.find('.ks-catalog'), {
                            slidesPerView:2.5,
                            paginationClickable: true,
                            spaceBetween: 0,
                            initialSlide:_initialSlide
                        });
                    });
                }else{
                    if(styleType === 'default'){
                        $(document).click(function(){
                            closePeriosBtns('.ks-catalog-title__btns');
                        });
                    }
                    var isMove = false;
                    $el.html(catalog).on('click','.ks-catalog-title__arrow',function(){
                        var className = 'ks-catalog-title__arrow--pullup';
                        if($(this).hasClass(className)){
                            $(this).removeClass(className).parents('.ks-catalog-title').first().nextAll().show();
                        }else{
                            $(this).addClass(className).parents('.ks-catalog-title').first().nextAll().hide();
                        }
                    }).on('click','.ks-catalog-title__th',function(){
                        var url = $(this).attr('data-url');
          
                        var periodid = $(this).attr('data-periodid');
                 
                        if (bindchange && typeof window[bindchange] === 'function') {
                            
                            domap(periodlist,function(item){
                                if(item.periodid == periodid){
                        
                                    window[bindchange](url,item,isloginplay);
                                }
                            });
                        }else if(url){
                  
                            if(target === '_blank'){
                                window.open(url);
                            }else{
                                location.href = url;
                            }
                        }
                    }).on('click','.ks-catalog-title__more',function(e){
                        var event = e || window.event;
                        event.stopPropagation();
                        var $btns = $(this).parents('.ks-catalog-title').first().find('.ks-catalog-title__btns');
                        $('.ks-catalog-title__btns').each(function(){
                            if(this !== $btns[0]){
                                closePeriosBtns(this);
                            }
                        });
                        if($btns.css('display') === 'block'){
                            closePeriosBtns($btns[0]);
                        }else{
                            $btns.css({
                                display:'block',
                                marginTop:'-10px',
                                opacity:0
                            }).animate({
                                marginTop:'0px',
                                opacity:1
                            },200);
                        }
                        
                    }).on('click','.ks-catalog-title__btn',function(){
                        var $this = $(this);
                        var type = $this.attr('data-type');
                        var url = $this.attr('data-url');
                        var periodid = $this.attr('data-periodid');
                        if(type == 0){
                            domap(periodlist,function(item){
                                if(item.periodid == periodid){
                                    if(item.$isCanLearn == 1){
										KS_Utils.open(url,target,{
											title:$this.text()
										})
                                        
                                    }else{
                                        KS_Popup.alert('购买课程后才可以考试！',{
                                            icon:'warning'
                                        })
                                    }
                                }
                            })
                        }
                        else if(type == 2){
                            
                            domap(periodlist,function(item){
                                if(item.periodid == periodid){
                                    var materiallist = item.materiallist;
                                    var code = '';
                                    if(window.innerWidth <= 800){
                                        code =  '<table width="100%" class="ks-catalog-data" cellpadding="0px" cellspacing="0px">'+
                                                '    <tr class="ks-catalog-data__head">'+
                                                '       <td>'+
                                                '        资料名称'+
                                                '       </td>'+
                                                '       <td width="80px">预览</td>'+
                                                '    </tr>'+
                                                '   {{each list item i}}'+
                                                '    <tr class="ks-catalog-data__item">'+
                                                '       <td class="ks-catalog-data__title">'+
                                                '        {{item.zlname}}'+
                                                '        <p style="font-size:12px;color:#999;position: relative;top: -7px;">{{item.doctype}}</p>'+
                                                '       </td>'+
                                                '       <td align="center"><a href="javascript:;" onclick="KS_Utils.open(\'{{item.zlurl}}\')" class="ks-button ks-button--small">预览</a></td>'+
                                                '    </tr>'+
                                                '   {{/each}}'+
                                                '</table>';
                                    }else{
                                        code =  '<table width="100%" class="ks-catalog-data" cellpadding="0px" cellspacing="0px">'+
                                                '    <tr class="ks-catalog-data__head">'+
                                                '       <td>'+
                                                '        资料名称'+
                                                '       </td>'+
                                                '       <td width="150px">资料类型</td>'+
                                                '       <td width="100px">预览</td>'+
                                                '    </tr>'+
                                                '   {{each list item i}}'+
                                                '    <tr class="ks-catalog-data__item">'+
                                                '       <td class="ks-catalog-data__title">'+
                                                '        {{item.zlname}}'+
                                                '       </td>'+
                                                '       <td class="ks-catalog-data__type" align="center">{{item.doctype}}</td>'+
                                                '       <td align="center"><a href="javascript:;" onclick="KS_Utils.open(\'{{item.zlurl}}\',\'_blank\')" class="ks-button ks-button--small">预览</a></td>'+
                                                '    </tr>'+
                                                '   {{/each}}'+
                                                '</table>';
                                    }
                                    
                                    
                                    var render = art.compile(code);
                                    var dataList = render({
                                        list:materiallist
                                    });
                                    if(window.innerWidth <= 800){
                                        KS_Popup.open({
                                            title:'课时资料',
                                            content:dataList,
                                            width:'100%',
                                            height:'100%',
                                            radius:'0px',
                                            contentPadding:'0px'
                                        });
                                    }else{
                                        KS_Popup.open({
                                            title:'课时资料',
                                            content:dataList,
                                            width:'800px',
                                            height:'460px'
                                        });
                                    }
                                    
                                }
                            });
                        }else{
							KS_Utils.open(url,target)
							
                        }
                    }).on('mouseenter','.ks-catalog-period',function(){
                        if(styleType === 'axis'){
                            isMove = this;
                            var that = this;
                            setTimeout(function(){
                                if(isMove === that){
                                    isMove = false;
                                    var $info = $(that).find('.ks-catalog-period-info');
                                    $info.css({
                                        display:'block',
                                        opacity:0,
                                        top:-$info.outerHeight() - 10
                                    }).animate({
                                        opacity:1,
                                        top:-$info.outerHeight()
                                    },200);
                                }
                            },500);
                            
                        }
                    }).on('mouseleave','.ks-catalog-period',function(){
                        isMove = false;
                        var $info = $(this).find('.ks-catalog-period-info');
                        if($info.length){
                            $info.stop().animate({
                                opacity:0,
                                top:-$info.outerHeight()-10
                            },200,function(){
                                $(this).hide();
                            });
                        }
                        
                    }).on('mouseenter','.ks-catalog-title__lock',function(){
                        showPopover(this,'该课时需要上个课时学习达到'+data.Course.periodunlockpercent+'%才能开启',{
                            width:'220px',
                            icon:'warning'
                        });
                    }).on('mouseleave','.ks-catalog-title__lock',function(){
                        hidePopover();
                    });
                }
                
                if (!isupdate && bindloaded && typeof window[bindloaded] === 'function') {
                    window[bindloaded]({
                        current: current,
                        periodlist: periodlist,
                        data: data
                    });
                }
            });
        },'json');
    }
    
     /**
     * 打开 Popover 弹出框
     */
    function showPopover(el,content,other){
        var $el = $(el);
        other = other || {};
        if(!document.getElementById('ks-popover')){
            $('body').append('<div class="ks-popover" id="ks-popover"></div>');
        }
        var $popover = $('#ks-popover');
        if(other.icon){
            $popover.addClass('ks-popover--takeicon');
            $popover.html('<div class="ks-popover__icon"><img src="/ks_inc/static/edu/images/popover/icon_'+other.icon+'.png" /></div>'+content);
        }else{
            $popover.removeClass('ks-popover--takeicon');
            $popover.html(content);
        }
        var offset = $el.offset();
        var cssData = {
            display:'block'
        }
        if(other.width){
            cssData.width = other.width;
        }
        if(offset.top - window.scrollY < window.innerHeight / 2){
            cssData.top = offset.top + $el.outerHeight();
            $popover.addClass('ks-popover--top');
        }else{
            cssData.top = offset.top - $popover.outerHeight();
            $popover.removeClass('ks-popover--top');
        }
        if(offset.left < window.innerWidth / 2){
            cssData.left = offset.left + $el.outerWidth() / 2 - $el.outerWidth() / 2;
            $popover.removeClass('ks-popover--left');
        }else{
            cssData.left = offset.left - $popover.outerWidth() + $el.outerWidth() / 2 + 17;
            $popover.addClass('ks-popover--left');
        }
        $popover.css(cssData).mouseenter(function(){
            $(this).show();
        }).mouseleave(function(){
            $(this).hide();
        });
    }
    
    /**
     * 关闭 Popover 弹出框
     */
    function hidePopover(){
        if(document.getElementById('ks-popover')){
            var $popover = $('#ks-popover');
            $popover.hide();
        }
    }
    /*
     * 获取训练营目录
     */
    function getCampDirectory(el) {
        var $el = $(el);
        var type = $el.attr('train-type');
        var target = $el.attr('target') === '_blank' ? ' target="_blank"' : '';
        var trainid = $el.attr('train-id');
        var getUrl = '/plus/ajaxs.ashx?a=gettraincamp&trainid=' + trainid;
        var getUrl2 = '/plus/ajaxs.ashx?a=gettraincatalogue&trainid=' + trainid

        var current = $el.attr('current');
        var callback = $el.attr('callback');
        if (trainid === undefined) {
            return false
        }
        //$el.html('<div class="chapter-loading">加载中...</div>');
        if (type == 'inner') {
            $el.append('<div id="camp-directory"><div class="camp-directory_item"></div></div><div class="camp-nobuy-tips">您还未购买，暂不能查看</div>')
            $('#camp-directory').css('margin-top', 0)
            getDirectory($el.attr('camp-id'), 1)

        } else {
            $.ajax({
                type: 'get',
                dataType: 'json',
                url: getUrl,
                success: function(data) {
                    var camplist = data.traincamp.camplist
                    if (camplist && camplist.length) {
                        $el.append('<div class="camp-list-box"><span class="camp-list-arrow arrow-prev"></span><div class="camp-list-con"><ul class="camp-list swiper-wrapper"></ul></div><span class="camp-list-arrow arrow-next"></span></div><div id="camp-directory"><div class="camp-directory_item"></div></div><div class="camp-nobuy-tips">您还未购买，暂不能查看</div>')

                        //赋值营期列表
                        var campListLi = '';
                        camplist.map(function(item) {
                            var is_buy
                            if (item.isfree == '1') {
                                is_buy = item.is_buy == 0 ? '<i class="lock-p"></i>' : ''
                            } else {
                                is_buy = ''
                            }
                            campListLi += '<li class="swiper-slide"><div class="camp-list_item" data-campid="' + item.campid + '" data-isfree="' + item.isfree + '"><p>' + is_buy + item.campname + '</p></div></li>'
                        })

                        //点击切换营期内容
                        $('.camp-list').html(campListLi).find('.camp-list_item').click(function() {
                            $(this).parent('li').addClass('curr').siblings().removeClass('curr')
                            // getDirectory($(this).attr('data-campid'),0,camplist.length)
                            getDirectory($(this).attr('data-campid'),0)
                        })

                        //默认选中第一个营期内容
                        $('.camp-list li:eq(0)').addClass('curr')
                        // getDirectory($('.camp-list .curr .camp-list_item').attr('data-campid'),0,camplist.length)
                        getDirectory($('.camp-list .curr .camp-list_item').attr('data-campid'),0)
                        
                        getSwiper(function(Swiper) {
                            //Number($el.attr('train-num'))
                            new Swiper($el.find('.camp-list-con'), {
                                slidesPerView: Number($el.attr('train-num')),
                                paginationClickable: true,
                                spaceBetween: 0
                            });
                        })

                    } else {
                        $el.html('<div class="empty">对不起，没有找到任何记录！</div>')
                    }

                },
                error: function() {
                    var msg = '数据请求失败了，程序员正在抢修中...';
                    $el.html('<div class="data-errer">' + msg + '</div>');
                    if (callback && typeof window[callback] === 'function') {
                        window[callback]({
                            error: msg
                        })
                    }
                }
            });
        }
        //请求任务显示
        function getDirectory(campid, type,campnum) {
            $.ajax({
                type: 'get',
                dataType: 'json',
                url: getUrl2 + '&campid=' + campid,
                success: function(data) {

                    //赋值营期的内容列表
                    var directory = data.campperiod.cataloguelist
                    var directoryInfo = data.campperiod
                    var isfree = data.campperiod.isfree
                    var is_buy
					var buy_btn
					
                    if (directoryInfo.is_buy == 0) {
                        
                        if (isfree == '0') {
                            is_buy = ''
                        } else {
                            is_buy = '<span>未购买</span>'
                        }
						buy_btn = '<a href="' + directoryInfo.view_url + '" class="camp-directory_buy-btn">立即购买</a>'
                    } else {
                        
                        is_buy = ''
						if(data.campperiod.is_addlearnrecord==0){
							buy_btn = '<a href="' + directoryInfo.view_url + '" class="camp-directory_buy-btn">立即加入</a>'
						}else{
							buy_btn = ''
						}
                    }
                    var price
                    if (isfree == '0') {
                        if(data.campperiod.issingle_buy){
                            price = '<span class="free_cor">免费</span>'
                        }else{
                            price = ''
                        }
                        
                    } else {
                        price = '<span>￥' + directoryInfo.price + '</span>'
                    }
                    var directory_info
                    if(campnum==1){
                        
                        directory_info = '<div class="fl camp-directory_item-left">' +
                        '	<div class="fl camp-directory_item-img">' +
                        '		<img src="' + directoryInfo.image + '" onerror="KS_Utils.replaceDefaultImg(this)">' +
                        '	</div>' +
                        '	<div class="fl camp-directory_item-con">' +
                        '		<h3 class="camp-directory_item-title"><a href="' + directoryInfo.view_url + '">' +
                        directoryInfo.campname + '</a>' + is_buy +
                        '    	</h3>' +
                        '    	<p>开课时间：' + directoryInfo.begintime + '~' + directoryInfo.endtime + '</p>' +
                        '    	<p>报名时间：' + directoryInfo.bmbegintime + '~' + directoryInfo.bmendTime + '</p>' +
                        '    	<p>' +
                        '        	<span>' + directoryInfo.student_count + '人正在学习</span>' +
                        '        	<span>总学分：' + directoryInfo.sum_credit + '</span>' +
                        '        	<span>通过学分：' + directoryInfo.pass_credit + '</span>' +
                        '    	</p>' +
                        '	</div>' +
                        '</div>'

                    }else{
                        directory_info = '<div class="fl camp-directory_item-left">' +
                        '	<div class="fl camp-directory_item-img">' +
                        '		<img src="' + directoryInfo.image + '" onerror="KS_Utils.replaceDefaultImg(this)">' +
                        '	</div>' +
                        '	<div class="fl camp-directory_item-con">' +
                        '		<h3 class="camp-directory_item-title"><a href="' + directoryInfo.view_url + '">' +
                        directoryInfo.campname + '</a>' + is_buy +
                        '    	</h3>' +
                        '    	<p>开课时间：' + directoryInfo.begintime + '~' + directoryInfo.endtime + '</p>' +
                        '    	<p>报名时间：' + directoryInfo.bmbegintime + '~' + directoryInfo.bmendTime + '</p>' +
                        '    	<p>' +
                        '        	<span>' + directoryInfo.student_count + '人正在学习</span>' +
                        '        	<span>总学分：' + directoryInfo.sum_credit + '</span>' +
                        '        	<span>通过学分：' + directoryInfo.pass_credit + '</span>' +
                        '    	</p>' +
                        '	</div>' +
                        '</div>' +
                        '<div class="fr camp-directory_item-right">' +
                        '	<div class="camp-directory_item-price">' + price + '</div>' +buy_btn+
                        '</div>'
                    }

                    var directory_list = ''
                    if (directory && directory.length) {
                        directory.map(function(item) {
                            var task_list = ''
                            item.child.map(function(citem) {

                                //判断是否必填
                                var must_learn = citem.must_learn == true ? '（必修）' : ''

                                //判断是否可以试看
                                var try_it,
                                    a_url;
									
									
                                if (isfree == '1') {

                                    if (directoryInfo.is_buy == 0) {
										//try_it = citem.try_it == true ? '<span class="fr free try-it">可试看</span>' : '<span class="fr free lock-it"></span>'
										try_it = '<span class="fr free lock-it"></span>'
										if(citem.task_url==''){
											a_url = '<a class="keshi-url" onClick="showTips(\'暂不能查看\')">'
										}else{
											a_url = '<a class="keshi-url" onClick="showTips(\'您还未购买，暂不能查看\')">'
										}
                                        
                                    } else {
										try_it = ''
										if(directoryInfo.is_addlearnrecord == 0){
											a_url = '<a class="keshi-url" onClick="showTips(\'未加入营期\')">'
										}else{
											if(citem.task_url==''){
												a_url = '<a class="keshi-url" onClick="showTips(\'暂不能查看\')">'
											}else{
												a_url = '<a href="' + citem.task_url + '" class="keshi-url" target="_blank">'
											}
										}
										
                                    }
                                } else {
									
                                    try_it = ''
									if(citem.task_url==''){
										a_url = '<a class="keshi-url" onClick="showTips(\'暂不能查看\')">'
									}else{
										if(directoryInfo.is_addlearnrecord == 0){
											a_url = '<a class="keshi-url" onClick="showTips(\'未加入营期\')">'
										}else{
											a_url = '<a href="' + citem.task_url + '" class="keshi-url" target="_blank">'
										}
										
									}
                                }

                                //赋值任务列表
                                task_list += '<div class="keshi" data-infoid="' + citem.infoid + '">'
                                    //+'	<a href="'+citem.task_url+'" class="keshi-url" target="_blank" data-isfree="'+isfree+'" data-isbuy="'+directoryInfo.is_buy+'" data-tryit="'+citem.try_it+'">'
                                    +
                                    a_url +
                                    '	<div class="learn-state">' +
                                    '		<span class="schedule-icon0"></span>' +
                                    '	</div><i class="directory_item-type">' + citem.type_name + '</i>' + citem.title + '<span class="red-font camp-tips">' + must_learn + '</span>' + try_it + '<span class="keshi-duration">（' + citem.credit + '学分）</span></a>' +
                                    '</div>'
                            })
                            directory_list += '<div class="section">' +
											'   <div class="section-name">' +item.periodname +
											'   </div>' +
											'   <div class="section-box" data-periodid="' + item.periodid + '">' +
											task_list +
											'   </div>' +
											'</div>'
                        })


                    } else {
                        directory_list = '<div class="empty">对不起，没有找到任何记录！</div>'
                    }
                    if (type == 1) {
                        $('.camp-directory_item').html('<div class="camp-directory_item-list">' + directory_list + '</div>')
                    } else {
                        $('.camp-directory_item').html('<div class="camp-directory_item-info clearfix">' + directory_info + '</div><div class="camp-directory_item-list">' + directory_list + '</div>')
                    }

                    // if($('.camp-list li').length==1){
                    //     $('.camp-directory_item-right').hide();
                    // }
                },
                error: function() {
                    var msg = '数据请求失败了，程序员正在抢修中...';
                    $el.html('<div class="data-errer">' + msg + '</div>');
                    if (callback && typeof window[callback] === 'function') {
                        window[callback]({
                            error: msg
                        })
                    }
                }
            });
        }

    }

	/*
     * 获取讨论列表
     */
	function getCommentList(el){
		var $el = $(el);
        var type = $el.attr('comment-type');//加载的类型
        var target = $el.attr('target') === '_blank' ? ' target="_blank"' : '';
        var action = $el.attr('comment-action')//表示是否是在个人中心调用，action=1表示个人中心，action=0表示前台界面
        var color = $el.attr('comment-color')||'#3c81f9'//模板颜色
        var pagesize = $el.attr('comment-pagesize')||10 //当前条数
        var periodid = $el.attr('comment-periodid')||0//课时id
        var classname //mobile为手机版
        if($el.attr('comment-model')=='mobile'){
            classname = 'ks-mobile-comment'
        }else if(type=='play-course'||type=='live-course'){
            classname = 'ks-play-comment'
        }else{
            classname = ''
        }
        var total = 0//总条数
        var ispublic=1;//是否公开的参数信息   默认公开 0-不公开   1-公开
        var flag //-1全部，1是班级,0问答，2课程，3教师，4商城5商城拼团,6点播播放页，7直播播放页
        var channelid //模型：10000问答，10001班级，10002课程，10003教师，10004点播播放页，10005播放页
		if(type=='class'){
            flag = 1
            channelid = 10001
		}else if(type=='ask'){
            flag = 0
            channelid = 10000
		}else if(type=='course'){
            flag = 2
            channelid = 10002
		}else if(type=='teacher'){
            flag = 3
            channelid = 10003	
		}else if(type=='shop'){
            flag = 4	
            channelid = $el.attr('comment-channelid')
		}else if(type=='fight-group'){
            flag = 5
            channelid = $el.attr('comment-channelid')
		}else if(type=='play-course'){
            flag = 6
            channelid = 10004
        }else if(type=='live-course'){
            flag = 7
            channelid = 10005
        }else{
            flag = -1	
            channelid = $el.attr('comment-channelid')
		}
		var showstatus = $el.attr('comment-showstatus')||-1; //showstatu-1全部，0未解决，1已解决
		var proid = $el.attr('comment-proid') //（课程ID，或班级ID，教师ID，商城ID）
        
        var callback = $el.attr('callback');
		
        if (proid === undefined) {
            return false
        }
       
		var emoji ='	<div class="ks-emoji hide"><ul class="clearfix">'
                    +'	   <li data-emoji="[微笑]"><img src="/KS_Inc/static/edu/images/emoji/smiley_0.png" class="ks-emoji-img" alt="微笑"/></li>'
                    +'	   <li data-emoji="[撇嘴]"><img src="/KS_Inc/static/edu/images/emoji/smiley_1.png" class="ks-emoji-img" alt="撇嘴" /></li>'
                    +'	   <li data-emoji="[色]"><img src="/KS_Inc/static/edu/images/emoji/smiley_2.png" class="ks-emoji-img" alt="色" /></li>'
                    +'	   <li data-emoji="[发呆]"><img src="/KS_Inc/static/edu/images/emoji/smiley_3.png" class="ks-emoji-img" alt="发呆" /></li>'
                    +'	   <li data-emoji="[得意]"><img src="/KS_Inc/static/edu/images/emoji/smiley_4.png" class="ks-emoji-img" alt="得意" /></li>'
                    +'	   <li data-emoji="[流泪]"><img src="/KS_Inc/static/edu/images/emoji/smiley_5.png" class="ks-emoji-img" alt="流泪" /></li>'
                    +'	   <li data-emoji="[害羞]"><img src="/KS_Inc/static/edu/images/emoji/smiley_6.png" class="ks-emoji-img" alt="害羞" /></li>'
                    +'	   <li data-emoji="[闭嘴]"><img src="/KS_Inc/static/edu/images/emoji/smiley_7.png" class="ks-emoji-img" alt="闭嘴" /></li>'
                    +'	   <li data-emoji="[睡觉]"><img src="/KS_Inc/static/edu/images/emoji/smiley_8.png" class="ks-emoji-img" alt="睡觉" /></li>'
                    +'	   <li data-emoji="[大哭]"><img src="/KS_Inc/static/edu/images/emoji/smiley_9.png" class="ks-emoji-img" alt="大哭" /></li>'
                    +'	   <li data-emoji="[尴尬]"><img src="/KS_Inc/static/edu/images/emoji/smiley_10.png" class="ks-emoji-img" alt="尴尬" /></li>'
                    +'	   <li data-emoji="[怒]"><img src="/KS_Inc/static/edu/images/emoji/smiley_11.png" class="ks-emoji-img" alt="怒" /></li>'
                    +'	   <li data-emoji="[调皮]"><img src="/KS_Inc/static/edu/images/emoji/smiley_12.png" class="ks-emoji-img" alt="调皮" /></li>'
                    +'	   <li data-emoji="[大笑]"><img src="/KS_Inc/static/edu/images/emoji/smiley_13.png" class="ks-emoji-img" alt="大笑" /></li>'
                    +'	   <li data-emoji="[惊讶]"><img src="/KS_Inc/static/edu/images/emoji/smiley_14.png" class="ks-emoji-img" alt="惊讶" /></li>'
                    +'	   <li data-emoji="[难过]"><img src="/KS_Inc/static/edu/images/emoji/smiley_15.png" class="ks-emoji-img" alt="难过" /></li>'
                    +'	   <li data-emoji="[酷]"><img src="/KS_Inc/static/edu/images/emoji/smiley_16.png" class="ks-emoji-img" alt="酷" /></li>'
                    +'	   <li data-emoji="[冷汗]"><img src="/KS_Inc/static/edu/images/emoji/smiley_17.png" class="ks-emoji-img" alt="冷汗" /></li>'
                    +'	   <li data-emoji="[抓狂]"><img src="/KS_Inc/static/edu/images/emoji/smiley_18.png" class="ks-emoji-img" alt="抓狂" /></li>'
                    +'	   <li data-emoji="[吐]"><img src="/KS_Inc/static/edu/images/emoji/smiley_19.png" class="ks-emoji-img" alt="吐" /></li>'
                    +'	   <li data-emoji="[偷笑]"><img src="/KS_Inc/static/edu/images/emoji/smiley_20.png" class="ks-emoji-img" alt="偷笑" /></li>'
                    +'	   <li data-emoji="[可爱]"><img src="/KS_Inc/static/edu/images/emoji/smiley_21.png" class="ks-emoji-img"  alt="可爱"/></li>'
                    +'	   <li data-emoji="[白眼]"><img src="/KS_Inc/static/edu/images/emoji/smiley_22.png" class="ks-emoji-img" alt="白眼" /></li>'
                    +'	   <li data-emoji="[傲慢]"><img src="/KS_Inc/static/edu/images/emoji/smiley_23.png" class="ks-emoji-img" alt="傲慢" /></li>'
                    +'	   <li data-emoji="[饥饿]"><img src="/KS_Inc/static/edu/images/emoji/smiley_24.png" class="ks-emoji-img"  alt="饥饿"/></li>'
                    +'	   <li data-emoji="[困]"><img src="/KS_Inc/static/edu/images/emoji/smiley_25.png" class="ks-emoji-img"  alt="困"/></li>'
                    +'	   <li data-emoji="[惊恐]"><img src="/KS_Inc/static/edu/images/emoji/smiley_26.png" class="ks-emoji-img"  alt="惊恐"/></li>'
                    +'	   <li data-emoji="[流汗]"><img src="/KS_Inc/static/edu/images/emoji/smiley_27.png" class="ks-emoji-img"  alt="流汗"/></li>'
                    +'	   <li data-emoji="[憨笑]"><img src="/KS_Inc/static/edu/images/emoji/smiley_28.png" class="ks-emoji-img"  alt="憨笑"/></li>'
                    +'	   <li data-emoji="[大兵]"><img src="/KS_Inc/static/edu/images/emoji/smiley_29.png" class="ks-emoji-img"  alt="大兵"/></li>'
                    +'	   <li data-emoji="[奋斗]"><img src="/KS_Inc/static/edu/images/emoji/smiley_30.png" class="ks-emoji-img"  alt="奋斗"/></li>'
                    +'	   <li data-emoji="[咒骂]"><img src="/KS_Inc/static/edu/images/emoji/smiley_31.png" class="ks-emoji-img"  alt="咒骂"/></li>'
                    +'	   <li data-emoji="[疑问]"><img src="/KS_Inc/static/edu/images/emoji/smiley_32.png" class="ks-emoji-img"  alt="疑问"/></li>'
                    +'	   <li data-emoji="[嘘]"><img src="/KS_Inc/static/edu/images/emoji/smiley_33.png"  class="ks-emoji-img" alt="嘘"/></li>'
                    +'	   <li data-emoji="[晕]"><img src="/KS_Inc/static/edu/images/emoji/smiley_34.png"  class="ks-emoji-img" alt="晕"/></li>'
                    +'	   <li data-emoji="[折磨]"><img src="/KS_Inc/static/edu/images/emoji/smiley_35.png" class="ks-emoji-img"  alt="折磨"/></li>'
                    +'	   <li data-emoji="[衰]"><img src="/KS_Inc/static/edu/images/emoji/smiley_36.png" class="ks-emoji-img"  alt="衰"/></li>'
                    +'	   <li data-emoji="[骷髅]"><img src="/KS_Inc/static/edu/images/emoji/smiley_37.png" class="ks-emoji-img"  alt="骷髅"/></li>'
                    +'	   <li data-emoji="[敲打]"><img src="/KS_Inc/static/edu/images/emoji/smiley_38.png" class="ks-emoji-img"  alt="敲打"/></li>'
                    +'	   <li data-emoji="[再见]"><img src="/KS_Inc/static/edu/images/emoji/smiley_39.png" class="ks-emoji-img"  alt="再见"/></li>'
                    +'	   <li data-emoji="[擦汗]"><img src="/KS_Inc/static/edu/images/emoji/smiley_40.png" class="ks-emoji-img"  alt="擦汗"/></li>'
                    +'	   <li data-emoji="[抠鼻]"><img src="/KS_Inc/static/edu/images/emoji/smiley_41.png" class="ks-emoji-img"  alt="抠鼻"/></li>'
                    +'	   <li data-emoji="[鼓掌]"><img src="/KS_Inc/static/edu/images/emoji/smiley_42.png" class="ks-emoji-img"  alt="鼓掌"/></li>'
                    +'	   <li data-emoji="[糗大了]"><img src="/KS_Inc/static/edu/images/emoji/smiley_43.png" class="ks-emoji-img"  alt="糗大了"/></li>'
                    +'	   <li data-emoji="[坏笑]"><img src="/KS_Inc/static/edu/images/emoji/smiley_44.png" class="ks-emoji-img"  alt="坏笑"/></li>'
                    +'	   <li data-emoji="[左哼哼]"><img src="/KS_Inc/static/edu/images/emoji/smiley_45.png" class="ks-emoji-img"  alt="左哼哼"/></li>'
                    +'	   <li data-emoji="[右哼哼]"><img src="/KS_Inc/static/edu/images/emoji/smiley_46.png" class="ks-emoji-img"  alt="右哼哼"/></li>'
                    +'	   <li data-emoji="[哈欠]"><img src="/KS_Inc/static/edu/images/emoji/smiley_47.png" class="ks-emoji-img"  alt="哈欠"/></li>'
                    +'	   <li data-emoji="[鄙视]"><img src="/KS_Inc/static/edu/images/emoji/smiley_48.png" class="ks-emoji-img"  alt="鄙视"/></li>'
                    +'	   <li data-emoji="[委屈]"><img src="/KS_Inc/static/edu/images/emoji/smiley_49.png" class="ks-emoji-img"  alt="委屈"/></li>'
                    +'	   <li data-emoji="[快哭了]"><img src="/KS_Inc/static/edu/images/emoji/smiley_50.png" class="ks-emoji-img"  alt="快哭了"/></li>'
                    +'	   <li data-emoji="[阴险]"><img src="/KS_Inc/static/edu/images/emoji/smiley_51.png" class="ks-emoji-img"  alt="阴险"/></li>'
                    +'	   <li data-emoji="[亲亲]"><img src="/KS_Inc/static/edu/images/emoji/smiley_52.png" class="ks-emoji-img"  alt="亲亲"/></li>'
                    +'	   <li data-emoji="[吓]"><img src="/KS_Inc/static/edu/images/emoji/smiley_53.png" class="ks-emoji-img"  alt="吓"/></li>'
                    +'	   <li data-emoji="[可怜]"><img src="/KS_Inc/static/edu/images/emoji/smiley_54.png" class="ks-emoji-img"  alt="可怜"/></li>'
                    +'	   <li data-emoji="[菜刀]"><img src="/KS_Inc/static/edu/images/emoji/smiley_55.png" class="ks-emoji-img"  alt="菜刀"/></li>'
                    +'	   <li data-emoji="[西瓜]"><img src="/KS_Inc/static/edu/images/emoji/smiley_56.png" class="ks-emoji-img"  alt="西瓜"/></li>'
                    +'	   <li data-emoji="[啤酒]"><img src="/KS_Inc/static/edu/images/emoji/smiley_57.png" class="ks-emoji-img"  alt="啤酒"/></li>'
                    +'	   <li data-emoji="[篮球]"><img src="/KS_Inc/static/edu/images/emoji/smiley_58.png" class="ks-emoji-img"  alt="篮球"/></li>'
                    +'	   <li data-emoji="[乒乓球]"><img src="/KS_Inc/static/edu/images/emoji/smiley_59.png" class="ks-emoji-img" alt="乒乓球" /></li>'
                    +'	   <li data-emoji="[咖啡]"><img src="/KS_Inc/static/edu/images/emoji/smiley_60.png" class="ks-emoji-img"  alt="咖啡"/></li>'
                    +'	   <li data-emoji="[饭]"><img src="/KS_Inc/static/edu/images/emoji/smiley_61.png" class="ks-emoji-img"  alt="饭"/></li>'
                    +'	   <li data-emoji="[猪头]"><img src="/KS_Inc/static/edu/images/emoji/smiley_62.png" class="ks-emoji-img"  alt="猪头"/></li>'
                    +'	   <li data-emoji="[玫瑰]"><img src="/KS_Inc/static/edu/images/emoji/smiley_63.png" class="ks-emoji-img"  alt="玫瑰"/></li>'
                    +'	   <li data-emoji="[凋谢]"><img src="/KS_Inc/static/edu/images/emoji/smiley_64.png" class="ks-emoji-img"  alt="凋谢"/></li>'
                    +'	   <li data-emoji="[示爱]"><img src="/KS_Inc/static/edu/images/emoji/smiley_65.png"  class="ks-emoji-img" alt="示爱"/></li>'
                    +'	   <li data-emoji="[爱心]"><img src="/KS_Inc/static/edu/images/emoji/smiley_66.png" class="ks-emoji-img"  alt="爱心"/></li>'
                    +'	   <li data-emoji="[心碎]"><img src="/KS_Inc/static/edu/images/emoji/smiley_67.png" class="ks-emoji-img"  alt="心碎"/></li>'
                    +'	   <li data-emoji="[蛋糕]"><img src="/KS_Inc/static/edu/images/emoji/smiley_68.png" class="ks-emoji-img"  alt="蛋糕"/></li>'
                    +'	   <li data-emoji="[闪电]"><img src="/KS_Inc/static/edu/images/emoji/smiley_69.png" class="ks-emoji-img"  alt="闪电"/></li>'
                    +'	   <li data-emoji="[炸弹]"><img src="/KS_Inc/static/edu/images/emoji/smiley_70.png" class="ks-emoji-img"  alt="炸弹"/></li>'
                    +'	   <li data-emoji="[刀]"><img src="/KS_Inc/static/edu/images/emoji/smiley_71.png" class="ks-emoji-img"  alt="刀"/></li>'
                    +'	   <li data-emoji="[足球]"><img src="/KS_Inc/static/edu/images/emoji/smiley_72.png" class="ks-emoji-img"  alt="足球"/></li>'
                    +'	   <li data-emoji="[瓢虫]"><img src="/KS_Inc/static/edu/images/emoji/smiley_73.png" class="ks-emoji-img"  alt="瓢虫"/></li>'
                    +'	   <li data-emoji="[便便]"><img src="/KS_Inc/static/edu/images/emoji/smiley_74.png" class="ks-emoji-img" alt="便便" /></li>'
                    +'	   <li data-emoji="[月亮]"><img src="/KS_Inc/static/edu/images/emoji/smiley_75.png" class="ks-emoji-img"  alt="月亮"/></li>'
                    +'	   <li data-emoji="[太阳]"><img src="/KS_Inc/static/edu/images/emoji/smiley_76.png" class="ks-emoji-img"  alt="太阳"/></li>'
                    +'	   <li data-emoji="[礼物]"><img src="/KS_Inc/static/edu/images/emoji/smiley_77.png" class="ks-emoji-img"  alt="礼物"/></li>'
                    +'	   <li data-emoji="[拥抱]"><img src="/KS_Inc/static/edu/images/emoji/smiley_78.png" class="ks-emoji-img"  alt="拥抱"/></li>'
                    +'	   <li data-emoji="[强]"><img src="/KS_Inc/static/edu/images/emoji/smiley_79.png" class="ks-emoji-img"  alt="强"/></li>'
                    +'	   <li data-emoji="[弱]"><img src="/KS_Inc/static/edu/images/emoji/smiley_80.png"  class="ks-emoji-img" alt="弱"/></li>'
                    +'	   <li data-emoji="[握手]"><img src="/KS_Inc/static/edu/images/emoji/smiley_81.png" class="ks-emoji-img"  alt="握手"/></li>'
                    +'	   <li data-emoji="[胜利]"><img src="/KS_Inc/static/edu/images/emoji/smiley_82.png"  class="ks-emoji-img" alt="胜利"/></li>'
                    +'	   <li data-emoji="[抱拳]"><img src="/KS_Inc/static/edu/images/emoji/smiley_83.png" class="ks-emoji-img"  alt="抱拳"/></li>'
                    +'	   <li data-emoji="[勾引]"><img src="/KS_Inc/static/edu/images/emoji/smiley_84.png" class="ks-emoji-img"  alt="勾引"/></li>'
                    +'	   <li data-emoji="[拳头]"><img src="/KS_Inc/static/edu/images/emoji/smiley_85.png" class="ks-emoji-img"  alt="拳头"/></li>'
                    +'	   <li data-emoji="[差劲]"><img src="/KS_Inc/static/edu/images/emoji/smiley_86.png" class="ks-emoji-img"  alt="差劲"/></li>'
                    +'	   <li data-emoji="[爱你]"><img src="/KS_Inc/static/edu/images/emoji/smiley_87.png" class="ks-emoji-img"  alt="爱你"/></li>'
                    +'	   <li data-emoji="[NO]"><img src="/KS_Inc/static/edu/images/emoji/smiley_88.png"  class="ks-emoji-img" alt="NO"/></li>'
                    +'	   <li data-emoji="[OK]"><img src="/KS_Inc/static/edu/images/emoji/smiley_89.png"   class="ks-emoji-img"alt="OK"/></li>'
                    +'	   <li data-emoji="[爱情]"><img src="/KS_Inc/static/edu/images/emoji/smiley_90.png" class="ks-emoji-img"  alt="爱情"/></li>'
                    +'	   <li data-emoji="[飞吻]"><img src="/KS_Inc/static/edu/images/emoji/smiley_91.png" class="ks-emoji-img"  alt="飞吻"/></li>'
                    +'	   <li data-emoji="[跳跳]"><img src="/KS_Inc/static/edu/images/emoji/smiley_92.png" class="ks-emoji-img"  alt="跳跳"/></li>'
                    +'	   <li data-emoji="[发抖]"><img src="/KS_Inc/static/edu/images/emoji/smiley_93.png" class="ks-emoji-img"  alt="发抖"/></li>'
                    +'	   <li data-emoji="[怄火]"><img src="/KS_Inc/static/edu/images/emoji/smiley_94.png" class="ks-emoji-img"  alt="怄火"/></li>'
                    +'	   <li data-emoji="[转圈]"><img src="/KS_Inc/static/edu/images/emoji/smiley_95.png" class="ks-emoji-img"  alt="转圈"/></li>'
                    +'	   <li data-emoji="[磕头]"><img src="/KS_Inc/static/edu/images/emoji/smiley_96.png" class="ks-emoji-img"  alt="磕头"/></li>'
                    +'	   <li data-emoji="[回头]"><img src="/KS_Inc/static/edu/images/emoji/smiley_97.png" class="ks-emoji-img"  alt="回头"/></li>'
                    +'	   <li data-emoji="[跳绳]"><img src="/KS_Inc/static/edu/images/emoji/smiley_98.png" class="ks-emoji-img"  alt="跳绳"/></li>'
                    +'	   <li data-emoji="[挥手]"><img src="/KS_Inc/static/edu/images/emoji/smiley_99.png" class="ks-emoji-img"  alt="挥手"/></li>'
                    +'	   <li data-emoji="[激动]"><img src="/KS_Inc/static/edu/images/emoji/smiley_100.png" class="ks-emoji-img" alt="激动" /></li>'
                    +'	   <li data-emoji="[街舞]"><img src="/KS_Inc/static/edu/images/emoji/smiley_101.png" class="ks-emoji-img"  alt="街舞"/></li>'
                    +'	   <li data-emoji="[献吻]"><img src="/KS_Inc/static/edu/images/emoji/smiley_102.png" class="ks-emoji-img"  alt="献吻"/></li>'
                    +'	   <li data-emoji="[左太极]"><img src="/KS_Inc/static/edu/images/emoji/smiley_101.png"  class="ks-emoji-img" alt="街舞"/></li>'
                    +'	   <li data-emoji="[右太极]"><img src="/KS_Inc/static/edu/images/emoji/smiley_102.png"  class="ks-emoji-img" alt="献吻"/></li>'
                    +'	</ul></div>'
				
		$el.append('<div class="ks-comment '+classname+'">'
					+'<div class="ks-comment-top">'
					+'	<textarea class="ks-comment-textarea" placeholder="最多只能输入255个字"></textarea>'
                    +'	<div class="ks-comment-set clearfix">'
                    +'		<span class="ks-submit-btn" style="background-color: '+color+';border: 1px solid '+color+';">立即询问</span>'
					+' 		<div id="ks-comment-switch1" class="ks-comment-open1" style="background:'+color+';border: 1px solid '+color+';">'
					+'			<div id="ks-comment-switch2" class="ks-comment-open2"></div>'
					+'		</div>'
					+'		<span class="ks-switch-text">公开</span><span class="ks-comment__expression"><img src="/KS_Inc/static/edu/images/lesson_btn_face.png" id="ks-comment__emoji"/>'+emoji+'</span><span class="ks-comment__image"><img src="/KS_Inc/static/edu/images/lesson_btn_pic.png" id="ks-comment__image"/></span>'
                    +'	</div>'
                    +'  <div class="ks-upload-box">'
                    +'      <div class="clearfix"><div id="ks-upload-showimg">'
                    +'          <ul id="ks-upload-showui">'
                    +'          </ul>'
                    +'          <div id="ks-upload-showinput">'
                    +'          </div>'
                    +'      </div>'
                    +'      <div class="ks-upload-upimg">'
                    +'          <input type="file" id="ks-upload-upgteimg" value="" multiple />'
                    +'      </div></div>'
                    // +'      <button class="ks-upload-btn" id="submit">开始上传</button>'
                    +'  </div>'
					+'</div>'
					+'<div class="ks-comment-list"></div><div class="ks-page-box"><div class="ks-page"></div></div></div>')
                    
        loadPage(1)


        /**
         * 留言列表
         * @param {Number} 留言当前页数
         * @param {Number} 加载列表的类型 type=0重新加载翻页，type=1不加载分页
         */
		function loadPage(page,type){
            KS_Utils.getUID(function(userid){
                
                var from
                if(action==1){
                    from = 1
                }else{
                    from = 0
                }
                var getUrl = '/webapi/user/GetUserAskTopList?userid='+userid+'&page='+page+'&pagesize='+pagesize+'&flag='+flag+'&channelid='+channelid+'&showstatus='+showstatus+'&proid='+proid+'&periodid='+periodid+'&from='+from;
                var comment_list='' //问题列表
            
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    url: getUrl,
                    success: function(res) {
                        var commentList = res.data
                        total = res.totalcount
                        if (commentList && commentList.length) {
                            commentList.map(function(item){
                                if(item.content.match(/\[[\u4e00-\u9fa5]+\]/g)&&item.content.match(/\[[\u4e00-\u9fa5]+\]/g).length){
                                    item.content.match(/\[[\u4e00-\u9fa5]+\]/g).map(function(eitem){
                                        var lis = $('.ks-emoji li');
                                        for(var i=0;i<lis.length;i++){
                                            if($(lis[i]).attr('data-emoji')==eitem){
                                                item.content = item.content.replace(eitem,$(lis[i]).html());
                                            }
                                        }
                                    })
                                }
                                var imgHtml = ''
                                if(item.showpics && item.showpics.length){
                                    item.showpics.map(function(imgitem){
                                        imgHtml+='<span class="comment-img"><img src="'+imgitem.pic_src+'" onerror="KS_Utils.replaceDefaultImg(this)" /></span>'
                                    })
                                }
                                var lookbtn
                                if(item.postnum){
                                    lookbtn ='<span class="ks-comment-look" style="color:'+color+'" data-topicid="'+item.topicid+'" data-load="false">查看</span>' 
                                }else{
                                    lookbtn=''
                                }
                                comment_list+='<li class="ks-comment__li" data-topicid="'+item.topicid+'">'
                                            +'	<div class="ks-comment__box ks-comment__first">'
                                            +'		<div class="ks-comment__avator"><img src="'+item.userface+'" onerror="KS_Utils.replaceDefaultImg(this)" type="user"></div>'
                                            +'		<div class="ks-comment__user-info">'
                                            +'			<h3>'+item.username+'</h3>'
                                            +'			<div class="ks-comment__content">'+item.content+'</div>'
                                            +'          <div class="ks-comment-img">'+imgHtml+'</div>'
                                            +'			<div class="ks-comment__bottom">'
                                            +'				<span class="ks-comment-time">'+item.adddate+'</span>'
                                            +'				<span class="ks-comment-replies">'+item.postnum+'个回答</span>'+lookbtn
                                            // +'				<span class="ks-comment-look" data-topicid="'+item.topicid+'" data-load="false">查看</span>'
                                            +'			</div>'
                                            +'		</div>'
                                            +'	</div>'
                                            +'	<ul class="ks-comment__reply"></ul>'
                                            +'</li>'
                            })
                        } else {
                            comment_list = '<div class="empty">对不起，没有找到任何记录！</div>'
                        }
                        $el.find('.ks-comment-list').html(comment_list)
                        $el.find('.ks-comment__bottom').on('click', '.ks-comment-look', function(){
                            var topicid = $(this).attr('data-topicid')
                            if($(this).attr('data-load')=='false'){
                                loadReply(topicid)
                            }
                            $(this).attr('data-load','true');
                            $(this).parents('.ks-comment__first').siblings('.ks-comment__reply').toggle();
                            if($(this).text()=='查看'){
                                $(this).text('收起')
                            }else{
                                $(this).text('查看')
                            }
                        });
                        $el.find('.comment-img').click(function(){
                            var imgArr = [];
                            $(this).parent().find('.comment-img').map(function(){
                                imgArr.push($(this).find('img').attr('src'));
                            });
                            var index = $(this).index();
                            imgPreview(imgArr,index)
                        })
                        if(!type){
                            $el.find(".ks-page").sPage({
                                page:page,
                                pageSize:pagesize,
                                total:total,
                                prevPage:'<i class="icon-prev"></i>',
                                nextPage:'<i class="icon-next"></i>',
                                color:color,
                                backFun:function(page){
                                    loadPage(page,1)
                                }
                            });
                        }
                    }
                });	
            })
        }

		/**
         * 回复列表
         * @param {Number} 留言id（topicid）
         */
		function loadReply(topicid){
			var reply_list='' //回复列表
			$.ajax({
				type: 'get',
				dataType: 'json',
				url: '/webapi/user/GetUserAskPostList?topicid='+topicid,
				success: function(res) {
					var replyList = res.data
					if (replyList && replyList.length) {
						replyList.map(function(item){
							reply_list+='	<div class="ks-comment__box">'
									+'		<div class="ks-comment__avator"><img src="'+item.userface+'" onerror="KS_Utils.replaceDefaultImg(this)" type="user"></div>'
									+'		<div class="ks-comment__user-info">'
									+'			<h3>'+item.username+'</h3>'
									+'			<div class="ks-comment__content">'+item.content+'</div>'
									+'			<div class="ks-comment__bottom">'
									+'				<span class="ks-comment-time">'+item.adddate+'</span>'
									+'			</div>'
									+'		</div>'
									+'	</div>'
						
						})
					} else {
						reply_list = ''
					}
					
					$el.find('.ks-comment__li').each(function() {
						if($(this).attr('data-topicid')==topicid){
							if(reply_list){
								$(this).find('.ks-comment__reply').html(reply_list)
							}else{
								$(this).find('.ks-comment__reply').addClass('ks-no-reply')
							}
							
						}
					});
				},
				error: function() {
					var msg = '数据请求失败了，程序员正在抢修中...';
					comment_list = '<div class="data-errer">' + msg + '</div>'
					if (callback && typeof window[callback] === 'function') {
						window[callback]({
							error: msg
						})
					}
				}
			});	
        }
        $el.on('click','.ks-emoji li',function(){
            var content = $el.find('.ks-comment-textarea').val()
			content+=$(this).attr('data-emoji')
			$el.find('.ks-comment-textarea').val(content)
			$el.find('.ks-emoji').addClass("hide")
        }).on('click','#ks-comment-switch1',function(){
			clickpublic(this,color)
		}).on('click','#ks-comment__emoji',function(e){
			e.stopPropagation()
			$el.find('.ks-emoji').removeClass("hide")
		}).on('click','.ks-emoji',function(e){
			e.stopPropagation()
		}).on('click','#ks-comment__image',function(){
            $el.find('.ks-upload-box').toggle()
        }).on('click','.ks-submit-btn',function(){
            commentSave($el.find('.ks-comment-textarea').val())
        });
		$(document).click(function(){
			if (!$(".ks-emoji").hasClass("hide")) {
				$('.ks-emoji').addClass("hide")
			}	
		});
        
        $el.find('#ks-upload-upgteimg').change(function(e){
            if($el.find('#ks-upload-showui li').length<9){
                uploadImg(e);
                
            }else{
                KS_Popup.msg('最多只能上传9张');
            }
        });
        
        limitImport('.ks-comment-textarea',255);

        /**
         * 提交讨论
         * @param {string} 文本域内容content
         */
		function commentSave(content){

            var imgArr = []
            if($('#ks-upload-showui li').length){
                for(var i=0;i<$('#ks-upload-showui li').length;i++){
                    imgArr.push($('#ks-upload-showui li').eq(i).find('.ks-upload-showimg').attr('src'))
                }
            }
            
            KS_Utils.getUID(function(userid){
                if(!userid){
					if(SOURCE === 'app'){
						KS_Utils.popup.msg('请先登录')
						setTimeout(function(){
							getUni(function(uni){
								uni.navigateTo({
									url:'/pages/user/login/index'
								})
							})
						},2000)
						
					}else{
						KS_Popup.alert('请先登录',{
						    icon:'warning'
						});
						return
						// showuserlogin();
					}
                    
                }
                var data = new Object()
                data={
                    userid:userid,
                    content:content,
                    flag:flag,
                    proid:proid,
                    periodid:periodid,
                    channelid:channelid,
                    photolist:imgArr.toString(),
                    Recommend:ispublic
                }
                $.ajax({
                    type: 'POST',
                    // dataType: 'json',
                    url: '/webapi/user/SaveAskTopic',
                    data:data,
                    success: function(res) {
                        var tips_msg
                        if(res.result){
                            tips_msg = '发布成功！';
                            $('.ks-comment-textarea').val('')
                            $('.ks-upload-box').hide()
                            $('#ks-upload-showui').html('')
                        }else{
                            tips_msg = res.msg;
                        }
                        KS_Popup.msg(tips_msg);
                        loadPage(1);
                    },
                    error: function() {
                        KS_Popup.msg('发布失败');
                        if (callback && typeof window[callback] === 'function') {
                            window[callback]({
                                error: msg
                            })
                        }
                    }
                });
            })
			
			
        }

        /**
         * 是否公开的点击事件
         * @param {object} 公开按钮obj
         */
        function clickpublic(obj,color){ 
            
            var switch2=$(obj).find("#ks-comment-switch2");
            var switch1=$(obj)
            
            if(switch1.attr('class')=='ks-comment-close1'){
                switch1.attr('class','ks-comment-open1')
                switch1.attr('style','background:'+color+';border: 1px solid '+color)
            }else{
                switch1.attr('class','ks-comment-close1')
                switch1.attr('style','background:#f5f5f5;border: 1px solid #d3d3d3')
            }
            
            if(switch2.attr('class')=='ks-comment-close2'){
                switch2.attr('class','ks-comment-open2')
            }else{
                switch2.attr('class','ks-comment-close2')
            }
            if(ispublic==0){
                ispublic=1;//公开
            }else{
                ispublic=0;//不公开
            }
        }
    }
    
    var audio = document.createElement('audio');
    function AudioPlayer(params){
        params = params || {};
        if(!params.el){
           return
        }
        this.list = params.list || [];
        this.current = params.current || 0;
        this.currentPlay = this.list[this.current] || {};
        this.$el = $(params.el);
        this.seekFlag = false;
        this.params = params;
        var prevDisabled = this.list[this.current-1] ? '' : ' ks-audio-player__prev--disabled';
        var nextDisabled = this.list[this.current+1] ? '' : ' ks-audio-player__next--disabled';
        var $el = this.$el;
        var that = this;
        getArtTemplate(function(art){
            var code = '<div class="ks-audio-player">'+
            '   <div class="ks-audio-player__icon-list"><span>{{list.length}}</span></div>'+
            '   <div class="ks-audio-player__list">'+
            '       <div class="ks-audio-player__list-tit">播放列表</div>'+
            '      {{each list item i}}'+
            '          <div class="ks-audio-player__list-item {{current == i ? \'ks-audio-player__list-item--active\' : \'\'}}" data-index="{{i}}">'+
            '              {{item.title}}'+
            '          </div>'+
            '      {{/each}}'+
            '   </div>'+
            '   <div class="ks-audio-player__cover">'+
            '       <div class="ks-audio-player__run">'+
            '           <div class="ks-audio-player__cover-bg" style="background-image:url({{currentPlay.cover}})">'+
            '          </div>'+
            '          <img src="{{currentPlay.cover}}" class="ks-audio-player__cover-img" />'+
            '      </div>'+
            '  </div>'+
            '  <div class="ks-audio-player__progress">'+
            '      <div class="ks-audio-player__total-time">00:00</div>'+
            '      <div class="ks-audio-player__time">00:00</div>'+
            '      <div class="ks-audio-player__progress-bar">'+
            '          <div class="ks-audio-player__progress-bar--on">'+
            '              <div class="ks-audio-player__progress-dot"><i></i></div>'+
            '          </div>'+
            '      </div>'+
            '  </div>'+
            '  <div class="ks-audio-player__msg">{{if currentPlay.title}}正在播放：{{currentPlay.title}}{{/if}}</div>'+
            '  <div class="ks-audio-player__tool">'+
            '       <div class="ks-audio-player__play"></div>'+
            '      <div class="ks-audio-player__prev'+prevDisabled+'"></div>'+
            '      <div class="ks-audio-player__next'+nextDisabled+'"></div>'+
            '  </div>'+
            '</div>';
            var render = art.compile(code);
            var renderRes = render({
                current:that.current,
                currentPlay:that.currentPlay,
                list:that.list
            });
            $el.html(renderRes);
            audio.src = that.currentPlay.src;
            audio.load();
            var eventName = '';
            if('ontouchstart' in document.documentElement){
                eventName = 'touchstart';
            }else{
                eventName = 'click';
            }
            document.addEventListener(eventName,function(){
                $el.find('.ks-audio-player__list').hide();
            });
            $el.on(eventName,'.ks-audio-player__play',function(){
                /**试听结束，暂停 */
                if(typeof that.currentPlay.audition === 'number' && audio.currentTime >= that.currentPlay.audition){
                    audio.pause();
                    return
                }
                if($(this).hasClass('ks-audio-player__play--pause')){
                    audio.pause()
                }else{
                    var playPromise = audio.play();
                    if (playPromise !== undefined) {  
                            playPromise.then(function() {        
                                audio.play()    
                        }).catch(function(){
                            
                        })
                    }
                }
            }).on(eventName,'.ks-audio-player__next',function(){
                that.handlerChange(that.current+1);
            }).on(eventName,'.ks-audio-player__prev',function(){
                that.handlerChange(that.current-1);
            }).on(eventName,'.ks-audio-player__icon-list',function(e){
                e.stopPropagation();
                $el.find('.ks-audio-player__list').toggle();
            }).on(eventName,'.ks-audio-player__list',function(e){
                e.stopPropagation();
            }).on(eventName,'.ks-audio-player__list-item',function(e){
                var index = Number($(this).attr('data-index'));
                that.handlerChange(index);
                $el.find('.ks-audio-player__list').hide();
            });
            audio.onplay = function(){
                $el.find('.ks-audio-player__play').addClass('ks-audio-player__play--pause');
                $el.find('.ks-audio-player__run').addClass('ks-audio-player__runing');
                if(typeof params.onplay === 'function'){
                    params.onplay()
                }
            }
            audio.onpause = function(){
                $el.find('.ks-audio-player__play').removeClass('ks-audio-player__play--pause');
                $el.find('.ks-audio-player__run').removeClass('ks-audio-player__runing');
                if(typeof params.onpause === 'function'){
                    params.onpause()
                }
            }
            audio.onerror = function(){
                $el.find('.ks-audio-player__msg').text('音频加载出错！').addClass('ks-audio-player__msg--error');
                if(typeof params.onerror === 'function'){
                    params.onerror()
                }
            }
            audio.onloadeddata = function(){
                var duration = Math.floor(audio.duration);
                that.duration = duration;
                var time = secondsConversion(duration);
                $el.find('.ks-audio-player__total-time').text(time);
                if(typeof params.onready === 'function'){
                    params.onready()
                }
                if(that.currentPlay.isCanSeek !== false){
                    that.createSeek()
                }
                var playPromise = audio.play();
                if (playPromise !== undefined) {  
                        playPromise.then(function() {        
                            audio.play()    
                    }).catch(function(){
                        
                    })
                }
            }
            audio.onended = function(){
                if(typeof params.onended === 'function'){
                    params.onended()
                }
                that.handlerChange(that.current + 1)
            }
            setInterval(function() {
                if(!that.seekFlag){
                    /**试听结束 */
                    if(typeof that.currentPlay.audition === 'number' && audio.currentTime >= that.currentPlay.audition){
                        audio.pause();
                        $el.find('.ks-audio-player__msg').text('试听已结束，请先购买！').addClass('ks-audio-player__msg--error');
                    }
                    var duration = Math.floor(audio.duration);
                    that.duration = duration;
                    var currentTime = Math.floor(audio.currentTime);
                    that.currentTime = currentTime;
                    var width = Math.floor(currentTime / duration * 100);
                    var time = secondsConversion(currentTime);
                    $el.find('.ks-audio-player__progress-bar--on').css('width',width + '%');
                    $el.find('.ks-audio-player__time').text(time)
                    
                }
            }, 1000); 
        });
        return this
    }
    AudioPlayer.prototype.handlerChange = function(index){
        if(!this.list[index]){
            return
        }
        
        this.currentTime = 0;
        this.current = index;
        this.currentPlay = this.list[index];
        var $el = this.$el;
        $el.find('.ks-audio-player__cover-bg').css('background-image','url('+ this.currentPlay.cover+')');
        $el.find('.ks-audio-player__cover-img').attr('src', this.currentPlay.cover);
        $el.find('.ks-audio-player__total-time').text('00:00');
        $el.find('.ks-audio-player__time').text('00:00');
        $el.find('.ks-audio-player__progress-bar--on').css('width','0%');
        $el.find('.ks-audio-player__msg').removeClass('ks-audio-player__msg--error');
        if(this.currentPlay.title){
            $el.find('.ks-audio-player__msg').text('正在播放：'+this.currentPlay.title);
        }else{
            $el.find('.ks-audio-player__msg').text('');
        }
        audio.src =  this.currentPlay.src;
        audio.currentTime = 0;
        
        if(this.list[index + 1]){
            $el.find('.ks-audio-player__next').removeClass('ks-audio-player__next--disabled');
        }else{
            $el.find('.ks-audio-player__next').addClass('ks-audio-player__next--disabled');
        }
        if(this.list[index-1]){
            $el.find('.ks-audio-player__prev').removeClass('ks-audio-player__prev--disabled');
        }else{
            $el.find('.ks-audio-player__prev').addClass('ks-audio-player__prev--disabled');
        }
        $el.find('.ks-audio-player__list-item').eq(index).addClass('ks-audio-player__list-item--active').siblings().removeClass('ks-audio-player__list-item--active');
        if(typeof this.params.onchange === 'function'){
            this.params.onchange(index);
        }
    }
    AudioPlayer.prototype.createSeek = function(){
        if(this.seekCreateed){
            return
        }
        this.seekCreateed = true;
        var that = this;
        var $el = this.$el;
        var $bar = $el.find('.ks-audio-player__progress-bar');
        
        var dot = $el.find('.ks-audio-player__progress-dot')[0];
        var bar = $bar[0];
        var seekTime = audio.currentTime;

        if('ontouchstart' in document.documentElement){
            bar.ontouchstart = function(e){
                seekTime = that.updateProgress(e.targetTouches[0].clientX - $bar.offset().left,this.offsetWidth);
            }
            dot.ontouchstart = function(e){
                e.stopPropagation();
                that.seekFlag = true;
            }
            bar.ontouchmove = function(e){
                if(that.seekFlag){
                    seekTime = that.updateProgress(e.targetTouches[0].clientX - $bar.offset().left,this.offsetWidth)
                }
            }
            bar.ontouchend = function(){
                audio.currentTime = seekTime;
                that.currentTime = seekTime;
                that.seekFlag = false;
                if(typeof that.params.onseek === 'function'){
                    that.params.onseek()
                }
            }
        }else{
            bar.onmousedown = function(e){
                seekTime = that.updateProgress(e.clientX - $bar.offset().left,this.offsetWidth);
            }
            dot.onmousedown = function(e){
                e.stopPropagation();
                that.seekFlag = true;
            }
            bar.onmousemove = function(e){
                if(that.seekFlag){
                    seekTime = that.updateProgress(e.clientX - $bar.offset().left,this.offsetWidth)
                }
            }
            bar.onmouseup = function(){
                audio.currentTime = seekTime;
                that.currentTime = seekTime;
                that.seekFlag = false;
                if(typeof that.params.onseek === 'function'){
                    that.params.onseek()
                }
            }
        }
    }
    AudioPlayer.prototype.updateProgress = function(x,progressWidth){
        var $el = this.$el;
        var duration = Math.floor(audio.duration);
        var proportion = Math.min(x / progressWidth,1);
        var width = Math.floor(proportion * 100);
        $el.find('.ks-audio-player__progress-bar--on').css('width',width + '%');
        var seekTime = Math.max(Math.floor(duration * proportion),0);
        var time = secondsConversion(seekTime);
        $el.find('.ks-audio-player__time').text(time);
        return seekTime
    }

    
    /**
     * 图片一选择就上传
     * @param {object} 文件内容
     */
    function uploadImg(e){
        KS_Utils.getUID(function(userid,apptoken){
            // var userid = $('#user-img').attr('userid')
            // var apptoken = $('#user-img').attr('apptoken')
            var file = e.currentTarget.files[0];
            var formData = new FormData();
            formData.append('file',file);
            if(apptoken){
                $.ajax({
                    url: "/webapi/user/UploadFile?userid="+userid+'&apptoken='+apptoken,
                    type: "POST",
                    data: formData,
                    processData: false,  // 不处理数据
                    contentType: false,   // 不设置内容类型
                    success: function (res) {
                        // var res = JSON.parse(res)
                        if(res.result){
                            $('#ks-upload-showui').append('<li><div class="ks-upload-showdiv"><img class="ks-upload-delete" src="/KS_Inc/static/edu/images/delete.svg"/></div><img id="ks-upload-img" class="ks-upload-showimg" src="' + res.fileUrl + '" /></li>')
                        }else{
                            alert(res.msg)
                        }
                        $('.ks-upload-showdiv img').click(function(){
                            $(this).parents('li').remove()
                        })
                    }
                })
            }else{
				if(SOURCE === 'app'){
					KS_Utils.popup.msg('请先登录')
					setTimeout(function(){
						getUni(function(uni){
							uni.navigateTo({
								url:'/pages/user/login/index'
							})
						})
					},2000)
					
				}else{
					KS_Popup.alert('您未登录，请先登录',{
					    icon:'warning'
					});
					return
				}
            }
        })
    }
    
    /**
     * 限制字数
     * @param {string} 文本域内容str
     * @param {Number} 文本域限制字数num
     */
    function limitImport(str,num){
        $(document).on('input propertychange',str,function(){
         var self = $(this);
         var content = self.val();
         if (content.length > num){
          self.val(content.substring(0,num));
         } 
         self.siblings('span').text(self.val().length+'/'+num);
        });
    }
    /**
     * 预览图片
     * @param {Array} photoList 
     * @param {Number} current 
     */
    function imgPreview(photoList,current){
        photoList = photoList || [];
        current = current || 0;
        getSwiper(function(Swiper){
            getArtTemplate(function(art){
                var code =  '<div class="ks-preview" id="ks-preview">'+
                            '    <div class="ks-preview__pagination">'+
                            '        <span class="ks-preview__current">{{current + 1}}</span>/{{list.length}}'+
                            '    </div>'+
                            '   <div class="swiper-container">'+
                            '        <div class="swiper-wrapper">'+
                            '           {{each list src i}}'+
                            '            <div class="swiper-slide" style="height:{{height}}px">'+
                            '               <div class="swiper-zoom-container"><img src="{{src}}" /> </div>'+
                            '           </div>'+
                            '           {{/each}}'+
                            '        </div>'+
                            '    </div>'+
                            '</div>'
                var render = art.compile(code);
            
                var renderRes = render({
                    list:photoList,
                    current:current,
                    height:window.innerHeight
                });
                if(document.getElementById('ks-preview')){
                    $('#ks-preview').remove();
                }
                
                $('body').append(renderRes);
                var $el = $('#ks-preview');
                var previewSwiper = new Swiper($el.find('.swiper-container')[0], {
                    zoom: true,
                    initialSlide:current,
                    on:{
                        slideChangeTransitionStart:function(){
                            if(previewSwiper){
                                $el.find('.ks-preview__current').text(previewSwiper.activeIndex + 1)
                            }
                            
                        }
                    }
                });
                $el.click(function(){
                    $el.fadeOut(300);
                });
                
            });
        });
    }
    /**
     * 放大图片
     * @param {object} 对象imgobj
     * @param {string} 字符串样式名
     */
    function amplification(imgobj,classname){

        $('body').append('<div class="ks-amplification '+classname+'">'
                        +'  <div class="ks-amplification-box">'
                        +'      <i class="ks-amplification-close"><img src="/KS_Inc/static/edu/images/close.png"/></i>'
                        +'      <div class="ks-amplification-img">'+$(imgobj).html()
                        +'      </div>'
                        +'  <div>'
                        +'</div>')
        $('body').addClass('no-scroll')
        $('.ks-amplification-close').click(function(){
            $('.ks-amplification').fadeOut()
            $('body').removeClass('no-scroll')
        })
    }
    /**
     * 加入购物车
     * @param {Number} 课程id
     * @param {Number} 课程类型
     */
    function addToCourseCart(courseId, type) {
        $.get('/index.aspx?c=course&a=shopcart&action=addtocart&id=' + courseId + '&type=' + type + params_schoolid, function(res) {
            if (res === "ok") {
                KS_Popup.alert("恭喜，成功加入购课车！", {
                    icon: 'success'
                });
                getCourseCartNum();
            } else {
                KS_Popup.alert(res, {
                    icon: 'error'
                });
            }
        })
    }

    /**
     * 遍历
     */
    function domap(data, fn) {
        for (var i = 0; i < data.length; i++) {
            fn(data[i], i)
        }
    }

    /**
     * 点赞
     */
    function gotozan(id, modelid, list, action) {

        if ((action == null || action == "") && action != "setfont") {
            action = "点赞#已赞"
        }
        $.ajax({
            type: 'post',
            datatype: 'text',
            url: "/plus/ajaxs.ashx?a=docorz&id=" + id + "&modelid=" + modelid + "&optype=1&isgetinfo=0",
            data: { act: action },
            success: function(msg) {
                if (msg == "0") { 
					if(SOURCE === 'app'){
						getUni(function(uni){
							uni.navigateTo({
								url:'/pages/user/login/index'
							})
						})
					}else{
                        var u = navigator.userAgent
                        if(!!u.match(/AppleWebKit.*Mobile.*/)){
                            location.href ="/login?f=m"
                        }else{
                            showuserlogin();
                        }
						// showuserlogin();
					}
				}
                if (list == null || list == "") {
                    if (msg == "-1") {
                        if (parseInt($("#zancount").html()) > 0) {
                            $("#zancount").html(parseInt($("#zancount").html()) - 1);
                        }
                        $("#zan").html(action.split('#')[0]);
                    } else if (msg == "+1") {
                        $("#zancount").html(parseInt($("#zancount").html()) + 1);
                        $("#zan").html(action.split('#')[1]);
                    }
                } else if (list == "list") {

                    if (msg == "-1") {
                        $("#zan" + id + "").removeClass("zan-hover");
                        if (parseInt($("#zancount" + id).html()) > 0) {
                            $("#zancount" + id).html(parseInt($("#zancount" + id).html()) - 1);
                        }
                        if (action == "setfont") {
                            $("#zan" + id + "").html("点赞");
                        }
                    } else if (msg == "+1") {
                        $("#zan" + id + "").addClass("zan-hover");
                        $("#zancount" + id).html(parseInt($("#zancount" + id).html()) + 1);
                        if (action == "setfont") {
                            $("#zan" + id + "").html("已赞");
                        }
                    }
                }

            }
        });
    }
    /**
     * 获取点赞数量
     */
    function getzan(id, modelid, list, action) {
        if ((action == null || action == "") && action != "setfont") {
            action = "点赞#已赞"
        }
        $.ajax({
            type: 'post',
            datatype: 'text',
            url: "/plus/ajaxs.ashx?a=docorz&id=" + id + "&modelid=" + modelid + "&optype=1&isgetinfo=1&list=" + list + "",
            data: { act: action },
            success: function(msg) {
                if (list == "list") {
                    var k = msg.split(',');
                    for (var i = 0; i < k.length; i++) {
                        $("#zan" + k[i]).addClass("zan-hover");
                        if (action == "setfont") {
                            $("#zan" + k[i]).html("已赞")
                        }
                    }
                } else {

                    $("#zan").html(msg);
                }
            }
        });
    }

    /**
     * 获取收藏
     */
    function getcollect(id, modelid, list, action) {
        if ((action == null || action == "") && action != "setfont") {
            action = "收藏#已收藏"
        }
        $.ajax({
            type: 'post',
            datatype: 'text',
            url: "/plus/ajaxs.ashx?a=docorz&id=" + id + "&modelid=" + modelid + "&optype=0&isgetinfo=1&list=" + list + "",
            data: { act: action },
            success: function(msg) {
                //  alert(msg);
                if (list == "list") {
                    var k = msg.split(',');
                    for (var i = 0; i < k.length; i++) {
                        $("#collect" + k[i]).addClass("collect-hover");
                        if (action == "setfont") {
                            $("#collect" + k[i]).html("已收藏")
                        }
                    }
    
                } else {
                    $("#collect").html(msg);
                }
            }
        });
    }
    /**
     * 收藏
     */
    function collect(id, modelid, list, action) {
    
        if ((action == null || action == "") && action != "setfont") {
            action = "收藏#已收藏";
    
        }
    
        $.ajax({
            type: 'post',
            datatype: 'text',
            url: "/plus/ajaxs.ashx?a=docorz&id=" + id + "&modelid=" + modelid + "&optype=0&isgetinfo=0",
            data: { act: action },
            success: function(msg) {
    
                //alert(msg);
                if (msg == "0") { 
                    var u = navigator.userAgent
                    if(!!u.match(/AppleWebKit.*Mobile.*/)){
                        location.href ="/login?f=m"
                    }else{
                        showuserlogin();
                    }
                    
                }
                if (list == "" || list == null) {
                    if (msg == "-1") {
    
                        if (parseInt($("#ccount").html()) > 0) {
                            $("#ccount").html(parseInt($("#ccount").html()) - 1);
                        }
                        $("#collect").html(action.split('#')[0]);
                    } else if (msg == "+1") {
                        $("#ccount").html(parseInt($("#ccount").html()) + 1);
                        $("#collect").html(action.split('#')[1]);
    
                    }
                } else if (list == "list") {
					console.log(msg)
                    if (msg == "-1") {
                        $("#collect" + id + "").removeClass("collect-hover");
                        if (parseInt($("#ccount" + id).html()) > 0) {
                            $("#ccount" + id).html(parseInt($("#ccount" + id).html()) - 1);
                        }
                        if (action == "setfont") {
                            $("#collect" + id + "").html("收藏");
                        }
                    } else if (msg == "+1") {
                        $("#collect" + id + "").addClass("collect-hover");
                        $("#ccount" + id).html(parseInt($("#ccount" + id).html()) + 1);
                        if (action == "setfont") {
                            $("#collect" + id + "").html("已收藏");
                        }
                    }
                }
            }
        });
    }

    /**
     * 替换默认图片地址
     */
    function replaceDefaultImg(img) {
        var type = img.getAttribute('type');
        switch (type) {
            case 'teacher':
                img.src = '/sysimg/tavatar.jpg';
                break;
            case 'expert':
                img.src = '/sysimg/eavatar.jpg';
                break;
            case 'user':
                img.src = '/sysimg/avatar.jpg';
                break;
            case 'noicon':
                img.src = '/sysimg/fileicon/chm.gif';
                break;
            case 'exam':
                img.src = '/SysImg/exam/shijuan.jpg';
                break;
            case 'logo':
                img.src = '/SysImg/nologo.gif';
                break;
            default:
                img.src = '/sysimg/nopic_225_142.png';
                break;
        }

    }

    /**
     * 图片放大
     */
    var imagesZoomInIndex = 0;

    function imagesZoomIn(src) {
        imagesZoomInIndex++;
        $('body').append('<div id="imagesZoomIn' + imagesZoomInIndex + '"><div style="position:fixed;left:0;top:0;width:100%;height:100%;background:#000;filter:alpha(opacity=60); -moz-opacity:0.6; -khtml-opacity: 0.6;  opacity: 0.6; z-index:9999;" onclick="$(\'#imagesZoomIn' + imagesZoomInIndex + '\').remove();$(\'body\').css(\'overflow\',\'\')"></div><img src="' + src + '" style="position:fixed;top:50%;left:50%;max-width:70%;max-height:70%;z-index:10000;filter:alpha(opacity=0); -moz-opacity:0; -khtml-opacity: 0;  opacity: 0;" /></div>').css('overflow', 'hidden');
        var $imageBoxTarget = $('#imagesZoomIn' + imagesZoomInIndex);
        $imageBoxTarget.find('img').load(function() {
            var _left = $(this).width() / 2;
            var _top = $(this).height() / 2;
            $(this).attr('style', 'position:fixed;top:50%;left:50%;max-width:70%;max-height:70%;z-index:10000;margin-left:-' + _left + 'px;margin-top:-' + _top + 'px;')
        })
    }

    /**
     * 分页滚动加载
     */
    function loadPageData(currPage, parameter, callBack) {
        var pageCount = parseInt(parameter.pageCount);
        var postParam = parameter.postParam;
        var postUrl = parameter.postUrl;
        if (currPage > pageCount) {
            $("#pagelistend").show().html("已全部加载完毕！");
            return false
        }
        var str = "";
        if (postParam.indexOf("=") != -1 || postParam == "") {
            str = "page=" + currPage + "&" + postParam + "&rnd=" + Math.random();
        } else {
            str = "rnd-" + Math.random() + ",p-" + currPage + "," + postParam
        }

        $.ajax({
            type: "get",
            url: postUrl,
            data: str,
            success: function(data) {
                if (data == "") {
                    $("#pagelistend").show().html("已全部加载完毕！");
                } else {
                    $("#pagelist").append(data);
                }

                //加载成功后执行方法
                typeof callBack === 'function' && callBack();
            }
        });

    }


    /**
     * 监听是否滚动到底部
     */
    function getIsScrolltolower(el) {
        var isScrolltolower = false;

        if (el) {
            if (el.scrollTop + el.offsetHeight >= el.scrollHeight) {
                isScrolltolower = true
            }

        } else {
            if (window.scrollY + window.innerHeight >= document.getElementsByTagName('body')[0].scrollHeight) {
                isScrolltolower = true
            }
        }
        return isScrolltolower
    }

    /**
     * 更新组件
     */
    function updateComponent(el){
        var $el = $(el);
        $el.each(function(){
            var props = getProps(this);
            switch(this.nodeName){
                case 'COURSE-KESHI':
                    getCourseCatalog(this,props,true);
                    break
                case 'EVALUATION-LIST':
                    new getEvaluationList(this,props);
                    break
                case 'COURSE-EXAM':
                    new getCourseExam(this,props);
                    break
                case 'COURSE-DATA':
                    new getCourseData(this,props);
                    break
            }
            
        })
    }

    function getProps(target){
        var attributes = target.attributes;
        var props = {};
        KS_Utils.map(attributes,function(attr){
            var name = attr.name.toLocaleLowerCase();
            if(name){
                var a = name.match(/\-\w/g) || [];
                KS_Utils.map(a,function(k){
                    var letter = k.split('-')[1].toUpperCase();
                    name = name.replace(k,letter);
                });
                props[name] = attr.value;
            }
        });
        return props
    }

    /**
     * 加载分页数据
     */
    function loadPage(parameter, callBack) {
        var currPage = 1;
        var pageCount = parameter.pageCount;
        if (parseInt(pageCount) > 1) {
            $("#pagelistend").show().html("滚动加载更多...");
        }
        $(window).scroll(function() {
            /**
             * 当内容滚动到底部时加载新的内容
             */
            if ($(this).scrollTop() + window.innerHeight + 20 >= $(document).height()) {
                currPage++;
                loadPageData(currPage, parameter, callBack);
            }
        });
    }
	function getUni(resolve){
		if(typeof uni === 'object'){
			resolve(uni)
		}else{
			setTimeout(function(){
				getUni(resolve)
			},200)
		}
	}
	
    KS_Utils = {
        addToCourseCart: addToCourseCart,
        getUserInfo: getUserInfo,
        gotozan: gotozan,
        getzan: getzan,
        getcollect: getcollect,
        collect: collect,
        replaceDefaultImg: replaceDefaultImg,
        imagesZoomIn: imagesZoomIn,
        loadPage: loadPage,
        getSwiper: getSwiper,
        getIsScrolltolower:getIsScrolltolower,
        getArtTemplate:getArtTemplate,
        popup:KS_Popup,
        getUserAppToken:getUserAppToken,
        getUID:getUID,
        getHistoryTime:getHistoryTime,
        onServerTimeReady:onServerTimeReady,
        showPopover:showPopover,
        map:domap,
        updateComponent:updateComponent,
        AudioPlayer:AudioPlayer,
        imgPreview:imgPreview,
		getUni:getUni,
		open:function(url,target,params){
			params = params || {}
			params.title = params.title || ''
			params.type = params.type || 'navigate'
			
			if(SOURCE === 'app'){
				getUni(function(uni){
					switch(params.type){
						case 'redirect':
							uni.redirectTo({
								url:'/pages/web/web?title='+params.title+'&url='+encodeURIComponent(url)
							})
						break
						default:
							uni.navigateTo({
								url:'/pages/web/web?title='+params.title+'&url='+encodeURIComponent(url)
							})
					}
					
				})
				return
			}
			if(target === '_blank'){
				window.open(url)
			}else{
				location.href = url
			}
		}
    }
    KS_GetCompoents = function(config) {
        config = config || {}
		SOURCE = config.source
		if(SOURCE === 'app'){
			/*异步加载uni-app所需脚本*/
			var wxJs = document.createElement('script')
			wxJs.src = '//res.wx.qq.com/open/js/jweixin-1.4.0.js'
			wxJs.onload = function(){
				var uniJs = document.createElement('script')
				uniJs.src = '//js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js'
				document.body.appendChild(uniJs)
			}
			document.body.appendChild(wxJs)
		}
        if (config.schoolid) {
            schoolid = config.schoolid;
            params_schoolid = '&schoolid=' + config.schoolid
        }
        var that = this;
        var hasCss = false;
        if(!hasCss){
            $('head').append('<link href="/KS_Inc/static/edu/components.css?v7.0" rel="stylesheet" type="text/css" />');
            if(config.primary){
                $('head').append('<style>'+
                                 '  .ks-button--primary{background-color: '+config.primary+';border-color: '+config.primary+';}'+
                                 '  .ks-input:focus{ border-color: '+config.primary+';}'+
                                 '</style>');
            }
            hasCss = true;
        }
        this.createExtend();
        $(document).ready(function() {
            
            getSwiper(function(Swiper){
                //配置轮播图
                $('[drag-carousel]').each(function() {
                    creatCarouse(this,Swiper)
                });
            })

            //获取购课车数量
            getCourseCartNum();

            /**课程目录组件注册 */
            that.reg('course-keshi',function(props){
                getCourseCatalog(this,props);
            });

            /**评论组件注册 */
            that.reg('evaluation-list',function(props){
                new getEvaluationList(this,props);
            });
            
            /**课程试卷 */
            that.reg('course-exam',function(props){
                new getCourseExam(this,props);
            });
            
            /**课程资料 */
            that.reg('course-data',function(props){
                new getCourseData(this,props);
            });
            setInterval(function() {
				/**
				 * 训练营目录
				 */
                $('camp-directory').each(function() {
                    if ($(this).attr('lazy-load') === 'true' && $(this).attr('loaded') !== 'true') {
                        $(this).attr('loaded', 'true');
                        getCampDirectory(this)
                    }
                });
				/**
				 * 讨论列表
				 */
				$('comment-list').each(function() {
                    if ($(this).attr('lazy-load') === 'true' && $(this).attr('loaded') !== 'true') {
                        $(this).attr('loaded', 'true');
                        getCommentList(this)
                    }
                });
                
                /**
                 * 倒计时
                 */
                $('countdown').each(function(index) {
                    setCountdown(this)
                });
            }, 100);

            /**
             * 图片懒加载
             */
            $(window).scroll(function() {
                var top = $(window).scrollTop() + window.innerHeight;
                $('img[preloading]').each(function() {
                    var thisTop = $(this).offset().top;
                    var src = $(this).attr('preloading');
                    if (top >= thisTop) {
                        $(this).attr('src', src).css('opacity', 0).removeAttr('preloading');
                        this.onload = function() {
                            $(this).animate({
                                opacity: 1
                            });
                        }
                        this.onerror = function() {
                            replaceDefaultImg(this)
                            $(this).animate({
                                opacity: 1
                            });

                        }
                    }
                });
            }).scroll();

        });
        return KS_Utils
    };
    /**
     * 组件注册
     */
    KS_GetCompoents.prototype.reg = function(name,component){
        $(name).each(function() {
            var props = getProps(this);
            $(this).css('display','block');
            component.call(this,props);
        });
    }
    /**
     * 基于jquery的方法扩展
     */
    KS_GetCompoents.prototype.createExtend = function() {
        /**
         * 轮播图方法扩展
         */
        $.fn.carousel = function(parameter) {
            var $this = $(this);
            var width = parameter.width;
            var height = parameter.height;
            var axis = parameter.axis || 'X';
            var arrow = parameter.arrow;
            var autoPlay = parameter.autoPlay;
            var object = parameter.object;
            var scrollType = parameter.scrollType || 'slide';
            var dots = parameter.dots;
            var number = parameter.number;
            var speed = parameter.speed || 400;
            var interval = parameter.interval;
            var size = $this.find(object).size();
            var index = 0;
            var playFlag = true;
            var initialWidth = parameter.width; //存储初始数据，用于检测是否设置百分比
            var initialHeight = parameter.height; //存储初始数据，用于检测是否设置百分比
            if ($this.css('position') == 'static') {
                $this.css({ position: 'relative' });
            };
            $this.css({ width: width, height: height, overflow: 'hidden' });
            var $carouselScroll;
            setTimeout(function() {
                if (initialWidth.indexOf('%') != '-1') {
                    width = $this.width();
                };
                if (initialHeight.indexOf('%') != '-1') {
                    height = $this.height();
                };
                $this.css({ width: width, height: height });
                if (scrollType == 'slide') {
                    if (axis == 'X') {
                        $this.wrapInner('<div class="carousel-scroll" style="width:99999px"></div>');
                        $this.find(object).css({ width: width, height: height, float: 'left', overflow: 'hidden' });
                    } else if (axis == 'Y') {
                        $this.wrapInner('<div class="carousel-scroll" style="height:99999px"></div>');
                        $this.find(object).css({ width: width, height: height, display: 'block', overflow: 'hidden' });
                    };
                    $carouselScroll = $this.find('.carousel-scroll');
                } else if (scrollType == 'fade') {
                    $this.find(object).css({ width: width, height: height, overflow: 'hidden', display: 'none' });
                    $this.find(object).first().show();
                };
                $(window).resize(function() {
                    $this.css({ width: initialWidth, height: initialHeight });
                    width = $this.width();
                    height = $this.height();
                    $this.css({ width: width, height: height });
                    $this.find(object).css({ width: width, height: height });
                });

                //是否需要小圆点
                if (dots) {
                    if (scrollType == 'slide') {
                        $this.find(object).each(function() {
                            $(this).attr('carousel-id', $(this).index());
                        });
                    };
                    $this.append('<div class="carousel-dots"><span></span></div>');
                    if (dots == 2) {
                        for (i = 0; i < size; i++) {
                            var num = i + 1;
                            $this.find('.carousel-dots span').append('<i>' + num + '</i>');
                        };
                    } else if (dots == 1) {
                        for (i = 0; i < size; i++) {
                            $this.find('.carousel-dots span').append('<i></i>');
                        };
                    };
                    $this.find('.carousel-dots').find('i:first').addClass('on');

                    $this.find('.carousel-dots').on('click', 'i', function() {
                        if (playFlag == true) {
                            playFlag = false;
                            var oldIndex = $this.find('.carousel-dots').find('i.on').index();
                            index = $(this).index();
                            $(this).addClass('on').siblings().removeClass('on');
                            if (scrollType == 'slide') {
                                var $thisObject = $this.find('' + object + '[carousel-id="' + index + '"]');
                                var prevObjectSize = $thisObject.prevAll(object).size();

                                var $nextObject = $thisObject.nextAll(object);

                                if (index == oldIndex) {
                                    //相同不执行任何操作
                                    playFlag = true
                                } else if (index > oldIndex) {
                                    if (prevObjectSize > 0) {
                                        //向右、上滚 
                                        if (axis == 'X') {
                                            var scrollWidth = width * prevObjectSize;
                                            $carouselScroll.animate({ marginLeft: '-' + scrollWidth + 'px' }, speed);
                                        } else if (axis == 'Y') {
                                            var scrollHeight = height * prevObjectSize;
                                            $carouselScroll.animate({ marginTop: '-' + scrollHeight + 'px' }, speed);
                                        };
                                        setTimeout(function() {
                                            playFlag = true;
                                            for (p = prevObjectSize - 1; p >= 0; p--) {
                                                $($this.find('' + object + '[carousel-id="' + index + '"]').prevAll(object)[p]).insertAfter($this.find(object).last());
                                            };
                                            if (axis == 'X') {
                                                $carouselScroll.animate({ marginLeft: '0px' }, 0);
                                            } else if (axis == 'Y') {
                                                $carouselScroll.animate({ marginTop: '0px' }, 0);
                                            };
                                        }, speed + 50);
                                    };
                                } else {
                                    //向左、下滚
                                    $nextObject.insertBefore($this.find(object).first());
                                    $thisObject.insertBefore($this.find(object).first());
                                    if (axis == 'X') {
                                        var scrollWidth = width * ($nextObject.size() + 1);
                                        $carouselScroll.css({ marginLeft: '-' + scrollWidth + 'px' });
                                        $carouselScroll.animate({ marginLeft: '0px' }, speed);

                                    } else if (axis == 'Y') {
                                        var scrollHeight = height * ($nextObject.size() + 1);
                                        $carouselScroll.css({ marginTop: '-' + scrollHeight + 'px' });
                                        $carouselScroll.animate({ marginTop: '0px' }, speed);
                                    };
                                    setTimeout(function() {
                                        playFlag = true;
                                    }, speed + 50);
                                }; //slide
                            } else if (scrollType == 'fade') {
                                $this.find(object).eq(index).fadeIn(speed).siblings().stop().hide();
                                setTimeout(function() {
                                    playFlag = true;
                                }, speed);
                            }; //fade
                        };
                    });
                };

                /**
                 * 是否需要左右按钮
                 */
                if (arrow == true) {
                    $this.append('<div class="carousel-prev"></div><div class="carousel-next"></div>');
                    $this.on('click', '.carousel-prev', function() {
                        index = $this.find('.carousel-dots .on').index();
                        if (size > 1) {
                            if (playFlag == true) {
                                playFlag = false;
                                index--;
                                if (index < 0) {
                                    index = size - 1;
                                };
                                if (dots == true) {
                                    $this.find('.carousel-dots').find('i:eq(' + index + ')').addClass('on').siblings().removeClass('on');
                                };
                                if (scrollType == 'slide') {
                                    $this.find(object).last().insertBefore($this.find(object).first());
                                    if (axis == 'X') {
                                        $carouselScroll.css({ marginLeft: -width + 'px' });
                                        $carouselScroll.animate({ marginLeft: '0px' }, speed);
                                    } else if (axis == 'Y') {
                                        $carouselScroll.css({ marginTop: -height + 'px' });
                                        $carouselScroll.animate({ marginTop: '0px' }, speed);
                                    };
                                } else if (scrollType == 'fade') {
                                    $this.find(object).eq(index).fadeIn(speed).siblings().stop().hide();
                                };
                                setTimeout(function() {
                                    playFlag = true;
                                }, speed + 50);
                            };
                        };
                    });
                    $this.on('click', '.carousel-next', function() {
                        nextClick();
                    });
                };

                /**
                 * 是否自动播放
                 */
                if (autoPlay == true) {
                    if (!interval) {
                        interval = 4000;
                    };
                    var autoPlayFlag = true;
                    setInterval(function() {
                        autoPlayFlag && nextClick()

                    }, interval)
                    $this.mousemove(function() {
                        autoPlayFlag = false;
                    });
                    $this.mouseout(function() {
                        autoPlayFlag = true;
                    });
                }
            }, 100);

            function nextClick() {
                index = $this.find('.carousel-dots .on').index();
                if (size > 1) {
                    if (playFlag == true) {
                        playFlag = false;
                        index++;
                        if (index >= size) {
                            index = 0;
                        };
                        if (dots) {
                            $this.find('.carousel-dots').find('i:eq(' + index + ')').addClass('on').siblings().removeClass('on');
                        };
                        if (scrollType == 'slide') {
                            if (axis == 'X') {
                                $carouselScroll.animate({ marginLeft: -width + 'px' }, speed);
                            } else if (axis == 'Y') {
                                $carouselScroll.animate({ marginTop: -height + 'px' }, speed);
                            };
                        } else if (scrollType == 'fade') {
                            $this.find(object).eq(index).fadeIn(speed).siblings().stop().hide();
                        };
                        setTimeout(function() {
                            if (scrollType == 'slide') {
                                $this.find(object).first().insertAfter($this.find(object).last());
                                if (axis == 'X') {
                                    $carouselScroll.animate({ marginLeft: '0px' }, 0);
                                } else if (axis == 'Y') {
                                    $carouselScroll.animate({ marginTop: '0px' }, 0);
                                };
                            };
                            playFlag = true;
                        }, speed + 50);
                    }
                }
            }
        };

        $.fn.tab = function(parameter) {
            var $this = $(this);
            var tabName = parameter.tabName;
            var boxName = parameter.boxName;
            var tabEvent = parameter.tabEvent || 'click';
            var type = parameter.type || 'normal';
            $this.each(function() {
                var $tabName = $(this).find(tabName);
                var $boxName = $(this).find(boxName);
                $tabName.first().addClass('active').siblings().removeClass('active');
                $boxName.first().show().siblings(boxName).hide();

                $tabName.on(tabEvent, function() {
                    var index = $(this).index();
                    $(this).addClass('active').siblings().removeClass('active');
                    if (type == 'normal') {
                        $boxName.eq(index).show().siblings(boxName).hide();
                    } else if (type == 'fade') {
                        $boxName.eq(index).fadeIn().siblings(boxName).stop().hide();
                    };
                });

            });

        }
    }


})(jQuery);

/*
* 分页组件
*/
(function ($, window, document, undefined) {
    'use strict'; var defaults = { page: 1, pageSize: 10, total: 0, showTotal: false, totalTxt: "共{total}条", noData: false, showSkip: false, showPN: true, prevPage: "上一页", nextPage: "下一页",color:'#3c81f9', backFun: function (page) { } }; function Plugin(element, options) { this.element = $(element); this.settings = $.extend({}, defaults, options); this.pageNum = 1, this.pageList = [], this.pageTatol = 0; this.init(); }
    $.extend(Plugin.prototype, {
        init: function () { this.element.empty(); this.viewHtml(); }, creatHtml: function (i) { i == this.settings.page ? this.pageList.push('<span class="active" style="background:'+this.settings.color+';border-color:'+this.settings.color+';" data-page=' + i + '>' + i + '</span>') : this.pageList.push('<span data-page=' + i + '>' + i + '</span>'); }, viewHtml: function () {
            var settings = this.settings; var pageTatol = 0; if (settings.total > 0) { pageTatol = Math.ceil(settings.total / settings.pageSize); } else { if (settings.noData) { pageTatol = 1; settings.page = 1; settings.total = 0; } else { return; } }
            this.pageTatol = pageTatol; var pageArr = []; this.pageNum = settings.page; if (settings.showTotal) { pageArr.push('<div class="ks-page-total">' + settings.totalTxt.replace(/\{(\w+)\}/gi, settings.total) + '</div>'); }
            pageArr.push('<div class="ks-page-number">'); this.pageList = []; if (settings.showPN) { settings.page == 1 ? this.pageList.push('<span class="span-disabled" data-page="prev">' + settings.prevPage + '</span>') : this.pageList.push('<span data-page="prev">' + settings.prevPage + '</span>'); }
            if (pageTatol <= 6) { for (var i = 1; i < pageTatol + 1; i++) { this.creatHtml(i); } } else {
                if (settings.page < 5) {
                    for (var i = 1; i <= 5; i++) { this.creatHtml(i); }
                    this.pageList.push('<span data-page="none">...</span><span data-page=' + pageTatol + '>' + pageTatol + '</span>');
                } else if (settings.page > pageTatol - 4) { this.pageList.push('<span data-page="1">1</span><span data-page="none">...</span>'); for (var i = pageTatol - 4; i <= pageTatol; i++) { this.creatHtml(i); } } else {
                    this.pageList.push('<span data-page="1">1</span><span data-page="none">...</span>'); for (var i = settings.page - 2; i <= Number(settings.page) + 2; i++) { this.creatHtml(i); }
                    this.pageList.push('<span data-page="none">...</span><span data-page=' + pageTatol + '>' + pageTatol + '</span>');
                }
            }
            if (settings.showPN) { settings.page == pageTatol ? this.pageList.push('<span class="span-disabled" data-page="next">' + settings.nextPage + '</span>') : this.pageList.push('<span data-page="next">' + settings.nextPage + '</span>'); }
            pageArr.push(this.pageList.join('')); pageArr.push('</div>'); if (settings.showSkip) { pageArr.push('<div class="ks-page-skip">跳至&nbsp;<input type="text" value="' + settings.page + '"/>&nbsp;页&nbsp;&nbsp;<span data-page="go">确定</span></div>'); }
            this.element.html(pageArr.join('')); this.clickBtn();
        }, clickBtn: function () {
            var that = this; var settings = this.settings; var ele = this.element; var pageTatol = this.pageTatol; this.element.off("click", "span"); this.element.on("click", "span", function () {
                var pageText = $(this).data("page"); switch (pageText) {
                    case "prev": settings.page = settings.page - 1 >= 1 ? settings.page - 1 : 1; pageText = settings.page; break; case "next": settings.page = Number(settings.page) + 1 <= pageTatol ? Number(settings.page) + 1 : pageTatol; pageText = settings.page; break; case "none": return; case "go": var p = parseInt(ele.find("input").val()); if (/^[0-9]*$/.test(p) && p >= 1 && p <= pageTatol) { settings.page = p; pageText = p; } else { return; }
                        break; default: settings.page = pageText;
                }
                if (pageText == that.pageNum) { return; }
                that.pageNum = settings.page; that.viewHtml(); settings.backFun(pageText);
            }); this.element.on("keyup", "input", function (event) { if (event.keyCode == 13) { var p = parseInt(ele.find("input").val()); if (/^[0-9]*$/.test(p) && p >= 1 && p <= pageTatol && p != that.pageNum) { settings.page = p; that.pageNum = p; that.viewHtml(); settings.backFun(p); } else { return; } } });
        }
    }); $.fn.sPage = function (options) { return new Plugin(this, options); }
})(jQuery, window, document);