// Global volume variables. These get pulled from the PHP config by ajax.
var maxVolume = 0;
var minVolume = 0;
var volFromServer = false;
var refreshTimerObj;
var gettingSongList = false;
var gettingJukeboxList = false;
var searchTimeout = null;
var queueTarget = 0;

$(document).ready(function() {
   $('#tabs').tabs({
      activate: function(event, ui) {
         if ( ui.newTab.index() == 4 ) { $('#searchbox').val(""); }
      }
   });
   getVolumeRange();
   $('#volume_slider').slider({ animate: "fast", max: maxVolume, min: minVolume, step: 2 });
   $('#volume_slider').slider({
      change: function(event, ui) { if ( !volFromServer ) { setVolume(); } volFromServer = false; }
   });
   $('#max_btn').click(function() { setSliderVolume(maxVolume); });
   $('#min_btn').click(function() { setSliderVolume(minVolume); });
   //$('#skipsong_btn').click(function() { skipSong($(this)); });
   //$('#skipsong_playing_btn').click(function() { skipSong($(this)); });
   $('.skipsong_btn').click(function() { skipSong($(this)); });
   $('#dropsong_btn').click(function() { dropSong($(this)); });
   $('#mute_btn').click(function() { toggleMute($(this)); });
   $('#mute_playing_btn').click(function() { toggleMute($(this)); });
   $('#category_go_btn').click(function() { changeQueue(); });
   $('#surpriseme_btn').click(function() { surpriseMe(); });
   $('#christmas_btn').click(function() { toggleChristmas($(this)); });
   $('#emptyjukebox_btn').click(function() { emptyJukebox($(this)); });
   $('#clearsearch_btn').click(function() { $('#searchbox').val(""); });
   $('#searchbox').keyup(function() { startSearchTimer(); });
   $('#christmas_freq').change(function() { changeChristmasFreq($('#christmas_freq').val()); });
   $('#queuetarget_sel').change(function() { changeQueueTarget(); });
   $('#newqueue_btn').click(function() { createQueue(); });
   $('#led_crazy_btn').click(function() { setPattern("crazy"); });
   $('#led_christmas_btn').click(function() { setPattern("christmas"); });
   $('#led_julyfourth_btn').click(function() { setPattern("julyfourth"); });
   $('#led_easter_btn').click(function() { setPattern("easter"); });
   $('#led_halloween_btn').click(function() { setPattern("halloween"); });
   $('#led_mellow_btn').click(function() { setPattern("mellow"); });
   $('#led_crazymellow_btn').click(function() { setPattern("crazymellow"); });
   $('#led_disableauto_btn').click(function() { disableAuto(); });
   $('#led_lightsoff_btn').click(function() { lightsOff(); });
   $('body').swipe({
      swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
         if ( (direction != "left") && (direction != "right") ) return false;
         var tabIndex = $('#tabs').tabs('option', 'active');
         if ( direction == "right" ) {
            if ( tabIndex > 0 ) $('#tabs').tabs('option', 'active', tabIndex - 1);
            $("html, body").animate({ scrollTop: 0}, 200);
         } else {
            if ( tabIndex < 4 ) $('#tabs').tabs('option', 'active', tabIndex + 1);
            $("html, body").animate({ scrollTop: 0}, 200);
         }
      },
      allowPageScroll: "vertical"
   });
   updateQueueSelects();
   getVolume();
   toggleMute($(this), 'show');
   getSongList();
   getQueueTarget();
   refreshTimerObj = setInterval('getSongList()', 10000);
   //document.documentElement.requestFullscreen();
});

function startSearchTimer() {
   if ( searchTimeout != null ) {
      clearTimeout(searchTimeout);
   }
   searchTimeout = setTimeout(executeSearch, 1000);
}

function updateQueueSelects() {
   var surprisemeVal = $("#surpriseme_sel").val();
   var queuetargetVal = $("#queuetarget_sel").val();
   $.ajax({
      url: 'ajax_getqueuelist.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         $("#queue_sel").html("<option value='0'>-- All Songs --</option>");
         $("#surpriseme_sel").html("<option value='0'>-- All Songs --</option>");
         $("#queuetarget_sel").html("<option value='0'>Jukebox</option>");
         jQuery.each( data.queues, function(i, val) {
            $("#queue_sel").append($('<option>', {
               value: val.id,
               text: val.name,
               selected: val.active
            }));
            $("#surpriseme_sel").append($('<option>', {
               value: val.id,
               text: val.name
            }));
            if ( val.type == 'user' ) $("#queuetarget_sel").append($('<option>', {
               value: val.id,
               text: val.name
            }));
         });
         $("#surpriseme_sel").val(surprisemeVal);
         $("#queuetarget_sel").val(data.queuetarget);
      }
   });
}

function createQueue() {
   $.ajax({
      url: 'ajax_createqueue.php',
      data: {queuename: $("#newqueue_input").val()},
      dataType: 'json',
      success: function(data, stat, jqo) {
         $("#newqueue_input").val("");
         updateQueueSelects();
      }
   });
}

function changeQueueTarget() {
   var newtarget = $('#queuetarget_sel').val();
   $.ajax({
      url: 'ajax_setqueuetarget.php',
      data: {queue: newtarget},
      dataType: 'json',
      success: function(data, stat, jqo) {
         queueTarget = data;
         if ( data == 0 ) {
            $('#queuetab').html('Jukebox');
            $('#jukebox_contents').removeClass('queuehidden');
            $('#customq_contents').addClass('queuehidden');
         } else {
            $('#queuetab').html('CustomQ');
            $('#jukebox_contents').addClass('queuehidden');
            $('#customq_contents').removeClass('queuehidden');
            getCustomQueueList();
         }
      }
   });
}

function getQueueTarget() {
   $.ajax({
      url: 'ajax_getqueuetarget.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         $('#queuetarget_sel').val(data);
         queueTarget = data;
         if ( data == 0 ) {
            $('#queuetab').html('Jukebox');
            $('#jukebox_contents').removeClass('queuehidden');
            $('#customq_contents').addClass('queuehidden');
         } else {
            $('#queuetab').html('CustomQ');
            $('#jukebox_contents').addClass('queuehidden');
            $('#customq_contents').removeClass('queuehidden');
            getCustomQueueList();
         }
      }
   });
}

function toggleChristmas(callingElement) {
   callingElement.blur();
   callingElement.addClass("buttonactive");
   $.ajax({
      url: 'ajax_togglexmas.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         callingElement.removeClass("buttonactive");
         updateChristmasButton(data.christmas);
      },
      error: function(jqo, stat, err) {
         callingElement.removeClass("buttonactive");
      }
   });
}

function updateChristmasButton(active) {
   if ( active ) {
      $('#christmas_btn').val("Christmas: Active");
      if ( ! $('#christmas_btn').hasClass('christmas_active') ) { $('#christmas_btn').addClass('christmas_active'); }
   } else {
      $('#christmas_btn').val("Christmas: Inactive");
      if ( $('#christmas_btn').hasClass('christmas_active') ) { $('#christmas_btn').removeClass('christmas_active'); }
   }
}

function getSongList() {
   gettingSongList = true;
   $.ajax({
      url: 'ajax_listsongs.php',
      dataType: 'json',
      success: function(data, stat, jqo) {
         if ( data.volume != $('#volume_slider').slider("value") ) {
            volFromServer = true;
            $('#volume_slider').slider("value", data.volume);
         }
         $('#history_contents').html(data.songlist);
         $('#playing_contents').html(data.songplaying);
         updateChristmasButton(data.christmas);
         updateMuteButton(data.muted);
         $('#christmas_freq').val(data.christmasfreq);
         getJukeboxList();
      }
   });
}

function changeChristmasFreq(newfreq) {
   if ( gettingSongList == true ) {
      setTimeout(function() { changeChristmasFreq(newfreq); }, 200);
      return;
   }
   $.ajax({
      url: 'ajax_setchristmasfreq.php',
      data: {newfreq: newfreq}
   });
}

function getJukeboxList() {
   if ( queueTarget == 0 ) {
      gettingJukeboxList = true;
      $.ajax({
         url: 'ajax_getjukebox.php',
         dataType: 'html',
         success: function(data, stat, jqo) {
            $('#jukebox_contents').html(data);
            gettingSongList = false;
            gettingJukeboxList = false;
         }
      });
   } else {
      getCustomQueueList();
   }
}

function getCustomQueueList() {
   $.ajax({
      url: 'ajax_getcustomq.php',
      dataType: 'html',
      success: function(data, stat, jqo) {
         $('#customq_contents').html(data);
      }
   });
}

function executeSearch() {
   searchTimeout = null;
   var searchfor = $('#searchbox').val();
   if ( searchfor.length < 4 ) return false;
   $.ajax({
      url: 'ajax_searchsongs.php',
      dataType: 'html',
      data: {searchfor: searchfor},
      success: function(data, stat, jqo) {
         $('#search_contents').html(data);
      }
   });
}

function removeHighlight(elementID) {
   $(elementID).css("color", "#D8D8D8");
   $(elementID).css("background-color", "#1C1C1C");
}

function showQueued(elementID) {
   $(elementID).css("color", "orange");
   $(elementID).css("background-color", "#1C1C1C");
}

function dropCustomQSong(songid) {
   var elementID = "#customq_" + songid;
   $(elementID).css("color", "#1C1C1C");
   $(elementID).css("background-color", "#D8D8D8");
   $.ajax({
      url: 'ajax_dropcustomqsong.php',
      data: {songid: songid},
      success: function(data, stat, jqo) {
         getCustomQueueList();
      }
   });
}

function addSongToQueue(songid) {
   var elementID = "#search_" + songid;
   $(elementID).css("color", "#1C1C1C");
   $(elementID).css("background-color", "#D8D8D8");
   $.ajax({
      url: 'ajax_queuesong.php',
      data: {songid: songid},
      success: function(data, stat, jqo) {
         getJukeboxList();
         setTimeout(function() { showQueued(elementID); }, 200);
      }
   });
}

function dropJukeboxSong(id) {
   if ( gettingJukeboxList || gettingSongList ) return false;
   var elementID = "#juke_" + id;
   $(elementID).css("color", "#1C1C1C");
   $(elementID).css("background-color", "#D8D8D8");
   $.ajax({
      url: 'ajax_dropjukeboxsong.php',
      data: {id: id},
      success: function(data, stat, jqo) {
         getJukeboxList();
      }
   });
}

function getVolumeRange() {
   $.ajax({
      url: 'ajax_getvolrange.php',
      async: false,
      dataType: 'json',
      success: function(data, stat, jqo) {
         maxVolume = data.max;
         minVolume = data.min;
      }
   });
}

function updateMuteButton(muted) {
   $('#mute_btn').blur();
   $('#mute_playing_btn').blur();
   if ( muted ) {
      $('#mute_btn').prop('value', 'Unmute');
      $('#mute_playing_btn').prop('value', 'Unmute');
   } else {
      $('#mute_btn').prop('value', 'Mute');
      $('#mute_playing_btn').prop('value', 'Mute');
   }
}

function toggleMute(callingElement, show) {
   callingElement.blur();
   callingElement.addClass("buttonactive");
   if ( typeof show === 'undefined' ) { show = ""; }
   $.ajax({
      url: 'ajax_togglemute.php',
      data: {show: show},
      dataType: 'json',
      success: function(data, stat, jqo) {
         callingElement.removeClass("buttonactive");
         updateMuteButton(data.muted);
      },
      error: function(jqo, stat, err) {
         callingElement.removeClass("buttonactive");
      }
   });
}

function skipSong (callingElement) {
   callingElement.blur();
   if ( gettingJukeboxList || gettingSongList ) return false;
   callingElement.addClass("buttonactive");
   $.ajax({
      url: 'ajax_skipsong.php',
      async: false,
      success: function (data, stat, jqo) {
         callingElement.removeClass("buttonactive");
         getSongList();
      },
      error: function(jqo, stat, err) {
         callingElement.removeClass("buttonactive");
      }
   });
}

function emptyJukebox (callingElement) {
   callingElement.blur();
   callingElement.addClass("buttonactive");
   $.ajax({
      url: 'ajax_emptyjukebox.php',
      success: function (data, stat, jqo) {
         callingElement.removeClass("buttonactive");
         getJukeboxList();
         //skipSong();
      },
      error: function(jqo, stat, err) {
         callingElement.removeClass("buttonactive");
      }
   });
}

function dropSong (callingElement) {
   callingElement.blur();
   if ( gettingJukeboxList || gettingSongList ) return false;
   callingElement.addClass("buttonactive");
   $.ajax({
      url: 'ajax_dropsong.php',
      async: false,
      success: function (data, stat, jqo) {
         callingElement.removeClass("buttonactive");
         getSongList();
      },
      error: function(jqo, stat, err) {
         callingElement.removeClass("buttonactive");
      }
   });
}

function changeQueue () {
   var qid = $('#queue_sel').val();
   $.ajax({
      url: 'ajax_changequeue.php',
      data: {newid: qid},
      async: false,
      success: function (data, stat, jqo) {
         getSongList();
      }
   });
}

function surpriseMe () {
   var qid = $('#surpriseme_sel').val();
   $.ajax({
      url: 'ajax_surpriseme.php',
      data: {queueid: qid},
      success: function(data, stat, jqo) {
         getJukeboxList();
         // skipSong();
      }
   });
}

function setSliderVolume (value) {
   $('#volume_slider').slider("value", value);
}

function setVolume () {
   volume = $('#volume_slider').slider("value");
   $.ajax({
      url: 'ajax_setvolume.php',
      data: {volume: volume},
      dataType: 'text'
   });
}

function getVolume () {
   $.ajax({
      url: 'ajax_getvolume.php',
      dataType: 'json',
      success: function (data, stat, jqo) {
         $('#volume_slider').slider("value", data.volume);
      }
   });
}

function setColor(color) {
   $.ajax({
      url: 'ajax_setcolor.php',
      data: {color: color}
   });
}

function setPattern(pattern) {
   $.ajax({
      url: 'ajax_setpattern.php',
      data: {pattern: pattern}
   });
}

function disableAuto() {
   $.ajax({
      url: 'ajax_disableauto.php'
   });
}

function lightsOff() {
   $.ajax({
      url: 'ajax_lightsoff.php'
   });
}
