var rotator = {
  init:function(){    
    
    // give each image ID corresponding to its order
    var num = 1;
    $('.rotator img').each(function(){
      $(this).parent().attr('id', 'image-'+num);
      if ( $(this).attr('title') != '' ) {
       $(this).parent().append('<p>' + $(this).attr('title') + '</p>'); 
      }
      num++;
    });
    
    // make first image visible
    $('#image-1').css('display', 'block').addClass('current');
    rotator.current = 1;
    
    // store value of last image
    rotator.lastImage = $('.rotator div:last').attr('id').split('-')[1];    
    
    // set the order for the next slide to appear
    rotator.prepNextSlide();   
        
  },
  
  prepNextSlide:function(doFade){
    // set var img depending on whether last image is selected or not
    if(rotator.current == rotator.lastImage){
      rotator.nextImg = '#image-1';
      rotator.next   = 1;
    } else {
      rotator.next   = parseInt(rotator.current)+1;      
      rotator.nextImg = '#image-'+rotator.next;
    }    
    rotator.getRotatorSpeed();
  },
  
  getRotatorSpeed:function(){
    if($('#image-'+rotator.current).attr('class'))
      rotator.speed = parseInt($('#image-'+rotator.current).attr('class').split('-')[1] );  
    
    if(rotator.speed)
      rotator.rotatorSpeed = rotator.speed*1000;
    else
      rotator.rotatorSpeed = 5000;    
      
    // trigger the fading function
    rotator.timer = setTimeout(function(){ rotator.fadeIt(); }, rotator.rotatorSpeed);
  },
  
  fadeIt:function(){  
    
    // fade out current image
    $('#image-'+rotator.current).fadeOut('slow').removeClass('current');
    
    // set next image to be new image
    $(rotator.nextImg).addClass('current');
    $(rotator.nextImg).fadeIn('slow');
    
    rotator.current = rotator.next;
    
    rotator.prepNextSlide();
    
  }
}

$(document).ready(function(){  
  rotator.init();  
});
