$(window).load(function() {

  // breite des slideshow ul errechnen
  sliderWidth = 0;
  $("img", '#slideshow').each(function(id, elem) {
    sliderWidth += $(elem).outerWidth() + 120;
  });

  // scrollbuttons anzeigen ?
  if (sliderWidth>$('#slideshow').width()) {
    $('.prev', '#scroller').css('visibility', 'visible');
    $('.next', '#scroller').css('visibility', 'visible');
  }

  // mouse down
  $('.prev', '#scroller').mousedown(clickPrevBtn);
  $('.next', '#scroller').mousedown(clickNextBtn);

  // mouse out
  $('.prev', '#scroller').mouseout(stopAnim);
  $('.next', '#scroller').mouseout(stopAnim);

  // mouse up
  $('#scroller').mouseup(stopAnim);

});

function stopAnim() {
  $('.content', '#slideshow').stop();
}

function restTime(sliderWidth, direction) {
  // geschwindikgeit abhängig von position
  var leftPos = (($('.content', '#slideshow').position().left));
  var interval = 1000;
  var maxLeft = (sliderWidth-$('#slideshow').width());
  if (direction == 'prev') {
    var restTime = parseInt(-(interval / maxLeft * leftPos));
  } else {
    var restTime = parseInt(interval - -(interval / maxLeft * leftPos));
  }
  return restTime;
}

function callback() {
  var leftPos = (($('.content', '#slideshow').position().left));
  var direction = (leftPos == 0 ? 'prev' : 'next');
  $('.'+direction, '#scroller').attr('src', '/img/products/arrow'+direction+'.disabled.gif');
  $('.'+direction, '#scroller').css('cursor', 'default');
}

function clickPrevBtn() {
  $('.next', '#scroller').attr('src', '/img/products/arrownext.gif');
  $('.next', '#scroller').css('cursor', 'pointer');

  $('.content', '#slideshow').animate({left: 0}, restTime(sliderWidth, 'prev'), 'swing', callback);
  return false;
}

function clickNextBtn() {
  $('.prev', '#scroller').attr('src', '/img/products/arrowprev.gif');
  $('.prev', '#scroller').css('cursor', 'pointer');

  var maxLeft = -(sliderWidth-$('#slideshow').width());
  $('.content', '#slideshow').animate({left: maxLeft}, restTime(sliderWidth, 'next'), 'swing', callback);
  return false;
}
