// Configure require.js to use video.js and dash.js (https://github.com/videojs/video.js/blob/stable/docs/guides/setup.md)
// (https://github.com/Dash-Industry-Forum/dash.js)
require.config({
  'paths': {
    'video-js': "../../webjars/video-js/4.11.4/video.js",
    'dash-webm': "../../webjars/dash.js/1.4/contrib/webmjs/dash.webm.min.js",
    'videojs-dashjs': "../../webjars/dash.js/1.4/contrib/videojs/videojs-tech-dashjs.js"
  }
});

// Load the video-js css file.
function loadCss(url) {
  var link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  document.getElementsByTagName('head')[0].appendChild(link);
}

// Set up DASH player.
function setupPlayer(videoDashID) {
  // If the dash is not supported on the browser, play an flv video.
  if (videojs.Dashjs.isSupported()) {
    // Initalize the video.js player.
    var myPlayer = videojs(videoDashID, {context: new Webm.di.WebmContext()});
  } else {
    var flvVideoURL = document.getElementById(videoDashID).getElementsByClassName('flv-video-url')[0].value;
    var sourceElement = document.getElementById(videoDashID).getElementsByTagName('source')[0];
    sourceElement.setAttribute('src', flvVideoURL);
    sourceElement.setAttribute('type', 'video/x-flv');
    videojs(videoDashID);
  }
}

require(['jquery', 'dash-webm', 'video-js'], function($, dashwebm, videojs) {
  loadCss("../../webjars/video-js/4.11.4/video-js.min.css");
  videojs.options.flash.swf = "../../webjars/video-js/4.11.4/video-js.swf";
  require(['videojs-dashjs'], function(videojsdash) {
    $(function() {
      // Initialize DASH videos.
      $('video.dashvideo').each(function(index) {
        var videoDashID = 'dash-video' + index;
        $(this).attr('id', videoDashID);
        setupPlayer(videoDashID);
      });
    });
  });
});
