<?php session_start(); 

require "common.php";
if (isset($_SESSION['role'])){
	$role = $_SESSION['role'];
}
if (isset($_GET['lang'])){
	$_SESSION['lang'] = $_GET['lang'];
}
if (isset($_SESSION['lang'])){
	if ($_SESSION['lang'] == "chi"){
		require "language/chi.php";
	} else {
		require "language/eng.php";
	}
$lang = $_SESSION['lang'];
}

if(isset($_SESSION['UID']) != null){ 
	$UID = $_SESSION["UID"];  
		if (isset($_SESSION['STAFFCODE'])) {
		$staffcode = $_SESSION['STAFFCODE'];
		if ($_SESSION['lang'] == "chi") {
			$name = $_SESSION['CH_NAME'];
		} else {
			$name = $_SESSION['EN_NAME'];
		}
	} else {
		$stuid = $_SESSION['STUID'];
		$classcode = $_SESSION['CLASSCODE'];
		$classno = $_SESSION['CLASSNO'];
		if ($_SESSION['lang'] == "chi") {
			$name = $_SESSION['CH_NAME'];
		} else {
			$name = $_SESSION['EN_NAME'];
		}
		
	}
	foreach ($_POST as $key => $value) 	{ 
			if ($key !== "role") {
				$$key = $value;    //2個$$代表轉為VARIABLE
			}
	}
	foreach ($_GET as $key => $value) 	{ 
			if ($key !== "role") {
				$$key = $value;    //2個$$代表轉為VARIABLE
			}
	}


//設定學年
		if (!isset($targetschoolyear)){
			$targetschoolyear = $todayschyr;
		}

//完成設定學年
		//php add next year
		if (isset($addnextyear)){
			$p = strval($schyr) +1;
			$sql= mysqli_query($splink,"Insert into SCHYEAR (SCHYEAR) VALUES (\"". $p ."\")");
		}
		//finish add next year

//學年選擇表		
			$sql=mysqli_query($splink,"Select SCHYEAR from SCHYEAR ORDER BY SCHYEAR DESC");
			$yearlist = "";
			while ($row = mysqli_fetch_row($sql)){
				if (isset($targetschoolyear)){
					if ($targetschoolyear == $row[0]) {
						$selected = "selected";
					} else {
						$selected = "";
					}
				} else {
					$selected = "";
				}
				$pp = $row[0]+1;
				$yearlist .="<option value=\"".$row[0]."\" ".$selected.">".$row[0]."-".substr($pp,2)."</option>";
			//	$yearlist .="<option value=\"".$row[0]."\" ".$selected.">".$row[0]."</option>";
			}
//完成學年選擇表

	require "templates/header.php"; 
	
	//設定各類時段
	if (isset($settimeperiod)){
		if (isset($setactiveyear) && !isset($addnextyear)){
			$sql=mysqli_query($splink,"UPDATE SCHYEAR SET activeyear=\"0\"");
			$sql = mysqli_query($splink,"UPDATE SCHYEAR SET activeyear=\"1\" WHERE SCHYEAR=\"".$targetschoolyear."\"");
		}

		//php save apply date
		if (isset($savemoduleenable)){
			if (!isset($apenable)) {
				$apenable=1;
			}
			$sql = mysqli_query($splink, "UPDATE moduleenable SET apenable=\"".$apenable1."\" , Start_date=\"".$Start_date1."\", End_date=\"".$End_date1."\" WHERE  module=\"sportday\"");
			$sql = mysqli_query($splink, "UPDATE moduleenable SET apenable=\"".$apenable2."\" , Start_date=\"".$Start_date2."\", End_date=\"".$End_date2."\" WHERE  module=\"workerapply\"");
			$sql = mysqli_query($splink, "UPDATE moduleenable SET apenable=\"".$apenable3."\" , Start_date=\"".$Start_date3."\", End_date=\"".$End_date3."\" WHERE  module=\"competitionapply\"");
			$msg .= $txtsuccesssave;
		}
		//finish save apply date
		//php save grade year
		if (isset($saveyear)){
			if (strlen($gradeAyear) > 0 && strlen($gradeByear) > 0 && strlen($gradeCyear) > 0 ) {
				$csql= mysqli_query($splink,"Select * from gradeyear where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"A\"");
				if (mysqli_num_rows($csql) > 0 ) {
					$sql = mysqli_query($splink,"Update gradeyear SET gradeyear=\"".$gradeAyear."\" where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"A\"");
				} else {
					$sql = mysqli_query($splink,"Insert into gradeyear ( gradeyear, SCHYEAR, grade) VALUES ( \"".$gradeAyear."\", \"".$targetschoolyear."\" , \"A\")");
				}
				$csql= mysqli_query($splink,"Select * from gradeyear where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"B\"");
				if (mysqli_num_rows($csql) > 0 ) {
					$sql = mysqli_query($splink,"Update gradeyear SET gradeyear=\"".$gradeByear."\" where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"B\"");
				} else {
					$sql = mysqli_query($splink,"Insert into gradeyear ( gradeyear, SCHYEAR, grade) VALUES ( \"".$gradeByear."\", \"".$targetschoolyear."\" , \"B\")");
				}
				$csql= mysqli_query($splink,"Select * from gradeyear where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"C\"");
				if (mysqli_num_rows($csql) > 0 ) {
					$sql = mysqli_query($splink,"Update gradeyear SET gradeyear=\"".$gradeCyear."\" where SCHYEAR = \"".$targetschoolyear."\" AND grade=\"C\"");
				} else {
					$sql = mysqli_query($splink,"Insert into gradeyear ( gradeyear, SCHYEAR, grade) VALUES ( \"".$gradeCyear."\", \"".$targetschoolyear."\" , \"C\")");
				}
			} else {
				$msg .= $txtemptyinput;
			}
		}
		//php finish save grade year
		//php save eventname
		if (isset($saveeventname)){
			$sql = mysqli_query($splink,"Update SCHYEAR SET EVENT_CHNAME=\"".$EVENT_CHNAME."\", EVENT_ENNAME=\"".$EVENT_ENNAME."\" WHERE SCHYEAR=\"".$todayschyr."\"");
		}
		//finish php save eventname
		?>
        <link rel="stylesheet" href="jscss/jquery.datepick.css">
        <script src="jscss/jquery.plugin.js"></script>
        <script src="jscss/jquery.datepick.js"></script>
        <script>
        $(document).ready(function() {
            $( "#Start_date1" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate: "<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                
                });
            $( "#End_date1" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate:"<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                });
            $( "#Start_date2" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate: "<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                
                });
            $( "#End_date2" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate:"<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                });
            $( "#Start_date3" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate: "<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                
                });
            $( "#End_date3" ).datepick({
                dateFormat: 'yyyy-mm-dd',
                        minDate:"<?=date("Y-m-d")?>",
                        maxDate: new Date(<?=$targetschoolyear+2?>,8,0),
                monthsToShow: 1, 
                });
         });
        </script> 
        <?php
		$sql = mysqli_query($splink,"Select * from moduleenable where module=\"sportday\"");
		while ($row= mysqli_fetch_row($sql)){
            $sdstart=$row[3];
			$sdend=$row[4];
		}
		$sql = mysqli_query($splink,"Select * from moduleenable where module=\"workerapply\"");
		while ($row= mysqli_fetch_row($sql)){
            $wdstart=$row[3];
			$wdend=$row[4];
			$wenable = $row[2];
		}
		$sql = mysqli_query($splink,"Select * from moduleenable where module=\"competitionapply\"");
		while ($row= mysqli_fetch_row($sql)){
            $adstart=$row[3];
			$adend=$row[4];
			$senable=$row[2];
		}
		$EVENT_CHNAME="";
		$EVENT_ENNAME="";
		$sql = mysqli_query($splink,"Select EVENT_CHNAME, EVENT_ENNAME from SCHYEAR where SCHYEAR=\"".$todayschyr."\"");
		while ($row = mysqli_fetch_row($sql)){
			$EVENT_CHNAME = $row[0];
			$EVENT_ENNAME = $row[1];
		}
		?>
        <h2><?=$txtsettimeperiod?></h2>
        <center><?=$msg?></center>
        <h3><?=$txtactiveyear?></h3>
        <form action="setting.php" method="POST"><input type="hidden" name="settimeperiod" />
        <div class="select-wrapper">
        <select name="targetschoolyear" onchange="submit()"><option></option><?=$yearlist?></select>
        </div><br />
        <input type="submit" name="addnextyear" value="<?=$txtaddnextyear?>"  class="special"/><input type="hidden" name="setactiveyear" />
        </form>
        <br />	
		<h3><?=$txtsportdayname?></h3>
        <form action="setting.php" method="POST"><input type="hidden" name="settimeperiod" />
        <?=$txtchi?>:<input type="text" name="EVENT_CHNAME" value="<?=$EVENT_CHNAME?>"  class="special"/>
        <?=$txteng?>:<input type="text" name="EVENT_ENNAME" value="<?=$EVENT_ENNAME?>"  class="special"/>
        <br />
        <input type="submit" name="saveeventname" value="<?=$txtsave?>" />
        </form>
        <br />
        <h3><?=$txtsettingdayforcomingevent?></h3>
        <link rel="stylesheet" href="jquery/jquery-ui.css">
        <link rel="stylesheet" href="jquery/jquery-ui.theme.css"> 
        <script src="jquery/external/jquery/jquery.js"></script> 
        <script src="jquery/jquery-ui.js"></script>

        <form action="setting.php" method="post"><input type="hidden" name="settimeperiod" /><input type="hidden" name="targetschoolyear" value="<?=$targetschoolyear?>" />
        <table border="1"><thead>
        <tr><th></th><th><?=$txtheatsdate?></th><th><?=$txtfinaldate?></th></tr></thead>
        <tbody>
        <tr><td><?=$txtsportdaydate?></td>
        <td><input type="date" value="<?=$sdstart?>" name="Start_date1" id="Start_date1"/>
        <input type="hidden" name="apenable1" value="1"  /></td>
        <td><input type="date" value="<?=$sdend?>" name="End_date1" id="End_date1" /></td></tr>
        <tr><th></th><th><?=$txtstartdate?></th><th><?=$txtenddate?></th></tr>
        <tr><td><?=$txtstudentworkerapplydate?></td>
        <td><input type="date" value="<?=$wdstart?>" name="Start_date2" id="Start_date2"/><input type="hidden" value="1" name="apenable2" /></td>
        <td><input type="date" value="<?=$wdend?>" name="End_date2" id="End_date2" /></td></tr>
        <tr><td><?=$txtcompetitionapplydate?></td>
        <td><input type="date" value="<?=$adstart?>" name="Start_date3" id="Start_date3"/><input type="hidden" value="1" name="apenable3" /></td>
        <td><input type="date" value="<?=$adend?>" name="End_date3" id="End_date3" /></td>
        </tr></tbody>
        </table><input type="submit" value="<?=$txtsave?>" name="savemoduleenable" class="special"></form>
        <script>
        (function() {
          var elem = document.createElement('input');
          elem.setAttribute('type', 'date');
          if ( elem.type === 'text' ) {
             $('#Start_date1').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
             $('#End_date1').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
             $('#Start_date2').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
             $('#End_date2').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
             $('#Start_date3').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
             $('#End_date3').datepicker({
                dateFormat: "yy-mm-dd",
                minDate: 0,
             }); 
          }			
        })();
        </script>
       <br />
       <br />
       <h3><?=$txtsettinggradeyear?></h3>
       <?php
	   $sql = mysqli_query($splink,"Select gradeyear from gradeyear where SCHYEAR=\"".$targetschoolyear."\" AND grade=\"A\"");
	   if (mysqli_num_rows($sql) > 0 ){
		   while ($row = mysqli_fetch_row($sql)) {
			   $gradeAyear = $row[0];
		   }
	   } else {
		   $gradeAyear = "";
	   }
	   $sql = mysqli_query($splink,"Select gradeyear from gradeyear where SCHYEAR=\"".$targetschoolyear."\" AND grade=\"B\"");
	   if (mysqli_num_rows($sql) > 0 ){
		   while ($row = mysqli_fetch_row($sql)) {
			   $gradeByear = $row[0];
		   }
	   } else {
		   $gradeByear = "";
	   }
	   $sql = mysqli_query($splink,"Select gradeyear from gradeyear where SCHYEAR=\"".$targetschoolyear."\" AND grade=\"C\"");
	   if (mysqli_num_rows($sql) > 0 ){
		   while ($row = mysqli_fetch_row($sql)) {
			   $gradeCyear = $row[0];
		   }
	   } else {
		   $gradeCyear = "";
	   }
	   ?>
       <br />
       <form action="setting.php" method="post"><input type="hidden" name="settimeperiod" /><input type="hidden" name="targetschoolyear" value="<?=$targetschoolyear?>" />
       <table border="1"><thead>
       <tr align="center"><th><?=$txtgrade?></th><th><?=$txtgradeyear?></th></tr></thead><tbody>
       <tr><td><?=$txtgradeA?></td><td><input type="text" name="gradeAyear" value="<?=$gradeAyear?>" /></td></tr>
       <tr><td><?=$txtgradeB?></td><td><input type="text" name="gradeByear" value="<?=$gradeByear?>" /></td></tr>
       <tr><td><?=$txtgradeC?></td><td><input type="text" name="gradeCyear" value="<?=$gradeCyear?>" /></td></tr>
       <tr><td colspan="2" align="center"><input type="Submit" name="saveyear" value="<?=$txtsave?>" class="special"/></td></tr>
		</tbody>
        </table></form>
	<?php
	
	}
	//完成設定各類時段
    
	//設定項目比賽日期及場次
	if (isset($eventdateid)){
		//php save eventdateid
		if (isset($saveeventdateid)){
			if (isset($DATE)){
				$temp = explode("-",$COMPETITION_ID);
				$COMPETITION_ID=$temp[0];
				$HeatorFinal=$temp[1];
				$sql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$COMPETITION_ID."\" AND HeatorFinal=\"".$HeatorFinal."\"");
				if (mysqli_num_rows($sql) > 0 ) {
					$msg = $txtalrecordreadyexists;
				} else {
					$sql = mysqli_query($splink,"Insert into COMPETITION_DATEID ( COMPETITION_ID, DATE,ORDER_ID, HeatorFinal,EVENTTIME) VALUES (\"".$COMPETITION_ID."\",\"".$DATE."\" , \"".$ORDER_ID."\",\"".$HeatorFinal."\",\"".$EVENTTIME."\")");
					$msg = $txtsuccesssave;
				}
			}
		}
		//finish php save eventdateid
		//php delete eventdateid
		if (isset($removeID)){
			$sql =mysqli_query($splink,"Select keyid, ORDER_ID from COMPETITION_DATEID where ORDER_ID > \"".$ORDER_ID."\"");
			while ($row = mysqli_fetch_row($sql)){
				$neworder = $row[1] - 1;
				$usql = mysqli_query($splink,"Update COMPETITION_DATEID SET ORDER_ID=\"".$neworder."\" where keyid=\"".$row[0]."\"");
			}
			$sql = mysqli_query($splink,"Delete from COMPETITION_DATEID where keyid=\"".$keyid."\"");
			unset($keyid);
			unset($ORDER_ID);
			$msg = $txtsuccessdelete;
		}
		//finish php delete eventdateid
		//php moveupdown eventdateid
		if (isset($targetmoveup_x) || isset($targetmovedown_x) ) {
			if (isset($targetmoveup_x)) {
				$targetmove = $ORDER_ID -1 ;
			} else {
				$targetmove = $ORDER_ID + 1;
			}
			$sql = mysqli_query($splink,"Update COMPETITION_DATEID SET ORDER_ID=\"".$ORDER_ID."\" WHERE ORDER_ID=\"".$targetmove."\"");
			$sql = mysqli_query($splink,"Update COMPETITION_DATEID SET ORDER_ID=\"".$targetmove."\" WHERE keyid=\"".$keyid."\"");
			$msg = $txtsuccessmoverecord;
			unset($keyid);
		}
		//finish php moveupdown eventdateid
		//finish list of event
		?>
        <h2><?=$txteventdateid?></h2>
        <?=$msg?>
        <?php
		//list of event
		$itemlist= "";
		//查詢可報名的EVENT
		$sql = mysqli_query($splink,"Select keyid, CH_DES, EN_DES, SETLANE from COMPETITIONITEM where Allowapply = \"1\" AND INTERCLASS=\"0\" ORDER BY  SEX, GRADE,TRACKFIELD");
		$nooflist = mysqli_num_rows($sql);
		while ($row = mysqli_fetch_row($sql)){
			//查詢是否需要安排線道
			if ($row[3] == 1 ) {
				//查詢是否多於8人
				$csql = mysqli_query($splink,"Select * from APPLICATION_COMPETITION where COMPETITION_ID=\"".$row[0]."\"");
				if (mysqli_num_rows($csql) > 8 ) {
					$csql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$row[0]."\" AND HeatorFinal=\"0\"");
					if (mysqli_num_rows($csql) > 0 ) {
					} else {
						if ($lang == "chi") {
							$showname = $row[1];
						} else {
							$showname = $row[2];
						}
						$itemlist .= "<option value=\"".$row[0]."-0\">".$showname."(".$txt1stheat.")</option>";
					}
					$csql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$row[0]."\" AND HeatorFinal=\"1\"");
					if (mysqli_num_rows($csql) > 0 ) {
					} else {
						if ($lang == "chi") {
							$showname = $row[1];
						} else {
							$showname = $row[2];
						}
						$itemlist .= "<option value=\"".$row[0]."-1\">".$showname."(".$txtfinal.")</option>";
					}
				} else {
					//少於8人...
					$csql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$row[0]."\" AND HeatorFinal=\"1\"");
						if (mysqli_num_rows($csql) > 0 ) {
						} else {
						if ($lang == "chi") {
							$showname = $row[1];
						} else {
							$showname = $row[2];
						}
						$itemlist .= "<option value=\"".$row[0]."-1\">".$showname."(".$txtfinal.")</option>";
					}
				}
			} else {
			//不需要安排線道的項目				
				$csql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$row[0]."\"");
				if (mysqli_num_rows($csql) > 0 ) {
				} else {
					if ($lang == "chi") {
						$showname = $row[1];
					} else {
						$showname = $row[2];
					}
					$itemlist .= "<option value=\"".$row[0]."-1\">".$showname."(".$txtfinal.")</option>";
				}
			}
		}
		//get dates
		$sql = mysqli_query($splink,"Select Start_date, End_date from moduleenable where module=\"sportday\"");
		while ($row = mysqli_fetch_row($sql)){
			$start_date = $row[0];
			$end_date= $row[1];
		}
		//ID list
		$finalno = 0;
		$nofinalno = 0;
		$sql = mysqli_query($splink,"SELECT COUNT(COMPETITION_ID) FROM `TRACKEVENT_HEAT_LANE` group by COMPETITION_ID");
		while ($row = mysqli_fetch_row($sql)){
			if ($row[0] > 8 ) {
				$finalno++;
			} else {
				$nofinalno++;
			}
		}
		$idlist = "";
		$x = 0;
		while ($x < $nooflist + $finalno ) {
			$id = $x+1;
			$sql = mysqli_query($splink,"Select * from COMPETITION_DATEID where ORDER_ID=\"".$id."\"");
			if (mysqli_num_rows($sql) > 0 ) {
				
			} else {
				$idlist .= "<option value=\"".$id."\">".$id."</option>";
			}
			$x++;
		}
		if (strlen($itemlist) !== 0 ) {
		?>
        <form action="setting.php" method="POST"><input type="hidden" name="eventdateid" />
        <table><thead><tr><th><?=$txtcompetitionitem?></th><th><?=$txtdate?></th><th><?=$txttime?> eg. 1045</th><th><?=$txttimetableeventno?></th><th><?=$txtfunction?></th></tr></thead>
        <tbody>
		<tr><td><div class="select-wrapper"><select name="COMPETITION_ID"><?=$itemlist?></select></div></td>
        <td><input type="radio" name="DATE" value="<?=$start_date?>" id="DATE1" <?php if (isset($DATE) && $DATE==$start_date) {?> checked="checked" <?php } ?>/><label for="DATE1"><?=$start_date?></label>
        &nbsp;&nbsp;<input type="radio" name="DATE" value="<?=$end_date?>" id="DATE2" <?php if (isset($DATE) && $DATE==$end_date) {?> checked="checked" <?php } ?> /><label for="DATE2"><?=$end_date?></label>
        </td>
        <td><input type="text" name="EVENTTIME" value="" size="5"/></td>
        <td><div class="select-wrapper"><select name="ORDER_ID"><?=$idlist?></select></div></td>
        <td><input type="submit" name="saveeventdateid" value="<?=$txtsave?>" />
        </td></tr>
        </tbody>
        </table></form>
        <?php
		}
        //顯示已有項目
		$sql= mysqli_query($splink,"Select MAX(ORDER_ID) from COMPETITION_DATEID");
		$noofeve = mysqli_num_rows($sql);
		while ($row = mysqli_fetch_row($sql)) {
			$maxorder  = $row[0];
		}
		$sql =mysqli_query($splink,"Select A.keyid, B.CH_DES, B.EN_DES, A.DATE, A.ORDER_ID,A.HeatorFinal,A.EVENTTIME from COMPETITION_DATEID AS A inner join COMPETITIONITEM AS B ON A.COMPETITION_ID=B.keyid ORDER BY ORDER_ID");
		if (mysqli_num_rows($sql) > 0 ) {
			?>
            <table style="alignment-baseline:central; width:70%"><thead><tr><th><?=$txtcompetitionitem?></th><th><?=$txtdate?>/<?=$txttime?></th><th><?=$txttimetableeventno?></th><th><?=$txtfunction?></th></tr></thead>
	        <tbody>
            <?php
			while ($row = mysqli_fetch_row($sql)){
				if ($lang == "chi") {
					$showname = $row[1];
				} else {
					$showname = $row[2];
				}
				if ($row[5] == 0 ) {
					$showname .= "(".$txt1stheat.")";
				} else {
					$showname .= "(".$txtfinal.")";
				}
				?>
                <tr><td><?=$showname?></td><td><?=$row[3]?></br><?=$row[6]?></td><td><?=$row[4]?></td>
                <td>
                <form action="setting.php#<?=$row[0]?>" method="POST" id=<?=$row[0]?>><input type="hidden" name="eventdateid" />
                <input type="hidden" name="keyid" value="<?=$row[0]?>" />
                <input type="hidden" name="ORDER_ID" value="<?=$row[4]?>" />
				<?php
				if ($maxorder > 1 ) {
					if ($row[4] == 1) {
						?>
						<img src="img\clearbox.png">
						<input type="image" src="img\orderdown.png" name="targetmovedown" onclick="submit()">
						<?php
					} else if ($row[4] == $maxorder) {
						?>
						<input type="image" src="img\orderup.png" name="targetmoveup" onclick="submit()">
						<img src="img\clearbox.png">
						<?php
					} else {
						?>
						<input type="image" src="img\orderup.png" name="targetmoveup" onclick="submit()">
						<input type="image" src="img\orderdown.png" name="targetmovedown" onclick="submit()">
						<?php
					}
				}
                ?>
                <input type="submit" name="removeID" value="<?=$txtdelete?>" />
                </form>
                </td>
                </tr>
                <?php
			}
			?>
            </tbody></table>
            <?php
		}
	}
	//完成設定項目比賽日期及場次    
    //匯入所需資料
	if (isset($setupuser)) {
		//匯入學生資料
		if (isset($uploadstustudent)) {
			if (is_uploaded_file($_FILES['upfile']['tmp_name'])) {     	//確認上載檔案
				$i=0;													//行數
				$name = $_FILES['upfile']['name'];     					//讀取檔案名稱
				$datafield= NULL;
				$handle=fopen($_FILES['upfile']['tmp_name'],"r");		//以唯讀方式開啟上載檔案
			//	echo $name;
				$fileyear = substr($name,2,2);
				while (($data = fgetcsv($handle,1000,",")) !== FALSE) { //逐行讀取CSV內容
					$nofield = 15;                          //TB_STU_STUDENT包含多少個需要的FIELD
				//	echo $nofield;
					if ($i == 0) {
					//	echo "\$i=0";
						$fno = 0;
						$tbfield = NULL;
						while ($fno < $nofield) {
							if ($fno == $nofield -1) {
								$tbfield .= "`".$data[$fno]."`";
							} else {
								$tbfield .= "`".$data[$fno]."` ,";
							}
							$fno++;
						}
					}
					if ($i > 0 ) {						//由第二行開始
						//第12個FIELD為PASSWORD
							$fno = 0 ;
							$datafield .= " ( ";
							while ( $fno < $nofield ) {
								if ($fno == 12) {     //12 is the field for password
									$hash1 = password_hash($data[$fno],PASSWORD_BCRYPT);
									$datafield .= "\"".$hash1. "\" ,";
								} else {
									$datafield .= "\"".$data[$fno]. "\",";
								}
								$fno++;
							}
							$datafield = substr($datafield,0,-1)." ) , ";
					}
				$i++;
				}
				$datafield = substr($datafield, 0, -2);
				fclose($handle);
				echo $txtwaitimport."<br>";
				$sql = mysqli_query($splink,"TRUNCATE TB_STU_STUDENT");
				$sql = "INSERT INTO TB_STU_STUDENT (".$tbfield. ") VALUES ".$datafield;
			//	echo $sql;
				$result = mysqli_query ($splink, $sql);
				$sql = mysqli_query($splink,"Select SUID from TB_STU_STUDENT GROUP by SUID");
				while ($r=mysqli_fetch_row($sql)){
					$s= mysqli_query($splink,"Update SW_PFM SET SUID=\"".$r[0]."\"");
				}
				echo $txtfinishimport;
				}
		}
		?><p><?=$txtimportTBSTUSTUDENT?></p>
		<form action="setting.php" method="POST" enctype="multipart/form-data">
		<input type="hidden" name="import"/>
		<input type="hidden" name="MAX_FILE_SIZE" value="20000000" >
		<input type="file" name="upfile" accept=".csv">
		<input type="submit" name="uploadstustudent" value="<?=$txtupload?>">
		</form>
		<hr>
		<?php
		//加新用戶
		if (isset($submitaddnewstaff)){
				if (isset($editing)){
					if ($password == "") {
						$sql= mysqli_query($splink,"update teacherinfo set `CH_NAME`=\"".$CH_NAME."\",`EN_NAME`=\"".$EN_NAME."\",`stafftitle`=\"".$stafftitle."\"where STAFFCODE=\"".$keyid."\"");
					} else {
						$password = password_hash($password,PASSWORD_BCRYPT);
					//	$password = md5($password);
						$sql= mysqli_query($splink,"update teacherinfo set `CH_NAME`=\"".$CH_NAME."\",`EN_NAME`=\"".$EN_NAME."\",`stafftitle`=\"".$stafftitle."\",`password`=\"".$password."\" WHERE `STAFFCODE`=\"".$keyid."\"");
					}
					echo $txtsuccessedit; 
				} else {
					$password = password_hash($password,PASSWORD_BCRYPT);
					$sql = mysqli_query($splink,"Select * from teacherinfo where STAFFCODE=\"".$STAFFCODE."\" OR STAFFUID=\"".$STAFFUID."\"");
					if (mysqli_num_rows($sql) > 0){
						echo "<strong>".$txtSTAFFCODEorSTAFFUIDthesame."</strong>";
					} else {
						$sql= mysqli_query($splink,"INSERT INTO teacherinfo ( `STAFFCODE`,`STAFFUID`,`CH_NAME`,`EN_NAME`,`stafftitle`,`password`) VALUES (\"".$STAFFCODE."\",\"".$STAFFUID."\",\"".$CH_NAME."\",\"".$EN_NAME."\",\"".$stafftitle."\",\"".$password."\")");
						echo $txtsuccessadd;
					}
				}
			}
		//移除用戶
		if (isset($deletestaff)){
			$sql= mysqli_query($splink,"Delete from teacherinfo where STAFFCODE=\"".$keyid."\"");
			echo $txtsuccessdelete;
		}
		//show edit user
		if (isset($editwho)){
			$sql=mysqli_query($splink,"select `STAFFCODE`,`STAFFUID`,`CH_NAME`,`EN_NAME`,`stafftitle` from teacherinfo where STAFFCODE=\"".$keyid."\"");
			while ($row = mysqli_fetch_row($sql)){
				$sstaffcode=$row[0];
				$sstaffuid=$row[1];
				$sch_name=$row[2];
				$sen_name=$row[3];
				$sstafftitle=$row[4];
			}
		}
		?><p>&nbsp;</p>
    	<p><?=$txtaddnewstaff?></p>
        <form action="setting.php" method="post">
		<?php if (isset($sstaffcode)){ ?><input type="hidden" name="editing" value="1">
			<input type="hidden" name="keyid" value="<?=$sstaffcode?>">
			<?php } ?>
        <input type="hidden" name="setupuser" value="1" />
        <input type="hidden" name="system" value="1" />
      	<table border="1">
            <tr>
            <td><?=$txtwstaffcode?><br />：</td><td><?php if (isset($sstaffcode)){ echo $sstaffcode;} else { ?><input type="text" name="STAFFCODE" value="" /><?php }?></td>
            </tr>
            <td width="100"><?=$txtstaffuid?>(login ID)：</td><td><?php if (isset($sstaffuid)){ echo $sstaffuid;} else { ?><input type="text" name="STAFFUID" value="" /><?php }?></td>
            </tr><tr>
            <td width="200"><?=$txtchname?>：</td><td><input type="text" name="CH_NAME" value="<?php if (isset($sch_name)){ echo $sch_name;}?>" /></td>
            </tr><tr>
            <td width="200"><?=$txtenname?>：</td><td><input type="text" name="EN_NAME" value="<?php if (isset($sen_name)){ echo $sen_name;}?>" /></td>
            </tr><tr>
            <td width="200"><?=$txtnoticetitle?>：</td><td><input type="text" name="stafftitle" value="<?php if (isset($sstafftitle)){ echo $sstafftitle;}?>" /></td>
            </tr><tr>
            <tr>
            <td width="50"><?=$txtpassword?>：</td><td><input type="password" name="password" value="" /></td>
            </tr>
		</table><input type="submit" name="submitaddnewstaff" value="<?=$txtsave?>" />
        <input type="submit" name="cancel" value="<?=$txtcancel?>" />
        </form>
		<hr>
		<p>
		<?php


		?>
		<p><strong><?=$txtexistuser?></strong></p>
        <p>
        <p>
        <table border="1">
        <tr align="center" >
        <td width="80"><?=$txtwstaffcode?></td>
        <td width="100"><?=$txtstaffuid?></td>
        <td width="200"><?=$txtchname?></td>
        <td width="200"><?=$txtenname?></td>
        <td width="60"><?=$txtnoticetitle?></td>
        <td width="50"><?=$txtedit?></td>
        </tr>
        <?php
		$listsql = mysqli_query($splink,"Select * from teacherinfo order by STAFFUID");
		while ($xx = mysqli_fetch_row($listsql)){
			$color = "";
			if (isset($keyid)){ 
				if ($keyid == $xx[0]){
					$color = " bgcolor=\"#f9f4bd\"";
				}
			}
			?>
			<tr align="center" <?=$color?>>
			<td><?=$xx[0]?></td>
			<td><?=$xx[1]?></td>
			<td><?=$xx[2]?></td>
			<td><?=$xx[3]?></td>
			<td><?=$xx[4]?></td>
			<td><form action="setting.php" method="POST"><input type="hidden" name="setupuser" value="1" />
			<input type="hidden" name="keyid" value="<?=$xx[0]?>" />
			<input type="submit" name="editwho" value="<?=$txtedit?>" />
			<input type="submit" name="deletestaff" value="<?=$txtdelete?>" />

			</form></td>
			</tr>
			<?php
		}
		?>
        </table>
        <p>
        <?php
		
	}
	//完成匯入資料    

	//設定陸運會工作人員職位
	if (isset($setstudentworker)) {
		//save record
		if (isset($saveduty)){
			if (!isset($allowapply)) {
				$allowapply = 0;
			}
			if (!isset($activate)) {
				$activate = 0;
			}
			if (isset($targetkeyid)){
				$sql = mysqli_query($splink,"Update studentworker SET CH_DES=\"".$CH_DES."\", EN_DES=\"".$EN_DES."\", NEED_NUM=\"".$NEED_NUM."\", REQUIRE_SEX=\"".$REQUIRE_SEX."\",CH_REMARK=\"".$CH_REMARK."\",EN_REMARK=\"".$EN_REMARK."\",allowapply=\"".$allowapply."\", activated=\"".$activate."\" WHERE keyid=\"".$targetkeyid."\"");	
				unset($targetkeyid);
				echo $txtsuccessupdaterecord;
			} else {
				$sql = mysqli_query($splink,"INSERT INTO studentworker (CH_DES,EN_DES,NEED_NUM, REQUIRE_SEX, CH_REMARK, EN_REMARK,allowapply) VALUES (\"".$CH_DES."\",\"".$EN_DES."\",\"".$NEED_NUM."\",\"".$REQUIRE_SEX."\",\"".$CH_REMARK."\",\"".$EN_REMARK."\",\"".$allowapply."\")");
				echo $txtsuccessaddrecord;
			}
		}
		//finish save record
		//delete record
		if (isset($deleteduty)){
			
			$sql = mysqli_query($splink,"Update studentworker SET activated=\"".$activate."\" where keyid=\"".$targetkeyid."\"");
			echo $txtsuccessdelete;
		}
		//finish deltet record
		// show edit detail
		if (isset($editduty)){
			$sql = mysqli_query($splink,"Select CH_DES, EN_DES, NEED_NUM, REQUIRE_SEX, CH_REMARK, EN_REMARK, allowapply, keyid from studentworker where keyid=\"".$targetkeyid."\"");
			while ($row = mysqli_fetch_row($sql)){
				$skeyid=$row[7];
				$sCH_DES=$row[0];
				$sEN_DES=$row[1];
				$sNEED_NUM= $row[2];
				$sREQUIRE_SEX=$row[3];
				$sCH_REMARK = $row[4];
				$sEN_REMARK = $row[5];
				$sallowapply = $row[6];
			}
		}
		//finish show edit detail
		?>
        <form action="setting.php" method="POST"><input type="hidden" name="setstudentworker" />
        <?php if (isset($editduty)){ ?>
			<input type="hidden" name="targetkeyid" value="<?=$skeyid?>" />
        <?php } ?>
        <div class="row uniform">
            <div class="6u 12u$(xsmall)">
                <label for="CH_DES"><?=$txtdutyname."(".$txtchi.")"?></label><input id="CH_DES" type="text" value="<?php if(isset($sCH_DES)) { echo $sCH_DES;}?>" name="CH_DES" placeholder="<?=$txtchi.":".$txtdutyname?>" />
            </div>
            <div class="6u 12u$(xsmall)">
                <label for="EN_DES"><?=$txtdutyname."(".$txteng.")"?></label><input id="EN_DES" type="text" value="<?php if(isset($sEN_DES)) { echo $sEN_DES;}?>" name="EN_DES" placeholder="<?=$txteng.":".$txtdutyname?>" />
            </div>
            <div class="6u 12u$(xsmall)">
                <label for="NEED_NUM"><?=$txtneed_num?></label><input id="NEED_NUM" type="text" value="<?php if(isset($sNEED_NUM)) { echo $sNEED_NUM;}?>" name="NEED_NUM" placeholder="<?=$txtneed_num?>"/>
            </div>
            <div class="6u 12u$(xsmall)">
                <label for="REUIRE_SEX"><?=$txtsex?></label>
                <div class="select-wrapper">
                    <select name="REQUIRE_SEX" id="REUIRE_SEX"><option value="" disabled selected>--<?=$txtselectsex?>--</option>
                    <option value="0" <?php if (isset($sREQUIRE_SEX) && $sREQUIRE_SEX==0) { ?> selected="selected" <?php }?>><?=$txtboy."/".$txtgirl?></option>
                    <option value="1" <?php if (isset($sREQUIRE_SEX) && $sREQUIRE_SEX==1) { ?> selected="selected" <?php }?>><?=$txtboy?></option>
                    <option value="2" <?php if (isset($sREQUIRE_SEX) && $sREQUIRE_SEX==2) { ?> selected="selected" <?php }?>><?=$txtgirl?></option>
                    </select></td>
                </div>
            </div>
            <div class="12u$">
                <label for="CH_REMARK"><?=$txtsex?></label>
                <input id="CH_REMARK" type="text" value="<?php if(isset($sCH_REMARK)) { echo $sCH_REMARK;}?>" name="CH_REMARK" placeholder="<?=$txtchi.":".$txtremark?>"/>
            </div>
            <div class="12u$">
            	<label for="EN_REMARK"><?=$txtsex?></label>
                <input id="EN_REMARK" type="text" value="<?php if(isset($sEN_REMARK)) { echo $sEN_REMARK;}?>" name="EN_REMARK" placeholder="<?=$txteng.":".$txtremark?>"/>
            </div>
            <div class="6u 12u$(xsmall)">
                <input type="checkbox" name="allowapply" value="1" <?php if (isset($sallowapply) && $sallowapply ==1) { echo "checked";}?> id="allowapply"/>
                <label for="allowapply"><?=$txtallowapp?></label>
            </div>
            <div class="12u$">
                <input type="submit" name="saveduty" value="<?php if (isset($editduty)){ echo $txtsave; } else { echo $txtadd; }?>" />
            </div>
        </div>    
        </form>
        <hr />
        <div class="table-wrapper">
        <table border="1"><thead >
        <tr><th style="text-align:center"><?=$txtduty?></th><th style="text-align:center"><?=$txtneed_num?></th><th style="text-align:center"><?=$txtsex?></th>
        <th style="text-align:center"><?=$txtremark?></th><th style="text-align:center"><?=$txtallowapp?></th><th style="text-align:center"><?=$txtstatus?></th><th style="text-align:center"><?=$txtfunction?></th></tr></thead>
        <tbody>
        <?php
		$sql = mysqli_query($splink,"Select * from studentworker");
		$x = 1;
		while ($row = mysqli_fetch_row($sql)){
			if ($row[4] == 0 ) {
				$selectsex = $txtboy."/".$txtgirl;
			} else if ($row[4] == 1) {
				$selectsex = $txtboy;
			} else {
				$selectsex = $txtgirl;
			}
			
			?>
            <tr><td><?=$txtchi?>：<?=$row[1]?><br /><?=$txteng?>：<?=$row[2]?></td>
            <td align="center"><?=$row[3]?></td>
            <td align="center"><?=$selectsex?></td>
            <td align="center"><?=$row[5]?><br /><?=$row[6]?></td>
            <td align="center"><?php if ($row[7] ==1) { echo "√";}?></td>
            <td align="center"><?php if ($row[8] ==1) { echo $txtvalid;}?></td>
            <td align="center"><form action="setting.php" method="POST"><input type="hidden" name="setstudentworker" />
            <input type="hidden" name="targetkeyid" value="<?=$row[0]?>" />
            <input type="submit" name="editduty" value="<?=$txtedit?>" class="button"/></form></td>
            </tr>
            <?php 
			if ( $x/7 == 1 ) {
				?>
                <tr><th style="text-align:center"><?=$txtduty?></th><th style="text-align:center"><?=$txtneed_num?></th><th style="text-align:center"><?=$txtsex?></th>
                <th style="text-align:center"><?=$txtremark?></th><th style="text-align:center"><?=$txtallowapp?></th><th style="text-align:center"><?=$txtstatus?></th><th style="text-align:center"><?=$txtfunction?></th></tr></thead>
				<?php
				$x = 0;
			}
			$x++;
		}
		?>
        </tbody>    
        </table>
        </div>
        <?php
	}
	//完成設定陸運會工作人員職位
	//設定職員職位
	if (isset($setstaffduty)){
		//php for cancel
		if (isset($cancel)) {
			unset($keyid);
		}
		//finish php cancel
		//php save staff list
		if (isset($savestafflist)){
			$x= 0;
			$nSTAFF="";
			while ($x < sizeof($STAFF)){
				$nSTAFF .= $STAFF[$x].",";
				$x++;
			}
			$STAFF = substr($nSTAFF,0,-1);
			$sql= mysqli_query($splink,"Update staffduty SET STAFF=\"".$STAFF."\" WHERE keyid=\"".$keyid."\"");
			unset($keyid);
		}
		//php finish save staff list
		//php change order
		if (isset($changeorder)){
			$sql = mysqli_query($splink,"Select STAFF from staffduty where keyid=\"".$keyid."\"");
			while ($row = mysqli_fetch_row($sql)){
				$STAFF = explode(",",$row[0]);
			} 
			$x = sizeof($STAFF);
			$i = 1;
			$nSTAFF="";
			while ( $i < $x ) {
				$nSTAFF .= $STAFF[$i].",";
				$i++;
			}
			$nSTAFF .= $STAFF[0];
			$sql= mysqli_query($splink,"Update staffduty SET STAFF=\"".$nSTAFF."\" WHERE keyid=\"".$keyid."\"");
			unset($keyid);
		}
		//finish php change order
		?>
        <h2><?=$txtsetstaffduty?></h2>
        <?php
        if (!isset($selectstaff)) {
			?>
            <table><thead><tr><th width="250"><?=$txtdutyname?></th><th><?=$txtstaff?></th><th width="200"><?=$txtfunction?></th></tr></thead>
            <tbody>
            <?php
            $sql = mysqli_query($splink,"Select CH_DES, EN_DES, STAFF,keyid from staffduty");
            while ($row = mysqli_fetch_row($sql)){
                if ($lang == "chi") {
                    $dutyname = $row[0];
                } else {
                    $dutyname = $row[1];
                }
                $temp = explode(",",$row[2]);
                $x = 0;
                $showt = "";
                while ($x < sizeof($temp)){
                    $tsql = mysqli_query($splink,"Select CH_NAME, EN_NAME from teacherinfo where STAFFCODE=\"".$temp[$x]."\"");
                    while ($trow = mysqli_fetch_row($tsql)){
                        if ($lang == "chi") {
                            $showt .= $trow[0]."、";
                        } else {
                            $showt .= $trow[1]."、";
                        }
                    }
                    $x++;
                }
                $showt = mb_substr($showt,0, -1);
                ?>
                <tr id=<?=$row[3]?>><td><?=$dutyname?></td><td><?=$showt?></td>
                <td>
                <form action="setting.php#<?=$row[3]?>" method="POST"><input type="hidden" name="setstaffduty" />
                <input type="hidden" name="keyid" value="<?=$row[3]?>" />
				<input type="submit" name="selectstaff" value="<?=$txtedit?>" class="button small"/>&nbsp;
                <input type="submit" name="changeorder" value="<?=$txtchangeorder?>" class="button special small" />
                </form></td></tr>
                <?php
            }
            ?>
            </tbody></table>
            <?php
		} else {
			$sql = mysqli_query($splink,"Select CH_DES, EN_DES, STAFF from staffduty where keyid=\"".$keyid."\"");
			while ($row = mysqli_fetch_row($sql)){
                if ($lang == "chi") {
                    $dutyname = $row[0];
                } else {
                    $dutyname = $row[1];
                }
				$stafflist = explode(",",$row[2]);
			}
			?>
            <h3><?=$dutyname?></h3>
            <form action="setting.php#<?=$keyid?>" method="POST"><input type="hidden" name="setstaffduty" />
            <input type="hidden" name="keyid" value="<?=$keyid?>" />
            <input type="submit" name="savestafflist" value="<?=$txtsave?>" />&nbsp;&nbsp;<input type="submit" name="cancel" value="<?=$txtcancel?>" />
            <br />
            <div class="row uniform">
			<?php
			$sql = mysqli_query($splink,"Select STAFFCODE, STAFFUID, CH_NAME, EN_NAME from teacherinfo order by STAFFUID");
			$selectlist = "";
			$x = 1;
			while ($row = mysqli_fetch_row($sql)){
				if (in_array($row[0],$stafflist)) {
					$check = "checked=\"checked\"";
				} else {
					$check = "";
				}
				if ($lang =="chi") {
					$showt = $row[2];
				} else {
					$showt = $row[3];
				}
				$selectlist .= "<div class=\"3u 12u$(small)\"><input type=\"checkbox\" name=\"STAFF[]\" value=\"".$row[0]."\" ".$check." id=\"".$row[0]."\"><label for=\"".$row[0]."\">".substr($row[1],0,3)." ".$showt."</label></div>";
				if ($x == 3) {
					$selectlist .= "</br>";
					$x = 0;
				}
				$x++;
			}
			echo $selectlist;
			?>
            </div>
            <br />
            <input type="submit" name="savestafflist" value="<?=$txtsave?>" />&nbsp;&nbsp;<input type="submit" name="cancel" value="<?=$txtcancel?>"  />
            </form>
            <?php
		}
	}
	//完成設定職員職位
	//設定比賽項目
	if (isset($setcompetitionitem)){
		//php saveitem
		if (isset($saveitem)){
			if (!isset($Allowapply)) {
				$Allowapply = 0;
			}
			if (!isset($SETLANE)) {
				$SETLANE = 0;
			}
			if ($eventtype == 0 ) {
				$INTERHOUSE = 0;
				$INTERCLASS = 0;
				$OPENSCH = 0;
			} else if ($eventtype == 1) {
				$INTERHOUSE = 1;
				$INTERCLASS = 0;
				$OPENSCH = 0;
			} else if ($eventtype == 2) {
				$INTERHOUSE = 0;
				$INTERCLASS = 1;
				$OPENSCH = 0;
			} else  {
				$INTERHOUSE = 0;
				$INTERCLASS = 0;
				$OPENSCH = 1;
			} 
			$error=0;
				//檢測成積是否出現錯誤
				if ($UNIT == 0) {  //徑項
					if ($STANDARD !== "") {  //如果輸入非空白
						$tresult = explode(":", $STANDARD);
						$size = sizeof($tresult) ;
						if ( $size > 3 ) {
							$error = 1;
							$msg .= $txtstandard." ".$txtresultinputerror."<br>";
						}
						if ($size == 2) {
							if  ($tresult[0] > 59) {
								$error = 1;
								$msg .= $txtstandard." ".$txtresultinputerror."<br>";
							}
						}
						$sizeindex = $size - 1;	
						$t2result = explode(".",$tresult[$sizeindex]) ;
						if (sizeof($t2result) > 2 ) {
							$error = 1;
							$msg .= $txtstandard." ".$txtresultinputerror."<br>";
						}
						if ($t2result[0] > 59) {
							$error = 1;
							$msg .= $txtstandard." ".$txtresultinputerror."<br>";
						}
					} 
					if ($MEASURE !== "") {  //如果輸入非空白
						$tresult = explode(":", $MEASURE);
						$size = sizeof($tresult) ;
						if ( $size > 3 ) {
							$error = 1;
							$msg .= $txtmeasurestandard." ".$txtresultinputerror."<br>";
						}
						if ($size == 2) {
							if  ($tresult[0] > 59) {
								$error = 1;
								$msg .= $txtmeasurestandard." ".$txtresultinputerror."<br>";
							}
						}
						$sizeindex = $size - 1;	
						$t2result = explode(".",$tresult[$sizeindex]) ;
						if (sizeof($t2result) > 2 ) {
							$error = 1;
							$msg .= $txtmeasurestandard." ".$txtresultinputerror."<br>";
						}
						if ($t2result[0] > 59) {
							$error = 1;
							$msg .= $txtmeasurestandard." ".$txtresultinputerror."<br>";
						}
					} 
				} else {   //田項
					$tresult = explode(".", $STANDARD);
					if (sizeof($tresult) > 2 ) {
						$error = 1;
						$msg .= $txtstandard." ".$txtresultinputerror."<br>";
					}
					$tresult = explode(".", $MEASURE);
					if (sizeof($tresult) > 2 ) {
						$error = 1;
						$msg .= $txtmeasurestandard." ".$txtresultinputerror."<br>";
					}

				}
				
			if ($error == 0 ) {
				if ($UNIT == 0) {  //徑項  --成績用時間顯示
					if ($STANDARD !== ""){
						$rec = explode(":", $STANDARD);
						if (sizeof($rec) == 1 ){
							$sec = explode(".", $rec[0]);
							if (sizeof($sec) == 1) { //no dec.
								$newsec = $rec[0].".00";
							} else {
								if (strlen($sec[1]) == 1 ) {
									$newsec = $sec[0].".".$sec[1]."0";
								} else {
									$newsec = $sec[0].".".$sec[1];
								}
							}
							if (strlen($sec[0]) == 1) {
								$nSTANDARD = "00:00:0".$newsec;
							} else {
								$nSTANDARD = "00:00:".$newsec;
							}
						} else if (sizeof($rec) == 2 ) {
							$sec = explode(".",$rec[1]);
							if (sizeof($sec) == 1) { //no dec.
								$newsec = $rec[1].".00";
							} else {
								if (strlen($sec[1]) == 1 ) {
									$newsec = $sec[0].".".$sec[1]."0";
								} else {
									$newsec = $sec[0].".".$sec[1];
								}
							}
							if (strlen($sec[0]) == 1) {
								$sec = "0".$newsec;
							} else {
								$sec = $newsec;
							}
							if (strlen($rec[0]) == 1) {
								$min = "0".$rec[0];
							} else {
								$min = $rec[0];
							}
							$nSTANDARD = "00:".$min.":".$sec;
						} else {
							$sec = explode(".",$rec[2]);
								if (sizeof($sec) == 1) { //no dec.
									$newsec = $rec[2].".00";
								} else {
									if (strlen($sec[1]) == 1 ) {
										$newsec = $sec[0].".".$sec[1]."0";
									} else {
										$newsec = $sec[0].".".$sec[1];
									}
								}
							if (strlen($sec[0]) == 1) {
								$sec = "0".$newsec;
							} else {
								$sec = $newsec;
							}
							if (strlen($rec[1]) == 1) {
								$min = "0".$rec[1];
							} else {
								$min = $rec[1];
							}
							if (strlen($rec[0]) == 1) {
								$hr = "0".$rec[0];
							} else {
								$hr = $rec[0];
							}
							if ($sec == "") {
								$sec = "00.00";
							}
							$nSTANDARD = $hr.":".$min.":".$sec;
						}
					} else {
						$nSTANDARD = "";
					
					}
					if ($MEASURE !== ""){
						$rec = explode(":", $MEASURE);
						if (sizeof($rec) == 1 ){
							$sec = explode(".", $rec[0]);
							if (sizeof($sec) == 1) { //no dec.
								$newsec = $rec[0].".00";
							} else {
								if (strlen($sec[1]) == 1 ) {
									$newsec = $sec[0].".".$sec[1]."0";
								} else {
									$newsec = $sec[0].".".$sec[1];
								}
							}
							if (strlen($sec[0]) == 1) {
								$nMEASURE = "00:00:0".$newsec;
							} else {
								$nMEASURE = "00:00:".$newsec;
							}
						} else if (sizeof($rec) == 2 ) {
							$sec = explode(".",$rec[1]);
							if (sizeof($sec) == 1) { //no dec.
								$newsec = $rec[1].".00";
							} else {
								if (strlen($sec[1]) == 1 ) {
									$newsec = $sec[0].".".$sec[1]."0";
								} else {
									$newsec = $sec[0].".".$sec[1];
								}
							}
							if (strlen($sec[0]) == 1) {
								$sec = "0".$newsec;
							} else {
								$sec = $newsec;
							}
							if (strlen($rec[0]) == 1) {
								$min = "0".$rec[0];
							} else {
								$min = $rec[0];
							}
							$nMEASURE = "00:".$min.":".$sec;
						} else {
							$sec = explode(".",$rec[2]);
								if (sizeof($sec) == 1) { //no dec.
									$newsec = $rec[2].".00";
								} else {
									if (strlen($sec[1]) == 1 ) {
										$newsec = $sec[0].".".$sec[1]."0";
									} else {
										$newsec = $sec[0].".".$sec[1];
									}
								}
							if (strlen($sec[0]) == 1) {
								$sec = "0".$newsec;
							} else {
								$sec = $newsec;
							}
							if (strlen($rec[1]) == 1) {
								$min = "0".$rec[1];
							} else {
								$min = $rec[1];
							}
							if (strlen($rec[0]) == 1) {
								$hr = "0".$rec[0];
							} else {
								$hr = $rec[0];
							}
							if ($sec == "") {
								$sec = "00.00";
							}
							$nMEASURE = $hr.":".$min.":".$sec;
						}
					} else {
						$nMEASURE = "";
					
					}

				} else {		//田項 --成績用距離顯示
					$tresult = explode(".", $STANDARD);
					if (sizeof($tresult) > 1) {
						$dec =$tresult[1];
						if (strlen($tresult[1]) > 2 ) {
							$dec = substr($tresult[1],0,2);
							if (substr($tresult[1],2,1) > 4 ) {
								$dec = $dec+1;
								
							}
						}
						if (strlen($dec) == 1 ) {
							$dec = $dec."0";
						}
						$nSTANDARD = $tresult[0].".".$dec;
					} else {
						$nSTANDARD = $STANDARD."00";
					}
					$tresult = explode(".", $MEASURE);
					if (sizeof($tresult) > 1) {
						$dec =$tresult[1];
						if (strlen($tresult[1]) > 2 ) {
							$dec = substr($tresult[1],0,2);
							if (substr($tresult[1],2,1) > 4 ) {
								$dec = $dec+1;
								
							}
						}
						if (strlen($dec) == 1 ) {
							$dec = $dec."0";
						}
						$nMEASURE = $tresult[0].".".$dec;
					} else {
						$nMEASURE = $MEASURE."00";
					}
				}
				if (isset($keyid)){
				// edit old	
					$sql = mysqli_query($splink,"Select * from COMPETITIONITEM where  CH_DES=\"".$CH_DES."\" AND NOT keyid=\"".$keyid."\"");
					if (mysqli_num_rows($sql) > 0) {
						echo "same input";
					} else {
						if ($EVENT_CODE !== "" && $CH_DES !=="" ) {
							$sql = mysqli_query($splink,"Update COMPETITIONITEM SET Allowapply=\"".$Allowapply."\", CH_DES=\"".$CH_DES."\", EN_DES=\"".$EN_DES."\", GRADE=\"".$GRADE."\", TRACKFIELD=\"".$TRACKFIELD."\", SEX=\"".$SEX."\", SETLANE=\"".$SETLANE."\",INTERHOUSE=\"".$INTERHOUSE."\",INTERCLASS=\"".$INTERCLASS."\", OPENSCH=\"".$OPENSCH."\" , STANDARD=\"".$nSTANDARD."\",MEASURE=\"".$nMEASURE."\" where keyid=\"".$keyid."\"");
							echo $txtsuccesssave;
						} else {
							echo "MustinputEVENTCODEandCH_DES";
						}
					}
				} else {
					// insert new
						$sql = mysqli_query($splink,"Select * from COMPETITIONITEM where CH_DES=\"".$CH_DES."\"");
						if (mysqli_num_rows($sql) > 0) {
							echo "same input";
						} else {
							if ($EVENT_CODE !== "" && $CH_DES !=="" ) {
								$sql = mysqli_query($splink,"insert into COMPETITIONITEM (Allowapply, CH_DES, EN_DES, GRADE, TRACKFIELD, SEX, SETLANE, UNIT, INTERHOUSE, INTERCLASS, OPENSCH, STANDARD, MEASURE ) VALUES (\"".$Allowapply."\",\"".$CH_DES."\",\"".$EN_DES."\",\"".$GRADE."\",\"".$TRACKFIELD."\",\"".$SEX."\",\"".$SETLANE."\",\"".$UNIT."\",\"".$INTERHOUSE."\",\"".$INTERCLASS."\",\"".$OPENSCH."\",\"".$nSTANDARD."\",\"".$nMEASURE."\")");
								echo $txtsuccesssave;
							} else {
								echo "MustinputEVENTCODEandCH_DES";
							}
						}
				}
				unset($keyid);
				unset($Allowapply);
				unset($CH_DES);
				unset($EN_DES);
				unset($GRADE);
				unset($TRACKFIELD);
				unset($SEX);
				unset($SETLANE);
				unset($UNIT);
				unset($eventtype);
				unset($STANDARD);
				unset($MEASURE);
			} else {
				echo $msg;
			}
			
		}
		
		//finish php saveitem
		//php cancel
		if (isset($cancel)){
							unset($keyid);
				unset($Allowapply);
				unset($CH_DES);
				unset($EN_DES);
				unset($GRADE);
				unset($TRACKFIELD);
				unset($SEX);
				unset($SETLANE);
				unset($UNIT);
				unset($eventtype);
				unset($STANDARD);
				unset($MEASURE);
		}
		//finish php cancel
		//set filterlist
		$gradelist = "<option value=\"0\">".$txtall."</option>";
		$sql = mysqli_query($splink,"Select GRADE from COMPETITIONITEM group by GRADE ORDER BY GRADE");
		while ($row = mysqli_fetch_row($sql)){
			$tt = "txt".$row[0];
			$select="";
			if (isset($filterlist) && $filterlist== $row[0]) {
				$select=" selected";
			}
			if ($tt == "txtO") {
				$showsex = $txtnotvalid;
			} else {
				$showsex = $$tt;
			}
			$gradelist .= "<option value=\"".$row[0]."\" ".$select.">".$showsex."</option>";
		}
		
		//設定比賽項目
		if (!isset($filterlist)){
			$filterlists = "";
		} else {
			if ($filterlist == "0") {
				$filterlists = "";
			} else {
				$filterlists = " WHERE GRADE = \"".$filterlist."\" ";
			}
		}
		
		//顯示需要修改項目
		if (isset($selectedit)){
			$sql =mysqli_query($splink,"Select keyid, Allowapply, CH_DES, EN_DES, GRADE,TRACKFIELD, SEX, SETLANE, UNIT, INTERHOUSE, INTERCLASS, OPENSCH, STANDARD,MEASURE from COMPETITIONITEM where keyid=\"".$keyid."\"");
			while ($row = mysqli_fetch_row($sql)){
				$keyid=$row[0];
				$Allowapply=$row[1];
				$CH_DES= $row[2];
				$EN_DES= $row[3];
				$GRADE = $row[4];
				$TRACKFIELD = $row[5];
				$SEX=$row[6];
				$SETLANE = $row[7];
				$UNIT=$row[8];
				$eventtype = 0;
				if ($row[9] == 1) {
					$eventtype = 1;
				}
				if ($row[10] == 1 ) {
					$eventtype = 2;
				}
				if ($row[11] == 1 ) {
					$eventtype = 3;
				}
				$STANDARD= $row[12];
				$MEASURE = $row[13];
			}
		//	unset($keyid);
		}
		$sql =mysqli_query($splink,"Select keyid, Allowapply, CH_DES,EN_DES, GRADE,TRACKFIELD,SEX,SETLANE,UNIT,INTERHOUSE, INTERCLASS, OPENSCH, STANDARD from COMPETITIONITEM ". $filterlists. " ORDER BY GRADE, SEX,TRACKFIELD,SETLANE");
		?>
        
        <form action="setting.php" method="POST"> <input type="hidden" name="setcompetitionitem" />
        <?php if (isset($filterlist)) { ?><input type="hidden" name="filterlist" value="<?=$filterlist?>"  /><?php  } ?>
        <?php if (isset($selectedit)) { ?><input type="hidden" name="keyid" value="<?=$keyid?>"  /><?php  } ?>
		<div class="row uniform">
            <div class="6u 12u$(small)">
            <input type="checkbox" name="Allowapply" id="Allowapply" value="1" <?php if (isset($Allowapply) && $Allowapply == "1") { ?> checked="checked" <?php } ?> />
            <label for="Allowapply"><?=$txtallowapp?></label>
            </div>
            <div class="12u$">
            <label for="CH_DES"><?=$txtitemname."(".$txtchi.")"?></label>
            <input id="CH_DES" type="text" name="CH_DES" value="<?php if (isset($CH_DES)) { echo $CH_DES; } ?>" /><br />
            <label for="EN_DES"><?=$txtitemname."(".$txteng.")"?></label>
            <input id="EN_DES" type="text" name="EN_DES" value="<?php if (isset($EN_DES)) { echo $EN_DES; } ?>" /></td>
            </div>
            <div class="3u 12u$(small)">
                <label for="GRADE"><?=$txtgrade?></label>
                <div class="select-wrapper">
                <select name="GRADE" id="GRADE"><option value="A" <?php if (isset($sGRADE) && $sGRADE=="A") { ?> selected="selected" <?php } ?>><?=$txtA?></option>
                <option value="B" <?php if (isset($GRADE) && $GRADE=="B") { ?> selected="selected" <?php } ?>><?=$txtB?></option>
                <option value="C" <?php if (isset($GRADE) && $GRADE=="C") { ?> selected="selected" <?php } ?>><?=$txtC?></option>
                <option value="O" <?php if (isset($GRADE) && $GRADE=="O") { ?> selected="selected" <?php } ?>><?=$txtnotvalid?></option>
                </select>
                </div>
            </div>
             <div class="3u 12u$(small)">
                <label for="eventtype"><?=$txteventtype?></label>
                <div class="select-wrapper">
                <select name="eventtype" id="eventtype">
                <option><?=$txtnotvalid?></option>
                <option value="1" <?php if (isset($eventtype) && $eventtype=="1") { ?> selected="selected" <?php } ?>><?=$txtinterhouse?></option>
                <option value="2" <?php if (isset($eventtype) && $eventtype=="2") { ?> selected="selected" <?php } ?>><?=$txtinterclass?></option>
                <option value="3" <?php if (isset($eventtype) && $eventtype=="3") { ?> selected="selected" <?php } ?>><?=$txtopensch?></option>
                </select>
                </div>
            </div>
           
            <div class="3u 12u$(small)">
                <label for="TRACKFIELD"><?=$txttrackorfield?></label>
                <div class="select-wrapper">
                <select name="TRACKFIELD" id="TRACKFIELD"><option value="1" <?php if (isset($TRACKFIELD) && $TRACKFIELD=="1") { ?> selected="selected" <?php } ?>><?=$txtistrack?></option>
                <option value="2" <?php if (isset($TRACKFIELD) && $TRACKFIELD=="2") { ?> selected="selected" <?php } ?>><?=$txtisfield?></option></select>
                </div>
            </div>
            <div class="3u 12u$(small)">
                <label for="SEX"><?=$txtsex?></label>
                <div class="select-wrapper">
                <select name="SEX" id="SEX"><option value="1" <?php if (isset($sSEX) && $sSEX=="1") { ?> selected="selected" <?php } ?>><?=$txtboy?></option>
                <option value="2" <?php if (isset($SEX) && $SEX=="2") { ?> selected="selected" <?php } ?>><?=$txtgirl?></option>
                <option value="0" <?php if (isset($SEX) && $SEX=="0") { ?> selected="selected" <?php } ?>><?=$txtnotvalid?></option></select>
                </div>
            </div>
            <div class="12u$">
                <input type="checkbox" id="SETLANE" name="SETLANE" value="1" <?php if (isset($SETLANE) && $SETLANE == "1") { ?> checked="checked" <?php } ?> />
                <label for="SETLANE"><?=$txtneedsetlane?></label>
            </div>
            <div class="3u 12u$(small)">
                <label for="UNIT"><?=$txtunit?></label>
                <div class="select-wrapper">
                <select name="UNIT" id="UNIT"><option value="0" <?php if (isset($UNIT) && $UNIT=="0") { ?> selected="selected" <?php } ?>><?=$txtdistance?></option>
                <option value="1" <?php if (isset($sUNIT) && $sUNIT=="1") { ?> selected="selected" <?php } ?>><?=$txttimes?></option></select>
                </div>
            </div>        
             <div class="3u 12u$(small)">
            <label for="STANDARD"><?=$txtstandard?></label>
            <input id="STANDARD" type="text" name="STANDARD" value="<?php if (isset($STANDARD)) { echo $STANDARD; } ?>" /><br />
            </div>
             <div class="3u 12u$(small)">
            <label for="MEASURE"><?=$txtmeasurestandard?></label>
            <input id="MEASURE" type="text" name="MEASURE" value="<?php if (isset($MEASURE)) { echo $MEASURE; } ?>" /><br />
            </div>
             <div class="12u$">
            <?=$txtrecordfieldremark?><br />
            <?=$txtrecordtrackremark?>
            </div>
           <div class="12u$">
				<br /><ul class="actions">
    	        <input type="submit" name="saveitem" value="<?=$txtsave?>"  class="special"><?php if (isset($selectedit)) { ?> &nbsp;<input type="submit" name="cancel" value="<?=$txtcancel?>" /><?php } ?>
          		</ul>
            </div>
        </div>
        </form><br />        
        
        <hr />
        <br />
		<form action="setting.php" method="GET"><input type="hidden" name="setcompetitionitem" />
        <div class="row uniform">
        	<div class="3u 12u$(xsmall)">
            <label for="filterlist"><?=$txtshowgrade?></label>
            <div class="select-wrapper" align="center">
            <select name="filterlist" onchange="submit()" id="filterlist"><?=$gradelist?></select>
            </div>
            </div>
        </div>
        </form>
		<table border="1"><tr><th><?=$txtallowapp?></th><th><?=$txtitemname?></th>
        <th style="text-align:center"><?=$txtgrade?></th>
        <th style="text-align:center"><?=$txttrackorfield?></th>
        <th style="text-align:center"><?=$txtsex?></th>
        <th style="text-align:center"><?=$txtneedsetlane?></th>
        <th style="text-align:center"><?=$txtunit?></th>
        <th style="text-align:center"><?=$txtstandard?></th>
        <th><?=$txtfunction?></th></tr>
		<?php
		while ($row = mysqli_fetch_row($sql)){
			if ($row[1] == 1){
				$app = "√";
			} else {
				$app = "";
			}
			if ($row[4]== "A") {
				$grade = $txtA;
			} else if ($row[4] =="B") {
				$grade = $txtB;
			} else if ($row[4] =="C" ){
				$grade = $txtC;
			} else {
				$grade = $txtnotvalid;
			}
			if ($row[5] == 1) {
				$trackfield= $txtistrack;
			} else {
				$trackfield = $txtisfield;
			}
			if ($row[6] == 1) {
				$sex = $txtboy;
			} else if ($row[6] == 2) {
				$sex = $txtgirl;
			} else {
				$sex = $txtnotvalid;
			}
			if ($row[7] == 1) {
				$needlane = "√";
			} else {
				$needlane = "";
			}
			if ($row[8] == 0 ) {
				$unit = $txtdistance;
			} else {
				$unit = $txttimes;
			}
			$specialtype="";
			if ($row[9] ==1 ) {
				$specialtype =  "(".$txtinterhouse.")";
			}
			if ($row[10] == 1) {
				$specialtype = "(".$txtinterclass.")";
			}
			if ($row[11] == 1) {
				$specialtype = "(".$txtopensch.")";
			}
			$standard = $row[12];
			?>
			<tr><td align="center"><?=$app?></td><td><?=$txtchi?>：<?=$row[2]?><br /><?=$txteng?>：<?=$row[3]?></td>
            <td align="center"><?=$grade.$specialtype?></td><td align="center"><?=$trackfield?></td>
            <td align="center"><?=$sex?></td><td align="center"><?=$needlane?></td><td><?=$unit?></td>
            <td><?=$standard?></td>
			<td>
            <form action="setting.php" method="GET"><input type="hidden" name="setcompetitionitem" /> <?php if (isset($filterlist)) { ?><input type="hidden" name="filterlist" value="<?=$filterlist?>"  /><?php  } ?>
            <input type="hidden" name="keyid" value="<?=$row[0]?>" /><input type="submit" name="selectedit" value="<?=$txtedit?>" /></form>
            </td>
			</tr>
			<?php
		}
		?>
		</table>
		<?php
	}
	//完成設定比賽項目

	//設定最高記錄
	if (isset($sethighestrecord)){
		//php save record
		if (isset($savebestrecord)){
			$sql = mysqli_query($splink,"Select UNIT from COMPETITIONITEM where keyid=\"".$COMPETITION_ID."\"");
			while ($row = mysqli_fetch_row($sql)){
				$unit = $row[0];
			}
			if ($unit == 0 ) {
				$rec = explode(":", $RECORD);
				if (sizeof($rec) == 1 ){
					
					$sec = explode(".", $rec[0]);
					if (sizeof($sec) == 1) { //no dec.
						$newsec = $rec[0].".00";
					} else {
						if (strlen($sec[1]) == 1 ) {
							$newsec = $sec[0].".".$sec[1]."0";
						} else {
							$newsec = $sec[0].".".$sec[1];
						}
					}
					if (strlen($sec[0]) == 1) {
						$record = "00:00:0".$newsec;
					} else {
						$record = "00:00:".$newsec;
					}
					
					
					/*
					$sec = explode(".", $rec[0]);
					if (strlen($sec[0]) == 1) {
						$record = "00:00:0".$RECORD;
					} else {
						$record = "00:00:".$RECORD;
					}
					*/
					
				} else if (sizeof($rec) == 2 ) {
					
								$sec = explode(".",$rec[1]);
								if (sizeof($sec) == 1) { //no dec.
									$newsec = $rec[1].".00";
								} else {
									if (strlen($sec[1]) == 1 ) {
										$newsec = $sec[0].".".$sec[1]."0";
									} else {
										$newsec = $sec[0].".".$sec[1];
									}
								}
								if (strlen($sec[0]) == 1) {
									$sec = "0".$newsec;
								} else {
									$sec = $newsec;
								}
								if (strlen($rec[0]) == 1) {
									$min = "0".$rec[0];
								} else {
									$min = $rec[0];
								}
								$record = "00:".$min.":".$sec;
								
					/*
					$sec = explode(".",$rec[1]);
					if (strlen($sec[0]) == 1) {
						$sec = "0".$rec[1];
					} else {
						$sec = $rec[1];
					}
					if (strlen($rec[0]) == 1) {
						$min = "0".$rec[0];
					} else {
						$min = $rec[0];
					}
					$record = "00:".$min.":".$sec;
					*/
				} else {
					
								$sec = explode(".",$rec[2]);
									if (sizeof($sec) == 1) { //no dec.
										$newsec = $rec[2].".00";
									} else {
										if (strlen($sec[1]) == 1 ) {
											$newsec = $sec[0].".".$sec[1]."0";
										} else {
											$newsec = $sec[0].".".$sec[1];
										}
									}
								if (strlen($sec[0]) == 1) {
									$sec = "0".$newsec;
								} else {
									$sec = $newsec;
								}
								if (strlen($rec[1]) == 1) {
									$min = "0".$rec[1];
								} else {
									$min = $rec[1];
								}
								if (strlen($rec[0]) == 1) {
									$hr = "0".$rec[0];
								} else {
									$hr = $rec[0];
								}
								if ($sec == "") {
									$sec = "00.00";
								}
								$record = $hr.":".$min.":".$sec;
					
					/*
					$sec = explode(".",$rec[2]);
					if (strlen($sec[0]) == 1) {
						$sec = "0".$rec[2];
					} else {
						$sec = $rec[2];
					}
					if (strlen($rec[1]) == 1) {
						$min = "0".$rec[1];
					} else {
						$min = $rec[1];
					}
					if (strlen($rec[0]) == 1) {
						$hr = "0".$rec[0];
					} else {
						$hr = $rec[0];
					}
					
					$record = $hr.":".$min.":".$sec;
					*/
				}
				if ($STANDARD !== ""){
					$rec = explode(":", $STANDARD);
					if (sizeof($rec) == 1 ){
						$sec = explode(".", $rec[0]);
						if (sizeof($sec) == 1) { //no dec.
							$newsec = $rec[0].".00";
						} else {
							if (strlen($sec[1]) == 1 ) {
								$newsec = $sec[0].".".$sec[1]."0";
							} else {
								$newsec = $sec[0].".".$sec[1];
							}
						}
						if (strlen($sec[0]) == 1) {
							$standard = "00:00:0".$newsec;
						} else {
							$standard = "00:00:".$newsec;
						}
						/*
						$sec = explode(".", $rec[0]);
						if (strlen($sec[0]) == 1) {
							$standard = "00:00:0".$STANDARD;
						} else {
							$standard = "00:00:".$STANDARD;
						}
						*/
						
					} else if (sizeof($rec) == 2 ) {
						
						
								$sec = explode(".",$rec[1]);
								if (sizeof($sec) == 1) { //no dec.
									$newsec = $rec[1].".00";
								} else {
									if (strlen($sec[1]) == 1 ) {
										$newsec = $sec[0].".".$sec[1]."0";
									} else {
										$newsec = $sec[0].".".$sec[1];
									}
								}
								if (strlen($sec[0]) == 1) {
									$sec = "0".$newsec;
								} else {
									$sec = $newsec;
								}
								if (strlen($rec[0]) == 1) {
									$min = "0".$rec[0];
								} else {
									$min = $rec[0];
								}
								$standard = "00:".$min.":".$sec;
						
						/*
						$sec = explode(".",$rec[1]);
						if (strlen($sec[0]) == 1) {
							$sec = "0".$rec[1];
						} else {
							$sec = $rec[1];
						}
						if (strlen($rec[0]) == 1) {
							$min = "0".$rec[0];
						} else {
							$min = $rec[0];
						}
						$standard = "00:".$min.":".$sec;
						
						*/
					} else {
								$sec = explode(".",$rec[2]);
									if (sizeof($sec) == 1) { //no dec.
										$newsec = $rec[2].".00";
									} else {
										if (strlen($sec[1]) == 1 ) {
											$newsec = $sec[0].".".$sec[1]."0";
										} else {
											$newsec = $sec[0].".".$sec[1];
										}
									}
								if (strlen($sec[0]) == 1) {
									$sec = "0".$newsec;
								} else {
									$sec = $newsec;
								}
								if (strlen($rec[1]) == 1) {
									$min = "0".$rec[1];
								} else {
									$min = $rec[1];
								}
								if (strlen($rec[0]) == 1) {
									$hr = "0".$rec[0];
								} else {
									$hr = $rec[0];
								}
								if ($sec == "") {
									$sec = "00.00";
								}
								$standard = $hr.":".$min.":".$sec;
						/*
						$sec = explode(".",$rec[2]);
						if (strlen($sec[0]) == 1) {
							$sec = "0".$rec[2];
						} else {
							$sec = $rec[2];
						}
						if (strlen($rec[1]) == 1) {
							$min = "0".$rec[1];
						} else {
							$min = $rec[1];
						}
						if (strlen($rec[0]) == 1) {
							$hr = "0".$rec[0];
						} else {
							$hr = $rec[0];
						}
						
						$standard = $hr.":".$min.":".$sec;
						*/
					}
				} else {
					$standard = "";
				}
			} else {
				$record = $RECORD;
				$standard = $STANDARD;
			}
			if (isset($keyid)){
				$sql = mysqli_query($splink,"Update BEST_RECORD SET SCHYEAR=\"".$SCHYEAR."\", COMPETITION_ID=\"".$COMPETITION_ID."\" , NAME=\"".$NAME."\", HOUSE=\"".$HOUSE."\", RECORD=\"".$record."\", STANDARD=\"".$standard."\" where keyid=\"".$keyid."\"");
				$msg = $txtsuccesssave;
				unset($keyid);	
			} else {
				$sql = mysqli_query($splink,"Insert into BEST_RECORD (SCHYEAR,COMPETITION_ID, NAME, HOUSE, RECORD, STANDARD) VALUES (\"".$SCHYEAR."\", \"".$COMPETITION_ID."\", \"".$NAME."\",\"".$HOUSE."\", \"".$record."\",\"".$standard."\")");
				$msg =  $txtsuccesssave."<br>";
			}
		}
		//完成PHP SAVE RECORD
		//PHP DEL RECORD
		if (isset($delbestrecord)) {
			$sql= mysqli_query($splink,"delete from BEST_RECORD where keyid=\"".$keyid."\"");
			unset($keyid);
			$msg = $txtsuccessdelete;
		}
		//完成DEL RECORD
		//顯示修改記錄內容
		if (isset($editbestrecord)){
			$sql = mysqli_query($splink,"Select SCHYEAR, COMPETITION_ID, NAME, HOUSE, RECORD, STANDARD from BEST_RECORD where keyid=\"".$keyid."\"");
			while ($row = mysqli_fetch_row($sql)){
				$sSCHYEAR=$row[0];
				$sCOMPETITION_ID=$row[1];
				$sNAME = $row[2];
				$sHOUSE= $row[3];
			//	$sRECORD=$row[4];
			//	$sSTANDARD=$row[5];
				$record = explode(":",$row[4]);
				if (sizeof($record) > 2 ) {
					//time
					$sRECORD = "";
					if ($record[0] !== "00") {
						if (substr($record[0],0,1) == "0" ) {
							$sRECORD .= substr($record[0],-1).":";
						} else {
							$sRECORD .= $recrod[0].":";
						}
					}
					if ($record[1] !== "00") {
						if (substr($record[1],0,1) == "0" ) {
							$sRECORD .= substr($record[1],-1).":";
						} else {
							$sRECORD .= $recrod[0].":";
						}
					}
					$sRECORD .=$record[2];
				} else {
					//distance
					$sRECORD = $row[4];
				}
				$standard = explode(":",$row[5]);
				if (sizeof($standard) > 2 ) {
					//time
					$sSTANDARD = "";
					if ($standard[0] !== "00") {
						if (substr($standard[0],0,1) == "0" ) {
							$sSTANDARD .= substr($standard[0],-1).":";
						} else {
							$sSTANDARD .= $standard[0].":";
						}
					}
					if ($standard[1] !== "00") {
						if (substr($standard[1],0,1) == "0" ) {
							$sSTANDARD .= substr($standard[1],-1).":";
						} else {
							$sSTANDARD .= $standard[0].":";
						}
					}
					$sSTANDARD .=$standard[2];
				} else {
					//distance
					$sSTANDARD = $row[5];
				}
			}
		}
		//完成顯示修改記錄內容
		$sql = mysqli_query($splink,"Select keyid, CH_DES, EN_DES from COMPETITIONITEM ORDER BY GRADE, TRACKFIELD, SEX");
		$complist="";
		while ($row = mysqli_fetch_row($sql)){
			if (isset($sCOMPETITION_ID) && $sCOMPETITION_ID == $row[0] ) {
				$selected = " selected";
			} else {
				$selected = "";
			}
			if ($lang == "chi") {
				$item = $row[1];
			} else {
				$item = $row[2];
			}
			$complist .= "<option value=\"".$row[0]."\"".$selected." >".$item."</option>";
		}
		?>
        <h2><?=$txtsethighestrecord?></h2>
        <center><?=$msg?></center>
        
        
        <form action="setting.php" method="post" ><input type="hidden" name="sethighestrecord" />
        <?php if (isset($keyid)){ ?><input type="hidden" name="keyid" value="<?=$keyid?>" /><?php } ?>
        <div class="row uniform">
            <div class="3u 12u$(small)">
            <label for="SCHYEAR"><?=$txtschyear?></label>
            <input id="SCHYEAR" type="text" name="SCHYEAR" value="<?php if (isset($sSCHYEAR)){ echo $sSCHYEAR;} ?>" placeholder="<?=$txtschyear?>"/>
            </div>
            <div class="9u 12u$(small)">
            <label for="COMPETITION_ID"><?=$txtcompetitionitem?></label>
            	<div class="select-wrapper">
            	<select name="COMPETITION_ID" ><?=$complist?></select>
				</div>
            </div>
            <div class="6u 12u$(small)">
            <label for="NAME"><?=$txtname?></label>
            <input type="text" id="NAME" name="NAME" value="<?php if (isset($sNAME)){ echo $sNAME;} ?>" placeholder="<?=$txtname?>"/>
			</div>
            <div class="6u 12u$(small)">
            <label for="HOUSE"><?=$txthouse?></label>
            <input type="text" id="HOUSE" name="HOUSE" value="<?php if (isset($sHOUSE)){ echo $sHOUSE;} ?>" placeholder="<?=$txthouse?>"/>
			</div>
            <div class="12u$">
			<?=$txtrecordinputremark?></div>
            <div class="6u 12u$(small)">
            <label for="RECORD"><?=$txtrecord?></label>
            <input type="text" id="RECORD" name="RECORD" value="<?php if (isset($sRECORD)){ echo $sRECORD;} ?>" placeholder="<?=$txtrecord?>"/>
			</div>
            <div class="6u 12u$(small)">
            <label for="STANDARD"><?=$txtstandard?></label>
            <input type="text" id="STANDARD" name="STANDARD" value="<?php if (isset($sSTANDARD)){ echo $sSTANDARD;} ?>" placeholder="<?=$txtstandard?>"/>
			</div>
            <div class="12u$">
            	<ul class="actions">
            	<input type="submit" name="savebestrecord" value="<?=$txtsave?>" class="special"/>&nbsp;<input type="submit" name="" value="<?=$txtcancel?>"/>
                </ul>
            </div>
        </div>
        </form>
        <hr />
        <table border="1">
        <thead><tr><th><?=$txtschyear?></th><th><?=$txtcompetitionitem?></th><th><?=$txtname?></th>
        <th><?=$txthouse?></th><th><?=$txtrecord?></th><th><?=$txtstandard?></th><th><?=$txtfunction?></th></tr>
        </thead>
        <?php
		$sql = mysqli_query($splink,"Select A.keyid, A.SCHYEAR, B.CH_DES,B.EN_DES, A.NAME, A.HOUSE, A.RECORD, A.STANDARD, B.UNIT from BEST_RECORD AS A inner join COMPETITIONITEM AS B ON A.COMPETITION_ID=B.keyid ORDER BY A.COMPETITION_ID");
		$x=0;
		while ($row = mysqli_fetch_row($sql)){
			if ($lang == "chi") {
				$compitem = $row[2];

			} else {
				$compitem = $row[3];
			}
			if ($row[8] ==0) {
				$unit = $txttimes;
			} else {
				$unit = $txtdistance;
			}			?>
            <tr><td><?=$row[1]?></td>
            <td><?=$compitem?></td>
            <td><?=$row[4]?></td>
            <td><?=$row[5]?></td>
            <td><?=$unit." ".$row[6]?></td>
            <td><?=$unit." ".$row[7]?></td>
            <td><form action="setting.php" method="post" ><input type="hidden" name="sethighestrecord" />
            <input type="hidden" name="keyid" value="<?=$row[0]?>" />
            <input type="submit" name="editbestrecord" value="<?=$txtedit?>" class="special"/>
            <input type="submit" name="delbestrecord" value="<?=$txtdelete?>" />
            </form>
            </tr>
            <?php
            if ($x/8 ==1 ) { ?>
				<tr><th><?=$txtschyear?></th><th><?=$txtcompetitionitem?></th><th><?=$txtname?></th>
        <th><?=$txthouse?></th><th><?=$txtrecord?></th><th><?=$txtstandard?></th><th><?=$txtfunction?></th></tr>
    	        <?php
				$x=0;
			}
			$x++;
		}
		?>
        </table>
        <?php
	}
	//完成設定最高記錄
	//下載文件
	if (isset($downloaddoc)){
		?>
        <h2><?=$txtdownloaddoc?></h2>
        <form action="makeword.php" method="POST"><input type="submit" name="downloadeventbook" value="<?=$txtdownloadeventbook?>" /></form>
        <?php
	}
	//完成下載文件
	
	require "templates/footer.php";
	mysqli_close($splink);
} else {
	require "language/eng.php";
	echo $txtnoright;
	echo '<meta charset="utf-8"';
	echo '<meta http-equiv=REFRESH CONTENT=2;url=index.php>';
}
?>