$.gallery = {
  lock : 0,
  currentId : "",
  timeout : 0
};

function crossFading(currentId,nextItemId){

  $("#" + currentId).fadeOut(1000);
  $("#" + nextItemId).fadeIn(1000,
    function(){
      $.gallery.lock = 0;
    }
  );
}

function looping(){
  $('#next').click();
}



$(document).ready(
  function(){
    
    // assign ID and class "JS" to each gallery image, hide all gallery images except the first one 
    $('div.gallery img').addClass("JS").attr("id", function (arr) { return "gal" + arr; }).not(":first").css("display","none");

    // using jQuery click event handler
    $('div.galleryController a').click(
      function(event){    
        // don't do anything in transition
        if(!$.gallery.lock){
        
          // clear timeout during transition
          clearTimeout($.gallery.timeout);
        
          var items = $('div.gallery img');
          var currentItem = items.not(":hidden").eq(0);
          $.gallery.currentId = currentItem.attr("id");
            
          // lock buttons before transition
          $.gallery.lock = 1;
          
          // determine the next item to display
          var nextItem = ($(this).attr("id") == $(this).parent().find('a').eq(0).attr("id")) ? ( (items.eq(0).attr("id") == currentItem.attr("id")) ? items.eq(items.length - 1) : items.not(":hidden").eq(0).prev() ) : ( (items.eq(items.length - 1).attr("id") == currentItem.attr("id")) ? nextItem = items.eq(0) : items.not(":hidden").eq(0).next() );

          // determine if dynamic loading is needed
          if(nextItem.attr("longdesc")){
            nextItem.attr("alt",currentItem.attr("alt"));
            nextItem.attr("src",nextItem.attr("longdesc")).bind("load",
              function(){
                $(this).removeAttr("longdesc");
              }
            );
          }
          
          crossFading($.gallery.currentId, nextItem.attr("id"));
          $.gallery.timeout = setTimeout(looping,8000);
          
        }
        event.preventDefault(); 
      }  
    );

    // start looping
    $.gallery.timeout = setTimeout(looping,8000);

    // announcement
     $('#ann_skip').click(
      function(event){
        event.preventDefault();
        $('#announcement').fadeOut();
      }
    );
	
  }
);
