$(document).ready(function(){
  prepareHero ();
  preparePromos ();
});

var onYouTubePlayerReady, youTubeStateChange, youTubeError, playHeroVideoPlayer, pauseHeroVideoPlayer;
function prepareHero (){
  var slide_width = 900;
  var currentSlide = 0;
  var ytapi_prefix = "ytapi";
  var ytdom_prefix = "ytplayer";
  var ytph_prefix = "ytplayerplaceholder";
  var timeline_start = -6;
  var timeline_stop = 274;
  var $tray = $(document.getElementById('slide_tray'));
  var $win = $(window);
  //set the contents of #video_slide_template to the named template 'video_slide'
  $.template('video_slide', document.getElementById('video_slide_template'));
  //set the contents of #image_slide_template to the named template 'image_slide'
  $.template('image_slide', document.getElementById('image_slide_template'));
  
  //seconds for slideshow auto-advance
  var auto_time = 6000;
  var auto_timer = false;
  
  
  var tray_max_left, tray_cur_left, $next, $prev, btn_width, indic_cont, next_dis;

  for ( var i = 0 ; i < slide_data.length ; i++ ) {
    if (slide_data[i].type == 'video') {
      slide_data[i].ytph_id = ytph_prefix+i;
      slide_data[i].$dom = $.tmpl('video_slide', slide_data[i]).appendTo($tray);
    } else if (slide_data[i].type == 'image') {
      $.tmpl('image_slide', slide_data[i]).appendTo($tray);
    }
  }

  function initSlideShow() {
    $tray.css('width', slide_width*slide_data.length);
    tray_max_left = -slide_width*(slide_data.length-1);
    $next = $(document.getElementById('next-slide')).click(forward);
    $prev = $(document.getElementById('prev-slide')).click(previous).fadeTo(0, .3).addClass('disabled');
    $loadingSheild = $(document.getElementById('hp_hero_loading_sheild'));
    btn_width = $next.width();
    indic_cont = $(document.getElementById('hp_hero_indicators'));
    for ( var i = 0 ; i < slide_data.length ; i++ )
    {
      if (slide_data[i].type == 'video') {
        load_with_yt_api(slide_data[i]);
      }
      slide_data[i].indicator = $(document.createElement('div')).attr('data-i', i).addClass('indicator').appendTo(indic_cont).click(inicatorClick);
    }
    progressComplete(0);
    $loadingSheild.delay(250).fadeTo(400, 0, function(){$loadingSheild.remove(); setAutoComplete()});
  }

  var yt_api_loaded = true,
      yt_api_ready = false,
      yt_api_ready_timer,
      yt_unloaded_players = [];
  
  function load_with_yt_api(slide_data)
  {
    
    document.getElementById(slide_data.ytph_id).src = 'http://www.youtube.com/embed/'+slide_data.yt_video_id;
    
    /**
    
    yt_unloaded_players.push(slide_data);
    if (!yt_api_loaded) {
      onYouTubePlayerAPIReady = function(){
        console.log('API ready');
        yt_api_ready = true;
      }
      var tag = document.createElement('script');
      tag.src = "http://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      yt_api_loaded = true;
    }
    if (!yt_api_ready) {
      if (!yt_api_ready_timer) {
        yt_api_ready_timer = setInterval(function(){
          if (yt_api_ready) yt_api_process_unloaded_players();
          clearInterval(yt_api_ready_timer);
        }, 500);
      }
    } else {
      yt_api_process_unloaded_players();
    }
    
    **/
  }
  
  function yt_api_process_unloaded_players()
  {
    for(var i = 0; i < yt_unloaded_players.length; i++ )
    {
      
      $(document.getElementById(yt_unloaded_players[i].ytph_id)).attr('src', 'http://www.youtube.com/embed/'+yt_unloaded_players[i].yt_video_id+'?wmode=opaque');
    }
    yt_unloaded_players = [];
  }
  
  function inicatorClick () {
    $('.indicator', indic_cont).removeClass('active');
    progress($(this).addClass('active').attr('data-i')-currentSlide);
  }
  
  function setAutoComplete () {
    stopAutoComplete();
    auto_timer = setTimeout(
      auto_forward,
      auto_time
    );
  }
  
  function auto_forward () {
    if (currentSlide+1 < slide_data.length)
      forward();
    else
      progress(-(slide_data.length-1));
    setAutoComplete();
  }
  
  function stopAutoComplete () {
    if (auto_timer)
      clearTimeout(auto_timer);
    auto_timer = false;
  }
  
  function progressComplete(left) {
    tray_cur_left = left;
    indic_cont.children().removeClass('active').filter('[data-i='+currentSlide+']').addClass('active');
    next_dis = $next.hasClass('disabled');
    var prev_dis = $prev.hasClass('disabled');
    if (left == tray_max_left && !next_dis)
      $next.stop().fadeTo(150, .3).addClass('disabled');
    else if (left != tray_max_left && next_dis)
      $next.stop().fadeTo(150, 1).removeClass('disabled');
    
    if (left == 0 && !prev_dis)
      $prev.stop().fadeTo(150, .3).addClass('disabled');
    else if (left != 0 && prev_dis)
      $prev.stop().fadeTo(150, 1).removeClass('disabled');
  }

  function progress(delta) {
    //make sure current video is paused
    //if (slide_data[currentSlide].type == 'video')
      //slide_data[currentSlide].$pause.click();

    var new_left = tray_cur_left-(slide_width*delta);

    if (new_left < tray_max_left)
      new_left = tray_max_left;
    else if (new_left > 0)
      new_left = 0;

    if (new_left !== tray_cur_left) {
      $tray.stop().animate({left:new_left});
      currentSlide += delta;
    }
    progressComplete(new_left);
  }
  function forward() {
    stopAutoComplete();
    progress(1);
  }
  function previous() {
    stopAutoComplete();
    progress(-1);
  }
  $(window).load(initSlideShow); 
}

function preparePromos () {
  var $next = $(document.getElementById('hp_promos_next'));
  var $prev = $(document.getElementById('hp_promos_prev'));
  var $tray = $(document.getElementById('hp_promos_tray'));
  var $promos;
  var promo_width;
  var tray_max_left;
  var visible_promos = 3;
  var disabled_arrow_opacity = .3;
  
  function initPromos() {
    $next.click(nextset);
    $prev.click(prevset);
    $promos = $tray.children('li');
    promo_width = $promos.outerWidth();
    var tray_width = promo_width*$promos.length;
    $tray.css('width', tray_width);
    tray_max_left = (-tray_width)+(promo_width*visible_promos);
    buttonDisabler(0);
  }

  function nextset() {
    if (!$next.hasClass('disabled'))
      progress(3);
  }
  
  function prevset() {
    if (!$prev.hasClass('disabled'))
      progress(-3);
  }

  function progress(delta){
    var cur_left = $tray.position().left;
    var new_left = cur_left-(delta*promo_width);
    if (new_left < tray_max_left)
      new_left = tray_max_left;
    if (new_left > 0)
      new_left = 0;
    if (new_left != cur_left)
      $tray.stop().animate({left:new_left}, {duration:400});
    buttonDisabler(new_left);
  }
  
  function buttonDisabler(left){
    if (left == tray_max_left)
      $next.fadeTo(0, disabled_arrow_opacity).addClass('disabled');
    else
      $next.fadeTo(0, 1).removeClass('disabled');
    if (left == 0)
      $prev.fadeTo(0, disabled_arrow_opacity).addClass('disabled');
    else
      $prev.fadeTo(0, 1).removeClass('disabled');
  }
  
  $(window).load(initPromos);
}
