<?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;
		}

//完成設定學年
//學年選擇表		
			$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>";
			}
//完成學年選擇表

//設定計分方式

/*swimming gala
	$absscore = 1;  // 個人項目缺席扣分
	$attscore = 1;	// 個人項目出席並達標加分
	$singlerank = array("9","7","6","5","4","3","2","1"); //25米個人項目排名得分
	$singlerank = array("18","14","12","10","8","6","4","2");//50米或以上個人項目排名得分
	$houserank = array("36","28","30","20","16","12","8","2"); //社制項目排名得分
	$newrecscore = 2; //個人項目新記錄加分
*/

	$absscore = 1;  // 個人項目缺席扣分
	$attscore = 1;	// 個人項目出席並達標加分
	$singlerank = array("9","7","6","5","4","3","2","1"); //個人項目排名得分
	$houserank = array("18","14","12","10","8","6","4","2");//社制項目排名得分
	$newrecscore = 2; //個人項目新記錄加分
	$gradearray = array("A","B","C");
	$sexarray = array("M","F");
	$housearray = array("R","Y","B","G");
//完成設定計分方式


//讀取學生組別
	if ($role == 2) {
		
		$sql = mysqli_query($splink,"Select DOB , SCHHOUSE,SEX from ".$targetschoolyear."_studentinfo where STUID=\"".$stuid."\"");
		while ($row= mysqli_fetch_row($sql)){
			$yearofbirth = substr($row[0],0,4);
			$SCHHOUSE= $row[1];
			if ($row[2] =="M") {
				$sexb1g2 = 1;
			} else {
				$sexb1g2 = 2;
			}
		}
		$sql = mysqli_query($splink, "Select MAX( CASE WHEN grade=\"A\" THEN gradeyear END ) ,MAX( CASE WHEN grade=\"B\" THEN gradeyear END) , MAX(CASE WHEN grade=\"C\" THEN gradeyear END ) from gradeyear where SCHYEAR = \"".$targetschoolyear."\"");
		while ($row=mysqli_fetch_row($sql)){
			if ($yearofbirth <= $row[2]) {
				$STUGRADE = "C";
			} else if ( $yearofbirth <= $row[1]){
				$STUGRADE="B";
			} else {
				$STUGRADE="A";
			}
		}
	}
//讀取學生組別
//讀取學生組別年齡
		$sql = mysqli_query($splink, "Select MAX( CASE WHEN grade=\"A\" THEN gradeyear END ) ,MAX( CASE WHEN grade=\"B\" THEN gradeyear END) , MAX(CASE WHEN grade=\"C\" THEN gradeyear END ) from gradeyear where SCHYEAR = \"".$targetschoolyear."\"");
		while ($row = mysqli_fetch_row($sql)){
			$gradeAyr= $row[0];
			$gradeByr = $row[1];
			$gradeCyr = $row[2];
		}
//完成讀取學生組別年齡


	require "templates/header.php"; 
	//輸入分數
	if (isset($inputresult)){
		//php save result
		if (isset($submitresult)){
			$x = 0;
			$error = 0;
			while ($x < sizeof($targetSTUID)){
				$result = "r".$targetSTUID[$x];
				$attendance = "a".$targetSTUID[$x];
				//檢測成積是否出現錯誤
				if ($eventtype == 1 || $eventtype == 3) {  //徑項
					if ($$result !== "") {  //如果輸入非空白
						$tresult = explode(":", $$result);
						$size = sizeof($tresult) ;
						if ( $size > 3 ) {
							$error = 1;
							if ($eventtype == 1) {
								$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
								while ($row = mysqli_fetch_row($sql)){
									if ($lang == "chi") {
										$stname = $row[2];
									} else {
										$stname = $row[3];
									}
									$stclass = $row[0];
									$stclassno = $row[1];
									$msg .= $stclass.$stclassno." ".$stname." ".$txtresultinputerror."<br>";
								}
							} else {
								$msg .= $txttracknum.$targetSTUID[$x]." ".$txtresultinputerror."<br>";
							}
						}
						if ($size == 2) {
							if  ($tresult[0] > 59) {
								$error = 1;
								if ($eventtype == 1) {
									$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
									while ($row = mysqli_fetch_row($sql)){
										if ($lang == "chi") {
											$stname = $row[2];
										} else {
											$stname = $row[3];
										}
										$stclass = $row[0];
										$stclassno = $row[1];
										$msg .= $stclass.$stclassno." ".$stname." ".$txtresultinputerror."<br>";
									}
								} else {
									$msg .= $txttracknum.$targetSTUID[$x]." ".$txtresultinputerror."<br>";
								}
							}
						}
						$sizeindex = $size - 1;	
						$t2result = explode(".",$tresult[$sizeindex]) ;
						if (sizeof($t2result) > 2 ) {
							$error = 1;
							if ($eventtype == 1) {
								$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
								while ($row = mysqli_fetch_row($sql)){
									if ($lang == "chi") {
										$stname = $row[2];
									} else {
										$stname = $row[3];
									}
									$stclass = $row[0];
									$stclassno = $row[1];
									$msg .= $stclass.$stclassno." ".$stname." ".$txtresultinputerror."<br>";
								}
							} else {
								$msg .= $txttracknum.$targetSTUID[$x]." ".$txtresultinputerror."<br>";
							}
						}
						if ($t2result[0] > 59) {
							$error = 1;
							if ($eventtype == 1) {
								$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
								while ($row = mysqli_fetch_row($sql)){
									if ($lang == "chi") {
										$stname = $row[2];
									} else {
										$stname = $row[3];
									}
									$stclass = $row[0];
									$stclassno = $row[1];
									$msg .= $stclass.$stclassno." ".$stname." ".$txtresultinputerror."<br>";
								}
							} else {
								$msg .= $txttracknum.$targetSTUID[$x]." ".$txtresultinputerror."<br>";
							}
						}
					} 
				} else if ($eventtype == 2) {   //田項
					$tresult = explode(".", $$result);
					if (sizeof($tresult) > 2 ) {
						$error = 1;
						$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
						while ($row = mysqli_fetch_row($sql)){
							if ($lang == "chi") {
								$stname = $row[2];
							} else {
								$stname = $row[3];
							}
							$stclass = $row[0];
							$stclassno = $row[1];
						}
						$msg .= $stclass.$stclassno." ".$stname." ".$txtresultinputerror."<br>";
					}
				}
				//檢測出席是否出現錯誤
				if (!isset($$attendance)){
					$error = 1;
					if ($eventtype !== "3") {
						$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
						while ($row = mysqli_fetch_row($sql)){
							if ($lang == "chi") {
								$stname = $row[2];
							} else {
								$stname = $row[3];
							}
							$stclass = $row[0];
							$stclassno = $row[1];
							$msg .= $stclass.$stclassno." ".$stname." ".$txtattendanceinputerror."<br>";
						}
					} else {
						$msg .= $txttracknum.$targetSTUID[$x]." ".$txtattendanceinputerror."<br>";
					}
				}
				//檢測會否出現有出席但沒有成績
				if (isset($$attendance) && $$attendance == 3 && $$result !== "") {
					$error = 1;
					$sql = mysqli_query($splink,"Select CLASSCODE, CLASSNO, CHNAME, ENNAME from studentinfo where STUID=\"".$targetSTUID[$x]."\"");
					while ($row = mysqli_fetch_row($sql)){
						if ($lang == "chi") {
							$stname = $row[2];
						} else {
							$stname = $row[3];
						}
						$stclass = $row[0];
						$stclassno = $row[1];
					}
					$msg .= $stclass.$stclassno." ".$stname." ".$txthaveattendancebutnoresultinputerror."<br>";
				}
				$x++;
			}
			//輸入沒問題的話便可輸入到數據庫
			if ($error == 0) {
				$x = 0;
				while ($x < sizeof($targetSTUID)){
					$result = "r".$targetSTUID[$x];
					if ($eventtype == 1 || $eventtype == 3) {  //徑項  --成績用時間顯示
						if ($$result !== ""){
							$rec = explode(":", $$result);
							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) {
									$result = "00:00:0".$newsec;
								} else {
									$result = "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];
								}
								$result = "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";
								}
								$result = $hr.":".$min.":".$sec;
							}
						} else {
							$result = "";
						
						}
					} else {		//田項 --成績用距離顯示
						$tresult = explode(".", $$result);
						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";
							}
							$result = $tresult[0].".".$dec;
						} else {
							$result = $$result."00";
						}
					}
					$result = str_replace(" ","", $result) ;   //移除result內的空格
					$attendance = "a".$targetSTUID[$x];
					if ($eventtype == 4 ) { //公開組
						
					} else if ($eventtype == 3 ) { //社際
						if ($targetSTUID[$x] == "1") {
							$targetHOUSE = "R";
						} else if ($targetSTUID[$x] == "2") {
							$targetHOUSE = "Y";
						} else if ($targetSTUID[$x] == "3") {
							$targetHOUSE = "B";
						} else if ($targetSTUID[$x] == "4") {
							$targetHOUSE = "G";
						} else if ($targetSTUID[$x] == "5") {
							$targetHOUSE = "R";
						} else if ($targetSTUID[$x] == "6") {
							$targetHOUSE = "Y";
						} else if ($targetSTUID[$x] == "7") {
							$targetHOUSE = "B";
						} else {
							$targetHOUSE = "G";
						}
						if ($targetSTUID[$x] < 5 ) {
							$targetteam = "A";
						} else {
							$targetteam = "B";
						}
						$csql = mysqli_query($splink,"Select * from INTERHOUSE_RESULT where SCHHOUSE=\"".$targetHOUSE."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND TEAM = \"".$targetteam."\"");
						if (mysqli_num_rows($csql) > 0 ) {
							$sql= mysqli_query($splink,"Update INTERHOUSE_RESULT SET RESULT = \"".$result."\", ATTENDANCE=\"".$$attendance."\" WHERE SCHHOUSE=\"".$targetHOUSE."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND TEAM = \"".$targetteam."\" AND SCHYEAR=\"".$todayschyr."\"");
						} else {
							$sql = mysqli_query($splink,"Insert into INTERHOUSE_RESULT ( SCHYEAR, COMPETITION_ID, SCHHOUSE,TEAM, RESULT, ATTENDANCE ) VALUES (\"".$todayschyr."\",\"".$COMPETITION_ID."\",\"".$targetHOUSE."\",\"".$targetteam."\", \"".$result."\",\"".$$attendance."\")");
						}
					} else {   //個人項目
						if (isset($heatfinal) && $heatfinal == 2) {
							$sql = mysqli_query($splink,"Update TRACKEVENT_FINAL_LANE SET RESULT =\"".$result."\",ATTENDANCE=\"".$$attendance."\" WHERE STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
						} else if (isset($heatfinal) && $heatfinal == 1)  {
							$asql = mysqli_query($splink,"Update APPLICATION_COMPETITION SET ATTENDANCE=\"".$$attendance."\" WHERE STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND SCHYEAR=\"".$todayschyr."\"");
							$sql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET RESULT =\"".$result."\", ATTENDANCE=\"".$$attendance."\" WHERE STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
						} else {
							$asql = mysqli_query($splink,"Update APPLICATION_COMPETITION SET ATTENDANCE=\"".$$attendance."\" WHERE STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND SCHYEAR=\"".$todayschyr."\"");
							$sql = mysqli_query($splink,"Select * from HEAT_RESULT where STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
							if (mysqli_num_rows($sql) > 0 ) {
								$sql = mysqli_query($splink,"Update HEAT_RESULT SET RESULT =\"".$result."\" WHERE STUID=\"".$targetSTUID[$x]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
							} else {
								$sql = mysqli_query($splink,"Insert into HEAT_RESULT ( COMPETITION_ID, STUID, RESULT ) VALUES (\"".$COMPETITION_ID."\",\"".$targetSTUID[$x]."\", \"".$result."\")");
							}
						}
					}
					$result = "r".$targetSTUID[$x];
					$attend = "a".$targetSTUID[$x];
					unset($$result);
					unset($$attend);
					$x++;
				}
				$msg = $txtsuccesssave;
			} else {
				$msg = $txtfailsave."<br>".$msg;
			}
		}
		//php finish save result
		//php cancel
		if (isset($cancel)){
			unset($COMPETITION_ID);
		}
		//finish php cancel
		?>
        <h2><?=$txtinputresult?></h2>
        <?php
		if (isset($COMPETITION_ID) && $COMPETITION_ID !=="") {
		} else {
			?>
            <form action="eventday.php" method="POST"><input type="hidden" name="inputresult" />
            <input type="radio" name="eventtype" value="1" id="eventtype1" onchange="submit()" <?php if (isset($eventtype) && $eventtype == 1) { ?> checked="checked" <?php } ?>/><label for="eventtype1"><?=$txtistrack?></label>
            <input type="radio" name="eventtype" value="2" id="eventtype2" onchange="submit()" <?php if (isset($eventtype) && $eventtype == 2) { ?> checked="checked" <?php } ?> /><label for ="eventtype2"><?=$txtisfield?></label>
            <input type="radio" name="eventtype" value="3" id="eventtype3" onchange="submit()" <?php if (isset($eventtype) && $eventtype == 3) { ?> checked="checked" <?php } ?> /><label for ="eventtype3"><?=$txtinterhouse?></label>
            </form>
            <?php 
		}
		if (isset($eventtype)){
			if (isset($COMPETITION_ID) && $COMPETITION_ID !=="") {
			} else {
				if ($eventtype == 3) {
					$eventneed =  "TRACKFIELD=\"1\" AND INTERHOUSE=\"1\" AND INTERCLASS=\"0\" ";
				} else {
					$eventneed =  "TRACKFIELD=\"".$eventtype."\" AND INTERHOUSE=\"0\" AND INTERCLASS=\"0\" ";
				}
				$sql = mysqli_query($splink,"Select keyid, CH_DES, EN_DES from COMPETITIONITEM where ".$eventneed." ORDER BY INTERHOUSE, INTERCLASS, GRADE, SEX, keyid");
				$selectlist = "";
				while ($row = mysqli_fetch_row($sql)){
					if (isset($COMPETITION_ID) && $COMPETITION_ID == $row[0]) {
						$selected = " selected=\"selected\"";
					} else {
						$selected = "";
					}
					if ($lang == "chi") {
						$showname = $row[1];
					} else {
						$showname = $row[2];
					}
					$selectlist .= "<option value=\"".$row[0]."\" ".$selected.">".$showname."</option>";
				}
				?>
				<form action="eventday.php" method="POST"><input type="hidden" name="inputresult" /><input type="hidden" name="eventtype" value="<?=$eventtype?>" />
				<div class="select-wrapper"><select name="COMPETITION_ID" onchange="submit()"><option value=""><--<?=$txtselectevent?>--></option>
				<?=$selectlist?></select></div>
				</form>
				<?php 
			}
			if (isset($COMPETITION_ID) && $COMPETITION_ID !== "") {
				$sql = mysqli_query($splink,"Select CH_DES, EN_DES,UNIT from COMPETITIONITEM where keyid=\"".$COMPETITION_ID."\"");
				while ($row = mysqli_fetch_row($sql)){
					if ($lang == "chi") {
						$showname = $row[0];
					} else {
						$showname = $row[1];
					}
					if ($row[2] == 0) {
						$unit = $txttime;
					} else {
						$unit = $txtdistance."(".$txtmetre.")";
					}
				}
				?>
                <h3><?=$showname?></h3>
                <?php
				$ready=1;
				if ($eventtype == "1") {   //track
					$sql = mysqli_query($splink,"Select * from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					?>
                    <form action="eventday.php" method="POST"><input type="hidden" name="inputresult" />
                    <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>"><input type="hidden" name="eventtype" value="<?=$eventtype?>" />
                    <?php
					if (mysqli_num_rows($sql) > 8 ) {  //徑項多於8人報名需要分初賽同決賽
						$ready=0;
						?>
                        <input type="radio" name="heatfinal" value="1" id="heatfinal1" onchange="submit()" <?php if (isset($heatfinal) && $heatfinal == 1) {?> checked="checked" <?php } ?> /><label for="heatfinal1"><?=$txt1stheat?></label>
                        <input type="radio" name="heatfinal" value="2" id="heatfinal2" onchange="submit()" <?php if (isset($heatfinal) && $heatfinal == 2) {?> checked="checked" <?php } ?>/><label for="heatfinal2"><?=$txtfinal?></label>
                        <?php
						if (isset($heatfinal) && $heatfinal== 1 ) {
							$sql = mysqli_query($splink,"Select EVENT_ID from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" GROUP BY EVENT_ID ORDER BY EVENT_ID");
							?>
                            <br />
                            <label for="event_id"><?=$txteventid?>：</label>
                            <div class="select-wrapper">
                            <select name="EVENT_ID" onchange="submit()" id="event_id"><option value=""><--<?=$txtselectevent?>--></option>
                            <?php
							while ($row = mysqli_fetch_row($sql)){
								if (isset($EVENT_ID) && $EVENT_ID == $row[0]) {
									$selected = "selected=\"selected\"";
									$ready=1;
								} else {
									$selected = "";
								}
								?>
                                <option value="<?=$row[0]?>" <?=$selected?> ><?=$row[0]?></option>
                                <?php
							}
							?>
                            </select></div>
                            <?php
						} 
						if (isset($heatfinal) && $heatfinal== 2 ) {
							$ready = 1;
						}
					} 
					?>
					<br /><input type="submit" name="cancel" value="<?=$txtback?>" />
					</form>
					<?php
					if ($ready == 1){
						if (isset($heatfinal) && $heatfinal == 1 ) {   //初賽
							$sql = mysqli_query($splink,"Select A.STUID, B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.REGNO, B.SEX, A.LANE_NO,A.ATTENDANCE,A.RESULT from TRACKEVENT_HEAT_LANE AS A inner join studentinfo AS B on A.STUID=B.STUID where A.EVENT_ID=\"".$EVENT_ID."\" AND A.COMPETITION_ID=\"".$COMPETITION_ID."\" ORDER BY A.LANE_NO");
						} else if (isset($heatfinal) && $heatfinal == 2) {  //含決賽項目
							$sql = mysqli_query($splink,"Select A.STUID, B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.REGNO, B.SEX, A.LANE_NO,A.ATTENDANCE,A.RESULT from TRACKEVENT_FINAL_LANE AS A inner join studentinfo AS B on A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" ORDER BY A.LANE_NO");					
						} else {    //直接比賽
							$sql = mysqli_query($splink,"SET @row_number:=0");
							$sql = mysqli_query($splink,"Select A.STUID, B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.REGNO, B.SEX, @row_number:=@row_number+1 AS LANE_NO from APPLICATION_COMPETITION AS A inner join studentinfo AS B on A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" ORDER BY LANE_NO");
						}
						if ((mysqli_num_rows($sql) > 0 ) ) {
							?>
							<font color="#FF0000"><center><?=$msg?></center></font>
							<br />
							<?=$txtrecordtrackremark?><br /><br />
							<form action="eventday.php" method="POST"><input type="hidden" name="inputresult" />
							<input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>"><input type="hidden" name="eventtype" value="<?=$eventtype?>" />
							<?php if (isset($heatfinal)) {?>
							<input type="hidden" name="heatfinal" value="<?=$heatfinal?>" />
							<?php } 
							if (isset($EVENT_ID)){?>
							<input type="hidden" name="EVENT_ID" value="<?=$EVENT_ID?>" />
							<?php								
							}
							?>
							<table class="alt"><thead><tr><th style="text-align:center"><?=$txttracknum?></th><th style="text-align:center"><?=$txtstudentregno?></th><th style="text-align:center"><?=$txtclass?></th><th style="text-align:center"><?=$txtclassno?></th>
							<th style="text-align:center"><?=$txtname?></th><th style="text-align:center"><?=$txtattendance?></th><th style="text-align:center"><?=$txtresult." ".$unit?></th></tr></thead>
							<tbody>
							<?php 
							while ($row = mysqli_fetch_row($sql)){
								if ($lang =="chi") {
									$showname = $row[1];
								} else {
									$showname = $row[2];
								}
								if (isset($heatfinal)  ) {   //需要決賽
									$result = $row[9];
									$attend= $row[8];
								} else { //初賽
									$asql= mysqli_query($splink,"Select ATTENDANCE from APPLICATION_COMPETITION where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$row[0]."\"");
									while ($arow = mysqli_fetch_row($asql)){
										$attend= $arow[0];
									}
									$result = "";
									$rsql = mysqli_query($splink,"Select RESULT from TRACKEVENT_HEAT_LANE where STUID=\"".$row[0]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
									while ($rrow = mysqli_fetch_row($rsql)){
										$result = $rrow[0];
									}
								}
								
								$iresult = "r".$row[0];
								$iattend = "a".$row[0];
								
								
								?>
								<tr><td style="text-align:center"><?=$row[7]?></td><td style="text-align:center"><?=$row[5]?></td><td style="text-align:center"><?=$row[3]?></td><td style="text-align:center"><?=$row[4]?></td>
								<td style="text-align:center"><?=$showname?></td>
								<td style="text-align:center"><input type="hidden" name="targetSTUID[]" value="<?=$row[0]?>" />
								<input type="radio" name="a<?=$row[0]?>" value="1" id="a<?=$row[0]?>1" <?php if  (isset($$iattend) && $$iattend == 1) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 1 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>1"><?=$txtattended?></label>
								<input type="radio" name="a<?=$row[0]?>" value="2" id="a<?=$row[0]?>2" <?php if  (isset($$iattend) && $$iattend == 2) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 2 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>2"><?=$txtapplyleave?></label>
								<input type="radio" name="a<?=$row[0]?>" value="3" id="a<?=$row[0]?>3" <?php if  (isset($$iattend) && $$iattend == 3) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 3 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>3"><?=$txtabsent?></label>
								</td><td style="text-align:center"><input id="r<?=$row[0]?>" type="text" name="r<?=$row[0]?>" value="<?php if (isset($$iresult)) { echo $$iresult; } else { if (isset($result)) { echo $result; }}?>"/>
								</td></tr>
								<?php
							}
							?>
							</tbody></table>
							<input type="submit" name="submitresult" value="<?=$txtsave?>" class="special" />&nbsp;<input type="submit" name="cancel" value="<?=$txtback?>" /></form>
							<?php
						}
					}
				} else if ($eventtype == "2") {    				//field
					$sql=mysqli_query($splink,"Select A.STUID, B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.REGNO, B.SEX from APPLICATION_COMPETITION AS A inner join studentinfo AS B on A.STUID = B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" ORDER BY B.CLASSCODE, B.CLASSNO");
					if (mysqli_num_rows($sql) > 0 ) {
						?>
                        <font color="#FF0000"><center><?=$msg?></center></font>
                        <br />
                        <?=$txtrecordfieldremark?><br /><br />
                        <form action="eventday.php" method="POST"><input type="hidden" name="inputresult" />
                        <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>"><input type="hidden" name="eventtype" value="<?=$eventtype?>" />
                        <table class="alt"><thead><tr><th style="text-align:center"><?=$txtstudentregno?></th><th style="text-align:center"><?=$txtclass?></th><th style="text-align:center"><?=$txtclassno?></th>
                        <th style="text-align:center"><?=$txtname?></th><th style="text-align:center"><?=$txtattendance?></th><th style="text-align:center"><?=$txtresult." ".$unit?></th></tr></thead>
                        <tbody>
                        <?php 
						while ($row = mysqli_fetch_row($sql)){
							if ($lang =="chi") {
								$showname = $row[1];
							} else {
								$showname = $row[2];
							}
							$asql= mysqli_query($splink,"Select ATTENDANCE from APPLICATION_COMPETITION where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$row[0]."\"");
							while ($arow = mysqli_fetch_row($asql)){
								$attend= $arow[0];
							}
							$result = "";
							$rsql = mysqli_query($splink,"Select RESULT from HEAT_RESULT where STUID=\"".$row[0]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
							while ($rrow = mysqli_fetch_row($rsql)){
								$result = $rrow[0];
							}
							$iresult = "r".$row[0];
							$iattend = "a".$row[0];
							
							
							?>
                            <tr><td style="text-align:center"><?=$row[5]?></td><td style="text-align:center"><?=$row[3]?></td><td style="text-align:center"><?=$row[4]?></td>
                            <td style="text-align:center"><?=$showname?></td>
                            <td style="text-align:center"><input type="hidden" name="targetSTUID[]" value="<?=$row[0]?>" />
                            <input type="radio" name="a<?=$row[0]?>" value="1" id="a<?=$row[0]?>1" <?php if  (isset($$iattend) && $$iattend == 1) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 1 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>1"><?=$txtattended?></label>
                            <input type="radio" name="a<?=$row[0]?>" value="2" id="a<?=$row[0]?>2" <?php if  (isset($$iattend) && $$iattend == 2) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 2 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>2"><?=$txtapplyleave?></label>
                            <input type="radio" name="a<?=$row[0]?>" value="3" id="a<?=$row[0]?>3" <?php if  (isset($$iattend) && $$iattend == 3) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 3 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$row[0]?>3"><?=$txtabsent?></label>
                            </td><td style="text-align:center"><input id="r<?=$row[0]?>" type="text" name="r<?=$row[0]?>" value="<?php if (isset($$iresult)) { echo $$iresult; } else { if (isset($result)) { echo $result; }}?>"/>
                            </td></tr>
                            <?php
						}
						?>
                        </tbody></table>
                        <input type="submit" name="submitresult" value="<?=$txtsave?>" class="special" />&nbsp;<input type="submit" name="cancel" value="<?=$txtback?>" /></form>
                        <?php
					}
				} else {  //社際比賽
					$sql=mysqli_query($splink,"Select SCHHOUSE, TEAM, LANE_NO from INTERHOUSE_COMPETITION where COMPETITION_ID=\"".$COMPETITION_ID."\" GROUP BY SCHHOUSE, TEAM ORDER BY LANE_NO");
					if (mysqli_num_rows($sql) > 0 ) {
						?>
                        <font color="#FF0000"><center><?=$msg?></center></font>
                        <br />
                        <?=$txtrecordfieldremark?><br /><br />
                        <form action="eventday.php" method="POST"><input type="hidden" name="inputresult" />
                        <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>"><input type="hidden" name="eventtype" value="<?=$eventtype?>" />
                        <table class="alt"><thead><tr><th style="text-align:center"><?=$txttracknum?></th>
                        <th style="text-align:center"><?=$txthouse?></th><th style="text-align:center"><?=$txtteam?></th>
                        <th style="text-align:center"><?=$txtattendance?></th><th style="text-align:center"><?=$txtresult." ".$unit?></th></tr></thead>
                        <tbody>
                        <?php 
						while ($row = mysqli_fetch_row($sql)){
							$house[] = $row[0];
							$team[]= $row[1];
							$lane_no[]=$row[2];
						}
						$x = 0;
						while ($x < 8 ) {
							$lane = $x+1;
							$indexoflane_no = array_search($lane,$lane_no);
							if ( $lane_no[$indexoflane_no] == $lane ) {
								$result = "";
								$attend = "";
								if ($lane < 5) {
									$teamAOB = "A";
								} else {
									$teamAOB = "B";
								}
								$rsql = mysqli_query($splink,"Select RESULT, ATTENDANCE from INTERHOUSE_RESULT where SCHHOUSE=\"".$house[$indexoflane_no]."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND TEAM = \"".$teamAOB."\"");
								while ($rrow = mysqli_fetch_row($rsql)){
									$result = $rrow[0];
									$attend = $rrow[1];
								}
								$iresult = "r".$lane_no[$indexoflane_no];
								$iattend = "a".$lane_no[$indexoflane_no];
								if ($house[$indexoflane_no] == "R") {
									$housename = $txthouseRed;
								} else if ($house[$indexoflane_no] == "Y") {
									$housename = $txthouseYellow;
								} else if ($house[$indexoflane_no] == "B") {
									$housename = $txthouseBlue;
								} else {
									$housename = $txthouseGreen;
								}
								
								?>
								<tr><td style="text-align:center"><?=$lane?></td><td style="text-align:center"><?=$housename?></td><td style="text-align:center"><?=$team[$indexoflane_no]?></td>
								<td style="text-align:center"><input type="hidden" name="targetSTUID[]" value="<?=$lane?>" />
								<input type="radio" name="a<?=$lane?>" value="1" id="a<?=$lane?>1" <?php if  (isset($$iattend) && $$iattend == 1) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 1 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$lane?>1"><?=$txtattended?></label>
								<input type="radio" name="a<?=$lane?>" value="2" id="a<?=$lane?>2" <?php if  (isset($$iattend) && $$iattend == 2) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 2 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$lane?>2"><?=$txtapplyleave?></label>
								<input type="radio" name="a<?=$lane?>" value="3" id="a<?=$lane?>3" <?php if  (isset($$iattend) && $$iattend == 3) { ?> checked="checked" <?php }  else { if  (isset($attend) && $attend == 3 ){ ?> checked="checked" <?php } }?>/><label for="a<?=$lane?>3"><?=$txtabsent?></label>
								</td><td style="text-align:center"><input id="r<?=$lane?>" type="text" name="r<?=$lane?>" value="<?php if (isset($$iresult)) { echo $$iresult; } else { if (isset($result)) { echo $result; }}?>"/>
								</td></tr>
								<?php
							} else {
								?>
								<tr><td style="text-align:center"><?=$lane?></td><td style="text-align:center"></td><td style="text-align:center"></td>
								<td style="text-align:center"></td>
								<td style="text-align:center"></td></tr>
                                <?php
							}
							$x++;
						}
						?>
                        </tbody></table>
                        <input type="submit" name="submitresult" value="<?=$txtsave?>" class="special" />&nbsp;<input type="submit" name="cancel" value="<?=$txtback?>" /></form>
                        <?php
					}				
				}
			}
		}
	}
	//完成輸入分數

	//顯示比賽結果
	if (isset($showresult)) {
		?>
        <h2><?=$txtshowresult?></h2>
        <?php
		$selectlist = "";
		$sql = mysqli_query($splink,"Select B.keyid, B.CH_DES, B.EN_DES from CONFIRMED_RESULT AS A inner join COMPETITIONITEM AS B ON A.COMPETITION_ID=B.keyid where SCHYEAR=\"".$todayschyr."\" group by COMPETITION_ID");
		while ($row = mysqli_fetch_row($sql)){
			if ($lang == "chi") {
				$showname = $row[1];
			} else {
				$showname = $row[2];
			}
			if (isset($COMPETITION_ID) && $COMPETITION_ID== $row[0]) {
				$selected = " selected=\"selected\" ";
			} else {
				$selected = "";
			}
			$selectlist .= "<option value=\"".$row[0]."\" ".$selected.">".$showname."</option>";
		}
		?>
        <form action="eventday.php" method="POST"><input type="hidden" name="showresult" />
        <select name="COMPETITION_ID" onchange="submit()"><option><?=$txtselectevent?></option><?=$selectlist?></select></form>
		<?php
		if (isset($COMPETITION_ID)) {
			$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND HeatorFinal = \"0\" AND SCHYEAR=\"".$todayschyr."\"");
			if (mysqli_num_rows($csql) > 0 ) {
				$haveheat = 1;
			} else {
				$haveheat = 0;
			}
			if ($haveheat == 1) { 
				if (!isset($heatorfinal)) {
					$heatorfinal = 0;
				}
				?>
				<form action="eventday.php" method="POST"><input type="hidden" name="showresult" />
				<input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>" />
				<input type="radio" name="heatorfinal" value="0" onclick="submit()" id="heatorfinal1" <?php if (isset($heatorfinal) && $heatorfinal== 0) { ?> checked="checked"<?php } ?>><label for="heatorfinal1"><?=$txt1stheat?></label>&nbsp;
				<input type="radio" name="heatorfinal" value="1" onclick="submit()" id="heatorfinal2" <?php if (isset($heatorfinal) && $heatorfinal== 1) { ?> checked="checked"<?php } ?>><label for="heatorfinal2"><?=$txtfinal?></label>&nbsp;
				</form>
				<?php
			}
			$sql = mysqli_query($splink,"Select CH_DES, EN_DES, INTERHOUSE, INTERCLASS from COMPETITIONITEM where keyid=\"".$COMPETITION_ID."\"");
			while ($row = mysqli_fetch_row($sql)){
				if ($lang == "chi") {
					$showname = $row[0];
				} else {
					$showname = $row[1];
				}
				$isHOUSE = $row[2];
				$isCLASS = $row[3];
			}
			?>
			<h3><?=$showname?></h3>
			<table><thead>
			<?php if ($isHOUSE == 0 ) { ?>
			<th><?=$txtclass?></th><th><?=$txtclassno?></th><th><?=$txtname?></th>
			<?php } else { ?>
			<th><?=$txthouse?></th>
			<?php } ?>
			<th><?=$txtstatus?></th><th><?=$txtresult?></th>
			<th><?=$txtrank?></th><th><?=$txtnewrecord?></th>
			</thead>
			<tbody>
			<?php
			if ($isHOUSE == 1 ) {
				//社際
			} else if ($isCLASS == 1) {
				//班際
			} else { //個人項目
				//處理有排名.
				if ($haveheat == 1 && $heatorfinal==0) {
					$csql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO , A.RANK, A.RESULT, A.is_NEWRECORD,A.STUID, B.SCHHOUSE from CONFIRMED_RESULT AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND A.HeatorFinal =\"0\" AND NOT A.RANK = \"\" ORDER BY CAST(A.RANK AS SIGNED) ASC");
				} else {
					$csql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO , A.RANK, A.RESULT, A.is_NEWRECORD,A.STUID, B.SCHHOUSE from CONFIRMED_RESULT AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND A.HeatorFinal =\"1\" AND NOT A.RANK = \"\" ORDER BY CAST(A.RANK AS SIGNED) ASC");
				} 
				while ($crow = mysqli_fetch_row($csql)){
					if ($lang == "chi" ) {
						$showname = $crow[0]."(".$crow[8].")";
					} else {
						$showname = $crow[1]."(".$crow[8].")";
					}
					
					if ($crow[6] ==1) {
						$newrec = "*";
					} else {
						$newrec = "";
					}
					$asql = mysqli_query($splink,"Select ATTENDANCE from APPLICATION_COMPETITION where SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$crow[7]."\"");
					while ($arow = mysqli_fetch_row($asql)){
						if ($arow[0] == 1) {
							$att = $txtattended;
						} else if ($arow[0] == 2) {
							$att = $txtapplyleave;
						} else {
							$att = $txtabsent;
						}
					}
					
					?>
					<tr><td><?=$crow[2]?></td><td><?=$crow[3]?></td><td><?=$showname?></td>
					<td><?=$att?></td><td><?=$crow[5]?></td><td><?=$crow[4]?></td><td><?=$newrec?></td></tr>
					<?php
				}
				//處理無排名
				if ($haveheat == 1) {
					$csql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO , A.RANK, A.RESULT, A.is_NEWRECORD,A.STUID, B.SCHHOUSE from CONFIRMED_RESULT AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND A.HeatorFinal =\"0\" AND A.RANK = \"\" ORDER BY CAST(A.RANK AS SIGNED) ASC");
				} else {
					$csql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO , A.RANK, A.RESULT, A.is_NEWRECORD,A.STUID, B.SCHHOUSE from CONFIRMED_RESULT AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND A.HeatorFinal =\"1\" AND A.RANK = \"\" ORDER BY CAST(A.RANK AS SIGNED) ASC");
				} 
				while ($crow = mysqli_fetch_row($csql)){
					if ($lang == "chi" ) {
						$showname = $crow[0]."(".$crow[8].")";
					} else {
						$showname = $crow[1]."(".$crow[8].")";
					}
					
					if ($crow[6] ==1) {
						$newrec = "*";
					} else {
						$newrec = "";
					}
					$asql = mysqli_query($splink,"Select ATTENDANCE from APPLICATION_COMPETITION where SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$crow[7]."\"");
					while ($arow = mysqli_fetch_row($asql)){
						if ($arow[0] == 1) {
							$att = $txtattended;
						} else if ($arow[0] == 2) {
							$att = $txtapplyleave;
						} else {
							$att = $txtabsent;
						}
					}
					?>
					<tr><td><?=$crow[2]?></td><td><?=$crow[3]?></td><td><?=$showname?></td>
					<td><?=$att?></td><td><?=$crow[5]?></td><td><?=$crow[4]?></td><td><?=$newrec?></td></tr>
					<?php
				}

			}
			?>
			</tbody></table>
			<?php
		}
	}
	//完成顯示比賽結果

	//獎牌榜
	if (isset($medaltablenscore)){
		?>
        <h2><?=$txtmedaltablenscore?></h2>
        <?php
		//個人項目
		$x = 0;
		while ($x < sizeof($gradearray)){
			if ($x == 0) {
				$gradeyearlist = " LEFT(B.DOB,4) < \"".$gradeAyr."\" ";
				$showgrade = $txtgradeA;
			} else if ($x == 1) {
				$gradeyearlist = " ( LEFT(B.DOB,4) >= \"".$gradeAyr."\" AND LEFT(B.DOB,4) < \"".$gradeByr."\") ";
				$showgrade = $txtgradeB;
			} else {
				$gradeyearlist = " LEFT(B.DOB,4 ) >= \"".$gradeByr."\" ";
				$showgrade = $txtgradeC;
			}
			$sx = 0;
			while ($sx < sizeof($sexarray)){
				if ($sx == 0 ) {
					$showsex = $txtmale;
				} else {
					$showsex = $txtfemale;
				}
				$sql = mysqli_query($splink, "Select B.CLASSCODE, B.CLASSNO, B.CHNAME,B.ENNAME, B.SCHHOUSE, SUM(CASE WHEN A.RANK = 1 THEN 1 ELSE 0 END) AS GOLD ,SUM(CASE WHEN A.RANK = 2 THEN 1 ELSE 0 END) AS SILVER,SUM(CASE WHEN A.RANK = 3 THEN 1 ELSE 0 END) AS BRONZE,SUM(CASE WHEN A.RANK = 1 THEN 1 ELSE 0 END) + SUM(CASE WHEN A.RANK = 2 THEN 1 ELSE 0 END) + SUM(CASE WHEN A.RANK = 3 THEN 1 ELSE 0 END) AS amount, A.STUID FROM `CONFIRMED_RESULT` AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.HeatorFinal=1 AND ".$gradeyearlist." AND B.SEX=\"".$sexarray[$sx]."\" GROUP BY A.STUID ORDER BY amount DESC, GOLD DESC, SILVER DESC, BRONZE DESC LIMIT 10");
				?>
				<h3><?=$showsex.$showgrade?><h3>
				<table><thead><tr><th><?=$txtclass?><?=$txtclassno?></th><th><?=$txtname?></th><th><?=$txthouse?></th>
				<th><?=$txtgold?></th><th><?=$txtsilver?></th><th><?=$txtbronze?></th><th><?=$txttotalnum?></th>
				<th><?=$txteventscore?></th>
                </tr>
                </thead>
				<tbody>
				<?php
				while ($row = mysqli_fetch_row($sql)){
					if ($lang == "chi") {
						$showname= $row[2];
					} else {
						$showname = $row[3];
					}
					$scsql = mysqli_query($splink,"Select SCORE from STU_SCORE where SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$row[9]."\"");
					while ($scrow = mysqli_fetch_row($scsql)){
						$showscore = $scrow[0];
					}
					?>
					<tr><td><?=$row[0].$row[1]?></td>
					<td><?=$showname?></td><td><?=$row[4]?></td>
					<td><?=$row[5]?></td><td><?=$row[6]?></td><td><?=$row[7]?></td><td><?=$row[8]?></td>
                    <td><?=$showscore?></td>
                    </tr>
					<?php
				}
				?>
				</tbody></table><br />
			<?php
				$sx++;
			}
			$x++;
		}
		
		//社際項目
		?>
        <hr/>
        <div class="row uniform">
		<?php
		//社- 分男女
		$x = 0;
		while ($x < sizeof($gradearray)){
			$sx = 0;
			while ($sx < sizeof($sexarray)) {
				$sql = mysqli_query($splink,"Select SCHHOUSE, SCORE from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND GRADE=\"".$gradearray[$x]."\" AND SEX = \"".$sexarray[$sx]."\" ORDER BY SCORE DESC");
				if ($sx == 0 ) {
					$showsex = $txtmale;
				} else {
					$showsex = $txtfemale;
				}
				if ($x == 0) {
					$showgrade = $txtgradeA;
				} else if ($x == 1) {
					$showgrade = $txtgradeB;
				} else {
					$showgrade = $txtgradeC;
				}
				?>
                <div class="6u 12u$(xsmall)">
                <h3><?=$txtinterhouse.$showsex.$showgrade?></h3>
				<table><thead><tr><th style="text-align:center"><?=$txthouse?></th>
				<th style="text-align:center"><?=$txteventscore?></th>
				</tr>
				</thead>
				<tbody>
				<?php
				if (mysqli_num_rows($sql) > 0 ) {
					unset($haveR);
					unset($haveY);
					unset($haveB);
					unset($haveG);
					while ($row = mysqli_fetch_row($sql)){
						if ($row[0] == "R") {
							$showname= $txthouseRed;
							$haveR=1;
						} else if ($row[0] == "Y") {
							$showname= $txthouseYellow;
							$haveY=1;
						} else if ($row[0] == "B") {
							$showname= $txthouseBlue;
							$haveB = 1;
						} else  {
							$showname= $txthouseGreen;
							$haveG = 1;
						}
							$showscore = $row[1];
						?>
						<tr><td align="center"><?=$showname?></td>
						<td align="center"><?=$showscore?></td>
						</tr>
						<?php
					}
					if (!isset($haveR)){
						?>
                        <tr><td align="center"><?=$txthouseRed?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveY)){
						?>
                        <tr><td align="center"><?=$txthouseYellow?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveB)){
						?>
                        <tr><td align="center"><?=$txthouseBlue?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveG)){
						?>
                        <tr><td align="center"><?=$txthouseGreen?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					
				} else {
						?>
						<tr><td align="center"><?=$txthouseRed?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseYellow?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseBlue?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseGreen?></td>
						<td align="center">0</td></tr>
						</tr>
						<?php
					
					
				}
				?>
				</tbody></table><br />
                </div>
				<?php	
				$sx++;
			}
			$x++;
		}

		//社  - 組別排名
		$x = 0;
		while ($x < sizeof($sexarray)){
				$sql = mysqli_query($splink,"Select SCHHOUSE, SUM(SCORE) from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND SEX=\"".$sexarray[$x]."\" GROUP BY SCHHOUSE  ORDER BY SCORE DESC");
				if ($x == 0 ) {
					$showsex = $txtmale;
				} else {
					$showsex = $txtfemale;
				}
				?>
                <div class="6u 12u$(xsmall)">
                <h3><?=$txtinterhouse.$showsex?></h3>
				<table><thead><tr><th style="text-align:center"><?=$txthouse?></th>
				<th style="text-align:center"><?=$txteventscore?></th>
				</tr>
				</thead>
				<tbody>
				<?php
				if (mysqli_num_rows($sql) > 0 ) {
					unset($haveR);
					unset($haveY);
					unset($haveB);
					unset($haveG);
					while ($row = mysqli_fetch_row($sql)){
						if ($row[0] == "R") {
							$showname= $txthouseRed;
							$haveR=1;
						} else if ($row[0] == "Y") {
							$showname= $txthouseYellow;
							$haveY=1;
						} else if ($row[0] == "B") {
							$showname= $txthouseBlue;
							$haveB = 1;
						} else  {
							$showname= $txthouseGreen;
							$haveG = 1;
						}
							$showscore = $row[1];
						?>
						<tr><td align="center"><?=$showname?></td>
						<td align="center"><?=$showscore?></td>
						</tr>
						<?php
					}
					if (!isset($haveR)){
						?>
                        <tr><td align="center"><?=$txthouseRed?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveY)){
						?>
                        <tr><td align="center"><?=$txthouseYellow?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveB)){
						?>
                        <tr><td align="center"><?=$txthouseBlue?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					if (!isset($haveG)){
						?>
                        <tr><td align="center"><?=$txthouseGreen?></td>
						<td align="center">0</td></tr>
                        <?php
					}
					
				} else {
						?>
						<tr><td align="center"><?=$txthouseRed?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseYellow?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseBlue?></td>
						<td align="center">0</td></tr>
                        <tr><td align="center"><?=$txthouseGreen?></td>
						<td align="center">0</td></tr>
						</tr>
						<?php
					
					
				}
				?>
				</tbody></table>
                </div>
				<?php	
			$x++;
		}
		//社 全場總分
		$sql = mysqli_query($splink,"Select SCHHOUSE, SUM(SCORE) from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" GROUP by SCHHOUSE ORDER BY SCORE DESC");
		?>
		<div class="12u 12u$(xsmall)">
		<h3><?=$txtinterhouse.$txtoverallscore?></h3>
		<table><thead><tr><th style="text-align:center"><?=$txthouse?></th>
		<th style="text-align:center"><?=$txteventscore?></th>
		</tr>
		</thead>
		<tbody>
		<?php
		if (mysqli_num_rows($sql) > 0 ) {
			unset($haveR);
			unset($haveY);
			unset($haveB);
			unset($haveG);
			while ($row = mysqli_fetch_row($sql)){
				if ($row[0] == "R") {
					$showname= $txthouseRed;
					$haveR=1;
				} else if ($row[0] == "Y") {
					$showname= $txthouseYellow;
					$haveY=1;
				} else if ($row[0] == "B") {
					$showname= $txthouseBlue;
					$haveB = 1;
				} else  {
					$showname= $txthouseGreen;
					$haveG = 1;
				}
					$showscore = $row[1];
				?>
				<tr><td align="center"><?=$showname?></td>
				<td align="center"><?=$showscore?></td>
				</tr>
				<?php
			}
			if (!isset($haveR)){
				?>
				<tr><td align="center"><?=$txthouseRed?></td>
				<td align="center">0</td></tr>
				<?php
			}
			if (!isset($haveY)){
				?>
				<tr><td align="center"><?=$txthouseYellow?></td>
				<td align="center">0</td></tr>
				<?php
			}
			if (!isset($haveB)){
				?>
				<tr><td align="center"><?=$txthouseBlue?></td>
				<td align="center">0</td></tr>
				<?php
			}
			if (!isset($haveG)){
				?>
				<tr><td align="center"><?=$txthouseGreen?></td>
				<td align="center">0</td></tr>
				<?php
			}
			
		} else {
				?>
				<tr><td align="center"><?=$txthouseRed?></td>
				<td align="center">0</td></tr>
				<tr><td align="center"><?=$txthouseYellow?></td>
				<td align="center">0</td></tr>
				<tr><td align="center"><?=$txthouseBlue?></td>
				<td align="center">0</td></tr>
				<tr><td align="center"><?=$txthouseGreen?></td>
				<td align="center">0</td></tr>
				</tr>
				<?php
			
			
		}
		?>
		</tbody></table>
		</div>
		<?php	

		?>
        </div>
        <?php
	}
	//完成獎牌榜
	
	//徑項分組
	if (isset($setlaneevent)){
		?>
        <h2><?=$txtsetlaneevent?></h2>
        <form action="eventday.php" method="POST"><input type="hidden" name="setlaneevent" />
        <input type="radio" name="eventtype" value="1" id="eventtype1" onchange="submit()" <?php if (isset($eventtype) && $eventtype == 1) { ?> checked="checked" <?php } ?>/><label for="eventtype1"><?=$txt1stheat?></label>
        <input type="radio" name="eventtype" value="2" id="eventtype2" onchange="submit()" <?php if (isset($eventtype) && $eventtype == 2) { ?> checked="checked" <?php } ?> /><label for ="eventtype2"><?=$txtfinal?></label>
        </form>
        
        <?php
		//設定初賽
		if (isset($eventtype) && $eventtype==1){
			//php Gen list for all
			if (isset($gentrack)){
				$sql = mysqli_query($splink,"TRUNCATE TRACKEVENT_HEAT_LANE");
				$sql = mysqli_query($splink,"Select A.COMPETITION_ID,COUNT(A.COMPETITION_ID), B.CH_DES, B.EN_DES from APPLICATION_COMPETITION AS A inner join COMPETITIONITEM AS B ON A.COMPETITION_ID=B.keyid where B.SETLANE=\"1\" AND B.INTERHOUSE=\"0\" AND B.INTERCLASS=\"0\" GROUP BY A.COMPETITION_ID");
				while ($row = mysqli_fetch_row($sql)){
					
					//先清各社人數
					unset($hseR);
					unset($hseY);
					unset($hseB);
					unset($hseG);
					//設定當前EVENT_ID
					$esql= mysqli_query($splink,"Select Max(EVENT_ID) from TRACKEVENT_HEAT_LANE");
					while ($erow = mysqli_fetch_row($esql)){
						$event_id=$erow[0] + 1;
					}
					if (!isset($event_id)){
						$event_id=1;
					}
					if ($row[1] < 9) { //如果少過8人就不用安排線道
						$gsql = mysqli_query($splink,"Select STUID from APPLICATION_COMPETITION where COMPETITION_ID=\"".$row[0]."\"");
						while ($grow = mysqli_fetch_row($gsql)){
							$setlane[]=$grow[0];
						}
						$startlane = floor((8 - $row[1])/2) + 1;
						for ( $i = $startlane; $i < 9; $i++ ) {
							if (empty($setlane)) {
								break;
							} else {
								$key = array_rand($setlane, 1);
								// Save the record in $selected.
								$selected = $setlane[$key];
								// Remove the key/pair from the array.
								unset($setlane[$key]);
								// insert the selected value into event and lane 
								$isql = mysqli_query($splink,"Insert into TRACKEVENT_HEAT_LANE ( EVENT_ID, COMPETITION_ID, STUID, LANE_NO ) VALUES (\"".$event_id."\",\"".$row[0]."\",\"".$selected."\",\"".$i."\")");
							}
						}
					} else {//多於8人，但餘數只有3人的話 最尾2組會平均分開人數
						//get student in each house
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"R\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseR[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"Y\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseY[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"B\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseB[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"G\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseG[]=$hrow[0];
						}
						// count num of ecah house
						$noofR=sizeof($hseR);
						$noofY=sizeof($hseY);
						$noofB=sizeof($hseB);
						$noofG=sizeof($hseG);
						
						// count how many event need for all the item
						if ($row[1]%8 == 0 ) {
							$noofevent= floor($row[1]/8);
						} else {
							$noofevent = floor($row[1]/8) + 1;
						}

						$x = 0; // new event id = inital event_id + $x 
						while ($x < $noofevent ) {
							for ( $i = 1; $i < 9; $i++ ) {
								if (sizeof($hseR)+sizeof($hseY)+sizeof($hseB)+sizeof($hseG) == 0 ) {
									break;
								} else {
								// get max and min house every round
								$noofH = array($noofR, $noofY, $noofB, $noofG);		// put all number in array
								$minH = array_keys($noofH, min($noofH)); 			//get the min number in array
								$maxH = array_keys($noofH, max($noofH));			//get the max number in array
								if ($minH[0] == 0 ) {
									$minHse = "hseR";
									$minnoofHse = "noofR";
								} else if ($minH[0] == 1) {
									$minHse = "hseY";
									$minnoofHse = "noofY";
								} else if ($minH[0] == 2 ) {
									$minHse = "hseB";
									$minnoofHse = "noofB";
								} else {
									$minHse = "hseG";
									$minnoofHse = "noofG";
								}
								$newevent_id = $event_id + $x;
									if ($i == 1 || $i == 5 ) {
										if ($minHse == "hseR" && $i == 5) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseR)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
													$key = array_rand($hseR, 1);						// Save the record in $selected.
													$noofR = $noofR - 1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
											}
										}
									} else if ( $i== 2 || $i == 6) {
										if ($minHse == "hseY" && $i == 6) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hsey)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
												$key = array_rand($hseY, 1);						// Save the record in $selected.
												$noofY = $noofY - 1;

													$selected = $hseY[$key];
													unset($hseY[$key]);
											}
										}
									} else if ( $i == 3 || $i == 7) {
										if ($minHse == "hseB" && $i == 7) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseB)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}

											} else {
												$key = array_rand($hseB, 1);						// Save the record in $selected.
												$noofB = $noofB - 1;
													$selected = $hseB[$key];
													unset($hseB[$key]);
											}
										}
									} else {
										if ($minHse == "hseG" && $i == 8 ) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseG)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
												$key = array_rand($hseG, 1);						
												$noofG = $noofG - 1;
												$selected = $hseG[$key];							// Save the record in $selected.
												unset($hseG[$key]);							// Remove the key/pair from the array.
											}
										}
									} 
									// insert the selected value into event and lane 
									$isql = mysqli_query($splink,"Insert into TRACKEVENT_HEAT_LANE ( EVENT_ID, COMPETITION_ID, STUID, LANE_NO ) VALUES (\"".$newevent_id."\",\"".$row[0]."\",\"".$selected."\",\"".$i."\")");
								}
							}
							$x++;
						}
						if ($row[1]%8 < 5 ) {
							// get the last two  event_id then divide the student to two group 
							$lasttwoeventid =  $newevent_id - 1 ;
							$hsql = mysqli_query($splink,"Select keyid from TRACKEVENT_HEAT_LANE where EVENT_ID = \"".$lasttwoeventid."\" OR EVENT_ID = \"".$newevent_id."\"");
							$totalstuid = mysqli_num_rows($hsql);
							if (is_int( $totalstuid/ 2 )) {
								$lasttwoeventstuid = $totalstuid/2;
								$lasteventstuid = $totalstuid/2;
							} else {
								$lasttwoeventstuid = floor($totalstuid/2) + 1;
								$lasteventstuid = floor($totalstuid/2) ;
							}
							$lasttwostartlane = floor((8 - $lasttwoeventstuid)/2)+1;
							$laststartlane = floor((8 - $lasteventstuid)/2)+1;
							$x = 0;
							while ($hrow = mysqli_fetch_row($hsql)){
								if ($x < $lasttwoeventstuid) {
									$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET EVENT_ID=\"".$lasttwoeventid."\", LANE_NO=\"".$lasttwostartlane."\" where keyid = \"".$hrow[0]."\"");
									$lasttwostartlane++;
								} else {
									$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET EVENT_ID=\"".$newevent_id."\", LANE_NO=\"".$laststartlane."\" where keyid = \"".$hrow[0]."\"");
									$laststartlane++;
								}
								$x++;
							}
						} else {
							$hsql =mysqli_query($splink,"Select keyid from TRACKEVENT_HEAT_LANE where EVENT_ID=\"".$newevent_id."\"");
							$totalstuid=mysqli_num_rows($hsql);
							$startlane = floor( (8 - $totalstuid)/2) + 1;
							while ($hrow=mysqli_fetch_row($hsql)){
								$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET LANE_NO=\"".$startlane."\" where keyid = \"".$hrow[0]."\"");
								$startlane++;
							}
						}
					}
				}
				
			}
			//php finish gen list for all
			//php Gen list for selected event
			if (isset($regen)){
				$sql = mysqli_query($splink,"Select MAX(EVENT_ID ), Min(EVENT_ID) from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
				while ($row = mysqli_fetch_row($sql)) {
					$event_id = $row[1];
				}
				$sql = mysqli_query($splink,"delete from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
				$sql = mysqli_query($splink,"Select COMPETITION_ID, COUNT(COMPETITION_ID) from APPLICATION_COMPETITION where COMPETITION_ID=\"".$COMPETITION_ID."\"");
				while ($row = mysqli_fetch_row($sql)){
					
					//先清各社人數
					unset($hseR);
					unset($hseY);
					unset($hseB);
					unset($hseG);
					if ($row[1] < 9) { //如果少過8人就不用安排線道
						$gsql = mysqli_query($splink,"Select STUID from APPLICATION_COMPETITION where COMPETITION_ID=\"".$row[0]."\"");
						while ($grow = mysqli_fetch_row($gsql)){
							$setlane[]=$grow[0];
						}
						$startlane = floor((8 - $row[1])/2) + 1;
						for ( $i = $startlane; $i < 9; $i++ ) {
							if (empty($setlane)) {
								break;
							} else {
								$key = array_rand($setlane, 1);
								// Save the record in $selected.
								$selected = $setlane[$key];
								// Remove the key/pair from the array.
								unset($setlane[$key]);
								// insert the selected value into event and lane 
								$isql = mysqli_query($splink,"Insert into TRACKEVENT_HEAT_LANE ( EVENT_ID, COMPETITION_ID, STUID, LANE_NO ) VALUES (\"".$event_id."\",\"".$row[0]."\",\"".$selected."\",\"".$i."\")");
							}
						}
					} else {//多於8人，但餘數只有3人的話 最尾2組會平均分開人數
						//get student in each house
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"R\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseR[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"Y\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseY[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"B\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseB[]=$hrow[0];
						}
						$hsql = mysqli_query($splink,"Select A.STUID from APPLICATION_COMPETITION AS A INNER JOIN studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID=\"".$row[0]."\" AND B.SCHHOUSE=\"G\"");
						while ($hrow = mysqli_fetch_row($hsql)){
							$hseG[]=$hrow[0];
						}
						// count num of ecah house
						$noofR=sizeof($hseR);
						$noofY=sizeof($hseY);
						$noofB=sizeof($hseB);
						$noofG=sizeof($hseG);
						
						// count how many event need for all the item
						if ($row[1]%8 == 0 ) {
							$noofevent= floor($row[1]/8);
						} else {
							$noofevent = floor($row[1]/8) + 1;
						}

						$x = 0; // new event id = inital event_id + $x 
						while ($x < $noofevent ) {
							for ( $i = 1; $i < 9; $i++ ) {
								if (sizeof($hseR)+sizeof($hseY)+sizeof($hseB)+sizeof($hseG) == 0 ) {
									break;
								} else {
								// get max and min house every round
								$noofH = array($noofR, $noofY, $noofB, $noofG);		// put all number in array
								$minH = array_keys($noofH, min($noofH)); 			//get the min number in array
								$maxH = array_keys($noofH, max($noofH));			//get the max number in array
								if ($minH[0] == 0 ) {
									$minHse = "hseR";
									$minnoofHse = "noofR";
								} else if ($minH[0] == 1) {
									$minHse = "hseY";
									$minnoofHse = "noofY";
								} else if ($minH[0] == 2 ) {
									$minHse = "hseB";
									$minnoofHse = "noofB";
								} else {
									$minHse = "hseG";
									$minnoofHse = "noofG";
								}
								$newevent_id = $event_id + $x;
									if ($i == 1 || $i == 5 ) {
										if ($minHse == "hseR" && $i == 5) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseR)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
													$key = array_rand($hseR, 1);						// Save the record in $selected.
													$noofR = $noofR - 1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
											}
										}
									} else if ( $i== 2 || $i == 6) {
										if ($minHse == "hseY" && $i == 6) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hsey)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
												$key = array_rand($hseY, 1);						// Save the record in $selected.
												$noofY = $noofY - 1;
													$selected = $hseY[$key];
													unset($hseY[$key]);
											}
										}
									} else if ( $i == 3 || $i == 7) {
										if ($minHse == "hseB" && $i == 7) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseB)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}

											} else {
												$key = array_rand($hseB, 1);						// Save the record in $selected.
												$noofB = $noofB - 1;
													$selected = $hseB[$key];
													unset($hseB[$key]);
											}
										}
									} else {
										if ($minHse == "hseG" && $i == 8 ) {
											if ($maxH[0] == 0 ) {
												$key = array_rand($hseR, 1);
												$noofR=$noofR -1;
												$selected = $hseR[$key];						
												unset($hseR[$key]);	
											} else if ($maxH[0] == 1) {
												$key = array_rand($hseY, 1);
												$maxnoofHse = "noofY";
												$selected = $hseY[$key];
												unset($hseY[$key]);
												$noofY = $noofY -1;
											} else if ($maxH[0] == 2 ) {
												$key = array_rand($hseB, 1);
												$maxnoofHse = "noofB";
												$selected = $hseB[$key];
												unset($hseB[$key]);
												$noofB = $noofB -1;
											} else {
												$key = array_rand($hseG, 1);
												$maxnoofHse = "noofG";
												$selected = $hseG[$key];
												unset($hseG[$key]);	
												$noofG = $noofG -1;
											}
										} else {
											if (empty($hseG)) {
												if ($maxH[0] == 0 ) {
													$key = array_rand($hseR, 1);
													$noofR=$noofR -1;
													$selected = $hseR[$key];						
													unset($hseR[$key]);	
												} else if ($maxH[0] == 1) {
													$key = array_rand($hseY, 1);
													$maxnoofHse = "noofY";
													$selected = $hseY[$key];
													unset($hseY[$key]);
													$noofY = $noofY -1;
												} else if ($maxH[0] == 2 ) {
													$key = array_rand($hseB, 1);
													$maxnoofHse = "noofB";
													$selected = $hseB[$key];
													unset($hseB[$key]);
													$noofB = $noofB -1;
												} else {
													$key = array_rand($hseG, 1);
													$maxnoofHse = "noofG";
													$selected = $hseG[$key];
													unset($hseG[$key]);	
													$noofG = $noofG -1;
												}
											} else {
												$key = array_rand($hseG, 1);						
												$noofG = $noofG - 1;
												$selected = $hseG[$key];							// Save the record in $selected.
												unset($hseG[$key]);							// Remove the key/pair from the array.
											}
										}
									} 
									// insert the selected value into event and lane 
									$isql = mysqli_query($splink,"Insert into TRACKEVENT_HEAT_LANE ( EVENT_ID, COMPETITION_ID, STUID, LANE_NO ) VALUES (\"".$newevent_id."\",\"".$row[0]."\",\"".$selected."\",\"".$i."\")");
								}
							}
							$x++;
						}
						if ($row[1]%8 < 5 ) {
							// get the last two  event_id then divide the student to two group 
							$lasttwoeventid =  $newevent_id - 1 ;
							$hsql = mysqli_query($splink,"Select keyid from TRACKEVENT_HEAT_LANE where EVENT_ID = \"".$lasttwoeventid."\" OR EVENT_ID = \"".$newevent_id."\"");
							$totalstuid = mysqli_num_rows($hsql);
							if (is_int( $totalstuid/ 2 )) {
								$lasttwoeventstuid = $totalstuid/2;
								$lasteventstuid = $totalstuid/2;
							} else {
								$lasttwoeventstuid = floor($totalstuid/2) + 1;
								$lasteventstuid = floor($totalstuid/2) ;
							}
							$lasttwostartlane = floor((8 - $lasttwoeventstuid)/2)+1;
							$laststartlane = floor((8 - $lasteventstuid)/2)+1;
							$x = 0;
							while ($hrow = mysqli_fetch_row($hsql)){
								if ($x < $lasttwoeventstuid) {
									$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET EVENT_ID=\"".$lasttwoeventid."\", LANE_NO=\"".$lasttwostartlane."\" where keyid = \"".$hrow[0]."\"");
									$lasttwostartlane++;
								} else {
									$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET EVENT_ID=\"".$newevent_id."\", LANE_NO=\"".$laststartlane."\" where keyid = \"".$hrow[0]."\"");
									$laststartlane++;
								}
								$x++;
							}
						} else {
							$hsql =mysqli_query($splink,"Select keyid from TRACKEVENT_HEAT_LANE where EVENT_ID=\"".$newevent_id."\"");
							$totalstuid=mysqli_num_rows($hsql);
							$startlane = floor( (8 - $totalstuid)/2) + 1;
							while ($hrow=mysqli_fetch_row($hsql)){
								$usql = mysqli_query($splink,"Update TRACKEVENT_HEAT_LANE SET LANE_NO=\"".$startlane."\" where keyid = \"".$hrow[0]."\"");
								$startlane++;
							}
						}
					}
				}
				
			}
			//finish PHP Gen list for selected event
			?>
	        <form action="eventday.php" method="POST"><input type="hidden" name="setlaneevent" />
            <input type="hidden" name="eventtype" value="<?=$eventtype?>" />
            <input type="submit" name="gentrack" value="<?=$txtgentrack?>" class="special" />
            </form><hr />
            
            <?php 

			$sql = mysqli_query($splink,"Select A.COMPETITION_ID, B.CH_DES, B.EN_DES from TRACKEVENT_HEAT_LANE AS A inner join COMPETITIONITEM AS B ON A.COMPETITION_ID=B.keyid where INTERHOUSE=\"0\" AND INTERCLASS=\"0\" GROUP BY A.COMPETITION_ID ORDER BY B.GRADE, B.SEX, B.keyid");
			if (mysqli_num_rows($sql) > 0 ) {
				while ($row = mysqli_fetch_row($sql)){
					if ($lang == "chi") {
						$eventname = $row[1];
					} else {
						$eventname = $row[2];
					}
					?><form action="eventday.php" method="POST"><input type="hidden" name="setlaneevent" />
                    <input type="hidden" name="eventtype" value="<?=$eventtype?>" />
                    <input type="hidden" name="COMPETITION_ID" value="<?=$row[0]?>" />
                    <h3 id="<?=$row[0]?>"><?=$eventname?></h3><input type="submit" name="regen" value="<?=$txtrearrange?>" /></form>
                    <table><thead>
                    <tr>
                    <th style="text-align:center"><?=$txteventid?></th>
                    <th style="text-align:center"><?=$txttracknum?>1</th>
                    <th style="text-align:center"><?=$txttracknum?>2</th>
                    <th style="text-align:center"><?=$txttracknum?>3</th>
                    <th style="text-align:center"><?=$txttracknum?>4</th>
                    <th style="text-align:center"><?=$txttracknum?>5</th>
                    <th style="text-align:center"><?=$txttracknum?>6</th>
                    <th style="text-align:center"><?=$txttracknum?>7</th>
                    <th style="text-align:center"><?=$txttracknum?>8</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
					$csql= mysqli_query($splink,"Select EVENT_ID from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$row[0]."\" GROUP BY EVENT_ID");
					while ($crow = mysqli_fetch_row($csql)){
						?>
                        <tr><td align="center"><?=$crow[0]?></td>
                        <?php
						$i = 1;
						while ($i < 9 ) {
							$ssql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.SCHHOUSE from TRACKEVENT_HEAT_LANE AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID = \"".$row[0]."\" AND A.EVENT_ID=\"".$crow[0]."\" AND LANE_NO=\"".$i."\"");
							$show ="";
							while ($srow = mysqli_fetch_row($ssql)){
								if ($lang == "chi") {
									$show = $srow[0]."(".$srow[4].")<br>".$srow[2].$srow[3];
								} else {
									$show = $srow[1]."(".$srow[4].")<br>".$srow[2].$srow[3];
								}
							}
							?>
							<td align="center"><?=$show?></td>
							<?php
							$i++;
						}
						?>
                        </tr>
                        <?php
					}
						?>
                    </tbody></table><br /><br />
                    <?php
				}
			}
		}
		//設定決賽
		if (isset($eventtype) && $eventtype == 2) {
			//php gen list for selected event
			if (isset($genfinal)){
				if (isset($excludestud) ) {
					if (sizeof($excludestud) == $maxselect) {
						$ready = 1;
					} else {
						$ready = 0;
						$msg =  $txtselectednoiswrong;
					}
				} else {
					$ready = 1;
				}
				if ($ready == 1) {
					$sql = mysqli_query($splink,"Delete from TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					$remove = "";
					if (isset($excludestud)) {
						$x = 0;
						while ($x < sizeof($excludestud)){
							$remove .= " AND NOT STUID=\"".$excludestud[$x]."\" ";
							$x++;
						}
					}
					$sql = mysqli_query($splink,"Select STUID from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" AND NOT RESULT=\"\" ".$remove." ORDER BY RESULT ASC limit 8");
					$i = 0;
					$lane_no = array(4,5,3,6,2,7,8,1);
					while ($row = mysqli_fetch_row($sql)){
						$isql = mysqli_query($splink,"INSERT INTO TRACKEVENT_FINAL_LANE (COMPETITION_ID, STUID, LANE_NO) VALUES (\"".$COMPETITION_ID."\",\"".$row[0]."\", \"".$lane_no[$i]."\")");
						$i++;
					}
				}
			}
			//finish php gen list for selected event
			//GET EVENT WITH HEATS
			unset($com_id);
			unset($com_name);
			$sql = mysqli_query($splink,"Select COMPETITION_ID, COUNT(COMPETITION_ID) from TRACKEVENT_HEAT_LANE GROUP BY COMPETITION_ID");
			while ($row = mysqli_fetch_row($sql)){
				$com_id[] = $row[0];
			}
			$x = 0;
			?>
            <center><?=$msg?></center><br />
            <div class="row" id="top">
            <?php
			while ($x < sizeof($com_id) ) {
				$sql= mysqli_query($splink,"Select CH_DES, EN_DES from COMPETITIONITEM where keyid=\"".$com_id[$x]."\"");
				while ($row = mysqli_fetch_row($sql)){
					if ($lang == "chi") {
						$showname = $row[0];
					} else {
						$showname = $row[1];
					}
					$com_name[] = $showname;
				}
				?>
                <div class="2u 12u$(xsmall)"><a href="#<?=$com_id[$x]?>"><?=$showname?></a></div>
                <?php
				$x++;
			}
			?>
            </div>
            <hr />
            <?php
			$x = 0;
			while ($x < sizeof($com_id)){
				$sql = mysqli_query($splink,"Select * from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$com_id[$x]."\" AND ATTENDANCE = \"0\"");
				$noheatleft = mysqli_num_rows($sql);
				$sql  = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$com_id[$x]."\"");
				$conno = mysqli_num_rows($sql);
				$sql = mysqli_query($splink,"Select * from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$com_id[$x]."\"");
				$heatappno = mysqli_num_rows($sql);
				$sql = mysqli_query($splink,"Select * from TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$com_id[$x]."\"");
				$finalno = mysqli_num_rows($sql);
				$sql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$com_id[$x]."\" AND NOT RANK=\"\" AND RANK < 9");
				$rankingno = mysqli_num_rows($sql);
				if ($noheatleft > 0 ) {
					$state= $txtnotfinishheatyet;
					$ready = 0;
				} else {
					if ($conno == $heatappno ) {
						if ($rankingno > 0 ) { //finish ranking
							if ($finalno > 0 ) {
								$ready = 2;
								$state = $txtfinishgenlane;
							} else {
								$ready = 1;
								$state = $txtreadyforgenlane;
							}
						} else {
							$state = $txtallheatconfirmwaitranking;
							$ready = 0;
						}
					} else {
						$state = $txtfinishedallheat;
						$ready = 0;
					}
				}
				$xx= 1;
				?>
                <h3 id="<?=$com_id[$x]?>"><?=$com_name[$x]?> - <?=$state?><a href="#top"><img src="img/orderup.png" alt="<?=$txttop?>"/></a></h3>
                <?php
				if ($ready !== 2) {
					?>
                    <form action="eventday.php#<?=$com_id[$x]?>" method="POST"><input type="hidden" name="setlaneevent" />
                    <?php
                    if ($rankingno > 8 ) {
                        $sql = mysqli_query($splink,"Select MAX(RANK) from CONFIRMED_RESULT where COMPETITION_ID=\"".$com_id[$x]."\" AND NOT RANK=\"\" AND RANK < 9") ;
                        while ($row = mysqli_fetch_row($sql)){
                            $maxrank = $row[0];
                        }
                        $sql = mysqli_query($splink,"Select A.STUID, B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO from CONFIRMED_RESULT AS A inner join studentinfo AS B ON A.STUID= B.STUID where A.COMPETITION_ID=\"".$com_id[$x]."\" AND A.RANK=\"".$maxrank."\"");
                        $noofstud = mysqli_num_rows($sql);
                        $selectno = $rankingno - 8 ;
                        
                        $selectlist = "";
                        while ($row = mysqli_fetch_row($sql)){
                            if ($lang == "chi" ) {
                                $studname = $row[3].$row[4]." ".$row[1];
                            } else {
                                $studname = $row[3].$row[4]." ".$row[2];
                            }
                            $selectlist .= "<option value=\"".$row[0]."\">".$studname."</option>";
                        }
                        ?>
                        <?=$txtselectwhocannotinfianl?><?=$selectno?>
                        <select name="excludestud[]" <?php if ($selectno > 1) { ?> multiple="multiple" style="height:120px" <?php } ?>><?=$selectlist?></select>
                        <input type="hidden" name="maxselect" value="<?=$selectno?>" />
                        <?php
                    }
                    ?>
                    <input type="hidden" name="eventtype" value="<?=$eventtype?>" /><input type="hidden" name="COMPETITION_ID" value="<?=$com_id[$x]?>" />
                    <input type="submit" name="genfinal" value="<?=$txtgentrack?>" class="special" <?php if ($ready ==0) { ?> disabled="disabled" <?php } ?>/>
                    </form>
					<?php
				}
				$sql = mysqli_query($splink,"Select STUID, LANE_NO from TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$com_id[$x]."\"");
				if (mysqli_num_rows($sql) > 0){
					?>
                    <table><thead>
                    <tr>
                    <th style="text-align:center"><?=$txttracknum?>1</th>
                    <th style="text-align:center"><?=$txttracknum?>2</th>
                    <th style="text-align:center"><?=$txttracknum?>3</th>
                    <th style="text-align:center"><?=$txttracknum?>4</th>
                    <th style="text-align:center"><?=$txttracknum?>5</th>
                    <th style="text-align:center"><?=$txttracknum?>6</th>
                    <th style="text-align:center"><?=$txttracknum?>7</th>
                    <th style="text-align:center"><?=$txttracknum?>8</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr>
                        <?php
						$i = 1;
						while ($i < 9 ) {
							$ssql = mysqli_query($splink,"Select B.CHNAME, B.ENNAME, B.CLASSCODE, B.CLASSNO, B.SCHHOUSE from TRACKEVENT_FINAL_LANE AS A inner join studentinfo AS B ON A.STUID=B.STUID where A.COMPETITION_ID = \"".$com_id[$x]."\" AND LANE_NO=\"".$i."\"");
							$show ="";
							while ($srow = mysqli_fetch_row($ssql)){
								if ($lang == "chi") {
									$show = $srow[0]."(".$srow[4].")<br>".$srow[2].$srow[3];
								} else {
									$show = $srow[1]."(".$srow[4].")<br>".$srow[2].$srow[3];
								}
							}
							?>
							<td align="center"><?=$show?></td>
							<?php
							$i++;
						}
						?>
                        </tr>
                    </tbody></table><br /><br />
                    <?php
				}
				$x++;
			}
		}
	}
	//完成徑項分組
	
	//下載文件
	if (isset($downloaddoc)){
		$itemlist= "";
		$sql = mysqli_query($splink,"Select keyid, CH_DES, EN_DES, SETLANE from COMPETITIONITEM where Allowapply = \"1\"");
		$nooflist = mysqli_num_rows($sql);
		while ($row = mysqli_fetch_row($sql)){
			if ($row[3] == 1 ) { //需要設定線道
				$csql = mysqli_query($splink,"Select * from APPLICATION_COMPETITION where COMPETITION_ID=\"".$row[0]."\"");
				if (mysqli_num_rows($csql) > 8 ) {
					//多過8人會有初賽
					$csql = mysqli_query($splink,"Select * from COMPETITION_DATEID where COMPETITION_ID=\"".$row[0]."\" AND HeatorFinal=\"0\"");
					if (mysqli_num_rows($csql) > 0 ) {
						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 TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$row[0]."\"");
					if (mysqli_num_rows($csql) > 0 ) {
						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 ) {
						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 ) {
					if ($lang == "chi") {
						$showname = $row[1];
					} else {
						$showname = $row[2];
					}
					$itemlist .= "<option value=\"".$row[0]."-1\">".$showname."(".$txtfinal.")</option>";
				} 
			}
		}

		?>
        <h2><?=$txtdownloaddoc?></h2>
        <form action="makeexcel.php" method="POST">
        <input type="submit" name="downloadallfieldlist" value="<?=$txtdownloadallfieldlist?>"/>
        <input type="submit" name="donwloadalltracknolanelist" value="<?=$txtdownloadalltracknolanelist?>"/>
        <input type="submit" name="donwloadalltrackneedlaneheatlist" value="<?=$txtdonwloadalltrackneedlaneheatlist?>"/>
        <input type="submit" name="donwloadtrackfinallist" value="<?=$txtdownloadtrackfinallist?>"/>
        <input type="submit" name="downloadinterhousetracklist" value="<?=$txtdownloadinterhousetracklist?>"/>
        </form>
        <h3><?=$txtdownloadsingleeventlist?></h3>
        <form action="makeexcel.php" method="POST">
        <div class="select-wrapper">
        <select name="targetevent"><?=$itemlist?></select>
        </div>
        <input type="submit" name="downloadsingleeventlist" value="<?=$txtdownload?>"/>
        </form>
        <?php
	}
	//完成下載文件
	//審核賽果
	if (isset($confirmresult)){
		//php savesonfirmresult
		if (isset($saveconfirmresult)){
			$sql = mysqli_query($splink,"Select GRADE from COMPETITIONITEM where keyid=\"".$COMPETITION_ID."\"");
			while ($row = mysqli_fetch_row($sql)){
				$compgrade = $row[0];
			}
			if (isset($houseevent)){    //interhouseevent
				$sql = mysqli_query($splink,"Select * from INTERHOUSE_RESULT where SCHYEAR=\"".$todayschyr."\" and NOT RANK=\"\" AND COMPETITION_ID=\"".$COMPETITION_ID."\"");
				if (mysqli_num_rows($sql) > 0 ) {
					//confirmed
				} else {
					$x= 0;
					while ($x < sizeof($rank)){
						$temp = explode("-", $rank[$x]);
						$SCHHOUSE = $temp[0];
						$TEAM = $temp[1];
						$RANK = $temp[2];
						$RESULT = $temp[3];
						$sql = mysqli_query($splink,"Select RECORD from BEST_RECORD where COMPETITION_ID=\"".$COMPETITION_ID."\"");
						if (mysqli_num_rows($sql) > 0 ) {
							while ($row = mysqli_fetch_row($sql)){
								$oldrecord = $row[0];
							}
						} else {
							$oldrecord = "";
						}
						echo $RESULT."/".$oldrecord."<br>";
						if ($RESULT < $oldrecord ) {
							$is_NEWRECORD = 1;
						} else {
							$is_NEWRECORD = 0;
						}
						$usql = mysqli_query($splink,"Update INTERHOUSE_RESULT SET RANK=\"".$RANK."\", is_NEWRECORD=\"".$is_NEWRECORD."\" where  SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND TEAM = \"".$TEAM."\"");
						
						$rankscoreindex = $RANK - 1;
						$SCORE = $houserank[$rankscoreindex];
						$csql = mysqli_query($splink,"Select SCORE from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\"");
						if (mysqli_num_rows($csql) > 0 ) {
							while ($crow = mysqli_fetch_row($csql)){
								$newscore = $crow[0] + $SCORE;
							}
							$usql = mysqli_query($splink,"Update HOUSE_SCORE SET SCORE = \"".$newscore."\" where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\"");
						} else {
							$isql = mysqli_query($splink,"Insert into HOUSE_SCORE (SCHYEAR, SCHHOUSE,GRADE, SCORE) VALUES (\"".$todayschyr."\",\"".$SCHHOUSE."\",\"".$compgrade."\",\"".$SCORE."\")");
						}
					$x++;
					}
				}
			} else {   //個人項目
				$x= 0;
				while ($x < sizeof($rank)){
					$temp = explode("-", $rank[$x]);
					$STUID = $temp[0];
					$RESULT = $temp[1];
					if (isset($temp[2])) {
						$RANK = $temp[2];
					} else {
						$RANK= "";
					}
					$sql = mysqli_query($splink,"Select SCHHOUSE,SEX from studentinfo where STUID=\"".$STUID."\"");
					while ($row = mysqli_fetch_row($sql)){
						$SCHHOUSE = $row[0];
						$SEX= $row[1];
					}
					$sql = mysqli_query($splink,"Select RECORD from BEST_RECORD where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					if (mysqli_num_rows($sql) > 0 ) {
						while ($row = mysqli_fetch_row($sql)){
							$oldrecord = $row[0];
						}
					} else {
						$oldrecord = "";
					}
					if ($trackfield == 1) {
						if ($RESULT < $oldrecord ) {
							$is_NEWRECORD = 1;
						} else {
							$is_NEWRECORD = 0;
						}
					} else {
						if ($RESULT > $oldrecord ) {
							$is_NEWRECORD = 1;
						} else {
							$is_NEWRECORD = 0;
						}
					}
					
					$ssql = mysqli_query($splink,"Select STANDARD,TRACKFIELD from COMPETITIONITEM where keyid=\"".$COMPETITION_ID."\"");
					while ($row = mysqli_fetch_row($ssql)){
						$standard = $row[0];
						$trackfield = $row[1];
					}
					$ssql = mysqli_query($splink,"Select * from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					if (mysqli_num_rows($ssql) > 0 ) {
						$haveheat = 1;
					} else {
						$haveheat = 0;
					}
					if (isset($EVENT_ID) ) {  //初賽
						$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\" AND HeatorFinal = \"".$confirmheatfinal."\" AND EVENT_ID=\"".$EVENT_ID."\"");
						if (mysqli_num_rows($csql) > 0 ) {
							//confirmed...do nothing
						//	$usql = mysqli_query($splink,"Update CONFIRMED_RESULT SET RESULT=\"".$RESULT."\", is_NEWRECORD=\"".$is_NEWRECORD."\" where  SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\" AND HeatorFinal = \"".$confirmheatfinal."\" AND EVENT_ID=\"".$EVENT_ID."\"");
						} else {
							$sql = mysqli_query($splink,"Insert into CONFIRMED_RESULT (SCHYEAR, COMPETITION_ID,EVENT_ID, STUID, HeatorFinal, RANK, RESULT, is_NEWRECORD) VALUES (\"".$todayschyr."\",\"".$COMPETITION_ID."\",\"".$EVENT_ID."\",\"".$STUID."\",\"".$confirmheatfinal."\",\"".$RANK."\",\"".$RESULT."\",\"".$is_NEWRECORD."\")");
							//計分
							$SCORE = 0;
							if ($is_NEWRECORD == 1 ) {
								$SCORE = $SCORE + $newrecscore;
							}
							$sql = mysqli_query($splink,"Select ATTENDANCE from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\"");
							while ($row = mysqli_fetch_row($sql)){
								if ($row[0] == 1) {  //出席就CHECK 達標
									if ($trackfield == 1 ) {
										if ($standard > $RESULT ) {
											$SCORE + $attscore;
										}
									} else {
										if ($standard < $RESULT) {
											$SCORE + $attscore;
										}
									}
								} else if ($row[0] == 2) {
									//請假不用扣分
								} else {
									//缺席扣分
									$SCORE = $SCORE - $absscore;
								}
							}
							$sql = mysqli_query($splink,"Select SCORE from STU_SCORE where SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
							if (mysqli_num_rows($sql) > 0) {
								while ($row = mysqli_fetch_row($sql)) {
									$SCORE = $SCORE + $row[0];
								}
								$sql = mysqli_query($splink,"Update STU_SCORE SET SCORE=\"".$SCORE."\" WHERE SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
							}  else {
								$sql = mysqli_query($splink,"INSERT INTO STU_SCORE ( SCHYEAR , STUID , SCORE ) VALUES (\"".$todayschyr."\",\"".$STUID."\",\"".$SCORE."\")");


							}
							
							//計社分
							$csql = mysqli_query($splink,"Select SCORE from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
							if (mysqli_num_rows($csql) > 0 ) {
								while ($crow = mysqli_fetch_row($csql)){
									$newscore = $crow[0] + $SCORE;
								}
								$usql = mysqli_query($splink,"Update HOUSE_SCORE SET SCORE = \"".$newscore."\" where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
							} else {
								$isql = mysqli_query($splink,"Insert into HOUSE_SCORE (SCHYEAR, SCHHOUSE,GRADE, SCORE,SEX) VALUES (\"".$todayschyr."\",\"".$SCHHOUSE."\",\"".$compgrade."\",\"".$SCORE."\",\"".$SEX."\")");
							}
						}
					} else {  //決賽
						$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\" AND HeatorFinal = \"".$confirmheatfinal."\"");
						if (mysqli_num_rows($csql) > 0 ) {
							//confirmed .. do nothing
						//	$usql = mysqli_query($splink,"Update CONFIRMED_RESULT SET RESULT=\"".$RESULT."\", is_NEWRECORD=\"".$is_NEWRECORD."\", RANK = \"".$RANK."\" where  SCHYEAR=\"".$todayschyr."\" AND COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\" AND HeatorFinal = \"".$confirmheatfinal."\"");
						} else {
							$sql = mysqli_query($splink,"Insert into CONFIRMED_RESULT (SCHYEAR, COMPETITION_ID, STUID, HeatorFinal, RANK, RESULT, is_NEWRECORD) VALUES (\"".$todayschyr."\",\"".$COMPETITION_ID."\",\"".$STUID."\",\"".$confirmheatfinal."\",\"".$RANK."\",\"".$RESULT."\",\"".$is_NEWRECORD."\")");
							if ($haveheat == 1) {   //有初賽
								//計分
								if ($RANK < 9 ) {
									$rankscoreindex = $RANK - 1;
									$SCORE = $singlerank[$rankscoreindex];
									$hsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND HeatorFinal = \"0\" AND is_NEWRECORD=\"1\"");
									if (mysqli_num_rows($hsql) > 0 ) {
										//初賽囉了破記錄分..決賽就冇....
									} else {
										if ($is_NEWRECORD == 1 ) {
											$SCORE = $SCORE + $newrecscore;
										}
									}
									$sql = mysqli_query($splink,"Select SCORE from STU_SCORE where SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
									if (mysqli_num_rows($sql) > 0) {
										while ($row = mysqli_fetch_row($sql)) {
											$SCORE = $SCORE + $row[0];
										}
										$sql = mysqli_query($splink,"Update STU_SCORE SET SCORE=\"".$SCORE."\" WHERE SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
									}  else {
										$sql = mysqli_query($splink,"INSERT INTO STU_SCORE ( SCHYEAR , STUID , SCORE ) VALUES (\"".$todayschyr."\",\"".$STUID."\",\"".$SCORE."\")");
									}
								}
								
								//計社分
								$csql = mysqli_query($splink,"Select SCORE from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
								if (mysqli_num_rows($csql) > 0 ) {
									while ($crow = mysqli_fetch_row($csql)){
										$newscore = $crow[0] + $SCORE;
									}
									$usql = mysqli_query($splink,"Update HOUSE_SCORE SET SCORE = \"".$newscore."\" where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
								} else {
									$isql = mysqli_query($splink,"Insert into HOUSE_SCORE (SCHYEAR, SCHHOUSE,GRADE, SCORE,SEX) VALUES (\"".$todayschyr."\",\"".$SCHHOUSE."\",\"".$compgrade."\",\"".$SCORE."\",\"".$SEX."\")");
								}
								
							} else {   //直接決賽
								$SCORE = 0;
								if ($RANK < 9 ) {
									$rankscoreindex = $RANK - 1;
									$SCORE = $singlerank[$rankscoreindex];
								}
								if ($is_NEWRECORD == 1 ) {
									$SCORE = $SCORE + $newrecscore;
								}
								$sql = mysqli_query($splink,"Select ATTENDANCE from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$STUID."\"");
								while ($row = mysqli_fetch_row($sql)){
									if ($row[0] == 1) {  //出席就CHECK 達標
										if ($trackfield == 1 ) {
											if ($standard > $RESULT ) {
												$SCORE + $attscore;
											}
										} else {
											if ($standard < $RESULT) {
												$SCORE + $attscore;
											}
										}
									} else if ($row[0] == 2) {
										//請假不用扣分
									} else {
										//缺席扣分
										$SCORE = $SCORE - $absscore;
									}
								}
								$sql = mysqli_query($splink,"Select SCORE from STU_SCORE where SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
								if (mysqli_num_rows($sql) > 0) {
									while ($row = mysqli_fetch_row($sql)) {
										$SCORE = $SCORE + $row[0];
									}
									$sql = mysqli_query($splink,"Update STU_SCORE SET SCORE=\"".$SCORE."\" WHERE SCHYEAR=\"".$todayschyr."\" AND STUID=\"".$STUID."\"");
								}  else {
									$sql = mysqli_query($splink,"INSERT INTO STU_SCORE ( SCHYEAR , STUID , SCORE ) VALUES (\"".$todayschyr."\",\"".$STUID."\",\"".$SCORE."\")");
								}
								
								//計社分
								$csql = mysqli_query($splink,"Select SCORE from HOUSE_SCORE where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
								if (mysqli_num_rows($csql) > 0 ) {
									while ($crow = mysqli_fetch_row($csql)){
										$newscore = $crow[0] + $SCORE;
									}
									$usql = mysqli_query($splink,"Update HOUSE_SCORE SET SCORE = \"".$newscore."\" where SCHYEAR=\"".$todayschyr."\" AND SCHHOUSE=\"".$SCHHOUSE."\" AND GRADE=\"".$compgrade."\" AND SEX=\"".$SEX."\"");
								} else {
									$isql = mysqli_query($splink,"Insert into HOUSE_SCORE (SCHYEAR, SCHHOUSE,GRADE, SCORE,SEX) VALUES (\"".$todayschyr."\",\"".$SCHHOUSE."\",\"".$compgrade."\",\"".$SCORE."\",\"".$SEX."\")");
								}
		
							}
						}
					}
				$x++;
				}
			}
			$msg = $txtsuccesssave;
		}
		//finish php savesonfirmresult
		//php gen heat ranking
		if (isset($genrankingforheat)){
			$sql = mysqli_query($splink,"Select keyid,RESULT from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND HeatorFinal =\"0\" AND NOT RESULT =\"\" ORDER BY RESULT ASC");
			$x= 1;
			while ($row = mysqli_fetch_row($sql)){
				$orirank = $x;
				if (isset($lastresult) && $row[1] == $lastresult ) {
					$rank = $lastrank;
				} else {
					$rank = $orirank; 
				}
				$upsql = mysqli_query($splink,"Update CONFIRMED_RESULT SET RANK = \"".$rank."\" where keyid = \"".$row[0]."\"");
				 $lastrank = $row[1] ;
				$x++;
			}
			$msg =  $txtfinishgetheatranking;
		}
		//finish php  gen heat ranking
		$selectlist = "";
		$sql= mysqli_query($splink,"Select A.COMPETITION_ID, B.CH_DES, B.EN_DES,B.TRACKFIELD,B.SETLANE from ( Select COMPETITION_ID from HEAT_RESULT GROUP BY COMPETITION_ID UNION SELECT COMPETITION_ID from TRACKEVENT_FINAL_LANE GROUP BY COMPETITION_ID ) AS A inner join COMPETITIONITEM AS B on A.COMPETITION_ID=B.keyid GROUP BY A.COMPETITION_ID ORDER BY B.INTERHOUSE, B.INTERCLASS,B.GRADE, B.TRACKFIELD, B.SEX");
		while ($row = mysqli_fetch_row($sql)){
			if ($row[3] == 1 && $row[4] == 1){  //TRACK
				$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$row[0]."\" GROUP BY EVENT_ID");
				$noofevent = mysqli_num_rows($csql);
				$csql = mysqli_query($splink,"Select * from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$row[0]."\" GROUP BY EVENT_ID");
				$noofheatevent = mysqli_num_rows($csql);
				$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$row[0]."\" AND NOT RANK=\"\"");
				$noofconfirmedresult = mysqli_num_rows($csql);
				$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$row[0]."\" AND HeatorFinal = \"1\" AND NOT RANK=\"\"");
				$noofconfirmedfinalresult = mysqli_num_rows($csql);
				$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$row[0]."\" AND NOT RESULT=\"\"");
				$nooffinishresult = mysqli_num_rows($csql);
				if ( $noofevent == $noofheatevent ) {
					if ($nooffinishresult > 0 ) {
						$showstat = "(".$txtwaitconfirmfinalresult.")";
							} else {
						$showstat = "(".$txt1stheat."-".$txtconfirmed.")";
					}
					if (isset($COMPETITION_ID) &&($row[0] == $COMPETITION_ID) ) {
						if ($noofconfirmedresult > 0 ) {
							$showrankbn = 2;
							if ($nooffinishresult > 0 ) {
								$showstat = "(".$txtwaitconfirmfinalresult.")";
							} else {
								$showstat = "(".$txtfinishgetheatranking.")";
							}
						} else {
							$showrankbn = 1;
						}
					} else {
						$showrankbn = 0;
					}
				} else {
					if ($noofconfirmedfinalresult > 0 ) {
									$showstat = "(".$txtconfirmed.")";
								} else {
									$showstat = "";
								}
					if (isset($COMPETITION_ID) &&($row[0] == $COMPETITION_ID)) {
						$showrankbn = 0;
					}
				}
			} else {  //FIELD
				$csql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$row[0]."\"");
				if (mysqli_num_rows($csql) > 0 ) {
					$showstat = "(".$txtconfirmed.")";
				} else {
					$showstat = "";
				}
			}
			if (isset($COMPETITION_ID) && $COMPETITION_ID== $row[0]){
				$selected = "selected=\"selected\"";
			} else {
				$selected="";
			}
			if ($lang == "chi") {
				$showname = $row[1];
			} else {
				$showname = $row[2];
			}
			$selectlist .= "<option value=\"".$row[0]."\" ".$selected.">".$showname.$showstat."</option>";
		}
		$sql= mysqli_query($splink,"Select A.COMPETITION_ID, B.CH_DES, B.EN_DES from INTERHOUSE_COMPETITION AS A inner join COMPETITIONITEM AS B on A.COMPETITION_ID=B.keyid GROUP BY A.COMPETITION_ID ORDER BY B.INTERHOUSE, B.INTERCLASS,B.GRADE, B.TRACKFIELD, B.SEX");
		while ($row = mysqli_fetch_row($sql)){
			if (isset($COMPETITION_ID) && $COMPETITION_ID== $row[0]){
				$selected = "selected=\"selected\"";
			} else {
				$selected="";
			}
			if ($lang == "chi") {
				$showname = $row[1];
			} else {
				$showname = $row[2];
			}
			$selectlist .= "<option value=\"".$row[0]."\" ".$selected.">".$showname."</option>";
		}
		?>
        <h2><?=$txtconfirmresult?></h2>
        <center><?=$msg?></center>
        <form action="eventday.php" method="POST"><input type="hidden" name="confirmresult" />
            <label for="listA"><?=$txtcompetitionitem?></label>
                <select id="listA" name="COMPETITION_ID" onchange="submit()"><option value= ""><?=$txtcompetitionitem?></option><?=$selectlist?></select>
        </form>
        <?php
		if (isset($COMPETITION_ID) && $COMPETITION_ID !==""){
			$sqlh = mysqli_query($splink,"Select * from HEAT_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\"");
			$finalresult = mysqli_num_rows($sqlh);
			if ($finalresult > 0 ) {
				$isheat = 1;
			} else {
				$isheat = 0;
			}
			$sqlf = mysqli_query($splink,"Select * from TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\"");
			$finalresult = mysqli_num_rows($sqlf);
			if ($finalresult > 0) {
				$isfinal = 1;
			} else {
				$isfinal = 0;
			}
			$sql = mysqli_query($splink,"Select * from INTERHOUSE_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" order by RESULT");
				$finalresult = mysqli_num_rows($sql);
			if ($finalresult > 0 ) {
				$ishouse = 1;
			} else {
				$ishouse = 0;
			}
			
			if ($ishouse == 1) {   //社際成積
				$rsql = mysqli_query($splink,"Select RECORD from BEST_RECORD where COMPETITION_ID=\"".$COMPETITION_ID."\"");
				if (mysqli_num_rows($rsql) > 0 ) {
					while ($rrow = mysqli_fetch_row($rsql)){
						$bestrecord = $rrow[0];
					}
				}

				$sql = mysqli_query($splink,"Select SCHHOUSE, TEAM, ATTENDANCE, RESULT from INTERHOUSE_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" order by RESULT");
				?>
                <form action="eventday.php" method="Post" ><input type="hidden" name="confirmresult" />
                <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>" />
                <input type="hidden" name="houseevent" />
				<table><thead>
				<th><?=$txttracknum?></th>
				<th><?=$txthouse?></th><th><?=$txtteam?></th>
				<th><?=$txtstatus?></th><th><?=$txtresult?></th>
				<th><?=$txtrank?></th><th><?=$txtnewrecord?></th>
				</thead>
				<tbody>
				<?php
				$x = 1;
				while ($row = mysqli_fetch_row($sql)){
					if ($row[0] == "R") {
						$housename= $txthouseR;
						if ($row[1] == "A" ) {
							$tracknum = 1;
						} else {
							$tracknum = 5;
						}
					} else if ($row[0] == "Y"){
						$housename= $txthouseY;
						if ($row[1] == "A" ) {
							$tracknum = 2;
						} else {
							$tracknum = 6;
						}
					} else if ($row[0] == "B") {
						$housename= $txthouseB;
						if ($row[1] == "A" ) {
							$tracknum = 3;
						} else {
							$tracknum = 7;
						}
					} else if ($row[0] == "G"){
						$housename= $txthouseG;
						if ($row[1] == "A" ) {
							$tracknum = 4;
						} else {
							$tracknum = 8;
						}
					}
					if ($row[2] == 1) {
						$att = $txtattended;
					} else if ($row[2] == 2) {
						$att = $txtapplyleave;
					} else {
						$att = $txtabsent;
					}
					if (isset($lastresult) && $row[3] == $lastresult ) {
						$showrank = $lastrank;
					} else {
						$showrank = $x;
						$lastrank = $showrank;
					}
					$lastresult = $row[3];
					$x++;
					if (isset($bestrecord)){
						if ($bestrecord > $row[3]) {
							$newrecord="*";
						} else {
							$newrecord= "";
						}
					} else {
						$newrecord = "";
					}
					//disable submit button if already confirmed
					$dsql = mysqli_query($splink,"Select * from INTERHOUSE_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND NOT RANK=\"\"");
					if (mysqli_num_rows($dsql) > 0 ) {
						$disablebutton = " disabled=\"disabled\" ";
					} else {
						$disablebutton = "";
					}
					?>
						<tr>
						<td><?=$tracknum?></td>
                        <td><?=$housename?></td><td><?=$row[1]?></td><td><?=$att?></td>
                        <td><?=$row[3]?></td>
	                    <td><input type="hidden" name="rank[]" value="<?=$row[0]?>-<?=$row[1]?>-<?=$showrank?>-<?=$row[3]?>" /><?=$showrank?></td>
                        <td><?=$newrecord?></td>
                        </tr>
                    <?php
                }
				?>
                </tbody>
				</table>
                <input type="submit" name="saveconfirmresult" value="<?=$txtconfirmresult?>" <?=$disablebutton?> class="special"/>&nbsp;&nbsp;<input type="submit" name="cancel" value="<?=$txtback?>" />
                </form>
				<?php	
			} else {				//個人項目
				$sql = mysqli_query($splink,"Select TRACKFIELD from COMPETITIONITEM WHERE keyid=\"".$COMPETITION_ID."\"");
				while ($row = mysqli_fetch_row($sql)){
					$trackfield = $row[0];
				}
				?>
                <?php
				$ready = 1;
				if ($trackfield == 2) { //field
					$sql = mysqli_query($splink,"Select A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME from HEAT_RESULT AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where COMPETITION_ID=\"".$COMPETITION_ID."\" ORDER BY A.RESULT DESC");
					$havelane = 0;
					$confirmheatfinal = 1;

					//disable submit button if already confirmed
					$dsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					if (mysqli_num_rows($dsql) > 0 ) {
						$disablebutton = " disabled=\"disabled\" ";
					} else {
						$disablebutton = "";
					}
				} else {  //track
					if ($isheat == 1 && $isfinal == 0 ) {  //只有初賽或直接決賽
						$sql = mysqli_query($splink,"Select A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME, LANE_NO from TRACKEVENT_HEAT_LANE AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND NOT A.RESULT = \"\" ORDER BY A.RESULT ASC");
						$sqlf = mysqli_query($splink,"SELECT A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME, LANE_NO  from TRACKEVENT_HEAT_LANE AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.RESULT = \"\"");
						if (mysqli_num_rows($sql) > 0) {
							$ready = 0;    //未有EVENT_ID時需要設為0
							if (isset($EVENT_ID)){
								$ready = 1;
								$sql = mysqli_query($splink,"Select A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME, LANE_NO from TRACKEVENT_HEAT_LANE AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND EVENT_ID=\"".$EVENT_ID."\" ORDER BY A.LANE_NO ASC");
							
								//disable submit button if already confirmed
								$dsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND EVENT_ID=\"".$EVENT_ID."\"");
								if (mysqli_num_rows($dsql) > 0 ) {
									$disablebutton = " disabled=\"disabled\" ";
									$showstat = "(".$txtconfirmed.")";
								} else {
									$disablebutton = "";
									$showstat = "";
								}
							}
							$havelane = 1;
							$confirmheatfinal=0;
							$esql = mysqli_query($splink,"Select EVENT_ID from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" GROUP BY EVENT_ID");
							$event_list = "";
							while ($erow = mysqli_fetch_row($esql)){
								$dsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND EVENT_ID=\"".$erow[0]."\"");
								if (mysqli_num_rows($dsql) > 0 ) {
									$showstat = "(".$txtconfirmed.")";
								} else {
									$showstat = "";
								}
								if (isset($EVENT_ID) && $EVENT_ID == $erow[0]) {
									$selected = " selected = \"selected\"";
								} else {
									$selected = "";
								} 
								$event_list .= "<option value = \"".$erow[0]."\" ".$selected.">".$erow[0].$showstat."</option>";
							}
							if ($showrankbn == 1) {
								?>
							 <form action="eventday.php" method="POST"><input type="hidden" name="confirmresult" />
                            <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>" />
                            <input type="submit" name="genrankingforheat" value="<?=$txtgenrankingforheat?>" />
                            </form>
                            <?php   
							} else if ($showrankbn == 2)  {
							} else  {
								?>
								<form action="eventday.php" method="POST"><input type="hidden" name="confirmresult" />
								<input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>" />
								<select name="EVENT_ID" onchange="submit()"><option><?=$txteventid?></option><?=$event_list?></select>
								</form>
								<?php
							}
						} else {  //不需要線道直接決賽項目
							$havelane = 0;
							$sql = mysqli_query($splink,"Select A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME from HEAT_RESULT AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND NOT A.RESULT = \"\" ORDER BY A.RESULT ASC");
							$sqlf = mysqli_query($splink,"SELECT A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME  from HEAT_RESULT AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.RESULT = \"\"");
							$confirmheatfinal =1;
							
							//disable submit button if already confirmed
							$dsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\"");
							if (mysqli_num_rows($dsql) > 0 ) {
								$disablebutton = " disabled=\"disabled\" ";
							} else {
								$disablebutton = "";
							}
						}
						
					}
					if ($isheat == 1 && $isfinal == 1) { //包含初賽的決賽
						$sql = mysqli_query($splink,"Select A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME, LANE_NO  from TRACKEVENT_FINAL_LANE AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.COMPETITION_ID=\"".$COMPETITION_ID."\" AND NOT A.RESULT = \"\" ORDER BY A.RESULT ASC");
						$sqlf = mysqli_query($splink,"SELECT A.STUID, A.RESULT, B.CLASSCODE, B.CLASSNO, B.CHNAME, B.ENNAME, LANE_NO  from TRACKEVENT_FINAL_LANE AS A INNER JOIN studentinfo AS B ON A.STUID = B.STUID where A.RESULT = \"\"");
						$havelane = 1;
						$confirmheatfinal=1;
						
						//disable submit button if already confirmed
						$dsql = mysqli_query($splink,"Select * from CONFIRMED_RESULT where COMPETITION_ID=\"".$COMPETITION_ID."\" AND HeatorFinal=\"1\"");
						if (mysqli_num_rows($dsql) > 0 ) {
							$disablebutton = " disabled=\"disabled\" ";
						} else {
							$disablebutton = "";
						}

					}
				}
				if (mysqli_num_rows($sql) > 0 && $ready==1) {
					if ($trackfield == 1 && $havelane == 1 && $isheat == 1 && $isfinal !== 1) {?>
                    <h3><?=$txt1stheat?></h3>
                    <?php }  
					if (($trackfield == 1 && $havelane == 1 && $isfinal == 1) || $trackfield == 2 ) {?>
                    <h3><?=$txtfinal?></h3>
                    <?php } ?>
                    
                    <form action="eventday.php" method="Post" ><input type="hidden" name="confirmresult" />
                    <input type="hidden" name="COMPETITION_ID" value="<?=$COMPETITION_ID?>" />
                    <input type="hidden" name="trackfield" value="<?=$trackfield?>" />
                    <input type="hidden" name="confirmheatfinal" value="<?=$confirmheatfinal?>" />
                    <?php if (isset($EVENT_ID)){ ?>
                    <input type="hidden" name="EVENT_ID" value ="<?=$EVENT_ID?>" />
                    <?php } ?>
                    <table><thead>
					<?php if ($trackfield == 1 && $havelane == 1) {?><th><?=$txttracknum?></th><?php } ?>
                    <th><?=$txtclass?></th><th><?=$txtclassno?></th><th><?=$txtname?></th>
                    <th><?=$txtstatus?></th><th><?=$txtresult?></th>
                    <?php if (!isset($EVENT_ID)){ ?>
                    <th><?=$txtrank?></th><th><?=$txtnewrecord?></th>
                    <?php } ?>
                    </thead>
                    <tbody>
                    <?php
					//get best record of the event
					$rsql = mysqli_query($splink,"Select RECORD from BEST_RECORD where COMPETITION_ID=\"".$COMPETITION_ID."\"");
					if (mysqli_num_rows($rsql) > 0 ) {
						while ($rrow = mysqli_fetch_row($rsql)){
							$bestrecord = $rrow[0];
						}
					}
					//finish get best record of the event 
					$rank = 1;
					while ($row = mysqli_fetch_row($sql)){
						if (isset($lastresult) && $lastresult == $row[1]) {
							$lastresult = $row[1];
							$showrank = $lastrank;
						} else {
							$showrank = $rank;
							$lastrank = $showrank;
							$lastresult = $row[1];
						}
						if ($row[1] =="") {
							$showrank = "";
						}
						if ($lang == "chi") {
							$showname = $row[4];
						} else {
							$showname = $row[5];
						}
						if ($havelane == 0) {
							$asql = mysqli_query($splink,"Select ATTENDANCE from APPLICATION_COMPETITION where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID=\"".$row[0]."\"");
						} else {
							if ($isfinal == 1 ) {
								$asql = mysqli_query($splink," Select ATTENDANCE from TRACKEVENT_FINAL_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID = \"".$row[0]."\"");
							} else {
								$asql = mysqli_query($splink," Select ATTENDANCE from TRACKEVENT_HEAT_LANE where COMPETITION_ID=\"".$COMPETITION_ID."\" AND STUID = \"".$row[0]."\"");
							}
						}
						while ($arow = mysqli_fetch_row($asql)){
							if ($arow[0] == 1) {
								$att = $txtattended;
							} else if ($arow[0] == 2) {
								$att = $txtapplyleave;
							} else {
								$att = $txtabsent;
							}
						}
						if (isset($bestrecord)){
							if ($trackfield == 1 ) {
								if ($bestrecord > $row[1] ) {
									$newrecord = "*";
								} else {
									$newrecord = "";
								}
							} else {
								if ($bestrecord < $row[1]) {
									$newrecord = "*";
								} else {
									$newrecord = "";
								}
							}
						} else {
							$newrecord = "";
						}
						?>
                        <tr>
						<?php if ($trackfield == 1 && $havelane == 1) {?><td><?=$row[6]?></td><?php } ?>
                        <td><?=$row[2]?></td><td><?=$row[3]?></td><td><?=$showname?></td><td><?=$att?></td>
                        <td><?=$row[1]?></td>
	                    <?php if (!isset($EVENT_ID)){ ?>
                        <td><input type="hidden" name="rank[]" value="<?=$row[0]?>-<?=$row[1]?>-<?=$showrank?>" /><?=$showrank?></td>
                        <td><?=$newrecord?></td>
                        <?php  }  else { ?>
                        <input type="hidden" name="rank[]" value="<?=$row[0]?>-<?=$row[1]?>" />
                        <?php  } ?>
                        </tr>
                        <?php
                        $rank = $rank + 1;
					}
					?>
                    </tbody>
                    </table>
                    <input type="submit" name="saveconfirmresult" value="<?=$txtconfirmresult?>" <?=$disablebutton?> class="special"/>&nbsp;&nbsp;<input type="submit" name="cancel" value="<?=$txtback?>" /></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>';
}
?>