var canFade = false; // whether or not the fade can take place
var currentOffset = 0; // the current image to load in the paths array
var interval = 10000; // the amount of time to wait between fades

String.extend({
  toElement: function() {
    var tagInfo = this.match(/<(\S*) (.*)>(.*)\<\/\1>/);
    if(tagInfo) {
      var tag = tagInfo[1],
          attributes = "{" + tagInfo[2].replace(/(\S*)=(['"\\]?)([^'"\\]*)\2\s?/g, "\"$1\":\"$3\",") + "}",
          html = tagInfo[3];
      return new Element(tag, Json.evaluate(attributes)).setHTML(html);
    } else return new Element("div").setHTML(this);
  }
});

window.addEvent('domready',function(){
	var j = new Request.JSON({
		'url':'/lib/xml/fadeimages.json',
		'onSuccess':function(rj,ck){
			var paths = rj.images;
			loadNext(paths); // load the first image to fade to
			fadeImage.delay(interval,paths); // set up the fade delay
		}
	}).get();	
});
var loadNext = function(paths){
	var largestOffset = paths.length-1;
	currentOffset = currentOffset+1 > largestOffset ? 0 : currentOffset+1;
	var el = document.getElement('img.fademe.'+currentOffset);
	if (el){ // check if the image we're trying to load has already been loaded once
		el.set('id','nextToLoad').setStyle('opacity',1);
		canFade = !canFade;
	} else { // it hasn't been - create it
		var el = new Element('img',{'src':paths[currentOffset],'alt':'home','class':'fademe '+currentOffset,'id':'nextToLoad'}).addEvent('load',function(){canFade = !canFade});
	}
	document.getElement('img#currentfocus').grab(el,'before'); // put the next image at the top so it shows through
}
var fadeImage = function(){ // if the image showing behind doesn't successfully load, the last successful one will stay and fading will appear to have paused
	var paths = this; // mootools can't pass an array as an argument, must be passed as this
	if (canFade){
		var sp = document.getElement('img#currentfocus');
		sp.set('tween',{duration:700,'onComplete':function(){
			document.getElement('img#nextToLoad').set('id','currentfocus');
			sp.set('id','dontload');
			canFade = !canFade; // disable fading until next image loads successfully
			loadNext(paths);
			fadeImage.delay(interval,paths);
		}}).tween('opacity',0); // fade the current image
	} else { //can't fade yet - image not loaded. wait 1 second and try again
		fadeImage.delay(1000,paths);
	}
}