
   var SelectedLetter     = false,
       SelectedArtist     = false,
       SelectedSong       = false,
       EditPending        = false,
       KeyControlEnabled  = true,
       SelectedArtistName = "",
       SelectedSongName   = "",
       SelectedYTID       = "",
       Sections           = ["SectionMarkerLetters",
                             "SectionMarkerArtists",
                             "SectionMarkerSongs"],
       ActiveSection      = 0;

   var Messages = [
                  ["Confirm artist delete:", "A"],
                  ["Add new artist:", "M"],
                  ["Edit artist:", "M"],
                  ["ERROR: Nothing deleted!", "A"],
                  ["ERROR: No artist added!", "A"],
                  ["ERROR: No artist changed!", "A"],
                  ["Confirm song delete:", "A"],
                  ["Add new song:", "M"],
                  ["Edit song:", "M"],
                  ["ERROR: Nothing deleted!", "A"],
                  ["ERROR: No song added!", "A"],
                  ["ERROR: No song changed!", "A"],
                  ["ERROR: Can not be empty:", "A"],
                  ["WARNING: Already in database!", "W"],
                  ["ERROR: Has songs. Can not delete!", "W"]
                  ];

   $(document).ready(function() {

      $()._9A_MODAL("INITIALIZE", { });

      attachEvents();

      createLettersButtons();

      $("#" + Sections[ActiveSection]).addClass("active");

   });

   // -------------------------------------------------------------------------- LETTERS

   function createLettersButtons() {

        $.get("server/get_data.php?JOB=LETTERS", function(data) {

            var Letters = JSON.parse(data),
                button,
                attribute
                div = document.getElementById("Letters");

            for(var i = 0; i < Letters.length; i++) {
                button = document.createElement("BUTTON");
                attribute = document.createAttribute("id");
                attribute.value = "letter_" + i;
                button.setAttributeNode(attribute);
                attribute = document.createAttribute("class");
                attribute.value = "letter_" + Letters[i]["A"];
                button.setAttributeNode(attribute);
                attribute = document.createAttribute("data-letter");
                attribute.value = Letters[i]["L"].toUpperCase();
                button.setAttributeNode(attribute);
                button.appendChild(document.createTextNode(Letters[i]["L"]));
                div.appendChild(button);
                $(button).click(function() {
                    if(EditPending) firstSaveWork();
                    if($(this).hasClass("active") || EditPending) return;
                    $("#Letters button").removeClass("active");
                    $(this).addClass("active");
                    $("#Songs").empty();
                    SelectedLetter = $(this).text();
                    SelectedArtist = false;
                    SelectedSong = false;
                    SelectedArtistName = "";
                    SelectedSongName   = "";
                    SelectedYTID = "";
                    getArtists();
                });
            }
        });
    }

   // -------------------------------------------------------------------------- ARTISTS

   function createArtistsButtons(Artists) {

       $("#Artists").empty();
       
       var button, span,
           attribute,
           div = document.getElementById("Artists");

      for(var i = 0; i < Artists["Artists"].length; i++) {

         button = document.createElement("BUTTON");
         attribute = document.createAttribute("id");
         attribute.value = "artist_" + Artists["Artists"][i]["ID"];
         button.setAttributeNode(attribute);
         attribute = document.createAttribute("class");
         attribute.value = "Artist";
         button.setAttributeNode(attribute);

         span = document.createElement("SPAN");
         attribute = document.createAttribute("class");
         attribute.value = "SongCount";
         span.setAttributeNode(attribute);
         span.appendChild(document.createTextNode(Artists["Artists"][i]["TotalSongs"]));
         button.appendChild(span);

         span = document.createElement("SPAN");
         attribute = document.createAttribute("class");
         attribute.value = "ArtistName";
         span.setAttributeNode(attribute);
         span.appendChild(document.createTextNode(Artists["Artists"][i]["Name"]));
         button.appendChild(span);

         // button.appendChild(document.createTextNode(Artists["Artists"][i]["Name"]));
         div.appendChild(button);
         
         $(button).click(function() {
            if(EditPending) firstSaveWork();
            if($(this).hasClass("active") || EditPending) return;
            $("#Artists button").removeClass("active");
            $(this).addClass("active");
            SelectedArtist = $(this).attr("id").split("_")[1];
            SelectedArtistName = $(this).children(".ArtistName").text();
            SelectedSong = false;
            SelectedSongName   = "";
            SelectedYTID = "";
            getSongs();
         });
      }
      $("#artist_" + Artists["SelectID"]).click();
   }

   function getArtists() {

      if(!SelectedLetter) return;

      $.get("server/get_data.php", { JOB: "ARTISTS", FirstLetter: SelectedLetter }, function(data) {
          var Artists = JSON.parse(data);
          createArtistsButtons(Artists);
      });

   }

   function controlArtist(todo) {

       if(todo == "CANCEL") {
          $("#ArtistAddEditDelete").fadeOut(300, function() {
             $("#Artists").fadeIn(300);
             EditPending = false;
          });
       }

       if(todo == "ADD") {
          if(EditPending) firstSaveWork();
          if(EditPending) return;
          $("#ArtistMessage").html(Messages[1][0]);
          $("#ArtistMessage").attr("class", Messages[1][1]);
          EditPending = true;
          $(".AED-A").hide();
          $("#ArtistAddInput").val("");
          $("#AddArtist").show();
          $("#Artists").fadeOut(300, function() {
             $("#ArtistAddEditDelete").fadeIn(300, function() {
                $("#ArtistAddInput").focus();
             });
          });
       }

       if(todo == "EDIT") {
          if(EditPending) firstSaveWork();
          if(EditPending || !SelectedLetter || !SelectedArtist) return;
          $("#ArtistMessage").html(Messages[2][0]);
          $("#ArtistMessage").attr("class", Messages[2][1]);
          EditPending = true;
          $(".AED-A").hide();
          $("#ArtistEditInput").val(SelectedArtistName);
          $("#EditArtist").show();
          $("#Artists").fadeOut(300, function() {
              $("#ArtistAddEditDelete").fadeIn(300, function() {
                  $("#ArtistEditInput").focus();
              });
          });
       }
       
       if(todo == "DELETE") {
          if(EditPending) firstSaveWork();
          if(EditPending || !SelectedLetter || !SelectedArtist) return;
          $("#ArtistMessage").html(Messages[0][0]);
          $("#ArtistMessage").attr("class", Messages[0][1]);
          EditPending = true;
          $(".AED-A").hide();
          $("#ArtistDeleteShow").text(SelectedArtistName);
          $("#DeleteArtist").show();
          $("#Artists").fadeOut(300, function() { $("#ArtistAddEditDelete").fadeIn(300); });
       }

   }

   function manageArtist(TheJob, TheArtist, MessageID) {
       var TheArtist = $.trim(TheArtist);
       if(TheArtist === "") {
          $("#ArtistMessage").html(Messages[12][0]);
          $("#ArtistMessage").attr("class", Messages[12][1]);
          return;
       }
       var queryParameters = { JOB: TheJob, ARTIST: TheArtist, FirstLetter: TheArtist.charAt(0).toUpperCase() };
       queryParameters.ID = (TheJob == "ADD" ? 0 : SelectedArtist);
       $.get("server/get_data.php", queryParameters, function(data) {
           var success = JSON.parse(data);
           if(success.Status == "ERROR") {
              $("#ArtistMessage").html(Messages[MessageID][0]);
              $("#ArtistMessage").attr("class", Messages[MessageID][1]);
           } else if(success.Status == "DUPLICATE") {
              $("#ArtistMessage").html(Messages[13][0]);
              $("#ArtistMessage").attr("class", Messages[13][1]);
           } else if(success.Status == "HAS-SONGS") {
              $("#ArtistMessage").html(Messages[14][0]);
              $("#ArtistMessage").attr("class", Messages[14][1]);
           } else {
              EditPending = false;
              createArtistsButtons(success);
              $("#ArtistAddEditDelete").fadeOut(300, function() {
                 $("#Artists").fadeIn(300);
                 if(TheJob == "DELETE") {
                    SelectedArtist = false;
                    SelectedArtistName = "";
                 }
                 if(TheArtist.charAt(0).toUpperCase() != SelectedLetter.toUpperCase()) {
                    $("#Letters button").removeClass("active");
                    $("#Letters button[data-letter='" + TheArtist.charAt(0).toUpperCase() + "']").addClass("active");
                    SelectedLetter = TheArtist.charAt(0).toUpperCase();
                    var elmnt = document.getElementById($("#Letters button[data-letter='" + TheArtist.charAt(0).toUpperCase() + "']").attr("id"));
                    elmnt.scrollIntoView();
                 }
              });
           }

       });
   }

   // ---------------------------------------------------------------------------- SONGS

   function createSongsButtons(Songs) {

       $("#Songs").empty();
       
       var button, itag,
           attribute,
           div = document.getElementById("Songs");

      for(var i = 0; i < Songs.length; i++) {
         button = document.createElement("BUTTON");
         attribute = document.createAttribute("id");
         attribute.value = "song_" + Songs[i]["ID"];
         button.setAttributeNode(attribute);
         attribute = document.createAttribute("class");
         attribute.value = "Song";
         button.setAttributeNode(attribute);
         attribute = document.createAttribute("data-ytid");
         attribute.value = $.trim(Songs[i]["YTID"]);
         button.setAttributeNode(attribute);

         if(!$.trim(Songs[i]["YTID"]) == "") {
             itag = document.createElement("I");
             attribute = document.createAttribute("class");
             attribute.value = "fab fa-youtube fr";
             itag.setAttributeNode(attribute);
             button.appendChild(itag);
         }
         button.appendChild(document.createTextNode(Songs[i]["Title"]));
         div.appendChild(button);
         $(button).click(function() {
            if($(this).hasClass("active") || EditPending) return;
            $("#Songs button").removeClass("active");
            $(this).addClass("active");
            SelectedSong = $(this).attr("id").split("_")[1];
            SelectedSongName = $(this).text();
            SelectedYTID = $(this).attr("data-ytid");
         });
      }
   }

   function getSongs() {

      if(!SelectedLetter || !SelectedArtist) return;

      $.get("server/get_data.php", { JOB: "SONGS", ARTISTID: SelectedArtist }, function(data) {
          var Songs = JSON.parse(data);
          createSongsButtons(Songs["Songs"]);
      });
   }

   function manageSong(TheJob, TheSong, YTID, MessageID) {
       var TheSong = $.trim(TheSong);
       if(TheSong === "") {
          $("#SongMessage").html(Messages[12][0]);
          $("#SongMessage").attr("class", Messages[12][1]);
          return;
       }
       var queryParameters = { JOB: TheJob, TITLE: TheSong, YTID: YTID, ARTISTID: SelectedArtist };
       queryParameters.ID = (TheJob == "ADD" ? 0 : SelectedSong);
       $.get("server/get_data.php", queryParameters, function(data) {
           var success = JSON.parse(data);
           if(success.Status === "ERROR") {
              $("#SongMessage").html(Messages[MessageID][0]);
              $("#SongMessage").attr("class", Messages[MessageID][1]);
           } else if(success.Status == "DUPLICATE") {
              $("#SongMessage").html(Messages[13][0]);
              $("#SongMessage").attr("class", Messages[13][1]);
           } else {
              createSongsButtons(success["Songs"]);
              $("#SongAddEditDelete").fadeOut(300, function() {
                 $("#Songs").fadeIn(300);
                 EditPending = false;
              });
           }
       });
   }

   function controlSong(todo) {

       if(todo == "CANCEL") {
          $("#SongAddEditDelete").fadeOut(300, function() {
             $("#Songs").fadeIn(300);
             EditPending = false;
          });
       }

       if(todo == "ADD") {
          if(EditPending) firstSaveWork();
          if(EditPending || !SelectedLetter || !SelectedArtist) return;
          $("#SongMessage").html(Messages[7][0]);
          $("#SongMessage").attr("class", Messages[7][1]);
          EditPending = true;
          $(".AED-S").hide();
          $("#SongAddInput").val("");
          $("#AddSong").show();
          $("#Songs").fadeOut(300, function() {
             $("#SongAddEditDelete").fadeIn(300, function() {
                $("#SongAddInput").focus();
             });
          });
       }

       if(todo == "EDIT") {
          if(EditPending) firstSaveWork();
          if(EditPending || !SelectedLetter || !SelectedArtist || !SelectedSong) return;
          $("#SongMessage").html(Messages[8][0]);
          $("#SongMessage").attr("class", Messages[8][1]);
          EditPending = true;
          $(".AED-S").hide();
          $("#SongEditInput").val(SelectedSongName);
          $("#YTIDEditInput").val(SelectedYTID);
          $("#EditSong").show();
          $("#Songs").fadeOut(300, function() {
              $("#SongAddEditDelete").fadeIn(300, function() {
                  $("#SongEditInput").focus();
              });
          });
       }
       
       if(todo == "DELETE") {
          if(EditPending) firstSaveWork();
          if(EditPending || !SelectedLetter || !SelectedArtist || !SelectedSong) return;
          $("#SongMessage").html(Messages[6][0]);
          $("#SongMessage").attr("class", Messages[6][1]);
          EditPending = true;
          $(".AED-S").hide();
          $("#SongDeleteShow").text(SelectedSongName);
          $("#DeleteSong").show();
          $("#Songs").fadeOut(300, function() { $("#SongAddEditDelete").fadeIn(300); });
       }

   }

   function firstSaveWork() {
      var data = { type: "warning",
                "title": "Add or edit pending...",
              "heading": "Make a choice:",
             "paragraf": "SAVE your work or CANCEL changes.",
              "buttons": [ { "type": "fas fa-times-circle", "caption": "CLOSE", "callback": "" } ]
                    };
      $()._9A_MODAL("SHOW", data);
   }