티스토리 뷰

반응형


<title> 토너먼트16강 </title>

<?php include 'common.php';

isset($_REQUEST["num"])  ? $num=$_REQUEST["num"] :   $num=''; 

 try{  
 $sql = "select * from mirae8441.game where num = ?  ";
  $stmh = $pdo->prepare($sql); 
  $stmh->bindValue(1,$num,PDO::PARAM_STR); 
  $stmh->execute();
      $count = $stmh->rowCount();    

// 좌측 그룹 (A조)의 순위 데이터를 담을 빈 배열을 만듭니다.
$leftGroupRanking = array();

// 우측 그룹 (B조)의 순위 데이터를 담을 빈 배열을 만듭니다.
$rightGroupRanking = array();

    
       while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
  
                 include 'rowDB.php';

 if($registedate!="") {
$week = array("(일)" , "(월)"  , "(화)" , "(수)" , "(목)" , "(금)" ,"(토)") ;
$registedate = $registedate . $week[ date('w',  strtotime($registedate)  ) ] ;
}

$pp_name_arr = explode(",", $pp_name);
$pp_grade_arr = explode(",", $pp_grade);

$participantArrayList = "";
        
                // print_r($making);


foreach ($pp_name_arr as $index => $name) {
  // $index는 배열 요소의 인덱스, $name은 해당 인덱스의 값인 $pp_name_arr[$index]
  $grade = $pp_grade_arr[$index];
  if($index !== count($pp_name_arr) -1 )
  $participantArrayList .= $name . $grade . " , ";
else
  $participantArrayList .= $name . $grade;
}

$pp_result_table = explode(';', $pp_result);
$pp_result_text = '';

foreach ($pp_result_table as $mainIndex => $table) {
$smallArray = explode(',',$table); 
foreach ($smallArray as  $subIndex => $smallData) {
$lastArray = explode('*',$smallData);     

foreach ($lastArray as  $index => $microData) {

                           // print $index;
     
  if($lastArray[0] === '0')
  $pp_result_text .= 'A조 ';
  if($lastArray[0] === '1')
  $pp_result_text .= 'B조 ';
  if($lastArray[0] === '2')
  $pp_result_text .= 'C조 ';
     
  if($index === 1 )
  $pp_result_text .= $microData . " " ;
  if($index === 2 )
  $pp_result_text .= $microData . "위 " ;

     
  }
    // A조에 해당하는 순위 데이터를 처리하고 $leftGroupRanking 배열에 추가합니다.
if ($lastArray[0] === '0') {
$leftGroupRanking[] = array(
'group' => $lastArray[0], // A조의 번호 (0, 1, 2 등)
'name' => $lastArray[1], // A조의 참가자 이름
'rank' => $lastArray[2] // A조의 참가자 등수
);
}

// B조에 해당하는 순위 데이터를 처리하고 $rightGroupRanking 배열에 추가합니다.
if ($lastArray[0] === '1') {
$rightGroupRanking[] = array(
'group' => $lastArray[0], // B조의 번호 (0, 1, 2 등)
'name' => $lastArray[1], // B조의 참가자 이름
'rank' => $lastArray[2] // B조의 참가자 등수
);
}


     $pp_result_text .= ", " ;   
  $lastArray[0] = '';
}
}




  } catch (PDOException $Exception) {
  print "오류: ".$Exception->getMessage();
  }  
  
  
  
// usort를 사용하여 $leftGroupRanking 배열을 rank(등수)에 따라 오름차순으로 정렬합니다.
usort($leftGroupRanking, function ($a, $b) {
    // rank 값을 숫자형으로 변환하여 순위(rank)에 따라 오름차순으로 정렬합니다.
    $rankA = intval($a['rank']);
    $rankB = intval($b['rank']);
    return $rankA - $rankB;
});

// usort를 사용하여 $rightGroupRanking 배열을 rank(등수)에 따라 오름차순으로 정렬합니다.
usort($rightGroupRanking, function ($a, $b) {
    // rank 값을 숫자형으로 변환하여 순위(rank)에 따라 오름차순으로 정렬합니다.
    $rankA = intval($a['rank']);
    $rankB = intval($b['rank']);
    return $rankA - $rankB;
});



// $group 값이 '0'인 요소만 담은 새로운 배열을 생성합니다.
$LG = array_filter($leftGroupRanking, function ($participant) {
    return $participant['group'] === '0';
});

// 정렬된 $LG 배열을 출력합니다.
foreach ($LG as $index => $participant) {
    $group = $participant['group'];
    $name = $participant['name'];
    $rank = $participant['rank'];

   // echo " 좌측 그룹 (A조) - 그룹 : " . $group . " (" . $name . ") - " . $rank . " 위 <br>";
}

// $group 값이 '1'인 요소만 담은 새로운 배열을 생성합니다.
$RG = array_filter($rightGroupRanking, function ($participant) {
    return $participant['group'] === '1';
});

// 정렬된 $RG 배열을 출력합니다.
foreach ($RG as $index => $participant) {
    $group = $participant['group'];
    $name = $participant['name'];
    $rank = $participant['rank'];

    // echo " 우측 그룹 (B조) - 그룹 : " . $group . " (" . $name . ") - " . $rank . " 위 <br>";
}

// $group 값이 '0'인 요소만 담은 새로운 배열을 생성합니다.
$LG = array_filter($leftGroupRanking, function ($participant) {
    return $participant['group'] === '0';
});

// $group 값이 '1'인 요소만 담은 새로운 배열을 생성합니다.
$RG = array_filter($rightGroupRanking, function ($participant) {
    return $participant['group'] === '1';
});
function findParticipantByRank($participants, $rank, $group)
{
    foreach ($participants as $participant) {
        if ($participant['rank'] === $rank) {
            return $group . $rank  . '위 ' . $participant['name'];
        }
    }
    return '';
}

// $groupA 배열 초기화
$groupA = array(
    findParticipantByRank($LG, '1', "A조" ),
    findParticipantByRank($RG, '8', "B조" ),
    findParticipantByRank($RG, '3', "B조" ),
    findParticipantByRank($LG, '6', "A조" ),
    findParticipantByRank($LG, '4', "A조" ),
    findParticipantByRank($RG, '5', "B조" ),
    findParticipantByRank($RG, '2', "B조" ),
    findParticipantByRank($LG, '7', "A조" ),
);

// $groupB 배열 초기화
$groupB = array(
    findParticipantByRank($RG, '1', "B조" ),
    findParticipantByRank($LG, '8', "A조" ),
    findParticipantByRank($LG, '3', "A조" ),
    findParticipantByRank($RG, '6', "B조" ),
    findParticipantByRank($RG, '4', "B조" ),
    findParticipantByRank($LG, '5', "A조" ),
    findParticipantByRank($LG, '2', "A조" ),
    findParticipantByRank($RG, '7', "B조" ),
);


// $groupA와 $groupB 배열 출력
// for ($i = 0; $i < 8; $i++) {
    // echo "groupA의 " . ($i + 1) . "번째 요소: " . $groupA[$i] . "<br>";
    // echo "groupB의 " . ($i + 1) . "번째 요소: " . $groupB[$i] . "<br>";
// }
 


if($T_rule=='')
$T_rule = "3전2선승";


 ?>
 
 
<meta name="viewport" content="width=device-width, initial-scale=0.7, user-scalable=yes">
 
<style>


    .tdwidth {
        width: 20px;
    }

    .tdwidth-first-last {
        width: 20px;
    }

td {
 height:30px;
 width:20px;
}
.spacer {
 height:10px;  
}

    th, td, tr {
border : none;
    }

  .highlight {
    border: 2px solid black; /* Add border to highlighted td elements */
  }
  
  .highlight-dragged {
        border: 2px dashed black;
    }

tr, th, td {
 height:10px;  
}

.playerscore:hover, .first_round:hover, .second_round:hover, .third_round:hover, .forth_round:hover {
    cursor: pointer;
height:12px;
}


.no-padding.col-sm-6 {
    padding-left: 0;
    padding-right: 0;
}
     
 
 
 table tr, td, th {
    height: 12px !important;
padding : 0px !important;
}
 

 
</style>




<form id="board_form" name="board_form" method="post">    
   
    <div class="container-fluid mt-3 mb-5">
       <div class="row">
<div class="d-flex mb-2 mt-3 justify-content-center align-items-center">   
<h3 class="text-center"> 16강 토너먼트 </h3> &nbsp;&nbsp; <span id="playTitle" class="text-secondary fs-5" > </span>
</div>
       </div>
       <div class="row">
<div class="d-flex mb-2 mt-2 justify-content-center align-items-center">   
<span class="text-secondary fs-4" > 경기룰
<select name="T_rule" id="T_rule" class="text-primary fs-5 " style=" border-width: 3px; border: 3px solid blue;" >
   <?php  
   $rulearr = array("5전3선승","3전2선승");

   for($i=0; $i<count($rulearr); $i++) {
 if($T_rule == $rulearr[$i])
print "<option selected value='" . $rulearr[$i] . "'> " . $rulearr[$i] .   "</option>";
 else   
   print "<option value='" . $rulearr[$i] . "'> " . $rulearr[$i] .   "</option>";
   }     
   

?>   
</select>     
</span>
&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;

   <span class="text-secondary fs-4" > 핸디방식 &nbsp;&nbsp;
   <input name="handy" id="handy" class="text-danger fs-5" value="<?=$handy?>" size="1" style=" border-width: 3px; border: 3px solid red;" readonly > </span>
&nbsp;&nbsp; &nbsp;&nbsp; 


<?php if($level === '1') { ?> 
 <button type="button" class="btn btn-danger delBtn">삭제</button> &nbsp;&nbsp;
<?php } ?> 
   <button type="button" class="btn btn-secondary  closeBtn">닫기</button> &nbsp;&nbsp;

       </div>
       <div class="row">

<div class="d-flex mb-2 mt-3 justify-content-center align-items-center">   
<span id="resultRank" class="text-secondary fs-5" > </span>
            </div>    

       </div>       

<!-- 승패기록 모달창 -->
<div class="modal fade " id="scoreModal" tabindex="-1" aria-labelledby="scoreModalLabel" aria-hidden="true">
   <div class="modal-dialog ">
<div class="modal-content " >
<div class="modal-header">
<h1 class="modal-title" >경기결과 입력</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button>
</div>
<div class="modal-body">                
   <h1>
<div class="d-flex justify-content-center mt-5 mb-3">
</div>
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 경기룰 : </span> &nbsp;&nbsp;
<span id="modalrule" class="text-primary"> </span>
 </div>               
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 핸디 : </span> &nbsp;&nbsp;
<span id="modalhandy" class="text-danger"> </span>
 </div>
 <div class="d-flex justify-content-center mb-5">
                           <button type="button" class="btn btn-primary btn-lg winBtn" data-side="left" >
<span id="leftname" > </span> &nbsp; 승 </button>
&nbsp;&nbsp;
<span  class="text-secondary "> VS  </span> &nbsp;&nbsp;
<button type="button" class="btn btn-primary btn-lg winBtn" data-side="right">
<span id="rightname" > </span> &nbsp;승  </button>
&nbsp;&nbsp;
 </div>                   
 </h1>
</div>
<div class="modal-footer">  
 <div class="d-flex justify-content-center mb-5 mt-5">   
<button type="button" class="btn btn-danger" id="delScoreBtn"> <h1> 기록삭제 </h1> </button> &nbsp;&nbsp;
<button id="closeModalBtn" type="button" class="btn btn-secondary" >  <h1> 닫기 </h1>  </button>
</div>

</div>
</div>
</div>

</div>  <!-- end of modal -->

<!-- 승패기록 모달창 -->
<div class="modal fade " id="first_round_Modal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog ">
<div class="modal-content " >
<div class="modal-header">
<h1 class="modal-title" >8강 경기결과 입력</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button>
</div>
<div class="modal-body">                
   <h1>
<div class="d-flex justify-content-center mt-5 mb-3">
</div>
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 경기룰 : </span> &nbsp;&nbsp;
<span id="modalrule_8" class="text-primary"> </span>
 </div>               
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 핸디 : </span> &nbsp;&nbsp;
<span id="modalhandy_8" class="text-danger"> </span>
 </div>
 <div class="d-flex justify-content-center mb-5">
                           <button type="button" class="btn btn-primary btn-lg winBtn_8" data-side="left" >
<span id="leftname_8" > </span> &nbsp; 승 </button>
&nbsp;&nbsp;
<span  class="text-secondary "> VS  </span> &nbsp;&nbsp;
<button type="button" class="btn btn-primary btn-lg winBtn_8" data-side="right">
<span id="rightname_8" > </span> &nbsp;승  </button>
&nbsp;&nbsp;
 </div>                   
 </h1>
</div>
<div class="modal-footer">  
 <div class="d-flex justify-content-center mb-5 mt-5">   
<button type="button" class="btn btn-danger" id="delScoreBtn_8"> <h1> 기록삭제 </h1> </button> &nbsp;&nbsp;
<button id="closeModalBtn_8" type="button" class="btn btn-secondary" >  <h1> 닫기 </h1>  </button>
</div>

</div>
</div>
</div>

</div>  <!-- end of modal -->

<!-- 승패기록 모달창 -->
<div class="modal fade " id="second_round_Modal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog ">
<div class="modal-content " >
<div class="modal-header">
<h1 class="modal-title" >4강 경기결과 입력</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button>
</div>
<div class="modal-body">                
   <h1>
<div class="d-flex justify-content-center mt-5 mb-3">
</div>
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 경기룰 : </span> &nbsp;&nbsp;
<span id="modalrule_4" class="text-primary"> </span>
 </div>               
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 핸디 : </span> &nbsp;&nbsp;
<span id="modalhandy_4" class="text-danger"> </span>
 </div>
 <div class="d-flex justify-content-center mb-5">
                           <button type="button" class="btn btn-primary btn-lg winBtn_4" data-side="left" >
<span id="leftname_4" > </span> &nbsp; 승 </button>
&nbsp;&nbsp;
<span  class="text-secondary "> VS  </span> &nbsp;&nbsp;
<button type="button" class="btn btn-primary btn-lg winBtn_4" data-side="right">
<span id="rightname_4" > </span> &nbsp;승  </button>
&nbsp;&nbsp;
 </div>                   
 </h1>
</div>
<div class="modal-footer">  
 <div class="d-flex justify-content-center mb-5 mt-5">   
<button type="button" class="btn btn-danger" id="delScoreBtn_4"> <h1> 기록삭제 </h1> </button> &nbsp;&nbsp;
<button id="closeModalBtn_4" type="button" class="btn btn-secondary" >  <h1> 닫기 </h1>  </button>
</div>

</div>
</div>
</div>

</div>  <!-- end of modal -->

<!-- 결승 모달창 -->
<div class="modal fade " id="third_round_Modal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog ">
<div class="modal-content " >
<div class="modal-header">
<h1 class="modal-title" >결승 경기결과 입력</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button>
</div>
<div class="modal-body">                
   <h1>
<div class="d-flex justify-content-center mt-5 mb-3">
</div>
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 경기룰 : </span> &nbsp;&nbsp;
<span id="modalrule_2" class="text-primary"> </span>
 </div>               
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 핸디 : </span> &nbsp;&nbsp;
<span id="modalhandy_2" class="text-danger"> </span>
 </div>
 <div class="d-flex justify-content-center mb-5">
                           <button type="button" class="btn btn-primary btn-lg winBtn_2" data-side="left" >
<span id="leftname_2" > </span> &nbsp; 승 </button>
&nbsp;&nbsp;
<span  class="text-secondary "> VS  </span> &nbsp;&nbsp;
<button type="button" class="btn btn-primary btn-lg winBtn_2" data-side="right">
<span id="rightname_2" > </span> &nbsp;승  </button>
&nbsp;&nbsp;
 </div>                   
 </h1>
</div>
<div class="modal-footer">  
 <div class="d-flex justify-content-center mb-5 mt-5">   
<button type="button" class="btn btn-danger" id="delScoreBtn_2"> <h1> 기록삭제 </h1> </button> &nbsp;&nbsp;
<button id="closeModalBtn_2" type="button" class="btn btn-secondary" >  <h1> 닫기 </h1>  </button>
</div>

</div>
</div>
</div>

</div>  <!-- end of modal -->

<!-- 최종 모달창 -->
<div class="modal fade " id="forth_round_Modal" tabindex="-1" aria-hidden="true">
   <div class="modal-dialog ">
<div class="modal-content " >
<div class="modal-header">
<h1 class="modal-title" >결승 경기결과 입력</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button>
</div>
<div class="modal-body">                
   <h1>
<div class="d-flex justify-content-center mt-5 mb-3">
</div>
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 경기룰 : </span> &nbsp;&nbsp;
<span id="modalrule_1" class="text-primary"> </span>
 </div>               
<div class="d-flex justify-content-center mb-5 mt-5">     
<span  class="text-secondary"> 핸디 : </span> &nbsp;&nbsp;
<span id="modalhandy_1" class="text-danger"> </span>
 </div>
 <div class="d-flex justify-content-center mb-5">
                           <button type="button" class="btn btn-primary btn-lg winBtn_1" data-side="left" >
<span id="leftname_1" > </span> &nbsp; 승 </button>
&nbsp;&nbsp;
<span  class="text-secondary "> VS  </span> &nbsp;&nbsp;
<button type="button" class="btn btn-primary btn-lg winBtn_1" data-side="right">
<span id="rightname_1" > </span> &nbsp;승  </button>
&nbsp;&nbsp;
 </div>                   
 </h1>
</div>
<div class="modal-footer">  
 <div class="d-flex justify-content-center mb-5 mt-5">   
<button type="button" class="btn btn-danger" id="delScoreBtn_1"> <h1> 기록삭제 </h1> </button> &nbsp;&nbsp;
<button id="closeModalBtn_1" type="button" class="btn btn-secondary" >  <h1> 닫기 </h1>  </button>
</div>

</div>
</div>
</div>

</div>  <!-- end of modal -->

<div class="row">          
            <?php            

            // 16강 토너먼트 표 생성 함수
            function createTournamentBracket($groupA,$groupB)
            {
                $rounds = ceil(log(count($groupA), 2));
                $totalMatches = pow(2, $rounds - 1);
                // print_r($rounds);
                // print_r($totalMatches);
                // print_r($groupA);

echo '<div class="col-sm-6" > ';
echo '<table id="matchlistA" class="table" >';
echo ' <thead >  <tr>';
echo '<th style="width:200px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '</tr> </thead> ';
                   // echo '<div class="round">';
                // for ($i = 0; $i < $rounds; $i++) {
                   //  $matches = $totalMatches / pow(2, $i);
$repeat = 6 ;   
$matches = count($groupA) ;
 for ($j = 0; $j < $matches; $j++) {
if ($j !== 0) { // 첫번째 줄 제외
echo '<tr>';
echo '<td class="tdwidth spacer">&nbsp;</td>'; // 첫번째 칸
for ($k = 0; $k < $repeat -1; $k++) { // 첫번째 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';
}

echo '<tr>';
  if($groupA[$j] === '')
  {
   $groupA[$j] = 'x';  // 부전승은 과거 bye로 이제는 x로 표기
echo '<td rowspan="2" class="text-center  tdwidth highlight spacer">' . $groupA[$j] . '</td>'; // 첫번째 칸
  }
  else
  {
                    // 클릭동작을 위한 클래스 삽입   
   if($j===0 or $j===2 or $j===4 or $j===6) 
echo '<td rowspan="2" class="text-center  tdwidth highlight spacer playerscore" data-leftname="' .  $groupA[$j] . '" data-rightname="' .  $groupA[$j+1] . '" > ' . $groupA[$j] . '</td>'; // 첫번째 칸
   if($j===1 or $j===3 or $j===5 or $j===7) 
echo '<td rowspan="2" class="text-center  tdwidth highlight spacer playerscore" data-leftname="' .  $groupA[$j-1] . '" data-rightname="' .  $groupA[$j] . '" > ' . $groupA[$j] . '</td>'; // 첫번째 칸
  }
  
for ($k = 0; $k < $repeat - 1; $k++) { // 첫번째 칸과 마지막 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';
echo '<tr>';
for ($k = 0 ; $k < $repeat - 1; $k++) { // 첫번째 칸과 마지막 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';

if ($j !== $matches - 1) { // 마지막 줄 제외
// spacer가 아닌 추후 승자가 들어간 칸
echo '<tr>';
for ($k = 0; $k < $repeat ; $k++) { // 마지막 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';
echo '<tr>';
for ($k = 0; $k < $repeat ; $k++) {
echo '<td class="tdwidth spacer">&nbsp;</td>'; // 마지막 칸
}
echo '</tr>';
}
}

echo '</table>';
echo '</div> ';

echo '<div class="col-sm-6"> ';
echo '<table id="matchlistB" class="table">';
echo '<thead >  <tr>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:20px;" >&nbsp;</th>';
echo '<th style="width:200px;">&nbsp;</th>';
echo '</tr> </thead> ';

$repeat = 6 ;   
$matches = count($groupB)  ;
 for ($j = 0; $j < $matches; $j++) {
if ($j !== 0) { // 첫번째 줄 제외
echo '<tr>';
echo '<td class="tdwidth spacer">&nbsp;</td>'; // 첫번째 칸
for ($k = 0; $k < $repeat -1; $k++) { // 첫번째 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';
}

echo '<tr>';
for ($k = 0; $k < $repeat - 1; $k++) { // 첫번째 칸과 마지막 칸을 제외한 나머지 칸
echo '<td class="tdwidth spacer">&nbsp;</td>';
}
  if($groupB[$j] === '')
  {
   $groupB[$j] = 'x';
   
   
echo '<td rowspan="2" class="text-center  tdwidth highlight spacer">' . $groupB[$j] . '</td>'; // 첫번째 칸
  }
  else
  {
                                            // 클릭동작을 위한 클래스 삽입   
   if($j===0 or $j===2 or $j===4 or $j===6) 
echo '<td rowspan="2"   class="text-center  tdwidth highlight spacer playerscore" data-leftname="' .  $groupB[$j] . '" data-rightname="' .  $groupB[$j+1] . '" > ' . $groupB[$j] . '</td>'; // 첫번째 칸
   if($j===1 or $j===3 or $j===5 or $j===7) 
echo '<td rowspan="2"   class="text-center  tdwidth highlight spacer playerscore" data-leftname="' .  $groupB[$j-1] . '" data-rightname="' .  $groupB[$j] . '" > ' . $groupB[$j] . '</td>'; // 첫번째 칸
  }
  
echo '</tr>';
echo '<tr>';
for ($k = 0 ; $k < $repeat - 1; $k++) { // 첫번째 칸과 마지막 칸을 제외한 나머지 칸
echo '<td   class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';

if ($j !== $matches - 1) { // 마지막 줄 제외
// spacer가 아닌 추후 승자가 들어간 칸
echo '<tr>';
for ($k = 0; $k < $repeat ; $k++) { // 마지막 칸을 제외한 나머지 칸
echo '<td  class="tdwidth spacer">&nbsp;</td>';
}
echo '</tr>';
echo '<tr>';
for ($k = 0; $k < $repeat ; $k++) {
echo '<td  class="tdwidth spacer">&nbsp;</td>'; // 마지막 칸
}
echo '</tr>';
}
}

echo '</table>';
echo '</div> ';

               
            }

            createTournamentBracket($groupA,$groupB);
            ?>        
       
     </div>

<div class="row">   
<div class="d-flex mt-3 mb-3 justify-content-center align-items-center">   
<span class="text-secondary fs-3" ><?=$branch?> </span>

</div>    
</div>    

<div class="row">   
<div class="d-flex mt-3 mb-3 justify-content-center align-items-center">   
<span id="output" class="text-secondary fs-3" > </span>

</div>    
</div>    


<input type="hidden" id="level" name="level" value="<?=$level?>" >
<input type="hidden" id="pp_name_text" name="pp_name_text" value="<?=$pp_name_text?>" >
<input type="hidden" id="pp_grade_text" name="pp_grade_text" value="<?=$pp_grade_text?>" >
<input type="hidden" id="tableIndex" name="tableIndex" value="<?=$tableIndex?>" >   <!--선택된 테이블  -->
<input type="hidden" id="tableCount" name="tableCount" value="<?=$tableCount?>" >   <!--테이블 개수  -->
<input type="hidden" id="PP_count" name="PP_count" value="<?=$PP_count?>" >   <!--참가인원수  -->

<input type="hidden" id="mode" name="mode" value="<?=$mode?>">
<input type="hidden" id="num" name="num" value="<?=$num?>" >                        
<input type="hidden" id="gamenum" name="gamenum" value="<?=$gamenum?>" >                        
<input type="hidden" id="user_name" name="user_name" value="<?=$user_name?>" size="4" >
<input type="hidden" id="updatetime" name="updatetime" value="<?=$updatetime?>" size="4" >
<input type="hidden" id="pp_name" name="pp_name" value="<?=$pp_name?>" >
<input type="hidden" id="pp_grade" name="pp_grade" value="<?=$pp_grade?>" >
<input type="hidden" id="pp_point" name="pp_point" value="<?=$pp_point?>" >
<input type="hidden" id="pp_result" name="pp_result" value="<?=$pp_result?>" >
<input type="hidden" id="pp_group" name="pp_group" value="<?=$pp_group?>" > <!-- 조별로 테이블을 형성하기 위한 자료 -->
<input type="hidden" id="branch" name="branch" value="<?=$branch?>" > <!-- select disabled 자료전송이 안되는 부분 해결 -->
<input type="hidden" id="pp_table" name="pp_table" value="<?=$pp_table?>" >
<input type="hidden" id="rule" name="rule" value="<?=$rule?>" >
<input type="hidden" id="registedate" name="registedate" value="<?=$registedate?>" >
<input type="hidden" id="match_name" name="match_name" value="<?=$match_name?>" > 
<input type="hidden" id="making" name="making" value="<?=$making?>" > <!-- table 셔플이 중복금지를 위한 변수 -->
<input type="hidden" id="playerbefore" name="playerbefore" value="<?=$playerbefore?>" > 
<input type="hidden" id="playerafter" name="playerafter" value="<?=$playerafter?>" > <!--player 추가된 후 숫자  -->

<input type="hidden" id="T_rule" name="T_rule" value="<?=$T_rule?>" >
<input type="hidden" id="T_table" name="T_table" value="<?=$T_table?>" >
<input type="hidden" id="T_result" name="T_result" value="<?=$T_result?>" >

<input type="hidden" id="level" name="level" value="<?=$level?>" >
<input type="hidden" id="user_name" name="user_name" value="<?=$user_name?>" >

</div>
  </form>  
    
</body>
</html>

<script>


var participantList = []; // Array to store participant names and grades

var playerRecord;

var lossesSum = []; // Array to store the sum of losses in each column
var currentModalTd = null; // 현재 모달이 띄워진 td 요소를 저장할 변수
var colIndex, rowIndex; // 현재 선택한 셀의 행과 열 인덱스를 저장할 변수

var ajaxRequest = null ;
var ajaxRequest1 = null ;

window.addEventListener('unload', function(event) {
    if (window.opener ) {
        // Refresh parent window
        window.opener.location.reload();        
    }
    if (window.opener.opener) {
        // Refresh grandparent window
        window.opener.opener.location.reload();
    }
});

function inputSecondRound() {  // 4강진출자들 승패기록 함수
    // 모든 first_round 클래스를 가진 td 요소들에 대해
    const SecondRoundCells = document.querySelectorAll("td.second_round");


let totalAdvancingPlayers = [];  // 두 테이블의 결과를 저장하기 위한 배열

  SecondRoundCells.forEach(cell => {
cell.addEventListener("click", function() {
var level = $("#level").val();
               if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
            const parentTableId = this.closest('table').id;
            const table = this.closest('table');

            // 테이블 ID가 matchlistA 또는 matchlistB가 아닌 경우 함수를 종료
            if (parentTableId !== 'matchlistA' && parentTableId !== 'matchlistB') {
                return;
            }

var  advancingPlayers = [];
var  matchListTable = document.getElementById(parentTableId);
var  rowCount = matchListTable.rows.length;
var  cellIndex = (parentTableId === 'matchlistA') ? 2 : 5 ;  // 예: matchlistB에서는 cells[5]을 사용 (승) 찾음

for(var i = 0; i < rowCount; i++){
if (matchListTable.rows[i].cells[cellIndex]) { // 해당 셀이 존재하는지 확인
// 해당 열에서 '(승)'이 포함된 경우, 직전 열의 값을 추출
if(parentTableId === 'matchlistA')
{   // table matchlistA인 경우
       // 승을 발견했을때 선수이름을 가져오기 위한 좌표지정        
var relatedTdValue = matchListTable.rows[i].cells[0].innerText;
if (relatedTdValue.indexOf('x') === -1 && relatedTdValue.trim() != ''  ) 
advancingPlayers.push({name: relatedTdValue, row: i, col: 1});    
}
if(parentTableId === 'matchlistB')
{   // table matchlistB인 경우
       // 승을 발견했을때 선수이름을 가져오기 위한 좌표지정        
var relatedTdValue = matchListTable.rows[i].cells[5].innerText;                             
if (relatedTdValue.indexOf('x') === -1 && relatedTdValue.trim() != ''  ) 
advancingPlayers.push({name: relatedTdValue, row: i, col: 5});    

}

    }   
        }     

var tableId = $(table).attr('id');
var leftName, rightName;

// console.log('advancingPlayers : ' + advancingPlayers);

// alert('advancingPlayers : ' + inputHidden.value);
// alert('tableId : ' + tableId + clickedRow);
// 각 td요소 클릭에 대한 처리방법  

let rowData1 = advancingPlayers.find(item => item.row === 1);
let rowData2 = advancingPlayers.find(item => item.row === 6);
let rowData3 = advancingPlayers.find(item => item.row === 11);
let rowData4 = advancingPlayers.find(item => item.row === 16);
let rowData5 = advancingPlayers.find(item => item.row === 21);
let rowData6 = advancingPlayers.find(item => item.row === 26);
let rowData7 = advancingPlayers.find(item => item.row === 31);
let rowData8 = advancingPlayers.find(item => item.row === 36);

// 존재하는 rowData 값만을 담을 배열
let validRowData = [rowData1, rowData2, rowData3, rowData4, rowData5, rowData6, rowData7, rowData8].filter(item => item);

           //2명의 미탈락자가 있는 경우에만
   
// 첫 번째와 두 번째 값을 확인
if (validRowData.length >= 1) {
leftName = validRowData[0].name;
clickedRow = validRowData[0].row;     
}

if (validRowData.length >= 2) {
rightName = validRowData[1].name;
 var opponentRow = validRowData[1].row;
}
   

            // alert(leftName);
// hidden input에 값을 저장
var inputHidden = document.createElement("input");
inputHidden.type = "hidden";

            // alert("opponentRow : " + opponentRow);
// leftName과 rightName을 inputHidden의 값으로 설정
if (leftName && rightName) {
inputHidden.value = `Left: ${leftName}, Right: ${rightName}`;
} else if (leftName) {
inputHidden.value = `Left: ${leftName}`;
} else {
inputHidden.value = "No valid data found";  // 또는 다른 적절한 메시지나 값을 할당
}

document.body.appendChild(inputHidden);


// 클릭한 TD와 해당 선수의 좌표, 상대 선수의 좌표를 추출합니다.
console.log("클릭한 TD - 행:", clickedRow );
console.log("상대 선수의 TD - 행:", opponentRow);
 
           // 2명이 존재할때 실행
         if( typeof opponentRow !== 'undefined')
 {

$("#leftname_4").text(leftName) ; 
$("#rightname_4").text(rightName) ;

            var rule = $("#T_rule").val();
            var handy = $("#handy").val();            

// 숫자와 '부' 문자를 추출할 정규식
var regex = /(\d+)부/;
var handy_result = '';

var leftMatch = leftName.match(regex);
var rightMatch = rightName.match(regex);

if (leftMatch && rightMatch) { // 정규식과 일치하는지 확인
var leftpersonHandy = parseInt(leftMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
var rightpersonHandy = parseInt(rightMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
handy_result = Math.abs(leftpersonHandy - rightpersonHandy); // 절댓값으로 결과를 저장
}

if(handy==='2+1' && leftpersonHandy !== rightpersonHandy)
  handy_result += 1;        

// 최대핸디는 6점으로 제한
if(handy_result > 6 ) 
   handy_result = '6 (최대)';  

$("#modalrule_4").text(rule) ;
$("#modalhandy_4").text(handy_result + '점') ;       


var level = $("#level").val();
var user_name = '<?php echo $user_name; ?>';
// level 4이면 이름이 같아야 한다.

console.log(leftName);
console.log(rightName);

 }

if(level === '1' && (leftName!=='' && rightName!=='' && typeof leftName !=='undefined' && typeof rightName !=='undefined' ) )
{
                $("#second_round_Modal").modal("show"); 
}         

        // 점수를 잘못 넣었을때 삭제하는 버튼
        $("#delScoreBtn_4").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var td_cell = tables[tableIndex].getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tables[tableIndex].getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol];

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

td_cell.style.backgroundColor = '';
td_cell.style.border = '2px solid black';        
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '2px solid black';

  // 셀에서 'x' 제거
td_cell.innerHTML = td_cell.innerHTML.replace(' x', '');
OP_td_cell.innerHTML = OP_td_cell.innerHTML.replace(' x', '');

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

// insertTextIntoCell(tableIdForTd, rowIndexForTd, columnForTd, "");
// insertTextIntoCell(tableIdForTd, rowIndexForOP_td, columnForTd, "");

   drawRoundLines() ;
  save();
$("#closeModalBtn_4").click(); // Close the modal
        });   
 
// 8강에서 왼쪽 오른쪽승을 클릭했을때 처리할 부분임  
$(".winBtn_4").off("click").on("click", function () {
var level = $("#level").val();
if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
// 8강 선수들 기록하기
var tables = ['matchlistA', 'matchlistB'];

for (var tableName of tables)
{
var adPlayers = [];
var matchTable = document.getElementById(tableName);
var rowCount = matchTable.rows.length;
var cellIndex = (tableName === 'matchlistA') ? 2 : 5;  // 예: matchlistB에서는 cells[5]을 사용 (승) 찾음


for(var i = 0; i < rowCount; i++){
if (matchTable.rows[i].cells[cellIndex]) { // 해당 셀이 존재하는지 확인
// 해당 열에서 '(승)'이 포함된 경우, 직전 열의 값을 추출
if(tableName === 'matchlistA')
{   // table matchlistA인 경우
   // 승을 발견했을때 선수이름을 가져오기 위한 좌표지정        
var relatedTdValue = matchTable.rows[i].cells[0].innerText;
if (relatedTdValue.indexOf('x') === -1 && relatedTdValue.trim() != ''  ) 
adPlayers.push({name: relatedTdValue, row: i, col: 1});    
}
if(tableName === 'matchlistB')
{   // table matchlistB인 경우
   // 승을 발견했을때 선수이름을 가져오기 위한 좌표지정        
var relatedTdValue = matchTable.rows[i].cells[5].innerText;                             
if (relatedTdValue.indexOf('x') === -1 && relatedTdValue.trim() != ''  ) 
adPlayers.push({name: relatedTdValue, row: i, col: 5});    

}

}   
 }  
   totalAdvancingPlayers.push(...adPlayers);  // 누적된 결과를 전체 배열에 추가
  }


  
  $("#round4").val(encodeURIComponent(JSON.stringify(totalAdvancingPlayers)));



var Parent_td_cell = table.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[0];        
var Right_Parent_td_cell = table.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[5];        

// 8강은 한칸씩 이동되서 (승) 표기됨 Parent개념 도입
var Parent_OP_td_cell = table.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[0];
var Right_Parent_OP_td_cell = table.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[5];

var tableId = $(Parent_td_cell).parent().parent().attr('id');

var side = $(this).data("side");

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(Parent_td_cell).parent().parent().parent().attr('id');
var RightTableId = $(Right_Parent_td_cell).parent().parent().parent().attr('id');

// OP_td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForOpTd = $(Parent_OP_td_cell).parent().parent().parent().attr('id');

console.log('clickedRow ' , clickedRow);
console.log('Parent_td_cell ' , Parent_td_cell);
// alert(Parent_td_cell);
if (Parent_td_cell) {
Parent_td_cell.style.backgroundColor = '';
}
if (Right_Parent_td_cell) 
{    Right_Parent_td_cell.style.backgroundColor = '';
}
if (Parent_OP_td_cell) {
Parent_OP_td_cell.style.backgroundColor = '';
}
if (Right_Parent_OP_td_cell) {
Right_Parent_OP_td_cell.style.backgroundColor = '';
}


          // 상부클릭 행검사
  if(clickedRow < 18 )
  {
if (side === "left") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = '';
Parent_td_cell.style.border = '3px solid blue';        
Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_td_cell.innerHTML = Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;
}
if(RightTableId === 'matchlistB')
{
Right_Parent_td_cell.style.backgroundColor = '';
Right_Parent_td_cell.style.border = '3px solid blue';        
Right_Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_td_cell.innerHTML = Right_Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

// alert("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(tableIdForTd);
let columnForTd = (RightTableId === 'matchlistA') ? 2 : (RightTableId === 'matchlistB' ? 2 : 2);

// 함수 호출 좌측상단 영역 (leftName, rightName) 설정  
setLeftRightName(RightTableId, rowIndexForTd, columnForTd, 1, 2 );   // 절반으로 나뉠때 하단    
                
// insertTextIntoCell(RightTableId, 7, columnForTd, "(승)");  // 3행에 기록 (좌측승리)
// insertTextIntoCell(RightTableId, 27, columnForTd, "");


if (side === "right") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = 'lightgray';
Parent_td_cell.style.border = '2px solid lightgray';
Parent_OP_td_cell.style.backgroundColor = '';
Parent_OP_td_cell.style.border = '3px solid blue';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_td_cell.innerHTML.indexOf('x') === -1) {
Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_OP_td_cell.innerHTML = Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
        // 설정을 matchlistA와 반대로 설정해야 한다.
Right_Parent_OP_td_cell.style.backgroundColor = '';
Right_Parent_OP_td_cell.style.border = '3px solid blue';        
Right_Parent_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_OP_td_cell.innerHTML = Right_Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(Right_Parent_OP_td_cell.innerHTML);
let columnForTd = (RightTableId === 'matchlistA') ? 2 : (RightTableId === 'matchlistB' ? 2 : 2);

// 이름설정  
setLeftRightName(RightTableId, rowIndexForTd, columnForTd, 1, 2 ); // 절반으로 나뉠때 하단   

// insertTextIntoCell(RightTableId, 7, columnForTd, "");
// insertTextIntoCell(RightTableId, 27, columnForTd, "(승)");


}

 // 절반이하 하부행 클릭
   if(clickedRow >= 18 )
    {
if (side === "left") {
  if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = '';
Parent_td_cell.style.border = '3px solid blue';        
Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Parent_OP_td_cell.style.border = '2px solid lightgray';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Parent_OP_td_cell.innerHTML += ' x';
}

// 상대방의 셀에서 'x' 제거
if (Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_td_cell.innerHTML = Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
Right_Parent_td_cell.style.backgroundColor = '';
Right_Parent_td_cell.style.border = '3px solid blue';        
Right_Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_td_cell.innerHTML = Right_Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

let columnForTd = (tableIdForTd === 'matchlistA') ? 3 : (tableIdForTd === 'matchlistB' ? 2 : 2);

// 함수 호출 좌측상단 영역   
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 2 ); // 절반으로 나뉠때 하단    
                
// insertTextIntoCell(tableIdForTd, 7, columnForTd, "(승)");  // 3행에 기록 (좌측승리)
// insertTextIntoCell(tableIdForTd, 27, columnForTd, "");


if (side === "right") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = 'lightgray';
Parent_td_cell.style.border = '2px solid lightgray';
Parent_OP_td_cell.style.backgroundColor = '';
Parent_OP_td_cell.style.border = '3px solid blue';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_td_cell.innerHTML.indexOf('x') === -1) {
Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_OP_td_cell.innerHTML = Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
        // 설정을 matchlistA와 반대로 설정해야 한다.
Right_Parent_OP_td_cell.style.backgroundColor = '';
Right_Parent_OP_td_cell.style.border = '3px solid blue';        
Right_Parent_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_OP_td_cell.innerHTML = Right_Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(tableIdForTd);
let columnForTd = (tableIdForTd === 'matchlistA') ? 3 : (tableIdForTd === 'matchlistB' ? 2 : 2);

// 함수 호출 좌측상단 영역   
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 2 );

// insertTextIntoCell(tableIdForTd, 7, columnForTd, "");
// insertTextIntoCell(tableIdForTd, 27, columnForTd, "(승)");

  } 
}
 

        // 승리처리
// 2라운드 선처리하기
drawRoundLines();
save();
$("#closeModalBtn_4").click(); // Close the modal
        });
    

});
});
}

function inputThirdRound() {  // 결승진출자들 승패기록 함수
    // 모든 first_round 클래스를 가진 td 요소들에 대해
    const thirdRoundCells = document.querySelectorAll("td.third_round");

let totalAdvancingPlayers = [];  // 두 테이블의 결과를 저장하기 위한 배열

    thirdRoundCells.forEach(cell => {
        cell.addEventListener("click", function() {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
            const parentTableId = this.closest('table').id;
            const table = this.closest('table');

            // 테이블 ID가 matchlistA 또는 matchlistB가 아닌 경우 함수를 종료
            if (parentTableId !== 'matchlistA' && parentTableId !== 'matchlistB') {
                return;
            }

let advancingPlayers = [];
const tableIds = [ 'matchlistA', 'matchlistB'];

for (const parentTableId of tableIds) {
let matchListTable = document.getElementById(parentTableId);
if (!matchListTable) continue; // 해당 테이블이 존재하지 않으면 다음 테이블로 넘어갑니다.

let rowCount = matchListTable.rows.length;
let playerNameCellIndex = (parentTableId === 'matchlistA') ? 0 : 5;

for (let i = 0; i < rowCount; i++) {
if (matchListTable.rows[i].cells[playerNameCellIndex]) { // 해당 셀이 존재하는지 확인
let relatedTdValue = matchListTable.rows[i].cells[playerNameCellIndex].innerText;

// if (relatedTdValue.trim() !== '') 
// totalAdvancingPlayers.push({ name: relatedTdValue, row: i, col: playerNameCellIndex });

if (relatedTdValue.indexOf('x') === -1 && relatedTdValue.trim() !== '') {
advancingPlayers.push({ name: relatedTdValue, row: i, col: playerNameCellIndex });
}
}
}
}

 console.log('advancingPlayers',  advancingPlayers  );

var tableId = $(table).attr('id');
let leftName ="" ;
let rightName ="" ;

let rowData1 = advancingPlayers.find(item => item.col === 0);
let rowData2 = advancingPlayers.find(item => item.col === 5);

// 존재하는 rowData 값만을 담을 배열
let validRowData = [rowData1, rowData2].filter(item => item);

           //2명의 미탈락자가 있는 경우에만
   
// 첫 번째와 두 번째 값을 확인
if (validRowData.length >= 1) {
leftName = validRowData[0].name;
clickedRow = validRowData[0].row;     
}

if (validRowData.length >= 2) {
rightName = validRowData[1].name;
 var opponentRow = validRowData[1].row;
}    
            
// hidden input에 값을 저장
var inputHidden = document.createElement("input");
inputHidden.type = "hidden";

            // alert("opponentRow : " + opponentRow);
// leftName과 rightName을 inputHidden의 값으로 설정
if (leftName && rightName) {
inputHidden.value = `Left: ${leftName}, Right: ${rightName}`;
} else if (leftName) {
inputHidden.value = `Left: ${leftName}`;
} else {
inputHidden.value = "No valid data found";  // 또는 다른 적절한 메시지나 값을 할당
}

document.body.appendChild(inputHidden);

// 클릭한 TD와 해당 선수의 좌표, 상대 선수의 좌표를 추출합니다.
console.log("클릭한 TD - 행:", clickedRow );
console.log("상대 선수의 TD - 행:", opponentRow);

         if( typeof opponentRow !== 'undefined' && typeof clickedRow !== 'undefined')
 {
$("#leftname_2").text(leftName) ; 
$("#rightname_2").text(rightName) ;

            var rule = $("#T_rule").val();
            var handy = $("#handy").val();            

// 숫자와 '부' 문자를 추출할 정규식
var regex = /(\d+)부/;
var handy_result = '';

var leftMatch = leftName.match(regex);
var rightMatch = rightName.match(regex);

if (leftMatch && rightMatch) { // 정규식과 일치하는지 확인
var leftpersonHandy = parseInt(leftMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
var rightpersonHandy = parseInt(rightMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
handy_result = Math.abs(leftpersonHandy - rightpersonHandy); // 절댓값으로 결과를 저장
}
if(handy==='2+1' && leftpersonHandy !== rightpersonHandy)
  handy_result += 1;        

// 최대핸디는 6점으로 제한
if(handy_result > 6 ) 
   handy_result = '6 (최대)';  

$("#modalrule_2").text(rule) ;
$("#modalhandy_2").text(handy_result + '점') ;

var level = $("#level").val();
var user_name = '<?php echo $user_name; ?>';
// level 4이면 이름이 같아야 한다.

console.log(leftName);
console.log(rightName);
 }
 
if(level === '1' && (leftName!=='' && rightName!=='' && typeof leftName !=='undefined' && typeof rightName !=='undefined' ) )
{
                $("#third_round_Modal").modal("show"); 
}         

        // 점수를 잘못 넣었을때 삭제하는 버튼
        $("#delScoreBtn_2").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var tableA = document.getElementById('matchlistA'); // matchlistA 테이블에 직접 접근
var tableB = document.getElementById('matchlistB'); // matchlistB 테이블에 직접 접근

var td_cell = tableA.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[0];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tableB.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[5];

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

td_cell.style.backgroundColor = '';
td_cell.style.border = '2px solid black';        
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '2px solid black';

  // 셀에서 'x' 제거
td_cell.innerHTML = td_cell.innerHTML.replace(' x', '') ;
OP_td_cell.innerHTML = OP_td_cell.innerHTML.replace(' x', '') ;

insertTextIntoCell('matchlistA', 17, 3, "");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , ""); // 우측행 공백

   drawRoundLines() ;
  save();
$("#closeModalBtn_2").click(); // Close the modal
        });   
 
// 8강에서 왼쪽 오른쪽승을 클릭했을때 처리할 부분임  
$(".winBtn_2").off("click").on("click", function () {
var level = $("#level").val();
               if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var tableA = document.getElementById('matchlistA'); // matchlistA 테이블에 직접 접근
var tableB = document.getElementById('matchlistB'); // matchlistB 테이블에 직접 접근

var NameValue1 = tableA.rows[clickedRow].cells[0].innerText;
var NameValue2 = tableB.rows[opponentRow].cells[5].innerText;
var Left_td_cell = tableA.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[0];        
var Right_td_cell = tableB.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[5];

var winner = [];

// round2 자료 넣음
totalAdvancingPlayers.push({ name: NameValue1, row: clickedRow, col: 0 });
totalAdvancingPlayers.push({ name: NameValue2, row: opponentRow, col: 5 });

$("#round2").val(encodeURIComponent(JSON.stringify(totalAdvancingPlayers)));

var side = $(this).data("side");

console.log('clickedRow ' , clickedRow);

if (side === "left") {
Left_td_cell.style.backgroundColor = '';
Left_td_cell.style.border = '3px solid blue';        
Right_td_cell.style.backgroundColor = 'lightgray';
Right_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_td_cell.innerHTML.indexOf('x') === -1) {
Right_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Left_td_cell.innerHTML.indexOf('x') !== -1) {
Left_td_cell.innerHTML = Left_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Left_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_td_cell.parentNode.rowIndex;
               
insertTextIntoCell('matchlistA', 17, 3, "(승)");  // 4행에 기록 (좌측승리)
toggleClassInCell('matchlistA', 17, 3, "forth_round");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , ""); // 우측행 공백
toggleClassInCell('matchlistB', 17, 1, "forth_round");  // 4행에 기록 (좌측승리)

        winner.push({ name: NameValue1, row: clickedRow, col: 0 }); 

 }

if (side === "right") {
    Left_td_cell.style.backgroundColor = 'lightgray';
Left_td_cell.style.border = '2px solid lightgray';        
Right_td_cell.style.backgroundColor = '';
Right_td_cell.style.border = '3px solid blue';
// 탈락한 선수의 셀에 'x' 추가
if (Left_td_cell.innerHTML.indexOf('x') === -1) {
Left_td_cell.innerHTML += ' x';

}
// 상대방의 셀에서 'x' 제거
if (Right_td_cell.innerHTML.indexOf('x') !== -1) {
Right_td_cell.innerHTML = Right_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Left_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_td_cell.parentNode.rowIndex;
               
insertTextIntoCell('matchlistA', 17, 3, "");  // 4행에 기록 (좌측 공백)
toggleClassInCell('matchlistA', 17, 3, "forth_round");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , "(승)"); // 우측행 승리
toggleClassInCell('matchlistB', 17, 1, "forth_round");  // 4행에 기록 (좌측승리)

winner.push({ name: NameValue2, row: opponentRow, col: 5 });


}


         $("#round1").val(encodeURIComponent(JSON.stringify(winner)));
 // 절반이하 하부행 클릭
  
            // 승리처리
// 2라운드 선처리하기

            
drawRoundLines();
save();
$("#closeModalBtn_2").click(); // Close the modal
        });
    
   });
});
}

// 우승이 결정된 후 다시 지울경우 대비해서 만드는 함수
function inputForthRound() {  // 결승진출자들 승패기록 함수
    // 모든 first_round 클래스를 가진 td 요소들에 대해
    const forthRoundCells = document.querySelectorAll("td.forth_round");

let totalAdvancingPlayers = [];  // 두 테이블의 결과를 저장하기 위한 배열

    forthRoundCells.forEach(cell => {
        cell.addEventListener("click", function() {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
            const parentTableId = this.closest('table').id;
            const table = this.closest('table');

            // 테이블 ID가 matchlistA 또는 matchlistB가 아닌 경우 함수를 종료
            if (parentTableId !== 'matchlistA' && parentTableId !== 'matchlistB') {
                return;
            }

let advancingPlayers = [];

const tableIds = [ 'matchlistA', 'matchlistB'];

             // 결승오른 사람 추출
             advancingPlayers=  extractSemifinalResults();

 console.log('advancingPlayers',  advancingPlayers  );

let leftName ="" ;
let rightName ="" ;

let rowData1 = advancingPlayers[0];
let rowData2 = advancingPlayers[1];

// 존재하는 rowData 값만을 담을 배열
let validRowData = [rowData1, rowData2].filter(item => item);

console.log('validRowData',  validRowData  );

           //2명의 미탈락자가 있는 경우에만
   
// 첫 번째와 두 번째 값을 확인
if (validRowData.length >= 1) {
leftName = validRowData[0].name;
clickedRow = validRowData[0].row;     
}

if (validRowData.length >= 2) {
rightName = validRowData[1].name;
 var opponentRow = validRowData[1].row;
}    
            
// hidden input에 값을 저장
var inputHidden = document.createElement("input");
inputHidden.type = "hidden";

            // alert("opponentRow : " + opponentRow);
// leftName과 rightName을 inputHidden의 값으로 설정
if (leftName && rightName) {
inputHidden.value = `Left: ${leftName}, Right: ${rightName}`;
} else if (leftName) {
inputHidden.value = `Left: ${leftName}`;
} else {
inputHidden.value = "No valid data found";  // 또는 다른 적절한 메시지나 값을 할당
}

document.body.appendChild(inputHidden);

// 클릭한 TD와 해당 선수의 좌표, 상대 선수의 좌표를 추출합니다.
console.log("클릭한 TD - 행:", clickedRow );
console.log("상대 선수의 TD - 행:", opponentRow);

         if( typeof opponentRow !== 'undefined' && typeof clickedRow !== 'undefined')
 {
$("#leftname_1").text(leftName) ; 
$("#rightname_1").text(rightName) ;

            var rule = $("#T_rule").val();
            var handy = $("#handy").val();            

// 숫자와 '부' 문자를 추출할 정규식
var regex = /(\d+)부/;
var handy_result = '';

var leftMatch = leftName.match(regex);
var rightMatch = rightName.match(regex);

if (leftMatch && rightMatch) { // 정규식과 일치하는지 확인
var leftpersonHandy = parseInt(leftMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
var rightpersonHandy = parseInt(rightMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
handy_result = Math.abs(leftpersonHandy - rightpersonHandy); // 절댓값으로 결과를 저장
}
if(handy==='2+1' && leftpersonHandy !== rightpersonHandy)
  handy_result += 1;        

// 최대핸디는 6점으로 제한
if(handy_result > 6 ) 
   handy_result = '6 (최대)';  

$("#modalrule_1").text(rule) ;
$("#modalhandy_1").text(handy_result + '점') ;

var level = $("#level").val();
var user_name = '<?php echo $user_name; ?>';
// level 4이면 이름이 같아야 한다.

console.log(leftName);
console.log(rightName);
 }
 
if(level === '1' && (leftName!=='' && rightName!=='' && typeof leftName !=='undefined' && typeof rightName !=='undefined' ) )
{
                $("#forth_round_Modal").modal("show"); 
}         

        // 점수를 잘못 넣었을때 삭제하는 버튼
        $("#delScoreBtn_1").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var tableA = document.getElementById('matchlistA'); // matchlistA 테이블에 직접 접근
var tableB = document.getElementById('matchlistB'); // matchlistB 테이블에 직접 접근

var td_cell = tableA.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[0];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tableB.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[5];

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

td_cell.style.backgroundColor = '';
td_cell.style.border = '2px solid black';        
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '2px solid black';

  // 셀에서 'x' 제거
td_cell.innerHTML = td_cell.innerHTML.replace(' x', '') ;
OP_td_cell.innerHTML = OP_td_cell.innerHTML.replace(' x', '') ;

insertTextIntoCell('matchlistA', 17, 3, "");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , ""); // 우측행 공백

   drawRoundLines() ;
  save();
$("#closeModalBtn_1").click(); // Close the modal
        });   
 
// 8강에서 왼쪽 오른쪽승을 클릭했을때 처리할 부분임  
$(".winBtn_1").off("click").on("click", function () {
var level = $("#level").val();
               if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var tableA = document.getElementById('matchlistA'); // matchlistA 테이블에 직접 접근
var tableB = document.getElementById('matchlistB'); // matchlistB 테이블에 직접 접근

var NameValue1 = tableA.rows[clickedRow].cells[0].innerText;
var NameValue2 = tableB.rows[opponentRow].cells[5].innerText;
var Left_td_cell = tableA.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[0];        
var Right_td_cell = tableB.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[5];

var winner = [];

// round2 자료 넣음
totalAdvancingPlayers.push({ name: NameValue1, row: clickedRow, col: 0 });
totalAdvancingPlayers.push({ name: NameValue2, row: opponentRow, col: 5 });

$("#round2").val(encodeURIComponent(JSON.stringify(totalAdvancingPlayers)));

var side = $(this).data("side");

console.log('clickedRow ' , clickedRow);

if (side === "left") {
Left_td_cell.style.backgroundColor = '';
Left_td_cell.style.border = '3px solid blue';        
Right_td_cell.style.backgroundColor = 'lightgray';
Right_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_td_cell.innerHTML.indexOf('x') === -1) {
Right_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Left_td_cell.innerHTML.indexOf('x') !== -1) {
Left_td_cell.innerHTML = Left_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Left_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_td_cell.parentNode.rowIndex;
               
insertTextIntoCell('matchlistA', 17, 3, "(승)");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , ""); // 우측행 공백

        winner.push({ name: NameValue1, row: clickedRow, col: 0 }); 

 }

if (side === "right") {
    Left_td_cell.style.backgroundColor = 'lightgray';
Left_td_cell.style.border = '2px solid lightgray';        
Right_td_cell.style.backgroundColor = '';
Right_td_cell.style.border = '3px solid blue';
// 탈락한 선수의 셀에 'x' 추가
if (Left_td_cell.innerHTML.indexOf('x') === -1) {
Left_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_td_cell.innerHTML.indexOf('x') !== -1) {
Right_td_cell.innerHTML = Right_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Left_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_td_cell.parentNode.rowIndex;
               
insertTextIntoCell('matchlistA', 17, 3, "");  // 4행에 기록 (좌측승리)
insertTextIntoCell('matchlistB', 17, 1 , "(승)"); // 우측행 공백

winner.push({ name: NameValue2, row: opponentRow, col: 5 });


}


         $("#round1").val(encodeURIComponent(JSON.stringify(winner)));
 // 절반이하 하부행 클릭
  
            // 승리처리
// 2라운드 선처리하기
drawRoundLines();             
save();
$("#closeModalBtn_1").click(); // Close the modal
        });
    
   });
});
}

function drawRoundLines() {
    var tables = document.querySelectorAll("table[id^='matchlist']");
    var numberOfColumns = 0; // Initialize number of columns
    
    if (tables.length > 0) {
        var firstTable = tables[0];
        numberOfColumns = firstTable.rows[0].cells.length;
    }
    
    for (var tableIndex = 0; tableIndex < tables.length; tableIndex++) {
        var table = tables[tableIndex];
        var tdElements = table.getElementsByTagName('td');
        var firstRoundArray = [];
        var indicesArray = [];
        
        for (var i = 0; i < tdElements.length; i++) {
            if (tdElements[i].className && tdElements[i].className.indexOf('drop') !== -1) {
                firstRoundArray.push(tdElements[i]);
            }
        }
        
        // Update the border color of td elements without 'x'
        // for (var j = 0; j < firstRoundArray.length; j++) {            
            // firstRoundArray[j].style.borderTop = '3px solid blue';
            // firstRoundArray[j].style.borderBottom = '3px solid blue';
            
            // // Check if the current td element is in the rightmost column
            // var columnIndex = j % numberOfColumns;
            // if (columnIndex === (numberOfColumns - 1)) {
                // firstRoundArray[j].style.borderRight = '1px solid blue';
            // }
        // }
                
        var offset = (tableIndex === 0) ? 1 : -1;

    }

drawLines();
}

function drawLines() {
    // 검사할 테이블 ID들
    var tableIDs = ['matchlistA', 'matchlistB'];

    for (let tableId of tableIDs) {
        var table = document.getElementById(tableId);

// console.log("tableId : " + tableId);

  // for (let i = 0; i < table.rows.length; i++) {
// for (let j = 0; j < table.rows[i].cells.length; j++) {
// let cell = table.rows[i].cells[j];
// console.log(`Cell at row ${i+1}, col ${j+1}: ${cell.textContent}`);
// }
// }

// 1라운드 라인그리기
var rows = [1, 11, 21, 31];

// 각 행에 대해
for (var r of rows)
{
var thick = 3;
var color = "lightgray";
if (tableId === "matchlistA" ) {
changeCellBorder(tableId,  r + 2, 1, thick, thick, 0, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3, 2, 0, thick, 0, 0, color );                        
}
if (tableId === "matchlistB" ) {
changeCellBorder(tableId,  r + 2, 5, thick, 0, 0, thick, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3, 5, 0, 0, 0, thick, color );                        
}
}

    // 1라운드 좌에서 우로 상향선 그리기

// matchlistB 두 대결자의 아래쪽이 승리할 경우 선을 처리함
var rows = [6, 16, 26, 36];

// 각 행에 대해
for (var r of rows)
{

var color= "lightgray";
var thick = 3;
if (tableId === "matchlistA" ) {
changeCellBorder(tableId,  r - 1 , 2, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r  , 2, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r +1    , 2, 0, thick, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
}
if (tableId === "matchlistB" ) {
changeCellBorder(tableId,  r - 1 , 5, 0, 0, 0, thick, color);                        
changeCellBorder(tableId,  r ,     5, 0, 0, 0, thick, color);                        
changeCellBorder(tableId,  r + 1 , 5, 0, 0, thick, thick, color); // row와 topBorder, rightBorder, bottomBorder, leftBorder
}

}

// 2라운드선 그려주기

var rows = [3,  23];

for (var r of rows)
{

var thick = 3 ;
var color = "lightgray"
if (tableId === "matchlistA" ) {
changeCellBorder(tableId,  r + 2,  3, thick, thick, 0, 0, color );  // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3,  3, 0, thick, 0, 0, color );  // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 4,  3, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 5,  2, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 6,  3, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 7,  3, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 8,  3, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 9,  3, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r + 10, 2, 0, thick, 0, 0, color );   // 0열에 셀합침이 있으면 -1이 들어감
changeCellBorder(tableId,  r + 11, 3, 0, thick, thick, 0, color );       

}
if (tableId === "matchlistB" ) {     
changeCellBorder(tableId,  r + 2, 4, thick, 0, 0, thick, color );  // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 4, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 5, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 6, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 7, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 8, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 9, 4, 0, 0, 0, thick, color );                        
changeCellBorder(tableId,  r + 10, 4, 0, 0, 0, thick, color );   // 0열에 셀합침이 있으면 -1이 들어감
changeCellBorder(tableId,  r + 11, 4, 0, 0, thick, thick, color );                     
}
}

 
// 좌측 결승 선그려주기 // 절반에서 상단모양 좌에서 우측 상방향으로 꺾인선
  var rows = [7,  27];  

// 각 행에 대해
for (var r of rows)
{

if (tableId === "matchlistA" ) {
var rr = 7; // r과 같은 형식으로 그려주기 위한 변수선언
var thick = 3 ;
var color = "lightgray" ;
changeCellBorder(tableId,  rr + 2, 4,    thick, thick, 0, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  rr + 3, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 4, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 5, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 6, 3, 0, thick, 0, 0, color );  // 파란색 선이 겹치는 현상 발생                      
changeCellBorder(tableId,  rr + 7, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 8, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 9, 4, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  rr + 10,4, 0, thick, 0, 0, color );  // 0열에 셀합침이 있으면 -1이 들어감

changeCellBorder(tableId,  rr + 11, 3, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 12, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 13, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 14, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 15, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 16, 3, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 17, 5, 0, 0, 0, thick, color );                             
changeCellBorder(tableId,  rr + 18, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 19, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 20, 4, 0, thick, 0, 0, color );                             
changeCellBorder(tableId,  rr + 21, 3, 0, thick, thick, 0, color );  
}

if (tableId === "matchlistB" ) {
var rr = 7; // r과 같은 형식으로 그려주기 위한 변수선언
var thick = 3 ;
var color = "lightgray" ;
changeCellBorder(tableId,  rr + 2, 3,    thick, 0, 0, thick, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  rr + 3, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 4, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 5, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 6, 3,        0, 0, 0, thick, color );  // 파란색 선이 겹치는 현상 발생                      
changeCellBorder(tableId,  rr + 7, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 8, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 9, 3,        0, 0, 0, thick, color );                        
changeCellBorder(tableId,  rr + 10,3,        0, 0, 0, thick, color );  // 0열에 셀합침이 있으면 -1이 들어감

changeCellBorder(tableId,  rr + 11, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 12, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 13, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 14, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 15, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 16, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 17, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 18, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 19, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 20, 3, 0,0,     0, thick, color );                             
changeCellBorder(tableId,  rr + 21, 3, 0,0, thick, thick, color );  
                   
  }

}


// 결승전 선
  var rows = [17];  

// 각 행에 대해
for (var r of rows)
{

if (tableId === "matchlistA" ) 
     {
var thick = 3 ;
var color = "lightgray" ;
changeCellBorder(tableId,  r , 5, 0, 0, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r , 6, 0, 0, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder

    }
  if (tableId === "matchlistB" ) 
{   
var thick = 3 ;
var color = "lightgray" ;
changeCellBorder(tableId,  r , 1, 0, 0, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r , 2, 0, 0, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
}
}


}  // end of each for

    drawWin();

// class 리스너
inputFirstRound();
inputSecondRound(); 
inputThirdRound(); 
inputForthRound(); 

// 랭킹표시
displayRank();

}

// 다음 라운드 진출자 선표시
function drawWin() {
    // 검사할 테이블 ID들
    var tableIDs = ['matchlistA', 'matchlistB'];

    for (let tableId of tableIDs) {
        var table = document.getElementById(tableId);

// 1라운드 라인그리기
var rows = [1, 11, 21, 31];

// 각 행에 대해
for (var r of rows)
{
if (tableId === "matchlistA" ) 
var cell = table.rows[r].cells[0];
if (tableId === "matchlistB" ) 
var cell = table.rows[r].cells[5];
      if (cell.className && cell.className.indexOf('first_round') !== -1 ) {
var thick = 3;
var color = "blue";
if (tableId === "matchlistA" ) {
changeCellBorder(tableId,  r + 2, 1, thick, thick, 0, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3, 2, 0, thick, 0, 0, color );                        
}
if (tableId === "matchlistB" ) {
changeCellBorder(tableId,  r + 2, 5, thick, 0, 0, thick, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
changeCellBorder(tableId,  r + 3, 5, 0, 0, 0, thick, color );                        
}
  }
}

    // 1라운드 좌에서 우로 상향선 그리기

// matchlistB 두 대결자의 아래쪽이 승리할 경우 선을 처리함
var rows = [6, 16, 26, 36];

// 각 행에 대해
for (var r of rows)
{
if (tableId === "matchlistA" ) 
var cell = table.rows[r].cells[0];
if (tableId === "matchlistB" ) 
var cell = table.rows[r].cells[5];
      if (cell.className && cell.className.indexOf('first_round') !== -1 ) {
var thick = 3;
var color = "blue";
if (tableId === "matchlistA" ) {
changeCellBorder(tableId,  r - 1 , 2, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r  , 2, 0, thick, 0, 0, color );                        
changeCellBorder(tableId,  r +1    , 2, 0, thick, thick, 0, color ); // row와 topBorder, rightBorder, bottomBorder, leftBorder
}
if (tableId === "matchlistB" ) {
changeCellBorder(tableId,  r - 1 , 5, 0, 0, 0, thick, color);                        
changeCellBorder(tableId,  r ,     5, 0, 0, 0, thick, color);                        
changeCellBorder(tableId,  r + 1 , 5, 0, 0, thick, thick, color); // row와 topBorder, rightBorder, bottomBorder, leftBorder
}

 }
}

    }  // end of for
}


    
function insertTextIntoCell(tableId, row, col, text) {
    // 주어진 ID를 가진 테이블을 찾습니다
    let table = document.getElementById(tableId);

    if (table) {
        // 특정 셀이 있는지 확인합니다
        if (table.rows[row] && table.rows[row].cells[col]) {
            let cell = table.rows[row].cells[col];
            let currentText = cell.innerText.trim();

            // 해당 셀의 현재 값이 "(승)" 또는 공백일 경우에만 텍스트를 업데이트합니다
            if (currentText === "(승)" || currentText === "") {
                cell.innerText = text;
            }
        } else {
            console.log(`Cell at (${row}, ${col}) not found in the table "${tableId}".`);
        }
    } else {
        console.log(`Table with id "${tableId}" not found.`);
    }
}
// 클래스를 넣어주고 add remove하는 함수
function toggleClassInCell(tableId, row, col, className) {
    // Find the table with the given ID
    let table = document.getElementById(tableId);

    if (table) {
        // Check if the specific cell exists
        if (table.rows[row] && table.rows[row].cells[col]) {
            let cell = table.rows[row].cells[col];
            let currentText = cell.innerText.trim();

            // Update the class of the cell based on its current text
            if (currentText === "(승)" || currentText === "") {
                if (cell.classList.contains(className)) {
                    cell.classList.remove(className);
                } else {
                    cell.classList.add(className);
                }
            }
        } else {
            console.log(`Cell at (${row}, ${col}) not found in the table "${tableId}".`);
        }
    } else {
        console.log(`Table with id "${tableId}" not found.`);
    }
}


function setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, choice, Round) {
// td요소에 left, Rightname 설정

    let table = document.getElementById(tableIdForTd);
    let cell = table.rows[rowIndexForTd].cells[columnForTd];            

    // 클래스 추가
   
    // data 속성 추가
    let leftNameValue = '';
    let rightNameValue = '';
    let count = 0;
  
    switch(choice){        
        case 1:            
            start = 0;
            end = 18;
            break;        
        case 2:       
            start = 19;
            end = 38;
            break;        
    }

if(tableIdForTd ==='matchlistA')
    columnIndex = 0;  
else
columnIndex = 5;  // matchlistB 테이블
  
    let matchlistATable = document.getElementById(tableIdForTd);
  
    for(let i = start; i < end; i++){
        // Add check for rows and cells before accessing them
        if(matchlistATable.rows[i] && matchlistATable.rows[i].cells[columnIndex]){
            let tdValue = matchlistATable.rows[i].cells[columnIndex].innerText;

            if(!tdValue.includes('탈락') && tdValue.trim() != '') {
                if(count === 0){
                    leftNameValue = tdValue;
                    count++;
                }
                else if(count === 1){
                    rightNameValue = tdValue;
                    break;
                }
            }
        }
    }

    // 위의 코드로 얻은 leftNameValue를 data-leftname의 값으로 설정
    cell.setAttribute("data-leftname", leftNameValue);
    // 위의 코드로 얻은 rightNameValue를 data-rightname의 값으로 설정
    cell.setAttribute("data-rightname", rightNameValue);
}

function ClickEvent_16() 
{
    // 16강 클릭
// 각 테이블에 대해 이벤트 핸들러를 설정합니다.
var tables = $("table[id^='matchlist']");

    tables.each(function(tableIndex, table) {
        // Handle click event on td elements with class 'diagonal'
        $(table).on("click", "td.playerscore", function () {
var level = $("#level").val();
             if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var clickedRow = this.parentNode.rowIndex;
var tableId = $(table).attr('id');

console.log('tableIndex : ' + tableIndex);

// 각 td요소 클릭에 대한 처리방법  
 if(clickedRow === 1 || clickedRow === 11  || clickedRow === 21 || clickedRow === 31 )   
  {
clickedRow = this.parentNode.rowIndex;
            var clickedCol = this.cellIndex;  
var opponentRow = clickedRow + 5;
var opponentCol = clickedCol ;
  }
   else
  {
clickedRow = this.parentNode.rowIndex  ;
var clickedCol = this.cellIndex;   
var opponentRow = clickedRow - 5 ;
var opponentCol = clickedCol ;
  }   

// 클릭한 TD와 해당 선수의 좌표, 상대 선수의 좌표를 추출합니다.
console.log("클릭한 TD - 행:", clickedRow, "열:", clickedCol);
console.log("상대 선수의 TD - 행:", opponentRow, "열:", opponentCol);

// 기억한 행과 열의 인덱스와 현재 클릭한 행과 열의 인덱스를 비교하여 동일하면 모달 창을 띄우지 않습니다.
// 현재 클릭한 td와 모달을 띄우기 전에 저장한 td가 같은지 비교하여 모달이 이미 열려있는 경우 닫지 않고 유지하도록 합니다.            

var leftName = $(this).data("leftname"); // Get the corresponding pp_name
var rightName = $(this).data("rightname"); 

$("#leftname").text(leftName) ; 
$("#rightname").text(rightName) ;

            var rule = $("#T_rule").val();
            var handy = $("#handy").val();            

// 숫자와 '부' 문자를 추출할 정규식
var regex = /(\d+)부/;
var handy_result = '';

var leftMatch = leftName.match(regex);
var rightMatch = rightName.match(regex);

if (leftMatch && rightMatch) { // 정규식과 일치하는지 확인
var leftpersonHandy = parseInt(leftMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
var rightpersonHandy = parseInt(rightMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
handy_result = Math.abs(leftpersonHandy - rightpersonHandy); // 절댓값으로 결과를 저장
}

if(handy==='2+1' && leftpersonHandy !== rightpersonHandy)
  handy_result += 1;        

// 최대핸디는 6점으로 제한
if(handy_result > 6 ) 
   handy_result = '6 (최대)';  

$("#modalrule").text(rule) ;
$("#modalhandy").text(handy_result + '점') ;
      


var level = $("#level").val();
var user_name = '<?php echo $user_name; ?>';
// level 4이면 이름이 같아야 한다.

console.log(leftName);
console.log(rightName);

if(level === '1' && (leftName!=='' && rightName!=='' && typeof leftName !=='undefined' && typeof rightName !=='undefined' ) )
{
                $("#scoreModal").modal("show"); 
}         

        // 점수를 잘못 넣었을때 삭제하는 버튼
        $("#delScoreBtn").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var td_cell = tables[tableIndex].getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tables[tableIndex].getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol];

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

td_cell.style.backgroundColor = '';
td_cell.style.border = '2px solid black';        
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '2px solid black';

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

   drawRoundLines() ;
  save();
$("#closeModalBtn").click(); // Close the modal
        });   
 
// 승을 클릭했을때 처리할 부분임  
$(".winBtn").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var td_cell = tables[tableIndex].getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tables[tableIndex].getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol];

var tableId = $(td_cell).parent().parent().attr('id');

var side = $(this).data("side");

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

// OP_td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForOpTd = $(OP_td_cell).parent().parent().parent().attr('id');

 if (clickedRow === 1  || clickedRow === 11 || clickedRow === 21 || clickedRow === 31) {
if (side === "left") {
td_cell.style.backgroundColor = '';
td_cell.style.border = '3px solid blue';        
OP_td_cell.style.backgroundColor = 'lightgray';
OP_td_cell.style.border = '2px solid lightgray';

changeClass(OP_td_cell, td_cell, 'first_round');

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);



// 함수 호출
if (clickedRow === 1  || clickedRow === 11)
     setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 1, 1 );
   else
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 1 );  // 뒷 숫자 1은 1round

} else {
td_cell.style.backgroundColor = 'lightgray';
td_cell.style.border = '2px solid lightgray';
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '3px solid blue';

changeClass(td_cell, OP_td_cell,  'first_round');

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

// 함수 호출
if (clickedRow === 1  || clickedRow === 11)
     setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 1, 1 );
   else
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 1 );

}
} else {
if (side === "left") {
td_cell.style.backgroundColor = 'lightgray';
td_cell.style.border = '2px solid lightgray';
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '3px solid blue';

changeClass(td_cell, OP_td_cell,  'first_round');

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

// 함수 호출
if (clickedRow === 6  || clickedRow === 16)
     setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 1, 1 );
   else
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 1 );

} else {
td_cell.style.backgroundColor = '';
td_cell.style.border = '3px solid blue';
OP_td_cell.style.backgroundColor = 'lightgray';
OP_td_cell.style.border = '2px solid lightgray';

    changeClass(OP_td_cell, td_cell, 'first_round');


  // td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

// 함수 호출
if (clickedRow === 6  || clickedRow === 16)
     setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 1, 1 );
   else
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 1 );

}
}

        // 승리처리
// 1라운드 선처리하기
drawRoundLines() ;
save();
$("#closeModalBtn").click(); // Close the modal
});

        });

    });

}


// 탈락한 선수에서는 'drop' 클래스를 추가한다.
function changeClass(origin_tdcell, change_tdcell, classNameValue) {
origin_tdcell.classList.remove(classNameValue);
origin_tdcell.classList.remove('playerscore');
origin_tdcell.classList.add('drop');

change_tdcell.classList.remove(classNameValue);
change_tdcell.classList.remove('playerscore');
change_tdcell.classList.remove('drop');
change_tdcell.classList.add(classNameValue);
}

function displayRank() {
    // 먼저 데이터를 파싱합니다.
    var encodedData = $("#T_result").val();
    var decode_round = decodeURIComponent(encodedData);

    if (decode_round) {
        var data = JSON.parse(decode_round);

        // '우승' 데이터의 존재를 확인합니다.
        var champion = data.find(entry => entry.round === '우승');
        var finalist1 = data.find(entry => entry.round === '좌측결승');
        var finalist2 = data.find(entry => entry.round === '우측결승');
        
        // 공동 3위를 결정합니다.
        var semifinalists = data.filter(entry => entry.round.endsWith('4강') && (!finalist1 || entry.name !== finalist1.name) && (!finalist2 || entry.name !== finalist2.name));

        if (champion && finalist1 && finalist2 && semifinalists.length >= 2) {
            // 최종 결과 문자열을 생성합니다.
            var resultString = "우승 : " + cleanString(champion.name) +
                ",   준우승 : " + (finalist1.name === champion.name ? cleanString(finalist2.name) : cleanString(finalist1.name)) +
                ",   공동3위 : " + cleanString(semifinalists[0].name) + ", " + cleanString(semifinalists[1].name);

            $("#resultRank").text(resultString);
        }
    }

    // 금요리그 일자기록
    var TitleString = "<?php echo $registedate; ?>" + " , " + "<?php echo $match_name; ?>";
    $("#playTitle").text(TitleString);
}

// 문자열을 정제하는 함수
function cleanString(str) {
    // 조, 숫자+부 및 x 문자열 제거
return str.replace(/^[A-Z]조\d+위\s*|\d+부|\s*x/g, "").trim();
}

function getTextFromTableCell(tableID, row, col) {
    const table = document.getElementById(tableID);
    if (!table) {
        console.error("Table with the given ID not found:", tableID);
        return null;
    }

    const rows = table.getElementsByTagName("tr");
    if (row >= rows.length) {
        console.error("Invalid row index:", row);
        return null;
    }

    const cells = rows[row].getElementsByTagName("td");
    if (col >= cells.length) {
        console.error("Invalid column index:", col);
        return null;
    }

    return cells[col].textContent || cells[col].innerText;
}

function changeCellBorder(tableId, row, col, topBorder, rightBorder, bottomBorder, leftBorder, lineColor) {
    // 주어진 ID를 가진 테이블을 찾습니다
    let table = document.getElementById(tableId);

    if(table) {
        // 특정 셀이 있는지 확인합니다
        if (table.rows[row-1] && table.rows[row-1].cells[col-1]) {
            let cell = table.rows[row-1].cells[col-1];

            // 셀에 고유한 클래스를 추가합니다
            let uniqueClass = `${tableId}-cell-${row}-${col}`;
            cell.classList.add(uniqueClass);

            // 새로운 style 태그를 만듭니다
            let style = document.createElement('style');
            style.type = 'text/css';

            // 동적으로 CSS 규칙을 추가합니다
            let styles = `.${uniqueClass} {`;

            if (topBorder && lineColor) {
                styles += `border-top: ${topBorder}px solid ${lineColor} !important;`;
            }
            if (rightBorder && lineColor) {
                styles += `border-right: ${rightBorder}px solid ${lineColor} !important;`;
            }
            if (bottomBorder && lineColor) {
                styles += `border-bottom: ${bottomBorder}px solid ${lineColor} !important;`;
            }
            if (leftBorder && lineColor) {
                styles += `border-left: ${leftBorder}px solid ${lineColor} !important;`;
            }

            styles += `}`;
            style.innerHTML = styles;

            // style 태그를 문서에 추가합니다
            document.head.appendChild(style);
        } else {
            console.log(`Cell at (${row}, ${col}) not found in the table "${tableId}".`);
        }
    } else {
        console.log(`Table with id "${tableId}" not found.`);
    }
}

function inputCellText(tableId, row, col, inputText) {
    // 주어진 ID를 가진 테이블을 찾습니다
    let table = document.getElementById(tableId);

    if(table) {
        // 특정 셀이 있는지 확인합니다
        if (table.rows[row-1] && table.rows[row-1].cells[col-1]) {
            let cell = table.rows[row-1].cells[col-1];

            // 해당 셀에 텍스트를 삽입합니다
            cell.innerText = inputText;
        } else {
            console.log(`Cell at (${row}, ${col}) not found in the table "${tableId}".`);
        }
    } else {
        console.log(`Table with id "${tableId}" not found.`);
    }
}

function extractQuarterfinalResults() {
    // Retrieve and parse the JSON data from the hidden input
    const savedResults = JSON.parse(decodeURIComponent(document.querySelector('input[name="T_result"]').value));

    // Filter the results for '좌측4강' and '우측4강'
    const quarterfinalResults = savedResults.filter(result => result.round === '좌측4강' || result.round === '우측4강');

    return quarterfinalResults;
}

function extractSemifinalResults() {
    // Retrieve and parse the JSON data from the hidden input
    const savedResults = JSON.parse(decodeURIComponent(document.querySelector('input[name="T_result"]').value));

    // Filter the results for '좌측결승' and '우측결승'
    const semifinalResults = savedResults.filter(result => result.round === '좌측결승' || result.round === '우측결승');

    return semifinalResults;
}

function SaveResult() {
    const matchlistA = document.querySelector('#matchlistA');
    const matchlistB = document.querySelector('#matchlistB');

    let results = [];

    for (const row of matchlistA.rows) {
        // 8강
        if (row.cells[1] && row.cells[1].textContent.includes('(승)')) {
            results.push({
                name: row.cells[0].textContent.trim(),
                round: '좌측8강',
row: row.rowIndex,  // Storing the row index of the winnerRow here too
class: row.cells[0].getAttribute('class') // Storing the class of the td
            });
        }
        // 4강
        if ((row.rowIndex === 3 || row.rowIndex === 13  || row.rowIndex === 23  || row.rowIndex === 33 ) && row.cells[2] && row.cells[2].textContent.includes('(승)')) {
            var winnerRow = row;
            while (winnerRow && !(winnerRow.cells[1] && winnerRow.cells[1].textContent.includes('(승)'))) {
                winnerRow = winnerRow.previousElementSibling;
            }
            if (winnerRow) {
                results.push({
                    name: winnerRow.cells[0].textContent.trim(),
                    round: '좌측4강',
row: winnerRow.rowIndex,  // Storing the row index of the winnerRow here too
 class: winnerRow.cells[0].getAttribute('class') // Storing the class of the td
                });
            }
        }

// 좌측결승 중상부에 존재할 경우
if ((row.rowIndex === 7 || row.rowIndex === 27) && row.cells[2] && row.cells[2].textContent.includes('(승)')) {
    console.log("좌측결승 조건 시작");
    var winnerRow = row;
    while (winnerRow && !(winnerRow.cells[1] && winnerRow.cells[1].textContent.includes('(승)'))) {
        winnerRow = winnerRow.previousElementSibling;
        if (!winnerRow) {
            console.log("winnerRow가 null입니다.");
            break;  // 추가된 부분
        }
    }
    if (winnerRow) {            
        console.log("좌측결승 데이터 추가:", winnerRow.cells[0].textContent.trim());
        results.push({
            name: winnerRow.cells[0].textContent.trim(),
            round: '좌측결승',
row: winnerRow.rowIndex,  // Storing the row index of the winnerRow here too
class: winnerRow.cells[0].getAttribute('class') // Storing the class of the td
        });
    } else {
        console.log("좌측결승 조건 실패");
    }


        
    }
// 우승은 별도처리
    for (const row of matchlistA.rows) {              
// 우승
if ((row.rowIndex === 17) && row.cells[3] && row.cells[3].textContent.includes('(승)')) {
// alert('win');
var champion = results.find(result => result.round === '좌측결승');
if (champion) {
results.push({
name: champion.name,
round: '우승',
row: champion.rowIndex,  // Storing the row index of the winnerRow here too
 class: champion.cells[0].getAttribute('class') // Storing the class of the td
});
}
}
        
    }

    for (const row of matchlistB.rows) {
        // 8강
        if (row.cells[4] && row.cells[4].textContent.includes('(승)')) {
            results.push({
                name: row.cells[5].textContent.trim(),
                round: '우측8강',
row: row.rowIndex  // Storing the row index of the winnerRow here too
            });
        }
        // 4강
        if (row.cells[3] && row.cells[3].textContent.includes('(승)')) {
            let winnerRow = row;
            while (winnerRow && !(winnerRow.cells[4] && winnerRow.cells[4].textContent.includes('(승)'))) {
                winnerRow = winnerRow.previousElementSibling;
            }
            if (winnerRow) {
                results.push({
                    name: winnerRow.cells[5].textContent.trim(),
                    round: '우측4강',
row: winnerRow.rowIndex,  // Storing the row index of the winnerRow here too

                });
            }
        }  

// 우측결승
    
    }

// 우측결승 중상부에 존재할 경우
var conditions = [
{ rowIndex: [7, 3, 1], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [7, 3, 6], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [7, 13, 11], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [7, 13, 16], cellIndex: [2, 3, 4], resultCell: 5 }
];

for (var condition of conditions) {
if (condition.rowIndex.every((rowIdx, idx) => matchlistB.rows[rowIdx].cells[condition.cellIndex[idx]].textContent.includes('(승)'))) {
results.push({
name: matchlistB.rows[condition.rowIndex[2]].cells[condition.resultCell].textContent.trim(),
round: '우측결승',
row: matchlistB.rows[condition.rowIndex[2]].rowIndex  // Storing the row index of the winnerRow here too
});
console.log('우측상단결승 찾음');
}
}
    // 우측 절반이하 부분 
var conditions = [
{ rowIndex: [17, 3, 21], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [17, 3, 26], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [17, 13, 31], cellIndex: [2, 3, 4], resultCell: 5 },
{ rowIndex: [17, 13, 36], cellIndex: [2, 3, 4], resultCell: 5 }
];

for (var condition of conditions) {
if (condition.rowIndex.every((rowIdx, idx) => matchlistB.rows[rowIdx].cells[condition.cellIndex[idx]].textContent.includes('(승)'))) {
results.push({
name: matchlistB.rows[condition.rowIndex[2]].cells[condition.resultCell].textContent.trim(),
round: '우측결승',
row: matchlistB.rows[condition.rowIndex[2]].rowIndex  // Storing the row index of the winnerRow here too
});
console.log('우측상단결승 찾음');
}
}



// 우승은 matchlistB 별도처리
    for (const row of matchlistB.rows) {              
// 우승
if ((row.rowIndex === 17) && row.cells[1] && row.cells[1].textContent.includes('(승)')) {
var champion = results.find(result => result.round === '우측결승');
if (champion) {
results.push({
name: champion.name,
round: '우승',
row: champion.rowIndex  // Storing the row index of the winnerRow here too
});
}

}
        
    }

    // 결과를 input type=hidden에 저장
    document.querySelector('input[name="T_result"]').value = encodeURIComponent(JSON.stringify(results));
}

// table의 좌표를 입력해서 text값 가져오기
function getCellValue(tableId, rowIndex, colIndex) {
    let table = document.getElementById(tableId);
    if (table) {
        let row = table.rows[rowIndex];
        if (row) {
            let cell = row.cells[colIndex];
            if (cell) {
                return cell.textContent || cell.innerText;
            } else {
                console.error(`Cell not found at column index ${colIndex}`);
                return null;
            }
        } else {
            console.error(`Row not found at index ${rowIndex}`);
            return null;
        }
    } else {
        console.error(`Table with ID ${tableId} not found.`);
        return null;
    }
}

// 행열을 찾기 쉽게 add class 삽입
function addClass(tableId) {
 let table = document.getElementById(tableId);

    if (table) {
        // 각 행(row)에 대해서 반복합니다
        for (let i = 0; i < table.rows.length; i++) {
            let row = table.rows[i];

            // 각 셀(cell)에 대해서 반복합니다
            for (let j = 0; j < row.cells.length; j++) {
                let cell = row.cells[j];

                // 셀에 'rc-{row}-{col}' 형식의 클래스를 추가합니다
                cell.classList.add(`rc-${i}-${j}`);

                // 셀에 'title' 속성을 추가하여 행과 열 번호를 표시합니다
                cell.setAttribute('title', `행: ${i }, 열: ${j }`);
            }
        }
    } else {
        console.log(`Table with id "${tableId}" not found.`);
    }
}

function save() {
    var num = $("#num").val();       
    var user_name = $("#user_name").val(); 

// 경기결과 저장
SaveResult();

// Get all the tables
var tables = $("table[id^='matchlist']");
var tableDataArray = [];

tables.each(function(tableIndex, table) {
// Extract data to store and send to the server
var tdElements = $(table).find('td');
var tdDataArray = [];        

for (var i = 0; i < tdElements.length; i++) {
var tdText = tdElements[i].textContent;
var tdClass = tdElements[i].className; // Get class of the td element

// Combine textContent and class name using a format of your choice
// Here, I'm using a format "textContent|className"
tdDataArray.push(tdText + "|" + tdClass);
}

var dataToSend = tdDataArray.join(','); // Separate data with commas
tableDataArray.push(dataToSend);
});

$("#T_table").val(tableDataArray.join(';'));  // Separate each table's data with a semicolon
  
    

    if(Number(num) > 0) 
        $("#mode").val('modify');     
    else
        $("#mode").val('insert');  

// ajax 요청 생성 중복호출 금지
if (ajaxRequest !== null) {
ajaxRequest.abort();
}

   ajaxRequest =  $.ajax({
        url: "process.php",
        type: "post",
        data: $("#board_form").serialize(), 
        dataType:"json",
        success : function( data ){
// 화면에 우승 표시

displayRank();
            // console.log(data);

   // if (opener) {
// opener.location.reload();
// }
// // opener의 opener 리로드 해야 버그가 없다.
// if (window.opener && window.opener.opener) {
// // Do something with window.opener.opener
// window.opener.opener.location.reload(); // 예시로, opener의 opener의 페이지를 새로고침합니다.
// }
        },
        error : function( jqxhr , status , error ){
            console.log( jqxhr , status , error );
        }        
    });
}

$(document).ready(function(){

   // 클릭이벤트 함수      
// console.clear();

$("#closeModalBtn").click(function(){ 
$('#scoreModal').modal('hide');
});
$("#closeModalBtn_8").click(function(){ 
$('#first_round_Modal').modal('hide');
});

$("#closeModalBtn_4").click(function(){ 
$('#second_round_Modal').modal('hide');
});

$("#closeModalBtn_2").click(function(){ 
$('#third_round_Modal').modal('hide');
});

$("#closeModalBtn_1").click(function(){ 
$('#forth_round_Modal').modal('hide');
});


$(".closeBtn").click(function(){    // 저장하고 창닫기
       //  opener.location.reload();
self.close();
 });
 
 
$(".delBtn").click(function(){      // delBtn
var num = $("#num").val();    
var state = $("#state").val();  
var user_name = $("#user_name").val();      

// DATA 삭제버튼 클릭시
Swal.fire({ 
   title: '해당 DATA 삭제', 
   text: " DATA 삭제는 신중하셔야 합니다. '\n 정말 삭제 하시겠습니까?", 
   icon: 'warning', 
   showCancelButton: true, 
   confirmButtonColor: '#3085d6', 
   cancelButtonColor: '#d33', 
   confirmButtonText: '삭제', 
   cancelButtonText: '취소' })
   .then((result) => { if (result.isConfirmed) { 
   
    // 대진표관련 자료 초기화 후 update

       $("#T_table").val('');     
       $("#T_result").val('');     
       $("#mode").val('modify');     
   
$.ajax({
url: "process.php",
type: "post",
data: $("#board_form").serialize(),
dataType:"json",
success : function( data ){
// console.log( data);
if (opener) {
opener.location.reload();
}
setTimeout(function() {         
 window.close();
   }, 1000);
},
error : function( jqxhr , status , error ){
console.log( jqxhr , status , error );
}        
   });
   
   } });    
  

 });   
   
fillTDElementsWithData();

//클릭이벤트 등록
ClickEvent_16();
drawRoundLines() ;

    displayRank();
// 우승문구 넣음
// inputCellText("matchlistA", 18, 5, "(우");
// inputCellText("matchlistB", 18, 1, "승)");


// 행과열을 나타내는 class 강제로 만듬
 addClass('matchlistA');
 addClass('matchlistB');

});
  
function fillTDElementsWithData() {
    var data = $("#T_table").val();
    
    if (data !== null) {
        var tableDataArray = data.split(';');
        var tables = document.querySelectorAll("table[id^='matchlist']");
        
        tables.forEach(function(table, tableIndex) {
var tableData = tableDataArray[tableIndex];
   if (tableData !== undefined && tableData !== '') {
var cellDataArray = tableData.split(',');
var tdElements = table.getElementsByTagName('td');

Array.from(tdElements).forEach(function(td, i) {
var cellDataParts = cellDataArray[i].split('|');
var cellText = cellDataParts[0];
var cellClass = cellDataParts[1];

td.textContent = cellText;
td.className = cellClass;

if (cellClass.indexOf('drop') !== -1) {
td.style.backgroundColor = 'lightgray';
td.style.border = 'lightgray';
} else if (cellClass.indexOf('first_round') !== -1) {
td.style.backgroundColor = '';
td.style.border = '3px solid blue';
}
});
}

        });
    } else {       

        var tablesName = ["matchlistA", "matchlistB"];
        
        tablesName.forEach(function(tableId) {
            var table = document.getElementById(tableId);
            
            if (!table) {
                console.warn(`Table with id ${tableId} does not exist.`);
                return;
            }
            
            var trElements = table.getElementsByTagName('tr');
            
            trElements.forEach(function(tr, i) {
                var cells = tr.cells;
                
                if (tableId === "matchlistA" && cells.length > 1 && cells[0].textContent.trim() === 'x') {
                    if (i % 5 === 2 && trElements[i + 5] && trElements[i + 5].cells.length > 1) {
                        trElements[i + 5].cells[1].textContent = '(승)';
                    } else if (trElements[i - 5] && trElements[i - 5].cells.length > 1) {
                        trElements[i - 5].cells[1].textContent = '(승)';
                    }
                } else if (tableId === "matchlistB" && cells.length > 5 && cells[5].textContent.trim() === 'x') {
                    if (i % 5 === 2 && trElements[i + 5] && trElements[i + 5].cells.length > 4) {
                        trElements[i + 5].cells[4].textContent = '(승)';
                    } else if (trElements[i - 5] && trElements[i - 5].cells.length > 4) {
                        trElements[i - 5].cells[4].textContent = '(승)';
                    }
                }
            });
        });
    }
}



function inputFirstRound() {  // 8강진출자들 승패기록 함수
    
    const firstRoundCells = document.querySelectorAll("td.first_round");

let totalAdvancingPlayers = [];  // 두 테이블의 결과를 저장하기 위한 배열

firstRoundCells.forEach(cell => {
cell.addEventListener("click", function() {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
// 8강 선수들 기록하기
tables = ['matchlistA', 'matchlistB'];

for (var tableName of tables)
{
var adPlayers = [];
var matchTable = document.getElementById(tableName);
var rowCount = matchTable.rows.length;
  
// 초기 배열
var firstRoundData = [];

// matchlistA 테이블의 'first_round' 클래스를 가진 td 요소에서 데이터 추출하여 배열에 저장
$('#matchlistA td.first_round').each(function(index, element) {
var playerName = $(element).text().trim();
var trIndex = $(element).closest('tr').index(); // tr의 index 가져오기
firstRoundData.push({ part: 'A', name: playerName, index: index,  row: trIndex });
});
// matchlistB 테이블의 'first_round' 클래스를 가진 td 요소에서 데이터 추출하여 배열에 저장
$('#matchlistB td.first_round').each(function(index, element) {
var playerName = $(element).text().trim();
var trIndex = $(element).closest('tr').index(); // tr의 index 가져오기
firstRoundData.push({ part: 'B', name: playerName, index: index,  row: trIndex });
});


// console.log(firstRoundData);

// 데이터 출력
if (firstRoundData.length > 0) {
var output = '';
firstRoundData.forEach(function(data) {
output += `Part: ${data.part} ,Name: ${data.name}, Index : ${data.index}, Row: ${data.row}<br>`;
});
$('#output').html(output);
} else {
$('#output').html('No data found for this row.');
}

$("#playresult").val(encodeURIComponent(JSON.stringify(firstRoundData)));
  

            const parentTableId = this.closest('table').id;
            const table = this.closest('table');

            // 테이블 ID가 matchlistA 또는 matchlistB가 아닌 경우 함수를 종료
            if (parentTableId !== 'matchlistA' && parentTableId !== 'matchlistB') {
                return;
            }

var clickedRow = this.parentNode.rowIndex;
var tableId = $(table).attr('id');

let leftName, rightName;

 if(clickedRow === 1 || clickedRow === 6  || clickedRow === 11  || clickedRow === 16 )   
  {

var clickedCol = this.cellIndex;  
var opponentCol = clickedCol ;

let validRowData = firstRoundData.filter(item => item.row === 0 || item.row === 5 || item.row === 10 || item.row === 15);

// 첫 번째와 두 번째 값을 확인
if (validRowData.length >= 1) {
leftName = validRowData[0].name;
clickedRow = validRowData[0].row;     
}

if (validRowData.length >= 2) {
rightName = validRowData[1].name;
var opponentRow = validRowData[1].row;
}

            // alert(leftName);
// hidden input에 값을 저장
const inputHidden = document.createElement("input");
inputHidden.type = "hidden";

            // alert("opponentRow : " + opponentRow);
// leftName과 rightName을 inputHidden의 값으로 설정
if (leftName && rightName) {
inputHidden.value = `Left: ${leftName}, Right: ${rightName}`;
} else if (leftName) {
inputHidden.value = `Left: ${leftName}`;
} else {
inputHidden.value = "No valid data found";  // 또는 다른 적절한 메시지나 값을 할당
}

document.body.appendChild(inputHidden);

  }
   if(clickedRow === 21 || clickedRow === 26  || clickedRow === 31  || clickedRow === 36 )
  {
            var clickedCol = this.cellIndex;  
var opponentCol = clickedCol ;

let rowData1 = advancingPlayers.find(item => item.row === 21);
let rowData2 = advancingPlayers.find(item => item.row === 26);
let rowData3 = advancingPlayers.find(item => item.row === 31);
let rowData4 = advancingPlayers.find(item => item.row === 36);

// 존재하는 rowData 값만을 담을 배열
let validRowData = [rowData1, rowData2, rowData3, rowData4].filter(item => item);

// 첫 번째와 두 번째 값을 확인
if (validRowData.length >= 1) {
leftName = validRowData[0].name;
clickedRow = validRowData[0].row;     
}

if (validRowData.length >= 2) {
rightName = validRowData[1].name;
 var opponentRow = validRowData[1].row;
}

            // alert(leftName);
// hidden input에 값을 저장
const inputHidden = document.createElement("input");
inputHidden.type = "hidden";

// leftName과 rightName을 inputHidden의 값으로 설정
if (leftName && rightName) {
inputHidden.value = `Left: ${leftName}, Right: ${rightName}`;
} else if (leftName) {
inputHidden.value = `Left: ${leftName}`;
} else {
inputHidden.value = "No valid data found";  // 또는 다른 적절한 메시지나 값을 할당
}
document.body.appendChild(inputHidden);

  }   

// 클릭한 TD와 해당 선수의 좌표, 상대 선수의 좌표를 추출합니다.
console.log("클릭한 TD - 행:", clickedRow, "열:", clickedCol);
console.log("상대 선수의 TD - 행:", opponentRow, "열:", opponentCol);

$("#leftname_8").text(leftName) ; 
$("#rightname_8").text(rightName) ;

            var rule = $("#T_rule").val();
            var handy = $("#handy").val();            

// 숫자와 '부' 문자를 추출할 정규식
var regex = /(\d+)부/;
var handy_result = '';

var leftMatch = leftName.match(regex);
var rightMatch = rightName.match(regex);

if (leftMatch && rightMatch) { // 정규식과 일치하는지 확인
var leftpersonHandy = parseInt(leftMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
var rightpersonHandy = parseInt(rightMatch[1], 10); // 첫 번째 캡처 그룹에서 숫자 추출
handy_result = Math.abs(leftpersonHandy - rightpersonHandy); // 절댓값으로 결과를 저장
}

if(handy==='2+1' && leftpersonHandy !== rightpersonHandy)
  handy_result += 1;        

// 최대핸디는 6점으로 제한
if(handy_result > 6 ) 
   handy_result = '6 (최대)';  

$("#modalrule_8").text(rule) ;
$("#modalhandy_8").text(handy_result + '점') ;       


var level = $("#level").val();
var user_name = $("#user_name").val();
// level 4이면 이름이 같아야 한다.

console.log(leftName);
console.log(rightName);

if(level === '1' && (leftName!=='' && rightName!=='' && typeof leftName !=='undefined' && typeof rightName !=='undefined' ) )
{
                $("#first_round_Modal").modal("show"); 
}         

}
        // 점수를 잘못 넣었을때 삭제하는 버튼
        $("#delScoreBtn_8").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
var td_cell = tables[tableIndex].getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol-1];        
// 상대방의 셀을 색칠한다.
var OP_td_cell = tables[tableIndex].getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol+1];

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(td_cell).parent().parent().parent().attr('id');

td_cell.style.backgroundColor = '';
td_cell.style.border = '2px solid black';        
OP_td_cell.style.backgroundColor = '';
OP_td_cell.style.border = '2px solid black';

  // 셀에서 'x' 제거
td_cell.innerHTML = td_cell.innerHTML.replace(' x', '');
OP_td_cell.innerHTML = OP_td_cell.innerHTML.replace(' x', '');

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = td_cell.parentNode.rowIndex;
var rowIndexForOP_td = OP_td_cell.parentNode.rowIndex;

// tableIdForTd 값에 따라 column 값을 설정합니다
let columnForTd = (tableIdForTd === 'matchlistA') ? 1 : (tableIdForTd === 'matchlistB' ? 4 : 1);

// insertTextIntoCell(tableIdForTd, rowIndexForTd, columnForTd, "");
// insertTextIntoCell(tableIdForTd, rowIndexForOP_td, columnForTd, "");

   drawRoundLines() ;
  save();
$("#closeModalBtn_8").click(); // Close the modal
        });   
 
// 8강에서 왼쪽 오른쪽승을 클릭했을때 처리할 부분임  
$(".winBtn_8").off("click").on("click", function () {
var level = $("#level").val();
  if (level !== '1') return; // level이 1이 아닌 경우 함수 종료
  
var td_cell = table.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol];        
// 8강은 한칸씩 이동되서 (승) 표기됨 Parent개념 도입
var Parent_td_cell = table.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol-1];        
var Right_Parent_td_cell = table.getElementsByTagName("tr")[clickedRow].getElementsByTagName("td")[clickedCol+1];        

// 8강은 한칸씩 이동되서 (승) 표기됨 Parent개념 도입
var OP_td_cell = table.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol];
var Parent_OP_td_cell = table.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol-1];
var Right_Parent_OP_td_cell = table.getElementsByTagName("tr")[opponentRow].getElementsByTagName("td")[opponentCol+1];

var tableId = $(Parent_td_cell).parent().parent().attr('id');

var side = $(this).data("side");

// td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForTd = $(Parent_td_cell).parent().parent().parent().attr('id');
var RightTableId = $(Right_Parent_td_cell).parent().parent().parent().attr('id');

// OP_td_cell이 포함된 테이블의 id를 얻습니다
var tableIdForOpTd = $(Parent_OP_td_cell).parent().parent().parent().attr('id');

console.log('clickedRow ' , clickedRow);
console.log('Parent_td_cell ' , Parent_td_cell);

// console.log("Table id for td_cell: " + tableIdForTd);
// console.log("Table id for OP_td_cell: " + tableIdForOpTd);

          // 상부클릭 행검사
  if(clickedRow === 1 || clickedRow === 6  || clickedRow === 11  || clickedRow === 16 )
  {
if (side === "left") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = '';
Parent_td_cell.style.border = '3px solid blue';        
Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_td_cell.innerHTML = Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;
}
if(RightTableId === 'matchlistB')
{
Right_Parent_td_cell.style.backgroundColor = '';
Right_Parent_td_cell.style.border = '3px solid blue';        
Right_Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_td_cell.innerHTML = Right_Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

// alert("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(tableIdForTd);
let columnForTd = (RightTableId === 'matchlistA') ? 2 : (RightTableId === 'matchlistB' ? 3 : 2);

// 함수 호출 좌측상단 영역 (leftName, rightName) 설정  
setLeftRightName(RightTableId, rowIndexForTd, columnForTd, 1, 2 );   // 절반으로 나뉠때 하단 2는 2round 8강의미    
                
// insertTextIntoCell(RightTableId, 3, columnForTd, "(승)");  // 3행에 기록 (좌측승리)
// insertTextIntoCell(RightTableId, 13, columnForTd, "");


if (side === "right") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = 'lightgray';
Parent_td_cell.style.border = '2px solid lightgray';
Parent_OP_td_cell.style.backgroundColor = '';
Parent_OP_td_cell.style.border = '3px solid blue';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_td_cell.innerHTML.indexOf('x') === -1) {
Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_OP_td_cell.innerHTML = Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
        // 설정을 matchlistA와 반대로 설정해야 한다.
Right_Parent_OP_td_cell.style.backgroundColor = '';
Right_Parent_OP_td_cell.style.border = '3px solid blue';        
Right_Parent_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_OP_td_cell.innerHTML = Right_Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(Right_Parent_OP_td_cell.innerHTML);
let columnForTd = (RightTableId === 'matchlistA') ? 2 : (RightTableId === 'matchlistB' ? 3 : 2);

// 이름설정  
setLeftRightName(RightTableId, rowIndexForTd, columnForTd, 1, 2); // 절반으로 나뉠때 하단   

// insertTextIntoCell(RightTableId, 3, columnForTd, "");
// insertTextIntoCell(RightTableId, 13, columnForTd, "(승)");


}

 // 절반이하 하부행 클릭
   if(clickedRow === 21 || clickedRow === 26  || clickedRow === 31  || clickedRow === 36 )
    {
if (side === "left") {
  if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = '';
Parent_td_cell.style.border = '3px solid blue';        
Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Parent_OP_td_cell.style.border = '2px solid lightgray';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Parent_OP_td_cell.innerHTML += ' x';
}

// 상대방의 셀에서 'x' 제거
if (Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_td_cell.innerHTML = Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
Right_Parent_td_cell.style.backgroundColor = '';
Right_Parent_td_cell.style.border = '3px solid blue';        
Right_Parent_OP_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_OP_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_OP_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_td_cell.innerHTML = Right_Parent_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

let columnForTd = (tableIdForTd === 'matchlistA') ? 2 : (tableIdForTd === 'matchlistB' ? 3 : 2);

// 함수 호출 좌측상단 영역   
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 2 ); // 절반으로 나뉠때 하단    
                
// insertTextIntoCell(tableIdForTd, 23, columnForTd, "(승)");  // 3행에 기록 (좌측승리)
// insertTextIntoCell(tableIdForTd, 33, columnForTd, "");


if (side === "right") {
if(tableIdForTd === 'matchlistA')
{
Parent_td_cell.style.backgroundColor = 'lightgray';
Parent_td_cell.style.border = '2px solid lightgray';
Parent_OP_td_cell.style.backgroundColor = '';
Parent_OP_td_cell.style.border = '3px solid blue';

// 탈락한 선수의 셀에 'x' 추가
if (Parent_td_cell.innerHTML.indexOf('x') === -1) {
Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Parent_OP_td_cell.innerHTML = Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Parent_OP_td_cell.parentNode.rowIndex;

}
if(RightTableId === 'matchlistB')
{
        // 설정을 matchlistA와 반대로 설정해야 한다.
Right_Parent_OP_td_cell.style.backgroundColor = '';
Right_Parent_OP_td_cell.style.border = '3px solid blue';        
Right_Parent_td_cell.style.backgroundColor = 'lightgray';
Right_Parent_td_cell.style.border = '2px solid lightgray';
// 탈락한 선수의 셀에 'x' 추가
if (Right_Parent_td_cell.innerHTML.indexOf('x') === -1) {
Right_Parent_td_cell.innerHTML += ' x';
}
// 상대방의 셀에서 'x' 제거
if (Right_Parent_OP_td_cell.innerHTML.indexOf('x') !== -1) {
Right_Parent_OP_td_cell.innerHTML = Right_Parent_OP_td_cell.innerHTML.replace(' x', '');
}

// td_cell이 있는 행의 인덱스를 얻습니다
var rowIndexForTd = Right_Parent_td_cell.parentNode.rowIndex;
var rowIndexForOP_td = Right_Parent_OP_td_cell.parentNode.rowIndex;
}

console.log("Row index for td_cell: " + rowIndexForTd);
// tableIdForTd 값에 따라 column 값을 설정합니다
// alert(tableIdForTd);
let columnForTd = (tableIdForTd === 'matchlistA') ? 2 : (tableIdForTd === 'matchlistB' ? 3 : 2);

// 함수 호출 좌측상단 영역   
setLeftRightName(tableIdForTd, rowIndexForTd, columnForTd, 2, 2 );  // 마지막의 2는 2라운드

// insertTextIntoCell(tableIdForTd, 23, columnForTd, "");
// insertTextIntoCell(tableIdForTd, 33, columnForTd, "(승)");


}


        // 승리처리
// 1라운드 선처리하기
drawRoundLines() ;
save();
$("#closeModalBtn_8").click(); // Close the modal
        });  
});
});
}


</script>


반응형
댓글