function questionChange(){
	var typeName = $("#quesTypeId").find("option:selected").text();
	if(typeName=="单项选择题" || typeName=="单选题" || typeName=="单选"){
		$("#answer_td").text("选项及答案");
		$("#Choose").show();
        $(".RadioContent").show();
        $(".CheckboxContent").hide();
        $("#answer-content").hide();
        $(".radioAdd").html("");
	}else if(typeName=="多项选择题" || typeName=="多选题" || typeName=="多选"){
		$("#answer_td").text("选项及答案");
		$("#Choose").show();
        $(".CheckboxContent").show();
        $(".RadioContent").hide();
        $("#answer-content").hide();
        $(".checkboxAdd").html("");
	}else{
		$("#answer_td").text("答案");
		$("#answer-content").show();
		$("#Choose").hide();
	}
}
 
function clean(){
	if (!$(".CheckboxContent").is(":hidden")) {
        $(".CheckboxContent").html("");
    }
    if (!$(".RadioContent").is(":hidden")) {
        $(".RadioContent").html("");
    }
}
function add(){
	if(($(".CheckboxContent .row").length=="26")&&(!$(".CheckboxContent").is(":hidden"))){
		alert("无法继续添加选项!");
		return;
	}else if(($(".RadioContent .row").length=="26")&&(!$(".RadioContent").is(":hidden"))){
		alert("无法继续添加选项!");
		return;
	}
	var Arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
	if (!$(".CheckboxContent").is(":hidden")) {
		var v=Arr[$(".CheckboxContent .row").length];
		var id=v+"_"+"checkbox_input";
		var input=v+"_"+"checkbox_hidden";
        $(".CheckboxContent").append
        (" <div class=\"row\"><label class=\"col-lg-1 col-sm-1 checkbox-inline\"><input type=\"checkbox\"  name=\"optionsCKs\" value="+v+"  class=\"validate[required] checkbox\" />" 
        		+ v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a><div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input  listInput\" id="
        		+id+"   style=\"width: 350px;\" readonly=\"readonly\" /></div><div id="+v+"_checkbox_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+" /></div></div>");
    }
    if (!$(".RadioContent").is(":hidden")) {
    	var v=Arr[$(".RadioContent .row").length];
    	var id=v+"_"+"radio_input";
    	var input=v+"_"+"radio_hidden";
        $(".RadioContent").append
        (" <div class=\"row\"><label class=\"col-lg-1 col-sm-1\"><input class=\"validate[required] radio \" type=\"radio\" name=\"optionsRadios\"   value="+v+" />" 
        		+v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a> <div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input listInput\" id="
        		+id+"   style=\"width: 350px;\" readonly=\"readonly\" /></div><div id="+v+"_radio_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+" /></div></div>");
    }
}
function del($this){
	$this=$($this);
	var str=$this.parent().find("input").val();
	var num=str.charCodeAt()-65;
	$this.parent().remove();
	var Arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
	if (!$(".CheckboxContent").is(":hidden")) {
		$(".CheckboxContent .row").each(function(i){
			if(i>=num){
				var v=Arr[i];
				var text_value=$("#"+Arr[i+1]+"_checkbox_hidden").val();
				 var input_value=$("#"+Arr[i+1]+"_checkbox_input").val();
				var id=v+"_"+"checkbox_input";
				var input=v+"_"+"checkbox_hidden";
				if(input_value==""){
					$(this).html("<label class=\"col-lg-1 col-sm-1 checkbox-inline\"><input type=\"checkbox\"  name=\"optionsCKs\" value="+v+"  class=\"validate[required] checkbox\" />" 
			        		+ v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a><div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input  listInput\" id="
			        		+id+"   style=\"width: 350px;\" readonly=\"readonly\"  value=''   /></div><div id="+v+"_checkbox_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+" /></div>");
				}else{
					$(this).html("<label class=\"col-lg-1 col-sm-1 checkbox-inline\"><input type=\"checkbox\"  name=\"optionsCKs\" value="+v+"  class=\"validate[required] checkbox\" />" 
			        		+ v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a><div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input  listInput\" id="
			        		+id+"   style=\"width: 350px;\" readonly=\"readonly\"  value="+input_value+"   /></div><div id="+v+"_checkbox_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+" /></div>");
				}
				$("#"+input).val(text_value);
			}
		});
	}
	if (!$(".RadioContent").is(":hidden")) {
		 $(".RadioContent .row").each(function(i){
			 if(i>=num){
				 var v=Arr[i];
				 var text_value=$("#"+Arr[i+1]+"_radio_hidden").val();
				 var input_value=$("#"+Arr[i+1]+"_radio_input").val();
				 var id=v+"_"+"radio_input";
				 var input=v+"_"+"radio_hidden";
				 if(input_value==""){
					 $(this).html("<label class=\"col-lg-1 col-sm-1\"><input class=\"validate[required] radio \" type=\"radio\" name=\"optionsRadios\"   value="+v+" />" 
				        		+v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a> <div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input listInput\" id="
				        		+id+"   style=\"width: 350px;\" readonly=\"readonly\"  value=''        /></div><div id="+v+"_radio_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+"   /></div>");
				 }else{
					 $(this).html("<label class=\"col-lg-1 col-sm-1\"><input class=\"validate[required] radio \" type=\"radio\" name=\"optionsRadios\"   value="+v+" />" 
				        		+v + ".</label><a  onclick=\"del(this)\" href=\"javascript:void(0)\">删除</a> <div class=\"col-lg-5 col-sm-5\"><input class=\"validate[required] text-input listInput\" id="
				        		+id+"   style=\"width: 350px;\" readonly=\"readonly\"  value=" +input_value+ "        /></div><div id="+v+"_radio_div class=\"list\" field=\"answer\" name=\"答案\" title=\"点击输入内容\"><input type=\"hidden\" id="+input+"   /></div>");
				 }
				 $("#"+input).val(text_value);
			 }
		});
	 }
}

function getRadioIds(){
	var length=$("input[name=optionsRadios]").length.toString();		//radio的个数
	if(length != 4){
		alertify.error("单项选择题选项应该为4个!");
		return "false";
	}
	var str=$("input[name=optionsRadios]:checked").val();				//被选中的按钮
	if(!str){
		alertify.error("请设置一个选项为答案!");
		return "false";
	}
	var code=str.charCodeAt(0);											//被选中按钮转ascii
	var correctOption=code-65;											//被选中的-65转成与数据库对应的数据
	var arr = new Array();
	var arr1=new Array();
	for(var i=0;i<length;i++){
		var isCorrectOption=0;
		if(i==correctOption){
			isCorrectOption=1;
		}
		var str=(String.fromCharCode(i+65));
		arr1.push($("#"+str+"_radio_input").html());
		var obj = {
			"id" :  $("#"+str+"_radio_id").val(),
			"optionNo" : i,
			"isCorrectOption" : isCorrectOption,
			"content" : $("#"+str+"_radio_input").html(),
			"summary" :$("#"+str+"_radio_input").text()
		};
		arr.push(JSON.stringify(obj));
	}
	var nary=arr1.sort();
	for(var i=0;i<arr1.length;i++){
		if(nary[i] == '' || nary[i] == '<br>'){
			alertify.error("选项不能为空，请输入!");
			return "false";
		}
		if(nary[i]==nary[i+1]){
			alertify.error("选项不能重复，请重新修改!");
			return "false";
		}
	}
	return arr;
}

function getCheckBoxIds(){
	var length=$("input[name=optionsCKs]").length.toString();
	if(length != 5){
		alertify.error("多项选择题选项应该为5个!");
		return "false";
	}
	var strarr = new Array();
	 $("input[name=optionsCKs]:checked").each(function(){
		strarr.push( $(this).val());
	});
	if(strarr.length == 0){
		alertify.error("请至少设置一个选项为答案!");
		return "false";
	}
	var correctArr=new Array();
	var arr1=new Array();
	for(var i=0;i<strarr.length;i++){
		var code=strarr[i].charCodeAt(0);
		var correctOption=code-65;
		correctArr.push(correctOption);
	}
	var arr = new Array();
	for(var i=0;i<length;i++){
		var isCorrectOption=0;
		if($.inArray(i, correctArr)!=-1){
			isCorrectOption=1;
		}
		var str=(String.fromCharCode(i+65));
		arr1.push($("#"+str+"_checkbox_input").html());
		var obj = {
				"id" : $("#"+str+"_checkbox_id").val(),
				"optionNo" : i,
				"isCorrectOption" : isCorrectOption,
				"content" : $("#"+str+"_checkbox_input").html(),
				"summary" :	$("#"+str+"_checkbox_input").text()
		};
		arr.push(JSON.stringify(obj));
	}
	var nary=arr1.sort();
	for(var i=0;i<arr1.length;i++){
		if(nary[i] == '' || nary[i] == '<br>'){
			alertify.error("选项不能为空，请输入!");
			return "false";
		}
		if(nary[i]==nary[i+1]){
			alertify.error("选项不能重复，请重新修改!");
			return "false";
		}
	}
	return arr;
}

function validationBodyAnswer(){
	if($("#body-content").text()==""){
		alertify.error("题干不能为空，请输入!");
		$("#body-content").focus();
		return false;
	}
	var typeName = $("#quesTypeId").find("option:selected").text();
	if(typeName!="单项选择题" && typeName!="单选题" && typeName!="单选" && typeName!="多项选择题" && typeName!="多选题" && typeName!="多选"){
		if ($("#answer-content").text()==""){
			alertify.error("答案不能为空!");
			return false;
		}else{
			return true;
		}
	}else{
		return true;
	}
	
}

function validateBaseInfo(){
	var chapter=$("#chapter").val();
	if(chapter == ''){
		alertify.error("知识点--章不能为空，请输入!");
		$("#chapter").focus();
		return false;
	}
	chapter = parseInt(chapter) - 0;
	if(!chapter || chapter <= 0){
		alertify.error("知识点--章必须为正整数，请重新输入!");
		$("#chapter").select();
		$("#chapter").focus();
		return false;
	}
	return true;
}

function toDate(str){     
    if(str && str.length > 0){
    	var reg = /^(\d{4})-(\d{1,2})-(\d{1,2})$/
    	var result = str.match(reg);
    	if(result != null){
    		var year = result[1] - 0;
    		var month = result[2] - 0;
    		var day = result[3] - 0;
    		var d = new Date(year, month-1, day);
            if(d.getFullYear() == year && (d.getMonth() + 1) == month && d.getDate() == day){
            	return d;
            }
    	}
	}
	return null;
}

function goSave(url){
	var isValid =  validateBaseInfo();
	if(isValid){
		if(validationBodyAnswer()){
			var id = $("#quesId").val();
			var courseId=$("#courseId").val();														//课程id
			var questionNo=$("#questionNo").val();													//题号
			var typeId=$("#quesTypeId").val();														//题型id
			var typeName = $("#quesTypeId").find("option:selected").text();
			var bookId=$("#bookId").val();															//教材id
			var enableTimeYear = $('#enableTimeYear').val();
			var enableTimeMonth = $('#enableTimeMonth').val();
			if(enableTimeYear != '' && !(/^[1-2][0-9]{3}$/.test(enableTimeYear))){
				alertify.error("请输入正确的年份");
				$('#enableTimeYear').focus();
				return false;
			}
			if(enableTimeYear != '' && enableTimeMonth == ''){
				alertify.error("请选择月份");
				$('#enableTimeMonth').focus();
				return false;
			}
			if(enableTimeYear == '' && enableTimeMonth != ''){
				alertify.error("请输入年份");
				$('#enableTimeYear').focus();
				return false;
			}
			/**
			var enableTime = $("input[name='enableTime']").val();									//启用时间
			if(enableTime != '' && toDate(enableTime) == null){										//验证启用时间
				alertify.error('提示', "请输入正确的日期，格式：yyyy-mm-dd", 'error',function(){
					$('#enableTime').datebox("showPanel");
				});
				return false;
			}
			**/
			var setTime = toDate($("input[name='setTime']").val());				//命题时间
			if(setTime == null){												//命题时间必填
				alertify.error("请输入正确的日期，格式：yyyy-mm-dd");
				$('#setTime').datebox("showPanel");
				return false;
			}
			var bookEnableDate = bookEnableDateMap[bookId];
			if(bookEnableDate){
				if(setTime != null){
					bookEnableDate = new Date(bookEnableDate);
					bookEnableDate.setHours(0);
					bookEnableDate.setMinutes(0);
					bookEnableDate.setSeconds(0);
					if(bookEnableDate.getTime() > setTime.getTime()){
						alertify.error('提示', "命题时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
						$('#setTime').datebox("showPanel");
						return false;
					}
				}
			}else{
				alertify.error("当前选中的教材没有配置教材启用时间，请与业务管理员联系。");
				return false;
			}
			var enableTime = '';
			if(enableTimeYear != ''){
				//enableTime = enableTimeYear + "-" + enableTimeMonth + "-1";
				enableTime = new Date();
				enableTime.setFullYear(enableTimeYear);
				enableTime.setMonth(enableTimeMonth - 1);
				enableTime.setDate(1);
				enableTime.setHours(0);
				enableTime.setMinutes(0);
				enableTime.setSeconds(0);
				if(setTime != null){
					setTime.setHours(0);
					setTime.setMinutes(0);
					setTime.setSeconds(0);
					if(setTime.getTime() > enableTime.getTime()){
						alertify.error("命题时间不能大于试题启用时间，请重新填写。");
						return false;
					}
				}
				if(bookEnableDate){
					bookEnableDate.setHours(0);
					bookEnableDate.setMinutes(0);
					bookEnableDate.setSeconds(0);
					if(bookEnableDate.getTime() > enableTime.getTime()){
						alertify.error("试题启用时间不能小于教材启用时间[" + bookEnableDate.getFullYear() + "-" + (bookEnableDate.getMonth() + 1) + "]");
						return false;
					}
				}
				enableTime = enableTimeYear + "-" + enableTimeMonth + "-1";
			}
			setTime = $("input[name='setTime']").val();												//命题时间
			var setTeacherName = $("#setTeacherName").val();										//命题教师
			var assessmentDemand=$('input[name="assessmentDemand"]:checked').val();
			var estimateDifficultyCode=$('input[name="estimateDifficultyCode"]:checked').val();		//预计难度
			var gradeCode=$('input[name="gradeCode"]:checked').val();								//层次
			var abilityCode=$('input[name="abilityCode"]:checked').val();							//能力要求
			var chapter=$("#chapter").val();														//章
			var section=$("#section").val();														//节
			var item=$("#item").val();															//目
			var page=$("#page").val();																//页
			var score=$("#score").val();															//满分值
			var body=$("#body-content").html();														//题干
			var bodySummary=$("#body-content").text();
			var answer="";
			var answerSummary="";
			var arr = new Array();
			if(typeName!="单项选择题" && typeName!="单选题" && typeName!="单选" && typeName!="多项选择题" && typeName!="多选题" && typeName!="多选"){
				answer=$("#answer-content").html();													//答案
				answerSummary=$("#answer-content").text();
			}else{
				if(typeName=="单项选择题" || typeName=="单选题" || typeName=="单选"){
					arr=getRadioIds();
					if(arr=="false"){
						return;
					}
				}else{
					arr=getCheckBoxIds();
					if(arr=="false"){
						return;
					}
				}
			}
			var remark=$("#remark").val();															//备注
			var obj = {
					"id"	:	id,
					"assessmentDemand":assessmentDemand,													//考核要求
					"courseId" : courseId,																	//课程id
					"questionNo" : questionNo,																//题号
					"typeId": typeId,																		//题型id
					"bookId" : bookId,																		//教材id
					"enableTime":enableTime,																//启用时间
					"setTime":setTime,																		//命题时间
					"setTeacherName":setTeacherName,														//命题教师
					"estimateDifficultyCode" : estimateDifficultyCode,										//预计难度
					"gradeCode" : gradeCode,																//层次
					"abilityCode" : abilityCode,															//能力要求
					"chapter" : chapter,																	//章
					"section" : section,																	//节
					"item" : item,																			//目
					"page" : page,																			//页
					"score" :  score,																		//满分值
					"body" : body,																			//题干
					"bodySummary" :bodySummary,
					"answer" : answer,																		//答案
					"answerSummary" : answerSummary,
					"remark" : remark																		//备注
				};
			var Question = JSON.stringify(obj);
			$(document).mask('正在保存试题，请稍等...');
			$.ajax({
				type : "POST",
				url : url + "/question/save?paperId=0",
				data : "{Question:" + Question + ",arr:" + "[" + arr + "]" + "}", 
				contentType : "application/json; charset=utf-8",
				dataType : "json",
				success : function(callback) {
					$(document).unmask();
					//console.log(callback);
					//callback = eval(callback);
					if(callback.flag=='failed'){
						alertify.error(callback.msg);
					}else{
						if(saveType == 'ADD'){
							$('#body-content').html('');
							$('#A_radio_input').html('');
							$('#B_radio_input').html('');
							$('#C_radio_input').html('');
							$('#D_radio_input').html('');
							
							$('#A_checkbox_input').html('');
							$('#B_checkbox_input').html('');
							$('#C_checkbox_input').html('');
							$('#D_checkbox_input').html('');
							$('#E_checkbox_input').html('');
							
							$("input:radio[name='optionsRadios']:checked").removeAttr("checked");						
							$("input:checkbox[name='optionsCKs']:checked").removeAttr("checked");
							
							$('#answer-content').html('');
							$('#answerSheet').html('');
							$('#remark').val('');
							$('#infoTable tr:gt(0)').remove();
							//alertify.error('提示', "新增试题成功!", 'info');
							addQuesIntoPaper(url,callback.question.id);
						}else{
							updateQuesIntoPaper(url,$("#quesId").val(),callback.question.id);
						}
					}
				}
			});
		}
	}
}

function addQuesIntoPaper(url,quesId){
	window.parent.refreshTbl();
	alertify.confirm("新增试题成功，是否继续新增试题？", function (data) {
        if(!data) {
        	parent.closeAddQuestionDiv();
        }
	});
}

function updateQuesIntoPaper(url,oldQuesId,newQuesId){
	window.parent.refreshTbl();
	alertify.success('保存试题成功。');
	//parent.closeEditQuestionDiv();
}