/**
 * @author Ryan Cannon <ryan.cannon@nfl.com>
 * @copyright 2007 NFL
 * @package nfl.ui.shop
 * @requires prototype
 * @requires nfl
 *
 * The shop widget displays a random image from shop data embeded on the page.
 * The folowing HTML stucture
 *
 *   div.nfl-shop-widget
 *     a.featured-item
 *       img
 *     form
 *       ul
 *        li
 *         a
 *         input
 *
 **/
nfl.namespace("nfl.ui.shop");
nfl.namespace("nfl.util.shop");
nfl.util.shop.initialize	=  function(){
	var list = $$('div.nfl-shop-widget').collect(nfl.util.shop.create);
	return (list.size && list.size() == 1) ? list.first() : list;
}
nfl.util.shop.create = function(div) {
	return new nfl.ui.shop.widget(div);
}
	
nfl.ui.shop.widget = Class.create();
nfl.ui.shop.widget.prototype	= {
		/**
		 * Finds the relevant HTML structures, sets the cleanup listener and randomly features an item.
		 * @method initialize
		 * @param {HTMLDivElement} The show widget <div> 
		 */
		initialize: function(div){
			this.div 			= $(div);
			this.featuredLink	= this.div.select('a.featured-item').first();
			this.featuredImage	= this.featuredLink.select('img').first();
			this.items			= this.div.select('li');
			var rand			= Math.floor((Math.random() * this.items.size()));
			this.setFeatured(this.items[rand]);
			Event.observe(window,"unload",this.cleanup.bindAsEventListener(this));
		},
		/**
		 * Nulls references to HTML elements to avoid memory leaks
		 * @method cleanup
		 */
		cleanup: function() {
			this.div = this.featuredLink = featuredImage = this.items = null;
		},
		/**
		 * Nulls references to HTML elements to avoid memory leaks
		 * @method cleanup
		 * @param {Extended Element | Integer} The item to feature.
		 */
		setFeatured: function(item) {
			if (! isNaN(item)) { item = this.items[item] }
			var link	= item.select('a').first();
			var input	= item.select('input').first();
			if (link && input) {
				this.featuredLink.href		= link.href;
				this.featuredImage.title	= link.innerText || link.textContent;
				this.featuredImage.src		= input.value;
			}
		}
}
document.observe("dom:loaded", nfl.util.shop.initialize);
//document.fire('script:libShopLoaded');
