/**
 * $LastChangedDate$
 * $Rev$
 * $Author$
 * $HeadURL$
 */

/**
 * Javascript that controls the youtube player
 */
  //
  // YouTube JavaScript Player With Playlist
  // http://911-need-code-help.blogspot.com/2009/10/youtube-javascript-player-with-playlist.html
  // Revision 1 [2009-10-12]
  //
  // Prerequisites
  // 1) Create following elements in your HTML:
  // -- a) ytplayer: a named anchor
  // -- b) ytplayer_div1: placeholder div for YouTube JavaScript Player
  // -- c) ytplayer_div2: container div for playlist
  // 2) Include SWFObject library from http://code.google.com/p/swfobject/
  //
  // Variables
  // -- ytplayer_playlist: an array containing YouTube Video IDs
  // -- ytplayer_playitem: index of the video to be played at any given time
  //
  var ytplayer_playitem = 0;
  swfobject.addLoadEvent( ytplayer_render_player );
  function ytplayer_render_player( )
  {
      //set start based on hash
      if (window.location.hash) {
        ytplayer_playitem = parseInt(window.location.hash.substring(1));
      }
      if (isNaN(ytplayer_playitem)) {
          ytplayer_playitem = 0;
      }
      document.title = page_titles[ytplayer_playitem];

      swfobject.embedSWF
    (
      'http://www.youtube.com/v/' + ytplayer_playlist[ ytplayer_playitem ] + '&enablejsapi=1&rel=0&fs=1&autoplay=1&color1=0xffffff&color2=0xffffff&iv_load_policy=3&showinfo=0',
      'ytplayer_div1',
      '510',
      '311',
      '8',
      null,
      null,
      {
        allowScriptAccess: 'always',
        allowFullScreen: 'true',
        wmode: 'transparent'
      },
      {
        id: 'ytplayer_object'
      }
    );
    $("#nowplaying").html(song_info[ ytplayer_playitem ]);
    $("#buyLinksList").html(buy_links[ ytplayer_playitem ]);
    $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
  }
  function ytplayer_playlazy( delay )
  {
    //
    // Thanks to the anonymous person posted this tip:
    // http://www.tipstrs.com/tip/1084/Static-variables-in-Javascript
    //
    if ( typeof ytplayer_playlazy.timeoutid != 'undefined' )
    {
      window.clearTimeout( ytplayer_playlazy.timeoutid );
    }
    ytplayer_playlazy.timeoutid = window.setTimeout( ytplayer_play, delay );
  }

  //play with no delay
  function ytplayer_play( )
  {
    var o = document.getElementById( 'ytplayer_object' );
    if ( o )
    {
      o.loadVideoById( ytplayer_playlist[ ytplayer_playitem ] );
    }
    $("#nowplaying").html(song_info[ ytplayer_playitem ]);
    $("#buyLinksList").html(buy_links[ ytplayer_playitem ]);
    //update the URL with the song position
    window.location.hash = ytplayer_playitem;
    $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
    document.title = page_titles[ytplayer_playitem];
  }
  //
  // Ready Handler (this function is called automatically by YouTube JavaScript Player when it is ready)
  // * Sets up handler for other events
  //
  function onYouTubePlayerReady( playerid )
  {
    var o = document.getElementById( 'ytplayer_object' );
    if ( o )
    {
      o.addEventListener( "onStateChange", "ytplayer_statechange" );
      o.addEventListener( "onError", "ytplayer_error" );
    }
  }
  //
  // State Change Handler
  // * Sets up the video index variable
  // * Calls the lazy play function
  //
  var states = ['END', 'PLAY', 'STOP', 'BUFFER'];
  function ytplayer_statechange( state )
  {
      if (state < 0 | state > 3) {
          //do nothing
          return;
      }
      data_dict = {action: states[state],
              siteid: document.location.hostname,
              client_timestamp: (new Date().getTime()/1000),
              song_media: song_ids[ytplayer_playitem],
              sessionid: session_id,
              playlist_uid: playlist_uid,
              player_type: 1};
      if (typeof(auth_user) !== 'undefined') {
          data_dict['userid'] = auth_user;
      }
      //@TODO: add callback that deals with failed stats recording
      $.getJSON("/json/record_stats",
                data_dict);
      if ( state == 0 )
    {
      $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
      ytplayer_playitem += 1;
      ytplayer_playitem %= ytplayer_playlist.length;
      ytplayer_play();
    }
  }
  //
  // Error Handler
  // * Sets up the video index variable
  // * Calls the lazy play function
  //
  function ytplayer_error( error )
  {
    if ( error )
    {
      data_dict = {action: 'PLAY_ERROR',
              siteid: document.location.hostname,
              client_timestamp: (new Date().getTime()/1000),
              song_media: song_ids[ytplayer_playitem],
              sessionid: session_id,
              playlist_uid: playlist_uid,
              player_type: 1};
      if (typeof(auth_user) !== 'undefined') {
          data_dict['userid'] = auth_user;
      }
      //@TODO: add callback that deals with failed stats recording
      $.getJSON("/json/record_stats",
                data_dict);
      $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
      ytplayer_playitem += 1;
      ytplayer_playitem %= ytplayer_playlist.length;
      ytplayer_playlazy( 5000 );
      //@TODO: notify server of error
    }
  }

  //play by playlist index
  function ytplayer_playbyindex(videoid) {
      $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
      ytplayer_playitem = videoid;
      ytplayer_play();
  }
  //
  // skip skip_val number of items in playlist
  // * Sets up the video index variable
  // * Calls the lazy play function
  //
  function ytplayer_skip( skip_val )
  {
      $('#trackname_'+ytplayer_playitem).toggleClass('trBold');
      ytplayer_playitem += ytplayer_playlist.length + skip_val;
      ytplayer_playitem %= ytplayer_playlist.length;
      ytplayer_play();
  }
