//	Do the following when the document is ready
$(function() {
	initCategoriesMenu();
	initWidgetTabs();
	initFeaturedVideos();
	initMoreVideos();
	setPagesWidthForIE7();
	addNthChildForIE();
});

//	Events for the Categories menu in the header area.
function initCategoriesMenu() {
	$("#nav-shows")
		.mouseover(function() {
			$("#shows-menu").show();
			$("#nav-shows > a").addClass("open");
		})
		.mouseout(function() {
			$("#shows-menu").hide();
			$("#nav-shows > a").removeClass("open");
		});
}

//	Attaches events to the Related Videos / Maps tabs in the details view.
function initWidgetTabs() {
	var mapIsPresent = false;
	if ($('#map').length > 0 && $('#tab-map').length > 0) mapIsPresent = true;

	if ($('.widget-tabs').length > 0) {
		$('.widget-tabs .tabs li').click(function() {
			$('.widget-tabs .tabs li').removeClass('on');
			$(this).addClass('on');
		});
		$('#tab-video-info').click(function() {
			$('#video-info').addClass('on');
			$('#comments').removeClass('on');
			if (mapIsPresent) $('#map').removeClass('on');
		});
		$('#tab-comments').click(function() {
			$('#video-info').removeClass('on');
			$('#comments').addClass('on');
			if (mapIsPresent) $('#map').removeClass('on');
		});
		if (mapIsPresent) {
			$('#tab-map').click(function() {
				$('#video-info').removeClass('on');
				$('#comments').removeClass('on');
				$('#map').addClass('on');
			});

			var videoLat = $('#id_geo_lat').text();
			var videoLng = $('#id_geo_long').text();
			var videoLocation = new google.maps.LatLng(videoLat, videoLng);
			var myOptions = { zoom: 15, center: videoLocation, mapTypeId: google.maps.MapTypeId.ROADMAP };
			var map = new google.maps.Map(document.getElementById("map-container"), myOptions);
			var videoLocationMarker = new google.maps.Marker({ position: videoLocation, map: map });
		}
	}
}

function initFeaturedVideos() {
	//	This function is only needed for the Featured Videos area in the home page,
	//	and we'll only want to proceed if there is more than one video in that list.
	var $featuredVideosItems = $(".rotating-promo li");
	if ($featuredVideosItems.length > 1) {

		var $featuredVideos = $(".rotating-promo"),
			$featuredVideosList = $(".rotating-promo ol"),
			$featuredControls = $('<div id="featured-controls"></div>');
		
			//	Create the previous/next arrow links and icon navigation, and place them in the featured controls area.
			$featuredPrevious = $('<a id="featured-previous" href="#"><span>&lsaquo;</span></a>').appendTo($featuredControls),
			$featuredThumbnails = $('<div id="featured-thumbnails"></div>').appendTo($featuredControls),
			$featuredNext = $('<a id="featured-next" href="#"><span>&rsaquo;</span></a>').appendTo($featuredControls),
			$featuredThumbnailsList = $('<ul></ul>').appendTo($featuredThumbnails),
			//	This is to keep track of which item is currently being shown, so we know which thumbnail to highlight.
			featuredThumbnailCurrent = 0,

			//	And the following are just various calculations that we'll need shortly.
			//	In some cases we need a numerical value (for making calculations) and in others
			//	we'll need the string equivalent (assigning CSS values) so we'll have both int
			//	and string values in some cases.
			listItemCount = $featuredVideosItems.length,
			listItemWidth = $featuredVideosItems.filter(":first").width(),
			listItemWidthStr = listItemWidth + "px",
			listTotalWidth = listItemCount * listItemWidth;
			listTotalWidthStr = listTotalWidth + "px",
			listLastItemLeftPos = 0 - ((listItemCount - 1) * listItemWidth) + "px",
			listRightCloneLeftPos = 0 - (listItemCount * listItemWidth) + "px";
		
		//	Now that the featured video controls are set up, add them to the featured videos area.
		$featuredControls.appendTo($featuredVideos);

		//	In order to create the illusion of an infinitely repeating loop, we'll clone the first element 
		//	of the list and place it at the end, and also we'll clone the last element and place it 
		//	before the first element. Then, when one of these clones is shown, the animation will complete 
		//	and then the list will (invisibly to the user) instantly snap to the real list element.
		$featuredVideosItems.filter(":last").clone().addClass("clone-left").prependTo($featuredVideosList);
		//	Now that we've added a clone of the last element, which is now the first element, the REAL 
		//	first element is now the second element in the list. Hence, nth-child(2).
		$featuredVideosItems.filter(":nth-child(2)").clone().addClass("clone-right").appendTo($featuredVideosList);

		//	Link behavior for the previous button.
		$featuredPrevious.click(function() {
			//	When the Featured Videos area is in the middle of the animation, the "animated" class 
			//	is present, so we'll check for it and if it's currently there, the button does nothing.
			if (!$featuredVideos.hasClass("animating")) {
				//	We're about to start the animation so we'll add the "animating" class now.
				$featuredVideos.addClass("animating");
				$featuredVideosList.animate({'left': '+=' + listItemWidthStr}, 'slow', function() {
					//	Now the animation is finished, we'll check if the left clone is in view,
					//	and if so, we'll instantly snap the position back over to the real last item.		
					if ($featuredVideosList.css("left") == listItemWidthStr) {
						$featuredVideosList.css("left", listLastItemLeftPos);
					}
				
					//	And now for the thumbnails. First, we remove highlighting from all of them.
					$("#featured-thumbnails li").removeClass("on");
					//	Then we need to handle snapping from the first to the last element.
					//	If we're currently at 0 (the first), then we'll set this to equal the last.
					if (featuredThumbnailCurrent == 0) {
						featuredThumbnailCurrent = listItemCount - 1;
					} else {
						//	Otherwise we simply decrement by 1.
						featuredThumbnailCurrent -= 1;
					}
					//	Now that we have the new current thumbnail we can highlight it.
					$("#featured-thumbnail-" + featuredThumbnailCurrent).addClass("on");

					//	And now we're done so we can remove the "animating" class.
					$featuredVideos.removeClass("animating");
				});
			}
			//	And finally, disable the link's default behavior.
			return false;
		});
		//	The behavior for the next button is almost identical to the previous button, just subtract 
		//	from left positioning instead of add.
		$featuredNext.click(function() {
			if (!$featuredVideos.hasClass("animating")) {
				$featuredVideos.addClass("animating");
				$featuredVideosList.animate({'left': '-=' + listItemWidthStr}, 'slow', function() {
					if ($featuredVideosList.css("left") == listRightCloneLeftPos) {
						$featuredVideosList.css("left", "0px");
					}
					$("#featured-thumbnails li").removeClass("on");
					if (featuredThumbnailCurrent == listItemCount - 1) {
						featuredThumbnailCurrent = 0;
					} else {
						featuredThumbnailCurrent += 1;
					}
					$("#featured-thumbnail-" + featuredThumbnailCurrent).addClass("on");
					$featuredVideos.removeClass("animating");
				});			
			}
			return false;
		});
	
		//	Now to build the thumbnail navigation.
		$featuredVideosItems.each(function(i) {
			//	Since we need to apply behavior to the link, we'll build the thumbnail's link first.
			newLink = $('<a href="#">&nbsp;</a>').click(function() {
				//	Like the next/previous buttons, these buttons shouldn't do anything while 
				//	an animation is in progress.
				if (!$featuredVideos.hasClass("animating")) {
					//	And now for yet another animation function.
					$featuredVideos.addClass("animating");
					//	Like the other buttons that we'll get to in a minute, we'll want to stop 
					//	the automatic rotation when one of these is clicked, so we'll clear the interval.
					clearInterval(featuredVideosInterval);
					//	First we'll store the parent element since we'll reference it a few times.
					thisParent = $(this).parent();
					//	Now that we have the parent element we can set it to on.
					$("#featured-thumbnails li").removeClass("on");
					$(thisParent).addClass("on");
					//	This mess grabs the unique number from the end of the list element's ID, 
					//	so we can determine which thumbnail has been clicked and scroll to it properly.
					thisParentIDNum = parseInt($(thisParent).attr("id").slice(-1));
					//	Lastly we animate as usual, using the ID number to determine where to scroll.
					$featuredVideosList.animate({'left': 0 - (thisParentIDNum * listItemWidth) + "px"}, 'slow', function() {
						featuredThumbnailCurrent = thisParentIDNum;
						$featuredVideos.removeClass("animating");
					});
				}
				return false;
			});
			//	Now that the link is ready, we'll build the list item (with a sequential unique ID) and add to the list.
			$('<li id="featured-thumbnail-' + i + '"></li>').append(newLink).appendTo($featuredThumbnailsList);
			//	And lastly we'll highlight the first thumbnail for the initial load.
			$("#featured-thumbnail-0").addClass("on");
		});
	
		//	And finally, we'll set up the interval that instructs the featured videos area to 
		//	automatically scroll to the right after a certain interval.
		//	In this case we'll just use the usual featured-next link's click function.
		var featuredVideosInterval = setInterval("$('#featured-next').click()", 8000);
		//	In order to identify an actual click from the user vs. an automated click,
		//	there is a span inside the links. When this span is clicked, we know the user 
		//	clicked the link themself, so in that case we clear the interval.
		$("#featured-next span").click(function() {
			clearInterval(featuredVideosInterval);
		});
		$("#featured-previous span").click(function() {
			clearInterval(featuredVideosInterval);
		});
	}
}

function initMoreVideos() {
	//	This is only necessary if we're on the home page, and if the Recent Videos area is there. */
	if ($('#home #recent-videos').length > 0) {
		//	Replicate nth-child for browsers that don't support it. */
		$('#recent-videos li:nth-child(1)')
			.add('#recent-videos li:nth-child(2)')
			.add('#recent-videos li:nth-child(3)')
			.add('#recent-videos li:nth-child(4)')
			.addClass('first-row');
		//	Reveal the rest of the videos once the Expand for More link is clicked.
		$('.video-list-actions a').click(function() {
			//	This link does different things depending on whether this is the first time 
			//	it has been clicked or not. First we check for the "expanded" class. If this 
			//	doesn't exist yet, show the remaining videos, if it does, use the default 
			//	behavior for this link and redirect to the archives.
			if (!$(this).hasClass('expanded')) {
				$('#recent-videos li').show();
				$(this).addClass('expanded').text("Collapse for Less");
			} else {
				$('#recent-videos li:not(.first-row)').hide();
				$(this).removeClass('expanded').text("Expand for More");
			}
			return false;
		});
	}
}

//	Since IE7 doesn't support display: table, and there's no other way in CSS to accomplish this,
//	we need some JavaScript to set the right width for the Pages area in the header.
//	This function finds the width of the header, subtracts the widths of the logo, nav and 
//	search / back to site link to find the remaining space, and applies that width to the pages list.
function setPagesWidthForIE7() {
	//	Only go further if using IE version less than 8, and if #pages exists.
	if ($.browser.msie && $.browser.version < 8 && $("#pages").length > 0) {
		var headerWidth = $("#header").outerWidth();
		var h1Width = $("#header h1").outerWidth();
		var showsWidth = $("#shows").outerWidth();
		var topRightWidth;

		if ($("#search").length > 0) {
			topRightWidth = $("#search").outerWidth();
		} else {
			topRightWidth = $("#back-to-site").outerWidth();
		}

		$("#pages").width(headerWidth - h1Width - showsWidth - topRightWidth);
	}
}

//	In order for the videos in the grid to wrap properly I have to use CSS to select 
//	every third list element, which isn't supported in IE8 and below. So we have this 
//	function that adds the style with jQuery.
function addNthChildForIE() {
	//	Only go further if using IE version less than 9
	if ($.browser.msie && $.browser.version < 9) {
		$('#recent-videos li:nth-child(4n+1)').css("clear", "left");
	}
}
