// what: the visual video scanner in the sidebar
// author: paul irish
// license: cc-wrapped gpl

var SCANNER = {
  isInAjax    : false,
  scansUrl    : '/parts/latest_scans',
  interval    : 2000,                   // how many milliseconds between visual updates
  intervalPtr : undefined,
  howManyPer  : 2,                      // how many to move at a time?
  animDuration: 500                     // length of slide animation
};

SCANNER.showScanActivity = function(){
  if (SCANNER.isInAjax) return;
  
  var videosLeft = $('#holdingDiv li');
  
  if (videosLeft.length < SCANNER.howManyPer){
    SCANNER.getMoreScans();
  }
  else {
    if ($('#scanner li').length > 6 ){ videosLeft = videosLeft.slice(0,SCANNER.howManyPer); } // if there are items there already, only move in the first few
    videosLeft.hide().prependTo('#scanner').slideDown( SCANNER.animDuration ); // get two ones at a time and slide them in.
    
    $('#latest_scans').removeAttr('style'); // clear the loading image.
    
    // remove videos if therea are more than 25. this is to avoid poor performance and mem leaks.
    var currScans = $('#scanner li');
    if (currScans.length >= 25) {currScans.slice(25,currScans.length).remove();}
  }
};

SCANNER.getMoreScans = function(){
  
  SCANNER.isInAjax = true;
  
  $.ajax({
    url: SCANNER.scansUrl,
    success: function(html){
      $("#holdingDiv").append(html);   // throw result into a holdingdiv that's hidden
      SCANNER.isInAjax = false;
    }
  });
  
};

SCANNER.init = function(){
  if ($('#scanner').length){
  	SCANNER.showScanActivity();
    SCANNER.intervalPtr = setInterval( SCANNER.showScanActivity , SCANNER.interval ); 
  }
  
} 


$(document).ready(function(){
  $('#searchInput').focus(function(){
    if ($(this).val() == 'video search') $(this).val('');
  }).blur(function(){
    if ($(this).val() == '') $(this).val('video search');
  });
  
  SCANNER.init();
});

