Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

var HostUri = "http://v3.myuclass.com/"
//范围 0、全部 1、个人 2、班级 3、学习组
var dataScope = "1";//默认显示个人列表

var pageIndex = 1;
$(function () {
    ucbook.invokeCsFunction("Ready");
 $(".cancelDel").click(function(){ 
        $(".isDelete").hide();
    });
        resizeWindow();
    $(window).resize(function(){
        resizeWindow();
    });
    Handlebars.registerHelper("formatTime", function (numDate) {
        var re = /-?\d+/;
        var m = re.exec(numDate);
        var d = new Date(parseInt(m[0]));
        return d.format("yyyy-MM-dd hh:mm:ss")
    });

    Handlebars.registerHelper("formatSize", formatSize);

    Handlebars.registerHelper("isDeleted", function (fileUrl, hwid) {
        var file = hwid + '\\' + fileUrl.substr(fileUrl.lastIndexOf("\\") + 1);
        if (fileList && fileList.indexOf(file) > -1)
            return "";
        return "loadedDel";
    });
    Handlebars.registerHelper("showDel", function (hwid, fileUrl, urlFlag) {
        var file = hwid + '\\' + fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
        if (urlFlag == "0") {
            if (fileList == null || fileList.indexOf(file) == -1) {
                return "None";
            }
        }
    });
    Handlebars.registerHelper("fileExists", function (hwid, fileUrl, urlFlag) {
        if (urlFlag == "0") {
            var file = hwid + '\\' + fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
            if (fileList && fileList.indexOf(file) > -1) {
                if ($(".perListSel").text() != "我的文件")
                    return "grey";
            } else {
                if ($(".perListSel").text() == "我的文件")
                    return "Def";
            }
        }
        return "";
    });

    Handlebars.registerHelper("nullStr", function (input) {
        if (input == null || input.toLowerCase() == "null") {
            return "   ";
        }
        return input;
    });

});

function resizeWindow() {
    var nScrollHight = 0; // 滚动距离总长(注意不是滚动条的长度)
    var nScrollTop = 0; // 滚动到的当前位置
    var nDivHightNum = $(".studyMain").height() - $(".rightTopNav").height() - $(".rightTab").height() - 1; //
    var nDivHight = $(".tabList").height(nDivHightNum);
    //$('.studyLeft').height($('.studyRight').height());
    $(".tabList").scroll(function () {
        nScrollHight = $(this)[0].scrollHeight;
        nScrollTop = $(this)[0].scrollTop;
        if (nScrollTop + nDivHightNum + 3 >= nScrollHight) {
            console.log("scroll");
            if (pageIndex < pageCount) {
                pageIndex = pageIndex + 1;
                console.log("pageIndex", pageIndex);
                SearchByClass("");
            }

        }
    });
}



function formatSize(bytes) {
    if (bytes === 0) return ' ';
    var k = 1024;
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i) * 100).toPrecision(3) / 100 + ' ' + sizes[i];
}

function SetHost(host) {
    this.HostUri = host;
}

function BindBaseData(baseData) {
    baseData = JSON.parse(baseData);
    BindClassList(baseData.classList);
    BindSubjectList(baseData.subjectList);
    BindClassEvent();
    //BindSubEvent();
    SearchByClass("unBindSub");
}




function BindSubEvent() {
    //选择科目
    $(".rightTopNav").find("li.enable").on("click", function (e) {
        var e = e || window.event;
        var tar = e.target || e.srcElement;
        $("*").removeClass("docTypeSel");
        $(tar).addClass("docTypeSel");
        pageIndex = 1;
        SearchByClass("hideSubClo");
        // $(".studyLeft li").removeClass("perListSel");
        // $(".studyLeft li:eq(0)").addClass("perListSel");
    });
}

function HideSubCol() {
    if ($(".docTypeSel").index() == 11) {
        $(".rightTab>.rightSub").css("visibility", "visible");
        $(".tabList>li>.tabListSub").css("visibility", "visible");
    } else if ($(".docTypeSel").index() == 0) {
        $(".rightTab>.rightSub").css("visibility", "visible");
        $(".tabList>li>.tabListSub").css("visibility", "visible");
    } else {
        $(".rightTab>.rightSub").css("visibility", "hidden");
        $(".tabList>li>.tabListSub").css("visibility", "hidden");
    }
}

function BindClassEvent() {
    //个人及班级文件
    $(".studyLeft").find("li").on("click", function (e) {
        var e = e || window.event;
        var tar = e.target || e.srcElement;
        $("*").removeClass("perListSel");
        $("*").removeClass("parent_id");
        if ($(tar).hasClass("before_div")){
            $(tar).next().addClass("perListSel")
        }
        else {
            $(tar).addClass("perListSel");
            $(tar).parent().addClass('parent_id');
        }
        if($(tar).parent().hasClass('classList_li')){
            $("#sendTime").show();
            $("#loadTime").hide();
        }
        else {
            $("#sendTime").hide();
            $("#loadTime").show();
        }
        $(".rightTopNav li").removeClass("docTypeSel");
        $(".rightTopNav li:first-child").addClass("docTypeSel");
        if ($(tar).html() == "我的文件") {
            dataScope = "1";
            pageIndex = 1;
            SearchByClass("unBindSub");
            //resizeWindow();
        } else if ($(tar).html() == "下载管理") {
            $(".studyRight").addClass("none");
            $(".studyDownload").removeClass("none");
            GetDownloadData();
            //resizeWindow();
        } else {
            dataScope = "2";
            pageIndex = 1;
            SearchByClass("unBindSub");
            //resizeWindow();
        }
    });
}

//填充班级列表
function BindClassList(classList) {
    var tmp = Handlebars.compile($("#classListTemp").html());
    $(".classList").html(tmp(classList));
}
//填充学科列表
function BindSubjectList(subjectList) {
    var tmp = Handlebars.compile($("#subjectListTemp").html());
    $(".rightTopNav").html(tmp(subjectList));
}
var subjects = [];
var fileList = [];
var pageCount = 1;
//填充数据
function BindLearningBagListByClass(learningBagList, callback) {
    learningBagList = JSON.parse(learningBagList);
    var dataList = learningBagList.dataList;
    subjects = learningBagList.subjectList;
    pageCount = learningBagList.pageData._APP_P_COUNT;
    BindDataList(dataList);
    switch (callback) {
        case "unBindSub":
            UnBindSubject(subjects);
            break;
        case "hideSubClo":
            HideSubCol();
            break;
        default:
            break;
    }
}

function SetFileList(filelist) {
    fileList = JSON.parse(filelist);
}

function BindDataList(dataList) {
    if (dataList && dataList.length > 0) {
        if (pageIndex == 1)
            $(".tabList").html('');
        var tmp = Handlebars.compile($("#dataListTemp").html());
        $(".tabList").append(tmp(dataList));
		 init();
        $(".no_pic").hide();
        $(".tab").show();
    } else {
        //没有数据
        $(".tab").hide();
        $(".no_pic").show();

    }
    if (dataScope == "1") {
        $(".tabListOper>span").removeClass("none");
        $(".tabListOper>.iconLoad").addClass("none");
        $(".tabListOper>.iconDele").show();
        $(".studyDownload").addClass("none");
        $(".studyRight").removeClass("none");
    }
    if (dataScope == "2") {
        $(".tabListOper>span").removeClass("none");
        $(".tabListOper>.iconDele").addClass("none");
        $(".tabListOper>.iconLoad").show();
        $(".studyDownload").addClass("none");
        $(".studyRight").removeClass("none");
        $(".rightTab>.rightSub").css("visibility", "visible");
        $(".tabList>li>.tabListSub").css("visibility", "visible");
    }
}

function UnBindSubject(subjects) {
    var liList = $(".rightTopNav").find("li");
    for (var j = 0; j < liList.length; j++) {
        var subLi = $(liList[j]);
        var currentSub = subLi.attr('sid').split(',');
        var isHas = false;
        for (var index = 0; index < subjects.length; index++) {
            var subject = subjects[index];
            if (currentSub.indexOf(subject.SUBJECT_ID.toString()) != -1 || currentSub[0] == "") {
                isHas = true;
                break;
            }
        }
        if (isHas) {
            subLi.removeClass("disable").addClass("enable");
            subLi.on("click", function (e) {
                var e = e || window.event;
                var tar = e.target || e.srcElement;
                $("*").removeClass("docTypeSel");
                $(tar).addClass("docTypeSel");
                pageIndex = 1;
                SearchByClass("hideSubClo");
            });
            console.log("包含" + subLi.text());
        } else {
            subLi.unbind("click");
            subLi.removeClass("enable").addClass("disable");
            console.log("不包含" + subLi.text());
        }
    }
}
function BindDownloadData(downloadData) {
    console.log(downloadData);
    downloadData = JSON.parse(downloadData);
    if (downloadData) {
        if (downloadData.downloadList && downloadData.downloadList.length > 0) {
            $(".downLoading").removeClass("none");
            var downloading = Handlebars.compile($("#downloadTemp").html());
            $(".loading").html(downloading(downloadData.downloadList));
            $(".loadingNumber").text(downloadData.downloadList.length);
        } else {
            $(".downLoading").addClass("none");
        }
        var loaded = Handlebars.compile($("#loadedTemp").html());
        $(".loaded").html(loaded(downloadData.completedList));
        $(".loadNumber").text(downloadData.completedList.length);
    }
    $(".iconStart").hover(function(){
        $(this).removeClass("iconStart").addClass('iconStartSel');
    },function(){
        $(this).removeClass("iconStartSel").addClass('iconStart');
    });
    $(".iconStop").hover(function(){
        $(this).removeClass("iconStop").addClass('iconStopSel');
    },function(){
        $(this).removeClass("iconStopSel").addClass('iconStop');
    });
    $(".iconOpen").hover(function(){
        $(this).removeClass("iconOpen").addClass('iconOpenSel');
    },function(){
        $(this).removeClass("iconOpenSel").addClass('iconOpen');
    });
    $(".iconRestart").hover(function () {
        $(this).removeClass("iconRestart").addClass('iconRestartSel');
    },function(){
        $(this).removeClass("iconRestartSel").addClass('iconRestart');
    });
}

function proHandle(proData) {
    proData = JSON.parse(proData);
    //console.log(proData.transferID + "- 已传输:" + (proData.transfered) + "-速度:" + (proData.perSecond));
    var transferLi = $("#" + proData.transferID);
    transferLi.find(".loadSpeed").eq(0).text(proData.perSecond);
    transferLi.find(".loadNetRight>.loadPro").eq(0).text(proData.transfered);
    var loadingPro = transferLi.find(".loadingPro").eq(0);
    loadingPro.children().width(loadingPro.width() * proData.rate);
}

//设置下载状态
function SetState(stateJson) {
    stateJson = JSON.parse(stateJson);
    $("#" + stateJson.tid).find(".loadState").text(stateJson.state);
}

function setLoadGrey(fid) {
    if (dataScope == "1") {
        SearchByClass("unBindSub");
    } else {
        $("#" + fid).find(".iconLoad").attr("class", "iconLoadgrey");
    }
}

function showMsg(msg) {
    console.log(msg);//此处可能需要添加一个弹出提示框
}
//****************************调用客户端**************************//
function SearchByClass(callBack) {
    $(".isDelete").hide();
    ucbook.invokeCsFunction("GetLearningBagListByClassID",
        $(".parent_id").attr('cid'), pageIndex.toString(), $('.docTypeSel').attr('sid'), dataScope, callBack);
}
function openFile(hwid, fileUrl, flag) {
    ucbook.invokeCsFunction("OpenFile", hwid, fileUrl, flag);
}

function openHomework(hwid,cid) {
    ucbook.invokeCsFunction("OpenHomework", hwid, $(".parent_id").attr('cid'));
}
/**
 * 下载相关
 */
function GetDownloadData() {
    ucbook.invokeCsFunction("GetDownloadData");
    $(".iconStart").hover(function(){
        $(this).removeClass("iconStart").addClass('iconStartSel');
    },function(){
        $(this).removeClass("iconStartSel").addClass('iconStart');
    });
    $(".iconOpen").hover(function(){
        $(this).removeClass("iconOpen").addClass('iconOpenSel');
    },function(){
        $(this).removeClass("iconOpenSel").addClass('iconOpen');
    });
    $(".iconRestart").hover(function () {
        $(this).removeClass("iconRestart").addClass('iconRestartSel');
    },function(){
        $(this).removeClass("iconRestartSel").addClass('iconRestart');
    });
}

function ResumeTask(e, tid) {
    e = $(e);
    e.parents().find(".loadState").text("正在恢复下载");
    e.siblings(".iconStart").removeClass("none");
    e.addClass("none");
    ucbook.invokeCsFunction("ResumeTask", tid);
}

function PauseTask(e, tid) {
    e = $(e);
    e.parents().find(".loadState").text("正在停止");
    e.siblings(".iconStop").removeClass("none");
    e.addClass("none");
    ucbook.invokeCsFunction("PauseTask", tid);
}


function CancelTask(e, tid) {
    e = $(e);
    e.parents().find(".loadState").text("正在取消");
    ucbook.invokeCsFunction("CancelTask", tid);
}
function deleteMyFile(fid, hwid, fileUrl) {
    $(".isDelete").show();
    $(".sureDelSel").unbind('click').click(function(){
    ucbook.invokeCsFunction("DeleteMyFile", fid, hwid, fileUrl);
    SearchByClass("unBindSub");
    });
}

function DelComFile(fileId) {
    ucbook.invokeCsFunction("DelComFile", fileId);
}

function DownloadFile(e, file_url, rel_homework_id, file_id, title, size, url_flag,source_file_id) {
    e = $(e);
    if (e.attr("class") != "iconLoadgrey") {
        ucbook.invokeCsFunction('StartTask', file_url, rel_homework_id, file_id, title, size, dataScope, url_flag,source_file_id);
        var downloadTip = e.find(".downloadTip");
        if (dataScope == 1) {
            downloadTip.text("文件正在下载，请稍候");
        } else {
            downloadTip.text("文件正在下载，请到我的文件中查看");
        }
        e.find(".downloadTip").show(300).delay(2000).hide(300);
    }
}

$(".classList_li").mouseover(function () {
    var str_num=$(this).text().length;
    alert(str_num);
    if(str_num>8){
        $(this).attr("title",$(this).text());
    }
});














