<HTML>
<HEAD>
	<TITLE>{siteTitle}</TITLE>
	<meta http-equiv=content-type content="text/html; charset=gb2312">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<LINK href="../CSS/Android.css" type=text/css rel=stylesheet>
    <script type="text/javascript" src="../Offline/common/string.js.php"></script>
    <script type="text/javascript" src="../Offline/script/animation.js"></script>
	<script type="text/javascript" src="../JS/CheckQuestion.js.php"></script>
	<script type="text/javascript" src="../JS/SelRadioCheckBox.js.php"></script>
	<script type="text/javascript" src="../Offline/common/jquery-1.6.2.min.js.php"></script>
	<script type="text/javascript" src="../Offline/common/smart-2.8.min.js.php"></script>
	<SCRIPT type=text/javascript>
	if( rexseeScreen.getScreenHeight() < 500 || rexseeScreen.getScreenWidth() < 500 )
	{
		rexseeScreen.setScreenOrientation('landscape');
		document.write('<LINK href="../Offline/resources/phone.css" type=text/css rel=stylesheet>');
	}
	else
	{
		document.write('<LINK href="../Offline/resources/pad10.css" type=text/css rel=stylesheet>');
	}
	window.onRexseeReady = function(){
			rexseeMenu.setOptionsMenuId("mainOptionsMenu1");
			rexseeTitleBar.setStyle('visibility:hidden;');
			rexseeStatusBar.setStyle('visibility:hidden;');
			
			rexseeSpecialKey.enableBackKeyListener(false);
			//rexseeSpecialKey.enableVolumeKeyListener(false);
			//rexseeBrowserStyle.setStyle('browser-zoom-button:visible;');
			
			//正在加载信息
			rexseeDialog.toast("正在努力为您加载信息...");
	}
	function checkSelectSurvey()
	{
		var strErr = "操作要求必须先选择一张或多张问卷！";
		objField = document.form.surveyID;
		if( objField.length == null )
		{
			if (objField.checked) return true;
			else
			{
				objField.focus();
				rexseeDialog.toast(strErr);
				return false;
			}
		}
		else
		{
			for (i=0;i<objField.length;i++){
				if (objField[i].checked) return true;
			}
			objField[0].focus();
			rexseeDialog.toast(strErr);
			return false;
		}
	}
	function taskSurveyAction()
	{
		if ( !checkSelectSurvey()) {return false;}
		var theSurveyID = getRadioCheckBoxValue(document.form.surveyID);
		var ParamString = "Action=downloadTaskSubmit" ;
		ParamString += "&surveyID="+theSurveyID;
		document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/wait.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=green><b>正在准备为您下载最新任务</b></font>&nbsp;";
		document.getElementById('downTaskBtn').disabled = true;
		ajax_Submit('BuildSurveyTask.php',ParamString);
	}
	function ajax_Submit(url,postStr) {
		var ajax=false; 
		try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { ajax = false; } }
		if (!ajax && typeof XMLHttpRequest!='undefined') ajax = new XMLHttpRequest(); 

		ajax.open("POST", url, true); 
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
		ajax.send(postStr);
		ajax.onreadystatechange = function(){
			if (ajax.readyState == 4)
			{
				if(ajax.status == 200)
				{
					//初始化本地数据表		
					var sql = "CREATE TABLE eq_task_list(taskID int(30) NOT NULL default '0',surveyID int(30) NOT NULL DEFAULT '0',taskName varchar(255) NOT NULL default '',taskDesc varchar(255) NOT NULL default '' );";
					if( ! rexseeDatabase.tableExists('eq_task_list','rexsee:enableq.db') )
					{
						rexseeDatabase.exec(sql,'rexsee:enableq.db');
					}
					var theRtnText = ajax.responseText.split('#######');
					if( theRtnText[0] == 'false' )
					{
						document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_no.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>"+theRtnText[1]+"</b></font>";
					}
					else if( theRtnText[0] == 'true' )
					{
						eval(theRtnText[2]);
						//开始创建本地数据库
						if( count(TaskListArray) != 0 )
						{
							var tmp = [];
							$.each(TaskListArray, function(key, val) { tmp[tmp.length] = parseInt(key);  });
							var tmp_rsort = rsort(tmp);
							var theSurveyID = theRtnText[1];
							
							sql = " DELETE FROM eq_task_list WHERE surveyID ='"+theSurveyID+"' ";
							rexseeDatabase.exec(sql,'rexsee:enableq.db');

							$.each(tmp_rsort, function(i, key) 
							{
								//插入本地数据库
								sql = " INSERT INTO eq_task_list (taskID,surveyID,taskName,taskDesc) VALUES ('"+key+"','"+TaskListArray[key].surveyID+"','"+TaskListArray[key].taskName+"','"+TaskListArray[key].taskDesc+"');";
								rexseeDatabase.exec(sql,'rexsee:enableq.db');
							});

							//纪录日志
							var sql = " SELECT surveyTitle FROM eq_survey_list WHERE surveyID ='"+theSurveyID+"' ";
							var surveyRow = eval('('+getDbRows(sql,'rexsee:enableq.db')+')');
							var theHomeURL = (rexseeApplication.getHome() == '' ) ? rexseeApplication.getDeveloperHome() : rexseeApplication.getHome();
							var remoteServer = str_replace('Offline/default.html','',theHomeURL);
							var theUploadURL = remoteServer+'Offline/UserAction.php';
							var postData = eval('({surveyID: "'+theSurveyID+'", userId: "{userId}",nickName: "{nickName}",actionMess:"任务下载:'+surveyRow.rows[0][0]+'",actionType:6})');
							$.ajaxSetup({async:false});
							$.post(theUploadURL, postData);			 
						}//TaskListArray
						document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_yes.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=green><b>您选择的问卷回复任务全部下载成功</b></font>";
					}
					else
					{
						document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_no.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>服务器程序异常，请联系软件开发商</b></font>:"+theRtnText;
					}//theRtnText
				}//ajax.status
				else
				{
					rexseeDialog.toast('网络传输问题');
				}
			}//ajax.readyState
		}//function
	}//function
	window.onException = function(className, message){
		//alert(unescape(message));
		var theLogFilePath = rexseeStorage.getRoot()+'enableq_offline/logs/';
		if( ! rexseeFile.exists(theLogFilePath) )
		{
			rexseeFile.newDir(theLogFilePath);
		}
		var theLogFile = theLogFilePath +'error.txt';
		if( !rexseeFile.exists(theLogFile) )
		{
			rexseeFile.newFile(theLogFile);
		}
		else
		{
			if( rexseeFile.size(theLogFile) > 102400 )
			{
				rexseeFile.remove(theLogFile);
				rexseeFile.newFile(theLogFile);
			}
		}
		var theOriFileContent = rexseeFile.getContent(theLogFile,'GBK');
		rexseeFile.putContent(theLogFile,theOriFileContent+"Error("+date('Y-m-d H:i:s',time())+"):"+className+":"+unescape(message)+"\r\n",'GBK');
	}
	</SCRIPT>
</HEAD>
<body style="background:#e5e5e5;color:#666">

<div class="titlebar">
 <table width=100%>
   <tr><td width=85><a id="rtnURL"><img src="../Images/return.png" width=85 height=30 border=0></a></td>
   <td align=center width=* class="pageTitle">任务下载</td>
   <td width=85><a href="Logout.php"><img src="../Images/lout.png" width=85 height=30 border=0></a></td>
 </table>
</div>

<div class="notesInfo">【说明】欢迎您，{nickName}，请选择需要删除的本地问卷。</div>

<div class="invertedshiftdown">
	<ul>
	<li><a href="javascript:animationLoad('DownSurveyList.php');">下载问卷</a></li>
	<li class="current"><a href="javascript:animationLoad('DownTaskList.php');">任务下载</a></li>
	<li><a href="javascript:animationLoad('UploadSurveyData.php');">数据上行</a></li>
	<li><a href="javascript:animationLoad('AbnormalSurveyList.php');">异常处理</a></li>
	<li><a href="javascript:animationLoad('DeleSurveyList.php');">问卷删除</a></li>
	<li><a href="javascript:animationLoad('CheckServerVersion.php');">程序更新</a></li>
	</ul>
</div>

<script id="main_list_tpl" type="text/x-jsmart-tmpl">
<div id="androidList" style="padding-left:10px;padding-right:10px;padding-top:5px;background: #e5e5e5;">
 <form name="form" id="form" method="post">
{foreach $surveys as $i => $survey}
 <table width=100% style="border:#d9d9d9 2px solid;margin-bottom:5px;margin-top:5px;background:#ffffff">
   <tr>
      <td height=70 width=99% valign=center style="border-bottom:#ddd 1px solid"><a href="javascript:void(0);" onclick="javascript:selRadioCheckRows('surveyID',{$survey.theOptionOdNum});"><div class="actiontitle"  style="line-height:30px;padding-top:20px;padding-bottom:20px;border-bottom:none">{$survey.surveyTitle}</div></a></td>
	  <td align=right valign=center width=1% style="border-bottom:#ddd 1px solid"><input type="radio" name="surveyID" id="surveyID" value="{$survey.surveyID}" {$survey.disabled}>&nbsp;</td>
   </tr>
   <tr>
      <td height=40 align=left style="padding-left:20px" class="sysinfo">{$survey.info}</td>
      <td align=right valign=center nowrap>{$survey.beginTime}&nbsp;(<font color=red>{$survey.replyNum}</font>)&nbsp;</td></tr>
 </table>
 {/foreach}
 <table width=100%>
   <tr><td><input type="button" name="downTaskBtn" id="downTaskBtn" class=btnclass value="开始下载" onclick="javascript:taskSurveyAction();">&nbsp;&nbsp;<span id="infocontent"></span>
   </td></tr>
 </table>
 
 </form>
</div>
<div class="pageinfo infoTotal">共计<span class=red>{$survey@total}</span>张问卷</div>
</script>
<script>
	var dataCheckRow = eval('('+ getDbRows('SELECT * FROM eq_survey_list WHERE surveyID =0 LIMIT 1','rexsee:enableq.db')+')');
	if( ! in_array('userName',dataCheckRow.columns) )
	{
		sql = " ALTER TABLE eq_survey_list ADD userName varchar(255) NOT NULL default '' ";
		rexseeDatabase.exec(sql,'rexsee:enableq.db');
	}
	dataCheckRow = null;

	var theHomeURL = (rexseeApplication.getHome() == '' ) ? rexseeApplication.getDeveloperHome() : rexseeApplication.getHome();
	var remoteServer = str_replace('Offline/default.html','',theHomeURL);
	//问卷列表
	sql = " SELECT * FROM eq_survey_list WHERE ( userName = '' OR userName ='{nickName}' ) ORDER BY surveyID DESC; ";
	var surveyRow = eval('('+getDbRows(sql,'rexsee:enableq.db')+')');
	var thisTotal = 0;
	if( count(surveyRow.rows) != 0 )
	{
		var datas ="{ surveys:[";
		var theOptionOdNum = 0;
		for( var tmp in surveyRow.rows )
		{
			datas += "{";
			datas += "surveyID:" + surveyRow.rows[tmp][0] +",";
			datas += "surveyTitle:'" + surveyRow.rows[tmp][1] +"',";
			datas += "beginTime:'" + surveyRow.rows[tmp][2]+"',";
			datas += "theOptionOdNum:" + theOptionOdNum +",";
			theOptionOdNum++;
			//Ajax
			var rtnMess = '';
			var theCheckURL = remoteServer+'Offline/TaskCountNum.php';
			var postData = eval('({surveyID: "'+surveyRow.rows[tmp][0]+'"})');
			$.ajaxSetup({async:false});
			$.post(theCheckURL, postData, 
				function(data) { 
					rtnMess = data;
			});	
			
			if( rtnMess == 'false' )
			{
				datas += " info:'<font color=red><b>问卷无任务，无法下载</b></span>',";
				datas += " disabled:'disabled',";
				datas += " replyNum:'0'";
			}
			else if( rtnMess == '' )
			{
				datas += " info:'<font color=red><b>无最新任务，无须下载</b></span>',";
				datas += " disabled:'disabled',";
				datas += " replyNum:'0'";
			}
			else
			{
				sql = " SELECT taskID FROM eq_task_list WHERE surveyID ='"+surveyRow.rows[tmp][0]+"' ORDER BY taskID ASC ; ";
				var taskRow = eval('('+getDbRows(sql,'rexsee:enableq.db')+')');
				var theNowTask = new Array();
				for( var k in taskRow.rows )
				{
					theNowTask[k] = taskRow.rows[k][0];
				}
				var theDiffArray = array_diff(rtnMess.split(','),theNowTask);				
				var theDiffNum = count(theDiffArray);
				if( theDiffNum == 0 )
				{
					datas += " info:'<font color=red><b>无最新任务，无须下载</b></span>',";
					datas += " disabled:'disabled',";
					datas += " replyNum:'0'";
				}
				else
				{
					thisTotal++;
					datas += " info:'<font color=green><b>有最新任务，可下载</b></span>',";
					datas += " disabled:'',";
					datas += " replyNum:'"+theDiffNum+"'";
				}
			}
			datas += "},";
		}
		datas = datas.substr(0,datas.length-1)+"] }";
	}
	else
	{
		var datas ="{ surveys:[] }";
	}
	var jsondatas = eval('('+datas+')');				

	var tplText = document.getElementById('main_list_tpl').innerHTML;
	var tpl = new jSmart( tplText );
	var res = tpl.fetch( jsondatas );
    document.write( res );

	if(thisTotal >0 )
	{
		document.getElementById('downTaskBtn').disabled = false;
	}
	else
	{
		document.getElementById('downTaskBtn').disabled = true;
	}
	$('#rtnURL').attr('href',"javascript:animationLoad('"+rexseeClient.getRoot('bulidClient.xml')+"index.html');");
</script>
<script>scroll(0, 0);</script>
</body>
</html>