var realTest = 0;
var rndST = 0;
var typeArr = new Array();
var box='';
var examInstallDir='';
var index = 0;
var len = 0;
var from3g = false;
var ty = 0;
var rndType = 0;
var xtIndex = 0;
/**
 * 新增方法组
 * @module  examMethods
 * @author  zhuang
 * @adddate 2018/5/14
 * @version 5.5
 */
window.examMethods = new Object();

/**
 * 获取当前做题的id
 * @method getTimId
 * @for    examMethods
 * @param  {Object} target [dom对象]
 */
examMethods.getTimId = function(target){
	
	var tmid = $(target).attr('tmid');
	if(tmid.indexOf('sub') !== -1){
		
		tmid = tmid.match(/\d+/);
		!$('#page_card').find('[tmid="'+tmid+'"]').length && (tmid = $(target).parents('.sjlist').find('input[name="tmid"]')[0].value)
		
	}
	
	return tmid
	
   
};

examMethods.getId = function(id){
	return document.getElementById(id) ? document.getElementById(id) : false
};

/**
 * 改变做题状态
 * @param {String} timid [题目id]
 * @param {String} type  [done 已做,notDone 未做,sign 标记,removeSign 取消标记]
 */
examMethods.setTimStatus = function(timid,type){
	
	var $timItem = $('#page_card').find('[tmid="'+timid+'"]');
	switch (type){
		case "done":
			$timItem.attr('style','background:#aaa;color: #fff;border:1px solid #aaa;').addClass('done')
			break;
		case "notDone":
			$timItem.attr('style','')
			break;
		case "sign":
			$timItem.addClass('sign-finish')
			break;
		case "removeSign":
			$timItem.removeClass('sign-finish')
			break;
    }

	
}

/**
 * 页面初始化
 */

$(window).load(function() {

    var $content = $('#content');
    $content.on('click', '.dx_button input', function() {
        this.type === 'radio' && $(this).parent().siblings('.dx_button_xz').attr('class', 'dx_button');
        $(this).parent()[0].className = 'dx_button_xz';
        examMethods.setTimStatus(examMethods.getTimId(this), 'done');
        getAnswer();
        this.type === 'radio' && from3g && typeof next === 'function' && next()
    });
    $content.on('click', '.dx_button_xz input', function() {
        if (this.type === 'checkbox') {
            $(this).parent()[0].className = 'dx_button';
            !$(this).parent().siblings('.dx_button_xz').length && examMethods.setTimStatus(examMethods.getTimId(this), 'notDone');
            getAnswer();
        }
    });

    $content.on('keyup', '.zgtdtq', function() {
        this.value ?
    		examMethods.setTimStatus(examMethods.getTimId(this), 'done') :
    		examMethods.setTimStatus(examMethods.getTimId(this), 'notDone');
        getAnswer()
    });

    $content.on('keyup', '.anstext', function() {
        var notEmpty = false;
        $(this).parents('.sjlist').find('.anstext').each(function() {
            if (this.value.replace(/\s+/)) {
                notEmpty = true
            }
        });

        notEmpty ? examMethods.setTimStatus(examMethods.getTimId(this), 'done') :
    			  examMethods.setTimStatus(examMethods.getTimId(this), 'notDone');
        getAnswer()
    })

});


function loadPageInitial(obj,typeid){
	
	if (obj!=this){
		document.documentElement.scrollTop = 0;
	}
    if (obj != null) {
		if (obj!=this){
	        $("input[name=btn]").attr("class", "topInput");
	        obj.className = 'topInputOver';
	        $("input[id=" + obj.id + "]").attr("class", "topInputOver");
	        obj.blur();
		}

	}
	

	$("#pid").val(typeid);

    
}

//进度
function thetotal() {     
    var leavenum0 = getNoFinishTMS();   
    var c = totalTMS - leavenum0;
    $("#theindex").html(c)
}

//=======================================================================begin
var allTest = 0;
var OverTest = 0;

function LoadFillBlank(answers) {
   answers = answers.replace(/#br#/g, "\n");
    var arr = answers.split('※');
    var i = 0;
    $(".xtcontentclass").find("input").each(function () {
        $(this).val(arr[i++]);
    });
    $(".zgtdtq").val(arr[0]);
}


function ToMyExams2(sjid, userid) {
    if (userid == 0)
        showuserlogin();
    else {
        SaveAnswer(0, sjid,1);
    }
    //window.navigate('/exam/ExCard.aspx?id='+sjid+'&status=0');
}

//3G答题方式索引

function clear3gIndex()
{

  $("div.sjlist").hide().eq(index).show();
    
}


//=======================================================================end
function loadPage(obj, typeid, isexplain, scoreid) {
	document.getElementById('content').className = 'Election'+typeid
    
    examInstallDir = "/plus/exam/";
    loadPageInitial(obj, typeid);
	if (obj == this) {
	    return;
	} //保存答案退出
	jQuery("#MaskLayer").show();

	if (typeArr[typeid] != undefined) {
		jQuery('#content').html(typeArr[typeid]).find('.sjlist').eq(xtIndex).show()
		setValue();
		jQuery("#MaskLayer").hide();
		typeof examLoadedCallBack === 'function' && examLoadedCallBack()
	} else {
	    jQuery.get(examInstallDir + 'GetSJAjax.ashx', { action: "getst1", realTest: realTest, rndst: rndST, isexplain: isexplain, ScoreID: scoreid, typeid: typeid, istjda: isTjDa, bo: $("#bo").val() }, function (d) {
	        
	        if ($("input[name=btn]").length == 1)
	        { d = d.replace(/第 一 大题/, ''); }

	        typeArr[typeid] = d; 
			$('#content').html(d).find('.sjlist').eq(xtIndex).show();
			
	        //3G执行部份
	        if (from3g==true) {
	            clear3gIndex();
	        }
          
	        if (d != '') {
				setValue();
				typeof examLoadedCallBack === 'function' && examLoadedCallBack()
			}
	        else { $('#content').html('找不到试题！'); }
	    });

	    jQuery("#MaskLayer").hide();
	}
    
}

//随机出题
function loadRndPage(obj, typeid,isexplain,scoreid) {
    loadPageInitial(obj,typeid);
    
	if (obj==this){return;} //保存答案退出
	jQuery("#MaskLayer").show();
	
	examInstallDir = "/plus/exam/";
	if (typeArr[typeid]!=undefined){
		jQuery('#content').html(typeArr[typeid]);
		setValue();
		jQuery("#MaskLayer").hide();
	} else {
	    jQuery.get(examInstallDir + 'GetSJAjax.ashx', { action: "getst2", realTest: realTest, rndst: rndST, isexplain: isexplain, ScoreID: scoreid, typeid: typeid, istjda: isTjDa, sjid: $("#sjid").val(), bo: $("#bo").val() }, function (d)
	    {
	        if ($("input[name=btn]").length == 1)
	        {
	            d = d.replace(/第 一 大题/, '');
	        }
	        typeArr[typeid] = d;
	        jQuery('#content').html(d);
	        
	        //3g
	         if (from3g == true)  {
	            clear3gIndex();
	        }

	        if (d != '')
	        {
	            setValue();
	        }
	        else { jQuery('#content').html('找不到试题！'); }
	    });
    jQuery("#MaskLayer").hide();
	}
}
function loadRndRank(obj, typeid, isexplain, scoreid, isTraining) {
	
    examInstallDir = "/plus/exam/";
    loadPageInitial(obj, typeid);
    
    if (obj == this) { return; } //保存答案退出
   
    jQuery("#MaskLayer").show();
    if (typeArr[typeid] != undefined) {
        jQuery('#content').html(typeArr[typeid]);
        setValue();
        jQuery("#MaskLayer").hide();
    } else {
     
        jQuery.get(examInstallDir + 'GetSJAjax.ashx', { action: "getst3", isTraining: isTraining, realTest: realTest, rndst: rndST, isexplain: isexplain, ScoreID: scoreid, typeid: typeid, istjda: isTjDa, sjid: $("#sjid").val(), bo: $("#bo").val() }, function (d)
        {
            typeArr[typeid] = d;
            jQuery('#content').html(d);
            
            //3G执行部份
            if (from3g == true) {
                clear3gIndex();
            }
            
            if (d != '')
            { setValue(); } else { jQuery('#content').html('找不到试题！'); }
        });
        jQuery("#MaskLayer").hide();
    }
}

//*******************************//
function loadMytrainPage(obj, typeid, isexplain, scoreid) {
   
    loadPageInitial(obj, typeid);
    if (obj == this) { return; } //保存答案退出
    jQuery("#MaskLayer").show();
    if (typeArr[typeid] != undefined) {
        jQuery('#content').html(typeArr[typeid]);
        setValue();
        jQuery("#MaskLayer").hide();
    } else {
      examInstallDir="/plus/exam/";
        jQuery.get(examInstallDir + 'GetSJAjax.ashx', { action: "getst4", realTest: 0, rndst: 0, isexplain: 0, ScoreID: scoreid, typeid: typeid, istjda: isTjDa, sjid: $("#sjid").val(), bo: $("#bo").val() }, function (d) {
          
            if ($("input[name=btn]").length == 1)
            { d = d.replace(/第 一 大题/, ''); }
            typeArr[typeid] = d;
            jQuery('#content').html(d);
            
            ////3g热行部份
            if (from3g == true) {
                clear3gIndex();
            }

            if (d != '')
            { setValue(); }
            else {
                jQuery('#content').html('找不到试题！');
            }
        });
        jQuery("#MaskLayer").hide();
    }
}


function SaveAnswer(isrnd,sjid,flag){
	
    if (isrnd==3){
		 loadRndPage(this,$("#pid").val(),0,0);
    } else if (isrnd == 1) {
       
        loadPage(this, $("#pid").val(), 0, 0);
    } else {
        getAnswer();
    }
   
    var tmanswer = '';
    if (isrnd == 2) {
        tmanswer = "1↓↑" + jQuery("#ans1").text();
     
    } else {
        jQuery(".hidans").each(function (i) {
        
            if (i == 0) {
                tmanswer = jQuery(this).attr('typeid') + '↓↑' + jQuery(this).val();
            } else {
                tmanswer += '↓◎↑' + jQuery(this).attr('typeid') + '↓↑' + jQuery(this).val();
            }
        });
    }
   
   var totalTMS=getTotalTMS(); //总题目数
   var noFinishTMS = getNoFinishTMS(); //未做完的题目数
 
   jQuery.post(examInstallDir+'GetSJAjax.ashx',{ action: "saveanswer", realTest: realTest, sjid: sjid, answer: tmanswer, hasusetime: jQuery("#HasUseTime").val(), totalTMS: totalTMS, noFinishTMS: noFinishTMS },

       function (d) {
           
       if (d == "locked") {
		clearInterval(tv);
		getAnswer();
		KesionJS.Alert("对不起，您已被踢出考场，系统强制提交！","jQuery('#myform').submit();"); 
	 }else if (d.indexOf('warning')!=-1){
		 var arr=d.split('|');
		 if (arr[1]==1){
		     box=jQuery.dialog.open(examInstallDir+"showWarning.aspx?rnd="+Math.random()+"&flag=1&sjid="+sjid+"&scoreid="+arr[2],{title:'警告',width:500,height:250,lock:true,min:false,max:false});
		 }else{
		     box=jQuery.dialog.open(examInstallDir+"showWarning.aspx?rnd="+Math.random()+"&flag=2&sjid="+sjid+"&scoreid="+arr[2],{title:'通知',width:500,height:250,lock:true,min:false,max:false});
		 }
	 } else if (d == 'success') {	    
           if (realTest == 0 ||realTest ==3) {
              
          		jQuery.dialog.tips('恭喜，答案保存成功!', 2, 'success.gif', function () { });
              
           }
           if (flag == 5 && realTest == 1) {
                jQuery.dialog.tips('恭喜，答案保存成功!', 2, 'success.gif', function () { });

           }

	 }else{
	  KesionJS.Alert(d);
	 }
   });
}

function setRightValue()
{

    $(".hidans").each(function() {
        var value = this.value;
        
        if (value.indexOf('★★') != -1) {
            value = value.split('★★')[1];
        }
        var arr = value.split('§№§');

        for (var i = 0; i < arr.length; i++) {
            if (arr[i]) {

                var tm = arr[i].split('〓');

                var tmid = tm[0].match(/\d+/);
                var answer = tm[1];
                if(answer && value.indexOf('★★') !== -1){
                   answer = answer.replace(/§№/g, '').replace(/№/g, '');
                }
                answer && examMethods.setTimStatus(tmid, 'done')
            }
        }
    });

}


function getV3(arr, tmid) {
    if (arr.length <= 0) return '';
    var varr = arr.split('〓');
    for (var i = 0; i < varr.length; i++) {
        if (varr[0] == tmid) {
            return varr[1];
        }
    }
    return '';
}
function getV(arr,tmid){
	if (arr.length <= 0) return '';
	for (var i=0;i<arr.length;i++){
		var varr=arr[i].split('〓');
		if (varr[0]==tmid){
			return varr[1];
		}
	}
	return '';
}


/**
 * 【修改】设置题目已保存的值
 * @method setValue
 * 
 */
function setValue() {
	
 	from3g ? $('#content').find('.sjlist').first().show().siblings().hide() : '';
	
	$('#page_card').find('[tmid]').each(function(){
		var tmid = $(this).attr('tmid');
		if (getCookie("sj" + tmid) === "tao") {
			examMethods.getId('t'+tmid).className = 'tao';
			examMethods.setTimStatus(tmid,'sign')
		}
	});

	var pid = jQuery("#pid").val();
	
	
    setMyValue(pid);
    
}
function setMyValue(pid){

    var answer = jQuery("#ans" + pid).text();
	
    var __panerItem = $('.panel-item').eq(getCurBtnIndex());
    var num = __panerItem.find('.page-card-item').length;
    
	var tmType = jQuery("#num" + jQuery("#pid").val()).attr("tmtype");
	
	if (tmType==7){  
		answer = answer.split('★★')[1];
	}
	
	if (answer != '' && answer!=undefined) {
		
		var arr = answer.split('§№§');
		if (tmType==7){ //会计分录题
			    var str='';
				for (var i = 1; i <= num; i++) {
					str+="<tr id='t" + i + "'><td valign='top' style='width:30px;'>(" + i + ")、</td><td valign='top' id='my" + i + "'>";
					var aa=arr[i-1].split('〓')[1].split('§');
					var tmid=arr[i-1].split('〓')[0];
					if (arr[i-1].indexOf('~~~')!=-1){  //计算题
						str+="<input type='hidden' name='isjst"+i+"' id='isjst"+i+"' value='1'/>";
						for(var n=1;n<=aa.length;n++){
						  tm=aa[n-1].split('~~~')[0];
						  tm=tm.replace(/class="anstext"/,"class='anstext' value='"+aa[n-1].split('~~~')[1]+"'");
						  str += "<div id='s"+i+""+n+"'>"+tm+"</div>";
						}
					}else{
						str+="<input type='hidden' name='isjst"+i+"' id='isjst"+i+"' value='0'/>";
						for(var n=1;n<=aa.length;n++){
						  str += oneDiv(i,n,aa[n-1]);
						}
					}
                    str+="</td><td valign='top'><input type='hidden' tmid='"+tmid+"' name='num" + i + "' id='num" + i+ "' value='"+aa.length+"'/></td></tr>";
				}
				$("#flda").empty().append(str);
				//显示作题记录
				 tmid = $(".sttj").attr("tmid");
				 if (tmarr["tm"+tmid]!=undefined){jQuery("#aaa"+tmid).html(tmarr["tm"+tmid]);}
			
		}
		else{
		    var tmid = 0;
	        for (var i = 1; i <= num; i++) {
	            tmid = $("#tmid" + i).val();
	            if ($("#tmtype" + i).val() == "6" && (tmType != 6)) {
	            	
	                arr = '';
	                arr = answer.split('★★')[1];
	                arr = arr.split('§№§');
	                arr = '';
	                var ansf = answer.split('★★');
	                for (var j = 0; j < ansf.length; j++) {
	                    if (tmid == ansf[j].split('◇◆◆')[0]) {
	                        arr = ansf[j].split('◇◆◆')[1];
	                        arr = arr.split('§№§');

	                        break;
	                    }
	                }
	                var tnum = $("#tnum" + tmid).val();
	                for (var n = 0; n < tnum ; n++) {
	                    if (arr.length >= n) {
	                        var subtm = jQuery("#dt_" + tmid + "_" + (n + 1)).val();
							if(arr[n]){
								if (typeof (jQuery("input[tmid=sub" + subtm + "][type=radio]")[0]) != 'undefined') {

									setVal(getV3(arr[n].replace(/sub/, ''), subtm), 2, n, 'sub' + subtm);
								} else if (typeof (jQuery("input[tmid=sub" + subtm + "][type=checkbox]")[0]) != 'undefined') {
									setVal(getV3(arr[n].replace(/sub/, ''), subtm), 3, n, 'sub' + subtm);
								} else if (typeof (jQuery("textarea[tmid=sub" + subtm + "]")[0]) != 'undefined') {
									setVal(getV3(arr[n].replace(/sub/, ''), subtm), 1, n, 'sub' + subtm);
								} else if (typeof (jQuery("input[tmid=sub" + subtm + "][type=text]")[0]) != 'undefined') {
									setVal(getV3(arr[n].replace(/sub/, ''), subtm), 5, n, 'sub' + subtm);
								}
							}
	                    }
	                }
	            } else {
	                if ($("#tmtype1").val() == "6") {
	                    tmid = $("#tmid1").val()
	                    tmid = "sub" + jQuery("#dt_" + tmid + "_" + i).val();
	                   
	                }
	              
	                if (typeof (jQuery("input[tmid=" + tmid + "][type=radio]")[0]) != 'undefined') {
	                    setVal(getV(arr, tmid), 2, i, tmid);
	                } else if (typeof (jQuery("input[tmid=" + tmid + "][type=checkbox]")[0]) != 'undefined') {
	                    setVal(getV(arr, tmid), 3, i, tmid);
	                } else if (typeof (jQuery("textarea[tmid=" + tmid + "]")[0]) != 'undefined') {
	                    setVal(getV(arr, tmid), 1, i, tmid);
	                } else if (typeof (jQuery("input[tmid=" + tmid + "][type=text]")[0]) != 'undefined') {
	                    setVal(getV(arr, tmid), 5, i, tmid);
	                }
	            }
	            //显示作题记录
	            if (tmarr["tm" + tmid] != undefined) { jQuery("#aaa" + tmid).html(tmarr["tm" + tmid]); }
	        }
		    
			
			if (tmType==6){ 
				//阅读理解，显示作题记录
				
			    tmid = $(".sttj").attr("tmid");	
				 if (tmarr["tm" + tmid] != undefined)
				 {
				    jQuery("#aaa" + tmid).html(tmarr["tm" + tmid]);
                     
				 }
			}
		}
	}
}

function setVal(v, tmtype, i, tmid) {

	if (v != '')
    {
    	if(tmid.indexOf('sub') !== -1){
    		tmid = $('#content').find('input[tmid="'+tmid+'"]').parents('.sjlist').find('input[name="tmid"]')[0].value
    	};
   		examMethods.setTimStatus(tmid,'done')
   		
    }
    switch (tmtype) {
        case 1:
            jQuery("#a" + i).val(v);
            break;
        case 2:
        	
            jQuery("input[tmid=" + tmid + "]").each(function() {
            	
                if (jQuery(this).val() == v) {
                    jQuery(this).attr("checked", true);
					$(this).parent().attr("class","dx_button_xz");  //选中状态css
                }
            });
            break;
        case 3:
            jQuery("input[tmid=" + tmid + "]").each(function() {
                var carr = v.split('|');
                for (var k = 0; k < carr.length; k++) {
                    if (jQuery(this).val() == carr[k]) {
                        jQuery(this).attr("checked", true);
						$(this).parent().attr("class","dx_button_xz");  //选中状态css
                    }
                }
            });
            break;
        case 5:
            var ma = v.split('※');
            jQuery("input[tmid=" + tmid + "]").each(function(ts) {
                jQuery(this).val(ma[ts]);
                dolength(jQuery(this)[0]);
            });
            break;
    }
}

//获取当前选中的大题index
function getCurBtnIndex() {
    var __curIndex = 0;
    var __btn = $('input[name="btn"]');
    for (var i = 0; i < __btn.length; i++) {
        if (__btn[i].className === 'topInputOver') {
            __curIndex = i;
            break
        }
    }
    return __curIndex
}


//取得答案
function getAnswer() {

    var typeid = jQuery("#pid").val();
    var getAnswerIndex = getCurBtnIndex();
    var __panerItem = $('.panel-item').eq(getAnswerIndex);
    
    var num = __panerItem.find('.page-card-item').length;
 	
	var tmType = $("#num" + typeid).attr("tmtype");
	
    var ansstr = '';
    var tempstr = '';

	/**
	 * 会计分录题
	 */
    if (tmType == 7) {
        for (var i = 1; i <= num; i++) {
            var numi = parseInt($("#num" + i).val());
            var tmid = $("#num" + i).attr("tmid");
            var isjst = $("#isjst" + i).val();
            if (isjst == 1) {
                for (var n = 1; n <= numi; n++) {
                    var v = $("#kjans" + i + "" + n).val();
                    if (tempstr == '') {
                        tempstr = '' + $("#s" + i + "" + n).html() + '~~~' + v;
                    } else {
                        tempstr += '§' + $("#s" + i + "" + n).html() + '~~~' + v;
                    }
                }
            } else {
                for (var n = 1; n <= numi; n++) {
                    if ($("input[name=kjans" + i + "" + n + "1]")[0] != undefined) {
                        var v = $("input[name=kjans" + i + "" + n + "1]:checked").val();
                        if (v == undefined) v = "";
                        if (tempstr == '') {
                            tempstr = v + "№" + $("input[name=kjans" + i + "" + n + "2]").val() + "№" + $("input[name=kjans" + i + "" + n + "3]").val();
                        } else {
                            tempstr += "§" + v + "№" + $("input[name=kjans" + i + "" + n + "2]").val() + "№" + $("input[name=kjans" + i + "" + n + "3]").val();
                        }
                    }
                }
            }

            if (i == 1) {
                ansstr = tmid + "〓" + tempstr;
            } else {
                ansstr += '§№§' + tmid + "〓" + tempstr;
            }
        }

	}
	/**
	 * 论述题
	 */
    else if (tmType == 9) {
        var lsanwer = '';
        for (var i = 1; i <= num; i++) {
            lsanwer = '';
            var numi = parseInt($("#num" + i).val());
            var tmid = $("#tmid1").val();
  
            tmid = "sub" + jQuery("#dt_" + tmid + "_" + i).val();
            for (var n = 1; n <= numi; n++) {
                var v = $("#a" + i + "" + n).val();
                if (lsanwer == '') {
                    lsanwer = v;
                } else {
                    lsanwer += '@@@@' + v;
                }
            }
            if (ansstr == '') {
                ansstr = tmid + "〓" + lsanwer;

            } else {
                ansstr += '§№§' + tmid + "〓" + lsanwer;
            }
            tempstr += lsanwer;
        }

    }else {

        for (var i = 1; i <= num; i++) {
            
            var tmid = $("#tmid" + i).val();
            
            if ($("#tmtype" + i).val() == "6" && (tmType != 6)) {

                var tnum = $("#tnum" + tmid).val();
                var str = '';
                for (var n = 1; n <= tnum; n++) {
                    subtm = jQuery("#dt_" + tmid + "_" + n).val();

                    if (typeof (jQuery("input[tmid=sub" + subtm + "][type=radio]")[0]) != 'undefined') {
                        tempstr = getAns(typeid, 2, "sub" + subtm);
                    } else if (typeof (jQuery("input[tmid=sub" + subtm + "][type=checkbox]")[0]) != 'undefined') {
                        tempstr = getAns(typeid, 3, "sub" + subtm);
                    } else if (typeof (jQuery("textarea[tmid=sub" + subtm + "]")[0]) != 'undefined') {
                        tempstr = getAns(typeid, 1, "sub" + subtm);
                    } else if (typeof (jQuery("input[tmid=sub" + subtm + "][type=text]")[0]) != 'undefined') {
                        tempstr = getAns(typeid, 5, "sub" + subtm);
                    }
                    if (str == '') {
                        str = tempstr
                    } else {
                        str += '§№§' + tempstr;
                    }
                }
                tempstr = '★★' + tmid + '◇◆◆' + str;


            } else {
                if ($("#tmtype1").val() == "6") {
                    tmid = $("#tmid1").val()
                    tmid = "sub" + jQuery("#dt_" + tmid + "_" + i).val();
                }
                if (typeof (jQuery("input[tmid=" + tmid + "][type=radio]")[0]) != 'undefined') {

                    tempstr = getAns(typeid, 2, tmid);
                } else if (typeof (jQuery("input[tmid=" + tmid + "][type=checkbox]")[0]) != 'undefined') {
                    tempstr = getAns(typeid, 3, tmid);
                } else if (typeof (jQuery("textarea[tmid=" + tmid + "]")[0]) != 'undefined') {
                    tempstr = getAns(typeid, 1, tmid);
                } else if (typeof (jQuery("input[tmid=" + tmid + "][type=text]")[0]) != 'undefined') {
                    tempstr = getAns(typeid, 5, tmid);
                }
            }
            if (i == 1) {
                ansstr = tempstr;
            } else {
                ansstr += '§№§' + tempstr;
            }
        }
    }

	/**
	 * 阅读分析及分录题保存题号，保存答案时供使用
	 */
    if (tmType == 6 || tmType == 7) {
        c = $("#tmid").val() + "★★" + ansstr;
    }

    $("#ans" + $("#pid").val()).val(ansstr);
    

}
function getAns(typeid, tmtype, i) {
	
    var str = '';
    switch (tmtype) {
        case 1:
            str = jQuery("textarea[tmid=" + i + "]").attr("tmid")+"〓"+jQuery("textarea[tmid=" + i + "]").val();
            break;
        case 2:
            if (jQuery("input[tmid=" + i + "][type=radio]").length > 0) {
                jQuery("input[tmid=" + i + "][type=radio]").each(function () {
                    if ($(this).parent().attr("class") == "dx_button_xz") {
                        str = jQuery(this).attr("tmid") + "〓" + jQuery(this).val();
                        return;
                    }                   
                    });              
            }
            break;
        case 3:
            if (jQuery("input[tmid=" + i + "][type=checkbox]").length > 0) {
                o = jQuery("input[tmid=" + i + "]");               
                var s = ''
                jQuery("input[tmid=" + i + "][type=checkbox]").each(function () {
                    if ($(this).parent().attr("class") == "dx_button_xz") {
                        if (s == '') {
                            s = jQuery(this).val();
                        } else {
                            s += "|" + jQuery(this).val();
                        }                       
                    }
                });
                str = o.attr("tmid") + "〓" + s;
            }
            break;
        case 5:
            var ss = '';
            $("input[tmid=" + i + "]").each(function(index) {
				if (index == 0) {
					ss = $(this).val();
				} else {
					ss += '※' + $(this).val();
				}
			});
			
			str = $("input[tmid=" + i + "]").attr("tmid")+"〓"+ss;
            break;
    }
    return str;
}
//得到当前总题目数
function getTotal() {
    var num = 0;
    jQuery("div.sjlist").each(function () {
        num++;
    });
    return num;
}

//得到总题目总数
function getTotalTMS(){
	
	return $('#page_card').find('.page-card-item').length;
}
//得到未做完的题目数
function getNoFinishTMS(){
    var hasnum = $('#page_card').find('.done').length;    
    var leavenum= getTotalTMS()-hasnum;
	return leavenum;
}

function addCookie(objName, objValue, objHours) {//添加cookie
    var str = objName + "=" + escape(objValue);
    if (objHours > 0) {//为0时不设定过期时间，浏览器关闭时cookie自动消失
        var date = new Date();
        var ms = objHours * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
    }
    document.cookie = str;
}

function getCookie(objName) {//获取指定名称的cookie的值
    var arrStr = document.cookie.split("; ");
    for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == objName) return unescape(temp[1]);
    }
}

/**
 * 做题标记
 * @method tag
 * @param {String} id [ta 未备注  tao 已备注]
 */
function tag(id) {
	
	if(examMethods.getId('t'+id).className === 'tao'){
		examMethods.getId('t'+id).className = 'ta';
		setCookie("sj" + id,'ta');
		examMethods.setTimStatus(id,'removeSign')
	}else{
		examMethods.getId('t'+id).className = 'tao';
		setCookie("sj" + id,'tao');
		examMethods.setTimStatus(id,'sign')
	}
	
}

function dolength(obj) {
    var intlen = obj.value.replace(/[^\x00-\xff]/g, "xx").length;
    var tmid = $(obj).attr("tmid");  
	
	if(intlen>13&&intlen<70){
		obj.style.width = intlen*7+'px';  
	};
   
}
//估分时，检查总分
function checkgfnum(obj,t) 
{ 
	 if (isNaN(obj.value)) { 
		obj.value='0';
		obj.focus(); 
		window.KesionJS.Alert( "分数必须输入数字! "); 
		return false; 
	} 
	if (obj.value>t){
		obj.value=t;
		obj.focus(); 
		window.KesionJS.Alert( "此题总分 "+t+" 分，评分不能超过 "+t+" 分! "); 
		return false; 
	}
}  

//加入错题本
function addctb(obj,type){
    var flag=obj.checked;
	var tips='';
	if (type==0){tips='此题已收藏，确定从您的试题收藏夹中删除吗？';}else{tips='此题已加入错题本，确定从错题本中删除吗？';}
	if (flag==false){
	 if (!confirm(tips)){
	  return;
	  }
	}
    $.get(dir+'GetSjAjax.ashx',{action:'addtoctb',flag:flag,tmid:obj.value,type:type},function(d){
	  if (d=='success'){
	   if (flag==true){
		if (type==0){
	    KesionJS.Alert('恭喜，试题收藏成功!');
		}else{
	    KesionJS.Alert('恭喜，加入错题本成功!');
		}
	   }else{
		if (type==0){
	   KesionJS.Alert('恭喜，取消试题收藏成功!');
		}else{
	   KesionJS.Alert('恭喜，从错题本中删除成功!');
		}
	   }
	  }else{
	   KesionJS.Alert(d);
	  }
	});
  }

//单题提交看答案
var tmarr=new Array();
var dir='/plus/exam/';
var fromuser=0;
function post(i,tmid,tmtype,fs){
	 var str='';
	 if (tmtype==6 || tmtype==7){
		getAnswer();
		str=$("#ans" + jQuery("#pid").val()).text();
	 }else{
			switch (parseInt(tmtype)){
				   case 1:  //主观题
			    case 5:  //填空题
			        if (jQuery("input[tmid=" + tmid + "]").length == 1) {
			            str += jQuery("input[tmid=" + tmid + "]").val();

			        }else if (jQuery("textarea[tmid=" + tmid + "]").length == 1) {
				           str += jQuery("textarea[tmid=" + tmid + "]").val();
				         
						}else{
				           jQuery("input[tmid=" + tmid + "]").each(function (mm) {
							if (mm==0){
							  str=jQuery(this).val();
							}else{
							  str+='※'+jQuery(this).val();
							}
						  });
						}
					  break;
				   case 2:  //单选题
				   case 4:  //判断题
					if (jQuery("input[tmid="+tmid+"]").length>0){				
								o=jQuery("input[tmid="+tmid+"]");
								var s=false;
								for (var j=0 ; j < o.length ; j++)
								{
									if (o[j].checked)
									{
										str=o[j].value;
									}
								}
						}
					break;
				 case 3:  //多选题
					if (jQuery("input[tmid="+tmid+"]").length>0){	
								o=jQuery("input[tmid="+tmid+"]");
								var s=''
								for (var j=0 ; j < o.length ; j++)
								{
									if (o[j].checked)
									{
									   if (s==''){
										s=o[j].value;
									   }else{
										s+=","+o[j].value
										}
									}
								}
								str=s;
						}
					break;
			}
     }
	if (str==''){	
	  KesionJS.Alert('请输入答案后再提交!');
	 return;
	}
	var pid=jQuery("#pid").val();
	
	jQuery.get(dir+'GetSjAjax.ashx',{action:'dtsubmit',fs:fs,tmid:tmid,answer:str,fromuser:fromuser},function(d){
	  var rstr=d;
	
	  if (rstr.indexOf('success|||')==-1){
	    KesionJS.Alert(rstr);
	  }else{
	     var mystr="";
		 if (parseInt(tmtype)!=5 || (parseInt(tmtype)==5 && str.indexOf('※')==-1)){
		 //mystr="<div><strong>您的答案：</strong>" +str+"</div>";
		 }
		 mystr+=rstr.split('|||')[1];
		 mystr="<div style='padding:5px'>"+mystr+"</div>";
		 jQuery("#aaa"+tmid).html(mystr);
		 tmarr["tm"+tmid]=mystr;
	  }
	});
}


//以前题目解释
function explaindt(subtm, tmid, f) {
    jQuery.ajax({
        url: dir + "ShowTMJS.aspx?subtm=" + subtm + "&tmid=" + tmid + "&f=" + f, success: function (d) {
            if (f == 0) {
                $("#l" + tmid).html(d);
            } else {
                $("#r" + tmid).html(d);
            }
        }
    });
   // window.open(dir + "ShowTMJS.aspx?subtm=" + subtm + "&tmid=" + tmid + "&f=" + f, "查看试题答案解释", "width:500,height:350", false);
	//box=jQuery.dialog.open(dir+"ShowTMJS.aspx?subtm="+subtm+"&tmid="+tmid+"&f="+f,{title:"查看试题答案解释",width:500,height:350});
}

//题目解释
function explaindst(subtm, tmid, f) {

    var tips = '查看解析需要扣费,您确定要查看吗？';

    if (!confirm(tips)) {
        return;
    } else {
        jQuery.ajax({
            url: dir + "ShowTMJS.aspx?action=st&subtm=" + subtm + "&tmid=" + tmid + "&f=" + f, success: function (d) {
                if (subtm== 0) {
                    $("#clickdt" + tmid).hide();
                    $("#l" + tmid).html(d);
                  
                }
				else 
				{
				  $("#clickdt" + tmid).hide();
				   $("#ls" + tmid).html(d);
				}
 
            }
        });
    }

}



//试卷纠错
function ErrorCorrection(sjid){
 box=jQuery.dialog.open(dir+'ErrorCorrection.aspx?sjid='+sjid,{fixed:true,title:"我要纠错",width:800,height:460,lock:true});
}

//试题纠错
function ErrorCorrectionSt(tmid){
 box=jQuery.dialog.open(dir+'ErrorCorrentctionSt.aspx?tmid='+tmid,{fixed:true,title:"我要纠错题目ID:"+tmid,width:800,height:460,lock:true});
}

///////////////////////会计分录题相关操作_begin///////////////////////////////////////////////
function cloneTr(i){
    var n=parseInt(jQuery("#num"+i).val())+1;
    jQuery("#num"+i).val(n);
    jQuery("#my"+i).append(oneDiv(i,n),"");
 }
function oneDiv(i,n,answer){
	 var arr=(answer+"№№").split('№');
     var str="<div id='s"+i+""+n+"'>借贷方向：<input name='kjans" + i + ""+n+"1'  type='radio' value='借'";
	 if (arr[0]=="借") str +=" checked";
	  str +=">借 <input name='kjans" + i + ""+n+"1' type='radio' value='贷'";
	 if (arr[0]=="贷") str +=" checked";
	  str +=">贷";
      str += "&nbsp;&nbsp;&nbsp;&nbsp;会计科目：<input style='width:120px' type='text' value='"+arr[1]+"' name='kjans" + i + ""+n+"2' id='kjans" + i + "" + n + "2' class='textbox'/> <input type='button' class='button' onclick=selectKM('kjans" + i + "" + n + "2') value='...'/>";
      str += "&nbsp;&nbsp;&nbsp;&nbsp;金额：<input style='width:60px' type='text' value='"+arr[2]+"'  name='kjans" + i + ""+n+"3' id='kjans" + i + ""+n+"3' class='textbox'/>";
      str += "&nbsp;&nbsp; <input type='button' class='button' onclick='cloneTr("+i+")' value='增'/> <input class='button' type='button' class='del' onclick='removeDiv("+n+","+i+");' value='删'/></div>";
    return str;
}
function removeDiv(n,i){
      if (jQuery("#my"+i).find("div").length==1){
           alert('不能删除了，最少需要一条记录!');
          return;
       }else{
           jQuery("#s"+i+""+n).remove();
     }
 }
function selectKM(FieldID){
	 OpenThenSetValue(examInstallDir+'SelectKM.aspx?from=editst&fieldID='+FieldID,300,320,window,jQuery('#'+FieldID)[0]);
 	// box=jQuery.dialog({title:'选择科目',content:'url:SelectKM.aspx?from=paper&fieldID='+FieldID,width:350,height:370,lock:true,min:false,max:false});
}
 ///////////////////////会计分录题相关操作_end///////////////////////////////////////////////


 /**
 * 设置题型链接状态 
 */
function setExamLinkState(id,num,name,url){
	var $id = $('#'+id);
	if(num == 0){
		$id.html('<a class="disabled">'+name+'</a>')
	}else{
		$id.html('<a href="'+url+'">'+name+'</a>')
	}
}