var te_cycle;
var te_paused;
var te_speed = 15000;
var te_pause = 20000;
var te_next_events;

$(document).ready(function(){
    //$('.todays-events-list').mouseover(te_pause_cycle);
    //$('.todays-events-list').mouseleave(te_resume_cycle);
    //cycle through hidden te-events if there are any
    var hiding =  $('.todays-events-list .hiding');
    if(hiding.length){
      te_start_cycle();
    }
});






function te_start_cycle(){
  cycle = setInterval(te_shuffle,te_speed);
}


function te_show_next(){
  var shown = $('.todays-events-list .shown');
  shown.removeClass('shown');
  shown.addClass('hiding');
  te_next_events.fadeIn(2000, te_show_done);
}

function te_show_done(){
  te_next_events.removeClass('hiding');
  te_next_events.addClass('shown');
}  

function te_pause_cycle(){
  clearInterval(te_cycle);
}

function te_resume_cycle(){
  te_start_cycle();
}

function te_shuffle() {
  var num_events = $('.todays-events-list li').length;
  var hiding =  $('.todays-events-list .hiding');
  var random_class = '';
  var shown = $('.todays-events-list .shown');
  max_tries = 100;
  te_next_events = $();
  $('#te-debug').html('');
  if(hiding.length){
    while(hiding.length && te_next_events.length < 3 && max_tries){
      max_tries -= 1;
      random_class = '.te-'+Math.ceil(Math.random() * num_events);
      event = hiding.filter(random_class);
      if(event){
        hiding = hiding.not(event);
        te_next_events = te_next_events.add(event);
      }
      //$('#te-debug').append(hiding.length+' '+te_next_events.length+' '+max_tries+' '+random_class+"\n");
      //var i; while(i<100000){ i+= 1; }
    }
    //Fill in with events already showing just in case there arent enough events today for 2 distinct sets of 3 
    max_tries = 100;
    while(te_next_events.length < 3 && max_tries){
      max_tries -= 1;
      random_class = '.te-'+Math.ceil(Math.random() * num_events);
      event = shown.filter(random_class);
      if(event){
        shown = shown.not(event);
        te_next_events = te_next_events.add(event);
      }
      shown = shown.not(random_class);
      te_next_events = te_next_events.add(random_class);
      //$('#te-debug').append(hiding.length+' '+te_next_events.length+' '+max_tries+' '+random_class+"\n");
      //var i; while(i<100000){ i+= 1; }
    }
  }
  
  //te_next_events = hiding;
  $('.todays-events-list .shown').fadeOut(2000,te_show_next);
}



