
   var todo = 0;
   var SelectedSong   = false;
   var SelectedArtist = false;

   $(document).ready(function() {

      // GetFilteredSongs(0, $("#sb_SongItems"));
      GetArtists($("#sb_ArtistList"), "");
      GetLetterFilter($("#LetterBox"));

      $("#sb_new_song, #sb_edit_song").click(function() {
         $("#sb_AddEdit").css("overflow", "hidden");
         $("#sb_AddEdit .container_title").text($(this).attr("data-tip"));
         $("#Artist_Field").text("Choose from list below...");
         $("#Artist_Field").attr("data-artist", 0);
         $("#Song_Field").val("");
         $("#Song_Field").attr("data-song", 0);
         todo = $(this).attr("data-todo");
         if($(this).attr("id") == "sb_edit_song") {
            if(!SelectedSong) return;
            $("#sb_ArtistList a").removeClass("active");
            $("#sb_ArtistList a[href='#" + $(SelectedSong).children(".artist").attr("data-artist") + "']").addClass("active");
            $("#Artist_Field").text($(SelectedSong).children(".artist").text());
            $("#Artist_Field").attr("data-artist", $(SelectedSong).children(".artist").attr("data-artist"));
            $("#Song_Field").val($(SelectedSong).children(".song").text());
            $("#Song_Field").attr("data-song", $(SelectedSong).children(".song").attr("data-song"));
         } else {
            $("#sb_ArtistList a").removeClass("active");
         }
         $("#sb_SongControls .message").text("");
         $("#sb_SongList, #sb_SongFilter, #sb_Song").fadeOut(500);
         $("#sb_AddEdit").fadeIn(500, function() { DoResize(); });

      });

      $("#sb_save_song, #sb_cancel_song").click(function() {
         if($(this).attr("id") == "sb_cancel_song") {
            $("#sb_AddEdit, #sb_SongFilter").fadeOut(500);
            $("#sb_SongList, #sb_Song").fadeIn(500, function() { DoResize(); });
            DoResize();
            return;
         }
         var artist = $("#Artist_Field").attr("data-artist");
         var SongID = (todo == 1 ? $("#Song_Field").attr("data-song") : 0);
         var Error  = false;
         if(artist == "" || parseInt(artist) == 0) {
            $("#sb_SongControls .message").text("You have to choose artist!").show();
            return;
         }
         if($.trim($("#Song_Field").val()) == "") {
            $("#sb_SongControls .message").text("Song name cannot be empty!").show();
            return;
         }
         $.post("../php/crud_songs.php", { todo: todo, user: 1, artist: artist, title: $.trim($("#Song_Field").val()), ID: SongID } ).done(function(data) {
            data = data.split("#");
            if(data[0] == "ERROR") {
               $("#sb_SongControls .message").text(data[1]).show();
            } else {
               $("#sb_AddEdit, #sb_SongFilter").fadeOut(500);
               $("#sb_SongList, #sb_Song").fadeIn(500, function() { DoResize(); });
               DoResize();
            }
         });
      });

      $("#sb_edit_song_data").click(function() {
         $("#sb_SongList, #sb_PasteSong").fadeToggle(500);
         DoResize();
      });

      $("#sb_PasteBox").on("input propertychange", function() {
         DoChanges("DISPLAY", $(this).val());
      });

      $("#sb_paste_save").click(function() {
         DoChanges("SAVE", $("#sb_PasteBox").val());
         $("#sb_PasteSong, #sb_SongList").fadeToggle(500);
      });

      $("#sb_paste_cancel").click(function() {
         $("#sb_PasteSong, #sb_SongList").fadeToggle(500);
      });

      $("#sb_filter_songs").click(function() {
         $("#sb_Song, #sb_SongFilter").fadeToggle(500);
         DoResize();
      });

      $("#sb_SongBody").scroll(function () { 
         $("#sb_PasteBox").scrollTop($("#sb_SongBody").scrollTop());
      });
      $("#sb_PasteBox").scroll(function () { 
         $("#sb_SongBody").scrollTop($("#sb_PasteBox").scrollTop());
      });

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

   });

   function DoChanges(How, What) {
      var Converted = "";
      var lines = What.split("\n");
      for(var i = 0; i < lines.length; i++) { Converted = Converted + AnalyseLine(lines[i]); console.log(lines[i], AnalyseLine(lines[i])); } // alert(Converted);
      // $("#temp").text(Converted);
      if(How == "DISPLAY") WriteSong(Converted, false);
      if(How == "SAVE") {
          console.log(Converted);
         $.post( "../php/crud_songs.php", { song: Converted, ID: $(SelectedSong).children(".song").attr("data-song"), todo: 3 } ).done(function(data) {
             
         });
      }
   }

   function DoResize() {

      var wWidth    = $(window).width() - 14;
      var OneHalf   = Math.floor(wWidth / 2);
      var TheModulo = wWidth % 2;
      var Resto     = wWidth - OneHalf;

      $("#sb_SongList, #sb_PasteSong, #sb_AddEdit").width((OneHalf + TheModulo) + "px");
      $("#sb_Song, #sb_SongFilter").width(Resto + "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");
      });

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

   }

   function AnalyseLine(Line) {
      var blocks  = Line.split(" ");
      var IsChord = [];
      var Failed  = false;
      var ChPos   = 0;
      // var Dest    = "";
      var Out     = "";
      if(Line == "") {
         Out = "e%$\n";
         return Out;
      }
      for(var b = 0; b < blocks.length; b++) {
         if(blocks[b].charAt(0) == "*") {
            if(blocks[b].charAt(1) == "-") Out = "l%$\n";
            else if(blocks[b].charAt(1) == "*") Out = "p%" + Line.substring(2) + "$\n";
            else Out = "t%" + Line.substring(1) + "$\n";
            return Out;
         }
         ChPos++;
         if(blocks[b] == "") {
            // Dest = Dest + " ";
            continue;
         }
         // Dest = Dest + " ";
         if(blocks[b].indexOf("/") != -1) {
            var DC = blocks[b].split("/");
            IsChord = RecognizeChord(DC[0]);
            if(IsChord[0]) {
               // Dest = Dest + IsChord[1][0] + IsChord[2][1] + IsChord[3][1] + "\\";
               Out = Out + "%" + IsChord[1][1] + "|" + IsChord[2][2] + "|" + IsChord[3][2] + "|";
            }
            IsChord = RecognizeChord(DC[1]);
            // Dest = Dest + IsChord[1][0] + IsChord[2][1] + IsChord[3][1];
            Out = Out + IsChord[1][1] + "|" + IsChord[2][2] + "|" + IsChord[3][2] + "|" + ChPos;
            ChPos = ChPos + blocks[b].length;
            continue;
         }
         var IsChord = RecognizeChord(blocks[b]);
         if(IsChord[0]) {
            // Dest = Dest + IsChord[1][0] + IsChord[2][1] + IsChord[3][1];
            Out = Out + "%" + IsChord[1][1] + "|" + IsChord[2][2] + "|" + IsChord[3][2] + "|" + ChPos;
            ChPos = ChPos + blocks[b].length;
         }
         else {
             // Dest = Line + "\n";
             Failed = true;
             break;
         }
      }
      if(!Failed) {
         // Dest = Dest + "\n";
         Out = "c" + Out + "$\n";
      } else Out = "v%" /* + Out */ + Line + "$\n";
      return Out;
   }

   function RecognizeChord(ChordToRecognize) {
      var Add      = "";
      var Minor    = "";
      var Chord    = "";
      var AddIdx   = 0;
      var MinorIdx = 0;
      var ChordIdx = 0;
      var GA = GetAdd(ChordToRecognize);
      var GM = GetMinor(GA[0]);
      var MC = MainChord(GM[0]);
      if(MC[1] == -1) {
         // console.log("FALSE");
         return [false];
      } else {
         // console.log("MC", MC, "GM", GM, "GA", GA);
         return[true, MC, GM, GA];
      }

      function GetAdd(InChord) {
         OutChord  = InChord;
         OutAdd    = "";
         OutAddIdx = -1;
         for(var a = 0; a < Adds.length; a++) {
            var n = InChord.toLowerCase().lastIndexOf(Adds[a]);
            if(n != -1) {
               OutAddIdx = a;
               OutAdd    = Adds[a];
               OutChord  = InChord.substring(0, n);
               break;
            }
         }
         // console.log("ADD", OutChord, OutAdd, OutAddIdx);
         return [OutChord, OutAdd, OutAddIdx];
      }

      function GetMinor(InChord) {
         OutChord    = InChord;
         OutMinor    = "";
         OutMinorIdx = -1;
         var m = InChord.charAt(InChord.length - 1).toLowerCase();
         if(m == "m") {
            OutChord    = InChord.substring(0, InChord.length - 1);
            OutMinorIdx = 0;
            OutMinor    = "m";
         }

         if($.inArray(OutChord, Mins) != -1) {
            OutChord = OutChord[0].toUpperCase() + OutChord.slice(1);
            OutMinorIdx = 0;
            OutMinor    = "m";
         }
         // console.log("MINOR", OutChord, OutMinor, OutMinorIdx);
         return [OutChord, OutMinor, OutMinorIdx];
      }
      function MainChord(InChord) {
         OutChord    = InChord;
         OutChordIdx = -1;
         for(var c = 0; c < Note.length; c++) {
            if(Note[c] == InChord
            || Notb[c] == InChord
            || Notx[c] == InChord) {
               OutChordIdx = c;
               OutChord    = Note[c];
               break;
            }
         }        
         // console.log("MAIN", OutChord, OutChordIdx);
         return [OutChord, OutChordIdx];
      }
   }

   function ReadSong(TheSong) {
      var Line;
      var InRead  = "";
      var OneRow  = "";

      $("#sb_SongBody").text("");
      TheSong = TheSong.replace("\n", "").split("$");
      for(var s = 0; s < TheSong.length - 1; s++) {
         Line = TheSong[s].split("%");
         OneRow = "";
         if($.trim(Line[0]) == "c") {
            for(var x = 1; x < Line.length; x++) {
               OneRow = OneRow + LineOut(Line[x], OneRow.length);
            }
         } else OneRow = OneRow + Line[1]; // + "\n";
         InRead = InRead +  OneRow + "\n";
      }
      $("#sb_SongBody").append(InRead);
   }

   function ArtistClick(obj) {
      if($(obj).attr("data-do") == 1) {
         // SelectedArtist = $(this);
         $("#Artist_Field").text($(SelectedArtist).text());
         $("#Artist_Field").attr("data-artist", $(SelectedArtist).attr("href").split("#")[1]);
         $("#sb_SongControls .message").text("You should save or cancel changes");
      }
      if($(obj).attr("data-do") == 2) {
         $("#sb_SongItems").html("");
         GetFilteredSongs($(obj).attr("href").split("#")[1], $("#sb_SongItems"));
      }
   }

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

   function SongClick(id) {
      var TheSong=[];
      $("#sb_SongBody").text("");
      $.post( "../php/get_song.php", { ID: id } ).done(function(data) {
          console.log(data);
         WriteSong(data, true);
         $("#sb_Song").fadeIn(500);
         $("#sb_SongFilter").fadeOut(500);
         DoResize();
      });
   }

   function WriteSong(TheSong, update) { // $("#temp").text(TheSong);
      $("#song_key").val(0);
      $("#sb_SongBody").text("");
      if(update) $("#sb_PasteBox").val("");
      TheSong = TheSong.split("$");
      var chunk;
      for(var c = 0; c < TheSong.length; c++) {
         chunk = TheSong[c].split("%");
         if(chunk.length > 1) {
            if($.trim(chunk[0]) == "k") {
               $("#song_key").val(parseInt(chunk[1]));
               continue;
            }
            if($.trim(chunk[0]) == "d") {
               $("#duration").val(parseInt(chunk[1]));
               continue;
            }
            if($.trim(chunk[0]) == "l") {
               $("#sb_SongBody").append('<hr>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + '*-\n');
            }
            if($.trim(chunk[0]) == "e") {
               $("#sb_SongBody").append("<br>"); //('<span class="e" data-row="' + (c + 1) + '">&nbsp;</span>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + '\n');
            }
            if($.trim(chunk[0]) == "t") {
               $("#sb_SongBody").append('<span class="t" data-row="' + (c + 1) + '">' + chunk[1] + '</span>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + '*' + chunk[1] + '\n');
            }
            if($.trim(chunk[0]) == "p") {
               $("#sb_SongBody").append('<span class="p" data-row="' + (c + 1) + '">' + chunk[1] + '</span>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + '**' + chunk[1] + '\n');
            }
            if($.trim(chunk[0]) == "c") {
               $("#sb_SongBody").append('<span class="c" data-row="' + (c + 1) + '">' + GetChords(chunk, $("#song_key").val()) + '</span>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + GetChords(chunk, $("#song_key").val()) + '\n');
            }
            if($.trim(chunk[0]) == "v" || $.trim(chunk[0]) == "s") {
               $("#sb_SongBody").append('<span class="v" data-row="' + (c + 1) + '">' + chunk[1] + '</span>');
               if(update) $("#sb_PasteBox").val($("#sb_PasteBox").val() + chunk[1] + '\n');
            }
         }
      }
   }

   function LineOut(InLine, InLen) {
      var TempChord = InLine.split("|");
      var OutChord = FindChord(TempChord[0], TempChord[1], TempChord[2]);
      var NSpaces  = TempChord[3] - InLen - 1;
      var Spaces   = "";
      if(TempChord.length == 7) {
         OutChord = OutChord + "/" + FindChord(TempChord[3], TempChord[4], TempChord[5]);
         NSpaces = TempChord[6] - InLen - 1;
      }
      for(var sp = 0; sp < NSpaces; sp++) { Spaces = Spaces + " "; }
      return (Spaces == "" ? " " : Spaces) + OutChord;
      function FindChord(c, m, a) {
         return(Note[c] + (parseInt(m) == 0 ? "m" : "") + (parseInt(a) == -1 ? "" : Adds[a]));
      }
   }