$(function(){
  if (typeof String.prototype.startsWith != "function") {
    String.prototype.startsWith = function(s) { return this.length >= s.length && this.substr(0, s.length) == s; };
    String.prototype.endsWith = function(s) { return this.length >= s.length && this.substr(this.length - s.length, s.length) == s; };
  }
  setTimeout('preprocessAllYoutubeVideos();', 200); // delay youtube video binding
});

function preprocessAllYoutubeVideos() {
  $('.deferred-image').each(
      function() {
        var img = $(this);
        if (img.attr('data-src') && img.attr('src') != img.attr('data-src')) {
          img.attr('src', img.attr('data-src'));
        }
      }
  );
  $('.youtube-video').each(preprocessYoutubeVideo);
}

function preprocessYoutubeVideo(index) {
  var thumb = $(this);
  var in_progress = false;
  var debug = true;
  var display = thumb.css('display'); /* see: http://bugs.jquery.com/ticket/8304 */
  var p = thumb.parent();
  var ix = p.children().index(thumb);
  var tw = thumb.width();
  var th = thumb.height();
  var t_src = thumb.attr("src");
  thumb.attr('title', 'Click to watch video...');
  thumb.after('<div class ="youtube-video-container"></div>');
  thumb.detach();
  var that = p.find(".youtube-video-container")
  .css({display: display, border: 'none', width: tw + 'px', height: th +'px'});
  var ie7_display = thumb.css('*display');
  if ($.browser.msie && display == 'inline-block') {
    that.css({'*display': 'inline', zoom: 1});
  }
  that.append(thumb);
  var zoom = $('<img class ="youtube-video-zoom-image" src="' + t_src + '" />').appendTo(that)
  .css({display: 'none', border: 'none', width: tw + 'px', height: th +'px'});
  var btn = $('<img class="close-button" src="img/close-button.gif" width="30" height="30"/>').appendTo(that)
  .css({display: 'none', border: 'none', position: 'absolute', 'z-index': 3});

  var src = 'http://www.youtube.com/embed/' + thumb.attr("data-youtube-id") + "?wmode=transparent";
  var vw = parseInt(thumb.attr("data-youtube-video-width"), 10);
  var vh = parseInt(thumb.attr("data-youtube-video-height"), 10);
  var vf = null;

  that.bind('click', showVideo);

  function windowWidth() {
    return window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
  }

  function windowHeight() {
    return window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
  }

  function windowVerticalScroll() {
    return window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
  }

  function showVideo() {
    if (in_progress) {
      return;
    }
    in_progress = true;
    zoom.css({
      position: 'absolute',
      left: that.position().left + 'px',
      top: that.position().top + 'px',
      display: 'block',
      opacity: 0,
      width: '64px',
      height: '36px'
    });
    var w = windowWidth();
    var h = windowHeight();
    var lf = (w - vw) / 2;
    var tp = Math.max(windowVerticalScroll() + (h - vh) / 2, 24);

    if (vf == null) {
      vf = $('<iframe class="youtube-video-player" src="' + src + '"></iframe>')
      .appendTo(that)
      .css({display: 'none', position: 'absolute',
            width: vw + 'px', height: vh + 'px',
            '-moz-border-radius': '4px', '-webkit-border-radius': '4px', 'border-radius': '4px',
            '-webkit-box-shadow': '0 0 9px 9px rgba(0,0,0,0.2)', '-moz-box-shadow': '0 0 9px 9px rgba(0,0,0,0.2)', 'box-shadow': '0 0  9px 9px rgba(0,0,0,0.2)',
            border: '9px solid black'});
    }
    vf.attr("src", src + '&autoplay=1');
    zoom.stop().animate({
      left: lf + 'px',
      top: tp + 'px',
      width: vw + 'px',
      height: vh + 'px',
      opacity: 1
    }, 1750, "swing", videoShown);
  }

  function videoShown() {
    var w = windowWidth();
    var h = windowHeight();
    var lf = (w - vw) / 2;
    var tp = Math.max(windowVerticalScroll() + (h - vh) / 2, 24);
    that.unbind('click');
    zoom.stop();
    zoom.css({display: 'none'});
    vf.css({
      position: 'absolute',
      display: 'block',
      left: lf + 'px',
      top: tp + 'px',
      width: vw + 'px',
      height: vh + 'px',
      opacity: 1
    });
    btn.css({
      position: 'absolute',
      display: 'block',
      left: btnLeft(lf),
      top: btnTop(tp)
    });
    btn.click(hideVideo);
    $(window).bind('resize', windowResized);
    in_progress = false;
  }

  function btnLeft(lf) { return (lf + vw) + 'px'; }

  function btnTop(tp) { return (tp - 15) + 'px'; }

  function hideVideo() {
    if (in_progress) {
      return;
    }
    in_progress = true;
    $(window).unbind('resize', windowResized);
    zoom.css({
      left: vf.position().left + 'px',
      top: vf.position().top + 'px',
      display: 'block'
    });
    vf.attr("src", src); /* to stop autoplay */
    vf.css({display: 'none'});
    vf.detach();
    vf = null;
    btn.css({display: 'none'});
    zoom.stop().animate({
      left: that.position().left + 'px',
      top: that.position().top + 'px',
      width: '64px',
      height: '36px',
      opacity: 0
    }, 1750, "swing", videoHidden);
  }

  function videoHidden() {
    zoom.stop();
    zoom.css({display: 'none'});
    btn.unbind('click');
    that.bind('click', showVideo);
    in_progress = false;
  }

  function windowResized() {
    if (vf.is(':visible') && btn.is(':visible')) {
      var w = windowWidth();
      var h = windowHeight();
      var lf = (w - vw) / 2;
      var tp = Math.max(windowVerticalScroll() + (h - vh) / 2, 24);
      vf.css({
        left: lf + 'px',
        top: tp + 'px'
      });
      btn.css({
        position: 'absolute',
        display: 'block',
        left: btnLeft(lf),
        top: btnTop(tp)
      });
    }
  }

}

