 (function($){
    /**
     * 计算服务器时间
     */
    var serverTime = 0;
    var weekday = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
        
    getServerTime(function(time){
        var serverDate = new Date(time);
        serverTime = 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
            })
            serverTime += 100;
        },100)
    });
    
    window.KS_Main = KS_Main;
    function KS_Main(parameter){
        parameter = parameter || {};
        this.parameter = parameter;
        typeof parameter.beforeCreat === 'function' && parameter.beforeCreat();
        this.created();
        typeof parameter.created === 'function' && parameter.created()
        
    };

    KS_Main.prototype.created = 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();
                    };
                });
            
            });
            
        };

        $.fn.nesting = function(parameter){
            var $this = $(this);
            var tagName = parameter.tagName;
            var nestedName = parameter.nestedName.split(',');
            var loopNum = parameter.loopNum;
            var size = $this.find(tagName).size();
            var frequency = Math.ceil(size/loopNum);
            var nestedTag = nestedName[0];
            var nestedTagName = nestedName[1];
            var tagId = -1;
            $this.find(tagName).each(function(){
                tagId++;
                $(this).attr('tag-id',tagId);
            });
            
            if($.trim(nestedTagName)==''||!nestedTagName){
                var appendTag = '<'+nestedTag+' nesting></'+nestedTag+'>';
            }else{
                var appendTag = '<'+nestedTag+' class="'+nestedTagName+'" nesting></'+nestedTag+'>';
            };
            for(f=0;f<frequency;f++){
                $this.append(appendTag);
                
                for(s=f*loopNum;s<f*loopNum+loopNum;s++){
                    
                    $this.find(tagName+'[tag-id="'+s+'"]').appendTo($this.find('[nesting]').eq(f))
                    
                };
            };
            
            
        };

        $.fn.aspectRatio = function(parameter){
        
            var $arr = $(this);
            var set = parameter.set;
            
            $(window).resize(function(){
                $arr.each(function(){
                    $(this).height($(this).width()*set);
                    
                });
            }).resize();

        };

        
        /**
         * 数字滚动
         */
        $.fn.countTo = function (options) {
            options = options || {};
            
            return $(this).each(function () {
                // set options for current element
                var settings = $.extend({}, $.fn.countTo.defaults, {	
                    from:            $(this).data('from'),
                    to:              $(this).data('to'),
                    speed:           $(this).data('speed'),
                    refreshInterval: $(this).data('refresh-interval'),
                    decimals:        $(this).data('decimals')
                }, options);
                
                // how many times to update the value, and how much to increment the value on each update
                var loops = Math.ceil(settings.speed / settings.refreshInterval),
                    increment = (settings.to - settings.from) / loops;
                
                // references & variables that will change with each update
                var self = this,
                    $self = $(this),
                    loopCount = 0,
                    value = settings.from,
                    data = $self.data('countTo') || {};
                
                $self.data('countTo', data);
                
                // if an existing interval can be found, clear it first
                if (data.interval) {
                    clearInterval(data.interval);
                }
                data.interval = setInterval(updateTimer, settings.refreshInterval);
                
                // initialize the element with the starting value
                render(value);
                
                function updateTimer() {
                    value += increment;
                    loopCount++;
                    
                    render(value);
                    
                    if (typeof(settings.onUpdate) == 'function') {
                        settings.onUpdate.call(self, value);
                    }
                    
                    if (loopCount >= loops) {
                        // remove the interval
                        $self.removeData('countTo');
                        clearInterval(data.interval);
                        value = settings.to;
                        
                        if (typeof(settings.onComplete) == 'function') {
                            settings.onComplete.call(self, value);
                        }
                    }
                }
                
                function render(value) {
                    var formattedValue = settings.formatter.call(self, value, settings);
                    formattedValue = formattedValue.replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
                    $self.html(formattedValue);
                }
            });
        };

        $.fn.countTo.defaults = {
            from: 0,               // the number the element should start at
            to: 0,                 // the number the element should end at
            speed: 1000,           // how long it should take to count between the target numbers
            refreshInterval: 100,  // how often the element should be updated
            decimals: 0,           // the number of decimal places to show
            formatter: formatter,  // handler for formatting the value before rendering
            onUpdate: null,        // callback method for every time the element is updated
            onComplete: null       // callback method for when the element finishes updating
        };


        /**
         * 动态嵌套
         */
        $('[nesting]').each(function(){
            var parameter = $(this).attr('nesting').split(',');
            var parameterLength = parameter.length;
            var nestingArray = {};
            for(i=0;i<parameterLength;i++){
                var nodeName = parameter[i].split(':')[0];
                var nodeContent = parameter[i].split(':')[1];
                if(nodeContent=='true'){
                    nodeContent = true;
                }
                if(nodeName=='loopNum'){
                    nodeContent = Number(nodeContent)
                }
                nestingArray[nodeName] = nodeContent
            };

            $(this).nesting(nestingArray);

        });


        //配置轮播图
        $('[drag-carousel]').each(function(){
            creatCarouse(this)
        });

        //获取购课车数量
        getCourseCartNum();
        
        /**
         * 显示课程课时
         * 
         */
        $('course-keshi').each(function(){
            getCourseKeshi(this)
        });


        setInterval(function(){

            //按比例设置高度
            $('[ratio]').each(function(){
                $(this).aspectRatio({
                    set:Number($(this).attr('ratio'))
                });
                $(this).removeAttr('ratio')
            });

            /**
             * 倒计时
             */
            $('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();
        
        
        /**
         * 图片出错处理
         */
        dealingWithAnErrorPicture();


         /**
         * 执行页面动画
         */
        if(!this.parameter.config || this.parameter.config.pageAnimate !== false){
            pageAnimate('.page-animate')
        }

        /**
         * 对外暴露方法
         */
        window.addToCourseCart = addToCourseCart;
        window.getUserInfo = getUserInfo;
        window.count = count;
        window.Tips = Tips;
        window.Alert = Alert;
        window.Confirm = Confirm;
        window.Close = Close;
        window.goSearch = goSearch;
        window.gotozan = gotozan;
        window.getzan = getzan;
        window.getcollect = getcollect;
        window.collect = collect;
        window.pageAnimate = pageAnimate;
        window.dealingWithAnErrorPicture = dealingWithAnErrorPicture;
        window.replaceDefaultImg = replaceDefaultImg;
        window.imagesZoomIn = imagesZoomIn;
        window.LoadPage = LoadPage;

        /**
         * 兼容处理
         */
        
        if(typeof replaceDefaultImgArray === 'object'){
            domap(replaceDefaultImgArray,function(img){
                replaceDefaultImg(img)
            })
        }

    }
    
    
    /**
     * 获取服务器时间
     */
    function getServerTime(resolve){
        $.get('/plus/ajaxs.ashx?a=gettime',function(res){
            typeof resolve === 'function' && resolve(res)
        })
        
    };

    function formatter(value, settings) {
        return value.toFixed(settings.decimals);
    }

    function count(options) {	
        var $this = $(this);
        options = $.extend({}, options || {}, $this.data('countToOptions') || {});
        if($this.attr('data-load') !== 'true'){
            $this.countTo(options);
            $this.attr('data-load','true');
        };
    }

    /**
     * 结束倒计时
     */
    function setCountdown(el){
        var beginTime = $(el).attr('begin-time');
        if(beginTime){
            beginTime = new Date($(el).attr('begin-time')).getTime();
            if(beginTime > serverTime){
                $(el).html('未开始.');
                return false
            }
        }
        var endTime = new Date($(el).attr('end-time'))
        var type = $(el).attr('type') || 0;        
        var nMS = endTime.getTime() - serverTime;
        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);
        
    }
    
    
   
    
    /**
     * 执行页面动画
     */
    function pageAnimate(el){
        $(el).each(function () {
            var ofTop = $(this).offset().top - $(window).height();
            var maxTop = $(this).offset().top + $(this).outerHeight();
            var type = $(this).attr('data-type') || 'fadeInUp';
           
            var $that = $(this);
            var delay = $that.attr('data-delay');
            if (delay) {
                $that.css({ animationDelay: delay + 's' });
            };
            
            $(window).scroll(function () {
                if ($(window).scrollTop() > ofTop && $(window).scrollTop() < maxTop) {
                    $that.removeClass('page-animate').addClass('animated ' + type);
                    if ($that.find('.page-timer').length != 0) {
                      
                        $that.find('.page-timer').each(count);
                    }
                }
            }).scroll();
        });
    }

    /**
     * 创建轮播图
     * @param {Object} 
     */
    function creatCarouse(obj){
        var parameter = $(obj).attr('drag-carousel').split(',');
        var parameterLength = parameter.length;
        var carouselArray = {};
        for(i=0;i<parameterLength;i++){
            var nodeName = parameter[i].split(':')[0];
            var nodeContent = parameter[i].split(':')[1];
            if(nodeContent === 'true'){
                nodeContent = true;
            }
            if(nodeName === 'speed' || nodeName === 'interval'){
                nodeContent = Number(nodeContent)
            }
            carouselArray[nodeName] = nodeContent
        }
        $(obj).carousel(carouselArray);

    }

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

    /**
     * 获取课时
     * <course-keshi course-id="{Number}" course-type="{String}" current="{Number}"></course-keshi>
     */

    function getCourseKeshi(el){
       
        var $el = $(el);
        var target = $el.attr('target') === '_blank' ? ' target="_blank"' : '';
        var courseType = $el.attr('course-type');
        var getUrl = courseType === 'face' ? '/plus/ajaxs.ashx?a=getcosInfo&isface=1' : '/plus/ajaxs.ashx?a=getcosInfo';
        var courseid = $el.attr('course-id');
        var current = $el.attr('current');
        var callback = $el.attr('callback');
        if(courseid === undefined){
            return false
        }
        $el.html('<div class="chapter-loading">加载中...</div>');
        /**
         * 通过periodid获取dom
         */
        function getPeriodidDom(periodid){
            return $el.find('[data-periodid="'+periodid+'"]')
        }

        /**
         * 将秒数转换 mm: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
            
        }

        $.ajax({
            type:'get',
            dataType:'json',
            url:getUrl+'&courseid='+courseid,
            success: function (data) {
                
                /**
                 * 课程购买链接
                 */
                var coursebuyurl = data.Course.coursebuyurl;
                /**
                 * 课程购买情况
                 */
                var specialPermission = false;
                var buyallcos_isCanLearn = false;
                var myPeriodids = [];
                var Pay = data.Pay;
                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 > serverTime){
                                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 Learn = data.Learn;
                var myLearnPeriodlist = [];
                if(Learn){
                    myLearnPeriodlist = Learn.periodlist
                }

                /**
                 * 课时列表
                 */
                var periodlist = data.Course.periodlist;
                var chapterIndex = 0;
                var sectionIndex = 0;
                var keshiIndex = 0;
                if(!periodlist.length){
                    $el.html('<div class="empty">该课程下暂无课时数据</div>');
                    return false
                }
                for(var i=0;i<periodlist.length;i++){
                    var item = periodlist[i];
                    var addtype = item.addtype;
                    var periodname = item.periodname;
                    var periodid = item.periodid;
                    var parentid = item.parentid;
                    switch(addtype){
                        case '0':
                            /**
                             * 章
                             */
                            chapterIndex++;
                            $el.append('<div class="chapter"><div class="chapter-name"><span class="chapter-index">'+chapterIndex+'</span>'+periodname+'</div><div class="chapter-box" data-periodid="'+periodid+'"></div></div>')
                            break
                        case '2':
                            /**
                             * 节
                             */
                            sectionIndex++;
                            var className = parentid == 0 ? 'chapter-section ' : '';
                            var code = '<div class="'+className+'section"><div class="section-name">'+periodname+'</div><div class="section-box" data-periodid="'+periodid+'"></div></div>';
                            if(parentid == 0){
                                /**
                                 * 当parentid为0，说明是独立的节，无章
                                 */
                                $el.append(code)
                            }else{
                                /**
                                 * 在已有章节点下追加节
                                 */
                                getPeriodidDom(parentid).append(code)
                            }
                            break
                        case '1':
                        case '4':
                            /**
                             * 课时
                             */
                            keshiIndex++;

                            /**
                             * isCanLearn
                             * 0 不可观看
                             * 1 可观看
                             * 2 已过期
                             * 3 可试听
                             * 4 已过期但可试听
                             */
                            var isCanLearn = 0;
                            
                            if(specialPermission || item.isfree == 0){
                                /**
                                 * 该课时免费
                                 */
                                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 == periodid){
                                            if(period_item.shixian == 0){
                                                isCanLearn = 1;
                                                break
                                            }else{
                                                if(period_item.enddate > serverTime){
                                                    /**
                                                     * 已满足学习条件，直接跳出循环
                                                     */
                                                    isCanLearn = 1;
                                                    break
                                                }else{
                                                    /**
                                                     * 当前课时已过期，但不跳出循环，继续查找是否有重复购买同课时并且满足学习条件
                                                     */
                                                    if(period_item.islistening == 1){
                                                        isCanLearn = 4
                                                    }else{
                                                        isCanLearn = 2
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    
                                }
                            }

                            /**
                             * 绑定试卷
                             */
                            var exampaper = '';
                            domap(item.exampaper,function(paper){
                                exampaper += '<div class="keshi-exam"><a href="'+paper.url+'" target="_blank">【试卷】'+paper.name+'</a></div>';
                            });
                            
                            /**
                             * 资料
                             */
                            var course_file = '';
                            if(item.zlurl){
                                course_file = isCanLearn === 1 ? '<a href="'+item.zlurl+'" target="_blank"><span class="zlicon"><font class="zl-link-tips">讲义下载</font></span></a>' : '<span class="zlicon zlicon-disabled"></span>'
                                
                            }
                            
                            /**
                             * 学习进度
                             */
                            var schedule = 0;
                            domap(myLearnPeriodlist,function(learn_period){
                                if(learn_period.periodid == periodid){
                                    schedule = learn_period.status == 1 ? 100 : (learn_period.maxlearncount / learn_period.timecount).toFixed(1)*100
 
                                }
                            });

                            item.schedule = schedule;
                            
                            var learnState = '<div class="learn-state"><span class="schedule-icon'+schedule+'"></span></div>';
                            var active = periodid == current ? ' active' : '';
                            var href = (isCanLearn === 1 || isCanLearn === 3 || isCanLearn === 4) ? item.url : coursebuyurl;
                            
                            var unlearn = isCanLearn === 1 ? '' : ' unlearn';
                            var state = ((isCanLearn === 1 && schedule > 0) && '继续学习') || (isCanLearn === 1 && '开始学习') || (isCanLearn === 2 && '已过期') || (isCanLearn === 3 && '试听') || (isCanLearn === 4 && '已过期') || '去购买';
                            var icon_lock = isCanLearn === 1 ? '' : '<i class="icon-lock"></i>';
                            var className = parentid == 0 ? 'chapter-keshi ' : '';
                            var free = item.isfree == 0 ? '<span class="free">免费</span>' : '';
                            var time = secondsConversion(item.timecount);
                            item.time = time;
                            var code = '<div class="'+className+'keshi'+active+'" data-periodid="'+periodid+'">'+course_file+'<a href="'+href+'" class="keshi-url'+unlearn+'"'+target+'>'+icon_lock+'<span class="learn-btn">'+state+'</span>'+learnState+'<span class="type-name">课时'+keshiIndex+'</span>'+periodname+free+'<span class="keshi-duration">'+time+'</span></a>'+exampaper+'</div>';
                            parentid == 0 ? $el.append(code) : getPeriodidDom(parentid).append(code);
                            break
                    }
                }
                $el.find('.chapter-loading').remove();

                if(callback && typeof window[callback] === 'function'){
                    window[callback]({
                        current:current,
                        periodlist:periodlist,
                        data:data
                    })
                }

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

    };


    /**
     * 加入购物车
     * @param {Number} 课程id
     * @param {Number} 课程类型
     */
    function addToCourseCart(courseId,type){
        $.get('/index.aspx?c=course&a=shopcart&action=addtocart&id='+courseId+'&type='+type,function(res){
            if (res === "ok"){
                Alert("恭喜，成功加入购课车！",{
                    icon:'success'
                });
                getCourseCartNum();
            }else{
                Alert(res,{
                    icon:'error'
                });
            }
        })  
    }

    /**
     * 获取用户信息
     * @param {Function} 已登录回调函数
     * @param {Function} 未登录回调
     * res 返回用户信息json
     */
    function getUserInfo(resolve,fail){
        $.get('/plus/ajaxs.ashx?a=checkislogin&json=1',function(res){
           
            var islogin = res.islogin === 'true' ? true : false;
            if(islogin){
                typeof resolve === 'function' && resolve(res)
            }else{
                typeof fail === 'function' && fail(res)
            }

        },'json')
    }
 

    /**
     * 弹窗交互
     */
    var popup_index = 0;
    var popup_functions = {};
    var popup_style = document.createElement('style');
        popup_style.id = 'popup_style';
    var popup_css = document.createTextNode(
        '.popup_alert,.popup_tips{position: fixed;left:50%;top:50%;z-index:9999;opacity:0;border-radius:4px;}'+
        '.popup_alert{min-width:300px;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2); background:#fff; padding-bottom:42px;}'+
        '.popup_mask{position: fixed;width:100%;height:100%;left:0;top:0; z-index:9990;background:rgba(0,0,0,0.3); opacity:0}'+
        '.popup_title{ font-size:16px; color:#666; height: 50px; line-height: 50px; padding:0 15px;position:relative;}'+
        '.popup_close{width:32px;height:32px;background-image:url(/ks_inc/static/img/icons.png);position:absolute; right:10px;top:50%;margin-top:-16px;background-repeat:no-repeat; background-position:0 -92px;cursor: pointer}'+
        '.popup_close:hover{background-position:-32px -92px;}'+
        '.popup_msg{padding:10px 15px 30px 65px; color:#666;position:relative;font-size:14px; line-height: 24px;}'+
        '.popup_button{ position:absolute;right:15px;bottom:15px;  }'+
        '.popup_button span{width:70px;height:32px; line-height:32px; background:#37a7ed; color:#fff; text-align:center;border-radius:4px; cursor: pointer;float:left;margin-left:10px; font-size:14px;}'+
        '.popup_button .cancel{background:#ccc}'+
        '.popup_icon_default,.popup_icon_warning,.popup_icon_success,.popup_icon_error{width:32px;height:32px; position:absolute;left:20px;top:5px;background-image:url(/ks_inc/static/img/icons.png); background-repeat:no-repeat;}'+
        '.popup_icon_warning{ background-position:0 -64px}'+
        '.popup_icon_success{ background-position:0 -32px}'+
        '.popup_icon_error{ background-position:-32px -32px}'+
        '.popup_tips{background:rgba(0,0,0,0.6);color:#fff;padding:10px 15px;font-size:14px;}'
    )
    popup_style.appendChild(popup_css)
    document.getElementsByTagName('head')[0].appendChild(popup_style);
    
    /**
     * 信息提示
     */
    function Tips(msg,parameter,callBack){
        parameter = parameter || {};
        popup_index++;
        var duration = parameter.duration || 3000;
        $('body').append('<div class="popup_tips" id="popup'+popup_index+'">'+msg+'</div>');
        if(typeof callBack === 'function'){
            popup_functions['callBack'+popup_index] = callBack;
        }
        setPopupAnimate(popup_index)
        closeTips(popup_index,duration)
        
    }
    function closeTips(popup_index,duration){
        setTimeout(function(){
            Close(popup_index)
        },duration)
    }
    /**
     * 信息提示框
     */
    function Alert(msg,parameter){
        openAlertOrConfirm(msg,parameter,0)
        
    }

    function openAlertOrConfirm(msg,parameter,type){
        
        parameter = parameter || {};
        popup_index++;
        var icon = parameter.icon || 'default';
        var title = parameter.title || '提示';
        var mask = '<div class="popup_mask" id="popup_mask'+popup_index+'"></div>';
        var cancelBtn = type ? '<span class="cancel" onclick="Close(\''+popup_index+'\')">取消</span>' : '';
        $('body').append('<div class="popup_alert" id="popup'+popup_index+'"><div class="popup_title"><div class="popup_close" onclick="Close(\''+popup_index+'\')"></div>'+title+'</div><div class="popup_msg"><i class="popup_icon_'+icon+'"></i>'+msg+'</div><div class="popup_button"><span onclick="Close(\''+popup_index+'\',true)">确认</span>'+cancelBtn+'</div></div>'+mask);
        if(typeof parameter.determine === 'function'){
            popup_functions['determine'+popup_index] = parameter.determine
        }
        if(typeof parameter.cancel === 'function'){
            popup_functions['callBack'+popup_index] = parameter.cancel
        }
       
        setPopupAnimate(popup_index)
    }
        
    /**
     * 信息提示确认框
     */
    function Confirm(msg,parameter){
        openAlertOrConfirm(msg,parameter,1)
    }

    function setPopupAnimate(id,callback){
        var $el = $('#popup'+id);
        var top = $el.height()/2;
        if(callback){
            $('#popup_mask'+id).animate({
                opacity:0
            },300)
            $el.animate({
                opacity:0,
                marginTop:-top-20
            },300,function(){
                callback()
            })
        }else{
            $el.css({
                marginLeft:-$el.width()/2+'px',
                marginTop:-top-20+'px'
            })
            $('#popup_mask'+id).animate({
                opacity:1
            },300)
            $el.animate({
                opacity:1,
                marginTop:-top
            },300)
        }
    }

    function Close(id,flag){
        setPopupAnimate(id,function(){
            switch($('#popup'+id).attr('class')){
                case 'popup_tips':
                    popup_functions['callBack'+id] && popup_functions['callBack'+id]()
                    break
                case 'popup_alert':
                
                    if(flag){
                        popup_functions['determine'+id] && popup_functions['determine'+id]()
                    }else{
                        popup_functions['callBack'+id] && popup_functions['callBack'+id]()
                    }
                    break
                
            }
            $('#popup_mask'+id).remove();
            $('#popup'+id).remove();
            
        })
        
    }

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

    /**
     * 搜索
     */
    function goSearch(key_el){
        var key = $(key_el).val();
        if(!key.replace(/\s+/g,'')){
            $(key_el).val('').focus();
           
        }else{
            location.href = '/search?type-course,key-'+key
        }
    }

    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") { 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) {
                //alert(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") { 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") {
                    
                    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 dealingWithAnErrorPicture(_range){
        var img_target = _range ? _range : $('img:not([preloading],[onerror])');
        for(var i=0;i<img_target.length;i++){
            isHaveImg(img_target[i])
        }	
    }

    /**
     * 判断是否为错误图片
     */
    function isHaveImg(img){
        
        var imgSrc = img.src;
        
        if(imgSrc.match(/\.jpg|\.png|\.gif|\.jpeg/i)){
			
            //创建图片对象
            var ImgObj = new Image();
            //设置图片对象地址
            ImgObj.src = imgSrc;
			ImgObj.onerror = function(){
                replaceDefaultImg(img);
            }
            
        }
    }

    /**
     * 替换默认图片地址
     */
    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 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);
            }
        });
    }
        
    

})(jQuery);




