var videoShowing = false;
var playMultiple = false;
$(function() {
	if ($('body').hasClass('home')) {
		var loaded2 = false;
		var timePassed = false;
		var msg1 = $(new Image());
		msg1.load(function() {
			$('#loader').after('<div id="msg1" class="homeSwap" _count="8" _curr="-1" _dir="f"></div>');
			var firstMsg = $('#msg1');
			firstMsg.attr('_timer', setInterval(function() {
				switchImage(firstMsg);
			}, 63));
			$('#loader').remove();
			setTimeout(function() {
				timePassed = true;
				if (loaded2) {
					homeMsg2Show();
				}
			}, 3500);
		}).attr('src', 'images/homeHighSchool.jpg');

		var msg2 = $(new Image());
		msg2.load(function() {
			if (timePassed) {
				homeMsg2Show();
			} else {
				loaded2 = true;
			}
		}).attr('src', 'images/homeSeeWhy.jpg');
		$('#homeButtonsBg').css({'display': 'block', 'opacity': 0});

	}
	$('#homeStats, #seeVideos, #seeHeroes, #knowTheFactsLink').mouseenter(function() {
		var anim = $(this).find('div');
		var delay = 63;
		if (this.id == 'seeVideos' || this.id == 'knowTheFactsLink' || this.id == 'seeHeroes') delay = 50;
		anim.attr({'_over': 'true', '_timer': setInterval(function() {
			smallAnims(anim);
		}, delay)});
	}).mouseleave(function() {
		$(this).find('div').attr('_over', 'false');
	}).click(function() {
		$(this).trigger('mouseleave');
		return true;
	});
	$('#seePhotos').mouseenter(function() {
		$(this).attr({'_over': 'true'});
		(function fadeNext() {
			if ($('#seePhotos').attr('_over') != 'true') return;
			var curr = $('#seePhotos').find('img.current');
			var next = curr.prev('img');
			if (next.length == 0) next = $('#seePhotos').find('img:last');
			curr.fadeOut(300).removeClass('current');
			next.fadeIn(300, function() {
				$('#seePhotos').attr('_timer', setTimeout(fadeNext, 700));
			}).addClass('current');
		})();
	}).mouseleave(function() {
		$(this).attr('_over', 'false');
		clearTimeout($(this).attr('_timer'));
	}).click(function() {
		$(this).trigger('mouseleave');
		return true;
	});
	$('#homeTakeAction, #getInvolved').mouseenter(function() {
		var $this = $(this);
		$this.css('background-position', '0 -' + $this.height() + 'px');
		setTimeout(function() {
			$this.css('background-position', '0 -' + ($this.height() * 2) + 'px');
		}, 50);
	}).mouseleave(function() {
		var $this = $(this);
		$this.css('background-position', '0 -' + $this.height() + 'px');
		setTimeout(function() {
			$this.css('background-position', '0 0');
		}, 50);
	});

	$('#moviePlayer').each(function() {
		if ($('#previews').length == 0) {
			showPolicyVideo($('#movieFrame').attr('_origId'));
		} else {
			$('#previews').click(function() {
				if ($('#movieFrame').attr('_playMulti') == 'true') {
					playMultiple = true;
					currCue = 0;
					showVideo(playlist[currCue]);
				} else {
					showVideo($('#movieFrame').attr('_origId'));
				}
			});
			$('#showPreview').click(function() {
				showVideo($(this).attr('_id'));
				$(window).scrollTop(0);
				return false;
			})
		}
	});
	$('#previews').each(function() {
		var firstTime = true;
		if ($('#previews img').length == 2) {
			(function swapPreview() { 
				if (!firstTime) {
					if (!$('#previews').hasClass('hidden')) {
						$('img.previewImg').each(function() {
							var $this = $(this);
							if ($this.hasClass('current')) {
								$this.removeClass('current').animate({left: 578}, 500);
							} else {
								$this.css({left: -578}).addClass('current').animate({left: 0}, 500);
							}
						});
					}
				}
				firstTime = false;
				setTimeout(swapPreview, 5000);
			})();
		} else if ($('#previews img').length > 2) {
			$('#previews img:not(.current)').css({left: -578});
			(function swapPreview() { 
				if (!firstTime) {
					if (!$('#previews').hasClass('hidden')) {
						$('img.previewImg').each(function() {
							var $this = $(this);
							if ($this.hasClass('current')) {
								$this.removeClass('current').animate({left: 578}, 500);
								var next = $this.next('img:first');
								if (next.length == 0) next = $('#previews img:first');
								next.css({left: -578}).addClass('current').animate({left: 0}, 500);
								return false;
							}
						});
					}
				}
				firstTime = false;
				setTimeout(swapPreview, 5000);
			})();
		}
	});
	$('div.videoGroup a').mouseenter(function() {
		if (!$.browser.msie || !videoShowing) {
			var $this = $(this);
			var height = 164;
			if (this.id == 'parentRight1' || this.id == 'communityRight4') height = 189;
			else if (this.id == 'communityLeft1') height = 178;
			$this.stop().animate({top: $this.attr('_fullTop'), height: height, width: 208}, 300);
			$this.find('img').css('display', 'block');
		}
	}).mouseleave(function() {
		var $this = $(this);
		$this.stop().animate({top: $this.attr('_origTop'), height: $this.attr('_origHeight'),
			width: $this.attr('_origWidth')}, 300, function() {
			$this.find('img').css('display', 'none');
		});
	}).each(function() {
		var $this = $(this);
		$this.attr({'_origHeight': $this.height(), '_origWidth': $this.width(), '_origTop': $this.position()['top'], '_origLeft': $this.position()['left']});
	}).click(function() {
		playMultiple = false;
		showVideo($(this).attr('_id'));
		$(this).trigger('mouseleave');
		return false;
	});
	if ($('#leadersQuotes').length > 0) {
		var firstTime = true;
		(function rotateQuotes() {
			if (!firstTime) {
				var curr = $('#leadersQuotes div.current');
				var next = curr.next('div.quote');
				if (next.length == 0) next = $('#leadersQuotes div.quote:first');
				curr.animate({left: 150, opacity: 0}, 500).removeClass('current');
				next.css({display: 'block', opacity: 0, left: -150}).animate({left: 0, opacity: 1}, 750).addClass('current');
			} else {
				firstTime = false;
			}
			setTimeout(rotateQuotes, 7000);
		})();
	}
	$('#back').click(function() {
		history.back();
		return false;
	});

	$('#videoList').find('a').click(function() {
		showPolicyVideo($(this).attr('_origId'));
		return false;
	});
});
function homeMsg2Show() {
	var firstMsg = $('#msg1');
	var onFinishFirst = function() {
		firstMsg.after('<div id="msg2" class="homeSwap" _count="8" _curr="0" _dir="f"></div>');
		var secondMsg = $('#msg2');
		secondMsg.attr('_timer', setInterval(function() {
			switchImage(secondMsg, setupHomeButtons);
		}, 63));
	};
	firstMsg.attr({'_dir': 'r', '_timer': setInterval(function() {
			switchImage(firstMsg, onFinishFirst);
		}, 63)
	});
}
function setupHomeButtons() {
	$('#homeTeensHover, #homeParentsHover, #homeCommunityHover').css({display: 'block', opacity: 0});
	$('#homeButtons a').mouseenter(function() {
		$('#' + this.id + 'Hover, #homeButtonsBg').stop().animate({opacity: 1}, 400);
	}). mouseleave(function() {
		$('#' + this.id + 'Hover, #homeButtonsBg').stop().animate({opacity: 0}, 400);
	});
	currShowing = $('#msg2');
	$('div.hoverable').each(setupHoverable);
}
function switchImage(item, onFinish) {
	var next = parseInt(item.attr('_curr'));
	if (item.attr('_dir') == 'f') {
		item.css('background-position', '0px -' + (item.height() * (next -1)) + 'px');
		next++;
		item.attr('_curr', next);
		if (next >= parseInt(item.attr('_count'))) {
			next = parseInt(item.attr('_count'));
			// need to stop it
			clearInterval(item.attr('_timer'));
			item.attr('_timer', -1);
			if (onFinish) {
				onFinish();
			}
		}
	} else {
		next--;
		var offset = (-item.height() * (next -1));
		item.css('background-position', '0px ' + offset + 'px');
		item.attr('_curr', next);
		if (next <= 0) {
			// need to stop it
			clearInterval(item.attr('_timer'));
			item.attr('_timer', -1);
			if (onFinish) {
				onFinish();
			}
		}
	}
}
function setupHoverable() {
	var id = this.id;
	var anim = $(this);
	var target = id.substring(0, id.length - 3);
	target = $('#' + target);
	anim.attr({'_curr': '0', '_dir': 'r', '_timer': -1});

	target.mouseenter(function() {
		target.attr('_over', 'true');
		if (parseInt(anim.attr('_timer')) > -1) {
			// already going, just ensure the direction is correct
			anim.attr('_dir', 'f');
			animQueueClear();
		} else {
			animQueueAdd(anim);
		}
	}).mouseleave(function() {
		target.attr('_over', 'false');
		if (parseInt(anim.attr('_timer')) > -1) {
			// already going, just ensure the direction is correct
			anim.attr('_dir', 'r');
		}
		setTimeout(function() {
			if ($('#homeButtons a[_over=true]').length == 0) {
				animQueueAdd($('#msg1'));
			}
		}, 100);
	});
}
var animating = false;
var animQueue = [];
var currShowing = null;
var idleTimer = -1;
var idleCurrent = 'msg2';
function animQueueAdd(newItem) {
	animQueue.push(newItem);
	playNext();
}
function playNext() {
	if (animating) {
		return;
	}
	if (animQueue.length > 0) {
		animating = true;
		var anim = animQueue[animQueue.length - 1];
		animQueueClear();
		var showNext = function() {
			var overBtn = $('#homeButtons a[_over=true]');
			if (overBtn.length > 0 && overBtn.attr('id') != anim.attr('id')) {
				// need to switch to the latest in the queue
				anim = $('#' + overBtn.attr('id') + 'Msg');
				animQueueClear();
			}
			currShowing = anim;
			anim.attr({'_dir': 'f', '_timer': setInterval(function() {
				switchImage(anim, animEnded);
			}, 63)});
		};
		var revAnim = currShowing;
		currShowing = null;
		revAnim.attr({'_dir': 'r', '_timer': setInterval(function() {
				if (animQueue.length > 0 && animQueue[animQueue.length - 1].attr('id') == revAnim.attr('id')) {
					animQueueClear();
					revAnim.attr('_dir', 'f');
					currShowing = revAnim;
					showNext = animEnded;
				}
				switchImage(revAnim, showNext);
			}, 63)
		});
	}
} 
function animEnded() {
	animating = false;
	if (currShowing && currShowing.attr('id') == 'msg1') {
		// need to run through the second part
		setTimeout(function() {
			if (currShowing && currShowing.attr('id') == 'msg1' && animQueue.length == 0) {
				animQueueAdd($('#msg2'));
			}
		}, 3500);
	}
	playNext();
}
function animQueueClear() {
	animQueue = [];
}
function resetIdleTimer() {
	clearTimeout(idleTimer);
	idleTimer = setTimeout(function() {
		if ($('#homeButtons a[_over=true]').length == 0) {
			
			if (idleCurrent == 'homeCommunity') {
				idleCurrent = 'msg1';
			} else if (idleCurrent == 'msg1') {
				idleCurrent = 'msg2';
			} else if (idleCurrent == 'msg2') {
				idleCurrent = 'homeTeens';
			} else if (idleCurrent == 'homeTeens') {
				idleCurrent = 'homeParents';
			} else if (idleCurrent == 'homeParents') {
				idleCurrent = 'homeCommunity';
			}
			
		}
	}, 5000);
}
function smallAnims(item) {
	var next = parseInt(item.attr('_curr'));
	next++;
	item.attr('_curr', next);
	if(item.attr('_over') == 'false') {
		// need to stop it
		clearInterval(item.attr('_timer'));
		item.attr({'_timer': -1, '_curr': 1});
		next = 1;
	} else if (next > parseInt(item.attr('_count'))) {
		item.attr({'_curr': 1});
		next = 1;
	} 
	item.css('background-position', '0px -' + (item.height() * (next -1)) + 'px');
}
function onYouTubePlayerReady(playerid) {
	document.getElementById('moviePlayer').addEventListener('onStateChange', 'playerStateChange');
	videoLoaded = true;
	document.getElementById('moviePlayer').playVideo();
}
var currCue = 0;
function playerStateChange(newState) {
	if (newState == 0) {
		//ended, let's see what we should do next
		if (playMultiple) {
			if ((currCue + 1) == playlist.length) {
				// hit the end
				playMultiple = false;
				currCue = 0;
				playerStateChange(0);
			} else {
				currCue++;
				showVideo(playlist[currCue]);
			}
		} else {
			$('#previews').removeClass('hidden').fadeIn(500);
			if ($.browser.msie) {
				$('#moviePlayer').css('display', 'none');
				videoShowing = false;
			}
		}
	}
}
var videoLoaded = false;
function showVideo(id) {
	if (!videoLoaded) {
		var params = {allowScriptAccess: 'always', allowFullScreen: 'true'};
		var atts = {id: 'moviePlayer', wmode: 'transparent'};
		swfobject.embedSWF('http://www.youtube.com/v/' + id + '&enablejsapi=1&playerapiid=player1&rel=0&showsearch=0&showinfo=0&fs=1', 
                   'moviePlayer', '578', '350', '8', null, null, params, atts);
	} else {
		document.getElementById('moviePlayer').loadVideoById(id);
		if ($.browser.msie) {
			videoShowing = true;
			$('#moviePlayer').css('display', 'block');
		}
	}
	$('#previews').fadeOut(500).addClass('hidden');
}
function showPolicyVideo(id) {
	if (id) {
	if (!videoLoaded) {
		var params = {allowScriptAccess: 'always', allowFullScreen: 'true'};
		var atts = {id: 'moviePlayer', wmode: 'transparent'};
		swfobject.embedSWF('http://www.youtube.com/v/' + id + '?enablejsapi=0&playerapiid=player1&rel=0&showsearch=0&showinfo=1&fs=0', 
                   'moviePlayer', '578', '350', '8', null, null, params, atts);
	} else {
		document.getElementById('moviePlayer').loadVideoById(id);
		if ($.browser.msie) {
			videoShowing = true;
			$('#moviePlayer').css('display', 'block');
		}
	}
	}
}
