/**
 * @author Florian Kapaun <mail@florian-kapaun.de>
 */



var audio_files_container = document.getElementById('audio-files');
var gif_files_container = document.getElementById('gifs');
var audio_elements = {
  "drehen":   [ "flasche", "schluessel", "stift_drehen" ],
  "druecken": [ "handy", "lampe", "stift_druecken" ],
  "heben":    [ "buch", "dvd", "geldbeutel", "karton", "klodeckel", "kronkorken",
                "laptop", "ordner", "topfdeckel", "tupperbox"
              ],
  "schieben": [ ],
  "ziehen":   [ "fenster", "jacke", "kuehlschrank", "mikrowelle", "rucksack",
                "schrank", "schublade", "schuhbaendel", "sportbeutel", "stift_ziehen",
                "tuer", "wasserhahn"
              ]
};
var gif_elements = {
  "drehen":   [ "flasche", "kleber", "schraube", "stift_drehen", "tankdeckel",
                "tuerschloss", "zahlenschloss"
              ],
  "druecken": [ "anwendungen", "armband", "auto", "fernseher", "handy", "lampe",
                "stift_druecken", "tab"
              ],
  "heben":    [ "buch", "dvd", "geldbeutel", "karton", "klodeckel", "kofferraum",
                "kronkorken", "laptop", "ordner", "topfdeckel", "tupperdeckel"
              ],
  "schieben": [ "bh", "schluesselring", "uhr", "uhr_2" ],
  "ziehen":   [ "fenster", "jacke", "jacke_2", "kuehlschrank", "mikrowelle",
                "rucksack", "schrank", "schublade", "schuhbaendel", "sportbeutel",
                "stift_ziehen",  "wasserhahn"
              ]
};



for (var c in audio_elements){

  // Create a list item for each category of the audio elements
  categories.innerHTML += '<li id="' + c + '"><div class="li-wrapper"><div class="audio-wrapper"></div><div class="category" href="#"><div class="gif-wrapper"></div>' + c + '</div></div></li>';

  for (var i of audio_elements[c]){

    // Create a audio player for each item in this audio elements category
    audio_files_container
      .innerHTML += '<audio id="audio-' + i + '" class="audio-file" data-name="' + i + '" preload="none" controls><source src="mp3/' + c + '/' + i + '.mp3" type="audio/mpeg">Your browser does not support the audio element. Update it now!</audio>'
    ;

    // Create a audio visualizer item for each item in this audio elements category
    document
      .getElementById(c)
      .getElementsByClassName('audio-wrapper')[0]
      .innerHTML += '<div id="' + i + '" class="audio-visualizer" tabindex="0"></div>'
    ;
  }
}

// Wait until the websites requests are fully loaded
window.addEventListener('load', function(){

  // If website is fully loaded begin to request the audio files by setting
  // their preload attribute to 'auto'
  var a = document.getElementsByClassName('audio-file');
  for (var i = 0; i < a.length; i++){
    a[i].preload = 'auto';


    a[i].onloadeddata = function(){

      // Get the duration of the requested audio element after it's loaded and
      // set it as animation-duration for the according audio visualizer
      var audio_visualizer = document.getElementById(this.dataset.name);
      audio_visualizer.setAttribute('style', 'animation-duration: ' + this.duration + 's;');

      // Add an eventlistener to the audio visualizer that starts the according
      // audio and animation on mouseenter
      audio_visualizer.addEventListener('mouseenter', function(){

        var audio = document.getElementById('audio-' + this.id);

        // Reset audio to make sure it isn't already playing and therefore not
        // restarting
        audio.currentTime = 0;

        // Start the audio
        var playPromise = audio.play();
        if (playPromise !== null){
          playPromise.catch( function(){ audio.play(); });
        };

        // Start the animation
        // Source: https://css-tricks.com/restart-css-animation/

        // Remove the class which enables the animation to make sure the
        // animation isn't already over
        this.classList.remove('run-animation');

        // Triggering reflow
        void this.offsetWidth;

        // Re-adding the animation class
        this.classList.add('run-animation');
      });
    };
  }

  // If the audio files are implemented, create the gif images
  for (var c in gif_elements){
    for (var i of gif_elements[c]){

      // Create image elements for each gif
      gif_files_container
        .innerHTML += '<img id="gif-' + i + '" class="gif" src="gif/' + c + '/' + i + '.gif">'
      ;

      // Create a gif visualizer item for each gif
      var gif_wrapper = document.getElementById(c).getElementsByClassName('gif-wrapper')[0];
      gif_wrapper.innerHTML += '<div id="' + i + '" class="gif-visualizer" tabindex="0"></div>';
    }
  }

  var g = document.getElementsByClassName('gif-visualizer');
  for (var i = 0; i < g.length; i++){

    // Add an eventlistener to each gif visualizer to make the according gif
    // visible on mouseenter
    g[i].addEventListener('mouseenter', function(){

      // Add class 'visible' to the gif which the visualizer is reffering to
      var gif = document.getElementById('gif-' + this.id);
      gif.classList.add('visible');
    });

    // Add an eventlistener to each gif visualizer to make the according gif
    // invisible again on mouseleave
    g[i].addEventListener('mouseleave', function(){

      // Remove class 'visible' to the gif which the visualizer is reffering to
      var gif = document.getElementById('gif-' + this.id);
      gif.classList.remove('visible');
    });
  }
});

// To ensure that the 'load' eventlistener is working even if a user clicks on
// page forward or backward in his browser
window.addEventListener('onunload', function(){});


// Trigger a click on the start-button if pressed enter
// Reference: https://www.w3schools.com/howto/howto_js_trigger_button_enter.asp
document.getElementById('start-button').addEventListener("keyup", function(event){

  // Number 13 is the "Enter" key on the keyboard. If this button is pressed on
  // the element, the same action should be performed as if the user had clicked
  // on it. Therefore we call a click on the element.
  if (event.keyCode === 13){ this.click(); }
});

// Remove the startscreen and enable audio playing
function removeStartScreen(){
  document.getElementById('enable-audio-play').play();
  document.getElementById('enable-audio').classList.add('fade-out');
}
