
  // Get all rows with class "row"
  var rows = document.querySelectorAll(".row");

  // Default state: Hide all rows except the one with id "general1"
  rows.forEach(function (row) {
    if (row.id !== "general1") {
      row.style.display = "none";
      removeRequired(row);
    } else {
      setRequired(row);
    }
  });
 

  // Add change event listener to the dropdown
  var staffSelect = document.getElementById("staff_select");
  staffSelect.addEventListener("change", function () {
    showRows();
    getAssessmentValues(); // Call updateTotalScore whenever the dropdown changes
});

function showRows() {
  var selectedValue = document.getElementById("staff_select").value;

  // Hide all general rows and remove required attribute
  var generalRows = document.querySelectorAll("[id^='general']");
  generalRows.forEach(function(row) {
    row.style.display = "none";
    removeRequired(row);
  });

  // Hide specific sections initially
  var sections = [
    "academic_and_non_academic_1",
    "tb",
    "academic_and_non_academic_2",
    "academic",
    "management_staff",
    "preliminary",
    "annual_performance",
    "junior1",
    "junior2",
    "junior_1",
    "junior_2"
  ];
  sections.forEach(function(id) {
    document.getElementById(id).style.display = "none";
  });

  if (selectedValue) {
    // Show all general rows and set required attribute
    generalRows.forEach(function(row) {
      row.style.display = "block";
      setRequired(row);
    });

    switch (selectedValue) {
      case "Senior Non Academic":
        document.getElementById("academic_and_non_academic_1").style.display = "block";
        document.getElementById("tb").style.display = "block";
        document.getElementById("academic_and_non_academic_2").style.display = "block";
        break;

      case "Senior Academic":
        document.getElementById("tb").style.display = "block";
        document.getElementById("academic").style.display = "block";
        document.getElementById("academic_and_non_academic_2").style.display = "block";
        break;

      case "Management Staff":
        document.getElementById("preliminary").style.display = "block";
        document.getElementById("management_staff").style.display = "block";
        document.getElementById("academic").style.display = "block";
        document.getElementById("junior1").style.display = "none";
        document.getElementById("junior2").style.display = "none";
        document.getElementById("junior_1").style.display = "block";
        document.getElementById("junior_2").style.display = "block";
        break;

      case "Management Staff Non":
        document.getElementById("preliminary").style.display = "block";
        document.getElementById("management_staff").style.display = "block";
        document.getElementById("academic_and_non_academic_1").style.display = "block";
        document.getElementById("junior1").style.display = "none";
        document.getElementById("junior2").style.display = "none";
        document.getElementById("junior_1").style.display = "block";
        document.getElementById("junior_2").style.display = "block";
        break;

      case "Annual Performance":
        document.getElementById("preliminary").style.display = "block";
        document.getElementById("annual_performance").style.display = "block";
        document.getElementById("junior1").style.display = "block";
        document.getElementById("junior2").style.display = "block";
        document.getElementById("junior_1").style.display = "none";
        document.getElementById("junior_2").style.display = "none";
        break;

      default:
        break;
    }
  }
}

function nill(row) {
  if (row.id !== "checkbox-container") {
    var inputs = row.querySelectorAll("input, textarea");
    inputs.forEach(function (input) {
      if (input.type !== "checkbox") {
        input.setAttribute("required", "");
        input.value='nill';
        // textarea.innerHTML='nill'
      }
    });
  }
}


function setRequired(row) {
  if (row.id !== "checkbox-container") {
    var inputs = row.querySelectorAll("input, textarea");
    inputs.forEach(function (input) {
      if (input.type !== "checkbox") {
        input.setAttribute("required", "");
      }
    });
  }
}

function removeRequired(row) {
  if (row.id !== "checkbox-container") {
    var inputs = row.querySelectorAll("input, textarea");
    inputs.forEach(function (input) {
      if (input.type !== "checkbox") {
        input.removeAttribute("required");
      }
    });
  }
}





var count = 2;
var limits = 500;

var count_dev_plan = 2;
var limits_dev_plan = 500;

var totalScore = 5;

("use strict");

function displaySelectedValue(selectElement) {
  var selectedValue = selectElement.value;
  var valueDisplay = selectElement
    .closest("tr")
    .querySelector('input[id^="valueDisplay_"]');
  valueDisplay.value = selectedValue;
  calculateTotalScore();
}

function calculateTotalScore() {
  var totalSelectedValues = 0;
  var allSelects = document.querySelectorAll('select[name="rating[]"]');
  allSelects.forEach(function (select) {
    totalSelectedValues += parseInt(select.value);
  });

  var totalScore = allSelects.length * 5;
  var finalScore = (totalSelectedValues * 100) / totalScore;
  document.getElementById("totalScore").value = finalScore.toFixed(2);
  getAssessmentValues();
}

function add_major_strength(item) {
  var t =
      '<td><textarea class="form-control" name="major_strength[]" rows="2" placeholder="" ></textarea></td>' +
      '<td class=""><input type="text"  class="form-control" name="major_strenght_effect[]" placeholder=""   min="0"/></td>' +
      '<td> <a  id="add_major_strength" class="btn btn-info btn-sm" name="add-invoice-item" onClick="add_major_strength(' +
      item +
      ')"><i class="fa fa-plus-square" aria-hidden="true"></i></a> <a class="btn btn-danger btn-sm"  value="" onclick="deleteRow(this)" ><i class="fa fa-trash" aria-hidden="true"></i></a></td>';
  count == limits ? alert("You have reached the limit of adding " + count + " inputs") : $("tbody#" + item).append(
      "<tr>" + t + "</tr>");
  count++;


}

function add_major_weakness(item) {
  var t =
      '<td><textarea class="form-control" name="major_weakness[]" rows="2" placeholder=""></textarea></td>' +
      '<td class=""><input type="text"  class="form-control" name="major_weakness_correction" placeholder=""   min="0"/></td>' +
      '<td> <a  id="add_major_weakness" class="btn btn-info btn-sm" name="add-invoice-item" onClick="add_major_weakness(' +
      item +
      ')"><i class="fa fa-plus-square" aria-hidden="true"></i></a> <a class="btn btn-danger btn-sm"  value="" onclick="deleteRow(this)" ><i class="fa fa-trash" aria-hidden="true"></i></a></td>';
  count == limits ? alert("You have reached the limit of adding " + count + " inputs") : $("tbody#" + item).append(
      "<tr>" + t + "</tr>");
  count++;


}


function add_key_goals() {
  var count = document.querySelectorAll('select[id^="rating_"]').length + 1;
  var newId = `rating_${count}`;
  var valueDisplayId = `valueDisplay_${count}`;
  var t = `
                <tr>
                    <td><textarea class="form-control" name="key_goals[]" id="description" rows="2" placeholder=""  required></textarea></td>
                    <td>
                        <select id="${newId}" name="rating[]" class="form-control" aria-describedby="basic-addon1" onchange="displaySelectedValue(this)">
                            <option value="" disabled selected>Select Rating</option>
                            <option value="1">POOR</option>
                            <option value="2">FAIR</option>
                            <option value="3">GOOD</option>
                            <option value="4">VERY GOOD</option>
                            <option value="5">EXCELLENT</option>
                        </select>
                    </td>
                    <td><span>Score: </span><input type="text" id="${valueDisplayId}" name="key_goals_score[]" style="border:0px; width: 45px;" value="" readonly></input></td>
                    <td width="100">
                        <a class="btn btn-info btn-sm" name="add-invoice-item" onClick="add_key_goals()" >
                            <i class="fa fa-plus-square" aria-hidden="true"></i>
                        </a>
                        <a class="btn btn-danger btn-sm" value="" onclick="deleteRow(this)" >
                            <i class="fa fa-trash" aria-hidden="true"></i>
                        </a>
                    </td>
                </tr>
            `;
  document.getElementById("key_goals_item").insertAdjacentHTML("beforeend", t);
  calculateTotalScore();
}

("use strict");
function add_exp_teaching() {
  var newRow =
    "<tr>" +
    '<td><textarea name="exp_institutions[]" class="form-control" rows="1" placeholder="" required></textarea></td>' +
    '<td><input type="text" name="exp_designation[]" class="form-control" required></td>' +
    '<td><input type="text" name="exp_specialization[]" class="form-control" required></td>' +
    '<td><input type="text" name="exp_subject[]" class="form-control" required></td>' +
    '<td><input type="text" name="exp_date[]" class="form-control datepicker" required></td>' +
    "<td>" +
    '<a class="btn btn-info btn-sm" name="add-invoice-item" onClick="add_exp_teaching()"><i class="fa fa-plus-square" aria-hidden="true"></i></a>' +
    '<a class="btn btn-danger btn-sm" value="delete" onclick="deleteRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></a>' +
    "</td>" +
    "</tr>";

  $("tbody#add_exp_teaching").append(newRow);

  $(".datepicker").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });
}

("use strict");
function exp_professional() {
  var newRow =
    "<tr>" +
    '<td><textarea name="exp_institutions[]" class="form-control" rows="1" placeholder="" required></textarea></td>' +
    '<td><input type="text" name="exp_designation[]" class="form-control" required></td>' +
    '<td><textarea name="exp_duty[]" class="form-control" rows="2" required></textarea></td>' +
    '<td><input type="text" name="exp_subject[]" class="form-control" required></td>' +
    '<td><input type="text" name="exp_date_start[]" class="form-control datepicker" required></td>' +
    '<td><input type="text" name="exp_date_end[]" class="form-control datepicker" required></td>' +
    "<td>" +
    '<a class="btn btn-info btn-sm" name="add-invoice-item" onClick="exp_professional()"><i class="fa fa-plus-square" aria-hidden="true"></i></a>' +
    '<a class="btn btn-danger btn-sm" value="delete" onclick="deleteRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></a>' +
    "</td>" +
    "</tr>";

  $("tbody#exp_professional").append(newRow);

  $(".datepicker").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });
}

("use strict");
function exp_research() {
  var newRow =
    "<tr>" +
    '<td><textarea name="exp_researh_topic[]" class="form-control" rows="2" placeholder="" required></textarea></td>' +
    '<td><input type="text" name="exp_researh_date[]" class="form-control datepicker" required></td>' +
    "<td>" +
    '<a class="btn btn-info btn-sm" name="add-invoice-item" onClick="exp_research()"><i class="fa fa-plus-square" aria-hidden="true"></i></a>' +
    '<a class="btn btn-danger btn-sm" value="delete" onclick="deleteRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></a>' +
    "</td>" +
    "</tr>";

  $("tbody#exp_research").append(newRow);

  $(".datepicker").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });
}

("use strict");
function exp_research_unpublish() {
  var newRow =
    "<tr>" +
    '<td><textarea name="exp_unpublish_topic[]" class="form-control" rows="2" placeholder="" required></textarea></td>' +
    '<td><textarea name="exp_unpublish_read[]" class="form-control" rows="2" placeholder="" required></textarea></td>' +
    '<td><input type="text" name="exp_unpublish_date[]" class="form-control datepicker" required></td>' +
    "<td>" +
    '<a class="btn btn-info btn-sm" name="add-invoice-item" onClick="exp_research_unpublish()"><i class="fa fa-plus-square" aria-hidden="true"></i></a>' +
    '<a class="btn btn-danger btn-sm" value="delete" onclick="deleteRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></a>' +
    "</td>" +
    "</tr>";

  $("tbody#exp_research_unpublish").append(newRow);

  $(".datepicker").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });
}

("use strict");
function key_duties_res() {
  var newRow =
    "<tr>" +
    '<td><textarea name="duties_responsibilites[]" class="form-control" placeholder="" required></textarea></td>' +
    '<td><textarea name="special_contributions[]" class="form-control" placeholder="" required></textarea></td>' +
    '<td><textarea name="duties_perf_circumstances[]" class="form-control" required></textarea></td>' +
    '<td><textarea name="duties_perf_circumstances_bad[]" class="form-control" required></textarea></td>' +
    "<td>" +
    '<a class="btn btn-info btn-sm" name="add-invoice-item" onClick="key_duties_res()"><i class="fa fa-plus-square" aria-hidden="true"></i></a>' +
    '<a class="btn btn-danger btn-sm" value="delete" onclick="deleteDevPlanRow(this)"><i class="fa fa-trash" aria-hidden="true"></i></a>' +
    "</td>" +
    "</tr>";

  $("tbody#key_duties_res").append(newRow);
}


("use strict");
function deleteRow(e) {
  var t = $("#request_table > tbody > tr").length;
  if (1 == t) alert("There only one row you can't delete.");
  else {
    var a = e.parentNode.parentNode;
    a.parentNode.removeChild(a);
  }
  calculateTotalScore();
}

("use strict");
//Add request input field
function add_dev_plans(e) {
  var t =
    '<td><textarea name="recommand_areas[]" class="form-control" placeholder="" required></textarea></td>' +
    '<td><textarea name="expected_outcomes[]" class="form-control" placeholder="" required></textarea></td>' +
    '<td><input type="text" id="responsible_person" name="responsible_person[]" class="form-control" required></td>' +
    '<td><input type="text" id="start_date" name="start_date[]" class="form-control datepicker_sub1" required></td>' +
    '<td><input type="text" id="end_date" name="end_date[]" class="form-control datepicker_sub2" required></td>' +
    '<td> <a  id="add_dev_plan" class="btn btn-info btn-sm" name="add-invoice-item" onClick="add_dev_plans(' +
    "key_dev_plan_item" +
    ')"><i class="fa fa-plus-square" aria-hidden="true"></i></a> <a class="btn btn-danger btn-sm"  value="" onclick="deleteDevPlanRow(this)" ><i class="fa fa-trash" aria-hidden="true"></i></a></td>';

  count_dev_plan == limits_dev_plan
    ? alert(
        "You have reached the limit of adding " + count_dev_plan + " inputs"
      )
    : $("tbody#key_dev_plan_item").append("<tr>" + t + "</tr>");
  count_dev_plan++;

  $(".datepicker_sub1").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });

  $(".datepicker_sub2").datetimepicker({
    timepicker: false,
    format: "Y-m-d",
  });
}

("use strict");
function deleteDevPlanRow(e) {
  var t = $("#request_table_dev_plan > tbody > tr").length;
  if (1 == t) alert("There only one row you can't delete.");
  else {
    var a = e.parentNode.parentNode;
    a.parentNode.removeChild(a);
  }
}

function initializeJavaScriptFunctions() {
  "use strict";
   //////////////////////////////////////////////////////////////////////////////////////////////////////

  //////////////////////////////// Non Academic  //////////////////////////////////////////
  /////////////*  A.ASSESSMENT OF OTHER PERFORMANCE STANDARDS AND INDICATORS *////////////

  function getNumericValue(elementId) {
    var element = document.getElementById(elementId);
    if (!element) {
     // console.error("Element with ID '" + elementId + "' not found.");
      return 0;
    }

    var value = element.value || element.innerHTML || element.textContent || "";
    //console.log("Raw value for", elementId, ":", value);
    value = value.replace(/[^0-9.-]+/g, ""); // Remove non-numeric characters
   // console.log("Numeric value for", elementId, ":", value);
    return parseFloat(value) || 0; // Convert to float or default to 0
}


    function getAssessmentValues(){
        var selectedOption = document.getElementById("staff_select").value;

       let assesment_a_total_score = getNumericValue("assesment_a_total_score");
       let assesment_b_total_score = getNumericValue("assesment_b_total_score");
       let assesment_c_total_score = getNumericValue("assesment_c_total_score");
       let assesment_d_total_score = getNumericValue("assesment_d_total_score");
       let totalScore = getNumericValue("totalScore");
  
        var calculatedScore = 0;
  
        // Calculate the score based on the selected option
        if (selectedOption === "Senior Non Academic") {
            assesment_b_total_score = 0;
            assesment_c_total_score = 0;
            assesment_d_total_score = 0;
          calculatedScore = (assesment_a_total_score + totalScore) / 2;
        } else if (selectedOption === "Senior Academic") {
            assesment_b_total_score = 0;
            assesment_c_total_score = 0;
          calculatedScore = (assesment_a_total_score + assesment_d_total_score) / 2;
        } else if (selectedOption === "Management Staff") {
            assesment_a_total_score = 0;
            assesment_c_total_score = 0;
            totalScore = 0;
          calculatedScore = (assesment_d_total_score + assesment_b_total_score) / 2;
        } else if (selectedOption === "Management Staff Non") {
            assesment_a_total_score = 0;
            assesment_c_total_score = 0;
            assesment_d_total_score = 0;
            totalScore = 0;
          calculatedScore = assesment_b_total_score;
        } else if (selectedOption === "Annual Performance") {
            assesment_a_total_score = 0;
            assesment_b_total_score = 0;
            assesment_d_total_score = 0;
            totalScore = 0;
          calculatedScore = assesment_c_total_score;
        }
        
         // Set the calculated score
      
      document.getElementById("calculatedScore").value = calculatedScore.toFixed(2) ;
      //console.log("Calculated score updated:", calculatedScore);
    }


  /*Demonstrated - Knowledge of duties & Quality of Work*/

  // Function to update the score for a specific category
  function updateScore() {
    var score = $(this).val();
    var scoreInputId = "#" + $(this).attr("name") + "_score";
    $(scoreInputId).val(score);

    updateTotalScore();
    getAssessmentValues();
    
  }

  // Function to handle manual changes to the score input fields
  function validateScore() {
    var score = parseInt($(this).val(), 10);
    if (score > 5) {
      $(this).val(5);
    } else if (score < 1 || isNaN(score)) {
      $(this).val(1);
    }

    updateTotalScore();
  }

  // Function to update the total score
  function updateTotalScore() {
    var selectedOption = document.getElementById("staff_select").value;  
    var totalScore = document.getElementById("totalScore").value || 0;
    var totalScore_a = 0;
    $(".assessment_a").each(function () {
      totalScore_a += parseInt($(this).val(), 10) || 0;
    });
    var adjustedScore = (totalScore_a * 100) / 55;

    // $('#assesment_a_total_score').text(adjustedScore.toFixed(2), '%');
    document.getElementById("assesment_a_total_score").value =
      adjustedScore.toFixed(2);
      let assesment_a_total_score = document.getElementById("assesment_a_total_score").value =
      adjustedScore.toFixed(2);
    // console.log("Total score updated:", adjustedScore);
    // console.log(totalScore)
    // console.log(assesment_a_total_score + totalScore)
  }

  // Attach click event handler to all radio buttons with relevant classes
  $(
    ".demonstrated, .timeliness, .impact, .overall, .interpersonal, .work_relationship, .communication, .contributing, .problem_solving, .decision_making, .managerial_potentials"
  ).click(updateScore);

  // Attach change event handler to the score input fields
  $(
    "#demonstrated_score, #timeliness_score, #impact_score, #overall_score, #interpersonal_score, #work_relationship_score, #communication_score, #contributing_score, #problem_solving_score, #decision_making_score, #managerial_potentials_score"
  ).change(validateScore);

  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  /////////////////////////////// Academic ///////////////////////////////////////////////////////////////

  // Function to update the score for a specific category in the assessment table
  function updateAssessmentScore() {
    var score = $(this).val();
    var scoreInputId = "#" + $(this).attr("name") + "_score";
    $(scoreInputId).val(score);

    updateAssessmentTotalScore();
    getAssessmentValues();
  }

  // Function to handle manual changes to the score input fields in the assessment table
  function validateAssessmentScore() {
    var score = parseInt($(this).val(), 10);
    if (score > 5) {
      $(this).val(5);
    } else if (score < 1 || isNaN(score)) {
      $(this).val(1);
    }

    updateAssessmentTotalScore();
  }

  // Function to update the total score in the assessment table
  function updateAssessmentTotalScore() {
    var totalScore = 0;
    $(".assessment_d").each(function () {
      totalScore += parseInt($(this).val(), 10) || 0;
    });
    var adjustedScore = (totalScore * 100) / 55;

    document.getElementById("assesment_d_total_score").value =
      adjustedScore.toFixed(2);
   // console.log("Total score updated:", adjustedScore);
  }

  // Attach click event handler to all radio buttons with relevant classes
  $(
    ".quality_teaching, .current_research, .quality_research, .quality_publication, .department_responsibilities, " +
      ".contribution, .relationship_colleagues, .acceptance_responsibility, .management_staff, .punctuality, .appearance"
  ).click(updateAssessmentScore);

  // Attach change event handler to the score input fields
  $(
    "#quality_teaching_score, #current_research_score, #quality_research_score, #quality_publication_score, " +
      "#department_responsibilities_score, #contribution_score, #relationship_colleagues_score, #acceptance_responsibility_score, " +
      "#management_staff_score, #punctuality_score, #appearance_score"
  ).change(validateAssessmentScore);

  ////////////////////////////////////////////////////////////////////////////////////////////////////////

  /////////////////////////////////  Premilinary /////////////////////////////////////////////////////////

// Function to update the score for a specific category in assessment C
function updateScoreC() {
    var score = $(this).val();
    var scoreInputId = "#" + $(this).attr("name") + "_score";
    $(scoreInputId).val(score);

    updateTotalScoreC();
    getAssessmentValues();
}

// Function to handle manual changes to the score input fields in assessment C
function validateScoreC() {
    var score = parseInt($(this).val(), 10);
    if (score > 5) {
        $(this).val(5);
    } else if (score < 1 || isNaN(score)) {
        $(this).val(1);
    }

    updateTotalScoreC();
}

// Function to update the total score for assessment C
function updateTotalScoreC() {
    var totalScoreC = 0;
    $(".assessment_c").each(function() {
        totalScoreC += parseInt($(this).val(), 10) || 0;
    });
    var adjustedScoreC = (totalScoreC * 100) / 50; // Assuming there are 10 criteria, max score is 50
    
    document.getElementById("assesment_c_total_score").value = adjustedScoreC.toFixed(2);
    //console.log('Total score updated:', adjustedScoreC);
}

// Attach click event handler to all radio buttons with relevant classes for assessment C
$(".quality, .work_output, .dependability, .job_attitude, .adaptability, .job_knowledge, .attendance, .physical_fitness, .cooperativeness, .learning_capacity").click(updateScoreC);

// Attach change event handler to the score input fields for assessment C
$("#quality_score, #work_output_score, #dependability_score, #job_attitude_score, #adaptability_score, #job_knowledge_score, #attendance_score, #physical_fitness_score, #cooperativeness_score, #learning_capacity_score").change(validateScoreC);




  ///////////////////////////////////////////////////////////////////////////////////////////////////////

  ///////////////////////////////////////// Management ////////////////////////////////////////////////

  // Function to update the score for a specific category in assessment B
function updateScoreB() {
    var score = $(this).val();
    var scoreInputId = "#" + $(this).attr("name") + "_score";
    $(scoreInputId).val(score);

    updateTotalScoreB();
    getAssessmentValues();
}

// Function to handle manual changes to the score input fields in assessment B
function validateScoreB() {
    var score = parseInt($(this).val(), 10);
    if (score > 5) {
        $(this).val(5);
    } else if (score < 1 || isNaN(score)) {
        $(this).val(1);
    }

    updateTotalScoreB();
}

// Function to update the total score for assessment B
function updateTotalScoreB() {
    var totalScore_b = 0;
    $(".assessment_b").each(function() {
        totalScore_b += parseInt($(this).val(), 10) || 0;
    });
    var adjustedScoreB = (totalScore_b * 100) / 50;
    
    document.getElementById("assesment_b_total_score").value = adjustedScoreB.toFixed(2) ;
    //console.log('Total score updated:', adjustedScoreB);
}

// Attach click event handler to all radio buttons with relevant classes for assessment B
$(".leadership, .decision_making_cap1, .decision_making_cap2, .decision_making_cap3, .management_com1, .management_com2, .management_com3, .functional1, .functional2, .functional3").click(updateScoreB);

// Attach change event handler to the score input fields for assessment B
$("#leadership_score, #leadership_build_score, #decision_making_cap1_score, #decision_making_cap2_score, #decision_making_cap3_score, #decision_making_cap4_score, #management_com1_score, #management_com2_score, #management_com3_score, #management_com4_score, #functional1_score, #functional2_score, #functional3_score, #functional4_score").change(validateScoreB);


  //////////////////////////////////////////////////////////////////////////
//  



}

// Run the initialization function on page load
