var totalSlides = 0;
var currentSlide = 1;
var contentSlides = "";
var tiempo_parcial = new Date();

$(document).ready(function(){
  $("#slideshow-previous").click(showPreviousSlide);
  $("#slideshow-next").click(showNextSlide);
  
  var totalWidth = 0;
  contentSlides = $(".slideshow-content");
  contentSlides.each(function(i){
    totalWidth += this.clientWidth;
    totalSlides++;
  });
  $("#slideshow-holder").width(totalWidth);
  $("#slideshow-scroller").attr({scrollLeft: 0});
  aleatorio();
  updateButtons();
});

window.setInterval('tiempo()',1000);

function tiempo()
{
if(totalSlides > 1){
var tiempo_total = new Date();
var intervalo = tiempo_total - tiempo_parcial;
if(intervalo > 10000) {
showNextSlide(); }
}
}

function showPreviousSlide()
{
tiempo_parcial = new Date();
  if(currentSlide > 1) {
    currentSlide--;
  } else {
  	currentSlide = totalSlides;
  }
  updateContentHolder();
  updateButtons();
}

function showNextSlide()
{
tiempo_parcial = new Date();
  if(currentSlide < totalSlides) {
    currentSlide++;
  } else {
  	currentSlide = 1;
  }
  updateContentHolder();
  updateButtons();
}

function aleatorio()
{
  var scrollAmount = 0;
  var rand = Math.floor(Math.random()*totalSlides);
  currentSlide = rand;
  contentSlides.each(function(i){
    if(currentSlide > i) {
      scrollAmount += this.clientWidth;
    }
  });
  $("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1);
  currentSlide++;
}

function updateContentHolder()
{
  var scrollAmount = 0;
  contentSlides.each(function(i){
    if(currentSlide - 1 > i) {
      scrollAmount += this.clientWidth;
    }
  });
  $("#slideshow-scroller").animate({scrollLeft: scrollAmount}, 1000);
}

function updateButtons()
{
if(totalSlides > 1){
  $("#slideshow-next").show();
  $("#slideshow-previous").show();
} else {
  $("#slideshow-next").hide();
  $("#slideshow-previous").hide();
}	
}
