// Add shufling to array
Array.implement({
	shuffle: function() {
		//destination array
		for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
		return this;
	}
});

// Author Daniel Sokolowski
// parent element should have overflow: hidden
// All child elements will be moved to position absolute to the fst elements position. 
// The elements will be faded in in rotating fashion


function initChildFader(element) {	
	// grab the elements and prepare by modifing css

	var parentElement = $(element);
	arrElements = parentElement.getElements('img');
  arrElements.set('tween', {duration: 2000});
  // make position absolute and all elements in same position 
  position = arrElements[0].getPosition();
  arrElements[0].setStyle('opacity', '0'); // since when elements are put on top of eachother
  																				 // the first one is deisplayed rather than the last one
  																				 // in html makrup before this script executes so this prevents 'the flicker'
  																				 // ToDo: should put it in 'domready'
  arrElements.setStyle('position','absolute');
  
  arrElements.setPosition('position');
  // lets shuffle the images but we must keep last child same position 
  // for proper stuf of animation
  
  lstChild = arrElements.pop();
  arrElements.shuffle();
  arrElements.push(lstChild);
  
  parentElement.arrChildren = arrElements
 	parentElement.childFader = function () {
 		// we need 3 z-index values
 		// if two elements have same z-index value the display is 
 		// determined by order in HTML markup 
 		// hence we need 3 values
 		// z-index 0 - hidden images
 		// z-index 1 - image that is being faded onto
 		// z-index 2 - images being faded in
 		
 		this.arrChildren.setStyle('z-index','0');
 		fstChild = this.arrChildren.shift();
 		lastChild = this.arrChildren.pop()

 		// move the last element to the front of all other elements
 		// this element will be faded onto
 		lastChild.setStyle('z-index','1');

 		//bring the fst element in array into focus
 		fstChild.setStyle('opacity', '0'); // hide it first
 		fstChild.setStyle('z-index','2');
 		fstChild.tween('opacity', '1');
 		
 		// store the 'shifted' array back into parent object
 		this.arrChildren.push(lastChild);
 		this.arrChildren.push(fstChild);
 		
    
 	}
}

window.addEvent('load', function() {
	
	initChildFader('idShowCase1');
	initChildFader('idShowCase2');
	initChildFader('idShowCase3');
 
 
 
  setInterval("$('idShowCase1').childFader()", 5000);
  //An anonymous function which waits and than executes
  
  (function() {
  	 $('idShowCase2').childFader();
  	 setInterval("$('idShowCase2').childFader()", 5000);
  }).delay(2000);

(function() {
  	 $('idShowCase3').childFader();
  	 setInterval("$('idShowCase3').childFader()", 5000);
  }).delay(4000);

 
  });