document.observe('dom:loaded', function(){
	/* 
		Pull out list items from radiant content
		Randomise the list
		Select 5 items from the list and display them
	*/
	var sidebarTips = (function (container) {
		var number = 5;
		var startIndex = 0, endIndex = 0;
		var rotationTime = 5000;
		var list = container.select('li').sort(function(){ return 0.5-Math.random(); });
		
		var hiddenHolder = container.down('ul').hide();
		var clippingContainer = new Element('div');		// mask out the items
		var holderContainer = new Element('ul');			// hold lists of active/inactive tips
		var oMargin;
		
		// pre-process - creating and inserting two holding divs
		container.down('h3').insert({after:clippingContainer});
		clippingContainer.setStyle({overflow:'hidden'}).insert(holderContainer);
		oMargin = parseInt(hiddenHolder.down('li').getStyle('margin-top'));
		
		/* Define */
		var showTips = function(){
			var visibleList = list.findAll(function(e){ return e.visible(); });
			
			// show the first five
			if (endIndex==0) { 
				startIndex = 0; endIndex = number; 
			} else if (endIndex+1 >= list.length) {
				endIndex = 0;
			} else {
				endIndex += 1;
			}
			
			// if first time, insert everything
			if (holderContainer.childElements().length==0) {
				list.slice(startIndex,endIndex).each(function(e,i) {
					holderContainer.insert(e);
				});
			} else {
				// remove the first item in the visible list and insert another one
				var oldItem = holderContainer.down(0);
				var newItem = list[endIndex];
				
				// reveal animation
				new Effect.Morph(oldItem, {style:'margin-top:'+-oldItem.getHeight()+'px', duration:0.6, 
					beforeStart:function(){ 
						var h=0;
						newItem.setStyle({'marginTop':oMargin+'px'});
						holderContainer.insert(newItem);
						holderContainer.childElements().slice(1).each(function(e,i) {
							var m = parseInt(e.getStyle('margin-top'));
							h = h==0 ? h + m*2 + e.getHeight() : h + m + e.getHeight()
						});
						// reset container
						new Effect.Morph(clippingContainer, {style:'height:'+h+'px', duration:0.6 });
					},
					afterFinish:function(){ hiddenHolder.insert(oldItem); } 
				});
			}
		}
		
		// every interval, show other fives until the end
		var startRotate = function () { return setInterval(showTips,rotationTime); }
		
		/* Event handlers */
		// when mouse over container, stop rotating
		container.observe('mouseover', (function(event) { 
			clearInterval(this.tipsInterval); 
			this.tipsInterval = undefined;
		}).bindAsEventListener(this));
		
		// resume when mouse out
		container.observe('mouseout', (function(event) { 
			if (!this.tipsInterval) { 
				this.tipsInterval = startRotate(); 
			}
		}).bindAsEventListener(this));
		
		/* Main */
		// show tips initially and begin rotation
		this.tipsInterval = startRotate();
		showTips();
	})($('sidebar-tips'));
});
