(function($, Drupal, drupalSettings) {

  EdlpTheme = function(){
    var _$body = $('body');
    var _is_front = _$body.is('.path-frontpage');
    var _$corpus_canvas;
    var _$content_container = $('main[role="main"]>.layout-content');
    var _$ajaxLinks;
    var _audio_player;
    var _randomPlayer;

    //  ___      _ _
    // |_ _|_ _ (_) |_
    //  | || ' \| |  _|
    // |___|_||_|_|\__|
    function init(){
      console.log("EdlpTheme init()");

      // TODO: redirect all no-front pages to front with write hash

      _$body.on('corpus-map-ready', onCorpusMapReady);

      _audio_player = new AudioPlayer();

      initAjaxLinks();

      if (_$body.is('.path-productions')) {
        initProductions();
      }

      // initScrollbars();
      initEvents();
    };

    //  ___             _
    // | __|_ _____ _ _| |_ ___
    // | _|\ V / -_) ' \  _(_-<
    // |___|\_/\___|_||_\__/__/
    function initEvents(){
      $('body')
        .on('on-studio-chutier-updated', function(e){
          initAjaxLinks();
        })
        .on('open_entree', function(e){
          // e.tid available
          closeAllModals();
        })
        .on('close_entree', function(e){
          // e.tid available
          closeAllModals();
        });
    }

    //    _          _ _
    //   /_\ _  _ __| (_)___
    //  / _ \ || / _` | / _ \
    // /_/ \_\_,_\__,_|_\___/
    //
    // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
    // https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/samples/gg589528%28v%3dvs.85%29
    // https://www.binarytides.com/using-html5-audio-element-javascript/
    function AudioPlayer(){
      var that = this;
      this.fid;
      this.audio = new Audio();
      // audio events
      this.audio_events = ["loadedmetadata","canplay","playing","pause","timeupdate","ended"];

      // UI dom objects
      this.$container   = $('<div id="audio-player">');
      // btns
      this.$btns        = $('<div>').addClass('btns').appendTo(this.$container);
      this.$previous    = $('<div>').addClass('previous').appendTo(this.$btns);
      this.$playpause   = $('<div>').addClass('play-pause').appendTo(this.$btns);
      this.$next        = $('<div>').addClass('next').appendTo(this.$btns);
      // timeline
      this.$timelinecont= $('<div>').addClass('time-line-container').appendTo(this.$container);
      this.$timeline    = $('<div>').addClass('time-line').appendTo(this.$timelinecont);
      this.$loader      = $('<div>').addClass('loader').appendTo(this.$timeline);
      this.$cursor      = $('<div>').addClass('cursor').appendTo(this.$timeline);
      // time
      this.$time        = $('<div>').addClass('time').appendTo(this.$container);
      this.$currentTime = $('<div>').addClass('current-time').html('00:00').appendTo(this.$time);
      this.$duration    = $('<div>').addClass('duration').html('00:00').appendTo(this.$time);
      // favoris
      this.$fav       = $('<div>').addClass('favoris').appendTo(this.$container);
      // cartel
      this.$cartel       = $('<div>').addClass('cartel').appendTo(this.$container);

      // hiding
      this.hideTimer = false;
      this.hideTimeMS = 10000;

      // history
      this.currentHistoricIndex = null;
      this.historic = [];
      this.shuffle_is_active = false;

      // object events
      this.event_handlers = {
        'audio-play-next':[],
        'audio-ended':[]
      };

      this.init();
    };
    AudioPlayer.prototype = {
      init(){
        // append ui to document
        this.$container.appendTo('header[role="banner"] .region-header');
        // record timeline width
        this.timeline_w = parseInt(this.$timeline.width());
        // init audio events
        var fn = '';
        for (var i = 0; i < this.audio_events.length; i++) {
          fn = this.audio_events[i];
          // capitalize first letter of event (only cosmetic :p )
          fn = 'on'+fn.charAt(0).toUpperCase()+fn.slice(1);
          this.audio.addEventListener(
            this.audio_events[i],
            this[fn].bind(this),
            true);
        }
        // init btns events
        this.$previous.on('click', this.playPrevious.bind(this));
        this.$playpause.on('click', this.togglePlayPause.bind(this));
        this.$next.on('click', this.playNext.bind(this));
        // TODO: previous and next btns
      },
      openDocument(node){
        console.log('AudioPlayer openDocument', node);
        this.historic.push(node);
        this.currentHistoricIndex = this.historic.length-1;
        // this.shuffle_mode = shuffle_mode || false;
        this.launch();
      },
      launch(){
        this.setSRC(this.historic[this.currentHistoricIndex].audio_url);
        this.loadNode(this.historic[this.currentHistoricIndex].nid);
        // emmit new playing doc (e.g.: corpus map nowing that audio played from RandomPlayer)
        _$corpus_canvas.trigger({
          'type':'audio-node-opened',
          'id':this.historic[this.currentHistoricIndex].id
        });
        this.showHidePreviousBtn();
        this.showHideNextBtn();
        this.show();
      },
      // audio functions
      setSRC(url){
        // console.log('AudioPlayer setSRC : url', url);
        this.clearTimeOutToHide();
        this.audio.src = url;
      },
      onLoadedmetadata(){
        var rem = parseInt(this.audio.duration, 10),
            mins = Math.floor(rem/60,10),
            secs = rem - mins*60;
        this.$duration.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
        this.updateLoadingBar();
      },
      updateLoadingBar(){
        this.$loader.css({
          'width':parseInt((100 * this.audio.buffered.end(0) / this.audio.duration), 10)+'%'
        });
        if( this.audio.buffered.end(0) < this.audio.duration ){
          // loop through this function until file is fully loaded
          var that = this;
          window.requestAnimationFrame(that.updateLoadingBar.bind(that));
        }else{
          console.log('Audio fully loaded');
        }
      },
      onCanplay(){
        this.play();
      },
      play(){
        this.audio.play();
      },
      playPrevious(){
        if(this.currentHistoricIndex > 0){
          this.currentHistoricIndex -= 1;
          this.launch();
        }
      },
      playNext(){
        if(this.currentHistoricIndex < this.historic.length-1){
          this.currentHistoricIndex += 1;
          this.launch();
        }else{
          this.emmit('audio-play-next');
        }
      },
      togglePlayPause(e){
        if(this.audio.paused){
          this.audio.play();
        }else{
          this.audio.pause();
        }
      },
      stop(){
        this.audio.pause();
        this.timeOutToHide();
      },
      // audio events
      onPlaying(){
        this.$container.addClass('is-playing');
      },
      onPause(){
        this.$container.removeClass('is-playing');
      },
      onTimeupdate(){
        // move cursor
        this.$cursor.css({
          'left':(this.audio.currentTime/this.audio.duration * this.timeline_w)+"px"
        });
        // update time text display
        var rem = parseInt(this.audio.currentTime, 10),
            mins = Math.floor(rem/60,10),
            secs = rem - mins*60;
        this.$currentTime.html('<span>'+(mins<10 ? '0':'')+mins+':'+(secs<10 ? '0':'')+secs+'</span>');
      },
      onEnded(){
        this.emmit('audio-ended');
        this.stop();
      },
      // cartel functions
      loadNode(nid){
        this.$cartel.addClass('loading');
        $.getJSON('/edlp/ajax/json/node/'+nid+'/player_cartel', {})
          .done(this.onNodeLoaded.bind(this))
          .fail(this.onNodeLoadFail.bind(this));
      },
      onNodeLoaded(data){
        console.log('AudioPlayer node loaded', data);
        this.$cartel.html(data.rendered).removeClass('loading');
        _$body.trigger({'type':'new-audio-cartel-loaded'});
        initAjaxLinks();
      },
      onNodeLoadFail(jqxhr, textStatus, error){
        console.warn('AudioPlayer node load failed', jqxhr.responseText);
        this.$cartel.removeClass('loading').html('');
      },
      // global
      show(){
        this.$container.addClass('visible');
      },
      showHidePreviousBtn(){
        if(this.historic.length > 1 && this.currentHistoricIndex > 0){
          this.$previous.addClass('is-active');
        }else{
          this.$previous.removeClass('is-active');
        }
      },
      showHideNextBtn(){
        if(this.currentHistoricIndex < this.historic.length-1 || this.shuffle_is_active){
          this.$next.addClass('is-active');
        }else{
          this.$next.removeClass('is-active');
        }
      },
      timeOutToHide(){
        this.clearTimeOutToHide();
        this.hideTimer = setTimeout(this.hide.bind(this), this.hideTimeMS);
      },
      clearTimeOutToHide(){
        if(this.hideTimer){
          clearTimeout(this.hideTimer);
        }
      },
      hide(){
        this.$container.removeClass('visible');
        // trigger highlighted node remove on corpus map
        _$corpus_canvas.trigger('audio-node-closed');
      },
      // object events
      on(event_name, handler){
        if(typeof this.event_handlers[event_name] == 'undefined'){
          console.warn('AudioPlayer : event '+event_name+' does not exists');
        }
        this.event_handlers[event_name].push(handler);
        return this;
      },
      emmit(event_name){
        var handler;
        for (var i = this.event_handlers[event_name].length; i >= 0 ; i--) {
          handler = this.event_handlers[event_name][i];
          setTimeout(handler, 0);
        }
      },
    }

    //  ___             _ _ ___
    // / __| __ _ _ ___| | | _ ) __ _ _ _ ___
    // \__ \/ _| '_/ _ \ | | _ \/ _` | '_(_-<
    // |___/\__|_| \___/_|_|___/\__,_|_| /__/
    function initScrollbars(){
      // console.log("initScrollbars");
      // TODO: find a better js scroll than overlayScrollbars which does not handle well max-height + overflow-y:auto;
      // $('.os-scroll').overlayScrollbars({
      //   overflowBehavior:{
      //     x:'h',
      //     y:'scroll',
      //     clipAlways:false
      //   }
      // });
    };

    //    _    _
    //   /_\  (_)__ ___ __
    //  / _ \ | / _` \ \ /
    // /_/ \_\/ \__,_/_\_\
    //      |__/
    // TODO: add url hash nav
    // TODO: implement history.js
    function initAjaxLinks(){
      console.log('initAjaxLinks');

      $('a', '#block-mainnavigation')
        .add('a', '#block-footer.menu--footer')
        .add('a', '#block-productions')
        .add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
        .add('a', '.productions-subtree')
        .add('a', '.productions-parent')
        // .add('a.index-link, a.notice-link', '#block-edlpentreesblock')
        .addClass('ajax-link');


      _$ajaxLinks = $('.ajax-link:not(.ajax-enabled)')
        .each(function(i,e){
          var $this = $(this);
          // avoid already ajaxified links
          if($this.is('.ajax-enable')) return;
          if($this.attr('data-drupal-link-system-path')){
            $this.on('click', onClickAjaxLink).addClass('ajax-enable');
          }
        });
    };
    function onClickAjaxLink(e){
      e.preventDefault();
      var $link = $(this);

      if($link.is('.is-active'))
        return false;

      // Audio links
      if($link.is('.audio-link')){
        _audio_player.openDocument({
          nid:$link.attr('nid'),
          audio_url:$link.attr('audio_url')
        });
        return false;
      }

      // other links
      var sys_path = $(this).attr('data-drupal-link-system-path');
      var ajax_path = sys_path;
      if(sys_path == '<front>'){
        backToFrontPage();
        return false;
      }

      // convert node link to edlp_ajax_node module links
      var node_match = ajax_path.match(/^\/?(node\/\d+)$/g);
      var term_match = ajax_path.match(/^\/?(taxonomy\/term\/\d+)$/g);
      if(node_match){
        ajax_path = 'edlp/ajax/json/'+node_match[0];
        // check for viewmode attribute
        if($link.attr('viewmode')){
          ajax_path += '/'+$link.attr('viewmode');
        }
      }else if(term_match){
        ajax_path = 'edlp/ajax/json/'+term_match[0];
        ajax_path = ajax_path.replace(/taxonomy\/term/, 'taxonomy_term');
        // check for viewmode attribute
        if($link.attr('viewmode')){
          ajax_path += '/'+$link.attr('viewmode');
        }
      }else{
        // convert other link to ajax
        ajax_path += '/ajax'
      }

      _$body.addClass('ajax-loading');
      $link.addClass('ajax-loading');

      // TODO: use Drupal.url()
      // Drupal.url = function (path) {
      //   return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
      // };

      var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
      $.getJSON(path, {})
        .done(function(data){
          onAjaxLinkLoaded(data, $link, sys_path);
        })
        .fail(function(jqxhr, textStatus, error){
          onAjaxLinkLoadError(jqxhr, textStatus, error, $link, sys_path);
        });

      return false;
    };
    function onAjaxLinkLoadError(jqxhr, textStatus, error, $link, sys_path){
      console.warn('ajaxlink load failed for '+sys_path+' : '+error, jqxhr.responseText);
      $link.removeClass('ajax-loading');
      _$body.removeClass('ajax-loading');
    };
    function onAjaxLinkLoaded(data, $link, sys_path){
      console.log('ajax link loaded : data', data);
      _$body.removeClass('ajax-loading');

      // replace all content with newly loaded
      _$content_container.html(data.rendered);

      // add body class for currently loaded content
      var body_classes = [
        'path-'+sys_path.replace(/\//g, '-'),
        'entity-type-'+data.entity_type,
        'bundle-'+data.bundle,
        'view-mode-'+data.view_mode
      ];
      _$body.removeClass().addClass(body_classes.join(' '));

      // id node add a generic path-node class to body
      m = sys_path.match(/^\/?(node\/\d+)$/g);
      if(m)
        _$body.addClass('path-edlp-node');

      // handle clicked link classes
      _$ajaxLinks.removeClass('is-active');
      $link.removeClass('ajax-loading').addClass('is-active');

      // if block attached (eg : from edlp_productions module)
      if(typeof data.block != 'undefined'){
        // if block not already added
        if(!$('#'+data.block.id, '.region-'+data.block.region).length){
          $('.region-'+data.block.region).append(data.block.rendered);
        }
      }

      initScrollbars();

      if(sys_path == "productions")
        initProductions();

      initAjaxLinks();

      _$body.trigger({'type':'new-content-ajax-loaded'});

      // TODO: call behaviours
      Drupal.attachBehaviors(_$content_container);

    };

    //   ___
    //  / __|___ _ _ _ __ _  _ ___
    // | (__/ _ \ '_| '_ \ || (_-<
    //  \___\___/_| | .__/\_,_/__/
    //              |_|
    function onCorpusMapReady(e){
      console.log('theme : onCorpusReady', e);
      _$corpus_canvas = $('canvas#corpus-map');
      _$corpus_canvas
        .on('corpus-cliked-on-map', function(e) {
          console.log('theme : corpus-cliked-on-map');
          backToFrontPage();
        })
        .on('corpus-cliked-on-node', function(e) {
          console.log('theme : corpus-cliked-on-node', e);
          _audio_player.openDocument(e.target_node);
        });

      _randomPlayer = new RandomPlayer(e.playlist);

      _$body.attr('corpus-map', 'ready');
    }

    //  ___              _           ___ _
    // | _ \__ _ _ _  __| |___ _ __ | _ \ |__ _ _  _ ___ _ _
    // |   / _` | ' \/ _` / _ \ '  \|  _/ / _` | || / -_) '_|
    // |_|_\__,_|_||_\__,_\___/_|_|_|_| |_\__,_|\_, \___|_|
    //                                          |__/
    function RandomPlayer(playlist){
      this.active = false;
      this.playlist = playlist;
      this.$btn = $('<a>').html('Shuffle').addClass('random-player-btn');
      this.init()
    };
    RandomPlayer.prototype = {
      init(){
        // this.shuffle();
        $('<div>')
          .addClass('block random-player')
          .append(this.$btn)
          .insertAfter('#block-userlogin, #block-studiolinkblock');

        // events
        this.$btn.on('click', this.toggleActive.bind(this));

        // attach an event on AudioPlayer
        _audio_player
          .on('audio-ended', this.onAudioPlayerEnded.bind(this))
          .on('audio-play-next', this.onAudioPlayNext.bind(this));
      },
      shuffle(){
        var tempPLaylist = [];
        for (var i = this.playlist.length-1; i >= 0 ; i--) {
          tempPLaylist.push(this.playlist[i]);
        }
        this.shuffledPlaylist = [];
        while(tempPLaylist.length > 0){
          var r = Math.floor(Math.random() * tempPLaylist.length);
          this.shuffledPlaylist.push(tempPLaylist.splice(r,1)[0]);
        }
        console.log('RandomPlayer, this.shuffledPlaylist', this.shuffledPlaylist);
      },
      toggleActive(e){
        if (this.active) {
          this.$btn.removeClass('is-active');
          this.stop();
        }else{
          this.$btn.addClass('is-active');
          this.shuffle();
          this.start();
        }
      },
      start(){
        this.active = _audio_player.shuffle_is_active = true;
        this.next();
      },
      stop(){
        this.active = _audio_player.shuffle_is_active = false;
        // stop audio player
        _audio_player.stop();
      },
      next(){
        if(this.active && this.shuffledPlaylist.length > 0)
          _audio_player.openDocument(this.shuffledPlaylist.splice(0,1)[0]);
      },
      onAudioPlayNext(){
        console.log('RandomPlayer : onAudioPlayNext()');
        this.next();
      },
      onAudioPlayerEnded(){
        console.log('RandomPlayer : onAudioPlayerEnded()');
        this.next();
      }
    };

    //  ___             _         _   _
    // | _ \_ _ ___  __| |_  _ __| |_(_)___ _ _  ___
    // |  _/ '_/ _ \/ _` | || / _|  _| / _ \ ' \(_-<
    // |_| |_| \___/\__,_|\_,_\__|\__|_\___/_||_/__/
    function initProductions(){
      console.log('theme : initProductions');
      var $grid = $('.row', _$content_container).masonry({
        itemSelector:'.col',
        columnWidth:'.col-2'
      });

      // layout Masonry after each image loads
      $grid.imagesLoaded().progress( function() {
        $grid.masonry('layout');
      });
      // var $grid = $('.row', _$content_container).imagesLoaded( function() {
      //   // init Masonry after all images have loaded
      //   $grid.masonry({
      //     itemSelector:'.col',
      //     columnWidth:'.col-2'
      //   });
      // });
    };

    //  ___            _   ___
    // | __| _ ___ _ _| |_| _ \__ _ __ _ ___
    // | _| '_/ _ \ ' \  _|  _/ _` / _` / -_)
    // |_||_| \___/_||_\__|_| \__,_\__, \___|
    //                             |___/
    function backToFrontPage(){
      closeAllModals();
      // assume we are going back to front page
      $('body').removeClass().addClass('path-frontpage');
      $('a[data-drupal-link-system-path="<front>"]').addClass('is-active');

    }

    //  __  __         _      _
    // |  \/  |___  __| |__ _| |___
    // | |\/| / _ \/ _` / _` | (_-<
    // |_|  |_\___/\__,_\__,_|_/__/
    function closeAllModals(){
      console.log('theme : closeAllModals');
      // TODO: animate the remove
      _$content_container.html('');
      _$ajaxLinks.removeClass('is-active');
    };

    init();
  } // end EdlpTheme()

  $(document).ready(function($) {
    var edlptheme = new EdlpTheme();
  });


})(jQuery, Drupal, drupalSettings);
