jQuery.fn.rotation = function(){
  
  // Walk through images and get configuration
  return this.each(function(){
    var img=$(this);
    var config=img.attr("config")+"?"+escape((new Date()).toString());
    $.get(config,function(data){
      init(data,img);
    },"xml");
  });

  // Set up rotation  
  function init(xml,img){

    // Settings
    var opts=$("slideshow",xml);
    var ser=$("slide",xml);
    var slides=[];
    var curr=0;
    var readyct=0;
    var pause=(opts.attr("delay") || 3) * 1000;
    var speed=(opts.attr("faderate") || 2) * 1000;
    var delayIn=(opts.attr("delayin") || 0) * 1000;

    // Set up container around images
    img.wrapAll('<div style="position:relative"><div/></div>');
    var slide=img.parent();
    var div=slide.parent();

    // Update main image and load in others in series
    for(var i=0;i<ser.length;i++){
      var s=ser[i];
      if (i==0) slides[i]=slide
      else slides[i]=$('<div style="position:absolute;top:0;left:0;z-index:-1">' +
          '<img src="'+s.getAttribute("src")+'" border=0 /></div>').insertAfter(slide);  
    }
    img_loaded();

    // When loaded
    function img_loaded(){
      if (!img[0].complete) setTimeout(function(){img_loaded();},200);
      else {
        div.width(slide.width()).height(slide.height());
        slide.css({position:'absolute',top:0,left:0,zIndex:1});
        rotation_advance();
      }
    }
	
    // Swap image
    function rotation_advance(){
      var n=(curr<ser.length-1)?curr+1:0;
      if (!slides[n].find("img")[0].complete) setTimeout(function(){rotation_advance();},pause);
      else {
        slides[curr].fadeOut(speed);
        slides[n].css("zIndex",0).delay(delayIn).fadeIn(speed,function(){
          setTimeout(function(){rotation_advance();},pause);
        });
	    curr=n;
      }
    }


  }
}

// Instantiate
jQuery(function(){$('.rotation').rotation()});


