$(document).ready( function(){

  var body = $('body');

  if(body.hasClass('home') || body.hasClass('single'))
  {
    initImageSwitching();
  } else if( body.hasClass('category-archives') ){
    initMetaDisplay();
  }

  function initMetaDisplay()
  {
    $('#main-content img').hover( function(){
      $('#main-content img').removeClass('current');
      $('.meta').html($(this).attr('alt'));
      $(this).addClass('current');
    });
  }
  
  function initImageSwitching()
  {
    var posts = $('.post');
    var postCount = 1;
    
    $.each(posts, function(index){

      var currentPost = $(this);
      var wrappedImages = currentPost.find('img').parents('p');
      var count = wrappedImages.length;
      
      if( count > 1 )
      {
        var elementId = 'switcher-' + postCount;
        postCount++;
        
        var element = $('<div id="' + elementId + '"></div>');
        var imageList = $('<ul class="images"></ul>');
        wrappedImages.remove();
        wrappedImages.find('img').wrap('<li/>').parent().appendTo(imageList);
        
        createNavigationElement( 1, count ).appendTo(element);
        imageList.appendTo(element);
        
        element.insertAfter( currentPost.find('.post-header') );
        
        //init jCarouselLite
        $("#" + elementId ).jCarouselLite({
          btnNext: "#" + elementId + " .switch.next",
          btnPrev: "#" + elementId + " .switch.previous",
          visible: 1,
          circular: false,
          afterEnd: switchingCallback
        });

      }
    });
  }
  
  function switchingCallback(image)
  {
    var parent = image.closest('div');
    
    //increase the counter for the current image on the page
    parent.find('.current').html(image.index()+1);
    
    parent.width(image.find('img').width());
    image.width(image.find('img').width());
    image.height(image.find('img').height());
    parent.height(image.find('img').height() + 30);
  }
  
  function createNavigationElement( current, last )
  {    
    return $('<div class="switching-nav group"><span class="switch previous disabled">Previous</span><div class="pages"><span class="current">' + current + '</span> / ' + last + '</div><span class="switch next">Next</span></div>');
  }
});
