
var vs_seeking = 0;
var vs_seek_sec = 0;

function video_stream_load() {
  if (function_exists('$f')) {
    var F = $f();
    F.load();
  }
}

function video_stream_seconds_to_timecode(secs) {
  var h, m, s, r;
  h = lpad(Math.floor(secs / 3600), 2, '0');
  r = secs % 3600;
  m = lpad(Math.floor(r / 60), 2, '0');
  r = r % 60;
  s = lpad(r, 2, '0');
  return h+':'+m+':'+s;
}

function video_fp_ms() { return Math.round($f().getTime() * 1000); }

function video_get_meta(typ) {
  if (typeof(eval('video_'+typ)) != 'undefined') {
    return eval('video_'+typ);
  }
  return $("#video-"+typ).html()
}

function video_seek_onstart(F, seconds) {
  F.pause();
  seekInterval = window.setInterval(function() {
    if (F.isPaused()) {
      window.clearInterval(seekInterval);
      F.seek(seconds);
      F.play();
      F.onStart(function() {});
    }
  }, 10);
}

function video_stream_goto(sec) {
  var vhtml5 = $("#idea-video-player-html5");
  if (vhtml5.size() > 0) {
    video_html5_goto_time(sec);
  }
  else if (function_exists('$f')) {
    var F = $f();

    if (F.isLoaded()) {
      video_stream_goto_time(sec);
    }
    else {
      $f().load(function() { video_stream_goto_time(sec); });
    }
  }
  return false;
}
var _video_html5_goto_sec = 0;
function video_get_html5_video_dom() {
  var V = $("#idea-video-player-html5");
  return (V.size() > 0) ? V[0] : false;
}

function video_html5_goto_listeners(vid, adding) {
  if (adding) {
    vid.addEventListener('canplaythrough', video_html5_can_play, false);
    vid.addEventListener('canplay', video_html5_can_play, false);
    vid.addEventListener('load', video_html5_can_play, false);
  }
  else {
    vid.removeEventListener('canplaythrough', video_html5_can_play, false);
    vid.removeEventListener('canplay', video_html5_can_play, false);
    vid.removeEventListener('load', video_html5_can_play, false);
  }
}

function video_html5_can_play() {
  var vid = video_get_html5_video_dom();
  video_html5_goto_listeners(vid, false);
	vid.currentTime = _video_html5_goto_sec;
  if (vid.paused) {
    vid.play();
  }
}

function video_html5_goto_time(t) {
  _video_html5_goto_sec = t;
  var vid = video_get_html5_video_dom();

  if(vid.readyState == 0) {
    video_html5_goto_listeners(vid, true);
    vid.play();
  }
  else if(vid.readyState !== 4){ //HAVE_ENOUGH_DATA
    vid.pause();
		video_html5_goto_listeners(vid, true);
	} else {
		vid.currentTime = _video_html5_goto_sec;
    if (vid.paused) {
      vid.play();
    }
	}
}

var _chp_seek = -1;
function video_stream_goto_time(t) {
  if (F = $f()) {
    if (F.isPlaying()) {
      F.seek(t);
    }
    else {
      var pl = F.getPlaylist();
      var i = 0;
      for (i=0; i<pl.length; i++) {
        if (typeof(pl[i].is_screenshot) == 'undefined' || !pl[i].is_screenshot) {
          _chp_seek = t;
          pl[i].onBegin(function() { if (_chp_seek >= 0) { $f().seek(_chp_seek); _chp_seek = -1; } });
          break;
        }
      }
      F.play(0);
    }
  }
  return false;
}

function video_stream_goto_chapter(tag) {
  var index=-1, clip, F = $f();
  playlist = F.getPlaylist()

  for (i in playlist) {
    clip = playlist[i];
    if (clip.video_tag == tag) {
      index = clip.index;
    }
  }

  if (index >=0) {
    F.play(parseInt(index));
  }
}
function video_stream_chapter_num(num) {
  if (!isNaN(num)) {
    video_stream_goto_chapter("chpt_"+num);
  }
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_on_begin(n, title) {
  t = $f().getTime();
  if (t < 1) {
    video_stream_chapter_show_info(n, title);
  }
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_on_start(n, title) {
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_on_pause(n) {
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_on_finish(n) {
  F.play(0);
  F.pause();
  video_stream_show_no_access_box();
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_show_info(n,title) {
  video_stream_hide_no_access_box();
  F = $f();
  F.getPlugin("clip_intro").css('height', '360').setHtml('<p></p><p></p><p class="chapter-num">Chapter '+n+'</p><p>'+title+'</p>').animate({opacity:1}, 250);
}

/**
 * When a chapter starts playing
 */
function video_stream_chapter_hide_info() {
  F = $f();
  F.getPlugin("clip_intro").setHtml('<p></p>').animate({opacity:0}, 500).css('height', '1');
}

/**
 * show orange box
 */
function video_stream_show_no_access_box() {
  F = $f();
  F.getPlugin("access_denied_outer").animate({opacity:1}, 10);
  F.getPlugin("access_denied").animate({opacity:1}, 10);
}

/**
 * show orange box
 */
function video_stream_hide_no_access_box() {
  F = $f();
  F.getPlugin("access_denied_outer").animate({opacity:0}, 10);
  F.getPlugin("access_denied").animate({opacity:0}, 10);
}



var orig_playlist;
function video_stream_init_chapters() {
  if (!function_exists('$f')) {
    return;
  }
  var F = $f();
  if (typeof(F) == 'undefined') {
    return;
  }
  orig_playlist = F.getPlaylist()
  $('.chapter-list a.video-chapter').each(function() {
    var chpt = $(this).attr('alt');
    $(this).click(function() {
      video_stream_goto_chapter(chpt);
    })
    .attr('href', 'javascript:void(0)');
  });
}

function video_stream_filter(a, nid, filt) {
  href = '/video_stream/ajax/'+nid+'/related/'+filt;
  $("a.related-video-filter").removeClass('active');
  $(a).addClass('active');

  $('.related-video-throbber').addClass('throbbing');
  $.getJSON(href, {'limit': 3}, function(R) { video_stream_filter_callback(R, a, nid, filt, 0, 0, 0); });
}
function video_stream_filter_more(a, nid, filt, n, t, a_more) {
  href = '/video_stream/ajax/'+nid+'/related/'+filt;
  $('.related-video-throbber').addClass('throbbing');
  $(a_more).addClass('throbbing');
  $.getJSON(href, {'limit': 10+n}, function(R) { video_stream_filter_callback(R, a, nid, filt, n, t, a_more); });
}

function video_stream_update_related_description(data) {
  var desc = data.term_desc;
  var curr_links = data.term_names;
  $("#related-videos .related-video-description").html('<div class="related-intro">'+desc+'</div> '+curr_links);
}

function video_stream_filter_callback(R, a, nid, filt, n, t, a_more) {
  if (R.status) {
    var data = R.data;

    var curr_count = $('#related-videos .video_list .video_list_item').size();
    var new_data = $('<div style="display:none">'+data.html+'</div>');
    var new_count = $('.video_list_item', new_data).size();

    var end_func = function() {
        video_stream_update_related_description(R.data);

        $('#related-videos .video_list').empty();
        $('#related-videos .video_list').append(data.html);

        var nItems = parseInt(R.data.num_items);
        var nTotal = parseInt(R.data.total_items);
        if (nItems < nTotal) {
          video_stream_add_more_link(nid, filt, nItems, nTotal);
        }

        $('#related-videos .video_list').animate({'opacity':1}, 150, 'linear', function() {
          $('.related-video-throbber').removeClass('throbbing');
          if (a_more) {
            $(a_more).removeClass('throbbing');
          }
        });
    }

    $('#related-videos .video_list').animate({'opacity':0}, 150, 'linear', function() { end_func() });
  }
  else {

    $('.related-video-throbber').removeClass('throbbing');
    if (a_more) {
      $(a_more).removeClass('throbbing');
    }
  }
}

function video_stream_add_more_link(nid, filt, nItems, nTotal) {
  var nDiff  = nTotal - nItems;
  var more_div = $('<div class="related-videos-more"></div>');
  var more = $('<a href="javascript:void(0)" class="throbber">'+nDiff+' more videos...</a></div>').click(function() { video_stream_filter_more(0,nid,filt,nItems,nTotal, this); }).appendTo(more_div);
  $('#related-videos .video_list').append(more_div);
}



function on_video_stream_filter(nid, filt) {
  href = '/video_stream/ajax/'+nid+'/related/'+filt;

  $('.related-video-throbber').addClass('throbbing');
  $.getJSON(href, {'limit': 3}, function(R) { video_stream_block_filter_callback(R, nid, filt); });
}

function video_stream_block_filter_callback(R, nid, filt) {

  if (R.status) {
    var data = R.data;
    var end_func = function() {
        $('#related_videos .video_list').empty();
        $('#related_videos .video_list').append(data.html);
        $('#related_videos .video_list').animate({'opacity':1}, 150, 'linear', function() {});
    }

    $('#related_videos .video_list').animate({'opacity':0}, 150, 'linear', function() { end_func() });
    $('.related-video-throbber').removeClass('throbbing');
  }
  else {
    $('.related-video-throbber').removeClass('throbbing');
  }
}


function video_stream_init() {
  var nid = $("#video-nid").html();

  setTimeout("video_stream_init_chapters()", 250);

  $("a.related-video-filter").each(function() {
    var href, param, index, end_index, filt='';
    href  = $(this).attr('href');
    param = 'filter-related';
    index = href.indexOf(param);
    if (index >= 0) {
      end_index = href.indexOf('&', index);
      if (end_index < 0) {
        end_index = href.indexOf('#', index);
      }
      filt = href.substring(index+param.length+1, end_index);
    }
    $(this).click(function() {
      video_stream_filter(this, nid, filt);
    }).attr('href', 'javascript:void(0)');
    $(this).removeClass('active');
  });

  $("a.related-video-filter.default").addClass('active');

  $("#cec-logo-list").mouseover(function(){ $(this).addClass("hover");});
  $("#cec-logo-list").mouseout(function(){ $(this).removeClass("hover");});

  $("#cec-logo-list .arrow").hover(function(){$(this).addClass("hover");}, function(){$(this).removeClass("hover");});
  $("#cec-logo-list .arrow").click(function() { video_stream_expand_cec_logos(); });
}

function video_stream_expand_cec_logos() {
  if($("#cec-logo-list").hasClass('expanded')) {
    $("#cec-logo-list").removeClass('expanded');
  }
  else {
    $("#cec-logo-list").addClass('expanded');
  }
}


var _tracker_range_id = -1;
var _tracker_cuepoints = new Array();
var _pause_prompt = 0;
var _pause_prompt_showing = 0;
var _video_play_count = 1;

function video_stream_tracker(cuepoint) {
  if (_tracker_range_id < 0) {
    video_stream_tracker_new_range(cuepoint);
  }
  // update the range end poitn
  _tracker_cuepoints[_tracker_range_id].end = cuepoint;

  // log the range end point
  _video_stream_log_range(_tracker_range_id);
}

function video_stream_tracker_on_finish(cuepoint) {
  // log the range end point
  video_stream_tracker(cuepoint);

  // update the play hash
  _video_play_count++;
  var hash   = $("#video-hash").html();
  var i = hash.indexOf("-");
  if (i>0) { hash = hash.substring(0, i); }
  $("#video-hash").html(hash +"-"+_video_play_count);
}

function video_stream_tracker_new_range(cuepoint) {
  // up the range ID
  _tracker_range_id++;

  // create the range tracker
  _tracker_cuepoints[_tracker_range_id] = {start: cuepoint, end: cuepoint};

  // log the range creation
  _video_stream_log_range(_tracker_range_id);
}

function _video_stream_log_range(_tracker_range_id) {
  var nid    = video_get_meta('nid');
  var hash   = video_get_meta('hash');
  var refer  = video_get_meta('referer');
  var range  = _tracker_cuepoints[_tracker_range_id];
  var href   = "/video_stream/tracker/"+nid+"/"+hash+"/"+_tracker_range_id+"/"+range.start+"/"+range.end;
  var params = {
    os: $.browser.OS(),
    browser: $.browser.browser() +' '+ $.browser.version.string(),
    flash_ver: String(flashembed.getVersion()).replace(',','.'),
    referer: escape(refer)
  };
  $.getJSON(href, params, function(R) { });
}


if (Drupal.jsEnabled) {
  $(document).ready(function() {

    video_stream_init();

  });
}
