window.table = {};
table.rows = new Array();

window.interval = {};
interval.start = 0;
interval.end = 0;

table.updateWidth = function()
{
  table.resetSliders();
  table.draw();
}

table.resetSliders = function()
{
  $("#intervalA").attr("max", $("#displayWindow").val() * 2);
  $("#intervalB").attr("max", $("#displayWindow").val() * 2);
  if (options.windowSelector == "aroundNow")
  {
    $("#intervalA").val($("#displayWindow").val());
    $("#intervalB").val($("#displayWindow").val());
  }
  else
  {
    $("#intervalA").val("2");
    $("#intervalB").val("2");
  }
}

table.toggleColorCode = function()
{
  if (options.colorCoding)
    options.colorCoding = false;
  else options.colorCoding = true;
  table.drawColor();      
}

table.setInterval = function()
{
  interval.start = Math.min($("#intervalA").val(), $("#intervalB").val())
  interval.end = Math.max($("#intervalA").val(), $("#intervalB").val())
  table.drawInterval();
  table.drawIntervalHeaders();
  $("#clipboard").val(interval.toStr());
}

table.addRow = function()
{
  var bestGuess = zfChoice;

  if (table.rows.length == 0)
  {
    table.rows.push(moment.tz.guess());
    table.rows.push("UTC");
  }

  if (bestGuess != undefined && !(table.rows.includes(bestGuess)) )
    table.rows.push(bestGuess);
     
  else if (bestGuess == undefined)
    alert("Could not deduce a timezone from the input: " + zfInput);

  else
    alert("Timezone "+ bestGuess + " is already present in the table.")

  searchbar.clear();
  table.draw();
}

table.draw = function()
{
  table.resetSliders();
  table.drawHeaders();
  table.drawMain();
  table.drawColor();
  table.attachRowControls();
  table.updateNowLine();
  table.drawInterval();
  table.drawIntervalHeaders();
  $("#tableAndSelectorWrapper").animate({ scrollLeft: $("#now").css("margin-left")}, 200);

  if (table.rows.length >= 2)
    $("#bigWrapper").css("display", "inline-block");
  else if (table.rows.length == 0)
    $("#bigWrapper").css("display", "none")
}

table.drawIntervalHeaders = function()
{
  if ($("#intervalA").val() != $("#intervalB").val())
  {
    var str = interval.toStr();
    str = str.split(/\r?\n/);
    console.log(str);
    var i = 0;
    var divs = $("table th .zoneInterval");
    divs.each(function(){
      console.log(str[i]);
      $(this).text(str[i++].split(": ")[1]);
      console.log($(this).text());
    })
    $("table th").css("lineHeight", "20px");
  }
  else
  {
    $("table th").css("lineHeight", "40px");
    $("table th .zoneInterval").text("");
  }
}

table.drawInterval = function()
{
  if ($("#intervalA").val() != $("#intervalB").val())
  {
    $("#intervalHilight").css("margin-left", 49*interval.start/2 - 2);
    $("#intervalHilight").css("width", 49*(interval.end - interval.start)/2);
    $("#intervalHilight").css("display", "block");
    $("#shareRawText").css("display", "inline-block")
  }
  else
  {
    $("#intervalHilight").css("display", "none");
    $("#shareRawText").css("display", "none");
  }
}

interval.toStr = function()
{
  var timeDump = $("#zoneTable table tr td time");
  var dayDump = $("#zoneTable table tr td .day")
  var intervalStr = "";
  var times = new Array();
  var days = new Array();
  var lesser, greater;
  
  if (Math.min($("#intervalA").val(), $("#intervalB").val()) == $("#intervalA").val())
  {
    lesser = $("#intervalA");
    greater = $("#intervalB");
  }
  else
  {
    lesser = $("#intervalB");
    greater = $("#intervalA");
  }
  
  for (var t of timeDump)
  {
    times.push(t.innerHTML);
  }
  for (var d of dayDump)
  {
    days.push(d.innerHTML);
  }
  
  for (var r of table.rows)
  {
    intervalStr += r + ": "
    switch(lesser.val()%2)
    {
      case 0:
        intervalStr += days[lesser.val()/2] + " ";
        intervalStr += times[lesser.val()/2];
        break;
      case 1:
        intervalStr += days[Math.floor(lesser.val()/2)] + " ";
        if (options.formatSelector == "24H")
          intervalStr += moment(times[Math.floor(lesser.val()/2)], "HH:mm").add(30, "minutes").format("HH:mm");
        else
          intervalStr += moment(times[Math.floor(lesser.val()/2)], "hh:mm A").add(30, "minutes").format("hh:mm A");
        break;
    }
    intervalStr += " - ";
    switch(greater.val()%2)
    {
      case 0:
        intervalStr += days[greater.val()/2] + " ";
        intervalStr += times[greater.val()/2];
        break;
      case 1:
        intervalStr += days[Math.floor(greater.val()/2)] + " ";
        if (options.formatSelector == "24H")
          intervalStr += moment(times[Math.floor(greater.val()/2)], "HH:mm").add(30, "minutes").format("HH:mm");
        else
          intervalStr += moment(times[Math.floor(greater.val()/2)], "hh:mm A").add(30, "minutes").format("hh:mm A");
        break;
    }
    for (var i = 0; i < $("#displayWindow").val(); i++)
    {
      times.shift();
      days.shift();
    }
    intervalStr += `
`
  }
  return intervalStr;
}

interval.copyText = function()
{
  if ($("#intervalA").val() != $("#intervalB").val())
  {
    $("#clipboard").select();
    document.execCommand('copy');
    alert(`Copied the interval to the clipboard:
${interval.toStr()}`)
  }
  else
    alert("You haven't set a time interval!");
}

table.updateNowLine = function()
{
  var timeNow = formatTime(moment());
  switch (options.windowSelector)
  {
    case "aroundNow":
      if ($("#displayWindow").val()%2 == 0)
       $("#now").css("margin-left", 49*($("#displayWindow").val()/2 - 1) + (49/60)*timeNow.split(":")[1]);
      else
        $("#now").css("margin-left", 49*Math.floor($("#displayWindow").val()/2) + (49/60)*timeNow.split(":")[1]);
      break;
    case "startingNow":
      $("#now").css("margin-left", (49/60)*timeNow.split(":")[1]);
      break;
  }
}

table.attachRowControls = function()
{
  $(".zoneControlDelete").on("click", table.rowDelete);
  $(".zoneControlUp").on("click", table.rowUp);
  $(".zoneControlDown").on("click", table.rowDown);
}

table.rowDelete = function(e)
{
  var btnGroup = $(".zoneControlDelete");
  var btnArray = new Array();
  for (var btn of btnGroup)
  {
    btnArray.push(btn);
  }
  for (var btn of btnArray)
  {
    if (btn == e.target)
    {
      table.rows.splice(btnArray.indexOf(btn), 1)
      break;
    } 
  }
  table.draw();
}

table.rowDown = function(e)
{
  var btnGroup = $(".zoneControlDown");
  var btnArray = new Array();
  for (var btn of btnGroup)
  {
    btnArray.push(btn);
  }
  for (var btn of btnArray)
  {
    if (btn == e.target)
    {
      var swap = table.rows[btnArray.indexOf(btn)];
      table.rows[btnArray.indexOf(btn)] = table.rows[btnArray.indexOf(btn) + 1];
      table.rows[btnArray.indexOf(btn) + 1] = swap;
      break;
    } 
  }
  table.draw();
}

table.rowUp = function(e)
{
  var btnGroup = $(".zoneControlUp");
  var btnArray = new Array();
  for (var btn of btnGroup)
  {
    btnArray.push(btn);
  }
  for (var btn of btnArray)
  {
    if (btn == e.target)
    {
      var swap = table.rows[btnArray.indexOf(btn)];
      console.log(swap)
      table.rows[btnArray.indexOf(btn)] = table.rows[btnArray.indexOf(btn) - 1];
      table.rows[btnArray.indexOf(btn) - 1] = swap;
      break;
    } 
  }
  table.draw();
}

table.drawColor = function()
{
  if (options.colorCoding)
  {
    var rows = $("#zoneTable table tr");
    rows.filter(":even").each(function(){
    
      $(this).children("td").each(function(){
        var time = $(this).children("time").html();
        switch (options.formatSelector)
        {
          case "24H":
            if (time.split(":")[0] < 8 && time.split(":")[0] != 0)
              $(this).addClass("early");
            if (time.split(":")[0] >= 17 || time.split(":")[0] == 0)
              $(this).addClass("late");
            break;
            
          case "12H":
            if ((time.split(":")[0] < 8 || time.split(":")[0] == 12) && time.split(" ")[1] == "AM")
              $(this).addClass("early")
            if ((time.split(":")[0] >= 5 && time.split(" ")[1] == "PM" && time.split(":")[0] != 12) || (time.split(":")[0] == 12 && time.split(" ")[1] == "AM"))
              $(this).addClass("late")
            break;
        }
        if ($(this).children(".day").text() == "Sat" || $(this).children(".day").text() == "Sun")
        {
          $(this).removeClass();
          $(this).addClass("weekend");
        }
      })

    })
    rows.filter(":odd").each(function(){
    
      $(this).children("td").each(function(){
        var time = $(this).children("time").html();
        switch (options.formatSelector)
        {
          case "24H":
            $(this).addClass("workingEven");
            if (time.split(":")[0] < 8 && time.split(":")[0] != 0)
              $(this).addClass("earlyEven");
            if (time.split(":")[0] >= 17 || time.split(":")[0] == 0)
              $(this).addClass("lateEven");
            break;
            
          case "12H":
            $(this).addClass("workingEven");
            if ((time.split(":")[0] < 8 || time.split(":")[0] == 12) && time.split(" ")[1] == "AM")
              $(this).addClass("earlyEven")
            if ((time.split(":")[0] >= 5 && time.split(" ")[1] == "PM" && time.split(":")[0] != 12) || (time.split(":")[0] == 12 && time.split(" ")[1] == "AM"))
              $(this).addClass("lateEven")
            break;
        }
        if ($(this).children(".day").text() == "Sat" || $(this).children(".day").text() == "Sun")
        {
          $(this).removeClass();
          $(this).addClass("weekendEven");
        }
      })

    })
  }
  else $("#zoneTable table tr td").removeClass();
}

table.drawHeaders = function()
{
  var headerHTML = "";
  var counter, uDisable, dDisable;

  for (var z of table.rows)
  {
    counter = table.rows.indexOf(z);
    uDisable = "";
    dDisable = "";
    if (counter == 0) { uDisable = "disabled"}
    if (counter == table.rows.length - 1) { dDisable = "disabled" }

    headerHTML +=
`<tr><th><div class="zoneControlUpWrapper">
<input type="button" name="zone${counter}Up" id="zone${counter}Up" class="zoneControlUp" value="&#9650;" ${uDisable}>
</div><div class="zoneControlDeleteWrapper">
<input type="button" name="zone${counter}Delete" id="zone${counter}Delete" class="zoneControlDelete" value="X">
</div><div class="zoneControlDownWrapper">
<input type="button" name="zone${counter}Down" id="zone${counter}Down" class="zoneControlDown" value="&#9660;" ${dDisable}>
</div><div class="zoneInfo">
${moment.tz.zone(z).abbr(moment())} [${moment.tz(moment(), z).format("Z")}]
</div>
<div class="zoneInterval">
</div>
</th></tr>
`  
  }
  $("#zoneHeaders").html(headerHTML);
}

table.drawMain = function()
{
  var mainHTML = "";
  var theHour = moment().startOf("hour");
  var now;
  for (var z of table.rows)
  { 
    now = moment().startOf("hour");
    mainHTML += "<table><tr>";
    for (var i = 0, j; i < $("#displayWindow").val(); i++)
    {
      switch (options.windowSelector)
      {
        case "startingNow":
          if (i == 0)
            j = 0;
          else j = 1;
          break;
        case "aroundNow":
          if (i == 0)
            if ($("#displayWindow").val()%2 == 0)
              j = -(Math.floor($("#displayWindow").val()/2) - 1);
            else
              j = -Math.floor($("#displayWindow").val()/2)
          else j = 1;
          break;
      }
      mainHTML += `<td><div class="day">${now.add(j, 'hours').tz(z).format("ddd")}</div><time>${formatTime(now.tz(z))}</time></td>`; 
    }
    mainHTML += "</tr></table>";
  }
  $("#zoneTable").html(mainHTML);
  $("#zoneTable").css("width", $("#zoneTable table").first().css("width"));
  console.log(mainHTML)
}
