$(function () {
    document.oncontextmenu = function () {
        return false;
    };

    isUploadData = false;
    totalStudents = 0;
    questionType = null;
    answersGroupList = new Array();//数据结构：[{groupAnswer: "",studentListByGroup: []}]
    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();
    realWidth = undefined;
    realHeight = undefined;
    mouseLastX = 0;
    mouseLastY = 0;
    mouseStartX = 0;
    mouseStartY = 0;

    var msg = JSON.stringify({
        status: "ok",
        msg: "web页面加载完成"
    });
    SendMsg(msg);
    //getAnswersData({});
})

//msg:string类型
function SendMsg(msg) {
    if (window.ucbook) {
        ucbook.postWebPageMessage(msg);
    }
}

function initEvents() {
    bindObjectAnswerItem();//绑定正确答案选项事件
    bindObjectAnswerConfirm();//绑定正确答案确定按钮事件
    //bindSubjectAnswerDetailAndTime();//绑定主观题作答详情和作答时间
    bindObjectAnswerDetailAndTime(); //绑定客观题作答详情和作答时间
    //bindEndAnswer();
    //bindAnalysisAnswer();
}

function getAnswersData(jsonData) {
    //jsonData = '{"AnswersGroupList":[{"GroupAnswer":"A ","GroupStudentList":[{"QuestionType":"ASingle","StudentName":"李四五六","StudentNumber":"003","CardID":"1049488485","Answer":"A ","CostTime":"4425.0145","AnswerStatus":"1"}]},{"GroupAnswer":"未提交","GroupStudentList":[{"QuestionType":"ASingle","StudentName":"张三三","StudentNumber":"002","CardID":"10668456","Answer":"未提交","CostTime":"0","AnswerStatus":"0"},{"QuestionType":"ASingle","StudentName":"王五","StudentNumber":"004","CardID":"2139002983","Answer":"未提交","CostTime":"0","AnswerStatus":"0"},{"QuestionType":"ASingle","StudentName":"赵六七八九","StudentNumber":"005","CardID":"1633550027","Answer":"未提交","CostTime":"0","AnswerStatus":"0"}]}],"SumStudents":"4","SubmitStuCount":"1","UnSubmitStuCount":"3","QuestionType":"ASingle","AnswerResult":null,"Accuracy":null,"CaptureImagePath":"F%3a%5cUCBook%5cAnswerDevcieTeach%5cBuild%5cDebug%5cUser%5cClassroomRecord%5c164%5cAnswerPicture%5c111557557.png","BeginTime":"2018/1/12 11:15:57","EndTime":"2018/1/12 11:16:06"}';

    json = JSON.parse(jsonData);
    questionType = json.QuestionType;    //题型
    console.log(json);
    for (var i = 0; i < json.AnswersGroupList.length; i++) {  //所有按照答案分好组的学生
        answersGroupList.push({
            groupAnswer: json.AnswersGroupList[i].GroupAnswer.trim(),
            studentListByGroup: json.AnswersGroupList[i].GroupStudentList
        });
    }
    answersGroupList = answersGroupList.sort();

    // 已经提交和未提交的学生信息
    for (var j = 0; j < answersGroupList.length; j++) {
        for (var i = 0; i < answersGroupList[j].studentListByGroup.length; i++) {
            if (answersGroupList[j].studentListByGroup[i].AnswerStatus == "1") {
                personAnalysis.submitStudentList.push(answersGroupList[j].studentListByGroup[i]);
            }

            if (answersGroupList[j].studentListByGroup[i].AnswerStatus == "0") {
                personAnalysis.unsubmitStudentList.push(answersGroupList[j].studentListByGroup[i]);
            }
        }
        personAnalysis.answerResultList.push(answersGroupList[j].groupAnswer);
    }

    var length = answersGroupList.length;
    var minTime = parseFloat(answersGroupList[0].studentListByGroup[0].CostTime);
    for (var i = 0; i < length-1; i++) {
        if (answersGroupList[i].studentListByGroup[0].length > 0) {
                if (minTime > parseFloat(answersGroupList[i + 1].studentListByGroup[0].CostTime)) {
                    minTime = parseFloat(answersGroupList[i + 1].studentListByGroup[0].CostTime);
                }
        }
    }
    
    timeAnalysis.minTime = minTime;

    for (var i = 0; i < answersGroupList.length; i++) {  //已作答学生使用的总时间，单位：毫秒
        for (var j = 0; j < answersGroupList[i].studentListByGroup.length; j++) {
            timeAnalysis.totalTime = timeAnalysis.totalTime + parseFloat(answersGroupList[i].studentListByGroup[j].CostTime);

            if (timeAnalysis.minTime > parseFloat(answersGroupList[i].studentListByGroup[j].CostTime)) {
                timeAnalysis.minTime = parseFloat(answersGroupList[i].studentListByGroup[j].CostTime);
            }

            if (timeAnalysis.maxTime < parseFloat(answersGroupList[i].studentListByGroup[j].CostTime)) {
                timeAnalysis.maxTime = parseFloat(answersGroupList[i].studentListByGroup[j].CostTime)
            }
        }
    }

    timeAnalysis.averageTime = timeAnalysis.totalTime / parseFloat(personAnalysis.submitStudentList.length);
    totalStudents = json.SumStudents;

    initStatisticsView();
    $(".loading").hide();
    createTimeCountObjectInit();
}

//function initStudentUI() {
//    $(".allNumber").text("0/" + totalStudents + "人");
//    $(".allStudentBox").empty();
//    var studentString = "";
//    for (var i = 0; i < answersGroupList.length; i++) {
//        for (var j = 0; j < answersGroupList[i].studentListByGroup.length; j++) {
//            studentString += '<li data-id="' + answersGroupList[i].studentListByGroup[j].StudentNumber + '" class="unAdmitBg">' + answersGroupList[i].studentListByGroup[j].StudentName + '</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 j = 0; j < data.length; j++) {
//        for (var i = 0; i < data[j].studentListByGroup.length; i++) {
//            if (data[j].studentListByGroup[i].AnswerStatus == "1") {
//                personAnalysis.submitStudentList.push(data[j].studentListByGroup[i]);
//            }

//            if (answersGroupList[i].studentListByGroup[j].AnswerStatus == "0") {
//                personAnalysis.unsubmitStudentList.push(answersGroupList[i].studentListByGroup[j]);
//            }
//        }
//    }

//    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 uploadData(msg, windowName) {//msg:0正常调用，1：关闭窗体时调用，2:非正常关闭窗口时调用
    var jsonTemp = {};
    extend(jsonTemp, json);
    var correctAnswer = '';
    var totalTimeUsed = 0;
    if (questionType == "ATorF") {//判断
        correctAnswer = !!rightAnswer ? (rightAnswer == 'A' ? 1 : 0) : '';
        for (var i = 0; i < jsonTemp.AnswersGroupList.length; i++) {
            if (jsonTemp.AnswersGroupList[i].GroupAnswer != "未提交") {
                jsonTemp.AnswersGroupList[i].GroupAnswer = jsonTemp.AnswersGroupList[i].GroupAnswer.trim() === "√" ? "1" : "0";
                for (var j = 0; j < jsonTemp.AnswersGroupList[i].GroupStudentList.length; j++) {
                    jsonTemp.AnswersGroupList[i].GroupStudentList[j].Answer = jsonTemp.AnswersGroupList[i].GroupStudentList[j].Answer.trim() === "√" ? "1" : "0";
                }
            }
        }
    } else {
        correctAnswer = rightAnswer && rightAnswer.replace(/true/g, 1).replace(/false/g, 0);
        if (questionType == "AMultiple") {//单题多选
            if (correctAnswer != null) {
                correctAnswer = correctAnswer.replace(/\s/g, '')
            }
        }
        else {
            correctAnswer = rightAnswer;
        }
    }
    jsonTemp.AnswerResult = correctAnswer;
    jsonTemp.Accuracy = Math.round($('#objectiveStudent .content .correct-student .objectiveStudent-area').find('.item').length / totalStudents * 100) + "%";

    ucbook.invokeCsFunction("SaveAnswerData", JSON.stringify(jsonTemp));
    
    if (windowName != "" || windowName!='') {
        if (msg == 2) {
            ucbook.invokeCsFunction("WindowClose", windowName);
        }
    }
    else {
        if (msg == 1) {
            ucbook.invokeCsFunction("FrmBrowserClose");
        }
    }
}

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();

    switch (questionType) {
        case "ASingle":
        case "AMultiple":
        case "ATorF":
        case "AVote":
            initObjectiveView();
            break;
        //case "subjective"://主观题
        //    initSubjectView();
        //    break;
        default:
            {
                console.log("试题类型错误-题型：" + questionType);
            }
    }
}

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(); //隐藏作答时间div
    answers = new Object();
    switch (questionType) {
        case "ASingle":
            var anwserType = new Array("A", "B", "C", "D", "E", "F");
            for (var i = 0; i < anwserType.length; i++) {
                answers[anwserType[i]] = new Array();
            }

            var groupList = new Array();
            for (var i = 0; i < answersGroupList.length; i++) {
                if (answersGroupList[i].groupAnswer != "未提交") {
                    groupList[i] = answersGroupList[i];
                }
            }

            for (var i = 0; i < groupList.length; i++) {
                for (var item in answers) {
                    if (groupList[i].groupAnswer == item) {
                        answers[item].push(groupList[i]);
                    }
                }
            }
            drawHistograms(anwserType.length);
            drawCountAnswerCollection();
            break;
        case "AMultiple":
            var anwserType = new Array("A", "B", "C", "D", "E", "F");
            for (var i = 0; i < 6; i++) {
                answers[anwserType[i]] = new Array();
            }
            var groupList = new Array(); //去除未提交后的学生，按照答案分组
            for (var i = 0; i < answersGroupList.length; i++) {
                if (answersGroupList[i].groupAnswer != "未提交") {
                    groupList[i] = answersGroupList[i];
                }
            }

            for (var i = 0; i < groupList.length; i++) {
                for (var item in answers) {
                    var answersList = groupList[i].groupAnswer.split(" ");
                    for (var j = 0; j < answersList.length; j++) {
                        if (answersList[j] == item) {
                            answers[item].push(groupList[i]);
                        }
                    }
                }
            }
            drawHistograms(6);
            drawCountAnswerCollection();
            break;
        case "ATorF":
            answers["true"] = new Array();
            answers["false"] = new Array();

            for (var i = 0; i < answersGroupList.length; i++) {
                for (var j = 0; j < answersGroupList[i].studentListByGroup.length; j++) {
                    if (answersGroupList[i].groupAnswer.trim() == "√") {
                        answers["true"].push(answersGroupList[i].studentListByGroup[j]);
                    }
                    else if (answersGroupList[i].groupAnswer.trim() == "×") {
                        answers["false"].push(answersGroupList[i].studentListByGroup[j]);
                    }
                }

            }
            drawHistogramsbool();
            drawCountAnswerCollectionBool();
            break;
        case "AVote":
            $("#wrong-answer").hide();
            var anwserType = new Array("A", "B", "C", "D", "E", "F");
            for (var i = 0; i < anwserType.length; i++) {
                answers[anwserType[i]] = new Array();
            }

            var groupList = new Array();
            for (var i = 0; i < answersGroupList.length; i++) {
                if (answersGroupList[i].groupAnswer != "未提交") {
                    groupList[i] = answersGroupList[i];
                }
            }

            for (var i = 0; i < groupList.length; i++) {
                for (var item in answers) {
                    var answersList = groupList[i].groupAnswer.split(" ");
                    for (var j = 0; j < answersList.length; j++) {
                        if (answersList[j] == item) {
                            answers[item].push(groupList[i]);
                        }
                    }
                }
            }
            drawHistogramsVote(anwserType.length);
            drawCountAnswerCollectionVote();
            break;
    }
    $('.objective-content .count-info').empty().append('<span>提交人数：</span><span class="count-info-number">' + personAnalysis.submitStudentList.length + '/' + totalStudents + '人</span>');
}

//画选项人数直方图，count：答案选项个数
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");
    
    for (var item in answers) {

        var length = 0;
        if (questionType == "ASingle") {
            length = answers[item].length > 0 ? answers[item][0].studentListByGroup.length : answers[item].length;
        } else if (questionType == "AMultiple") {
            for (var j = 0; j < answers[item].length; j++) {
                length = length + answers[item][j].studentListByGroup.length;
            }
        }

        var height = getHistogramsHeight(length);
            innerHtml += '<div class="histogram-area-item" data-type="' + item + '">';
            innerHtml += '<span class="histogram-area-pcount">' + length + '</span>'
            innerHtml += '<span class="histogram-item-countY" style="height:' + height + 'px;"></span>'
            innerHtml += '<span class="histogram-area-answeritem">' + anwserType[i] + '</span>';
            innerHtml += '</div>';
            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 drawHistogramsVote(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");
    for (var item in answers) {

        var length = 0;
        for (var j = 0; j < answers[item].length; j++) {
            length = length + answers[item][j].studentListByGroup.length;
        }

        var height = getHistogramsHeight(length);
        innerHtml += '<div class="histogram-area-item" data-type="' + String.fromCharCode((item + "").charCodeAt(0) - 16) + '">';
        innerHtml += '<span class="histogram-area-pcount">' + length + '</span>'
        innerHtml += '<span class="histogram-item-countY" style="height:' + height + 'px;"></span>'
        innerHtml += '<span class="histogram-area-answeritem">' + String.fromCharCode((anwserType[i] + "").charCodeAt(0) - 16) + '</span>';
        innerHtml += '</div>';
        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>';
    $(".histogram-area").append(innerHtml);
    $('.object-show-answer').empty().hide();
    $('.histogram-item-countY').addClass('histogram-item-countG');
}

//判断题型，画答案选择项直方图
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 / totalStudents * 208;
}

//创建答案选项
function initShowAnswerArea(count) {
    $('#objectAnswerItemList').empty();
    var mulclass = '';
    if (questionType == 'AMultiple' || questionType == "AVote") {
        mulclass = ' object-answer-optionmultiple'
    }

    for (var i = 1; i <= count; i++) {
        var codev = i;
        if (questionType != "AVote") {
            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 < personAnalysis.unsubmitStudentList.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>' + personAnalysis.unsubmitStudentList[j].StudentName + '</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();
}

function getType(o) {
    var _t;
    return ((_t = typeof (o)) == "object" ? o == null && "null" || Object.prototype.toString.call(o).slice(8, -1) : _t).toLowerCase();
}
function extend(destination, source) {
    for (var p in source) {
        if (getType(source[p]) == "array" || getType(source[p]) == "object") {
            destination[p] = getType(source[p]) == "array" ? [] : {};
            arguments.callee(destination[p], source[p]);        //递归调用在这里
        }
        else {
            destination[p] = source[p];
        }
    }
}

/**
 * 记录上次图片的操作
 * @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;
}