nfl.namespace('videoplayer');
//nfl.videoplayer.thumbnail = Class.create();
nfl.videoplayer.thumbnail = function(content){
	//initialize: function(content){
		nfl.log('nfl.videoplayer.thumbnail.initialize: isString(content) = '+ (isString(content)));
		//return ({xml: content})
		if(isString(content)){
			//this is xml, convert it to JSON
			return content;
			//return xml2json.parser(content)
		}else{
			//this is json
			return content;
		}
	//}
	
};
nfl.videoplayer.thumbnails = Class.create();
nfl.videoplayer.thumbnails.prototype	= {
	initialize: function(containerid, xmlURL, options) {
		nfl.log("nfl.videoplayer.thumbnails.initialize('"+ containerid +"','"+ xmlURL +"')");
		this.options	= options;
		this.xmlURL		= xmlURL;
		nfl.log("nfl.videoplayer.thumbnails.initialize: this.xmlURL = "+ this.xmlURL);
		this.itemTemplate	= '<div class="thumbnail"><img src="#{thumbsmall}" alt=""/></div><h3><a href="#" onclick="return false">#{body}</a></h3><p>#{caption}</p>';
		this.containerId	= containerid;
		this.__thumbitems	= [];
		document.observe('dom:loaded', function(){this.container	= $(this.containerId).getStyle('width')}.bind(this));
		document.observe('videogallery:thumbnails:click',this.onThumbnailClick.bind(this));
		document.observe('dom:loaded',this.getXML.bind(this));
	},
	getXML: function(){
		nfl.log("nfl.videoplayer.thumbnails.getXML; "+ this.xmlURL);
		new Ajax.Request(this.xmlURL, { onSuccess: this.onXMLResponse.bind(this), onFailure: this.onXMLFailure.bind(this), method: "get" });
	},
	onXMLResponse: function(transport){
		nfl.log("nfl.videoplayer.thumbnails.onXMLResponse:\n\r"+ transport.responseXML);
		var x			= transport.responseXML;
		// Works around security error in Firefox 1.5
		try {
			x.firstChild;
		}
		catch(e) {
			x = (new DOMParser()).parseFromString(transport.responseText, "text/xml");
		}
		var items		= x.getElementsByTagName('item')
		//create array of items
		nfl.log("nfl.videoplayer.thumbnails.onXMLResponse: items = "+ x.getElementsByTagName('item').length);
		nfl.log("nfl.videoplayer.thumbnails.onXMLResponse: videos = "+ x.getElementsByTagName('videos').length);
		if(items.length > 0){
			for(var i=0; i < items.length; i++){
				var item	= items[i];
				var itemXML	= "";
				//var itemXML	= item.innerHTML;
				//add attributes to item as xml
				['autoplay','body','caption','format','id','mediaFile','mediaPath','previewImage','runTime','thumbLarge','thumbSmall','video_cp','video_player_cp'].each(function(value) {
					itemXML += ("<" + value + ">" + item.getAttribute(value) + "</"+ value +">\r"); 
				});
				nfl.log("attempting to create thumbnail item with: \n\r"+ itemXML);
				this.__thumbitems[this.__thumbitems.length]	= xml2json.parser(itemXML);
			}
			/*
			x.getElementsByTagName('item').each(function(item){
				nfl.log("wt6f!!");
				var itemXML	= "";
				//var itemXML	= item.innerHTML;
				//add attributes to item as xml
				['autoplay','body','caption','format','id','mediaFile','mediaPath','previewImage','runTime','thumbLarge','thumbSmall','video_cp','video_player_cp'].each(function(value) {
					itemXML += ("<" + value + ">" + item.getAttribute(value) + "</"+ value +">\n\r"); 
				});
				nfl.log("attempting to create thumbnail item with: \n\r"+ itemXML);
			})
			while(item = x.getElementsByTagName('item')[++i]) {
				var itemXML	= item.innerHTML;
				//add attributes to item as xml
				['format', 'mediaFile', 'mediaPath', 'video_player_cp', 'id'].each(function(value) {
					itemXML += ("<" + value + ">" + item.getAttribute(value) + "</"+ value +">\n\r"); 
				});
				if(currentID && currentID == item.getAttribute('id')){
					//this item is currently the selected video
					itemXML += ("<selected>true</selected>\n\r");
				}
				//now create thumbnail xml to json data object wrapper call, add to internal array
				nfl.log("attempting to create thumbnail item with: \n\r"+ itemXML);
				this.__thumbitems[this.__thumbitems.length]	= new nfl.videoplayer.thumbnail(itemXML);
			}*/
			//generate output of items
			nfl.log("get item content..");
			var itemContent	= this.getItemHTML();
			//add fancy containers and scroll thingies  ;) (AW)
			nfl.log("create fancy containers..");
			var content	= "";
			content		+= "<div id=\"vg-thumbs-arrow-left\"></div>";
			content		+= "<div id=\"vg-thumbs-container\" style=\""+ this.thumbportsize +"\">";
			content		+= "<ul id=\"vg-list\">";
			content		+= itemContent;
			content		+= "</ul>";
			content		+= "</div>";
			content		+= "<div id=\"vg-thumbs-arrow-right\"></div>";
			//add content to container element
			nfl.log("update container object with new content..");
			$(this.containerId).update(content);
			//set hard width on #vg-list to calculated width of ((first item + first item offset) * number of items)
			var firstItem		= $('vg-list-item-'+ (this.__thumbitems[0].id));
			var secondItem		= $('vg-list-item-'+ (this.__thumbitems[1].id));
			var itemTotalWidth	= firstItem.getWidth() + 18;
			try{
				//itemTotalWidth	+= (secondItem.offsetLeft - itemTotalWidth);
			}catch(e){}
			Element.setStyle($('vg-list'),{ width: (itemTotalWidth * this.__thumbitems.length)+'px'});
			nfl.log('setting vg-list style width to ('+ itemTotalWidth +' * '+ this.__thumbitems.length +') = '+ (itemTotalWidth * this.__thumbitems.length));
			
			//wire up all thumbnails to fire an event on click
			nfl.log("wire up thumbnails for custom event support..");
			for(var u=0; u < this.__thumbitems.length; u++){
				var eleRef		= $('vg-list-item-'+ this.__thumbitems[u].id);
				eval("Event.observe(eleRef,'click',function(event){ document.fire(\"videogallery:thumbnails:click\",{thumbnail: "+ Object.toJSON(this.__thumbitems[u]) +", index: "+ u +"})})");
			}
			nfl.log("added custom events ");
			//wire up scroll handles to actions
			Event.observe($('vg-thumbs-arrow-left'),'click',function(event){ document.fire("videogallery:thumbnails:scroll",{direction:'left',id:'vg-list'});});
			Event.observe($('vg-thumbs-arrow-right'),'click',function(event){ document.fire("videogallery:thumbnails:scroll",{direction:'right',id:'vg-list'});});
			document.observe('videogallery:thumbnails:scroll',this.onScroll);
			document.fire('videogallery:thumbnails:loaded',{thumbnail: this.__thumbitems[0], index: 0});
			//document.fire("videogallery:thumbnails:click",{thumbnail: Object.toJSON(this.__thumbitems[0]), index: 0})
			$('vg-list-item-'+ this.__thumbitems[0].id).addClassName('active');
			this.__currentItem		= {thumbnail: this.__thumbitems[0], index: 0};
		}
	},
	onXMLFailure: function(){ nfl.log("nfl.videoplayer.thumbnails.onXMLFailure"); },
	getItemHTML: function(){
		var retString	= "";
		var t_template = new Template(this.itemTemplate);
		for(var u=0; u < this.__thumbitems.length; u++){
			retString += "<li id=\"vg-list-item-"+ this.__thumbitems[u].id +"\" class=\"vg-list-item\">"+ t_template.evaluate(this.__thumbitems[u]) +"</li>";
		}
		return retString;
	},
	onThumbnailClick: function(event){
		nfl.log("{nfl.videoplayer.thumbnails.onThumbnailClick}");
		//highlight current thumbnail
		nfl.log("onThumbnailClick: event.memo: \rthumbnail = "+ event.memo.thumbnail + "\rindex = "+ event.memo.index +"");
		var currentThumbObj		= event.memo.thumbnail;
		var currentThumbIndex	= event.memo.index;
		var currentItemId		= currentThumbObj.id;
		var prevItem			= this.__currentItem;
		this.__currentItem		= {thumbnail: currentThumbObj, index: currentThumbIndex};
		if(prevItem){
			this.__thumbitems[prevItem.index].selected = false;
			$('vg-list-item-'+ this.__thumbitems[prevItem.index].id).removeClassName('active');
		}
		this.__thumbitems[currentThumbIndex].selected = true;
		$('vg-list-item-'+ this.__thumbitems[currentThumbIndex].id).addClassName('active');
		nfl.log("onThumbnailClick: vg-list-item-"+ this.__thumbitems[currentThumbIndex].id +" highlighted");
		/* check to see if thumbnail is outside of viewport */
		var cThumbItem			= $('vg-list-item-'+ this.__thumbitems[currentThumbIndex].id);
		var itemOffset			= cThumbItem.viewportOffset();
		var containerOffset		= cThumbItem.up().up().viewportOffset();
		var itemVisible			= ((itemOffset.left < containerOffset.left) || (itemOffset.left > (containerOffset.left + cThumbItem.up().up().getWidth())))? false:true;
		nfl.log("onThumbnailClick: itemOffset.left("+ itemOffset.left +") < containerOffset.left("+ containerOffset.left +" || itemOffset.left("+ itemOffset.left +") > (containerOffset.left("+containerOffset.left+") + cThumbItem.up().up().getWidth()("+ cThumbItem.up().up().getWidth() +"))? "+ itemVisible);
		//nfl.log("onThumbnailClick: thumbnail item is visible? "+ itemVisible);
		if(!itemVisible){
			/* item is not in view, scroll it into view */
			/* figure out how far away we are from the view port set that this item is in */
			var itemcontainer		= cThumbItem.up();
			var containerLeft		= parseInt(itemcontainer.getStyle('margin-left'));
			var itemLeft			= cThumbItem.offsetLeft;
			var multiplier			= (itemLeft / (itemcontainer.up().getWidth()));
			if(itemOffset.left < containerOffset.left){
				direction		= "left";
				var newLeft				= (multiplier < 1)? 0 : (0 + (Math.ceil(multiplier) * itemcontainer.up().getWidth()));
			}else{
				direction		= "right";
				var newLeft				= 0 - (Math.floor(multiplier) * itemcontainer.up().getWidth());
			}
			nfl.log('onThumbnailClick: scroll item into view\rcontainerLeft:'+containerLeft+'\ritemLeft:'+itemLeft+'\rnewcontainerLeft:'+newLeft+'\rmultiplier:'+multiplier);
			itemcontainer.morph('margin-left: ' + newLeft + 'px;');
		}
	},
	onScroll: function(event){
		nfl.log("{nfl.videoplayer.thumbnails.onScroll}");
		var amountToScroll	= 0;
		direction 		= event.memo.direction;
		itemcontainer	= $(event.memo.id);
		portwidth 		= itemcontainer.up().getWidth();
		try{ 
			var itemLeft	= parseInt(itemcontainer.getStyle('margin-left'));
		}catch(e){
			itemcontainer.setStyle({'margin-left':'0px'});
			var itemLeft	= parseInt(itemcontainer.getStyle('margin-left'));
		}
		switch(direction){
			case 'left':
				amountToScroll	= (itemLeft == 0)?0:(amountToScroll + portwidth);
				break;
			case 'right':
				amountToScroll	= ((itemLeft + (0 - portwidth)) <= (0 - parseInt(itemcontainer.getStyle('width'))))?0:(amountToScroll - portwidth);
				nfl.log('('+ (itemLeft + (0 - portwidth)) +' <= (0 - '+ parseInt(itemcontainer.getStyle('width')) +') ? '+ ((itemLeft + (0 - portwidth)) <= (0 - parseInt(itemcontainer.getStyle('width')))));
				break;
			default:
				break;
		}
		nfl.log("{nfl.videoplayer.thumbnails.onScroll: amountToScroll = "+ amountToScroll +"}");
		//now perform scroll operation based on value outputs from switch statement above
		if(itemLeft % portwidth == 0){
			newLeft	= (itemLeft + amountToScroll);
			nfl.log("{nfl.videoplayer.thumbnails.onScroll: newLeft = "+ newLeft +"}");
			itemcontainer.morph('margin-left: ' + newLeft + 'px;');
			nfl.log("{nfl.videoplayer.thumbnails.onScroll: "+ event.memo.id +" morph started ");
		}else{
			nfl.log("{nfl.videoplayer.thumbnails.onScroll: item is in play: "+ itemLeft +" % "+ portwidth +" = "+ (itemLeft % portwidth) +"}");
		}
	}
}