<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../common/init.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="${ctx}/resources/css/main.css" type="text/css" />
<link rel='stylesheet' href='${ctx}/resources/css/easyui.css' type='text/css' media='screen' />
<link rel='stylesheet' href='${ctx}/resources/css/easyui/icon.css' type='text/css' media='screen' />
<link rel='stylesheet' href='${ctx}/resources/css/user-center-style.css' type='text/css' media='screen' />
<style>
.myButton1{
	width: 47px;height: 26px;margin: 0px;
}
.myButton2{
	width: 53px;height: 26px;margin: 0px;
}
.myButton3{
	width: 73px;height: 26px;margin: 0px;
}
.myMargin1{
	margin-right: 10px;
}
.myMargin2{
	margin-right: 20px;
}
.myMargin3{
	margin-right: 30px;
}
.myMargin4{
	margin-left: 3px;
}
.myTd1{
	width: 35px;
	text-align: left;
}

.myTd2{
	text-align: left;
}

.logDiv{
	margin-bottom: 10px;
	border-style: solid;
	border-width: 1px;
	border-color: #000000;
}
</style>
<%@ include file="../common/top.jsp"%>
<script type="text/javascript" src="${ctx}/resources/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx}/resources/js/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/resources/js/validator.js"></script>
<%@ include file="../common/validation.jsp"%>
</head>
<title>编辑细目表</title>
<body>
 <%@ include file="../common/header.jsp"%>
    <div id="content" class="content">
        <%@ include file="../common/sub_menu.jsp"%>
        <div class="page" id="page" >
        <div class="page-header">细目表详情</div>
        <div class="page-body">
        <table class="searchTable">
	               <tr>
	                   <th>课程：</th>
	                   <td style="padding:0px 5px;">
	                       <input readonly="readonly" id="course" name="course" class="easyui-combogrid" style="width:300px;" 
	                           data-options="url:'${ctx}/course/queryByCurrentUser',
		                                   method:'get',
		                                   panelHeight:'160',
		                                   idField: 'id',
		                                   textField: 'name',
		                                   columns: [[
						                    {field:'id',title:'id',width:30},
						                    {field:'code',title:'code',width:40},
						                    {field:'name',title:'课程名称',width:160}
						                    ]],
						                    fitColumns: true,
						                    onChange: onCourseChange                    
		                                    "/>
                       </td>
                       <th>教材：</th>
	                   <td style="padding:0px 5px;">
                           <input readonly="readonly" id="book" name="book" class="easyui-combogrid" style="width:400px;" 
                               data-options="url:'${ctx}/book/queryByCourseId',
	                                         method:'get',
	                                         panelHeight:'160',
	                                         idField: 'id',
	                                         textField: 'name',
	                                         columns: [[
	                                         {field:'id',title:'id',width:40},
	                                         {field:'code',title:'编号',width:40},
	                                         {field:'name',title:'名称',width:160},
	                                         {field:'author',title:'编者',width:40},
	                                         {field:'press',title:'出版社',width:100},
	                                         {field:'version',title:'版次',width:40}
	                                         ]],
	                                         fitColumns: true,
	                                         onSelect: getSelect,
	                                         onLoadSuccess: onBookLoadSuccess	                                         
	                                          "/>
							<input id="chapterSize" name="chapterSize" type="hidden"/>
							<input id="id" name="id" type="hidden"/>
                       </td>
                  </tr>
                  <tr>
                       <th>细目表名称：</th>
	                   <td style="padding:0px 5px;"><input name="name" readonly="readonly" style="width:300px;"/></td>
                       <th>状态：</th>
	                   <td style="padding:0px 5px;">${info.statusName}</td>
	              </tr>
	             </table>
                 
	             <div style="clear:both;"></div>
	             <div id="editTables">
		             
		            <table class="listTable" style="text-align:center;margin-bottom:10px;">
		            	<tr>
		            	   <td>章节</td>
		            	<c:forEach var="x"  begin="1" end="${chapterSize}" step="1">
		            	   	<td><label>${x}</label></td>
		                </c:forEach>
		            	   <td>重点章节题量</td>
		            	   <td>重点章节分值</td>
		            	</tr>
		            	<tr>
		            		<td width="80px">重点章节:</td>
		            	<c:forEach var="x"  begin="1" end="${chapterSize}" step="1">
		            		<td width="30px" align="center"><input name ="chapters" type="checkbox" id="keyChapter${x}" value="${x}"  onclick="javascript:return false;"/></td>
		            	</c:forEach>
			            	<td width="120px" align="center" id="keyschaptertotal">${info.keyschaptertotal}</td>
			            	<td width="120px" align="center" id="keyschaptertotalscore">${info.keyschaptertotalscore}</td>
		            	</tr>
		            </table>
<c:if test="${info.status==0 || info.status==4}">
<security:authorize ifAnyGranted="PAPER_TEACHER" >
	              	<table class="listTable" style="text-align:center;margin-bottom:10px;">
	              		 <tr>
	                   		<th>题型：</th> 
	                   		<td style="padding:0px 5px;" colspan="3">
	                   			<select name="addquestionName">
	                   				<c:forEach items="${questionTypes}" var="questionType">
	                   					<option value="${questionType.id}">${questionType.name}</option>
	                   				</c:forEach>
	                   			</select>
	                   		</td>
	                   		<th>小题分：</th> <td style="padding:0px 5px;" colspan="3"><input type="text" name="addscore" /></td>
	                   		<td><button class="btn" id="addQuestion">新增</button></td>
	                   		<td><button class="btn" id="deleteQuestion">删除</button></td>
	                   	</tr>
	                   </table>
</security:authorize>
</c:if>
 <table id="tt" class="easyui-datagrid"
	 data-options="url:'${ctx}/paperSkeleton/viewskeletondetail/list',
	fitColumns:false,
	iconCls: 'icon-edit',
	singleSelect: true,
	method:'get',
	onClickCell: onClickCell,
	showFooter: true,
	striped:true">
	  <thead >
		 <tr>
			<th rowspan="3" data-options="field:'id',width:80,hidden:true">题型id</th>
			<th rowspan="3" data-options="field:'name',width:80">题型</th>
			<th colspan="${chapterSize}">题量分布</th>
			<th rowspan="3" data-options="field:'questionTypeTotalCount',width:80,align:'right'">总题量</th>
			<th rowspan="3" data-options="field:'questionScore',width:80,align:'right',editor:'numberbox'">小题分</th>
			<th rowspan="3" data-options="field:'questionTypeTotalScore',width:80,align:'right'">小计</th>
		</tr>
			            
		<tr id="chapterTotal">
			<c:forEach var="x" begin="1" end="${chapterSize}" step="1"> 
				<th data-options="field:'questionCount${x}',formatter:function(value,row,index){ return getchapterQueCount(value,row,index);},width:30,align:'right',editor:'numberbox'">${x}</th>
			</c:forEach>
		</tr>
	</thead>
 </table>
 <div style="margin-top:5px;">
<c:if test="${info.status==0 || info.status==4}">
<security:authorize ifAnyGranted="PAPER_TEACHER" >
			      <button class="btn" id="save">保存</button>
			      <button class="btn" id="delete">删除</button>
			      <button class="btn" id="submitAudit">提交审核</button>
</security:authorize>
</c:if>
<c:if test="${info.status==1}">
<security:authorize ifAnyGranted="SECRETARY" >
			      <button class="btn" id="audit">审核</button>
</security:authorize>
</c:if>
<c:if test="${info.status!=0}">
			      <button class="btn" id="auditLog">审核日志</button>
</c:if>
			      <button class="btn" id="cancel">返回</button>
</div>
<div style="display: none;">
	<div id="logListDiv" title="审核日志列表" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-import'" style="width:600px;height:340px;padding:5px;overflow-x: hidden;">
		<div id="barcode-scan" style="font-size: 12px;margin-top: 10px;">
			<div id="showLogsDiv">
					
			</div>
		</div>
	</div>
	
	<div id="auditDiv" title="审核细目表" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-import'" style="width:420px;height:250px;padding:5px;overflow-x: hidden;">
        <div id="barcode-scan" style="font-size: 12px;margin-top: 10px;">
        	<form action="#" id="formForAudit">
				<input type="hidden" name="skeletonId" value="${info.id}"/>
				<table cellpadding="5">
					<tr>
						<td nowrap="nowrap">审核结果</td>
						<td>
							<input type="radio" name="auditResult" id="approved" value="2" checked="checked"/><label for="approved" class="myMargin3">通过</label>
							<input type="radio" name="auditResult" id="rejected" value="4"/><label for="rejected">拒绝</label>
						</td>
					</tr>
					<tr>
						<td nowrap="nowrap" valign="top">审核意见</td>
						<td><textarea rows="5" cols="50" name="remark" id="auditRemark"></textarea><span id="count"></span></td>
					</tr>
					<tr>
						<td colspan="2" align="center">
							<input type="button" id="saveAuditBtn" value="确定" class="myButton1 myMargin2"/>
							<input type="button" id="cancelAuditBtn" value="取消" class="myButton1"/>
						</td>
					</tr>
				</table>
            </form>
        </div>
    </div>
</div>
</body>
</html>
<script type="text/javascript">
function reloadWin(){
	window.location.reload();
}

var keyschapter = [];
$(document).ready(function(){
	var info = '${info}';
	var courseId = '${info.courseId}';
	var bookId = '${info.bookId}';	
	$('#course').combogrid('setValue', courseId);
	$('#book').combogrid('setValue', bookId);
	$('input[name="name"]').val('${info.name}');
	$('#chapterSize').val('${chapterSize}');
	$('#id').val('${info.id}');
	var str_keyschapter = '${info.keyChapters}';
	keyschapter =  str_keyschapter.split(',');
	var str_key = '';
	var str = '';
	for(var i=0;i<keyschapter.length;i++){
		str_key = "keyChapter"+keyschapter[i];
		var a = "#"+str_key;
		$(a).attr("checked",'true');
	}
	
	{//初始化审核意见输入框字符数控制
		$("#auditRemark").keydown(function(){
	    	calculate_byte(200,'auditRemark','count');
	    });
	    $("#auditRemark").keyup(function(){
	    	calculate_byte(200,'auditRemark','count');
	    });
	    $("#auditRemark").keypress(function(){
	    	calculate_byte(200,'auditRemark','count');
	    });
	}
	
	//取消
	$('#cancel').click(function(){
		//跳入审核命题列表
		//changMenu('paperSkeleton', 'audit', '/paperSkeleton/audit');
		window.history.go(-1);
		return false;
	});
	
	 $('#deleteQuestion').click(function(){
	    	var rows = $('#tt').datagrid('getRows');
	    	var row = $('#tt').datagrid('getSelected');
	    	var index = 0;
	    	for(var i=0;i<rows.length;i++){
	    		if(rows[i]['id']==row['id']){
	    			index = i;
	    		}
	        }  
	    	$('#tt').datagrid('deleteRow',index);
	    });

	//删除细目表
	$('#delete').click(function(){
		$.messager.confirm("操作提示", "您确定要删除此细目表吗？", function (data) {
	        if (data) {
	        	$(document).mask('正在删除，请稍等...');
	        	var param = {"skeletonId":${info.id}};
	        	$.post('${ctx}/paperSkeleton/delete',param,function(res){
	    			$(document).unmask();
	    			if(res.flag=='failed'){
	    	           $.messager.alert('提示', res.msg, 'error', function () {
	    	        	   //do nothing
	    	           });
	    	           return false;
	    			}else{
	    				window.history.go(-1);
	    			}
	    		});
	        }
	    });
	});

	//提交审核
	$('#submitAudit').click(function(){
		$.messager.confirm("操作提示", "您确定要提交审核吗？", function (data) {
	        if (data) {
	        	$(document).mask('正在提交审核，请稍等...');
	        	var param = {"skeletonId":${info.id}};
	        	$.post('${ctx}/paperSkeleton/submitAudit',param,function(res){
	    			$(document).unmask();
	    			if(res.flag=='failed'){
	    	           $.messager.alert('提示', res.msg, 'error', function () {
	    	        	   //do nothing
	    	           });
	    	           return false;
	    			}else{
	    				reloadWin();
	    			}
	    		});
	        }
	    });
	});

	//审核
	$('#audit').click(function(){
		calculate_byte(200,'auditRemark','count');
		$('#auditDiv').window('open');
	});

	$("#saveAuditBtn").click(function(){
		$.messager.confirm("操作提示", "您确定要保存审核结果吗？", function (data) {
	        if (data) {
	        	$(document).mask('正在保存审核结果，请稍等...');
	        	var param = $('#formForAudit').serialize();
	        	$.post('${ctx}/paperSkeleton/saveAudit',param,function(res){
	    			$(document).unmask();
	    			if(res.flag=='failed'){
	    	           $.messager.alert('提示', res.msg, 'error', function () {
	    	        	   //do nothing
	    	           });
	    	           return false;
	    			}else{
	    				reloadWin();
	    			}
	    		});
	        }
	    });
	});
	
	$("#cancelAuditBtn").click(function(){
    	$('#auditDiv').window('close');
    });

	$('#auditLog').click(function(){
		$(document).mask('正在查询审核日志，请稍等...');
		var param = {"skeletonId":${info.id}};
		$.post('${ctx}/paperSkeleton/getAuditLogs',param,function(res){
			$(document).unmask();
			if(res.flag=='failed'){
	           $.messager.alert('提示', res.msg, 'error', function () {
	        	   //do nothing
	           });
	           return false;
			}else{
				$('#showLogsDiv').html('');
				var htmlStr = '';
				for(var i=0;i<res.auditLogs.length;i++){
					htmlStr = htmlStr + '<div class="logDiv">';
					htmlStr = htmlStr + '<div><span class="myMargin1 myMargin4">操作时间:</span><span class="myMargin3">' + res.auditLogs[i].createdTimeStr + '</span><span class="myMargin1">操作类型:</span><span class="myMargin3">' + res.auditLogs[i].operCode + '</span><span class="myMargin1">操作人:</span><span>' + res.auditLogs[i].createdByName + '</span></div>';
					htmlStr = htmlStr + '<div><table width="100%"><tr><td class="myTd1" valign ="top" nowrap="nowrap">备注:</td><td class="myTd2"><div id="logRemark' + res.auditLogs[i].id + '"></div></td></tr></table></div>';
					htmlStr = htmlStr + '</div>';
				}
				$('#showLogsDiv').html(htmlStr);
				for(var i=0;i<res.auditLogs.length;i++){
					$('#logRemark' + res.auditLogs[i].id).text(res.auditLogs[i].remark);
				}
		    	$('#logListDiv').window('open');
			}
		});
	});
});

$('#addQuestion').click(function(){
	var addquestionId = $('select[name=addquestionName]').val();
	var questionName = $("select[name=addquestionName]").find("option:selected").text(); 
	var addsorce = $("input[name=addscore]").val();
	var rows = $('#tt').datagrid('getRows');
	var index = 0;
	for(var i=0;i<rows.length;i++){
		if(rows[i]['id']==addquestionId){
			index = i+1;
		}
    }  
	  $('#tt').datagrid('insertRow',{
		index: index,	// index start with 0
		row: {
			id: addquestionId,
			name:questionName,
			questionCount1:'',
			questionCount2:'',
			questionCount3:'',
			questionCount4:'',
			questionCount5:'',
			questionCount6:'',
			questionCount7:'',
			questionCount8:'',
			questionCount9:'',
			questionCount10:'',
			questionCount11:'',
			questionCount12:'',
			questionCount13:'',
			questionCount14:'',
			questionCount15:'',
			questionCount16:'',
			questionCount17:'',
			questionCount18:'',
			questionCount19:'',
			questionCount20:'',
			questionCount21:'',
			questionCount22:'',
			questionCount23:'',
			questionCount24:'',
			questionCount25:'',
			questionCount26:'',
			questionCount27:'',
			questionCount28:'',
			questionCount29:'',
			questionCount30:'',
			questionCount31:'',
			questionCount32:'',
			questionCount33:'',
			questionCount34:'',
			questionCount35:'',
			questionCount36:'',
			questionCount37:'',
			questionCount38:'',
			questionCount39:'',
			questionCount40:'',
            questionTypeTotalCount:'',
            questionScore:addsorce,
            questionTypeTotalScore:''
		}
	});
}); 

//验证相同题型分值是否相同
function check(map,rows){     	 
   	 var result = true;
   	 $(rows).each(function(n,obj){
   		 var sce = obj['questionScore'];//每一行的小题分
   		 var question_type_id = obj['id'];//题型Id
   		 var key = obj['id']+'-'+obj['questionScore'];
	    	 if(map.indexOf(key)>-1){
		    	//$.messager.alert('提示','相同题型不允许设置相同分值!', 'error');
				result =  false;
		    }else{
		    	map.push(key); 
		    }
   	 });
   	 return result;
} 
//保存
$('#save').click(function(){
	
	 var courseId = $('#course').combogrid('getValue');
	 var bookId = $('#book').combogrid('getValue');
	 var name = $('input[name="name"]').val();
	 var chapterSize = $('#chapterSize').val();
	 var id = $('#id').val();
	 var ids = [];
	 $('input[name="chapters"]:checked').each(function(){
		 var chapter_value=$(this).val();
		 ids.push(chapter_value);
	 });
	 var idStr = ids.join(',');
	 var paperSkeleton={'id':id,'name':name,'courseId':courseId,'bookId':bookId,'chaptersCount':chapterSize,'keyChapters':idStr};
	 var rows=$('#tt').datagrid('getRows');
	 var question_type_id = '';
	 var details = [];
	 
	 var map = [];  
	 if(!check(map,rows)){
		 $.messager.alert('提示','相同题型不允许设置相同分值!', 'error');
		 return false;
	 }
	 $(rows).each(function(n,obj){
		 var question_type_id = obj['id'];//题型Id
		 var question_score;//每一行的小题分
		 var str='';//记录题量跟章节拼成"t-z"格式
		 for(var i=1;i<=chapterSize;i++){ 
			 //i是对应的第几章节数
			 var content = obj['questionCount'+i];
			 if(content=='undefined'||content==''||content==undefined){
				 //没填 
			 }else{
				 //将题量跟章节拼成"t-z"字符串
				 str = str+content+'-'+i+',';
			 }
			 //每一行的小题分
			 question_score = obj['questionScore'];
			 var questionTypeTotalCount = obj['questionTypeTotalCount'];
			 if(!(questionTypeTotalCount=='undefined'&&question_score=='undefined')){
				 if(questionTypeTotalCount=='undefined'){
					 $.messager.alert('提示','请先设置题量!');
					 return false;
				 }
				 if(question_score=='undefined'){
					 $.messager.alert('提示','请先设置小题分!');
					 return false;
				 }
			 }   			 
		   }
		 if(str.length>0){
			var object = {questiontypeId:question_type_id,questionScore:question_score,str:str};
			object = JSON.stringify(object);
			details.push(object)
		 }
	 });

	 var obj = JSON.stringify(paperSkeleton);
	 $(document).mask('正在保存细目表，请稍等...');
	 $.ajax({
			type : "POST",
			url : "${ctx}/paperSkeleton/edit/paperskeleton",
			data : "{obj:" + obj + ",details:" + "[" + details + "]"+"}",
			contentType : "application/json; charset=utf-8",
			dataType : "json",
			success : function(callback) {
				$(document).unmask();
				if(callback.flag == 'success'){
					$.messager.alert('提示', '保存成功', 'info', function () {
						reloadWin();
                    });
				}else{
					$.messager.alert('提示', "更新失败，请刷新后操作!", 'error');
				}				
			}
		});
 });

//将选择的重点章节加入全局数组中
function addKeyChapters(obj){
	if(obj.checked){
		keyschapter.push(obj.value);
	}else{
		var a = keyschapter.indexOf(obj.value);
		keyschapter.splice(a,1);
	}
	var footerRows = $('#tt').datagrid('getFooterRows'); 
	var keyschaptertotal = 0;
	var keyschaptertotalscore = 0;
	var str = '';
	for(var i=0;i<keyschapter.length;i++){
		str = "questionCount"+keyschapter[i];
		if((undefined !=footerRows[0][str])&&(!isNaN(footerRows[0][str]))){
			keyschaptertotal = keyschaptertotal + footerRows[0][str];
		}
		if((undefined !=footerRows[1][str])&&(!isNaN(footerRows[1][str]))){
			keyschaptertotalscore = keyschaptertotalscore + footerRows[1][str];
		}
	}
	$('#keyschaptertotal').html(keyschaptertotal);
	$('#keyschaptertotalscore').html(keyschaptertotalscore);
}

function onBookLoadSuccess(){
	var options = $('#book').combogrid('options');
}
function getSelect(rowIndex, rowData){
	//获取章节
	var chapterSize = rowData.chapterSize;
	$('#chapterSize').val(chapterSize);
}
function onCourseChange(){
	
	var courseId = $('#course').combogrid('getValue');
	
	$('#book').combogrid('clear');
	$('#book').combogrid('grid').datagrid('load', {'courseId':courseId});
}

$.extend($.fn.datagrid.methods, {
editCell: function(jq,param){
    return jq.each(function(){
        var opts = $(this).datagrid('options');
        var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
        for(var i=0; i<fields.length; i++){
            var col = $(this).datagrid('getColumnOption', fields[i]);
            col.editor1 = col.editor;
            if (fields[i] != param.field){
                col.editor = null;
            }
        }
        $(this).datagrid('beginEdit', param.index);
        for(var i=0; i<fields.length; i++){
            var col = $(this).datagrid('getColumnOption', fields[i]);
            col.editor = col.editor1;
        }
    });
}
});

var editIndex = undefined;
function endEditing(){
if (editIndex == undefined){return true}
if ($('#tt').datagrid('validateRow', editIndex)){
    $('#tt').datagrid('endEdit', editIndex);
    editIndex = undefined;
    return true;
} else {
    return false;
}
}
function onClickCell(index, field){
	<c:if test="${info.status==0 || info.status==4}">
    if (endEditing()){
        $('#tt').datagrid('selectRow', index)
                .datagrid('editCell', {index:index,field:field});
        editIndex = index;
        setEditing(index, field);
    }
    </c:if>
}
function setEditing(index, field){
    var editors = $('#tt').datagrid('getEditors', index);
    var questionCount = editors[0];
    if(undefined != questionCount){
        $(questionCount.target).focus();
        questionCount.target.bind('keyup', function(){
        	//alert($(questionCount.target).val());
            calculate();
        });
    }
    var chapterSize = '${chapterSize}';
    
    function calculate(){
    	
        var rows = $('#tt').datagrid('getRows');
        var row = rows[index];
        var questionTypeTotalCount = questionCount.target.val(); //获取编辑框的值
        var totalquestion = 0;
        if(field=='questionScore'){//编辑框是小题分，就不应该重新算总题量
        	var totalCount = row['questionTypeTotalCount'];
        	if(undefined != totalCount){
        		var questionTypeTotalScore = totalCount * questionTypeTotalCount;
	            row['questionTypeTotalScore'] = questionTypeTotalScore;
        	}
        }else{//编辑框是章节
        	
            for(var i = 0; i < chapterSize; i++){
                var fieldName = "questionCount" + (i+1); 
                if(field == fieldName){
                	if($.trim(questionCount.target.val()).length>0){
            			totalquestion = parseInt(totalquestion) + parseInt(questionCount.target.val());
                	}
                }else{
            		if(undefined != row[fieldName]){
	                	if($.trim(row[fieldName]).length>0){
	                		totalquestion = parseInt(totalquestion) + parseInt(row[fieldName]);
	                	}
	                }
            		
            	}
            } 
        	
            row['questionTypeTotalCount'] = totalquestion;
        	
            var questionScore = row['questionScore'];
            if(undefined !=questionScore){
	            var questionTypeTotalScore = row['questionTypeTotalCount'] * row['questionScore'];
	            row['questionTypeTotalScore'] = questionTypeTotalScore;
            }
        }
    
        

        var footerRows = $('#tt').datagrid('getFooterRows'); 
         
        //计算章节的总题量
        var chapterQuestionCount = 0
        var tmpValue = questionCount.target.val(); //获取编辑框的值
	    for(var i=0;i<rows.length;i++){
	    	if(i==index){
	    		if($.trim(tmpValue).length>0){
	    			chapterQuestionCount = parseInt(chapterQuestionCount) + parseInt(tmpValue);		    			
	    		}
	    	}else{
	    		if(undefined != rows[i][field] && $.trim(rows[i][field]).length>0){
	    			chapterQuestionCount = parseInt(chapterQuestionCount) + parseInt(rows[i][field]);		    		
	    		}
	    	}
	    }
        footerRows[0][field] = chapterQuestionCount;
        
        var keyschaptertotal = 0;
        var keyschaptertotalscore = 0;
        
		
        
        
        var chapterQuestionScore = 0;
        //计算footerRows[1]需重新算，计算章节的总题分
         if(field=='questionScore'){//编辑框是小题分,需重新计算所有的列
        	 for(var i = 0; i < chapterSize; i++){
    			 var fieldName = "questionCount" + (i+1);
    			 var a = 0;
    			 for(var j=0;j<rows.length;j++){
    				 if(j==index){ //编辑行需单独计算
        				 if(($.trim(rows[j][fieldName]).length>0)&&(undefined != rows[index][fieldName])&&(!isNaN(rows[index][fieldName]))&&($.trim(questionCount.target.val()).length>0)){
 		        			a = parseInt(a) +  parseInt(questionCount.target.val())* parseInt(rows[index][fieldName]);
        				 }
        			 }else{
	        			 if(($.trim(rows[j][fieldName]).length>0)&&(undefined !=rows[j][fieldName])&&(undefined !=rows[j][field])&&($.trim(rows[j][field]).length>0)){
	        				a = parseInt(a) + parseInt(rows[j][fieldName])*parseInt(rows[j]['questionScore']);
	        			 }
        			 }
    				 footerRows[1][fieldName] = a;
        		 }  	
        	 }
            	
        }else{//编辑的是章节
	        for(var i=0;i<rows.length;i++){
	        	if(i==index){//编辑行需单独计算
	        		if((undefined != rows[index]['questionScore'])&&($.trim(rows[index]['questionScore']).length>0)&&(!isNaN(questionCount.target.val()))&&($.trim(questionCount.target.val()).length>0)){
	        			chapterQuestionScore = parseInt(chapterQuestionScore) +  parseInt(questionCount.target.val())* parseInt(rows[index]['questionScore']);
	        		}
	        	}else{
		        	if((undefined != rows[i][field])&&($.trim(rows[i][field]).length>0)){
		        		if(undefined != rows[i]['questionScore']){
		        			chapterQuestionScore = parseInt(chapterQuestionScore) +  parseInt(rows[i][field])* parseInt(rows[i]['questionScore']);
		        		}
		        	}
	        	}
	        }
	        footerRows[1][field] = chapterQuestionScore;
	        chapterQuestionScore = 0;
        }
         
         //计算重点章节总题量
	       if(field=='questionScore'){
	        	//编辑的是小题分，重点不作处理，重点章节分值需重新算
	        	for(var i=0;i<keyschapter.length;i++){
	        		str = "questionCount"+keyschapter[i];	        			
	        		if((undefined !=footerRows[1][str])&&(!isNaN(footerRows[1][str]))){
	        				keyschaptertotalscore = keyschaptertotalscore + footerRows[1][str];
	        		}
	        	}
	        	$('#keyschaptertotalscore').html(keyschaptertotalscore);
	        }else{//编辑的是章节
	        	var b = field.substring(field.length-1,field.length);
	        	var str = '';
	        	if(keyschapter.indexOf(b)>=0){
	        		var keyschaptertotal = 0;
	        		var keyschaptertotalscore = 0;
	        		for(var i=0;i<keyschapter.length;i++){
	        			str = "questionCount"+keyschapter[i];
	        			if((undefined !=footerRows[0][str])&&(!isNaN(footerRows[0][str]))){
	        				keyschaptertotal = keyschaptertotal + footerRows[0][str];
	        			}
	        			if((undefined !=footerRows[1][str])&&(!isNaN(footerRows[1][str]))){
	        				keyschaptertotalscore = keyschaptertotalscore + footerRows[1][str];
	        			}
	        		}
	        		$('#keyschaptertotal').html(keyschaptertotal);
	        		$('#keyschaptertotalscore').html(keyschaptertotalscore);
				}
	        }   
        
        var questionCountTotal = 0;
        var questionScoreTotal = 0;
        for(var i=0;i<rows.length;i++){
        	if(undefined != rows[i]['questionTypeTotalScore']){
        		questionScoreTotal = questionScoreTotal + rows[i]['questionTypeTotalScore'];
        	} 
        	if(undefined != rows[i]['questionTypeTotalCount']){
        		questionCountTotal = parseInt(questionCountTotal) + parseInt(rows[i]['questionTypeTotalCount']);
        	}
        } 
        
        footerRows[0]['questionTypeTotalCount'] = questionCountTotal;
        footerRows[0]['questionScore'] = '';
        footerRows[0]['questionTypeTotalScore'] = questionScoreTotal;
        
        
        footerRows[1]['questionTypeTotalCount'] = questionCountTotal;
        footerRows[1]['questionScore'] = '';
        footerRows[1]['questionTypeTotalScore'] = questionScoreTotal;
        $('#tt').datagrid('reloadFooter'); 
    }
    
} 
function getchapterQueCount(value,row,index){
	if(value==0){
		return '';
	}else{
		return value;
	}	
}

</script>
        