//	Do the following when the document is ready
$(function() {
	initShowsMenu();
	initSearch();
	initDeleteItemButtons();
	initDatePickers();
	textOverflowEllipsis();
	initAutoFocus();
	initWidgetTabs();
	initSetLocation();
	scoldIE6Users();
	initFeaturedVideos();
});

function initShowsMenu() {
	$("#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 Search field. */
function initSearch() {
	$("#search-input")
		.focus(function() {
			if (this.className == "") this.value = "";
		})
		.change(function() {
			this.className = "has-text";
		})
		.blur(function() {
			if (this.value == "") this.className = "";
			if (this.className == "") this.value = "Search Videos";
		});
}

//	Upload Video page functions
function showUploadMethod() {
	$("#mediaspace").scrollTo(0, 1000, {axis:'x'});
}
function showUploadAndConvert() {
	$("#method-upload-convert").css("z-index", "3");
	$("method-youtube").css("z-index", "2");
	$("#mediaspace").scrollTo(640, 1000, {axis:'x'});
}
function showSlurpFromYouTube() {
	$("#method-upload-convert").css("z-index", "2");
	$("method-youtube").css("z-index", "3");
	$("#mediaspace").scrollTo(1280, 1000, {axis:'x'});
}

//	Edit Item page functions
function initDeleteItemButtons() {
	$('.delete-item-btn').click(function() {
		//	If the confirmation paragraph hasn't yet been created...
		if ($(".delete-item-confirm").length == 0) {
			//	...create it, and then add it right after the Delete button.
			//	This includes an actual working Delete button for "Yes" and a "No" button that hides the paragraph 
			//	by calling the cancelDeleteItem() function below.
			var confirmationParagraph = $('<p class="delete-item-confirm">Are you sure? This is your last warning!<br /><input class="button-small" name="Delete" type="submit" value="Yes, delete it" /> <input class="button-small" type="button" value="No, cancel!" onclick="cancelDeleteItem()" /></p>');
			$(this).after(confirmationParagraph);
		}
		//	Now fade in the new confirmation paragraph.
		$(".delete-item-confirm").fadeIn("fast");
		
		//	Lastly, ensure this button doesn't execute it's usual delete action.
		return false;
	});
}

function cancelDeleteItem() {
	$(".delete-item-confirm").fadeOut("fast");
}

function initDatePickers() {
	//	If there aren't any inputs of id "date-pick" in the page, we stop here.
	//	(I would go by the id but we potentially use 'id_date' on other pages that don't have date pickers)
	if ($('.date-pick').length > 0) {
		//	The Date function's default is dd/mm/yyyy but thankfully we can change that here.
		Date.format = 'mm/dd/yyyy';
		//	First we grab the value of the hidden input with the original upload date for the item...
		var originalDateValue = $('#id_upload_date').attr('value');
		//	...and then pass it to the datePicker function, which will create a picker with the current date selected.
		$('.date-pick').datePicker({ startDate: '01/01/1996', endDate: originalDateValue });
	}
}

function textOverflowEllipsis() {
	//	This is my implementation of CSS 3's 'text-overflow: ellipsis', which is currently not supported
	//	by Firefox. Until they get their act together, I have to do this crap.
	//	If there is nothing in the page classed with 'text-overflow-ellipsis', stop here.
	$('.text-overflow-ellipsis').each(function() {
		//	For each element classed with 'text-overflow-ellipsis'...
		//	We'll need the width of the element, and the width of its parent.
		var elemWidth = $(this).width();
		var parentWidth = $(this).parent().width();
		var elemText;
		
		//	If the element is wider than its parent, then we'll operate on it. Otherwise stop here.
		if (elemWidth > parentWidth) {
			//	Repeat the following until the element is not wider than its parent...
			while(elemWidth > parentWidth) {
				//	First we'll grab the text of the element...
				elemText = $(this).text();
				//	Then we'll get its length in characters...
				elemTextLength = elemText.length;
				//	Then we'll trim one character off the end...
				elemText = elemText.substr(0, elemTextLength - 1);
				//	Then we'll put that back into the element's text.
				$(this).text(elemText);
				//	Lastly we'll grab the new width and re-iterate the while loop if necessary.
				elemWidth = $(this).width();
			}
		
			//	Next we'll remove a couple characters to make room for the ellipsis we'll add to the end.
			elemTextLength = elemText.length;
			elemText = elemText.substr(0, elemTextLength - 2);
			//	Then we'll add the ellipsis.
			elemText = elemText + "...";
			//	Finally we insert the new text into the document and we're done.
			$(this).text(elemText);
		}
	});
}

//	For when we have textareas or inputs intended to have their contents copied.
//	When the user clicks on them this will select all inner text right away.
function initAutoFocus() {
	$('.auto-focus').click(function() {
		$(this).select();
	});
}

function initWidgetTabs() {
	var mapIsPresent = false;
	var shareIsPresent = false;
	if ($('#map').length > 0 && $('#tab-map').length > 0) mapIsPresent = true;
	if ($('#share').length > 0 && $('#tab-share').length > 0) shareIsPresent = true;

	if ($('.widget-tabs').length > 0) {
		$('.widget-tabs .tabs li').click(function() {
			$('.widget-tabs .tabs li').attr('class', '');
			$(this).attr('class', 'on');
		});
		$('#tab-related-videos').click(function() {
			if (mapIsPresent) $('#map').attr('class', '');
			if (shareIsPresent) $('#share').attr('class', '');
			$('#related-videos').attr('class', 'on');
		});
		if (mapIsPresent) {
			$('#tab-map').click(function() {
				$('#related-videos').attr('class', '');
				if (shareIsPresent) $('#share').attr('class', '');
				$('#map').attr('class', '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 });
		}
		if (shareIsPresent) {
			$('#tab-share').click(function() {
				$('#related-videos').attr('class', '');
				if (mapIsPresent) $('#map').attr('class', '');
				$('#share').attr('class', 'on');
			});
		}
	}
}

function initSetLocation() {
	//	This function is only needed for the New Item and Edit Item pages.
	if ($('#new-item').length > 0 || $('#edit-item').length > 0) {
		//	First we grab the initial values of that lat and lng fields, to determine
		//	if we already have location data.
		var initialLatValue = $('#id_geo_lat').attr('value');
		var initialLngValue = $('#id_geo_long').attr('value');
		//	This is the default location for when there is no location data.
		var defaultLatLng = new google.maps.LatLng(37.7749295, -122.4194155);	// San Francisco
		
		//	If lat and lng values have not been provided...
		if (initialLatValue == '' || initialLngValue == '') {
			//	... then set the initial location to San Francisco,
			var initialLatLng = defaultLatLng;
			//	and make the marker invisible.
			var initialMarkerVisibility = false;
		} else {
			//	Otherwise, set the initial location to the provided lat/lng,
			var initialLatLng = new google.maps.LatLng(initialLatValue, initialLngValue);
			//	make the marker visible,
			var initialMarkerVisibility = true;
			//	and show the "location set" text immediately.
			$('#location-not-set').hide();
			$('#location-set').show();
		}
		
		//	Now that we've got that out of the way, we can initialize the map.
		var myOptions = { zoom: 15, center: initialLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP };
		var map = new google.maps.Map(document.getElementById('map-container'), myOptions);
		var geocoder = new google.maps.Geocoder();
		var videoLocationMarker = new google.maps.Marker({ position: initialLatLng, map: map, draggable: true, visible: initialMarkerVisibility });

		//	This provides the ability for the user to click anywhere on the map
		//	and immediately place a marker there.
		google.maps.event.addListener(map, 'click', function(e) {
			//	The event contains the latitutde and longitude of the point where the user clicked,
			//	so we merely show the marker and set its location to that point.
			videoLocationMarker.setPosition(e.latLng);
			videoLocationMarker.setVisible(true);
			map.setCenter(e.latLng);
			//	And then send the latitude/longitude values to our form fields.
			$('#id_geo_lat').attr('value', e.latLng.lat());
			$('#id_geo_long').attr('value', e.latLng.lng());
			//	Then we "refresh" the "location set" area to notify the user that it was updated.
			$('#location-not-set').hide();
			$('#location-set')
				.hide()
				.fadeIn('fast');
		});

		//	This sets the behavior for when the map's marker is dragged.
		google.maps.event.addListener(videoLocationMarker, 'dragend', function() {
			//	This is easy, we just get the current location of the marker...
			pt = videoLocationMarker.getPosition();
			//	And then send the latitude/longitude values to our form fields.
			$('#id_geo_lat').attr('value', pt.lat());
			$('#id_geo_long').attr('value', pt.lng());
			//	Then we "refresh" the "location set" area to notify the user that it was updated.
			$('#location-set')
				.hide()
				.fadeIn("fast");
		});

		$('#map-search-submit').click(function() {
			//	First get the current value of the search field.
			var searchValue = $('#map-search-input').attr("value");
			//	Then we submit a geocode request with that search value.
			geocoder.geocode({ 'address': searchValue }, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					//	First we center the map on the search results...
					map.setCenter(results[0].geometry.location);
					//	Set the marker's position to the search locations.
					videoLocationMarker.setPosition(results[0].geometry.location);
					videoLocationMarker.setVisible(true);
					$('#id_geo_lat').attr('value', results[0].geometry.location.lat());
					$('#id_geo_long').attr('value', results[0].geometry.location.lng());
					//	Now that we have a location, we hide the "not set" text...
					$('#location-not-set').hide();
					//	And then fade in the "location set" text.
					$('#location-set')
						.hide()
						.fadeIn("fast");
				} else {
					console.log("Google Maps geocode failed: ", status);
				}
			});
		});
	
		$('#clear-geo-container-link').click(function() {
			//	Removes the map's marker from view
			videoLocationMarker.setVisible(false);
			//	Clears the values for the search, lat, and lng fields
			$('#map-search-input').attr('value', '');
			$('#id_geo_lat').attr('value', '');
			$('#id_geo_long').attr('value', '');
			//	Resets the location area to the "not set" state
			$('#location-set').hide();
			$('#location-not-set').show();
			//	Resets the map to center over the default location
			map.setCenter(defaultLatLng);
			map.setZoom(15);
			//	Nullifies normal link behavior for this link
			return false;
		});
	
		//	We also want to intercept a keypress on the enter key, 
		//	so that if the key is pressed when entering a search, it doesn't submit the whole form.
		$('#map-search-input').keypress(function(e) {
			//	The enter key's keyCode is 13, so we'll check if the event's keyCode is 13.
			//	If not, do nothing and proceed as normal.
			if (e.keyCode == 13) {
				//	First we execute an onclick event on the Search button.
				$('#map-search-submit').click();
				//	Then we return false, to prevent anything else from happening (i.e. submitting the form)
				return false;
			}
		});
	}
}

//	Because having to support IE6 is something no one should have to deal with.
function scoldIE6Users() {
	//	IE6 doesn't have this function, so we're singling out IE6 here. Other, better browsers do nothing here.
	if (!window.XMLHttpRequest) {
		//	Now we build out a nice litle window to go at the top of the screen.
		//	I've chosen to do this in the JS instead of the HTML because this is a fast way to make it site-wide,
		//	and I don't want IE6-specific code sitting in each page.
		//	The following code is pretty crappy but whatever, it's done.

		var scoldIE6UsersElem = $('<div></div>').attr('id', 'scold-ie6-users');
		var scoldIE6UsersElemWrap = $('<div></div>');
		var scoldHeader = $('<h2></h2>').text('Sorry, but are you aware your web browser is eight years old?');
		var scoldText = $('<p></p>').text("We're all about fun here at VidSF, and taking time out to painfully work around Internet Explorer 6's many, many visual bugs is pretty much the opposite of fun. And really, you deserve better. Might we recommend upgrading to a modern browser?");
		
		var scoldList = $('<ul></ul>');

		var chromeLink = $('<a></a>')
			.attr('href', 'http://www.google.com/chrome')
			.text('Google Chrome');
		var chromeListElem = $('<li></li>')
			.append(chromeLink)
			.appendTo(scoldList);

		var firefoxLink = $('<a></a>')
			.attr('href', 'http://www.mozilla.com/en-US/firefox/')
			.text('Mozilla Firefox');
		var firefoxListElem = $('<li></li>')
			.append(firefoxLink)
			.appendTo(scoldList);

		var safariLink = $('<a></a>')
			.attr('href', 'http://www.apple.com/safari')
			.text('Apple Safari');
		var safariListElem = $('<li></li>')
			.attr('class', 'last')
			.append(safariLink)
			.appendTo(scoldList);
		
		$(scoldIE6UsersElemWrap)
			.append(scoldHeader)
			.append(scoldText)
			.append(scoldList)
			.appendTo(scoldIE6UsersElem);
		
		$(scoldIE6UsersElem).prependTo('#container');
	}
}

function initFeaturedVideos() {
	//	This function is only needed for the Featured Videos area in the home page.
	if ($('#featured-videos').length > 0) {
		var $featuredVideos = $("#featured-videos"),
			$featuredVideosWrap = $("#featured-videos .wrap"),
			$featuredVideosList = $("#featured-videos ol"),
			$featuredVideosItems = $("#featured-videos li"),
			
			//	Create the previous/next arrow links and place them in the featured videos area.
			$featuredNext = $('<a id="featured-next" href="#"><span>&gt;</span></a>').appendTo($featuredVideos),
			$featuredPrevious = $('<a id="featured-previous" href="#"><span>&lt;</span></a>').appendTo($featuredVideos),
			
			//	This is where the thumbnail navigation will go.
			$featuredThumbnails = $('<div id="featured-thumbnails"></div>').appendTo($featuredVideosWrap),
			$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";

		//	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);
		});
	}
}
