
   var SongLocked   = false;
   var SongPlay     = false;
   var AutoLock     = true;
   var WrkObj;
   var ArtistObj    = false;
   var SelectedList = false;
   var ViewerColumns = 2;

   $(document).ready(function() {

      GetLetterFilter($("#LetterBox"));
      PlayLists_Get();
      DoResize();

      WrkObj = $("#by_artist");
      $(WrkObj).addClass("active");
      $("#list_by_artist").show();
      // $("#artist_songlist").show();

      $(document).keyup(function(e) {
         var code = parseInt(e.keyCode || e.which);
         var increment;
         if(code == 107 || code == 187) increment =  2;
         if(code == 109 || code == 189) increment = -2;
         $("#song").css("font-size", parseInt($("#song").css("font-size")) + increment + "px");
      }); 

      $("#toolbar_left a").click(function() {
         // $(".work_list").fadeOut(500);
         if($(this).attr("id") == "by_artist") {
            if(!ArtistObj) $("#list_by_artist").fadeIn(500);
            else $("#artist_songlist").fadeIn(500);
         }
         else if($(this).attr("id") == "do_playlist") {
            if(!SelectedList) $("#create_playlist").fadeIn(500);
            else $("#playlist_songlist").fadeIn(500);
         } else if($(this).attr("id") == "by_genre") {
             Object.assign(document.createElement('a'), {
                target: '_blank',
                href: "lyrics.html",
            }).click();
            return;
         } else if($(this).attr("id") == "by_song") {
             ViewerColumns++;
             if(ViewerColumns == 4) ViewerColumns = 1;
             window.localStorage.setItem('GuitarSongBookColumns', ViewerColumns);
             return;
         } else $("." + $(this).attr("id")).show();
         if(WrkObj) $(WrkObj).removeClass("active");
         WrkObj = $(this);
         $(WrkObj).addClass("active");
         DoResize();
      });

      $("#locker").click(function() {
         if(SongPlay) return;
         if(SongLocked) {
            $("#locker").removeClass("active");
            $("#locker").find("i").removeClass("fa-lock");
            $("#locker").find("i").addClass("fa-unlock");
         } else {
            $("#locker").addClass("active");
            $("#locker").find("i").removeClass("fa-unlock");
            $("#locker").find("i").addClass("fa-lock");
         }
         SongLocked = !SongLocked;
      });

      $("#play").click(function() {
         if(SongPlay) {
            $("#curtain").hide();
            $("#song").stop(true, false);
            $("#play").removeClass("active");
            $("#play").find("i").removeClass("fa-stop");
            $("#play").find("i").addClass("fa-play");
            SongPlay = false;
         } else {
            clearSelection();
            $("#curtain").show();
            $("#song").animate({scrollTop: 0}, 1000);
            $("#play").addClass("active");
            $("#play").find("i").removeClass("fa-play");
            $("#play").find("i").addClass("fa-stop");
            SongPlay = true;
            if(AutoLock) {
               $("#locker").addClass("active");
               $("#locker").find("i").removeClass("fa-unlock");
               $("#locker").find("i").addClass("fa-lock");
               SongLocked = true;
            }
            var ScrollTo = parseInt($("#song")[0].scrollHeight) - parseInt($("#song").css("height"));
            var SongDuration = parseInt($("#duration").val()) * 1000;
            $("#song").delay(1500).animate({scrollTop: ScrollTo}, SongDuration, "linear", function() {
               $("#curtain").hide();
               $("#song").stop(true, false);
               $("#play").removeClass("active");
               $("#play").find("i").removeClass("fa-stop");
               $("#play").find("i").addClass("fa-play");
               SongPlay = false;
            });
         }
      });

      $("#pb_get_artist").click(function() {
         if(!ArtistObj) return;
         $("#sb_SongItems").html("");
         GetFilteredSongs($(ArtistObj).attr("href").split("#")[1], $("#sb_SongItems"))
         $("#list_by_artist, #artist_songlist").fadeToggle(500);
         DoResize();
      });

      $("#pb_filter_songs").click(function() {
         $("#list_by_artist, #artist_songlist").fadeToggle(500);
         DoResize();
      });

      $("#pb_get_playlist").click(function() {
         if(!SelectedList) return;
         GetPlayListItems();         
         DoResize();
      });

      $("#pb_filter_playlists").click(function() {
         $("#create_playlist, #playlist_songlist").fadeToggle(500);
         DoResize();
      });

      $("#keydn, #keyup").click(function() {
         if(SongPlay) return;
         var DoKey   = 1;
         var CurrKey = parseInt($("#song_key").val());
         if($(this).attr("id") == "keydn") DoKey = -1;
         var GoKey = CurrKey + DoKey;
         if(GoKey >= 12) GoKey = 0;
         if(GoKey < 0)  GoKey = 11;
         $("#song_key").val(GoKey);
         SetSongKey();
      });

      $("#tminus, #tplus").click(function() {
         if(SongPlay) return;
         var secs = parseInt($(this).attr("data-time"));
         var curr = parseInt($("#duration").val());
         var news = curr + secs;
         var pres = Math.floor(news / 60);
         var rest = news % 60;

         if(news == 0) return;

         var id  = $(SelectedSong).attr("href").split("#")[1];

         $.post( "../php/set_duration.php", { id: id, duration: news } ).done(function(data) {
            if(data == "OK") {
               $("#dursize").text(pres + ":" + (rest == 0 ? "00" : rest));
               $("#duration").val(news);
            }
         });

      });

   });

   function SetSongKey() {
      var id  = $(SelectedSong).attr("href").split("#")[1];
      var key = $("#song_key").val();
      $.post( "../php/set_song_key.php", { id: id, key: key } ).done(function(data) {
         if(data == "OK") {
            SongEnter(id);
         }
      });
   }

   function GetPlayListItems() {
      $.post("../php/do_songs.php", { user: User, stodo: 0, PlayListID: $(SelectedList).attr("id").split("_")[1] } ).done(function(data) {
         $("#pl_SongItems").html("");
         var FilteredSongs = data.split("#");
         var Output;
         var Details;
         for(var fs = 0; fs < FilteredSongs.length; fs++) {
            Details = FilteredSongs[fs].split("|");
            Output = "<a href='#" + Details[0] + "' class='song_item'>"
                   + "   <span class='artist' data-artist='" + Details[3] + "'>" + Details[1] + "</span>"
                   + "   <span class='song' data-song='" + Details[0] + "'>" + Details[2] + "</span>"
                   + "</a>";     // FilteredSongsHTML + FilteredSongs[fs]["Song_Title"] + "<br />";
            $("#pl_SongItems").append(Output);
         }
         $("#pl_SongItems a").click(function() { 
            $("#pl_SongItems a").removeClass("active");
            $(this).addClass("active");
            SelectedSong = $(this);
            SongClick($(this).attr("href").split("#")[1]);
         });
         $("#pl_SongItems a").dblclick(function() {
            $("#pl_SongItems a").removeClass("active");
            $(this).addClass("active");
            SelectedSong = $(this);
            if(SongPlay) return;
            SongEnter($(this).attr("href").split("#")[1]);
         });

         $("#create_playlist").hide();
         $("#playlist_songlist").show();

         DoResize();
      });
   }

   function PlayLists_Create(data) {
      $("#playlist_items").html("");
      var items = data.split("|");
      var CurrentID = items[0];
      var PlRow;
      var output;
      var FirstID = 0;
      for(var iii = 1; iii < items.length; iii++) {
         PlRow = items[iii].split("#");
         output = "<a href='#' class='pllist_item' id='pl_" + PlRow[0] + "'>"
                + "   <span class='plname'>" + PlRow[1] + "</span>"
                + "   <span class='pldate'>Last change: " + PlRow[2] + "</span>"
                + "</a>"
         $("#playlist_items").append(output);
      }
      $("#playlist_items a").click(function() { 
         $("#playlist_items a").removeClass("active");
         $(this).addClass("active");
         SelectedList = $(this);
      });
      $("#playlist_items a").dblclick(function() { 
         $("#playlist_items a").removeClass("active");
         $(this).addClass("active");
         SelectedList = $(this);
         GetPlayListItems();
      });
   }

   function SongClick(id) {}

   function ArtistEnter(obj) { $("#pb_get_artist").click(); }

   function SongEnter(sid) {
      if(SongPlay) return;
      var TheSong=[];
      let Lyrics = "";
      $("#song_key").val(0);
      $("#sb_SongBody").text("");
      $("#song_name").text($(SelectedSong).children(".song").text());
      $("#artist_name").text($(SelectedSong).children(".artist").text());
      $.post( "../php/get_song.php", { ID: sid } ).done(function(data) {
         $(".pjesma").html("");
         TheSong = data.split("$");
         var chunk;
         for(var c = 0; c < TheSong.length; c++) {
            chunk = TheSong[c].split("%");
            if(chunk.length > 1) {
               if($.trim(chunk[0]) == "y") {
                  if($.trim(chunk[1]) != "")
                     $("#YTVideo").html("<iframe width='300' height='200' src='https://www.youtube.com/embed/" + $.trim(chunk[1]) + "' frameborder='0' allowfullscreen></iframe>");
                  else $("#YTVideo").empty();
               }
               if($.trim(chunk[0]) == "k") {
                  $("#song_key").val(parseInt(chunk[1]));
                  continue;
               }
               if($.trim(chunk[0]) == "d") {
                  var gsec = parseInt(chunk[1]);
                  var mins = Math.floor(gsec / 60);
                  var secs = gsec % 60;
                  $("#dursize").text(mins + ":" + (secs == 0 ? "00" : secs));
                  $("#duration").val(gsec);
                  continue;
               }
               if($.trim(chunk[0]) == "l") {
                   $(".pjesma").append('<hr>');
                   Lyrics = Lyrics + "<hr>";
               }
               if($.trim(chunk[0]) == "e") $(".pjesma").append("<br>"); //('<span class="e" data-row="' + (c + 1) + '">&nbsp;</span>');
               if($.trim(chunk[0]) == "t") $(".pjesma").append('<span class="text" data-row="' + (c + 1) + '">' + chunk[1] + '</span><br>');
               if($.trim(chunk[0]) == "p") {
                   $(".pjesma").append('<span class="chorus" data-row="' + (c + 1) + '">' + chunk[1] + '</span><br>');
                   Lyrics = Lyrics + "<div class='chorus'>" + chunk[1] + "</div>";
               }
               if($.trim(chunk[0]) == "c") $(".pjesma").append('<span class="chord" data-row="' + (c + 1) + '">' + GetChords(chunk, $("#song_key").val()) + '</span><br>');
               if($.trim(chunk[0]) == "v" || $.trim(chunk[0]) == "s") {
                   $(".pjesma").append('<span class="verse" data-row="' + (c + 1) + '">' + chunk[1] + '</span><br>');
                   Lyrics = Lyrics + chunk[1] + "<br />";
               }
            }
         }
         Lyrics = Lyrics.replaceAll("<hr><hr>", "<hr>");
         // Lyrics = "<div id='title'><span>" + $(SelectedSong).children(".artist").text() + ":</span> " + $(SelectedSong).children(".song").text() + "</div><div id='song'>" + Lyrics + "</div>";
         window.localStorage.setItem('GuitarSongBook', '{ "Artist": "' + $(SelectedSong).children(".artist").text() + '", "Song": "' + $(SelectedSong).children(".song").text() + '", "Lyrics": "' + Lyrics + '" }');
         // WriteSong(data, true);
         // $("#sb_Song").fadeIn(500);
         // $("#sb_SongFilter").fadeOut(500);
         // DoResize();
      });
   }

   function ArtistClick(obj) {
      ArtistObj = obj;
   }

   function DoResize() {
      $("#lc_ArtistList").height(($("#list_by_artist").innerHeight() - $("#LB_Title").outerHeight() - $("#LetterBox").outerHeight() - 10) + "px");
      $("#sb_SongItems").height(($("#artist_songlist").innerHeight() - $("#AS_Title").outerHeight()) + "px");
      $(".content_box").each(function(v, i) {
         var InnerSpace = $(this).parent().innerHeight();
         var TitleSpace = $(this).siblings(".container_title").outerHeight();
         $(this).height((InnerSpace - TitleSpace - 200) + "px");
         $(this).css("top", TitleSpace + "px");
      });
   }

   function clearSelection() {
      if(document.selection) document.selection.empty();
      else if (window.getSelection) window.getSelection().removeAllRanges();
   }

// DRAG AND DROP -------------------------------------------------------------------- START

   var _startX = 0;            // mouse starting positions
   var _startY = 0;
   var _offsetX = 0;           // current element offset
   var _offsetY = 0;
   var _dragElement;           // needs to be passed from OnMouseDown to OnMouseMove
   var _oldZIndex = 0;         // we temporarily increase the z-index during drag

   InitDragDrop();

   function InitDragDrop() {
      document.onmousedown = OnMouseDown;
      document.onmouseup = OnMouseUp;
   }

   function OnMouseDown(e) {

      // IE is retarded and doesn't pass the event object
      if (e == null) e = window.event; 
    
      // IE uses srcElement, others use target
      var target = e.target != null ? e.target : e.srcElement;

      // for IE, left click == 1
      // for Firefox, left click == 0
      if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') {

         $(target).css("background-color", "steelblue");

         // grab the mouse position
         _startX = e.clientX;
         // _startY = e.clientY;
        
         // grab the clicked element's position
         _offsetX = ExtractNumber(target.style.left);
         // _offsetY = ExtractNumber(target.style.top);
        
         // bring the clicked element to the front while it is being dragged
         _oldZIndex = target.style.zIndex;
         target.style.zIndex = 10000;
        
         // we need to access the element in OnMouseMove
         _dragElement = target;

         // tell our code to start moving the element with the mouse
         document.onmousemove = OnMouseMove;
        
         // cancel out any text selections
         document.body.focus();

         // prevent text selection in IE
         document.onselectstart = function () { return false; };

         // prevent IE from trying to drag an image
         target.ondragstart = function() { return false; };
        
         // prevent text selection (except IE)
         return false;
      }
   }

   function OnMouseMove(e) {

      var xPos;

      if (e == null) var e = window.event; 

      // this is the actual "drag code"

      if(e.clientX > 600)      xPos = 600;
      else if(e.clientX < 308) xPos = 308;
      else                     xPos = e.clientX;

      // _dragElement.style.top  = (e.clientY) + 'px';

      _dragElement.style.left = xPos + 'px';
      $(".work_area, .work_list").css("width", xPos - 4 + "px");
      $(".song_area").css("left", xPos + 2 + "px");

      DoResize();

   }

   function OnMouseUp(e) {

      if (_dragElement != null) {

         // _dragElement.style.zIndex = _oldZIndex;

         // we're done with these events until the next OnMouseDown
         document.onmousemove = null;
         document.onselectstart = null;
         _dragElement.ondragstart = null;

         $(_dragElement).css("background-color", "white");

         // this is how we know we're not dragging      
         _dragElement = null;
        
      }

   }

   function ExtractNumber(value) {

      var n = parseInt(value);
	
      return n == null || isNaN(n) ? 0 : n;

   }

// DRAG AND DROP ---------------------------------------------------------------------- END