var rtrim = function(str, len) {
  if (false == ('string' == typeof str)) {
    return false;
  }
  out = '';
  newLen = parseInt(str.length) + parseInt(len);
  out = str.substring(0,newLen);
  return out;
}

var slideshow_player = new Object();

function onYouTubePlayerReady(playerId) {
  short_id = rtrim(playerId,-7);
  player = document.getElementById(short_id);

  slideshow_player[short_id] = player;

  if (player.addEventListener) {
    player.addEventListener('onStateChange', 'player_state_change');
  } else if (player.addachEvent) {
    player.attachEvent('onStateChange', 'player_state_change'); 
  }
}

function player_state_change(new_state) {
  switch (new_state) {
    case 1: // playing
      $('.gallery-pane-video:not(.ui-tabs-hide) > .details').animate({
        bottom: '-80px'
      }, 1000, 'easeInExpo');
      $('.gallery-list').unbind();
      break;
    case 2: // paused
      $('.gallery-pane-video:not(.ui-tabs-hide) > .details').animate({
        bottom: '0'
      }, 1000, 'easeInExpo');
      bind_slideshow_hover();
  }
}

function slideshow_rotate(obj) {
  switch (obj.action) {
    case 'play':
      $(obj.selector).tabs('rotate', 5000, true);
      break;
    case 'pause':
      $(obj.selector).tabs('rotate', 0, false);
      break;
  }
}

function bind_slideshow_hover() {
  // stop rotation while hovering and resume when hovering stops
  $('.gallery-list').hover(
    function() {
      slideshow_rotate({
        selector: '.gallery-list',
        action: 'pause'
      });
    },
    function() {
      slideshow_rotate({
        selector: '.gallery-list',
        action: 'play'
      });
    }
  );
}

$(function() {
  var gallery_video = new Object;

  // set up tabs
  $('.gallery-list').tabs({
    show: function(evt, ui) {
      $('.gallery-pane-video:not(.ui-tabs-hide) > .details').css('bottom','0');
      if ('undefined' != typeof gallery_video.tagName && 'OBJECT' == gallery_video.tagName) {
        if (-1 != gallery_video.getPlayerState()) {
          gallery_video.pauseVideo();
        }
      }
      $video = $('#gallery-pane-'+ui.index).find('#slideshow-video-'+ui.index);

      if ('undefined' != typeof $video[0] && 'OBJECT' == $video[0].tagName) {
        gallery_video = $video[0];
      }
    }
  });

  // begin slideshow rotation
  slideshow_rotate({
    selector: '.gallery-list',
    action: 'play'
  });

  bind_slideshow_hover();
});

