/* MEDIA GALLERY JAVASCRIPT */
/* Copyright - ESPNDB - ESPN, INC. - 2009 */


function toggleInactiveGalleries(show) {
	jQuery("#content-slide")
		.children(".content-block")
		.not(".activeGallery")
		.each(function() {
			if (show==null || jQuery(this).is(":visible") != show) {
				if(jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0,1))<7) {
					jQuery(this).css("display",(jQuery(this).css("display")=="none"?"block":"none"));
				} else {
					jQuery(this).animate({"height": "toggle"},{ queue:false, duration:500 });
				}
				
/*				if(jQuery.browser.msie) {
					jQuery(this).css("display",(jQuery(this).css("display")=="none"?"block":"none"));
				} else {
					jQuery(this).animate({height: "toggle"},{ queue:false, duration:500 });
				}
*/			}
		});
}

function activateGallery(gallery) {
	jQuery("#content-slide")
		.children(".content-block")
		.removeClass("activeGallery");
	jQuery("#content-slide")
		.children("#"+gallery+"Gallery")
		.addClass("activeGallery");
}

function _dbMGSetSizeIcon(obj,icon) {
	obj.removeClass('show').
	removeClass('hide').
	removeClass('collapse').
	removeClass('expand').
	removeClass('blank').
	addClass(icon);
}

function _dbMGToggleSizeIcon(obj) {
	if (obj != null) {
		if (obj.is('.hide')) {
			obj.removeClass('hide').addClass('show');
		} else if (obj.is('.show')) {
			obj.removeClass('show').addClass('hide');
		} else if (obj.is('.collapse')) {
			obj.removeClass('collapse').addClass('expand');
		} else if (obj.is('.expand')) {
			obj.removeClass('expand').addClass('collapse');
		}
	}
}

function _dbMGInjectAudio(mediaObj) {
	var audioTrack = mediaObj.attr("_dbMGID");
	var autoPlay = mediaObj.is(".noauto")?"false":"true";

	jQuery(".media").media({
		bgColor: '#000000',
		width: 258,
		height: 210,
		autoplay: autoPlay,
		src: 'http://a.espncdn.com/swf/espnradio/09/audio_player_circular.swf',
		params: {
			swliveconnect: 'true',
			quality: 'best',
			scale: 'noorder',
			flashVars: '&soundLink=http://podloc.andohs.net/dloadTrack.mp3?prm=2125x'+audioTrack+'&autoStart='+autoPlay,
			bgcolor: '#000000',
			wmode: 'transparent',
			allowscriptaccess: 'always',
			salign: 'lt',
			menu: 'false',
			allownetworking:'All',
			devicefont:'false'
		}
	});
}

function _dbMGInjectPhoto(photoURL) {
}

function _dbMGInjectVideo(mediaObj) {
	var videoId = mediaObj.attr("_dbMGID");
	var autoPlay = mediaObj.is(".noauto")?"false":"true";

	jQuery(".media").media({
		bgColor: '#000000',
		width: 576,
		height: 324,
		autoplay: autoPlay,
		src: 'http://assets.espn.go.com/espnvideo/mpf22/dev/r_videoClix2/ESPN_Player.swf?id='+videoId+'&autostart='+autoPlay+'&playerType=videoClix09',
		attrs: {
			data: 'http://assets.espn.go.com/espnvideo/mpf22/dev/r_videoClix2/ESPN_Player.swf?id='+videoId+'&autostart='+autoPlay+'&playerType=videoClix09'
		},
		params: {
			flashVars: 'adminOver=3805638&player=videoClix09&height=324&width=576&autostart='+autoPlay,
			bgcolor: '#000000',
			wmode: 'transparent',
			allowscriptaccess: 'always',
			quality: 'autohigh',
			align: 't',
			swliveconnect: 'true',
			menu: 'false',
			play: 'true',
			allowfullscreen: 'true',
			seamlesstabbing: 'true',
			vcxInProduction: 'true'
		}
	});
}

function _dbMGInjectMedia (gallery,mediaObj) {
	if (gallery=='audio') {
		_dbMGInjectAudio(mediaObj);
	} else if (gallery=='video') {
		_dbMGInjectVideo(mediaObj);
	} else if (gallery=='photo') {
		_dbMGInjectPhoto(mediaObj);
	}
}

function showPlayer(imageSrc) {
	if (!jQuery("#pop-container").is(":visible")) {
		if(jQuery('.expandCollapse').is(".expand")) {jQuery('.expandCollapse').click();}
		jQuery("#imgBoxImage").attr("src",imageSrc);
		jQuery("#imgBoxImage").css("height","100%");
		jQuery("#toggleInfo").attr("src","http://assets.espn.go.com/espndb/images/mediaGallery/info_down.gif");
		jQuery("#pop-container").animate({height: "toggle"},{ queue:false, duration:1000 });
		toggleInactiveGalleries();
	} else if (imageSrc == jQuery("#imgBoxImage").attr("src")) {
	} else {
		jQuery("#imgBoxImage").animate({opacity: 'toggle'},500,"",function (event) {
			jQuery("#imgBoxImage").attr("src",imageSrc);
			jQuery("#imgBoxImage").animate({opacity: 'toggle'},250);
		});
	}
}

function toggleControlBar (show) {
	if ((show == null && parseInt(jQuery("#controlBar").css("bottom"))!=0) || (show!=null && show==true)) {
		jQuery("#controlBar").animate({bottom: "0px"},{ queue:false, duration:1500 });
		jQuery("#toggleInfo").attr("src","http://assets.espn.go.com/espndb/images/mediaGallery/info_down.gif");
	} else {
		jQuery("#controlBar").stopTime("hide-control-timer");
		$x = (20-parseInt(jQuery("#controlBar").height()))+"px"
		jQuery("#controlBar").animate({bottom: $x},{ queue:false, duration:1500 });
		jQuery("#toggleInfo").attr("src","http://assets.espn.go.com/espndb/images/mediaGallery/info_up.gif");
	}
};

function initSlider() {
	var container = jQuery('div.container-gallery');
	var containerSlider = jQuery('div.slider-container');
	var containerInner = jQuery('div.content-g');
	var header = jQuery('div.photo');

	var ul = jQuery('ul', containerInner);
	var ulWidth = ul.innerWidth();
	var containerWidth = container.outerWidth();
	var headerWidth = header.outerWidth();

	var viewPortWidth = containerWidth - headerWidth;
	var sliderMax = ulWidth - viewPortWidth;

	jQuery('.slider', containerSlider).slider({
		min: 0,
		max: sliderMax,
		handle: '.handle',
		animate: true,
		stop: function (event, ui) {
			ul.animate({'left' : (ui.value * -1)}, 500);
		},
		slide: function (event, ui) {
			ul.css('left', (ui.value * -1));
		}
	}, showSliderContainer());
}

function showSliderContainer () {
	jQuery(".slider-container").slideDown();
}

function hideSliderContainer () {
	jQuery(".slider-container").slideUp();
	jQuery(".slider").css({'width' : '0px'});
	jQuery(".handle").css({'left' : '0px'});
}

function resetSlider() {
	var containerSlider = jQuery('div.slider-container');

	jQuery(".content-g ul").css('left', '0px');
	jQuery('.slider', containerSlider).slider('destroy');
	jQuery(".slider").html('<div class="handle ui-slider-handle"></div>');
	initSlider();
}

jQuery(window).ready(function () {
	// Whether to hide the expand/collapse button. Note, this does not hide the show/hide functionality.
	var hideExpansion = true;
	
	/* Initialize Slider */
	initSlider();

	/* Hover Script */
	var elements = jQuery('.content-g li');
	jQuery.each(elements, function(i,val) {
		jQuery(this).hover(function () {
			jQuery(this).find("div.tb-hover").css({'display':'block'});
		}, function() {
			jQuery(this).find("div.tb-hover").css({'display':'none'});
		});
	});
	
	
	// Initialize expand/collapse button
	if (hideExpansion) {
		_dbMGSetSizeIcon(jQuery('div.container-gallery').find('.expandCollapse'),'blank');
	}
	

	/* Expand and Collapse */
	jQuery('.expandCollapse').click(function () {
		var $this = jQuery(this);

		if ( $this.is('.expand') ) {
				_dbMGToggleSizeIcon($this);

				hideSliderContainer();

				jQuery(".content-g").animate(
					{'width' : ((jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0,1))<7)?'579px':'584px')},
					"fast",
					function(){
						jQuery(".container-gallery").animate(
							{'width' : '612px'},
							"fast",
							function(){
								jQuery(".slider").animate(
									{'width' : '524px'},
									"fast",
									function(event){jQuery(".container-gallery").css("float","none");resetSlider();}
								);
							}
						);
					}
				);
		} else if ( $this.is('.collapse') ) {
				_dbMGToggleSizeIcon($this);

				hideSliderContainer();

				jQuery(".container-gallery").css("float","right");

				jQuery(".container-gallery").animate(
					{'width' : '302px'},
					500,
					function(){
						jQuery(".content-g").animate(
							{'width' : ((jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0,1))<7)?'269px':'274px')},
							500,
							function(){
								jQuery(".slider").animate(
									{'width' : '214px'},
									"fast",
									resetSlider()
								);
							}
						);
					}
				);
		} else if ( $this.is('.show') || $this.is('.hide')) {
			_dbMGToggleSizeIcon($this);
			toggleInactiveGalleries();
		}


		return false;
	});

	/* BEG: Animated pop-up */
	jQuery("#togglePlayer").click(function(){
		expandCollapseBtn = jQuery('div.container-gallery').find('.expandCollapse')
			.map(function() {
				return this;
			});

		jQuery("#pop-container").animate({height: "toggle"},1000,function(event){
			jQuery("#media").empty();
			//if(jQuery('.expandCollapse').is(".collapse")) {jQuery('.expandCollapse').click();}
		});
		toggleInactiveGalleries(true);
		toggleControlBar(false);

		if (!hideExpansion) {
			if (jQuery('div.container-gallery').is(".container-4")) {
				_dbMGSetSizeIcon(expandCollapseBtn,'collapse');
			} else {
				_dbMGSetSizeIcon(expandCollapseBtn,'expand');
			}
		} else {
			_dbMGSetSizeIcon(expandCollapseBtn,'blank');
		}
	});

	jQuery("#toggleInfo").click(function(){ toggleControlBar(); });

	jQuery(".dbMGMedia").click(function() {
		var onlyItem = jQuery(".container-gallery").not(":visible");
		onlyItem = false;

		var thisObj = jQuery(this);

		expandCollapseBtn = jQuery(this).parents('.container-gallery').find('.expandCollapse')
			.map(function() {
				return this;
			});
		

		gallery=jQuery(this).parents('div').map(function () { 
				if (jQuery(this).attr('id').indexOf('Gallery')!=-1) {
					return jQuery(this).attr('id').substring(0,jQuery(this).attr('id').indexOf('Gallery')); 
				} else {
					return null;
				}
			      })
			  .get().join(", ");
		
		activateGallery(gallery);

		toggleControlBar(true);

		if (jQuery("#pop-container").is(":visible")) {
//			jQuery("#videoPlayer").animate({opacity: 'toggle'},500,"",function (event) {
				_dbMGInjectMedia(gallery,thisObj);
				
//				jQuery("#videoPlayer").animate({opacity: 'toggle'},500);
//			});
			jQuery(".controlBarContent").animate({opacity: 'toggle'},500,function(event){
				jQuery("#dbCBStory").text(thisObj.attr("_dbMGStory"));
				jQuery("#dbCBHeadline").text(thisObj.attr("_dbMGHeadline"));
				jQuery("#dbCBByline").text(thisObj.attr("_dbMGByline"));
			});
			jQuery(".controlBarContent").animate({opacity: 'toggle'},500);
		} else {
			if(jQuery(expandCollapseBtn).is(".expand")) {jQuery('.expandCollapse').click();}
			
			jQuery("#toggleInfo").attr("src","http://assets.espn.go.com/espndb/images/mediaGallery/info_down.gif");

			if (onlyItem) {
				jQuery("#pop-container").css({display: "block"});
				jQuery("#togglePlayer").css({display: "none"});
			} else {
				jQuery("#pop-container").animate({height: "toggle"},{ queue:false, duration:1000 });
				toggleInactiveGalleries();
				_dbMGSetSizeIcon(expandCollapseBtn,'show');
			}
			_dbMGInjectMedia(gallery,thisObj);

			jQuery("#dbCBStory").text(thisObj.attr("_dbMGStory"));
			jQuery("#dbCBHeadline").text(thisObj.attr("_dbMGHeadline"));
			jQuery("#dbCBByline").text(thisObj.attr("_dbMGByline"));
			if (!jQuery("#videoPlayer").is(":visible")) { jQuery("#videoPlayer").animate({opacity: 'toggle'},500); }
		}

		jQuery("#controlBar").stopTime("hide-control-timer");
		jQuery("#controlBar").oneTime(12000, "hide-control-timer", function () {
			toggleControlBar(false);
		});
		

		return false;
	});

	if (jQuery(".container-gallery").find(".dbMGMedia").length==1) {
		var mediaObj = jQuery(".container-gallery").find(".dbMGMedia");
		jQuery("#togglePlayer").css({display: "none"});
		if (mediaObj.parents('.gallery_demo_unstyled').length>0) {
			if (mediaObj.not(".thumb")) {
				mediaObj.addClass("click");
			} else {
				mediaObj.click();
			}
		} else {
			jQuery(".container-gallery").find(".dbMGMedia").addClass("noauto").click();
		}
	}

	/* END: Animated pop-up */



/* GALLERIA */
	jQuery('.gallery_demo_unstyled').addClass('gallery_demo'); // adds new class name to maintain degradability

	jQuery('ul.gallery_demo').galleria({
		history   : false, // activates the history object for bookmarking, back-button etc.
		clickNext : false, // helper for making the image clickable
		insert    : '#media', // the containing selector for our main image

		onThumb : function(thumb) { // thumbnail effects goes here
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:1,'filter':'alpha(opacity=100)'}).fadeIn(1500);
			if (thumb.is(".click")) { thumb.click(); }
		},

		onContainer : function(container) { // thumbnail effects goes here
			var thumb = container.children('img');

			// hover effects
			container.hover(
				function() { 
					var _div = jQuery(document.createElement('div')).addClass('tb-hover').text((thumb.attr("_dbMGStory").length>100)?thumb.attr("_dbMGStory").substr(0,100)+"...":thumb.attr("_dbMGStory"))
						.css("display","block")
						.css("font-size",(thumb.attr("_dbMGStory").length>65)?"9px":"")
						.click(function(){thumb.click();});
					container.prepend(_div);
				},
				function() { 
					container.not('.active').children('.tb-hover').remove();
				} // don't remove if the parent is active
			)
		}
	});
});



/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});