$(function() {
  $("#accordion").accordion({
    header: 'h2',
    fillSpace: true,
    change: function(event, ui) {
      var header = $(this).find(ui.options.header);
      var oldIndex = header.index(ui.oldHeader);
      var newIndex = header.index(ui.newHeader);
      if (oldIndex > newIndex) {
        $(".yoochooseTeaser img.teaserImage").eq(newIndex).show(function() {
          $(this).siblings('img.teaserImage')
            .fadeOut(1000);
          });
      } else {
        $(".yoochooseTeaser img.teaserImage").eq(newIndex).fadeIn(1000, function() {
          $(this).siblings('img.teaserImage')
            .hide();
          });    
      }
      clearTimeout(showNextTimeout);
      showNextTimeout = window.setTimeout(showNext, 20000);
    }
  });
  
  $(".yoochooseTeaser img.teaserImage")
    .eq($("#accordion").accordion('option', 'clearStyle'))
      .siblings('img.teaserImage')
        .hide();
  
  var showNext = function() {
    var accordion = $("#accordion")
    var index = accordion.find(".top").index(accordion.find(".ui-state-active").closest(".top"));
    accordion.accordion('activate', index < 2 ? index + 1 : 0);
  };
  
  showNextTimeout = window.setTimeout(showNext, 20000);
});
