/* Roller.js: Dojo text roller. (c) 2010 Code Red Consultancy */

dojo.require("dojo.fx");

/**
 * Text roller constructor.
 *
 * @param	divId	the id of the div containing the text and list
 */
function TextRoller(divId)
{
    this.divIdM = divId;
    this.resolvedM = false;
    this.listM = new Array();
    this.idxM = -1;
}



/**
 * Lookup the elements corresponding to the IDs given in the constructor.
 * Performed once only.
 */
TextRoller.prototype.lookupElems = function()
{
    if (this.resolvedM)
	return;

    // Resolve the fields.
    //
    this.divM = dojo.byId(this.divIdM);
    this.debugM = dojo.byId("debug");

    this.resolvedM = true;
}



/**
 * Append a message to the debug div.
 * If message is null, clear the div.
 *
 * @param   msg	    the message to append (or null to clear)
 */
TextRoller.prototype.debug = function(msg)
{
    with (this)
    {
	if (debugM != null)
	    if (msg == null)
		debugM.innerHTML = "Debug";
	    else
		debugM.innerHTML = debugM.innerHTML + ", " + msg;
    }
}



/**
 * Populate the text array with the HTML fragments in ordered lists
 * inside the div.
 */
TextRoller.prototype.fillList = function()
{
    with (this)
    {
	// debug("fillList()<br/>");

	var child = divM.firstElementChild;
	
	while (child != null)
	{
	    if (child.nodeName == "OL")
	    {
		var grandChild = child.firstElementChild;
		
		while (grandChild != null)
		{
		    if (grandChild.nodeName == "LI")
		    {
			var text = grandChild.innerHTML;
			
			listM.push(text);
		    }
		    
		    grandChild = grandChild.nextElementSibling;
		}
	    }
	    
	    child = child.nextElementSibling;
	}
	
	// debug("<br/>fillList() done");
    }
}



/**
 * Replace the text in the div with the next set of text.  Animate
 * it fading in, pausing, and fading out.  When the animation is done
 * call this method again.
 */
TextRoller.prototype.nextRoller = function()
{
    // this.debug("nextRoller()<br/>");
    this.idxM++;
    
    if (this.idxM >= this.listM.length)
	this.idxM = 0;
    
    dojo.style(this.divM, "opacity", "0");
    this.divM.innerHTML = this.listM[this.idxM];
    
    var	comp = this;
    var animation = dojo.fx.chain(
	[
	    dojo.fadeIn(
		{
		    node: this.divM,
		    duration: 200
		}
	    ),
	    dojo.animateProperty(
		{
		    node: this.divM,
		    duration: 5000
		}
	    ),
	    dojo.fadeOut(
		{
		    node: this.divM,
		    duration: 500,
		    onEnd: function()
		    {
			comp.nextRoller();
		    }
		}
	    )
	]
    );
    
    animation.play();
    // this.debug("nextRoller() done<br/>");
}



/**
 * Initialise the roller and start animating the text.
 */
TextRoller.prototype.init = function()
{
    this.lookupElems();
    this.fillList();
    this.debug("Initialised");
    this.nextRoller();
}


