// ***
// *** Begin "ChangingImages"
// ***
/*
 * @file ChangingImages.js
 * @date 2007-06-18
 * @modified 2007-08-03
 * @author Chris Bouchard
 *
 * Object to randomly replace the source of an image node with a URL from a given
 * list of URLs
 *
 * 
 * Usage:
 * 
 * ChangingImages.addChangingImage(newImgNode, newImgObjArray, [newDocumentRoot, [newMinDelay, newMaxDelay]]);
 * 
 *     *  newImgNode - (Object) the img element to change
 *                   - (String) the ID of the img element to change
 * 
 *     *  newImgObjArray - (Array) a list of Objects with the following keys: fileName, url, title, absolute
 *                       - (String) a JSON formatted string of such an array
 * 
 *     *  documentRoot [Optional] - (String) The folder in which to look for the files in newImgSrcArray
 *                                - Default value is '' (no documentRoot)
 * 
 *     *  newMinDelay [Optional] - (Number) The minimum time delay between changes, in milliseconds
 *                               - Default value is 30000 milliseconds (30 seconds)
 * 
 *     *  newMaxDelay [Optional] - (Number) The maximum time delay between changes, in milliseconds
 *                               - Default value is 60000 milliseconds (60 seconds)
 * 
 * 
 * Notes:
 * 
 * Animation is automatically used if brothercake's crossfade library is used.  If animation is
 * used, the image must NOT have any padding or border.
 * 
 * 
 */

var ChangingImages = new (function()
{
	var _defaultMinDelay = 30000;
	var _defaultMaxDelay = 60000;
	
	var _fileNameKey = 'fileName';
	var _urlKey = 'url';
	var _titleKey = 'title';
	var _absoluteKey = 'absolute';
	
	var _changingImageArray = new Array();
	
	this.addChangingImage = function(newImgNode, newImgObjArray, newDocumentRoot, newMinDelay, newMaxDelay)
	{
		var imageObject;
		
		// If type String, use as element ID
		if (typeof(newImgNode) == 'string')
		{
			newImgNode = document.getElementById(newImgNode);
		}
		
		// If type String, parse as JSON
		if (typeof(newImgObjArray) == 'string') // Interpret as JSON (assumed safe)
		{
			newImgObjArray = eval('(' + newImgObjArray + ');');
		}
		
		// Find the document root
		newDocumentRoot = (newDocumentRoot == null || newDocumentRoot == undefined) ? '' : (String(newDocumentRoot) + '/');
		
		// Initialize the image
		_setImageProperties(newImgNode, newImgObjArray[0], newDocumentRoot, false);
		
		// If there are n't enough images to rotate, then we're done
		if (newImgObjArray.length <= 1)
		{
            return;
		}
		
		// Create an object with information about the image
		imageObject = { currentImgIndex: 0, imgNode: newImgNode, imgObjArray: newImgObjArray, documentRoot: newDocumentRoot };
		
		// If both a new min and max delay are provided, include them in the image info object
		if (newMinDelay && newMaxDelay)
		{
			imageObject.minDelay = newMinDelay;
			imageObject.maxDelay = newMaxDelay;
		}
		
		// Let's try taking this out of the if
		// if (_changingImageArray.length > 0)
		{
            // Add this image to the list of changing images
            _changingImageArray.push(imageObject);
            
            // Start changing
			_setTimeoutReplaceImage(_changingImageArray.length - 1);
		}
	};
	
	var _setTimeoutReplaceImage = function(index)
	{
		var minDelay = _changingImageArray[index].minDelay || _defaultMinDelay;
		var maxDelay = _changingImageArray[index].maxDelay || _defaultMaxDelay;
		
		var randomDelay = Math.floor(Math.random() * (maxDelay - minDelay)) + minDelay;
		
		
		// An anonymous function is used to pass the index parameter to _replaceImage
		window.setTimeout((function() { _replaceImage(index); }), randomDelay);
	};
	
	var _replaceImage = function(index)
	{
        // Get the index of the next image
		var nextImgIndex = _generateNextIndex(_changingImageArray[index].imgObjArray, _changingImageArray[index].currentImgIndex);
		
		// Change the image
		_setImageProperties(_changingImageArray[index].imgNode, _changingImageArray[index].imgObjArray[nextImgIndex],
		                    _changingImageArray[index].documentRoot, true);
        
        // Update the current image index
		_changingImageArray[index].currentImgIndex = nextImgIndex;
		
		// Prepare to change again
		_setTimeoutReplaceImage(index);
	};
	
	var _generateNextIndex = function(valueList, currentIndex)
	{
		return (currentIndex + 1) % valueList.length;
	};
	
	var _setImageProperties = function(imageNode, imageObj, documentRoot, animate)
	{
        // If the crossfade animation library has been imported, use it to animate the transition
		// Otherwise just change the img source
		if (animate && window.ixf && window.crossfade)
		{
			crossfade(imageNode, documentRoot + imageObj[_fileNameKey], '1');
		}
		else
		{
			imageNode.src = documentRoot + imageObj[_fileNameKey];
		}
		
		imageNode.title = imageObj[_titleKey];
		imageNode.alt = imageObj[_titleKey];
		
		//JRB 10/11/2007: Relative URL's on the database contain leading '/', so remove it from the end of document.Root
		
		if (imageObj[_urlKey] != null)
		{
			imageNode.parentNode.href = imageObj[_absoluteKey] ? imageObj[_urlKey] : documentRoot.slice(0,-1) + imageObj[_urlKey];

		     //2010-01-07 S. Davies: restructure the following commented-out conditional to force "non-absolute pathed" PDFs to be opened in new window
             //imageNode.parentNode.target = imageObj[_absoluteKey] ? '_blank' : '_self';

            if ( imageObj[_absoluteKey] )
            {
                imageNode.parentNode.target = '_blank';
            }
            else if ( imageNode.parentNode.href.toUpperCase().indexOf('.PDF') == -1 ) 
            {
                imageNode.parentNode.target = '_self';
            }
            else
            {
                imageNode.parentNode.target = '_blank';
            }
        }
     }

})();





