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

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

//	Scripts that power our "Share this video" section on the details page.
function initShareActions() {
	//	First we check to see if our toggle link exists in the page. If not, stop here.
	if ($('#expand-share').length > 0) {
		//	Now that we have the link, we hook up the click events.
		$('#expand-share').click(function() {
			expandShareArea();
			//	Since this is a link, we need to disable its normal operation after running the function.
			return false;
		});
		$('#collapse-share').click(function() {
			collapseShareArea();
		});
	}
}

function expandShareArea() {
	//	When clicked, we hide the related-videos area and show the share-actions area, or vice versa.
	//	We do two different paths here, depending on whether or not there is a Related Videos area in the page.
	//	If there are Related Videos...
	if ($('#related-videos').length > 0) {
		//	...then we fade out both the share-collapsed and related-videos areas before proceeding.
		$('#share-collapsed').fadeOut(500);
		$('#related-videos').fadeOut(500, function() {
			//	IE has issues with slideDown/slideUp in this case, so we target IE and send it fadeIn/fadeOut instead.
			if ($.browser.msie) {
				$('#share-expanded').fadeIn(500);
			} else {
				$('#share-expanded').slideDown(500);
			}
		});	
	//	If there are no Related Videos...
	} else {
		//	Then we wait for just the share-collapsed area to fade before proceeding.
		$('#share-collapsed').fadeOut(500, function() {
			//	IE has issues with slideDown/slideUp in this case, so we target IE and send it fadeIn/fadeOut instead.
			if ($.browser.msie) {
				$('#share-expanded').fadeIn(500);
			} else {
				$('#share-expanded').slideDown(500);
			}	
		});
	}
}

function collapseShareArea() {
	//	When clicked, we hide the related-videos area and show the share-actions area, or vice versa.
	if ($.browser.msie) {
		$('#share-expanded').fadeOut(500, function() {
			$('#share-collapsed').fadeIn(500);
			//	Don't forget to check if related-videos exists in the page before proceeding.
			if ($('#related-videos').length > 0) {
				$('#related-videos').fadeIn(500);
			}
		});
	} else {
		$('#share-expanded').slideUp(500, function() {
			$('#share-collapsed').fadeIn(500);
			//	Don't forget to check if related-videos exists in the page before proceeding.			
			if ($('#related-videos').length > 0) {
				$('#related-videos').fadeIn(500);
			}
		});
	}
}

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').attr('class', '');
			$(this).attr('class', 'on');
		});
		$('#tab-related-videos').click(function() {
			if (mapIsPresent) $('#map').hide();
			$('#share').hide();
			$('#related-videos').show();
		});
		if (mapIsPresent) {
			$('#tab-map').click(function() {
				$('#related-videos').hide();
				$('#share').hide();
				$('#map').show();

				//	Since we need the map's div to be displayed before initializing the map, we initialize here.
				var videoLat = $('#id_geo_lat').text();
				var videoLng = $('#id_geo_long').text();
				var videoLocation = new google.maps.LatLng(videoLat, videoLng);
				var myOptions = { zoom: 13, 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 });
			});
		}
		$('#tab-share').click(function() {
			$('#related-videos').hide();
			if (mapIsPresent) $('#map').hide();
			$('#share').show();
		});
	}
}

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: 13, 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(13);
			//	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');
	}
}
