jQuery(function($){
  var currentSlide = $('#carousel-wrap .container .item:first-child');
  
  function carousel_update_links(){
    $('#carousel-wrap #links a').removeClass('act')
    id = $(currentSlide).attr('id')
    $('#carousel-wrap #links #' + id).addClass('act')
  }
  
  $.each($('#carousel-wrap .container .item'), function(index, value) {
    $('#carousel-wrap #links').append('<a id="' + $(value).attr('id') + '"></a>');
  })
  
  carousel_update_links()
  
  $('#carousel-wrap #links a').click(function(){
    index_1 = $(currentSlide).attr('id').replace('item_','')
    currentSlide = $('#carousel-wrap .container').find('#' + $(this).attr('id'))
    index_2 = $(currentSlide).attr('id').replace('item_','')
    path_length = Math.abs(index_1 - index_2)
    carousel_update_links()
    $('#carousel').stop().scrollTo( currentSlide, 2000 * path_length , { easing: 'elasout' });
  })
  
  
  var slidesNum = $('#carousel-wrap .container').children().size()
  $('#carousel-wrap .container').width($('#carousel-wrap').width());
  $('#carousel-wrap .container .item').width($('#carousel-wrap').width());

  $('#carousel-wrap .container').css('display', 'block')
  
  $('#carousel-wrap #carousel').stop().scrollTo(currentSlide, 0);
  
  $('#carousel-wrap').resize(function() {
    $('#carousel-wrap #carousel').stop().scrollTo(currentSlide, 0);
    
    $('#carousel-wrap .container').width($('#carousel-wrap').width());
    $('#carousel-wrap .container .item').width($('#carousel-wrap').width());
  });
  
  
  $.easing.elasout = function(x, t, b, c, d) {
    $('debug').html(t)
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/20; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-20*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
  };
  
  $('#carousel-wrap #next').click(function(){ 
    if(!$(currentSlide).is('#carousel-wrap .container div:last-child')){
      currentSlide = $(currentSlide).next()
      carousel_update_links()
    }
    $('#carousel').stop().scrollTo( currentSlide, 2000 , { easing: 'elasout' });
    
  });
  
  $('#carousel-wrap #prev').click(function(){
    if(!$(currentSlide).is('#carousel-wrap .container div:first-child')){
      currentSlide = $(currentSlide).prev()
      carousel_update_links()
    }
    $('#carousel').stop().scrollTo( currentSlide, 2000 , { easing: 'elasout' });
  });
});