$(function () {
    document.oncontextmenu = function () {
        return false;
    };
    personAnalysis = {
        studentList: [],
        submitStudentList: [],
        unsubmitStudentList: [],
        answerResultList: []
    };
    timeAnalysis = {
        totalTime: null,
        averageTime: null,
        minTime: null,
        maxTime: null
    };
    rightAnswer = null;
    classInfo = undefined;
    studentAnswerSheets = new Array(); //学生答案列表
    checkedAnswerSheets = new Array(); //提交答案学生列表
    picTransition = {}; //图片操作记录
    studentAdmitIds = new Array();
    endAdmit = false; //停止提交
    initEvents();
    getClassMessage();
    realWidth = undefined;
    realHeight = undefined;
    mouseLastX = 0;
    mouseLastY = 0;
    mouseStartX = 0;
    mouseStartY = 0;
    //推送接收器
    var events = new RobustEventSource('/messages/admin');
    events.onmessage = function (data) {
        /*var msg = JSON.parse(data);*/
        var msg = JSON.parse(data.data);
        switch (msg.type) {
            case 'QuizState':
                updateQuizState(msg);
                break;
            case 'Quiz':
                if (msg.on) {
                    testMsg = msg;
                    if (msg.expired) {
                        SendMsg('结束作答');
                        $('#endAnswer').hide();
                        $('#analysisAnswer').show();
                        $("#timer").hide();
                        $(".timearea").css({
                            "visibility": "hidden"
                        });
                        if (timer) {
                            clearInterval(timer);
                        }
                        initEndAnswer();
                        initStatisticsView();
                    } else {
                        timeAnalysis.totalTime = testMsg.lifeSpan < 0 ? null : testMsg.lifeSpan;
                        templimittime = testMsg.lifeSpan / 1000;
                        setLimitTime();
                    }
                }
                break;
            case 'LessonRecord': 
                break;
        }
    }
})

function initEvents() {
    bindObjectAnswerItem();
    bindObjectAnswerConfirm();
    bindSubjectAnswerDetailAndTime();
    bindObjectAnswerDetailAndTime();
    bindEndAnswer();
    bindAnalysisAnswer();
}

function getClassMessage() {
    fetch("/classInfo").then(function (res) {
        if (!res.ok) throw '加载 /classInfo 失败';
        return res.json();
    }).then(function (data) {
        classInfo = data;
        initStudentList();
        initStudentUI();
    }).catch(function (err) {
        console.error(err);
    });
}

function initStudentUI() {
    $(".allNumber").text("0/" + classInfo.students.length + "人");
    $(".allStudentBox").empty();
    var studentString = "";
    for (var i = 0; i < classInfo.students.length; i++) {
        studentString += '<li data-id="' + classInfo.students[i].uid + '" class="unAdmitBg">' + classInfo.students[i].uname + '</li>';
    }
    $(".allStudentBox").append(studentString);
}

function updateQuizState(data) {
    var i = 0;
    for (var answerSheet in data.answerSheets) {
        if (!studentAdmitIds.contains(answerSheet)) {
            studentAdmitIds.push(answerSheet);
            studentAnswerSheets[answerSheet] = data.answerSheets[answerSheet];
        }
    }
    // 已经提交的学生信息
    for (var p in data.answerSheetMetadata) {
        for (var i = 0; i < classInfo.students.length; i++) {
            if (p === classInfo.students[i].uid) {
                var substudentinfo = {};
                for (var pp in classInfo.students[i]) {
                    substudentinfo[pp] = classInfo.students[i][pp];
                }
                substudentinfo['timeUsed'] = data.answerSheetMetadata[p]['timeUsed'];
                substudentinfo['answerSheet'] = data.answerSheets[answerSheet];
                personAnalysis.submitStudentList.push(substudentinfo);
            }
        }
    }

    if (classInfo) {
        if (studentAdmitIds.length == classInfo.students.length) { //全部提交后 跳入展示页面
            fetch("/classroomControl", {
                method: "POST",
                body: JSON.stringify({
                    type: 'Quiz',
                    on: true,
                    id: '' + testMsg.id,
                    lifeSpan: testMsg.lifeSpan,
                    questions: testMsg.questions,
                    expired: true
                }),
            }).then(function (res) {
                if (res.ok) {
                    //SendMsg('结束作答');
                    SendMsg(JSON.stringify(uploadDataOfTiWen()));
                    fetch("/classroomControl", {
                        method: "POST",
                        body: JSON.stringify({
                            type: 'LessonRecord',
                            on: true,
                            lifeSpan: testMsg.lifeSpan,
                            data: uploadDataOfTiWen().data,
                            expired: true
                        })
                    })
                    console.log("终止答题成功");
                }
            }, function (err) {
                console.log("终止答题出错");
            });
        }
        updateProgressBar(studentAdmitIds.length, classInfo.students.length);
    }

    $(".allStudentBox li").each(function () {
        if (studentAdmitIds.contains("" + $(this).data("id"))) {
            $(this).removeClass("unAdmitBg").addClass("admitBg");
        }
    });
}

function getSubmitAnswerOf(student) {
    var answer = '';
    if(testMsg) {
        switch(testMsg.questions[0].type) {
            case 'single_selection':
            case 'multiple_selection':
                answer = student.answerSheet[0].map(function(answer) {
                    return String.fromCharCode(65 + parseFloat(answer));
                }).join('');
                break;
            case 'boolean_selection':
                answer = student.answerSheet[0][0] ? 1 : 0;
                break;
            case 'subjective':
                answer = student.answerSheet[0].images.join();
                break;
        }
    }
    return answer;
}

function uploadDataOfTiWen() {
    var correctAnswer = '';
    var totalTimeUsed = 0;
    if(testMsg) {
        if(testMsg.questions[0].type == "boolean_selection") {
            correctAnswer = !!rightAnswer ? (rightAnswer == 'A' ? 1 : 0) : '';
        } else {
            correctAnswer = rightAnswer && rightAnswer.replace(/true/g, 1).replace(/false/g, 0);
            if(testMsg.questions[0].type == "multiple_selection") {
                correctAnswer = correctAnswer.replace(/\s/g, '')
            }
        }
    } else {
        return {"data": {
            "correctAnswer": correctAnswer,
            "interactionRecords": personAnalysis.submitStudentList.map(function(student){
                totalTimeUsed += student.timeUsed;
                return {
                        "answer": getSubmitAnswerOf(student),
                        "answerTime": student.timeUsed / 1000,
                        "submitStatus": 1,
                        "userId": student.uid,
                        "userName": student.uname,
                    };
            }).concat(
                personAnalysis.unsubmitStudentList.map(function(student) {
                    return {
                        "answer": "",
                        "answerTime": "",
                        "submitStatus": 0,
                        "userId": student.uid,
                        "userName": student.uname,
                    }
                })),
            "maxSubmittime": personAnalysis.submitStudentList.length && personAnalysis.submitStudentList.sort(sortCompareAttribute('timeUsed')).reverse()[0]['timeUsed'] / 1000,
            "minSubmittime": personAnalysis.submitStudentList.length && personAnalysis.submitStudentList.sort(sortCompareAttribute('timeUsed'))[0]['timeUsed'] / 1000,
            "avgSubmittime": totalTimeUsed / 1000 / personAnalysis.submitStudentList.length || 0
        }, "msgType": "lessonRecord"}
    }
    return {
        "data": {
            "choiceCount": testMsg.questions[0] && testMsg.questions[0].optionsCount || '',
            "correctAnswer": correctAnswer,
            "interactionRecords": personAnalysis.submitStudentList.map(function(student){
                totalTimeUsed += student.timeUsed;
                return {
                        "answer": getSubmitAnswerOf(student),
                        "answerTime": student.timeUsed / 1000,
                        "submitStatus": 1,
                        "userId": student.uid,
                        "userName": student.uname,
                    };
            }).concat(
                personAnalysis.unsubmitStudentList.map(function(student){
                    return {
                        "answer": "",
                        "answerTime": "",
                        "submitStatus": 0,
                        "userId": student.uid,
                        "userName": student.uname,
                    }
                })),
            "limitTime": testMsg.lifeSpan,
            "maxSubmittime": personAnalysis.submitStudentList.length && personAnalysis.submitStudentList.sort(sortCompareAttribute('timeUsed')).reverse()[0]['timeUsed'] / 1000,
            "minSubmittime": personAnalysis.submitStudentList.length && personAnalysis.submitStudentList.sort(sortCompareAttribute('timeUsed'))[0]['timeUsed'] / 1000,
            "avgSubmittime": totalTimeUsed / 1000 / personAnalysis.submitStudentList.length || 0,
            "sCreateTime": new Date(testMsg.startTime).toLocaleString('cn', {hour12: false}).replace(/\//g, '-'),
            "topicType": testMsg.questions[0] && 
                (testMsg.questions[0].type == "single_selection" ? 1 :
                testMsg.questions[0].type == "multiple_selection" ? 2 :
                testMsg.questions[0].type == "boolean_selection" ? 3 :
                testMsg.questions[0].type == "subjective" ? 4 : '题型错误'),
        },
        "msgType": "lessonRecord"
    }
}

function updateProgressBar(admitedCount, allCount) {
    if (!endAdmit) {
        $("#submitLarge .studentNumberBox").each(function () {
            $(this).find(".admitNumberBox").width($(this).width() * admitedCount / allCount);
        });
        $(".allNumber").text("" + admitedCount + "/" + allCount + "人");

    }
}

function setLimitTime() {
    if (testMsg.lifeSpan == -1) {
        $("#timer").hide();
        $(".timearea").css({
            "visibility": "hidden"
        });
    } else {
        var minute = parseInt(templimittime / 60);
        var second = parseInt(templimittime % 60);
        minute = minute < 10 ? "0" + minute : minute;
        second = second < 10 ? "0" + second : second;
        $("#submitLarge .timearea").text(minute + ":" + second);
    }
    timer = setInterval(settime, 1000);
}

function settime() {
    if (templimittime == 0) {
        clearInterval(timer);
    }
    templimittime--;
    var minute = parseInt(templimittime / 60);
    var second = parseInt(templimittime % 60);
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    $("#submitLarge .timearea").text(minute + ":" + second);
}

function changeShowHide(item) {
    $("#submitLarge").hide();
    $("#submitTiny").show();
}

function initEndAnswer() {
    getUnSubmitStudent();
    handleEndData()
}

function initStatisticsView() {
    hideAnswerDetailArea(); // changed version 2
    $(".allStudentBox").hide();
    $(".ansFooter").hide();
    $("#timer").hide();
    if (testMsg) {
        switch (testMsg.questions[0].type) {
            case "single_selection":
            case "multiple_selection":
            case "boolean_selection":
                initObjectiveView();
                break;
            case "subjective":
                initSubjectView();
                break;
            default:
                {
                    console.log("试题类型错误");
                }
        }
    }
}

function hideAnswerDetailArea() {
    $('.answerDetailsArea').hide();
}
function hideObjectiveDetail() {
    $('.objective-content').hide();
}
function hideSubjectiveDetail() {
    $('.subjective-content').hide();
}

function showObjectiveContent() {
    $('.objective-content').show();
}
function showSubjectiveContent() {
    $('.subjective-content').show();
    $('.ansFooter').show();
}

function initObjectiveView() {
    showObjectiveContent();
    hideSubjectiveDetail();
    $(".objective-area").show();
    $('.objective-timecount').hide();
    answers = new Object();
    switch (testMsg.questions[0].type) {
        case "single_selection":
        case "multiple_selection":
            var anwserType = new Array("A", "B", "C", "D", "E", "F");
            for (var i = 0; i < testMsg.questions[0].optionsCount; i++) {
                answers[anwserType[i]] = new Array();
            }
            if (studentAnswerSheets.length != 0) {
                for (var student in studentAnswerSheets) {
                    if (student != "contains") {
                        for (var i = 0; i < studentAnswerSheets[student][0].length; i++) {
                            if (studentAnswerSheets[student][0][i] != undefined) {
                                answers[anwserType[studentAnswerSheets[student][0][i]]].push(student);
                            }
                        }
                    }
                }
            }
            drawHistograms(testMsg.questions[0].optionsCount);
            drawCountAnswerCollection();
            break;
        case "boolean_selection":
            answers["true"] = new Array();
            answers["false"] = new Array();
            if (studentAnswerSheets.length != 0) {
                for (var student in studentAnswerSheets) {
                    if (student != "contains") {
                        answers[studentAnswerSheets[student][0]].push(student);
                    }
                }
            }
            drawHistogramsbool();
            drawCountAnswerCollectionBool();
            break;
    }
    $('.objective-content .count-info').empty().append('<span>提交人数：</span><span class="count-info-number">' + $('.ansNumberBox .allNumber').text().slice(0, -1) + '</span>');
    createTimeCountObjectSubmitPerson();
    //$('.objective-content .count-info-number').empty().text($('.ansNumberBox .allNumber').text().slice(0, -1));
}

function drawHistograms(count) {
    $(".objective-area .area-bg").width(count * 150 + 220);
    $(".objective-area .area-bg .histogram-area").width(count * 150).empty();
    var innerHtml = "";
    var i = 0;
    var anwserType = new Array("A", "B", "C", "D", "E", "F");
    //var hasShow = false;
    for (var item in answers) {
        var height = getHistogramsHeight(answers[item].length);
        innerHtml += '<div class="histogram-area-item" data-type="' + item + '">';
        innerHtml += '<span class="histogram-area-pcount">' + answers[item].length + '人</span>'
        innerHtml += '<span class="histogram-item-countY" style="height:' + height + 'px;"></span>'
        innerHtml += '<span class="histogram-area-answeritem">' + anwserType[i] + '</span>';
        innerHtml += '</div>';
        //innerHtml += '<li class="histogram-item histogram' + (i + 1) + '" data-type="' + item + '">';
        //innerHtml += '<span class="answer-type">' + anwserType[i] + '</span>';
        //var height = getHistogramsHeight(answers[item].length);
        //innerHtml += '<div class="answer-histogram" style="height:' + height + 'px"></div>';
        //var bottom = 33 + height;
        //innerHtml += '<span class="answer-count" style="bottom:' + bottom + 'px;">' + answers[item].length + '人</span></li>';
        //if (!hasShow && answers[item].length != 0) {
        //    showNagtiveStudentMessage(item);
        //    hasShow = true;
        //}
        i++;
    }
    innerHtml += '<div class="histogram-area-item" data-type="none">';
    innerHtml += '<span class="histogram-area-pcount">' + personAnalysis.unsubmitStudentList.length + '人</span>'
    innerHtml += '<span class="histogram-item-countGray" style="height:' + getHistogramsHeight(personAnalysis.unsubmitStudentList.length) + 'px;"></span>'
    innerHtml += '<span class="histogram-area-answerun">未提交</span>';
    innerHtml += '</div>';
    //innerHtml += "<div class='dashed'></div></ul>"
    $(".histogram-area").append(innerHtml);
    //$(".dashed").width(55 + (count - 1) * 90);
    //initHistogramClick();

    initShowAnswerArea(count);
}

function drawHistogramsbool() {
    $(".objective-area .area-bg").width(2 * 150 + 220);
    $(".objective-area .area-bg .histogram-area").width(2 * 150).empty();
    var innerHtml = "";
    for (var item in answers) {
        var height = getHistogramsHeight(answers[item].length);
        innerHtml += '<div class="histogram-area-item" data-type="' + item + '">';
        innerHtml += '<span class="histogram-area-pcount">' + answers[item].length + '人</span>'
        innerHtml += '<span class="histogram-item-countY" style="height:' + height + 'px;"></span>'
        innerHtml += '<span class="histogram-area-answeritem">' + (item == 'true' ? rtagsvg('no', 1) : ftagsvg('no', 1)) + '</span>';
        innerHtml += '</div>';
    }
    innerHtml += '<div class="histogram-area-item" data-type="none">';
    innerHtml += '<span class="histogram-area-pcount">' + personAnalysis.unsubmitStudentList.length + '人</span>'
    innerHtml += '<span class="histogram-item-countGray" style="height:' + getHistogramsHeight(personAnalysis.unsubmitStudentList.length) + 'px;"></span>'
    innerHtml += '<span class="histogram-area-answerun">未提交</span>';
    innerHtml += '</div>';
    $(".histogram-area").append(innerHtml);
    initinitShowAnswerAreaBool()
}

function getHistogramsHeight(currentCount) {
    return currentCount / classInfo.students.length * 208;
}

function initShowAnswerArea(count) {
    $('#objectAnswerItemList').empty();
    var mulclass = '';
    if (testMsg.questions[0].type == 'multiple_selection') {
        mulclass = ' object-answer-optionmultiple '
    }
    for (var i = 1; i <= count; i++) {
        var codev = String.fromCharCode((i + "").charCodeAt(0) + 16);
        $('#objectAnswerItemList').append('<span class="object-answer-option' + mulclass + '">' + codev + '</span>');
    }
    bindObjectAnswerItem();
}

function initinitShowAnswerAreaBool() {
    var innerHtml = '<span class="object-answer-option">' + rtagsvg('circle') + '</span><span class="object-answer-option">' + ftagsvg('circle') + '</span>';
    $('#objectAnswerItemList').empty().append(innerHtml);
    bindObjectAnswerItem();
}

function ftagsvg(type, scale) {
    var f = '';
    if (type == 'circle') {
        f += '<svg xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;">'
        f += '<circle cx="50%" cy="50%" r="50%" style="fill:#e5e5e5;"></circle>'
        f += '<path style="fill:#666" d="M19.42,17.969l5.324-5.325c0.382-0.382,0.382-1.007,0-1.389c-0.382-0.382-1.007-0.382-1.389,0l-5.324,5.325'
        f += 'l-5.324-5.325c-0.382-0.382-1.007-0.382-1.389,0c-0.382,0.382-0.382,1.007,0,1.389l5.325,5.325l-5.325,5.324'
        f += 'c-0.382,0.382-0.382,1.007,0,1.389c0.382,0.382,1.007,0.382,1.389,0l5.324-5.324l5.324,5.324c0.382,0.382,1.007,0.382,1.389,0'
        f += 's0.382-1.007,0-1.389L19.42,17.969z" />'
        f += '</svg>'
    } else {
        f += '<svg xmlns="http://www.w3.org/2000/svg" style="width:34px;height:34px;transform:scale(' + scale + ',' + scale + ')">'
        f += '<path style="fill:' + (scale != 1 ? '#f89009' : '#666') + '" d="M19.183,17l8.367-8.367c0.6-0.6,0.6-1.582,0-2.183c-0.6-0.6-1.582-0.6-2.183,0L17,14.817L8.633,6.45'
        f += 'c-0.6-0.6-1.582-0.6-2.183,0s-0.6,1.582,0,2.183L14.817,17L6.45,25.367c-0.6,0.6-0.6,1.582,0,2.183c0.6,0.6,1.582,0.6,2.183,0'
        f += 'L17,19.183l8.367,8.367c0.6,0.6,1.582,0.6,2.183,0c0.6-0.6,0.6-1.582,0-2.183L19.183,17z" />'
        f += '</svg>';
    }
    return f;
}

function rtagsvg(type, scale) {
    var f = ''
    if (type == 'circle') {
        f += '<svg xmlns="http://www.w3.org/2000/svg" style="width:36px;height:36px;">'
        f += '<circle cx="50%" cy="50%" r="50%" style="fill:#e5e5e5;"></circle>'
        f += '<path style="fill:#666" d="M27.907,11.343c-0.458-0.458-1.207-0.458-1.664,0L15.426,22.16l-5.668-5.668'
        f += 'c-0.458-0.458-1.207-0.458-1.664,0c-0.458,0.458-0.458,1.207,0,1.664l6.501,6.501c0.458,0.458,1.207,0.458,1.664,0l11.649-11.649'
        f += 'C28.365,12.55,28.365,11.801,27.907,11.343z" />'
        f += '</svg>'
    } else {
        f += '<svg xmlns="http://www.w3.org/2000/svg" style="width:34px;height:34px;transform:scale(' + scale + ',' + scale + ')">'
        f += '<path style="fill:' + (scale != 1 ? '#f89009' : '#666') + '" d="M32.568,6.539c-0.719-0.719-1.896-0.719-2.615,0L12.955,23.538L4.047,14.63'
        f += 'c-0.719-0.719-1.896-0.719-2.615,0c-0.719,0.719-0.719,1.896,0,2.615l10.215,10.215c0.719,0.719,1.896,0.719,2.615,0L32.568,9.155'
        f += 'C33.287,8.435,33.287,7.259,32.568,6.539z"/>'
        f += '</svg>'
    }
    return f;
}

function initHistogramClick() {
    $(".histogram-item").click(function () {
        if ($(this).find('.answer-histogram-green').length > 0) {
            $(".content .value").addClass('value-green');
        } else {
            $(".content .value").removeClass('value-green');
        }
        var type = $(this).data("type");
        showNagtiveStudentMessage(type);
    })
}

function showNagtiveStudentMessage(type) {
    if (type == "true" || type == true) {
        $(".content .value").text('√');
    } else if (type == "false" || type == false) {
        $(".content .value").text('×');
    } else {
        $(".content .value").text(type);
    }
    $(".objectiveStudent-area").empty();
    var innerHtml = "";
    for (var i = 0; i < answers[type].length; i++) {
        for (var j = 0; j < classInfo.students.length; j++) {
            if (classInfo.students[j].uid == answers[type][i]) {
                //innerHtml += '<li class="item"><img src="http://zuoye.myuclass.com/getAvatar.anys?userId=' + classInfo.students[j].uid + '">';
                //innerHtml += '<span>' + classInfo.students[j].uname + '</span></li>';
                innerHtml += '<li class="item"><span>' + classInfo.students[j].uname + '</span></li>';
                break;
            }
        }
    }
    $(".objectiveStudent-area").append(innerHtml);
    $(".content-students").width($(".content").width() - $(".select-value").width());
    //if ($('.objectiveStudent-area').height() == 0) {
    //    $(".select-value").height(87);
    //} else {
    //    $(".select-value").height($('.objectiveStudent-area').height() - 20);
    //}
}

function initSubjectView() {
    showSubjectiveContent();
    hideObjectiveDetail();
    $('.subjective-timecount').hide();
    $(".subjecttive-area").show();
    $("#subjectiveStudent").empty();
    var innerHtml = "";
    for (var item in studentAnswerSheets) {
        for (var j = 0; j < classInfo.students.length; j++) {
            if (classInfo.students[j].uid == (parseInt(item)).toString() && studentAnswerSheets[item][0].images) {
                innerHtml += '<li class="item" data-id="' + classInfo.students[j].uid + '"><img src="' + studentAnswerSheets[item][0].images[0] + '">';
                innerHtml += '<div class="choose"><span class="name">' + classInfo.students[j].uname + '</span><div class="check-area"></div></div></li>';
                continue;
            }
        }
    }
    $("#subjectiveStudent").append(innerHtml);
    initChooseStudentClick();
    //$(".ansFooter").empty().append('<span class="ansFooterButton ansFooterButton1" onclick="jumpToAnalysis()">分析讲解</span>').show();
    $('.subjective-content .count-info').empty().append('<span>提交人数：</span><span class="count-info-number">' + $('.ansNumberBox .allNumber').text().slice(0, -1) + '</span>');
    createTimeCountSubjectSubmitPerson();
}

function initChooseStudentClick() {
    $("#subjectiveStudent .item").click(function () {
        if ($(this).hasClass("checked")) {
            $(this).removeClass("checked");
            $(this).find(".check-area").css({
                "background": "none"
            });
        } else {
            $(this).addClass("checked");
            $(this).find(".check-area").css({
                "background": "url(img/tick.png)"
            });
        }
    })
}

function jumpToAnalysis() {
    var checkCount = $("#subjectiveStudent .checked").size();
    if (checkCount == 0) {
        alert("您还未选择任何学生");
    } else {
        checkedAnswerSheets.length = 0;
        $("#subjectiveStudent li").each(function () {
            var id = $(this).data("id");
            for (var item in studentAnswerSheets) {
                if (id == (parseInt(item)).toString()) {
                    if ($(this).hasClass("checked")) {
                        checkedAnswerSheets[item] = studentAnswerSheets[item];
                        checkCount++;
                    }
                    continue;
                }
            }
        });
        $("#submitLarge").hide();
        initAnaysisView();
        decorationAnaysisView();
    }
}

function initAnaysisView() {
    $(".left-nav-students").empty();
    var innerHtml = "";
    for (var item in checkedAnswerSheets) {
        if (checkedAnswerSheets[item]) {
            for (var j = 0; j < classInfo.students.length; j++) {
                if (classInfo.students[j].uid == (parseInt(item)).toString()) {
                    innerHtml += '<li class="left-student" data-id="' + classInfo.students[j].uid + '" data-name="' + classInfo.students[j].uname + '"><img src="' + checkedAnswerSheets[item][0].images[0] + '">';
                    innerHtml += '<div><span>' + classInfo.students[j].uname + '</span></li>';
                }
            }
        }
    }
    $(".left-nav-students").append(innerHtml);
    $(".left-nav-students .left-student").eq(0).addClass("checked");
    $(".choose-student").text("当前学生：" + $(".left-nav-students .left-student").eq(0).data("name"));
    showStudentAnswers($(".left-nav-students .left-student").eq(0).data("id"));
}

function decorationAnaysisView() {
    $(".left-nav").css({
        "display": "inline-block"
    });
    $(".analysis-area").css({
        "display": "inline-block"
    });
    var studentAreaHeight = window.innerHeight - $(".quit-area").height() - 20;
    $(".left-nav").height(window.innerHeight);
    $(".left-nav .left-nav-students").height(studentAreaHeight);
    $(".analysis-area").width(window.innerWidth - 190).height(window.innerHeight);
    $(".center-nav").css({
        "top": (window.innerHeight - 160) / 2 + "px"
    });
    $(".icon-narrow").unbind().bind("click", imgNarrow);
    $(".icon-enlarge").unbind().bind("click", imgEnlarge);
    $(".icon-translate").unbind().bind("click", imgTranslate);
    initStudentChoose();
}

function initStudentChoose() {
    $(".left-nav-students li").click(function () {
        if ($(this).hasClass("checked")) {
            return;
        } else {
            $(".left-nav-students li").removeClass("checked");
            $(this).addClass("checked");
            $(".choose-student").text("当前学生：" + $(this).data("name"));
            if ($("#main-answer").attr("src")) {
                rememberLastTransition($("#main-answer").attr("src"));
            }
            showStudentAnswers($(this).data("id"));
        }
    })
}

function showStudentAnswers(id) {
    id = (parseInt(id)).toString();
    currentPic = 0;
    allPicCounts = checkedAnswerSheets[id][0].images.length;
    initPageNav(currentPic, allPicCounts, checkedAnswerSheets[id][0]);
}

function initPageNav(current, allPic, images) {
    answerImgReset();
    if (allPic == 1) {
        $(".center-nav").hide();
    } else {
        $(".center-nav").show();
    }
    $(".img-container").css({
        "overflow": "hidden"
    });
    $("<img>").attr("src", images.images[current]).load(function () {
        realWidth = this.width;
        realHeight = this.height;
        var realWH = realWidth / realHeight;
        var windowWH = (window.innerWidth - 190) / window.innerHeight;
        var margin;
        if (realWH > windowWH) {
            realWidth = window.innerWidth - 190;
            realHeight = (window.innerWidth - 190) / realWH;
            margin = "" + (window.innerHeight - realHeight) / 2 + "px 0";
        } else {
            realHeight = window.innerHeight;
            realWidth = window.innerHeight * realWH;
            margin = "0  " + (window.innerWidth - 190 - realWidth) / 2 + "px";
        }
        $("#main-answer").attr({
            "src": images.images[current]
        }).width(realWidth).height(realHeight).css({
            "margin": "" + margin
        });
        if (picTransition[images.images[current]]) {
            scale = picTransition[images.images[current]].scale;
            rotate = picTransition[images.images[current]].rotate;
            imgTransForm();
        }
    });
    if (current == 0) {
        $(".center-nav-item span:first-of-type").removeClass("icon-back-black").addClass("icon-back-white");
    } else {
        $(".center-nav-item span:first-of-type").removeClass("icon-back-white").addClass("icon-back-black");
    }
    if (current + 1 == allPic) {
        $(".center-nav-item span:last-of-type").removeClass("icon-next-black").addClass("icon-next-white");
    } else {
        $(".center-nav-item span:last-of-type").removeClass("icon-next-white").addClass("icon-next-black");
    }
    $(".icon-back-black").unbind().bind("click", function () {
        rememberLastTransition(images.images[current]);

        initPageNav(--current, allPic, images);
    });
    $(".icon-next-black").unbind().bind("click", function () {
        rememberLastTransition(images.images[current])
        initPageNav(++current, allPic, images);
    });
    $(".icon-back-white").unbind();
    $(".icon-next-white").unbind();
}

/**
 * 记录上次图片的操作
 * @param {Object} picUrl
 */
function rememberLastTransition(picUrl) {
    if (picTransition[picUrl] == undefined) {
        picTransition[picUrl] = {};
    }
    picTransition[picUrl].scale = scale || 1;
    picTransition[picUrl].rotate = rotate || 360;
}

/**    
 * 重置图片地址
 */
function answerImgReset() {
    scale = 1;
    rotate = 360;
    $("#main-answer").css({
        "transform": "none"
    });
}

/**
 * 图片缩小
 */
function imgNarrow() {
    if (scale == 0.125) {
        return;
    } else if (scale <= 0.5) {
        scale = scale * 0.5;
    } else {
        scale -= 0.5;
    }
    imgTransForm();
}

/**
 * 图片放大
 */
function imgEnlarge() {
    if (scale <= 0.5) {
        scale = scale * 2;
    } else {
        scale += 0.5;
    }
    imgTransForm();
}

/**
 * 图片旋转
 */
function imgTranslate() {
    rotate -= 90;
    imgTransForm();
}

function imgTransForm() {
    var scaleHeight = realHeight * scale;
    var scaleWidth = realWidth * scale;
    var marginTop;
    var marginLeft;
    if (scaleHeight < window.innerHeight) {
        marginTop = (window.innerHeight - scaleHeight) / 2;
        $(".img-container").css({
            "overflow-y": "hidden"
        });
    } else {
        marginTop = 0;
        $(".img-container").css({
            "overflow-y": "scroll"
        });
    }
    if (scaleWidth < window.innerWidth - 190) {
        marginLeft = (window.innerWidth - 190 - scaleWidth) / 2;
        $(".img-container").css({
            "overflow-x": "hidden"
        });
    } else {
        marginLeft = 0;
        $(".img-container").css({
            "overflow-x": "scroll"
        });
    }
    $("#main-answer").css({
        "transform": "rotate(" + rotate + "deg)"
    }).width(scaleWidth).height(scaleHeight).css({
        "margin": "" + marginTop + "px " + marginLeft + "px"
    });
}

function quitAnalysis() {
    $(".left-nav").hide();
    $(".analysis-area").hide();
    $("#submitLarge").show();
    $("#subjectiveStudent li").removeClass("checked").find(".check-area").css({
        "background": "none"
    });
}

function dragStart() {
    mouseStartX = mouseLastX;
    mouseStartY = mouseLastY;
}

function dragEnd() {
    setTimeout(function () {
        var moveX = mouseLastX - mouseStartX;
        var moveY = mouseLastY - mouseStartY;
        $(".img-container").scrollTop($(".img-container").scrollTop() - moveY);
        $(".img-container").scrollLeft($(".img-container").scrollLeft() - moveX);
    }, 20);
}

document.onmousemove = function (e) {
    mouseLastX = e.clientX;
    mouseLastY = e.clientY;
}