/* 
 * INITIALIZATION AND DISPLAY SPECIFIC PHOTOGALLERY CODE FOR SUPERBOWL 43
 * @author Arianna Winters
 * 
 */

nfl.namespace('nfl.global.mutex','nfl.global.timers.photogallery');
var imagesLoaded	= 0;
/* wire up slideshow */
nfl.global.timers.photogallery.fadeout	= null;
nfl.global.timers.photogallery.slideshowstart	= null;
/* ----------------------- sub routines ----------------------- */
function reInitializeThumbnails(){
	/* new thumbnail reinitializer. smarter, stronger, faster. we have the technology (A.W)*/
	imagesLoaded++;
	var container	= $('sb43-photogallery-slideshow');
	for(var i=0; i < nfl.global.photogallery.__thumbitems.length; i++){
		var thumbnail	= nfl.global.photogallery.__thumbitems[i];
		if(thumbnail.width > 0 && thumbnail.height > 0){
			/* image has been pre-loaded*/
			if(!thumbnail.resized){
				/* thumbnail needs resizing*/
				if(thumbnail.width > 0 && !thumbnail.resized && (thumbnail.width > 937 || thumbnail.height > 600)){
					/* calculate resized image dimensions (yeah, I know)*/
					var aspectRatio	= (thumbnail.width / thumbnail.height);
					var difference	= (thumbnail.height - 600);
					var multiplyer	= (difference * aspectRatio);
					var width		= thumbnail.width - multiplyer;
					var height		= 600;
					if(width > 937){
						//alert('image is still wider than container!');
						var wdifference	= (width - 937);
						var multiplyer	= (wdifference * aspectRatio);
						width		= 937;
						height		= height - multiplyer;
					}
					nfl.log('thumbnail aspect ratio:'+ (thumbnail.width / thumbnail.height));
					nfl.global.photogallery.__thumbitems[i].width = width; nfl.global.photogallery.__thumbitems[i].height = height; nfl.global.photogallery.__thumbitems[i].resized	= true;
					thumbnail.width = width; thumbnail.height = height; thumbnail.resized	= true;
				}
			}
			var liId	= ('pg-item-'+ thumbnail.id);
			if(!$(liId)){
				/* item has not been written to dom */
				var className	= '';
				var ssContent	= '';
				var photocontentWidth	= (thumbnail.width - (35+9+9));
				if(Prototype.Browser.IE && Prototype.Browser.Version == 6){photocontentWidth = (photocontentWidth - 10);}
				var style		= 'width:'+ thumbnail.width +'px;height:'+ thumbnail.height +'px;left:'+ ((container.getWidth() / 2) - (thumbnail.width / 2)) +'px;';
				if(i===nfl.global.photogallery.defaultImage){ 
					className	= 'active';
				}else{
					style		+= 'display:none;';
				}
				console.log("thumbnail.caption = " + thumbnail.caption);
				ssContent		+= '<li class="'+ className +'" style="'+ style +'" id="pg-item-'+ thumbnail.id +'">\n';
				ssContent		+= '<img class="photo-image" src="'+ thumbnail.images.xlarge +'" width="'+ thumbnail.width +'" height="'+ thumbnail.height +'"/>\n';
				ssContent		+= '<div class="photo-watermark-header" style="width:'+ thumbnail.width +'px"><div class="photo-watermark-sheild"></div><div class="photo-content" style="width:'
									+ photocontentWidth +'px"><h2>'+(i + 1)+' of ' + 
									(nfl.global.photogallery.__thumbitems.length) + '</h2>' + thumbnail.caption + ' ' + thumbnail.source + '</div></div>\n';
				ssContent		+= '<div class="photo-controls" style="width:'+ thumbnail.width +'px; display: none;">';
				ssContent		+= '<div id="photo-controls-arrow-left" style="left:0px;"></div><div id="photo-controls-arrow-right" style="left:'+(thumbnail.width - 125)+'px"></div>';
				ssContent		+= '</div>';
				ssContent		+= '</li>\n';
				
				$('sb43-photogallery-slideshow').insert(ssContent);
				$(liId).select('img').each(function(ele){
					ele.observe('click',function(event){ document.fire("photogallery:image:click",{ele:event.element()});});
				});
				$(liId).select('.photo-controls').each(function(ele){
					ele.observe('click',function(event){document.fire("photogallery:controls:click",{ele:event.element()});});
				});
			}
		}
	}
}
function checkMouseIsOver(event){
	var mousePos	= {x:(Event.pointerX(event)),y:(Event.pointerY(event))};
	var photo		= $('sb43-photogallery-slideshow').select('li.active img.photo-image')[0];
	//alert($('sb43-photogallery-slideshow').select('li.active img.photo-image').length);
	if(photo){
		try{
			var photoOffset	= photo.cumulativeOffset();
			var photoZone	= {width:photo.getWidth(),height:photo.getHeight(),x:(photoOffset.left),y:(photoOffset.top)};
			var isInZone	= ((mousePos.x >= photoZone.x && mousePos.x <= (photoZone.x + photoZone.width)) && (mousePos.y >= photoZone.y && mousePos.y <= (photoZone.y + photoZone.height)))
			//nfl.log('is '+ mousePos.x +'x'+mousePos.y+'inside rect('+photoZone.x+','+(photoZone.x + photoZone.width)+','+photoZone.y+','+(photoZone.y + photoZone.height)+')? '+ isInZone);
			if(isInZone){
				/* pause image carousel */
				clearTimeout(nfl.global.timers.photogallery.slideshowstart); nfl.global.timers.photogallery.slideshowstart = null;
				nfl.global.photogallery.slideshow.stop();
				var ele	= photo.next();
				fadeInMetaData(ele,true);
			}else{
				if(nfl.global.lastZoneResult != isInZone && !isInZone){
					/* unpause image carousel */
					nfl.global.photogallery.slideshow.stop();
					clearTimeout(nfl.global.timers.photogallery.slideshowstart); nfl.global.timers.photogallery.slideshowstart = null;
					nfl.global.timers.photogallery.slideshowstart = setTimeout(function(){
						nfl.global.photogallery.next();
						nfl.global.photogallery.slideshow	= new PeriodicalExecuter(onSlideShowIncrement, nfl.global.photogallery.slideshowInterval);
					},((nfl.global.photogallery.slideshowInterval * 1000) / 5));
				}
			}
		}catch(e){ nfl.log('checkMouseIsOver: error. '+ e.message); }
	}
	nfl.global.lastZoneResult	= isInZone;
}
function fadeInMetaData(ele,fadeout){
	if(typeof fadeout === 'undefined'){fadeout = true; /*default to true */}
	clearTimeout(nfl.global.timers.photogallery.fadeout); nfl.global.timers.photogallery.fadeout = null;
	clearTimeout(nfl.global.timers.photogallery.controlfadeout); nfl.global.timers.photogallery.controlfadeout = null;
	if(fadeout){
		if(ele.next().getStyle('display') == 'none'){ ele.next().appear(); }
		if(ele.getStyle('display') == 'none'){
			ele.appear({afterFinish:function(){
				nfl.global.timers.photogallery.fadeout = setTimeout("fadeOutMetaData('"+ele.identify()+"')",((nfl.global.photogallery.slideshowInterval * 1000) / 2));
			}});
		}else{
			nfl.global.timers.photogallery.fadeout = setTimeout("fadeOutMetaData('"+ele.identify()+"')",((nfl.global.photogallery.slideshowInterval * 1000) / 2));
		}
	}else{
		if(ele.getStyle('display') == 'none'){ ele.appear(); }
		if(ele.next().getStyle('display') == 'none'){ ele.next().appear(); }
	}
}
function fadeOutMetaData(ele){
	if(ele){ 
		ele	= $(ele);
		//nfl.log('fadeOut has ele passed to it!!');
		ele.fade({afterFinish:function(){
			nfl.global.timers.photogallery.controlfadeout = setTimeout(function(){ele.next().fade()},(nfl.global.photogallery.slideshowInterval * 1000));
		}});
	}else{
		//alert('fade meta data out');
		try{
		}catch(e){nfl.log('fadeOutMetaData Error: '+e.message);}
	}
}
function onSlideShowIncrement(){
	if(!nfl.global.lastZoneResult){
		try{
			/* since this action occurred from a control click set display to block for next items control elements */
			var cIndex	= nfl.global.photogallery.__currentItem.index;
			var nIndex	= ((cIndex + 1) >= nfl.global.photogallery.__thumbitems.length)? 0:(cIndex + 1);
			var thumbnail	= nfl.global.photogallery.__thumbitems[nIndex];
			$('pg-item-'+thumbnail.id).select('.photo-controls')[0].hide();
		}catch(e){nfl.log('e = '+ e.message);}
		nfl.global.photogallery.next();
	}
	/* automagic scroller item focus logic moved to photogallery.thumbnails class */
}
/* ----------------------- event handlers ----------------------- */
document.observe('photogallery:load',function(){
	nfl.global.photogallery				= new nfl.photogallery.thumbnails('sb43-photogallery-thumbbar',pg,{});
	nfl.global.photogallery.containerId = 'sb43-photogallery-thumbbar';
	nfl.global.photogallery.itemWidth	= $(nfl.global.photogallery.containerId).getElementsBySelector('.row-template')[0].getWidth();
	nfl.global.photogallery.templates	= {'row':decodeURI($(nfl.global.photogallery.containerId).getElementsBySelector('.row-template')[0].getOuterHTML()),'body':'#{rows}'};
	nfl.global.photogallery.numberOfThumbsPerScrollPanel	= 12;
	nfl.global.photogallery.write();
	nfl.global.photogallery.slideshowInterval	= 8;
	nfl.global.photogallery.slideshow	= null;
	nfl.global.photogallery.adIncrementer	= 0;
	nfl.global.lastZoneResult	= false;
	nfl.global.photogallery.defaultImage	= 0;
	if(location.hash != ''){
		/* check has params for thumbnail id */
		var hparams	= window.location.hashparams.get();
		if(hparams){
			nfl.log('has hash params..');
			for(var i=0; i < nfl.global.photogallery.__thumbitems.length; i++){
				nfl.log('checking hash params for "'+ window.location.hashparams.getStringFromHash(hparams) +'".. '+ (nfl.global.photogallery.__thumbitems[i].id == hparams.get('id')));
				if(nfl.global.photogallery.__thumbitems[i].id == hparams.get('id')){
					nfl.global.photogallery.defaultImage	= i;
					break;
				}
			}
		}
	}
	/* update photogallery title element */
	$('sb43-photogallery-thumbnails').select('.sub-title')[0].update(pg.headline);
	document.observe('mousemove',checkMouseIsOver);
	/* load in initial image after first preload */
	var imagesToPreload	= [];
	for(var i=0; i < nfl.global.photogallery.__thumbitems.length; i++){
		try{
			var thumbnail	= nfl.global.photogallery.__thumbitems[i];
			imagesToPreload[i] = new Image(); 
			if(i==nfl.global.photogallery.defaultImage){
				eval('imagesToPreload['+i+'].onload=function(){var imgObject = new Image(); imgObject.src = "'+ thumbnail.images.xlarge +'"; nfl.global.photogallery.__thumbitems['+ i +'].width = (imgObject.width); nfl.global.photogallery.__thumbitems['+ i +'].height = (imgObject.height); nfl.log("preloaded image '+ i +'. dimensions are "+nfl.global.photogallery.__thumbitems['+ i +'].width+"x"+nfl.global.photogallery.__thumbitems['+ i +'].height); document.fire("photogallery:thumbnails:click",{thumbnail: nfl.global.photogallery.__thumbitems['+ i +'], index: '+ i +'}); reInitializeThumbnails(); nfl.global.photogallery.slideshow	= new PeriodicalExecuter(onSlideShowIncrement, nfl.global.photogallery.slideshowInterval);}');
			}else{
				eval('imagesToPreload['+i+'].onload=function(){var imgObject = new Image(); imgObject.src = "'+ thumbnail.images.xlarge +'"; nfl.global.photogallery.__thumbitems['+ i +'].width = (imgObject.width); nfl.global.photogallery.__thumbitems['+ i +'].height = (imgObject.height); nfl.log("preloaded image '+ i +'. dimensions are "+nfl.global.photogallery.__thumbitems['+ i +'].width+"x"+nfl.global.photogallery.__thumbitems['+ i +'].height); reInitializeThumbnails(); }');
			}
			imagesToPreload[i].src = thumbnail.images.xlarge;
		}catch(e){ nfl.log('image preloading error on #'+i); }
	}
});

/* wire up photogallery display click to slideshow */
document.observe('photogallery:image:click',function(event){
	/* image carousel should already be paused */
	nfl.global.photogallery.slideshow.stop();
	clearTimeout(nfl.global.timers.photogallery.slideshowstart);
	/* advance image carousel */
	nfl.global.photogallery.next();
});
/* wire up keypress events */
document.observe('keypress',function(event){
	var evt					= (event) ? event : window.event;
	if(evt.keyCode == Event.KEY_LEFT || evt.keyCode == Event.KEY_RIGHT){
		nfl.global.photogallery.slideshow.stop();
		clearTimeout(nfl.global.timers.photogallery.slideshowstart);
		if(evt.keyCode == Event.KEY_LEFT){
			/* go backwards */
			nfl.global.photogallery.previous();
		}
		if(evt.keyCode == Event.KEY_RIGHT){
			/* go backwards */
			nfl.global.photogallery.next();
		}
		nfl.global.photogallery.slideshow	= new PeriodicalExecuter(onSlideShowIncrement, nfl.global.photogallery.slideshowInterval);
	}
	if(evt.keyCode == Event.KEY_RETURN){
		/* toggle slidshow state*/
		if(nfl.global.photogallery.slideshow.timer == null){
			/* start */
			nfl.global.photogallery.slideshow.stop();
			nfl.global.photogallery.slideshow	= new PeriodicalExecuter(onSlideShowIncrement, nfl.global.photogallery.slideshowInterval);
		}else{
			/* stop */
			nfl.global.photogallery.slideshow.stop();
		}
	}
});
/* wire up photogallery display controls to slideshow */
document.observe('photogallery:controls:click',function(event){
	var currentEle	= event.memo.ele;
	nfl.log("photogallery:controls:click id = "+currentEle.id);
	if(currentEle.id == 'photo-controls-arrow-right'){
		nfl.global.photogallery.slideshow.stop();
		clearTimeout(nfl.global.timers.photogallery.slideshowstart); nfl.global.timers.photogallery.slideshowstart = null;
		try{
			/* since this action occurred from a control click set display to block for next items control elements */
			var cIndex	= nfl.global.photogallery.__currentItem.index;
			var nIndex	= ((cIndex + 1) >= nfl.global.photogallery.__thumbitems.length)? 0:(cIndex + 1);
			var thumbnail	= nfl.global.photogallery.__thumbitems[nIndex];
			$('pg-item-'+thumbnail.id).select('.photo-controls')[0].show();
		}catch(e){nfl.log('e = '+ e.message);}
		nfl.global.photogallery.next();
	}
	if(currentEle.id == 'photo-controls-arrow-left'){
		nfl.global.photogallery.slideshow.stop();
		clearTimeout(nfl.global.timers.photogallery.slideshowstart); nfl.global.timers.photogallery.slideshowstart = null;
		try{
			/* since this action occurred from a control click set display to block for next items control elements */
			var cIndex	= nfl.global.photogallery.__currentItem.index;
			var nIndex	= ((cIndex - 1) < 0)? (nfl.global.photogallery.__thumbitems.length - 1):(cIndex - 1);
			var thumbnail	= nfl.global.photogallery.__thumbitems[nIndex];
			$('pg-item-'+thumbnail.id).select('.photo-controls')[0].show();
		}catch(e){nfl.log('e = '+ e.message);}
		nfl.global.photogallery.previous();
	}
});
/* wire up photogallery display to thumb click */
document.observe('photogallery:thumbnails:click',function(event){
	clearTimeout(nfl.global.timers.photogallery.fadeout);
	var thumbnail	= event.memo.thumbnail;
	thumbnail.index	= event.memo.index;
	/* fade out current photo */
	var container	= $('sb43-photogallery-slideshow');
	var currentItems	= container.select('li.active');
	var nextItem	= $('pg-item-'+ thumbnail.id);
	if(nextItem && nextItem.id !== currentItems[0].id){
		currentItems.each(function(item){item.fade();}.bind(this));
		nextItem.select('.photo-watermark-header')[0].show();
		nextItem.appear({afterFinish:function(){
			/* remove old items active class */
			$('sb43-photogallery-slideshow').select('li.active').each(function(item){item.removeClassName('active'); if(item.getStyle('display') !== 'none'){ item.fade(); /* this is a redundant check to prevent possible overlapping images */}});
			/* re-assign to current item */
			nextItem.addClassName('active');
			ele	= nextItem.select('.photo-watermark-header')[0];
			nfl.global.timers.photogallery.fadeout	= setTimeout("fadeOutMetaData('"+ele.identify()+"')",((nfl.global.photogallery.slideshowInterval * 1000) / 4));
		}});
	}
});
/* add another listener for ad rotator code */
document.observe('photogallery:thumbnails:click',function(event){
	nfl.global.photogallery.adIncrementer++;
	if(nfl.global.photogallery.adIncrementer > 7){
		/* rotate ad */
		nfl.log('rotate ad');
		var container	= $('sb43-photogallery-bottom-ad').select('.adcontainer')[0];
		nfl.ads.collection.each(function(Ad){
			if(Ad.id == (container.id+'-iframe')){ 
				Ad.update(Ad); 
			}
		});
		/* clear incrementer */
		nfl.global.photogallery.adIncrementer = 0;
	}
});