﻿$(document).ready(function () {

  if (Modernizr.video) {
    initVideo();
  } else {
    $('#flashPlayer').show();
  }

});


// Simple video toggle for the HTML5 video
function initVideo() {
  // REFACTOR?
  if ($('#videoPlayer').length > 0) {
      
      var $wrapper, $video, $button, state = 'start';

      $wrapper = $('#videoWrapper');
      $video = $('#videoPlayer');

      $wrapper.prepend('<div id="videoButton" class="play"></div>'); // add with JS, because without JS the 'button' makes no sense

      $button = $('#videoButton'); // the content of this link (<video>) is replaced by the flowplayer swf on non-html5 browsers
      
      /*
        when IE plays a video, it seems to promote it to the front, ignoring z-index, 
        meaning the html with click events above it dont fire. Forcing the redraw of the bg seems to force stack      
      */ 
      if (navigator.userAgent.indexOf('MSIE') != -1) {
        $video.hover(
	        function () {
	          $button.removeClass('play').removeClass('pause').addClass('pause');
	        },
	        function () {
            // not much to do here - should have used a onmouseover event instead
	        });
  		}
      
      // change the play/pause icons on hover
	    $button
      .hover(
        function () {          
          if (state == 'playing') {
            $(this).addClass("pause");
          } else if (state == 'paused') {
            $(this).addClass("play").removeClass('pause');
          }
        },
        function () {
          if (state == 'playing') {
            $(this).removeClass("pause");
          }
        }
      )
      .click(function () { 

        if (state == "playing") {
          $button.addClass("play");
          $video[0].pause();
        } else if (state == "paused") {
          $button.addClass("play");
          $video[0].play();
        } else {
          $button.removeClass("play");
          $video[0].play();
        }
      });      

      // handlers
      function fnPlaying() {
        console.log('playing');
        state = 'playing';        
        $button.removeClass("play").removeClass("pause");
      }
      function fnPause() {
        console.log('pause');
        state = 'paused';         
        $button.addClass("play").removeClass('pause');
      }
      function fnEnded() {
        console.log('ended');
        state = 'ended';        
        $button.addClass("play");
      }

      document.getElementById('videoPlayer').addEventListener('play', fnPlaying, false);
      document.getElementById('videoPlayer').addEventListener('pause', fnPause, false);
      document.getElementById('videoPlayer').addEventListener('ended', fnEnded, false);

    }

  }
