/* my simple fade slider plugin - v0.9 */
(function(a){function b(b,c){var d=this;this.state={holder:b,list:b.children(".slider"),items:b.children(".slider").children(),total:b.children(".slider").children().length,interval:!1,current:0,controls:!1},this.settings=a.extend({},a.fn.SimpleFader.defaults,c);if(this.settings.buildControls){var e=a('<ul class="slider_controls"/>'),f=1;this.state.items.each(function(){var a=f==1?d.settings.highlightLink:"";e.append('<li><a href="#" class="replace '+a+'">'+f+"</a></li>"),f++}),this.state.holder.append(e),this.state.controls=this.state.holder.find("ul.slider_controls").find("a")}else this.state.controls=this.settings.separateControls;this.state.items.css("position","absolute").not(":first").css("opacity",0),this.addListeners(),this.settings.sliderSetup.apply(this),this.state.paused||(this.state.interval=setTimeout(function(){d.moveTo(d.state.current-0+1)},d.settings.speed))}a.fn.SimpleFader=function(c){var d={allElements:this,moveTo:function(b){return this.allElements.each(function(){var c=a(this).data("SimpleFader");c&&c.moveTo(b)}),this},pause:function(){return this.allElements.each(function(){var b=a(this).data("SimpleFader");b&&b.pause()}),this},start:function(b){return this.allElements.each(function(){var c=a(this).data("SimpleFader");c&&c.start(b)}),this},stop:function(){return this.allElements.each(function(){})}};return this.each(function(){a(this).data("SimpleFader")||a(this).data("SimpleFader",new b(a(this),c))}),d},b.prototype.addListeners=function(){var b=this;this.state.controls&&this.state.controls.bind("click",function(c){c.preventDefault(),a(this).hasClass("selected")||b.moveTo(a(this).parent().index())})},b.prototype.pause=function(){clearInterval(this.state.interval),this.state.paused=!0},b.prototype.start=function(a){var b=this;this.state.paused=!1,this.settings.speed=a||this.settings.speed,this.state.interval=setTimeout(function(){b.moveTo(b.state.current-0+1)},b.settings.speed)},b.prototype.moveTo=function(b){var c=this;clearInterval(this.state.interval),b>=this.state.total&&(b=0);switch(this.settings.fadeType){case"in-out":this.state.items.eq(this.state.current).stop().animate({opacity:0},this.settings.duration,function(){a(this).css("display","none").css("zIndex",0),c.state.items.eq(b).css("display","block").css("zIndex",2).stop().animate({opacity:1},c.settings.duration,function(){c.state.paused||(c.state.interval=setTimeout(function(){c.moveTo(c.state.current-0+1)},c.settings.speed)),c.settings.afterAnimation.apply(c)})});break;case"cross":default:this.state.items.eq(this.state.current).stop().animate({opacity:0},this.settings.duration,function(){a(this).css("display","none").css("zIndex",0)}),this.state.items.eq(b).css("display","block").css("zIndex",2).stop().animate({opacity:1},this.settings.duration,function(){c.state.paused||(c.state.interval=setTimeout(function(){c.moveTo(c.state.current-0+1)},c.settings.speed)),c.settings.afterAnimation.apply(c)})}this.state.controls&&(this.state.controls.eq(b).parent().addClass("selected").siblings().removeClass("selected"),c.state.controls.removeClass(c.settings.highlightLink).eq(b).addClass(c.settings.highlightLink)),this.state.current=b,this.settings.duringAnimation.apply(this)},a.fn.SimpleFader.defaults={speed:7e3,duration:1e3,fadeType:"cross",buildControls:!1,separateControls:!1,highlightLink:"selected",duringAnimation:function(){},afterAnimation:function(){},sliderSetup:function(){}}})(jQuery);

if($('#main_wrapper').height() < $(window).height()) {
	$('#main_wrapper').css('height',$(window).height()+'px');
}

$.thisURL = $('link[rel=index]').attr('href');
$.themeURL = $.thisURL+'wp-content/themes/partyongeorge/';

//open links with class new-window in a new window
$('a.new-window').live('click',function(e) { e.preventDefault(); window.open(this.href); return false; });

//make the height of all .tall panels the same
if($('#panels.tall').length) {
	var tallest_ = 0;
	$('#panels.tall li').each(function() {
		tallest_ = ($(this).height() > tallest_) ? $(this).height() : tallest_;
	});
	
	$('#panels.tall li').css('height',tallest_+'px');
}

if(!$('#calendar').length) {
	$('a.features').unbind().bind('click',function(e) {
		e.preventDefault();
		document.location.href = $.thisURL+'#features';
	});
}

/************************************************************** COMMON SHOW LOADER OBJECT **************************************************************/
/* show loader object */
function ShowLoader(elem,delay) {
	var scope = this;
	
	this.loadingframe = 1;
	
	var left = elem.outerWidth()/2-20+'px';
	var top = elem.outerHeight()/2-20+'px';
	
	$.themeURL = ($.themeURL.match(/undefined/)) ? '' : $.themeURL;
	elem.append('<div class="loadinggif" style="display: none; background-image: url('+$.themeURL+'images/fancy_loading.png); left: '+left+'; top: '+top+'"></div>');
	this.loadingelem = elem.find('div.loadinggif');
	if(delay == 1) { return; }
	
	this.timer = setInterval(function() { scope.Animate(); },66);
	if(delay) { setTimeout(function() { scope.Stop(); },delay); }
}

ShowLoader.prototype.Animate = function() {
	if(!this.loadingelem) { this.Stop(); return; }
	this.loadingelem.css('background-position','0 ' + (this.loadingframe * -40) + 'px').css('display','block');
	this.loadingframe = (this.loadingframe + 1) % 12;
}

ShowLoader.prototype.Stop = function() {
	this.loadingelem.css('display','none');
	clearInterval(this.timer);
}

ShowLoader.prototype.Start = function() {
	var scope = this;
	this.loadingelem.css('display','block');
	this.timer = setInterval(function() { scope.Animate(); },66);
}


$('#featured #calendar a.handle').bind('click',function(e) {
	var el = $(this);
	e.preventDefault();
	if(el.hasClass('expanded')) {
		el.removeClass('expanded');
		Calendar.hideCalendar();
	} else {
		el.addClass('expanded');
		Calendar.showCalendar();
	}
});


var PromoSlider = $('#featured-promos').each(function() {
	$(this).SimpleFader({
		buildControls	:	true,
		speed			:	5000,
		duration		:	750
	});	
});

PromoSlider.hide = function() {
	PromoSlider.stop().animate({right:-(PromoSlider.width())+'px'},500,'easeInOutQuint');
};

PromoSlider.show = function() {
	PromoSlider.stop().animate({right:0},500,'easeInOutQuint');
};

BannerSlider = {
	_holder : false,
	_animationStyle : false, //slide | fade
	_buttonPosition : 'none', //center | left | right | none
	_slides : false,
	_numSlides : 0,
	_buttons : false,
	_paused : false,
	_interval : false,
	_speed : 5000,
	_currentSlide : 0,
	_expanded : false,
	_next : false,
	_prev : false,
	
	init : function(holder,animationStyle,position) {
		var buttonHTML_ = '';
		
		this._holder = holder;
		this._animationStyle = animationStyle;
		this._slides = this._holder.children('li');
		this._width = this._slides.width();
		this._buttonPosition = position;
		
		if(this._animationStyle == 'fade') {
			this._slides.eq(0).css('opacity','1');
		}
		
		
		this._next = $('#photos_next').css('opacity',0).css('display','block');
		this._prev = $('#photos_prev').css('opacity',0).css('display','block');
		
		this._nextPrev = $('#photos_next, #photos_prev');
		
		
		
		this._numSlides = this._slides.length;
		for(i=0;i<this._numSlides;i++) {
			var class_ = (!i) ? ' class="selected" ' : '';
			buttonHTML_ += '<a href="#"'+class_+'>Banner '+(i+1)+'</a>';
		}
		
		//this._holder.append('<li class="buttons">');
		//this._buttons = this._holder.find('li.buttons');
		//this._buttons.append(buttonHTML_);
		
		//this.positionButtons();
		
		this.addListeners();
		
		if(!this._paused) {
			this._interval = setTimeout("BannerSlider.moveSlider("+(this._currentSlide+1)+");",this._speed);
		}
		
		//if the hashtag is present
		if(document.location.hash == '#features') {
			$('a.features').click();
		}
		
	},
	
	addListeners : function() {
		var scope = this;
		
		this._holder.bind('mouseenter',function() {
			if(!scope._holder.hasClass('expanded')) { return; }
			scope._next.stop().animate({opacity:1},150);
			scope._prev.stop().animate({opacity:1},150);
		});
		
		
		this._nextPrev.bind('mouseenter',function() {
			if(!scope._holder.hasClass('expanded')) { return; }
			scope._next.stop().animate({opacity:1},150);
			scope._prev.stop().animate({opacity:1},150);		
		});
		
		this._holder.bind('mouseleave',function() {
			scope._next.stop().animate({opacity:0},150);
			scope._prev.stop().animate({opacity:0},150);		
		});
		
		this._nextPrev.bind('mouseleave',function() {
			scope._next.stop().animate({opacity:0},150);
			scope._prev.stop().animate({opacity:0},150);		
		});
		
		this._nextPrev.bind('click',function(e) {
			$(this).blur();
			e.preventDefault();
			if($(this).attr('id') == 'photos_next') {
				scope.moveExpanded((scope._currentSlide+1));
			} else {
				scope.moveExpanded((scope._currentSlide-1));
			}
		});
		
		$('a.features').bind('click',function(e) {
			e.preventDefault();
			if($(document).scrollTop() > 220) { $("html:not(:animated),body:not(:animated)").animate({ scrollTop: 145}, 200 ); }
			scope.expand();
		});
		
		this._slides.css('cursor','pointer').bind('click',function(e) {
			if(scope._expanded) {
				scope.collapse();
			} else {
				scope.expand();
			}
		});;
		
		/*this._buttons.find('a').bind('click',function(e) {
			clearInterval(scope._interval); scope.moveSlider($(this).index()); $(this).blur();
			return false;
		});*/
		
	},
	
	moveSlider : function(i) {
		clearInterval(this._interval);
	
		this._animating = true;
		var scope = this;
		
		if(i >= this._numSlides) { i = 0; }
		
		var animationArgs_ = {};
		var animationObj_ = false;
		
		switch(this._animationStyle) {
			case "fade":
				//fade out the currentslide and fade in the next slide
				animationObj_ = this._slides.eq(i);
				this._slides.stop(false,true).animate({opacity:0},1000,'easeInOutQuint',function() { $(this).css('opacity',0); });
				animationArgs_['opacity'] = 1;	
				break;
			case "slide":
				animationObj_ = this._holder;
				animationArgs_['marginLeft'] = i*-this._slides.width();
				break;
		}
		
		//scope._buttons.find('a').removeClass('selected');
		//scope._buttons.find('a').eq(i).addClass('selected');
			
		animationObj_.stop(false,true).animate(animationArgs_,1000,'easeInOutQuint',function() {
			this._animating = false;
			scope._currentSlide = i;
			if(!scope._paused) { scope._interval = setTimeout("BannerSlider.moveSlider("+(scope._currentSlide+1)+");",scope._speed); }
		});
	},
	
	moveExpanded : function(i) {
		var scope = this;
		
		if(i+3>this._numSlides) { i=0; }
		if(i<0) { i=this._numSlides-3; }
		
		var animationArgs_ = {};
			animationArgs_['left'] = -this._slides.eq(i).position().left;
		
		this._holder.stop().animate(animationArgs_,250,'easeInOutCubic');
		this._currentSlide = i;
	},
	
	expand : function(cp_) {
		//here we have to totally switch the slider - in a manner of speaking
		clearInterval(this._interval);
		this._slides.stop().animate({opacity:1},500);
		this._paused = true;
		
		this._currentSlide = 0;
		this._slides.css('opacity',1).parent().removeClass('collapsed').addClass('expanded');
		this._nextPrev.fadeIn(150);
		
		var width_ = this._numSlides*322;
		
		var scope = this;
		this._holder.stop().animate({width:width_,right:-(width_-966),left:0},500,'easeInOutQuint',function() { /*scope._buttons.css('display','block'); scope.positionButtons();*/ });
		//this._slides.animate({width:966},500,'easeInOutQuint');
		//this._slides.find('img').stop().animate({left:-330},500,'easeInOutQuint',cp_);
		this._expanded = true;		
			$('#nav a').removeClass('selected').each(function() {
				if($(this).text() == 'Features') {
					$(this).addClass('selected');
					return false;
				}
			});
		
	},
	
	collapse : function(cp_) {
		var scope = this;
		
		clearInterval(this._interval);
		
		//this._slides.stop().animate({opacity:0},250).parent().removeClass('expanded').addClass('collapsed');
		this._slides.parent().removeClass('expanded').addClass('collapsed');
		this._paused = false;

		this._nextPrev.fadeOut(150);
		
		if(!cp_) { Calendar.showCalendar(); }
		
		this._holder.stop().animate({width:284,right:0,left:682},500,'easeInOutQuint',function() { /*scope._buttons.css('display','none'); scope.positionButtons();*/ });
		//this._slides.animate({width:309},500,'easeInOutQuint');
		//this._slides.find('img').stop().animate({left:0},500,'easeInOutQuint',cp_);
		this._expanded = false;
			
			scope._slides.not(':eq(0)').fadeOut(100,function() { $(this).css('display','block').css('opacity',0); });
			scope.moveSlider(0);
		
			$('#nav a').removeClass('selected').each(function() {
				if($(this).text() == 'Calendar') {
					$(this).addClass('selected');
					return false;
				}
			});
		
	},
	
	hide : function() {
		var scope = this;
		var width_ = parseInt(this._holder.css('width'));
		var right_ = this._holder.position().left+width_
		this._next.css('display','none');
		this._prev.css('display','none');
		this._holder.stop().animate({left:966},500,'easeInOutQuint',function() { /*scope.positionButtons();*/ });
	},
	
	show : function() {
		var scope = this;
		this._next.css('display','block').css('opacity',0);
		this._prev.css('display','block').css('opacity',0);
		var right_ = this._holder.position().left-parseInt(this._holder.css('width'));
		var width_ = parseInt(this._holder.css('width'));
		this._holder.stop().animate({left:682},500,'easeInOutQuint',function() { /*scope.positionButtons();*/ });
	},
	
	positionButtons : function() {
		//position it properly - (966-17*i)/2
		var left_ = 0;
		switch(this._buttonPosition) {
			case "center":
				left_ = (this._slides.width()-17*i)/2;
				break;
			case "right":
				left_ = (this._slides.width()-17*i);
				break;
			case "left":
				left_ = 0;
				break;
			case "none":
				this._buttons.css('display','none');
				break;
		}
		
		this._buttons.css('left',left_+'px');
	}
}

BarHighlight = {
	_holder : $('#featuredbar'),
	_panels : $('#panels.tall li'),
	_selected : false,

	init : function() {
		this.addListeners();
	},
	
	addListeners : function() {	
		var scope = this;
		
		$('#panels.tall li').live('click',function() {
			$(this).removeClass('selected').addClass('selected').siblings().removeClass('selected');
			scope.showPanel($(this).index());
		});
		
		$('#panels.tall li a.more').bind('click',function(e) {
			e.stopPropagation();
		});
	},
	
	showPanel : function(i) {
		if($(document).scrollTop() > 220) { $("html:not(:animated),body:not(:animated)").animate({ scrollTop: 145}, 200 ); }
		var scope = this;
		
		//if the calendar is showing or the FeaturedEvent is showing - then just call moveTo
		BannerSlider.hide();
		if(FeaturedEvent._holder.css('z-index') != -1 || parseInt(Calendar._holder.css('left')) == 0) {
			this.moveTo(i);
			Calendar.hideCalendar();
			FeaturedEvent.hideEvent(function() { FeaturedEvent.hideHolder(); });
			BannerSlider.hide();
			PromoSlider.hide();
		} else {		
			this.animateTo(i,function() {
				FeaturedEvent.hideEvent(function() { FeaturedEvent.hideHolder(); });
				Calendar.hideCalendar();
				PromoSlider.hide();
			});
		}
	},
	
	animateTo : function(i,cb_) {
		var left_ = i*-966;
		if(parseInt(this._holder.css('left')) != left_) {
			this._holder.stop().animate({left:left_},500,'easeInOutCubic',cb_);
		} else {
			if(cb_) { cb_.call(); }
		}
	},
	
	moveTo : function(i) {
		var left_ = i*-966;
		this._holder.css('left',left_);
	}
}

/* BarHighlight object */
if($('#panels.tall').length) {
	BarHighlight.init();
}

/* featured event object */
FeaturedEvent = {
	_holder : $('#featuredevent'),
	_loader : false,

	init : function() {
		this._loader = new ShowLoader(this._holder,1);
	},
	
	addListeners : function() {
		var scope = this;
		$('#featuredevent a.next, #featuredevent a.prev').live('click',function(e) {
			e.preventDefault();
			scope.loadEvent($(this).attr('href'));
		});
	},
	
	hideHolder : function() {
		var scope = this;
		this._holder.stop().animate({opacity:0},500,'easeInOutQuint',function() {
			scope._holder.css('z-index','-1').css('opacity','1');
		});
	},
	
	hideEvent : function(cb_) {
		if(parseInt(this._holder.children().css('opacity')) || !this._holder.children().filter(':animated').length) {
			this._holder.children().stop().animate({opacity:0},300,cb_);
		} else {
			if(cb_) { cb_.call(); }
		}
	},
	
	showEvent : function(cb_) {
		this._holder.css('z-index','1');
		BarHighlight._panels.removeClass('selected');
		if(!parseInt(this._holder.css('opacity')) || this._holder.filter(':animated').length) {
			this._holder.stop().animate({opacity:1},300,cb_);
		} else {
			if(cb_) { cb_.call(); }
		}
	},
	
	loadEvent : function(href_) {
		var scope = this;
		this._holder.css('z-index',1).children().css('opacity',0);
		this._loader.loadingelem.css('opacity',1);
		this._loader.Start();
		this._holder.load(href_ + ' #event',function() {
			scope._loader.Stop();
			scope._holder.children().css('opacity',0).stop().animate({opacity:1},500,'easeInOutQuint');
			
			//reinitiate the loader
			scope._loader = new ShowLoader(scope._holder,1);
		});
	},
	
	goTo : function(i) {
	
	}
}

if($('#featuredevent').length) {
	FeaturedEvent.init();
}

/* BannerSlider object */
if($('#featuredbanner').length && $('#featuredbanner:visible').length) {
	BannerSlider.init($('#featuredbanner'),'slide','center');
} else if($('#featuredbanner_side').length) {
	BannerSlider.init($('#featuredbanner_side'),'fade','center');
	//BannerSlider._buttons.css('display','none');
	
	//also add an event listener on the features link in the main nav
	$('#nav a').each(function() {
		var link = $(this).text().toLowerCase();
		
		if(link === 'features') {
			if($('html').hasClass('jac')) {
				$(this).addClass('selected').parent().siblings().children().removeClass('selected');
			}
				$(this).bind('click',function(e) {
					e.preventDefault();
					$('#nav a').removeClass('selected');
					$(this).addClass('selected');
					BarHighlight._panels.removeClass('selected');
					//expand out BannerSlider
					BannerSlider.expand();
					PromoSlider.show();
					Calendar.hideCalendar();
				});
		} else if(link === 'calendar') {
				$(this).bind('click',function(e) {
					e.preventDefault();
					$('#nav a').removeClass('selected');
					$(this).addClass('selected');
					BarHighlight._panels.removeClass('selected');
					Calendar.showCalendar();
				});
		}
	});
}

/************************************************************** MEDIA PAGE OBJECTS **************************************************************/
/* photo slider object */
MediaPhotoSlider = {
	_holder : false,	
	_loaded : [],
	_loading : false,
	_next : false,
	_prev : false,
	_total : 0,
	_galleryImages : 0,
	_maxWidth : 0,
	_currentImg : 0,
	_completedInterval : false,
	_singleShowing : false,
	_galleries : [], 			//store the index of the gallery that was loaded in here, that way, we don't need to reload galleries
	
	init : function() {
		var scope = this;
		//create the html inside #media
		$('#media').append('<ul id="photos_overlay"/>');
		$('#media').append('<a href="#" id="photos_next">Next</a>');
		$('#media').append('<a href="#" id="photos_prev">Previous</a>');
		
		this._next = $('#photos_next');
		this._prev = $('#photos_prev');
		
		this._holder = $('#photos_overlay');
		this._loading = new ShowLoader(this._holder.parent(),1);		
		
		$('#content .photos li a').each(function() {
			scope._total++;
			scope._holder.append('<li class="gallery __'+(scope._total-1)+'">&nbsp;</li>');
		});
		
		this._holder.css('height',((scope._total*438)+10)+'px');
		
		this.addListeners();
		
		//make the photos visible
		this._holder.css('visibility','visible');
		//$('#content .photos li').eq(0).children('a').addClass('selected');
		
		if(this._total) {
			this.buildGallery($('#content .photos li').eq(0).children('a'));
		}
		
	},
	
	buildGallery : function(elem) {
		var scope = this;
		
		var ind_ = elem.parent().index();
		var galName_ = elem.attr('rel')
		
		//animate the UL vertically to this li
		var thisLI_ = this._holder.find('li.__'+ind_);
		var top_ = thisLI_.position().top;
		
		this._holder.stop().animate({top:-top_,left:0},500);
		
		//if this gallery has already been loaded - no need to reload it
		scope._currentImg = 0;
		this._prev.css('display','none');
		this._next.css('display','block');
		if($.inArray(ind_,this._galleries) != -1) { 
			this._loading.Stop(); 
			this._galleryImages = thisLI_.find('img').length;
			this._singleShowing = '__'+ind_;
			return; 
		}
		
		thisLI_.animate({opacity:0},400,function() {
			$(this).load(elem.attr('href')+' #gallery',function() { 
				scope._galleries.push(ind_);
				scope._galleryImages=0;
				$(this).find('img').each(function() {
					scope._galleryImages++;
					var img_ = new Image();
					var fullsize_ = $(this).parent().attr('href');
					var caption_ = '<div class="caption"><div class="bg"></div>'+$(this).attr('alt')+'<span class="number">photo '+scope._galleryImages+' of <span class="total"></span>&nbsp;in '+galName_+'</span></div>';
					$(this).parent().parent().html('<img src="'+fullsize_+'"/>'+caption_);
				});
				
				$(this).find('span.total').html(scope._galleryImages);
				
				var width_ = (scope._galleryImages*966)+10;
				$(this).css('width',width_+'px');
				$(this).children('ul').css('width',width_+'px');
				
				if(width_ > scope._maxWidth) {
					scope._maxWidth = width_;
					scope._holder.css('width',width_+'px');
				}
				
				scope._completedInterval = setInterval("MediaPhotoSlider.checkComplete('"+ind_+"')",200)
				
			});
		});
	},
	
	checkComplete : function(galInd) {
		var state_ = this._holder.find('li.__'+galInd+' img:last').get(0).complete;
		if(state_) {
			clearInterval(this._completedInterval);
			this._loading.Stop();
			this._holder.find('li.__'+galInd).animate({opacity:1},400);
			this._singleShowing = '__'+galInd;
		}
	},
	
	addListeners : function() {
		var scope = this;
		$('#content .photos li a').bind('click',function(e) {
		
			if($(document).scrollTop() > 160) { $("html:not(:animated),body:not(:animated)").animate({ scrollTop: 145}, 400 ,'easeInOutQuint'); }
		
			e.preventDefault();
			if($('#video').css('visibility') != 'hidden') {
				$('#video').css('visibility','hidden').css('z-index',-1);
				$('#photos_next,#photos_prev').css('display','block');
				if(MediaPlayer._initiated) {
					if(MediaPlayer._jw.getState() == 'PLAYING' || MediaPlayer._jw.getState() == 'BUFFERING') {
						MediaPlayer._jw.pause(true);
					}
				}
				$('#photos_overlay').css('visibility','visible').css('z-index',1);
			}
			
			$('#controlbar').css('display','none');
			
			scope._loading.Start();
			scope.buildGallery($(this));
			
			$('#content li a').removeClass('selected');
			$(this).addClass('selected');
		});
		
		$('#photos_overlay, #photos_next, #photos_prev').bind('mouseenter',function() {
				if(scope._singleShowing) {
					scope._next.stop().animate({opacity:1},250);
					scope._prev.stop().animate({opacity:1},250);
				}
		});
		
		$('#photos_overlay, #photos_next, #photos_prev').bind('mouseleave',function() {
				if(scope._singleShowing) {
					scope._next.stop().animate({opacity:0},250);
					scope._prev.stop().animate({opacity:0},250);			
				}
		});
		
		this._next.bind('click',function(e) {
			e.preventDefault();
			//var i_ = $('#content .photos li a.selected').parent().index();
			//var next_ = (i_+1);
			//$('#content li a').removeClass('selected');
			//$('#content .photos li:eq('+next_+') a').addClass('selected');
			var next_ = parseInt(scope._currentImg)+1;
			scope.animateTo(next_);
			scope._prev.css('display','block');
			if(next_ >= (scope._galleryImages-1)) {
				$(this).css('display','none');
			}
		});
		
		this._prev.bind('click',function(e) {
			e.preventDefault();
			//var i_ = $('#content .photos li a.selected').parent().index();
			//var prev_ = (i_-1);
			//$('#content li a').removeClass('selected');
			//$('#content .photos li:eq('+prev_+') a').addClass('selected');
			var prev_ = scope._currentImg-1;
			scope.animateTo(prev_);
			scope._next.css('display','block');
			if(prev_ == 0) {
				$(this).css('display','none');
			}
		});
	},
	
	animateTo : function(i) {
		var scope = this;
		var left_ = this._holder.children('li.'+scope._singleShowing+' li:eq('+i+')').position().left;
		this._holder.stop().animate({left:-left_},500,'easeInOutQuint',function() { scope._currentImg = i; });
	},
	
	goTo : function(i) {
		var left_ = this._holder.children('li:eq('+i+')').position().left;
		this._holder.css('left',-left_+'px');		
	}
}

/* jw player object */
MediaPlayer = {
	_initiated : false,
	_holder : $('#media'),
	_videoId : 'video',

	_playlist : [],

	_loading : false,
	_changingVolume : false, //boolean/int indicating if the volume is changing - if false, then the volume isn't being changed, if not false, then an int indicating the start position of the mousedown event
	_changingPos : false,//boolean/int indicating if the position is changing - if false, then the volume isn't being changed, if not false, then an int indicating the start position of the mousedown event
	_jw : false, //reference to the jwplayer object
	
	_controls : {},
	_hideControls : true,
	_hideInterval : false, //interval for hiding the controls
	_hideDelay : 250,
	
	_changingVolume : false, //boolean/int indicating we are changing the volume
	_changingSeek : false, //boolean/int indicating we are changing the position

	init : function() {
		var scope = this;
		
		this._initiated = true;
		
		$('#content .videos li a').each(function() {
			var matched_ = $(this).attr('href').match(/\?v=(.*)$/);
			scope._playlist.push(matched_[1]);
		});
		
		$('#content .videos li a').eq(0).addClass('selected');
		
		this._controls.bar = $('#controlbar');
		this._controls.bar.css('display','block');
			this._controls.play = this._controls.bar.find('a.play');
			this._controls.progressBar = $('#progress');
			this._controls.volumeIcon = $('#volumeicon');
			this._controls.volumeSlider = this._controls.bar.find('span.volume a');
			this._controls.pause = this._controls.bar.find('a.pause');
			this._controls.elapsed = this._controls.bar.find('#elapsed span.current');
			this._controls.total = this._controls.bar.find('#elapsed span.total');
			this._controls.buffer = this._controls.bar.find('span.buffered');
			this._controls.playback = this._controls.bar.find('span.playback');
			this._controls.pos = this._controls.playback.children('a');
			this._controls.fullscreen = this._controls.bar.find('a.fullscreen');
		
		this.initPlayer();
		this._loading = new ShowLoader(this._holder,1);		
		this.addListeners();
		
		if(this._hideControls) { this.toggleControls('hide'); }
	},
	
	toggleControls : function(which) {
		if(!this._hideControls) { return; };
		//which = show | hide
		var bottom_ = (which == 'show') ? 0 : -32;
		this._controls.bar.stop().animate({bottom:bottom_},400);
	},
	
	addListeners : function() {
		var scope = this;
		
		//dont allow a fake-fullscreen in IE7 - it doesnt work right
		$('#media a').bind('click',function(e) { e.preventDefault(); $(this).blur(); });
		
		
		//swap playlist files depending on what is clicked
		//kill all previous attached event listeners - will work on the iPad and iPhone
		$('#content .videos li a').die().live('click',function(e) {
			e.preventDefault();
			$('#video, #controlbar').css('visibility','visible').css('z-index',1);
			$('#controlbar').css('z-index',2).css('display','block');
			$('#photos_next,#photos_prev').css('display','none');
			$('#photos_overlay').css('visibility','hidden').css('z-index','-1');
			scope._jw.playlistItem($(this).parent().index());
			$('#content li a').removeClass('selected');
			$(this).addClass('selected');
			scope._jw.pause(true);
			scope.jw_reset();
		});
		
		/* JW Player Control Listeners */
		if(this._hideControls) {
			$('#media').bind('mouseenter',function() { clearInterval(scope._hideInterval); scope.toggleControls('show'); });
			$('#media').bind('mouseleave',function() { clearInterval(scope._hideInterval); scope._hideInterval = setTimeout("MediaPlayer.toggleControls('hide')",scope._hideDelay); });
		}
		
		//show the volume control
		$('#volumeicon, #volume').bind('mouseenter',function() { $('#volume').stop().animate({height:90,top:-90},200); });
		$('#volumeicon, #volume').bind('mouseleave',function() { $('#volume').stop().animate({height:0,top:5},200); });
		this._controls.volumeSlider.bind('mousedown',function(e) {
			e.preventDefault();
			scope._changingVolume = e.screenY;
		});
		this._controls.pos.bind('mousedown',function(e) {
			e.preventDefault();
			scope._changingSeek = e.screenX;
			if(scope._jw.getState() != 'PAUSED') {
				scope._jw.pause(true);
			}
		});		
		
		this._controls.fullscreen.bind('click',function() {
			if($(this).hasClass('active')) {
				scope.jw_toggleFullScreen(true);
			} else {
				scope.jw_toggleFullScreen(false);
			}
		});
		
		//add escape key functionality to exit fullscreen
		$(document).keyup(function(e) { key = e.keyCode ? e.keyCode : e.charCode; if(key == 27) { scope.jw_toggleFullScreen(false); } });
		
		$('#media').bind('mousemove',function(e) {
			e.preventDefault();
			if(scope._changingVolume !== false) {
				var top_ = scope._controls.volumeSlider.position().top;
				var newTop_ = top_ + (e.screenY-scope._changingVolume);
				
				if(newTop_ < 0) { newTop_ = 0; }
				if(newTop_ > 67) { newTop_ = 67; }
				
				scope._controls.volumeSlider.css('top',newTop_+'px');
				scope._changingVolume = e.screenY;
				
				scope.jw_setVolume();
			} else if(scope._changingSeek) {
				var width_ = scope._controls.pos.parent().width();
				var newWidth_ = width_ + (e.screenX-scope._changingSeek);
				
				if(newWidth_ < 0) { newWidth_ = 0; }
				if(newWidth_ > 760) { newWidth_ = 760; }
				
				scope._controls.pos.parent().css('width',newWidth_+'px');
				
				scope._changingSeek = e.screenX;
				scope.jw_jumpTo();
			}
		});
		
		$(document).bind('mouseup',function() { 
			scope._changingVolume = scope._changingSeek = false; 
		});
		
		$('#volumeicon').bind('click',function() { scope.jw_toggleMute(false); });
		$('#controls .play, #controls .pause').bind('click',function() { if($(this).hasClass('inactive')) { return; } scope.jw_togglePlayPause(false); });
		this._controls.buffer.bind('click',function(e) { e.preventDefault(); scope.jw_seekVideoPos(e); });
		this._controls.buffer.bind('mousemove',function(e) { scope.showVideoPos(e); });
		this._controls.playback.bind('click',function(e) { e.preventDefault(); scope.jw_seekVideoPos(e); });
		this._controls.playback.bind('mousemove',function(e) { scope.showVideoPos(e); });
		/* END JW Player Control Listeners */
		

	},
	
	secondsToMinSec : function(seconds) {
		var minutes_ = Math.floor(seconds/60);
		var seconds_ = (seconds%60).toFixed();
			seconds_ = (seconds_ < 10) ? '0'+seconds_.toString() : seconds_;
		return minutes_+':'+seconds_;
	},
	
	showVideoPos : function(e) {
		if(this._jw.getState() == 'IDLE') { return; }	
		//use offsetX to calculate what position this would be
		//var totalWidth_ = e.currentTarget.offsetWidth;  //always use offsetWidth of this._controls.buffer
		var totalWidth_ = this._controls.progressBar.width();
		var thisPos_ = e.offsetX;
				
		//get the percentage
		var percentage_ = thisPos_/totalWidth_;
				
		//get the seconds as a percentage
		var thisPosInSeconds_ = (this._jw.getDuration()*percentage_).toFixed();
		var time_ = this.secondsToMinSec(thisPosInSeconds_);
		e.currentTarget.title = time_;
	},
	
	initPlayer : function() {
		var scope = this;
		//start loading the video
		var jwOptions_ = {}
			jwOptions_['flashplayer'] = $.themeURL+'js/jwplayer.swf';
			jwOptions_['height'] = 438;
			jwOptions_['width'] = 966;
			jwOptions_['wmode'] = 'transparent';
			//jwOptions_['icons'] = false;
			jwOptions_['stretching'] = 'uniform';
			jwOptions_['provider']='http';
			jwOptions_['provider']='youtube';
			jwOptions_['type']='youtube';
			//jwOptions_['streamer']='../inc/scripts/xmoov.php';
			//jwOptions_['file'] = this._playlist[0];
			//jwOptions_['file'] = "http://www.youtube.com/watch?v=2JlVqfC8-UI";
			
			//playlist
			jwPlaylist = [];
			m=0;
			for(i in this._playlist) {
				jwPlaylist[m] = { file: "http://www.youtube.com/watch?v="+this._playlist[i] }
				m++;
			}
			jwOptions_['playlist'] = jwPlaylist;
			jwOptions_['start'] = 0;
			jwOptions_['volume'] = 80;
			jwOptions_['controlbar'] = 'none';
			jwOptions_['events'] = {};
				jwOptions_['events']['onPlay'] = function() { scope.jw_togglePlayPause(true); scope.jw_loadVideoSpecs(); }
				jwOptions_['events']['onPause'] = function() { scope.jw_togglePlayPause(true); }
				jwOptions_['events']['onBufferChange'] = function(bufferObj_) { scope.jw_updateBufferPos(bufferObj_); }
				jwOptions_['events']['onTime'] = function(posObj_) { scope.jw_updateVideoPos(posObj_); }
				jwOptions_['events']['onComplete'] = function() { scope.jw_reset(); }
		jwplayer("video").setup(jwOptions_);
		
		this._jw = jwplayer(this._videoId);
	},
	
	jw_loadVideoSpecs : function() {
		var time_ = this.secondsToMinSec(this._jw.getDuration());
		if(parseInt(time_) < 0) {
			setTimeout("MediaPlayer.jw_loadVideoSpecs()",20);
			return;
		}
		this._controls.total.html(time_);
	},
	
	jw_jumpTo : function() {
		var totalWidth_ = this._controls.progressBar.width();
		var thisPos_ = this._controls.playback.width();
		var percentage_ = thisPos_/totalWidth_;
		var thisPosInSeconds_ = (this._jw.getDuration()*percentage_).toFixed();
		this._jw.seek(thisPosInSeconds_);
		this._jw.pause(true);
	},
	
	jw_seekVideoPos : function(e) {
		//use offsetX to calculate what position this would be
		//var totalWidth_ = e.currentTarget.offsetWidth;  //always use offsetWidth of this._controls.buffer
		var totalWidth_ = this._controls.progressBar.width();
		var thisPos_ = e.offsetX;
				
		//get the percentage
		var percentage_ = thisPos_/totalWidth_;
				
		//get the seconds as a percentage
		var thisPosInSeconds_ = (this._jw.getDuration()*percentage_).toFixed();
			
		//jump to that pos
		this._jw.seek(thisPosInSeconds_);

	},
	
	jw_reset : function() {
			this._controls.pos.css('visibility','hidden');
			this._controls.playback.css('width',0);		
	},
	
	jw_updateBufferPos: function(bufferObj) {
		var percentage_ = Math.round(bufferObj['bufferPercent'])+'%';
		this._controls.buffer.css('width',percentage_);
	},
	
	jw_updateVideoPos : function(posObj) {
		var percentage_ = posObj['position']/posObj['duration']*100+'%';
			this._controls.pos.css('visibility','visible');
			this._controls.playback.css('width',percentage_);
		
			var time_ = this.secondsToMinSec(posObj['position']);
			this._controls.elapsed.html(time_);
	},
	
	jw_togglePlayPause : function(from_jw) {
		//from_jw is a boolean indicating if the event came from jw player (true), or something else (false)
		if(!from_jw) {
			//update jwplayer state
			this._jw.play();
		}
		
		//update icons according to state
		switch(this._jw.getState()) {
			case "PLAYING": case "BUFFERING":
				this._controls.play.removeClass('inactive').addClass('inactive');
				this._controls.pause.removeClass('inactive');
				break;
			case "PAUSED":
				this._controls.pause.removeClass('inactive').addClass('inactive');
				this._controls.play.removeClass('inactive');
				break;
		}
	},
	
	jw_toggleMute : function() {
		//remove all possible classes
		this._controls.volumeIcon.removeClass('low').removeClass('mid').removeClass('hi');
		
		if(this._controls.volumeIcon.hasClass('mute')) {
			this._controls.volumeIcon.removeClass('mute');
			this._jw.setMute(false);
			
				var top_ = this._controls.volumeSlider.parent().height()*0.21;
				this._controls.volumeSlider.css('top',top_);
				this.jw_setVolume();
		} else {
			this._controls.volumeIcon.addClass('mute');
			this._jw.setMute(true);
			this._controls.volumeSlider.css('top','66px');
		}
	},
	
	jw_setVolume : function() {
		//get the percentage position of this._controls.volumeSlider inside of #volume .span
		var percentage_ = ((1-this._controls.volumeSlider.position().top/this._controls.volumeSlider.parent().height())*100).toFixed();
		this._jw.setVolume(percentage_);
		
		//adjust the icon depending on the percentage - remove all possible classes
		this._controls.volumeIcon.removeClass();
		
		if(percentage_ <= 7) {
			this._jw.setMute(true);
			this._controls.volumeIcon.addClass('mute');
		} else {
			if(percentage_ <= 35) {
				this._controls.volumeIcon.addClass('low');
			} else if(percentage_ <= 80) {
				this._controls.volumeIcon.addClass('mid');
			} else {
				this._controls.volumeIcon.addClass('hi');
			}
		}
		
	},
	
	jw_toggleFullScreen : function(fullscreen) {
		var ID_ = '#'+this._videoId;
		var width_ = this._controls.bar.width();
		
		//set overflow:visible on #featured and #main_wrapper
		//if fullscreen = true - make it fullscreen and removeClass('active') and addClass('inactive');
		//if fullscreen = false - resize it to the original size and removeClass('inacitve') and addClass('active')
		if(fullscreen) {
			$('#featured, #main_wrapper').css('overflow','visible');
			$(ID_).addClass('fullscreen');
			$('body').css('overflow','hidden');
			this._jw.resize($(window).width(),$(window).height());
			this._controls.bar.css('position','fixed').css('width',width_+'px').css('left',($(window).width()-width_)/2+'px');
			this._controls.fullscreen.removeClass('active').removeClass('inactive').addClass('inactive').attr('title','Exit Fullscreen');
		} else {
			$('#featured, #main_wrapper').css('overflow','hidden');
			$(ID_).removeClass('fullscreen');
			$('body').css('overflow','auto');
			this._jw.resize(966,438);
			this._controls.bar.css('position','absolute').css('width','100%').css('left',0);
			this._controls.fullscreen.removeClass('inactive').removeClass('active').addClass('active').attr('title','Show Fullscreen');
		}
	}
	
}

/* MediaPlayer object */
if($('#media').length) {
	if($('#content .photos li a').length) {
		MediaPhotoSlider.init();
	}
	
	if($('div.videos li').length) {
		$('v#ideo').attr('controls','controls');
		if((navigator.userAgent.match(/(iPhone|iPad|iPod)/i))) {
			$('#content .videos li a').live('click',function(e) {
				$('#content li a').removeClass('selected');
				$(this).addClass('selected');
				e.preventDefault();
				var matched_ = $(this).attr('href').match(/\?v=(.*)$/);
				var video_ = "videos/"+matched_[1];
				var poster_ = video_.replace(/\.mp4/,'.jpg');
				//$('#video').attr('poster',poster_);
			
				//set the background attribute of #media to the url of the poster
				var myVar_ = $(this).text();
				window[myVar_] = new ShowLoader($('#media'),false);
			
				$('#video source').attr('src',video_).parent().get(0).load();
				$('#video').bind('canplaythrough',function() { $(this).get(0).play(); window[myVar_].Stop(); });
			});
		} else {
			MediaPlayer.init();
		}
	} else {
		$('#video').remove();
	}
}
