<html>
    <head>
		<meta charset="UTF-8">
		<style>
			* {
				margin: 0;
				padding: 0;
			}
			
			body {
				background: #EBEBEB;
				padding-top: 5px;
				font-family: "Microsoft YaHei" ! important;
				font-size: 14px;
			}
			.question_collection {
				margin: 1% 2%;
				background:#ffffff;
				box-shadow: 0 0 5px black;
			}
			
			.question_collection_type {
				height: 29px;
				border-bottom: 1px solid #E8E8E8;
			}
			
			.question_collection_type span {
				display: inline-block;
				width: 124px;
				height: 24px;
				padding-top: 5px;
			}
			
			.question_collection_type_name {
				background-image:url("img/title_bg.png");
			}
			
			span.question_collection_count {
				display: none;
			}
			
			.question_collection_header{
				display: none;
				font-size: 0;
			}
			
			.question_collection_header span {
				display: inline-block;
				width: 5%;
				text-align: center;
				font-size: 14px;
			}

			.question{
				border-bottom: 1px solid #E8E8E8;
				font-size : 0;
			}
			
			.question_number {
				display:inline-block;
				width: 5%;
				vertical-align: top;
				text-align: center;
				font-size: 14px;
			}
			
			.question_content {
				display: inline-block;
				width: 95%;
				vertical-align: middle;
				font-size: 14px;
			}
			
			.subquestion + .subquestion {
				margin-top: 20px;
				border-top: 2px solid #e9e9e9;
			}
			
			.question_model_answer {
				padding: 15px 0;
			}
			
			.question_result {
				display: none;
				vertical-align: middle;
				font-size: 14px;
			}
			
			.question_result > p{
				text-align:center;
			}
			#chapter_content {
				display: none;
			}
			#chapter_content .question_collection_header {
				height: 29px;
				line-height:29px;
				border-bottom: 1px solid #E8E8E8;
				display: block;
			}
			
			#chapter_content span.question_collection_count {
				display: inline-block;
			}
			#chapter_content .question_answer {
				display: none;
			}
			.view_model .question_number input {
			    display: none;
			}
			
			#chapter_content.view_model .question_collection_header {
			    display: none;
			}
			
			#exercise_preview .question_number input {
				display: none;
			}
			
			#exercise_preview .question_model_answer{
				display: none;
			}
			
			#exercise_result input {
				display: none;
			}
			#exercise_result .question_answer {
				display: none;
			}
			
			#exercise_result .question_content {
				width : 74%;
				border-right: 1px solid #e9e9e9;
			}
			#exercise_result .question_result {
				display: inline-block;
				width: 20%;
			}
			#chapter_panel{
				overflow: auto;
				height: 100%;
			}
			.container {
				background: white;
				height: 100%;
				width: 30%;
				font-family: "Microsoft YaHei" ! important;
				color: #333333;
				float: left;
			}
			.title {
				font-size: 18px;
				margin: 0px auto;
				height: 35px;
				width: 93%;
				line-height: 35px;
				text-align: center;
				background-color: #F5F5F5;
				margin-top: 8px;
			}
			.directory-panel {
				width: 93%;
				height: calc(100% - 35px);
				margin: 0px auto;
				overflow: auto;
			}
			.directory-toc {
				margin: 12px auto;
				width: 100%;
			}
			.directory-toc li a {
				display: inline-block;
				padding-left: 10px;
			}
			.directory-toc li div {
				font-size: 14px;
				line-height: 28px;
				list-style: none;
				border: 1px solid #D9D9D9;
				margin: 12px auto;
				background-color: #F5F5F5;
				overflow: hidden;
				text-overflow: clip;
				white-space: nowrap;
			}
			.directory-toc li span {
				margin-left: 10px;
				display: inline-block;
				width: 8px;
				height: 10px;
			}
			.collapsed {
				background: url(img/left.png) no-repeat;
			}
			.expanded {
				background: url(img/down.png) no-repeat;
			}
			.directory-toc li li div {
				background-color: #FFFFFF;
				border: none;
				font-weight: 600;
			}
			.directory-toc li li a {
				padding-left: 30px;
			}
			.directory-toc li li li a {
				padding-left: 36px;
			}
		</style>
    </head>
    <body>
        <div id="chapter_content">
        	<div class="container">
	        	<div class="title">目&nbsp; 录</div>
				<div class="directory-panel">
					<script type="text/template" id="directory-list-template">
						<ul id ="directory-toc" class="directory-toc">
						{{#recursive children}}
							<li>
								<div id={{id}}><a>{{cha_name}}</a></div>
								{{#if children}}
									<ul>{{{recursive children}}}</ul>
								{{/if}}
							</li>
						{{/recursive}}
						</ul>
					</script>
				</div>
			</div>
			<div id="chapter_panel">..</div>
        </div>
        <div id="exercise_preview">
        </div>
        <div id="exercise_result">
        </div>
        <script id="exercise_template" type="text/x-handlebars-template">
			{{#each questionCollections}}
				<div class="question_collection" data-index={{@index}} data-type={{type}}>
					<div class="question_collection_type">
						<span class= "question_collection_type_name">&nbsp;&nbsp; {{type}}</span>
						<span class="question_collection_count">（共{{questions.length}}题）</span>
					</div>
					<div class="question_collection_header">
						<span><input type="checkbox" data-type={{type}} name="group_selection"></input>&nbsp;&nbsp;&nbsp; </span>
						<span style="text-align: left">题目</span>
					</div>
					{{#each questions}}	
						<div class="question" data-index={{@index}} id="{{data.[0].topic.id}}">
							<div class="question_number" >
								<input type="checkbox" name="group_selection"></input>
								<span>{{inc @index}}</span>
							</div>
							<div class= "question_content">
                                <div class="question_stem">
                                    {{#each data}}
                                        {{#if topic.topic_stem}}
                                            <div>{{#if @index}}（{{@index}}）{{/if}}{{get_html_content topic.topic_stem}}</div>
                                        {{/if}}
                                        {{#if topindexs}}
                                            <div>
                                                {{#isShortAnswerType ../topic.topic_type}}
                                                {{else}}
                                                    {{#each topindexs}}
                                                        {{#if CdetContent}}
                                                            <div>{{get_alpha_index @index}}.{{get_html_content CdetContent}}</div>
                                                        {{/if}}
                                                    {{/each}}
                                                {{/isShortAnswerType}}
                                            </div>
                                        {{/if}}
                                    {{/each}}
                                </div>
								<div class="question_answer">
					                {{#each data}}
						                {{#if @index}}
							                <div class= "subquestion subquestion_type_{{topic.topic_type}}" id="{{topic.id}}">
								                <span class="subquestion_number">（{{@index}}）</span>
						                {{/if}}
						                {{#if topindexs}}
							                {{#isShortAnswerType ../topic.topic_type}}
								                <span class="short_answers">
									                {{#each topindexs}}
										                <span>{{inc @index}}.<span class="answer_blank" contenteditable="true"></span></span>
									                {{/each}}
								                </span>
							                {{else}}
								                <span class="multichoice_answer_list">
									                <span style="color:#999">你的选择：</span>
									                {{#each topindexs}}
										                <span class="question_answer_item" data-answer={{CdetAnswer}}>
											                {{#isMultiChoiceType ../../topic.topic_type}}
												                <input type="radio" name="{{TopicId}}" id="{{ID}}">
											                {{else}}
												                <input type="checkbox" name="{{TopicId}}" id="{{ID}}" >
											                {{/isMultiChoiceType}}
											                <label for="{{ID}}">{{get_alpha_index @index}}</label>
										                </span>
									                {{/each}}
								                </span>
							                {{/isShortAnswerType}}
						                {{/if}}		
						                {{#if @index}}
							                </div>
						                {{/if}}
					                {{/each}}
				                </div>
								<div class="question_model_answer">
									<span>参考答案：</span>
									{{#each data}}
                                        {{#if @index}}（{{@index}}）{{/if}}
										<span>
                                            {{#if  topic.topic_analytic}}
                                                {{get_html_content topic.topic_analytic}}
                                            {{else}}
                                                {{#each topindexs}}
                                                    {{#if CdetContent}}
                                                        {{#isShortAnswerType ../../topic.topic_type}}
                                                            <span>{{inc @index}}.{{get_html_content CdetContent}}</span>
                                                        {{else}}
                                                            {{#isCorrectAnswer CdetAnswer}}<span>{{get_alpha_index @index}}</span>{{/isCorrectAnswer}}
                                                        {{/isShortAnswerType}}
                                                    {{/if}}
                                                {{/each}}
                                            {{/if}}
                                        </span>
									{{/each}}
								</div>
							</div>
							<div class="question_result">
								<p class="rate">0%</p>
								<p>答对</p>
							</div>
						</div>
					{{/each}}
				</div>
			{{/each}}
		</script>
    
   <script src="js/zepto.js"></script>
	<script src="js/handlebars-1.0.rc.1.js"></script>   
	<script src="js/drag.js"></script>
    <script>
        var examinations = {}, bookid, subjectId, chapterid, chapterName, homeworkpath, questionContent, content, chapterlist, resultContent, homeWorkTopicStatus, flag = 0;

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

        function rearrangeQuestions(questions) {
            var count = questions.length,
    			questionCollections = [],
    			typeMap = {}, mapIndex = 0;

            for (var i = 0; i < count; i++) {
                var type = questions[i].data[0].topic.topic_type;
                if (typeMap[type] === undefined) {
                    typeMap[type] = mapIndex;
                    questionCollections[mapIndex] = { type: questions[i].type, questions: [] };
                    mapIndex++;
                }
                questionCollections[typeMap[type]].questions.push(questions[i]);
            }

            questionCollections.sort(function (collection1, collection2) {
                var curOrder = questionTypeOrders[subjectId];
                return curOrder[collection1.type] - curOrder[collection2.type];
            });
            return {
                count: count,
                questionCollections: questionCollections
            }
        }

        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("isMultiChoiceType", function (type, options) {
            if (type !== 0 && (typeof type === "string" && type !== "0")) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

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

        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("get_html_content", function (text) {
            try {
                var container = $("<div>" + text + "</div>");
                container.find("img").each(function (index, elem) {
                    var relativePath = elem.getAttribute("src");
                    if (relativePath[0] !== "/") relativePath += "/";
                    elem.src = "file:///" + homeworkpath + relativePath;
                });
                return new Handlebars.SafeString(container.html());
            } catch (e) {
                return "";
            }
        });

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

        Handlebars.registerHelper("isRightAnswer", function (str, options) {
            if (str !== "0") {
                return options.fn(this);
            }
        });

        var audaciousFn;
        Handlebars.registerHelper('recursive', function (children, options) {
            var out = '';
            if (options.fn !== undefined) {
                audaciousFn = options.fn;
            }
            children.forEach(function (child) {
                out = out + audaciousFn(child);
            });
            return out;
        });

        var template = Handlebars.compile($("#exercise_template").html());
        var directory_template = Handlebars.compile($('#directory-list-template').html());
        function renderToc() {
            var tocData = transData(chapterlist, 'id', 'up_id', 'children');
            var $data = directory_template({ "children": tocData });
            chapterid = tocData[0].id;
            chapterName = tocData[0].cha_name;
            $(".directory-panel").html($data);
            var directoryList = document.getElementById("directory-toc");
            if (directoryList) {
                this.listItem = function (li) {
                    if (li.getElementsByTagName("ul").length > 0) {
                        var ul = li.getElementsByTagName("ul")[0];
                        ul.style.display = "none";
                        var span = document.createElement("span");
                        span.className = "collapsed";
                        $(span).insertBefore($(li).find('a')[0]);
                    }
                }
                var items = directoryList.getElementsByTagName("li");
                for (var i = 0; i < items.length; i++) {
                    listItem(items[i]);
                }
            }
        }

        function transData(a, idStr, pidStr, chindrenStr) {
            var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;
            for (; i < len; i++) {
                hash[a[i][id]] = a[i];
            }
            for (; j < len; j++) {
                var aVal = a[j], hashVP = hash[aVal[pid]];
                if (hashVP) {
                    var ary = aVal.cha_number.split(".");
                    var orderNum = ary[ary.length - 1];
                    !hashVP[children] && (hashVP[children] = []);
                    hashVP[children][orderNum - 1] = aVal;
                } else {
                    r.push(aVal);
                }
            }
            return r;
        }

        function bindTocEvents() {
            $("#directory-toc").on('click', 'li div', function () {
                if ($(this).closest("ul").siblings("div").length > 0) {
                    $(this).closest('li').siblings("li").find("div").css("background-color", "#FFFFFF");
                    $(this).css("background-color", "#E7F1FF");
                    chapterid = this.id;
                    chapterName = $(this).find("a").html();
                    getChapterContent();
                }
                $(this).siblings('ul').toggle();
                if ($(this).find('span').hasClass('expanded')) {
                    $(this).find('span').attr('class', 'collapsed');
                } else {
                    $(this).find('span').attr('class', 'expanded');
                }
                $(this).closest('li').siblings('li').find('span').attr('class', 'collapsed');
                $(this).closest('li').siblings('li').find('ul').hide();
                return false;
            })
        }

        function bindCheckboxEvents() {
            $('input[name="group_selection"]').on("click", function () {
                if ($(this).data("type")) {
                    var isChecked = $(this).prop("checked");
                    var collection = $(".question_collection[data-type=" + $(this).data("type") + "]");
                    collection.find(".question_number input[type='checkbox']").prop("checked", isChecked);
                    var questions = collection.find(".question");
                    for (var i = 0; i < questions.length; i++) {
                        var id = $(questions[i]).attr("id");
                        if (isChecked) {
                            var obj = content.questionCollections[collection.data("index")].questions[i];
                            obj.bookid = bookid;
                            examinations[id] = obj;
                            //alert("into..."+JSON.stringify(examinations));
                        } else {
                            if (examinations[id]) {
                                delete examinations[id];
                            }
                        }
                    }
                } else {
                    var selectAll = $(this).closest(".question").siblings(".question_collection_header").find("input[type='checkbox']");
                    var id = $(this).closest(".question").attr("id");
                    if ($(this).prop("checked")) {
                        $(this).prop("checked", true);
                        if (!examinations[id]) {
                            var questionIndex = $(this).closest(".question").data("index");
                            var collectionIndex = $(this).closest(".question_collection").data("index");
                            var obj = content.questionCollections[collectionIndex].questions[questionIndex];
                            obj.bookid = bookid;
                            examinations[id] = obj;
                        }
                        var otherSelect = $(this).closest(".question").siblings(".question").find("input[type='checkbox']");
                        var count = 0;
                        if (otherSelect) {
                            for (var i = 0; i < otherSelect.length; i++) {
                                if ($(otherSelect[i]).prop("checked")) {
                                    count += 1;
                                }
                            }
                            if (count == otherSelect.length) {
                                if (!selectAll.prop("checked")) {
                                    selectAll.prop("checked", true);
                                }
                            }
                        }
                    } else {
                        $(this).prop("checked", false);
                        if (examinations[id]) {
                            delete examinations[id];
                        }
                        if (selectAll.prop("checked")) {
                            selectAll.prop("checked", false);
                        }
                    }
                }

            })
        }

        function hideContents() {
            $("#chapter_content").hide();
            $("#exercise_result").hide();
            $("#exercise_preview").hide();
        }

        function resultRate() {
            var q = $(".question");

            if (homeWorkTopicStatus.length > 0) {

                for (var i = 0; i < q.length; i++) {
                    var questionId = q[i].id;

                    for (var j = 0; j < homeWorkTopicStatus.length; j++) {
                        if (homeWorkTopicStatus[j].topicId == questionId) {
                            var rate = homeWorkTopicStatus[j].rate;
                            var rateDom = $(q[i]).find(".question_result p").first();
                            rateDom.css("color", changeRateStyle(rate)).html(rate + "%");
                        }
                    }
                }
            } else {
                $(".question_result .rate").css("color", "#FF3300");
            }
        }

        function changeRateStyle(rate) {
            if (rate >= 80 && rate <= 100) {
                return "#66CC00";
            } else if (rate >= 60 && rate < 80) {
                return "#FFC108";
            } else if (rate < 60) {
                return "#FF3300";
            }
        }

        function reCheckQuestions() {
            var questions = $(".question");
            var collections = $(".question_collection");
            for (var i = 0; i < questions.length; i++) {
                for (var j in examinations) {
                    if ($(questions[i]).attr("id") == j) {
                        $(questions[i]).find("input[name='group_selection']").prop("checked", true);
                    }
                }
            }

            for (var k = 0; k < collections.length; k++) {
                if ($(collections[k]).find(".question_number input:checked").length == $(collections[k]).find(".question").length) {
                    $(collections[k]).find(".question_collection_header input").prop("checked", true);
                }
            }
        }

        function showChapterContent() {
            hideContents();
            content = rearrangeQuestions(questionContent);
            //alert(content+":"+content.questionCollections);
            $("#chapter_panel").html(template(content));
            $("#chapter_content").show();
            if (examinations) {
                reCheckQuestions();
            }
            if (flag == 0) {
                bindTocEvents();
            }
            bindCheckboxEvents();
            $("body").css("overflow", "hidden");
            flag++;
        }

        function showExerciseResult() {
            var result = rearrangeQuestions(resultContent);
            $("#exercise_result").html(template(result));
            resultRate();
            $("#exercise_result").show();
            $("#exercise_result .question_collection").css("margin", "0px");
            $("body").css("overflow", "auto");
        }

        function exercisePreview() {
            var questions = [];
            if (!isEmptyObject(examinations)) {
                var count = 0;
                for (var i in examinations) {
                    questions[count] = examinations[i];
                    count++;
                }
            }

            var previewContent = rearrangeQuestions(questions);
            hideContents();
            $("#exercise_preview").html(template(previewContent));
            $("#exercise_preview").show();
            $("body").css("overflow", "auto");
        }

        function backToChapterFromPreview() {
            $("#exercise_result").hide();
            $("#chapter_content").show();
            $("body").css("overflow", "hidden");
        }

        function isEmptyObject(obj) {
            for (var name in obj) {
                return false;
            }
            return true;
        }

        function onMessage(message) {
            try {
                console.log(message)
                var msg = JSON.parse(message);
            } catch (e) {
                console.log(e + ":" + message);
                return;
            }
            switch (msg.action) {
                case "showExerciseBook":
                    flag = 0;
                    bookid = msg.arguments[0].bookid;
                    subjectId = msg.arguments[0].subjectId;
                    homeworkpath = msg.arguments[0].homeworkpath;
                    chapterid = msg.arguments[0].chapterid;
                    chapterlist = msg.arguments[0].chapterlist;
                    if (msg.arguments[0].viewModel) {
                        console.log("aaaa" + msg.arguments[0].viewModel);
                        $("#chapter_content").addClass("view_model");
                        
                    }
                    renderToc();
                    getChapterContent();
                    break;
                case "showChapterContent":
                    questionContent = msg.arguments;
                    showChapterContent();
                    break;
                case "previewHomework":
                    exercisePreview();
                    break;
                case "closePreview":
                    backToChapterFromPreview();
                    break;
                case "showHomeworkResult":
                    resultContent = msg.arguments.examinations;
                    homeworkpath = msg.arguments.homeworkpath;
                    homeWorkTopicStatus = msg.arguments.homeWorkTopicSta;
                    showExerciseResult();
                    break;
                case "getChoosedQuestions":
                    var results = [];
                    for (item in examinations) {
                        var obj = examinations[item];
                        if (typeof question !== "object") {
                            results.push(obj);
                        }
                    }
                    return ucbook.postWebPageMessage(JSON.stringify({ action: "setChooseQuestions", arguments: results }));
                    break;
            }
        }

        function getChapterContent() {
            var cmdJSON = JSON.stringify({ action: "getChapterContent", arguments: [bookid, chapterid, chapterName] });
            ucbook.postWebPageMessage(cmdJSON);

        }

        window.onload = function () {
            ucbook.onWebPageMessage = onMessage;
            ucbook.postWebPageMessage("ready");
        }
	</script>
        
    </body>
</html>
