function setupCarousel() {
  var width = $("#teaser").width();
  var item_width = $('#teaser li').width();
  var visible = width / item_width;
  var start = -((width - item_width) / 2) / item_width - visible + 2;


  var btns = '<div id="carousel-nav-prev" class="carousel-nav"><a href="#"></a></div><div id="carousel-nav-next" class="carousel-nav"><a href="#"></a></div>';
  $("#teaser").after(btns).jCarouselLite({
    btnNext: "#carousel-nav-next a",
    btnPrev: "#carousel-nav-prev a",
    auto: 1000,
    visible: visible,
    start: start,
    speed: 800,
    paused: true
  })
  var nav_width = ($("#main").width() - item_width) / 2;
  $('.carousel-nav').width(nav_width);
}

function destroyCarousel() {
  clearInterval($("#teaser").data('intervalId'));
  $("#teaser").width('');
  $('#teaser .cloned').remove();
  $('.carousel-nav').remove();
}

function getElementsWith(firstEl, expr) {
    var firstElement = $(firstEl); // First Element
    var collection = new Array(); // Collection of Elements
    $(firstEl).nextAll().each(function(){ // Traverse all siblings
        if ($(this).filter(expr).size() > 0) { // If Sib is not LastElement
            collection.push(this); // Add Sibling to Collection
        } else { // Else, if Sib is LastElement
            return false; // Break Loop
        }
    });         
    return collection; // Return Collection
}

$(document).ready(function() {
  if ($('#teaser:visible').size()) {
    setupCarousel();

    $(window).resize(function() {
      setTimeout(function() {
        destroyCarousel();
        setupCarousel();
      }, 2000);
    });  
  }
  
  // features
  // group features
  
  var feature_elements = $('.feature');
  if (feature_elements.size() > 0) {
    $('h2').each(function() {
      var features = getElementsWith($(this), '.feature');
      var container = $('<div class="feature-group"></div>');
      $.each(features, function() {
        container.append(this);
      });
      $(this).after(container);
      if ($('img', container).size() > 0 && $('img', container).size() == features.length) {
        container.addClass('with-images');
      }
    });
  }
  $('.feature-group.with-images').each(function() {
    var fg_el = $(this);
    var slideshow = $('<div class="features-slideshow"></div>');
    var details_elements = $('.details', this);
    details_elements.appendTo(slideshow);
    $(details_elements[0]).css('z-index', 1);
    slideshow.data('zIndex', 1);
    slideshow.data('visibleFeatureId', $('.feature', this).attr('id'));
    $(this).before(slideshow);
    $('.feature', $(this)).mouseover(function() {
      fid = $(this).attr('id');
      if (fid == slideshow.data('visibleFeatureId')) return false;
      slideshow.data('visibleFeatureId', fid);
      var zIndex = slideshow.data('zIndex') + 1;
      slideshow.data('zIndex', zIndex);
      var details_el = $('#' + fid + '-details');
      $('.feature', fg_el).removeClass('active');
      $(this).addClass('active');
      details_el.hide().css('z-index', zIndex).fadeIn(500);
    });
  });
  
  
  // cart
  function updateCart() {
    var totalAmount = parseFloat($('#basic-price').text());
    $('#optional-services .priceH').each(function() {
      var price_el = $(this);
      var parent_el = price_el.parent('.ctrlHolder');
      var input_el = $('select,input[type=radio]:checked', parent_el);
      var val = parseFloat(input_el.val());
      var serviceId = parent_el.attr('id').match(/service-(.*)/)[1];
      var target= $('#cart li#cart-item-' + serviceId);
      if (val) {
        var price = val * price_el.html();
        totalAmount += price;
        if (input_el[0].tagName == 'SELECT') {
          var option_text = $("option[value='"+val+"']", input_el).text();
        } else {
          var option_text = input_el.parent().text();
        }
        var content = $('h5', parent_el).text() + ': ' + option_text +
                      '<br/><span class="price">' + format_currency(price) + '</span>';
        if (target.length > 0) {
          target.html(content);
        } else {
          $('#cart ol').append('<li id="cart-item-'+serviceId+'">'+content+'</li>');
        }
      } else if (target.length > 0) {
        target.remove();
      }
    });
    $('#total-amount').html(format_currency(totalAmount));
  }
  
  var optional_services_el = $('#optional-services');
  if (optional_services_el.length > 0) {
    updateCart();
    $('#optional-services select, #optional-services input').change(function() {
      updateCart();
    });
  }
  
  // cart
  if ($("#cart-container").size() > 0) {
    var cartY = $("#cart-container").offset().top;
    function moveCart() {
      var scrollTop = $(window).scrollTop();
      var e = $("#cart-container");
      if (scrollTop > cartY) {
        e.css('position', 'fixed');
        e.css('marginTop', '0px');
        var cartX = $("#form").offset().left + 485;
        e.css('left', cartX);
      } else {
        e.css('position', 'absolute');
        e.css('left', null);
      }
    }

    $(window).scroll(moveCart).resize(moveCart);    
    moveCart();
  }

});
