(function ($) {
    
  Drupal.behaviors.loadCarousel = function(context) {
    
    //alert("bla");
    
    var itemIndex = -1;
    var content = $('#above_content .view-home-banner .view-content');
    var next = $('#above_content .view-home-banner .nav #next');
    var prev = $('#above_content .view-home-banner .nav #prev');
    var carouselScroll;
            
    // start by setting the interval...
    setClickInterval();
    
    $('#above_content .view-home-banner').hover(function(){
      clearInterval(carouselScroll);
    },function(){
      setClickInterval();
    }) 
    
    function setClickInterval(){
       clearInterval(carouselScroll);
       carouselScroll = setInterval(showItem,4000);
    }

    function showItem(previous){
      
      $items =  $("ul",content);      
      $item_current = $("li.active", $items);
      $length = $("li",$items).size();
     
      //no active items yet, first = active
      if(itemIndex == -1){
       //console.log("no active items yet, first = active") ;       
       itemIndex = 0;        
       $item_new = $("li:first",content);   
      }
          
     // is the first and we go to previous, than select the last
     else if (itemIndex==0 && previous==true){     
       itemIndex = $length-1;  
       $item_new = $('li:last', content);
     }

     // is the first and we go to previous, than select the last
     else if (previous==true){     
      $item_new = $('li.active',content).prev('li'); 
      itemIndex--; 
     }     
     
     // is it the last one? Then jump  to the first         
     else if (itemIndex == $length -1){
      
         $item_new = $("li:first",content);
         itemIndex = 0;  
     }
            
     // otherwise just jump to the next one
    else {
      $item_new = $('li.active',content).next('li');
      itemIndex++; 
    } 
    
    $('#above_content .view-home-banner .nav .counter').html((itemIndex+1));
    
    
    //alert(itemIndex);
    
    
    if ( typeof $item_current !== "undefined" && $item_current){
      $item_current.removeClass("active").fadeOut(700);        
    }       
    
    $item_new.addClass("active").fadeIn(700);

    }  
    
    next.click(function(){
      // show the next
      showItem();
      // reset the interval
      setClickInterval();
    })
    prev.click(function(){
      // show the next
      showItem(true);
      // reset the interval
      setClickInterval();
    })
    
    // show first item
    showItem();
  }
   
})(jQuery);
 
