; var navigation = (function () {
    var pages = [];

    function layoutPages() {
        var curPage = pages[pages.length - 1];
        if (typeof curPage.obj.layout === "function") {
            curPage.obj.layout();
        }
    }

    function layout() {
        var clientHeight = document.body.clientHeight,
			containerHeight = clientHeight - $('#navbar').offset().height;
        $(".container").height(containerHeight);
        layoutPages();
    }

    function bind() {
        window.onresize = layout;

        $("#homeButton").on('click', function () {
            backToPrevPage();
        });

        $(".header_right img").on('click', function () {
            window.location.href = "statistics.html";
        });
    }

    function update(page) {
        $("#title").text(page.title);
        if (pages.length === 1) {
            $("#homeButton").hide();
        } else if (pages.length === 2) {
            $("#homeButton").show();
        }
        page.obj.load(page.arg);
        layout();
    }

    function backToPrevPage() {
        var curObj = pages[pages.length - 1].obj;
        curObj.onPopup(function () {
            pages.pop();
            curObj.unload();
            update(pages[pages.length - 1]);
        });
    }

    return {
        init: function (pageObj) {
            bind();
            this.gotoPage(pageObj);
        },
        gotoPage: function (page) {
            if (pages.length > 0) {
                pages[pages.length - 1].obj.unload();
            }
            pages.push(page);
            update(page);
        },
        refresh: function () {
            pages[pages.length - 1].obj.refresh();
        }
    }
}());

var questionTypeOrders = {
    "100": { "单项选择": 1, "多项选择": 2, "基础题": 3, "阅读题": 4, "作文": 5, "复合题": 6, "其他": 7 },
    "103": { "单项选择": 1, "多项选择": 2, "填空题": 3, "判断题": 4, "解答题": 5, "复合题": 6 },
    "104": {
        "语音题": 1, "听力题": 2, "单项选择": 3, "单项填空": 4, "填空题": 5, "英汉互译": 6, "补全对话": 7, "句型转换": 8,
        "完形填空": 9, "完型填空": 10, "完成对话": 11, "看图填词句": 12, "词汇填空": 13, "改错题": 14, "连词成句": 15, "阅读填空": 16, "阅读理解": 17, "匹配题": 18, "复合题": 19, "其他": 20
    },
    "106": { "单项选择": 1, "多项选择": 2, "填空题": 3, "综合题": 4, "复合题": 5, "其他": 6 },
    "107": { "单项选择": 1, "多项选择": 2, "填空题": 3, "复合题": 4 },
    "165": { "单项选择": 1, "多项选择": 2, "非选择题": 3, "复合题": 4 },
    "166": { "单项选择": 1, "多项选择": 2, "综合题": 3, "复合题": 4 },
    "265": { "单项选择": 1, "多项选择": 2, "问答题": 3, "复合题": 4 },
    "105": { "单项选择": 1, "多项选择": 2, "判断题": 3, "探究实践题": 4, "分析说明题": 5, "复合题": 6 },
    "000": { "单项选择": 1, "多项选择": 2, "问答题": 3, "复合题": 4, "其他": 5, "填空题": 6, "判断题": 7 }

}

var question = (function () {
    var unfinished = false, errors = null;
    function calcStarLevel(rate) {
        if (rate == 100) return 3;
        if (rate >= 90) return 2;
        if (rate >= 80) return 1;
        return 0;
    }

    function appendStudentAnswer(questionData, result, topicStatics) {
        var curId = questionData[0].topic.id;
        questionData[0].correct = result.correct;
        questionData[0].partlyCorrect = result.partlyCorrect;
        if (topicStatics && topicStatics[curId]) {
            questionData[0].classCorrectRate = topicStatics[curId].rate;
        }

        if (questionData[0].topic.topic_type == "0" || questionData[0].topic.topic_type == "2") {
            if (result.answer.length > 0 && result.answer[0].length > 10) {
                var indexMap = {}, i = 0;

                for (i = 0; i < questionData[0].topindexs.length; i++) {
                    indexMap[questionData[0].topindexs[i].ID] = i;
                }

                for (i = 0; i < result.answer.length; i++) {
                    result.answer[i] = String.fromCharCode('A'.charCodeAt(0) + indexMap[result.answer[i]]);
                }
            }
            questionData[0].studentAnswer = result.answer.join(",");
        } else if (questionData[0].topic.topic_type == "1") {
            for (var j = 0; j < questionData[0].topindexs.length; j++) {
                questionData[0].topindexs[j].studentAnswer = result.answer[j];
            }
        } else {
            for (var k = 0; k < result.answer.length; k++) {
                appendStudentAnswer([questionData[k + 1]], result.answer[k], topicStatics);
            }
        }
    }

    return {
        rearrangeQuestions: function (questions, subject) {
            var count = questions.length,
    			curQuestion = null, curNumber = 1,
    			questionCollections = [],
    			typeMap = {}, mapIndex = 0;
            var curOrder = questionTypeOrders[subject];
            if (curOrder == null) {
                curOrder = questionTypeOrders["000"];
            }
            for (var i = 0; i < count; i++) {
                var type = questions[i].type; // data[0].topic.topic_type;
                if (type == "选择题" || type == "单选题") {
                    var t = questions[i].data[0].topic.topic_type;
                    if (t == 0)
                        type = "单项选择";
                    else if (t == 2)
                        type = "多项选择";
                    else if (t == 3)
                        type = "复合题";
                    questions[i].type = type;
                }
                var typeid = curOrder[type];

                if (typeMap[typeid] === undefined) {
                    typeMap[typeid] = mapIndex;
                    questionCollections[mapIndex] = { type: type, questions: [] };
                    mapIndex++;
                }
                questionCollections[typeMap[typeid]].questions.push(questions[i]);
            }

            questionCollections.sort(function (collection1, collection2) {
                return curOrder[collection1.type] - curOrder[collection2.type];
            });

            for (var i = 0; i < questionCollections.length; i++) {
                for (var j = 0; j < questionCollections[i].questions.length; j++) {
                    curQuestion = questionCollections[i].questions[j];
                    curQuestion.id = curQuestion.data[0].topic.id;
                    curQuestion.number = curNumber;
                    curQuestion.collectionIndex = i;
                    curQuestion.errorTimes = 0;
                    curNumber++;
                }
                questionCollections[i].errorCount = 0;
            }
            return {
                count: count,
                questionCollections: questionCollections
            }
        },

        judge: function (elem, questionData) {
            var curType = questionData[0].topic.topic_type,
				answer = [], correct = true, partlyCorrect = false,
				topindexs = questionData[0].topindexs;

            if (curType === "0" || curType === "2") {
                correct = true;
                unfinished = true;
                $(elem).find("input").each(function (index, elem) {
                    if (!elem.checked) {
                        if (topindexs[index].CdetAnswer === "1") correct = false;
                    } else {
                        unfinished = false;
                        answer.push(String.fromCharCode('A'.charCodeAt(0) + index));
                        if (topindexs[index].CdetAnswer === "0") correct = false;
                    }
                });
                questionData[0].studentAnswer = answer.join(",");
            } else if (curType === "1") {
                $(elem).find('.answer_blank').each(function (index, item) {
                    var text = item.innerText.trim();
                    if (text === "") {
                        unfinished = true;
                        correct = false;
                    } else {
                        if (text.trim() === questionData[0].topindexs[index].CdetContent.trim()) {
                            partlyCorrect = true;
                        } else {
                            correct = false;
                        }
                    }
                    topindexs[index].studentAnswer = text;
                    answer.push(text);
                });
            } else {
                $(elem).find(".subquestion")
							.each(function (index, item) {
							    var subquestionData = questionData[index + 1],
						subresult = question.judge(item, [subquestionData]);
							    if (!subresult.correct) {
							        correct = false;
							        if (subresult.partlyCorrect) partlyCorrect = true;
							    } else {
							        partlyCorrect = true;
							    }
							    answer.push(subresult);
							});
            }
            questionData[0].correct = correct;
            questionData[0].partlyCorrect = partlyCorrect;
            return { "id": questionData[0].topic.id, "correct": correct, "partlyCorrect": partlyCorrect, "answer": answer };
        },

        markPaper: function (qeustionContent, homeworkId, errorRecord, chapterContent) {
            var count = qeustionContent.count,
				results = {}, correctCount = 0,
				topicId = [], topicResult = [], correctRate = 0;
            unfinished = false;
            /*
            i = 0;
            var el = document.getElementsByClassName('question');
            for (var i = 0; i < el.length; i++) {
            $(el[i]).attr("data-index", i);
            //                $(el[i]).attr(el[i].dataset.collectionIndex, i);
            i++;
            }
            */
            function getDataById(id) {
                var cLen = chapterContentText.length;
                while (cLen--) {
                    if (String(chapterContentText[cLen].id) === String(id)) {
                        return chapterContentText[cLen];
                    };
                };
            };

            $(".question").each(function (index, item) {
                var curQuestion = getDataById($(item).attr("id"));
                var questionData = curQuestion.data;
                /*
                var collectionIndex = parseInt(item.dataset.collectionIndex);
                var index = parseInt(item.dataset.index);
                var questionCollection = qeustionContent.questionCollections[collectionIndex];
                var curQuestion = questionCollection.questions[index];
                var questionData = curQuestion.data;
                */
                var result = question.judge(item, questionData);
                if (result.correct) {
                    correctCount++;
                }
                else {
                    for (var i = 0; i < qeustionContent.questionCollections.length; i++) {
                        if (curQuestion.type == qeustionContent.questionCollections[i].type) {
                            qeustionContent.questionCollections[i].errorCount++;
                        }
                    }
                    //                    questionCollection.errorCount++;
                }

                results[questionData[0].topic.id] = result;
                topicId.push(questionData[0].topic.id);
                topicResult.push(result.correct ? 1 : 0);

                if (questionData[0].topic.topic_type === "3") {
                    for (var i = 0; i < result.answer.length; i++) {
                        topicId.push(result.answer[i].id);
                        topicResult.push(result.answer[i].correct ? 1 : 0);
                    }
                }

                if (!!errorRecord && !result.correct) errorRecord.push(curQuestion);
            });
            correctRate = Math.floor(correctCount / count * 100);
            qeustionContent.errorCount = count - correctCount;
            qeustionContent.correctRate = correctRate;
            qeustionContent.starLevel = calcStarLevel(correctRate);
            return {
                "homeworkClassId": homeworkId,
                "unfinished": unfinished,
                "errorCount": qeustionContent.errorCount,
                "correctCount": correctCount,
                "correctRate": correctRate,
                "starLevel": qeustionContent.starLevel,
                "content": encodeURIComponent(JSON.stringify(results)),
                "topicId": topicId.join(","),
                "topicResult": topicResult.join(",")
            }
        },

        mergeResult: function (qeustionContent, answerResult) {
            var errorCount = 0, questionCollection = null;
            try {
                var results = JSON.parse(decodeURIComponent(answerResult.content));
                qeustionContent.errorCount = answerResult.errorCount;
                qeustionContent.correctRate = answerResult.correctRate;
                qeustionContent.starLevel = answerResult.starLevel;
                qeustionContent.classCorrectRate = answerResult.classCorrectRate;

                for (var i = 0; i < qeustionContent.questionCollections.length; i++) {
                    errorCount = 0;
                    questionCollection = qeustionContent.questionCollections[i];

                    for (var j = 0; j < questionCollection.questions.length; j++) {
                        var question = questionCollection.questions[j],
							result = results[question.data[0].topic.id];
                        appendStudentAnswer(question.data, result, answerResult.topicStatics);
                        if (!result.correct) errorCount++;
                    }
                    questionCollection.errorCount = errorCount;
                }
            } catch (e) {
            };

            return questionCollection;
        },

        drawCorrectRate: function (correctRate, selector) {
            if (selector == "undefined" || selector == undefined)
                selector = "#correct_rate_canvas";

            var ctx = document.querySelector(selector).getContext("2d"),
				x = y = outerRadius = 50, radius = 40, lineWidth = 18,
				correctColor = "#33B5E5", wrongColor = "#FF8800",
				ratio = correctRate / 100,
				sAngle = (1.25 - ratio) * Math.PI,
				eAngle = (1.25 + (ratio ? ratio : 2)) * Math.PI,
				gap = (ratio == 0 || ratio == 100) ? 0 : 0.02;

            function drawPart(counterclockwise) {
                var x1, y1, d = 10, sign = counterclockwise ? -1 : 1,
					distance = outerRadius / Math.sqrt(2) + radius / 10;
                ctx.fillStyle = ctx.strokeStyle = counterclockwise ? wrongColor : correctColor;
                ctx.lineWidth = lineWidth;
                ctx.beginPath();
                ctx.arc(x, y, radius, sAngle + sign * gap, eAngle - sign * gap, counterclockwise);
                ctx.stroke();

                x1 = y1 = outerRadius - sign * distance;
                ctx.beginPath();
                ctx.moveTo(x1, y1);
                ctx.lineTo(x1 + sign * d, y1);
                ctx.lineTo(x1, y1 + sign * d);
                ctx.fill();
            }

            if (correctRate > 0) {
                drawPart(false);
            }
            if (correctRate < 100) {
                drawPart(true);
            }
        }
    }
}());

var questionTemplateHelper = (function () {
    var resourcePath = "";
    function getHTMLContent(text) {
        try {
            var container = $("<div>" + text + "</div>");
            container.find("img").each(function (index, elem) {
                var relativePath = elem.getAttribute("src"),
                		isDataUrl = relativePath.indexOf("data") == 0;
                if (isDataUrl) return;
                if (relativePath[0] !== "/") relativePath += "/";
                elem.src = resourcePath + relativePath;
            });
            return new Handlebars.SafeString(container.html());
        } catch (e) {
            return "";
        }
    }
    function getAnalysisContent(data) {
        var content = "";
        if (data[0].topic.topic_analytic) {
            content = extractAnalysisContent(data[0].topic.topic_analytic);
        } else {
            for (var i = 1, length = data.length; i < length; i++) {
                content += extractAnalysisContent(data[i].topic.topic_analytic);
            }
        }
        return getHTMLContent(!content ? "略" : content);
    }
    function extractAnalysisContent(text) {
        var analysisKeys = ["思路解析", "分析", "解析", "提示"],
		 	answerKeyss = ["参考答案", "答案", "解"],
		   	suggestionKeys = ["点拨"],
	        suffixPattern = "((<[^>]*>){2,})?[:：]?",
	        topicAnalytic = text.trim();
        function findPos(keys) {
            var pos = -1, re = null, result = null;
            for (var i = 0, length = keys.length; i < length; i++) {
                re = new RegExp(keys[i] + suffixPattern);
                result = topicAnalytic.match(re);
                if (result) break;
            }
            return result;
        }

        function trimAnswerContent(text) {
            var result = text.match(/^(<[^>]*>)*((\(\d\))?[ABCD]\s*)+(<\/[^>]*>)*/i);
            return !result ? text : text.substr(result.index + result[0].length);
        }

        function trimContent(content) {
            var start = content[0] == '<' ? content.indexOf('>') + 1 : 0,
	            end = content[content.length - 1] == '>' ? content.lastIndexOf('<') : content.length;
            return content.slice(start, end);
        }
        function extractContent(contentPos, pos1, pos2) {
            if (!contentPos) return "";
            var end = topicAnalytic.length;
            if (pos1 && pos1.index > contentPos.index) end = pos1.index;
            if (pos2 && pos2.index > contentPos.index && pos2.index < end) end = pos2.index;
            return trimContent(topicAnalytic.slice(contentPos.index + contentPos[0].length, end));
        }
        var result = null,
	        analysisPos = findPos(analysisKeys),
	        answerPos = findPos(answerKeyss),
	        suggestionPos = findPos(suggestionKeys),
	        analysisContent = null;
        if (!analysisPos && !answerPos && !suggestionPos) {
            analysisContent = trimAnswerContent(topicAnalytic);
        } else if (!analysisPos && !suggestionPos) {
            analysisContent = trimAnswerContent(topicAnalytic.substr(answerPos.index + answerPos[0].length));
        } else {
            analysisContent = extractContent(analysisPos, answerPos, suggestionPos) + extractContent(suggestionPos, answerPos, analysisPos);
        }
        return analysisContent;
    }
    function registerHelpers() {

        Handlebars.registerHelper("get_shown_type", function (qus_type, topic_type) {
            if (qus_type == "选择题") {
                var p;
                switch (topic_type) {
                    case "0":
                        p = "单项选择";
                        break;
                    case "2":
                        p = "多项选择";
                        break;
                    case "3":
                        p = "复合题";
                        break;
                }
                return p;
            }
            else
                return qus_type;
        });

        Handlebars.registerHelper("get_alpha_index", function (index) {
            return String.fromCharCode('A'.charCodeAt(0) + index);
        });

        Handlebars.registerHelper("isShortAnswerType", function (type, options) {
            if (type !== 1 && (typeof type === "string" && type !== "1")) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

        Handlebars.registerHelper("isCorrectAnswer", function (correct, options) {
            if (correct !== 1 && (typeof correct === "string" && correct !== "1")) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

        Handlebars.registerHelper("isCompositeQuestion", function (type, options) {
            if (type !== 3 && (typeof type === "string" && type !== "3")) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

        Handlebars.registerHelper("isMultiChoiceType", function (type, options) {
            if (type !== 0 && (typeof type === "string" && type !== "0")) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

        Handlebars.registerHelper("get_html_content", getHTMLContent);

        Handlebars.registerHelper("get_analysis_content", getAnalysisContent);

        Handlebars.registerHelper("inc", function (index) {
            return index + 1;
        });

        Handlebars.registerHelper("loop", function (count, options) {
            var out = "";
            for (var i = 0; i < count; i++) {
                out += options.fn(this);
            }
            return out;
        });

        Handlebars.registerHelper("addRed", function (value) {
            if (value === 0) {
                return '<td>0</td>'
            };
            if (value === '') {
                return '<td>/</td>'
            };
            if (value > 0) {
                return '<td class="red">' + value + '</td>'
            };


        });
        Handlebars.registerHelper("blue", function (value) {
            if (value === '') {
                return 'class="noData"'
            }
        });
        Handlebars.registerHelper("rate", function (value) {
            if (value === '') {
                return '<td>/</td>'
            } else {
                return '<td>' + value + '%</td>'
            }
        });
    }

    return {
        init: function () {
            registerHelpers();
        },

        setResourcePath: function (path) {
            resourcePath = path;
        }
    }
}());

var templateLoader = (function () {
    function getSource(tpl) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", tpl, false);
        xhr.send();
        if (xhr.readyState == 4 && (xhr.status == 0 || xhr.status == 200)) {
            return xhr.responseText;
        }
        return null;
    }

    return {
        load: function (tpl) {
            return Handlebars.compile(getSource(tpl));
        }
    }
}());
