 (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_Compoents = KS_Compoents;
    function KS_Compoents(){
        /**
         * 获取购课车数量
         */
        getCourseCartNum();
        /**
         * 显示课程课时
         * 
         */
        getCompoents('ks-course-keshi').each(function(){
            getCourseKeshi(this)
        });


        /**
         * 倒计时
         */
        setInterval(function(){
            getCompoents('ks-count-down').each(function(index){
                setCountdown(this)
            })
        },100)
       
        /**
         * 图片懒加载
         */
        $(window).scroll(function(){

            var top = $(window).scrollTop() + window.innerHeight;
            $('img[ks-preloading]').each(function(){
                var thisTop = $(this).offset().top;
                var src = $(this).attr('ks-preloading');
                if(top >= thisTop){
                    $(this).attr('src',src).css('opacity',0).removeAttr('ks-preloading');
                    this.onload = function(){
                        $(this).animate({
                            opacity:1
                        })
                    }
                    this.onerror = function(){
                        replaceDefaultImg(this)
                        $(this).animate({
                            opacity:1
                        })
                        
                    }
                }    
            })
        }).scroll();
        
        return {
            getCourseCartNum,
            getCourseKeshi,
            setCountdown,
            getUserInfo,
            addToCourseCart,
            replaceDefaultImg,
            dealingWithAnErrorPicture,
            imagesZoomIn,
            LoadPage,
            gotozan,
            getzan,
            getcollect,
            collect
        }
    };

    function getCompoents(name){
        return $(name)
    }

    function structureMount(el,value){
        $(el).html(value)
        // var $el = $(el);
        // var tag = $el.attr('tag') || 'div';
        // var _$el = $(document.createElement(tag))
        // _$el.attr('')
        // $(el).attr('c')
    }
    
    /**
     * 获取服务器时间
     */
    function getServerTime(callback){
        $.get('/plus/ajaxs.ashx?a=gettime',function(res){
            typeof callback === 'function' && callback(res)
        })
        
    };


    /**
     * 结束倒计时
     */
    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);
        
    }
    /**
     * 获取购课车数量
     * <course-cart-num></course-cart-num>
     */
     function getCourseCartNum(callback) {
       
        $.get('/index.aspx?c=course&a=shopcart&action=num&schoolid=' + SCHOOL_ID,function(num){
            
            getCompoents('ks-course-cart-num').each(function(){
                this.innerHTML = num
            });
            typeof callback === 'function' && callback(num)
        }) 
    };
    

    /**
     * 获取课时
     * <div ks-compoents="courseKeshi" course-id="{Number}" course-type="{String}" current="{Number}"></div>
     */

    function getCourseKeshi(el){
       
        var $el = $(el);
        var target = $el.attr('target') === '_blank' ? ' target="_blank"' : '';
        var getUrl = '/plus/ajaxs.ashx?a=getcosInfo&schoolid=' + SCHOOL_ID;
        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&schoolid=' + SCHOOL_ID+'&id='+courseId+'&type='+type,function(res){
            if (res === "ok"){
                Alert("恭喜，成功加入购课车！");
                getCourseCartNum();
            }else{
                Alert(res);
            }
        })  
    }

        
    /**
     * 获取用户信息
     * @param {Function} 已登录回调函数
     * @param {Function} 未登录回调
     * res 返回用户信息json
     */
     function getUserInfo(resolve, fail) {
         $.get('/plus/ajaxs.ashx?a=checkislogin&json=1&schoolid=' + SCHOOL_ID, 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="popup_cancel">取消</span>' : '';

        $('body').append('<div class="popup_alert" id="popup'+popup_index+'"><div class="popup_title"><div class="popup_close"></div>'+title+'</div><div class="popup_msg"><i class="popup_icon_'+icon+'"></i>'+msg+'</div><div class="popup_button"><span class="popup_sure">确认</span>'+cancelBtn+'</div></div>'+mask);
        var $popupEl = $('#popup'+popup_index);
        
        $popupEl.on('click','.popup_cancel',function(){
            Close(popup_index)
        }).on('click','.popup_close',function(){
            Close(popup_index)
        }).on('click','.popup_sure',function(){
            
            Close(popup_index,true)
        })
        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 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([ks-preloading],[onerror],[src])');
        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);




