var realTest=0;
var rndST=0;
var typeArr=new Array();
var box='';
$(function(){
$(".dx_button").find("input").click(function(){
		$(this).blur();																																																	       $(this).parent().parent().find("label").attr("class","dx_button");
		if ($(this).attr("type")=="radio"){
	   $(this).parent().attr("class","dx_button_xz");
		}else{ //多选
			$(this).parent().parent().find("label").find("input").each(function(){
					if ($(this)[0].checked==true){
						 $(this).parent().attr("class","dx_button_xz");
					}else{
						 $(this).parent().attr("class","dx_button");
					}
			});
		}
    })	

});

function loadPageInitial(obj,typeid){
	if (obj!=this){
    document.documentElement.scrollTop = 0;
	}
    if (obj != null) {
		if (obj!=this){
        jQuery("input[name=btn]").attr("class", "topInput");
        obj.className = 'topInputOver';
        jQuery("input[id=" + obj.id + "]").attr("class", "topInputOver");
        obj.blur();
		}
        getAnswer();
    }
	jQuery("#pid").val(typeid);
}
function initialCss(){
   //单选，多选
	$(".dx_button").find("input").click(function(){
		$(this).blur();																																																	       $(this).parent().parent().find("label").attr("class","dx_button");
		if ($(this).attr("type")=="radio"){
	   $(this).parent().attr("class","dx_button_xz");
		}else{ //多选
			$(this).parent().parent().find("label").find("input").each(function(){
					if ($(this)[0].checked==true){
						 $(this).parent().attr("class","dx_button_xz");
					}else{
						 $(this).parent().attr("class","dx_button");
					}
			});
		}
    })	
}
function loadPage(obj, typeid,isexplain,scoreid) {
	loadPageInitial(obj,typeid);
	if (obj==this){return;} //保存答案退出
	jQuery("#MaskLayer").show();
	if (typeArr[typeid]!=undefined){
		jQuery('#content').html(typeArr[typeid]);initialCss(); 
		setValue();
		jQuery("#MaskLayer").hide();
	}else{
    //jQuery.get('GetSJAjax.ashx', { action: "getst1", realTest:realTest,rndst:rndST,isexplain:isexplain,ScoreID:scoreid,typeid: typeid, istjda: isTjDa }, function(d) { typeArr[typeid]=d;jQuery('#content').html(d);initialCss(); if(d!=''){ setValue();}else{jQuery('#content').html('找不到试题！');} });
	jQuery("#MaskLayer").hide();
	}
    
}
function loadRndPage(obj, typeid,isexplain,scoreid) {
    loadPageInitial(obj,typeid);
	if (obj==this){return;} //保存答案退出
	jQuery("#MaskLayer").show();
	if (typeArr[typeid]!=undefined){
		jQuery('#content').html(typeArr[typeid]);initialCss(); 
		setValue();
		jQuery("#MaskLayer").hide();
	}else{
    //jQuery.get('GetSJAjax.ashx', { action: "getst2", realTest:realTest,rndst:rndST,isexplain:isexplain,ScoreID:scoreid,typeid: typeid, istjda: isTjDa }, function(d) { typeArr[typeid]=d;jQuery('#content').html(d);initialCss();																																								 if(d!=''){ setValue();}else{jQuery('#content').html('找不到试题！');} });
    jQuery("#MaskLayer").hide();
	}
}


function SaveAnswer(isrnd,sjid){
    if (isrnd==1){
		 loadRndPage(this,jQuery("#pid").val(),0,0);
		}else{
		 loadPage(this,jQuery("#pid").val(),0,0);
		}
  var tmanswer='';
  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.get('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({title:'警告',content:"url:showWarning.aspx?rnd="+Math.random()+"&flag=1&sjid="+sjid+"&scoreid="+arr[2],width:500,height:250,lock:true,min:false,max:false});
 	//	 }else{
 	//	  box=jQuery.dialog({title:'通知',content:"url:showWarning.aspx?rnd="+Math.random()+"&flag=2&sjid="+sjid+"&scoreid="+arr[2],width:500,height:250,lock:true,min:false,max:false});
 	//	 }
 //	 }else if (d=='success'){
 //	  if (realTest==0){
  //    jQuery.dialog.tips('恭喜，答案保存成功!',2,'success.gif',function(){});
 //	  }
 //	 }else{
 //	  KesionJS.Alert(d);
 //	 }
 //  }); 
}


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

function setValue() {
    jQuery("div.ta,span.ta").each(function() {
        jQuery(this).attr("class", getCookie("sj" + jQuery(this).attr("id").replace("t", "")));
    });
    var pid = jQuery("#pid").val();
    var answer = jQuery("#ans" + pid).val();
    var num = jQuery("#num" + jQuery("#pid").val()).val();
	var tmid=0;
    if (answer != '') {
        var arr = answer.split('§№§');
        for (var i = 1; i <= num; i++) {
            if (typeof (jQuery("input[name=a" + i + "][type=radio]")[0]) != 'undefined') {
				tmid=jQuery("input[name=a" + i + "][type=radio]").attr("tmid");
                setVal(getV(arr,tmid), 2, i);
            } else if (typeof (jQuery("input[name=a" + i + "][type=checkbox]")[0]) != 'undefined') {
				tmid=jQuery("input[name=a" + i + "][type=checkbox]").attr("tmid");
                setVal(getV(arr,tmid), 3, i);
            } else if (typeof (jQuery("textarea[name=a" + i + "]")[0]) != 'undefined') {
				tmid=jQuery("textarea[name=a" + i + "]").attr("tmid");
                setVal(getV(arr,tmid), 1, i);
            } else if (typeof (jQuery("input[name=a" + i + "][type=text]")[0]) != 'undefined') {
				tmid=jQuery("input[name=a" + i + "][type=text]").attr("tmid");
                setVal(getV(arr,tmid), 5, i);
            }
			 //显示作题记录
			 if (tmarr["tm"+pid+i]!=undefined){jQuery("#aaa"+i).html(tmarr["tm"+pid+i]); }

        }
    }
}
function setVal(v, tmtype, i) {
    switch (tmtype) {
        case 1:
            jQuery("#a" + i).val(v);
            break;
        case 2:
            jQuery("input[name=a" + i + "]").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[name=a" + i + "]").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[name=a" + i + "]").each(function(ts) {
                jQuery(this).val(ma[ts]);
                dolength(jQuery(this)[0]);
            });
            break;
    }
}

//取得答案
function getAnswer() {
    var typeid = jQuery("#pid").val();
    var num = jQuery("#num" + typeid).val();
    var tempstr = '';
    var ansstr = '';
    for (var i = 1; i <= num; i++) {
        if (typeof (jQuery("input[name=a" + i + "][type=radio]")[0]) != 'undefined') {
            tempstr = getAns(typeid, 2, i);
        } else if (typeof (jQuery("input[name=a" + i + "][type=checkbox]")[0]) != 'undefined') {
            tempstr = getAns(typeid, 3, i);
        } else if (typeof (jQuery("textarea[name=a" + i + "]")[0]) != 'undefined') {
            tempstr = getAns(typeid, 1, i);
        } else if (typeof (jQuery("input[name=a" + i + "][type=text]")[0]) != 'undefined') {
            tempstr = getAns(typeid, 5, i);
        }
        if (i == 1) {
            ansstr = tempstr;
        } else {
            ansstr += '§№§' + tempstr;
        }
    }
    jQuery("#ans" + jQuery("#pid").val()).val(ansstr)

}
function getAns(typeid, tmtype, i) {
    var str = '';
    switch (tmtype) {
        case 1:
            str = jQuery("textarea[name=a" + i + "]").attr("tmid")+"〓"+jQuery("textarea[name=a" + i + "]").val();
            break;
        case 2:
            if (jQuery("input[name=a" + i + "][type=radio]").length > 0) {
				jQuery("input[name=a" + i + "][type=radio]").each(function(){
				   if (jQuery(this)[0].checked==true){
					    str=jQuery(this).attr("tmid")+"〓"+jQuery(this).val();
						return;
				   }
				  });
            }
            break;
        case 3:
            if (jQuery("input[name=a" + i + "][type=checkbox]").length > 0) {
                o = jQuery("input[name=a" + i + "]");
                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 = o.attr("tmid")+"〓"+s;
				
            }
            break;
        case 5:
            var ss = '';
            jQuery("input[name=a" + i + "]").each(function(mm) {
                if (mm == 0) {
                    ss = jQuery(this).val();
                } else {
                    ss += '※' + jQuery(this).val();
                }
            });
			str = jQuery("input[name=a" + i + "]").attr("tmid")+"〓"+ss;
            break;
    }
    return str;
}

//得到总题目数
function getTotalTMS(){
	var num=0;
    jQuery(".hidnum").each(function(){
     num+=parseInt(jQuery(this).val());
    });
	return num;
}
//得到未做完的题目数
function getNoFinishTMS(){
	var ans='',temp='';
    jQuery(".hidans").each(function(){
	   temp=jQuery(this).val();
       if (temp!=''){
				if (ans==''){
				 ans=temp;
			   }else{
				 ans+='§№§'+temp;
			   }
       }
    });
    var arr=ans.split('§№§');
    var hasnum=0;
    var leavenum=0;
    for (var i=0;i<arr.length;i++){
		var v=arr[i].replace(/※/g,'');
		if (v.indexOf('〓')!=-1){
			 if (v.split('〓')[1]!=''){
			  hasnum++;
			 }
		}
    }
    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]);
    }
}
function tag(id) {
    if (jQuery("#t" + id).attr("class") == "ta") {
        jQuery("#t" + id).attr("class", "tao")
        addCookie("sj" + id, "tao", 0);
    } else {
        jQuery("#t" + id).attr("class", "ta")
        addCookie("sj" + id, "ta", 0);
    }
}
function dolength(o) {
    var intlen = o.value.replace(/[^\x00-\xff]/g, "xx").length
    if (intlen > 13 && intlen < 45) {
        o.style.width = intlen * 7;
    }

}
//估分时，检查总分
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('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='';
var fromuser=0;
function post(i,tmid,tmtype,fs){
	 var str='';
    switch (parseInt(tmtype)){
	       case 1:  //主观题
		   case 5:  //填空题
			    if (jQuery("#a"+i).length>0){	 
					   str+=jQuery("#a"+i).val();
				}else{
				  jQuery("input[name=a"+i+"]").each(function(mm){
				    if (mm==0){
					  str=jQuery(this).val();
					}else{
					  str+='※'+jQuery(this).val();
					}
				  });
				}
		      break;
		   case 2:  //单选题
		   case 4:  //判断题
		    if (jQuery("input[name=a"+i+"]").length>0){				
						o=jQuery("input[name=a"+i+"]");
						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[name=a"+i+"]").length>0){	
				        o=jQuery("input[name=a"+i+"]");
						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();
 	
}


//题目解释
function explaindt(tmid,f){
	//box=jQuery.dialog({title:"查看试题答案解释",content:"url:"+dir+"ShowTMJS.aspx?tmid="+tmid+"&f="+f,width:500,height:350});
}
//试卷纠错
function ErrorCorrection(sjid){
 //box=jQuery.dialog({title:"我要纠错",content:'url:ErrorCorrection.aspx?sjid='+sjid,width:700,height:480});
}