
   var DragPending = false;
   var DragObject  = false;
   var DragObjSize = [0,0];
   var DOHalfSize  = [0,0];
   var DOPosition  = [0,0];
   var ObjSource   = false;
   var PLIOffset   = [0,0];
   var Placeholder = false;
   var PlHolderHTM = "<div id=\"placeholder\"></div>";
   var OrdSource   = false;
   var EditPending = false;
   var NewPending  = 0;
   var ActivePl    = false;
   var TempEnum    = "";
   var DelPending  = false;

   var NoPlaylists  = "<dl>"
                    + "   <dt>No playlists available!</dt>"
                    + "   <dd>"
                    + "      <i class='fa fa-info-circle'></i>"
                    + "      <span>To create new one click <strong>plus button</strong> above.</span>"
                    + "   </dd>"
                    + "</dl>";
   var PlaylistEdit = "<dl>"
                    + "   <dt>Playlist name:</dt>"
                    + "   <dd><input type='text' name='pname' id='pname'></dd>"
                    + "   <dd class='controls'>"
                    + "      <span class='message'></span>" //<br class='purg' />
                    + "      <a href='#' id='savepl' class='fa fa-check-circle tt' data-tip='Save playlist'></a>"
                    + "      <a href='#' id='cancelpl' class='fa fa-times-circle tt' data-tip='Cancel'></a>"
                    + "      <br class='purg' />"
                    + "   </dd>"
                    + "<dl>";
   var SaveFirst    = "<dl>"
                    + "   <dt>You have been changed current playlist!</dt>"
                    + "   <dd>"
                    + "      <span>You should <strong>save your work</strong> or cancel editting.</span>"
                    + "      <a href='#' id='savepli' class='fa fa-check-circle tt' data-tip='Save playlist'></a>"
                    + "      <a href='#' id='cancelpli' class='fa fa-times-circle tt' data-tip='Cancel'></a>"
                    + "   </dd>"
                    + "</dl>";
   var DeleteList   = "<dl>"
                    + "   <dt>Delete playlist and all song references:</dt>"
                    + "   <dd><span class='todelete'></span>"
                    + "      <br class='purg' /><span class='message'></span>"
                    + "      <a href='#' id='deletenow' class='fa fa-check-circle'data-tip='Confirm delete'></a>"
                    + "      <a href='#' id='canceldpl' class='fa fa-times-circle' data-tip='Cancel'></a>"
                    + "      <br class='purg' />"
                    + "   </dd>"
                    + "<dl>";
   var NoPLItems    = "<dl class='noplaylistitems'>"
                    + "   <dt>Playlist songs not added yet!</dt>"
                    + "   <dd>"
                    + "      <i class='fa fa-info-circle'></i>"
                    + "      <span>Drag 'n' drop songs from filtered song list.</span>"
                    + "   </dd>"
                    + "</dl>";

   $(document).ready(function() {

      PlayLists_Get(); /* Get list of playlists. */

      $("#playlist_list").delegate("a", "mousedown", function(e) { PlayList_MouseDown(this, e); });

      $("#new_playlist, #edit_playlist").click(function() { $(".tooltip").remove(); PlayList_New_Edit(this); });

      $("#playlist_items").delegate("a", "mousemove", function(e){ PlayListItems_MouseMove(); });

      $("#pl_filter_songs").click(function() {
         $("#playlists_container, #playlist_container, #filters_container").fadeToggle(500, function() { DoResize(); });
      });

      $("#song_items").delegate(".song_item", "mousedown", function(event) {
         event.stopPropagation();
         event.preventDefault();
         if(ActivePl == 0 || !ActivePl) return;
         if(event.which == 1) DragItem($(this), event);
      });

      $("#playlist_items").delegate(".playlist_item", "mousedown", function(event) {
         event.preventDefault();
         var et = event.target;
         if($(et).attr("class") == "delete") {
            event.stopPropagation();
            $(this).remove();
            PlayListItems_Count();
            if(!EditPending) SetControls();
            return;
         }
         event.stopPropagation();
         if(event.which == 1) DragItem($(this), event);
      });

      $(window, ".song_item").mouseup(function(e) {
         if(!DragPending && !DragObject && !ObjSource) return;
         e.stopPropagation();
         if(e.which == 1) DropItem(e);
      });

      $("#playlist_items").delegate("button", "click", function(e) {
         $(".tooltip").remove();
         e.stopPropagation();
         $(this).parent().remove();
      });

      SongsList_GetFiltered();
      GetLetterFilter($("#LetterBox"));

   });

   /* DRAG 'N' DROP BEHAVIOR ---------------------------------------------------------------------- */

   function DragItem(obj, e) { /* Select song to drag. Start drag. */

      if(NewPending != 0) return;

      ObjSource = $(obj);

      DragObjSize[0] = $(ObjSource).width();
      DragObjSize[1] = $(ObjSource).height();
      DOHalfSize[0]  = DragObjSize[0] / 2;
      DOHalfSize[1]  = DragObjSize[1] / 2;
      DOPosition[0]  = e.pageX - DOHalfSize[0];
      DOPosition[1]  = e.pageY + 10;

      DragObject  = $(ObjSource).clone();

      $("body").append(DragObject);

      var DOStyles = { position: "absolute",
                       left: DOPosition[0] + "px",
                        top: DOPosition[1] + "px",
                      width: ($(obj).width() + "px"),
                     height: ($(obj).height() + "px"),
                     border: "solid 1px steelblue",
                     "z-index": "1000"
                     }

      $(DragObject).css(DOStyles);
      $(DragObject).fadeTo(500, 0.5);

      DragPending = true;
      TempEnum = PlayListItems_Enum();

      if($(obj).hasClass("playlist_item")) {
         $(DragObject).css("left", PLIOffset.left + "px");
         $("#playlist_items").append(PlHolderHTM);
         Placeholder = true;
         $("#placeholder").insertBefore($(obj));
         $(obj).hide();
      }

   }

   function DropItem(e) { /* Drop after adding song to playlist or changing order. */

      var SourceCopy;
      var xdif = e.pageX - PLIOffset.left;
      var ydif = e.pageY - PLIOffset.top;
      var DoChanges = false;

      if(xdif > -1 && ydif > -1 && xdif < $("#playlist_items").width() && ydif < $("#playlist_items").height() && NewPending == 0) {
         if($(ObjSource).hasClass("song_item")) {
            SourceCopy = $(ObjSource).clone();
            $(SourceCopy).prepend("<span class='delete'>&times</span>");
//            $(SourceCopy).prepend("<button type='button' class='close'>&times</button>");
         } else {
            SourceCopy = $(ObjSource);
         }
         $("#playlist_items").children().css("position", "relative");
         $(SourceCopy).insertBefore("#placeholder");
         $(SourceCopy).removeClass("song_item");
         $(SourceCopy).addClass("playlist_item");
         DoChanges = (TempEnum == PlayListItems_Enum() ? false : true);
         if(!EditPending && DoChanges) SetControls(e);
      }

      $("#playlist_items").children("#placeholder").remove();
      $(DragObject).remove();
      ObjSource = false;
      DragObject = false;
      DragPending = false;
      $("#playlist_items").children().css("display", "block");
      PlayListItems_Count();
   }

   function SetControls(e) {

      $("#playlist_list").hide();
      $("#playlist_worker").html(SaveFirst).show(300);

      EditPending = true;

      $("#cancelpli").click(function() {
         $(".tooltip").remove();
         EditPending  = false;
         NewPending   = 0;
         $("#playlist_worker").html("").hide();
         $("#playlist_list").show(300);
         $("#playlist_list #pl_" + ActivePl).mousedown();
      });

      $("#savepli").click(function() {
         $(".tooltip").remove();
         PlayListItems_Save(1);
         EditPending  = false;
         $("#playlist_worker").html("").hide();
         $("#playlist_list").show(300);
      });

   }

   /* PLAYLISTS ----------------------------------------------------------------------------------- */

   function PlayList_MouseDown(obj, e) { /* Select playlist. Delete behavior. */

      $("#playlist_list a").removeClass("active");
      $(obj).addClass("active");
      // $("#playlist_items").html("");
      ActivePl = $(obj).attr("id").split("_")[1];
      e.preventDefault();
      var et = e.target;
      if($(et).attr("data-class") == "delete") {
         NewPending = -1;
         e.stopPropagation();
         // $("#playlist_list").hide();
         $("#playlist_worker").html(DeleteList);
         $(".todelete").text($("#pl_" + ActivePl).children(".plname").text());
         $("#playlist_worker").show(300);

         $("#canceldpl").click(function() {
            $(".tooltip").remove();
            NewPending  = 0;
            $("#playlist_worker").html("").hide();
            $("#playlist_list").show(300);
         });

         $("#deletenow").click(function() {
            $(".tooltip").remove();
            $.post("../php/do_playlists.php", { user: User, todo: NewPending, id: ActivePl } ).done(function(data) {
               NewPending = 0;
               $("#playlist_worker").html("").hide();
               $("#playlist_list").show(300);
               PlayLists_Create(data);
            });
         });
      }
      PlayListItems_GetSaved();
   }

   function PlayList_New_Edit(obj) { /* Add new playlist or edit current playlist name. */

      if(NewPending != 0) return;

      if(EditPending) {
         $("#playlist_list").hide();
         $("#playlist_worker").html(SaveFirst).show(300);
         return;
      }

      $("#playlist_list").hide();
      $("#playlist_worker").html(PlaylistEdit).show(300).find("input").focus();
      NewPending = $(obj).attr("data-todo");

      if(NewPending == 2) $("#pname").val($("#pl_" + ActivePl).children(".plname").text());

      $("#cancelpl").click(function() {
         $(".tooltip").remove();
         NewPending  = 0;
         $("#playlist_worker").html("").hide();
         $("#playlist_list").show(300);
      });

      $("#savepl").click(function() {
         $(".tooltip").remove();
         var entry = $.trim($("#pname").val());
         if(entry == "") {
            $("#message").text("Cannot be empty!");
            return;
         }
         $.post("../php/do_playlists.php", { user: User, todo: NewPending, name: entry, id: ActivePl } ).done(function(data) {
            NewPending = 0;
            $("#playlist_worker").html("").hide();
            $("#playlist_list").show(300);
            PlayLists_Create(data);
         });
      });
   }

   function PlayLists_Create(data) { /* Create GUI presentation of playlists. */
      var items;
      if(data == "No playlists") {
         $("#playlist_list").hide();
         $("#playlist_worker").html(NoPlaylists).show(300);
      } else {
         $("#playlist_list").html("");
         items = data.split("|");
         if(items.length == 1) {
            $("#playlist_list").hide();
            $("#playlist_worker").html(NoPlaylists).show(300);
         }
         var CurrentID = items[0];
         var PlRow;
         var output;
         var FirstID = 0;
         for(var iii = 1; iii < items.length; iii++) {
            PlRow = items[iii].split("#");
            if(iii == 1) FirstID = PlRow[0];
            output = "<a href='#' class='pllist_item' id='pl_" + PlRow[0] + "'>"
                   + "   <span data-class='delete' class='delete'>&times;</span>"
                   + "   <span class='plname'>" + PlRow[1] + "</span>"
                   + "   <span class='pldate'>Last change: " + PlRow[2] + "</span>"
                   + "</a>"
            $("#playlist_list").append(output);
         }
         if(parseInt(CurrentID) != 0)
            $("#playlist_list #pl_" + CurrentID).mousedown();
         else {
            if(FirstID != 0) $("#playlist_list #pl_" + FirstID).mousedown();
         }
      }
   }

   /* PLAYLIST ITEMS ------------------------------------------------------------------------------ */

   function PlayListItems_Enum() { /* Enumerate current playlist items. Make list to save in database. */
      var NewPlaylist = "";
      $( "#playlist_items a" ).each(function( index ) {
         NewPlaylist = NewPlaylist + $(this).attr("href").replace("#", "|");
      });
      return NewPlaylist;
   }

   function PlayListItems_GetSaved() { /* Get saved playlist items. */
      $.post("../php/do_songs.php", { user: User, todo: 0, PlayListID: ActivePl } ).done(function(data) {
         $("#playlist_items").html("");
         if(data == "No playlist songs.") {
            $("#playlist_items").html(NoPLItems);
            return;
         }
         var allSongs = data.split("#");
         var oneSong, theSong;
         for(var iii = 0; iii < allSongs.length; iii++) {
            oneSong = allSongs[iii].split("|");
            theSong = "<a href='#" + oneSong[0] + "' class='playlist_item'>"
                    // + "   <button type='button' class='close'>&times</button>"
                    + "   <span class='delete'>&times</span>"
                    + "   <span class='author' data-author='" + oneSong[3] + "'>" + oneSong[1] + "</span>"
                    + "   <span class='song' data-song='" + oneSong[0] + "'>" + oneSong[2] + "</span>"
                    + "</a>";
            $("#playlist_items").append(theSong);
         }
      });
   }

   function PlayListItems_MouseMove() { /* Detect mouse drag over playlist items. Manage placeholder. */
      var elem = document.elementFromPoint(window.mouseXPos, window.mouseYPos);
      if($(elem).attr("class") == "author" || $(elem).attr("class") == "song")
         elem = $(elem).parent();
      if($(elem).parent().attr("id") != "playlist_items") return;
      if(elem) {
         var po = $(elem).offset();
         var half = $(elem).height() / 2;
         if((window.mouseYPos - po.top) >= half) $("#placeholder").insertAfter($(elem));
         else $("#placeholder").insertBefore($(elem));
      }
   }

   function PlayListItems_Save(stodo) { /* Save playlist items into playlist. */
      if(ActivePl == 0 || !ActivePl) {
         $("#playlist_items").html("");
         return;
      }
      var songs = "";
      if(stodo == 1) songs = PlayListItems_Enum().substring(1);
      $.post( "../php/do_songs.php", { stodo: stodo, user: User, id: ActivePl, songs: songs } ).done(function(data) {
      });
   }

   function PlayListItems_Count() {
      if($("#playlist_items a").length == 0)
         $("#playlist_items").html(NoPLItems);
      else
         $("#playlist_items .noplaylistitems").remove();
   }

   /* FILTERING SONG LIST ------------------------------------------------------------------------- */

   function SongsList_GetFiltered() { /* Get filtered song list to choose from. */
      $.post("../php/songs_filter.php", { user: User, Artist_ID: 1 } ).done(function(data) {
         var allSongs = data.split("#");
         var oneSong, theSong;
         for(var iii = 0; iii < allSongs.length; iii++) {
            oneSong = allSongs[iii].split("|");
            theSong = "<a href='#" + oneSong[0] + "' class='song_item'>"
                    + "   <span class='author' data-author='" + oneSong[3] + "'>" + oneSong[1] + "</span>"
                    + "   <span class='song' data-song='" + oneSong[0] + "'>" + oneSong[2] + "</span>"
                    + "</a>";
            $("#song_items").append(theSong);
         }
      });
   }

   /* WINDOW EVENTS ------------------------------------------------------------------------------- */

   $(window).resize(function() { DoResize(); }); /* Browser event. */

   $(window).mousemove(function(e){ /* Draging behavior. */

      if(e.which != 1 || DragPending == false || DragObject == false || ActivePl == 0 || !ActivePl) return;

         window.mouseXPos = e.pageX;
         window.mouseYPos = e.pageY;
         
         if($(DragObject).hasClass("playlist_item"))
            $(DragObject).css({ left: (PLIOffset.left + "px"), top: ((e.pageY + 10) + "px") });
         else
            $(DragObject).css({ left: ((e.pageX - DOHalfSize[0]) + "px"), top: ((e.pageY + 10) + "px") });

         DOPosition[0] = e.pageX - PLIOffset.left;
         DOPosition[1] = e.pageY - PLIOffset.top;

         if(DOPosition[0] < 0
         || DOPosition[1] < 0
         || DOPosition[0] > $("#playlist_items").width()
         || DOPosition[1] > $("#playlist_items").height()) {
            $("#playlist_items").children("#placeholder").remove();
            Placeholder = false;
         } else {
            if(!Placeholder) {
               Placeholder = true;
               $("#playlist_items").append(PlHolderHTM);
            }
         }

         $("#playlist_items a").mousemove();

   });

   function DoResize() { /* Resize interface items. */

      var wWidth    = $(window).width() - 14;
      var OneThird  = Math.floor(wWidth / 3);
      var TheModulo = wWidth % 3;

      $("#playlists_container, #songs_container, #filters_container, #playlist_worker").width(OneThird + "px");
      $("#playlist_container, #filters_container").css("left", (OneThird + 6) + "px");
      $("#playlist_container, #filters_container").css("width", (OneThird + TheModulo) + "px");
/*
      var wHeight = $(window).height() - 6;
      var OneHalf = Math.floor(wHeight / 2);
      TheModulo   = wHeight % 2;

      $("#playlists_container, #playlist_worker").height((OneHalf + TheModulo - 2) + "px");
      $("#filters_container").height((OneHalf - 2) + "px");
*/
      $(".container").each(function(v, i) {
         var InnerSpace = $(this).innerHeight();
         var TitleSpace = $(this).children(".container_title").outerHeight();
         $(this).children(".content_box").height((InnerSpace - TitleSpace) + "px");

      });

      $("#lc_ArtistList").height(($("#fartist").innerHeight() - $("#LetterBox").outerHeight() - 15) + "px");

      PLIOffset = $("#playlist_items").offset();

   }

   /* FILTERING SONGS LIST ------------------------------------------------------------------------ */

   function ArtistClick(obj) {
      $("#song_items").html("");
      GetFilteredSongs($(obj).attr("href").split("#")[1], $("#song_items"));
   }