
var sliderTopTimer;
var initializeSliderTop = function(){

   clearTimeout(sliderTopTimer);

   var $container = $("#sliderTop"),
      $items = $(".item", $container),
      $buttonContainer = $(".buttons", $container);

   $('.image', $container).each(function(){
      src = $(this).css("background-image");
      $('<img />').attr('src', src.substring(4, src.length - 1).replace(/^"+|"+$/g, ''));
   });
   $('.caption', $container).each(function(){
      $('<img />').attr('src', this.src);
   });

   if($items.length > 1){
      $items.each(function(){
         $span = $("<span>");
         if($(this).is(":visible")){
            $span.addClass("active");
         }
         $span.appendTo($buttonContainer);
      });

      var startTimer = function(){
         clearTimeout(sliderTopTimer);
         sliderTopTimer = setTimeout("this.nextSlide()", 6000);
      }

      var lock = false;

      var $buttons = $("span", $buttonContainer).click(function(){
         clearTimeout(sliderTopTimer);
         if(!$(this).hasClass("active") && !lock){
            changeSlide($(this).index());
         }
      });

      this.nextSlide = function(){
         next = $buttons.filter(".active").index()+1;
         if(next > $buttons.length-1){
            next = 0;
         }
         changeSlide(next);
      }

      var changeSlide = function(index){
         lock = true;
         var $visibleItem = $(".item:visible", $container);
         $(".caption", $visibleItem).hide("slide", {direction: "down"}, 500, function(){
            $visibleItem.fadeOut(500, function(){
               $items.eq(index).fadeIn(500, function(){
                  $(".caption", this).show("slide", {direction: "down"}, 500, function(){
                     lock = false;
                  });
               });
            });
         });
         startTimer();
         $buttons.removeClass("active").eq(index).addClass("active");
      }

      $buttonContainer.show(0);
      startTimer();
   }

}

