$(document).ready(function(){
	playlist.bindEvents();
	playlist.current_video_page = 1;
	playlist.switchPage(1);
	
	playlist.toggleUiMessages();
	
	// Look at the hash and automatically select the playlist
	if (location.hash.match(/edit-[0-9]+$/)) {
		$('[href='+location.hash+']').click();
	}
	
	// Focus support
	$('input, textarea, select').click(function() {
		$(this).addClass('jsFocus');
	}).blur(function(){
		$(this).removeClass('jsFocus');
	});
	
	// Click the "create" button when you hit return
	$(document).keydown(function(e){
		if (e.keyCode == 13) {
			if ($('#create_playlist_name').is('.jsFocus')) {
				$('#create_playlist').click();
			}
			// For renaming
			if ($('#playlist_newname_field').is('.jsFocus')) {
				$('#playlist_newname_save').click();
			}
		}
	});
	
	// Close rename screen when you click outside of it
	$(document).click(function(e){
		if ($(e.target).parents('h2').parents('#playlist_show').length == 0) {
			playlist.renamePlaylistClose();
		}
	});
});

var playlist = {
	filter_tags: '',
	create: function() {
		name = $('#create_playlist_name').val();
		
		// Sanitize name
		name = sanitize(name);
		
		if (name == '') {
			if ($('#create_playlist_container .form-error').length == 0) {
				$('#create_playlist').after('<span class="form-error">Please enter a valid name</span>');
 							
				function hideError() {
					$('#create_playlist_container .form-error').fadeOut('slow', function(){
						$(this).remove();
					});
				}
				
				setTimeout(hideError, 1500)
			}
			return;
		}
		
		// Start loading animation
		$('#create_playlist_container').addClass('loading');
		
		playlist.makeRequest('create', {name: name}, function(data) {
			li = $('<li><span class="playlist-title">'+chomp(data.name, 50)+' (0)</span><span class="actions"><a title="Edit this playlist" href="#edit-'+data.id+'">Edit</a> <a title="Delete this playlist" href="#delete-'+data.id+'">Delete</a></span></li>');
			
			li.appendTo('#playlist_show_all ul');
			
			// Events
			li.find('[href*=edit]').  click(playlist.switchPlaylist);
			li.find('[href*=delete]').click(playlist.deletePlaylist);
			
			// Hide "you have no playlists" message, if necessary
			playlist.toggleUiMessages();
		
			// Empty field
			$('#create_playlist_name').val('');
			
			// Stop loading animation
			$('#create_playlist_container').removeClass('loading');
			
			// Select the new playlist
			playlist.switchPlaylist(data.id);
		});
	},
	
	addVideo: function() {
		if(!playlist.current_playlist) return;
		var vid = $(this).parent().data('video');
		data = {
			playlist: playlist.current_playlist.id,
			videos: [vid.id]
		};
		
		$('<li></li>').addClass('loading').hide().appendTo('#playlist_videos').slideDown('fast', function(){		
			playlist.makeRequest('addVideos', data, function(video) {
				var content = templates.playlist_video(video[0]);
				var playlist_id = content.data('playlist_id');
				
				content = content.html();
				
				var elm = $('#playlist_videos li.loading').removeClass('loading').append(content);
				
				// For some reason, we lost the delete event, so let's add it back
				elm.find('a')
					.unbind('click', playlist.removeVideoFromList) // Just in case other browsers still have the event
						.click(playlist.removeVideoFromList);
				
				// Adding playlist_id back
				elm.data('playlist_id', playlist_id);
				
				//playlist.addVideoToList(video[0]);
				
				playlist.updateCount();
				playlist.toggleUiMessages();
			});
		});
	},
	
	addVideoToList: function(video) {
		$('#playlist_videos').append(templates.playlist_video(video));
	},
	
	renamePlaylist: function() {
		if (! playlist.current_playlist) return;
		var playlist_id = playlist.current_playlist.id;
		
		new_name = $('#playlist_newname_field').val();
				
		new_name = sanitize(new_name);
		if (new_name == '') return false;
		
		data = {
			id: playlist_id,
			name: new_name
		};
		
		$('#playlist_newname *').hide();
		$('#playlist_newname').append('Loading...');
		
		playlist.makeRequest('editName', data, function(data) {
			if (data.success) {
				playlist.current_playlist.name = new_name;
				
				playlist.renamePlaylistClose();
				
				$('#playlist_show_title').text(chomp(new_name));
				$('#playlist_show_all [href=#edit-'+playlist_id+']').parents('li').children('.playlist-title').text(chomp(new_name, 50)+' (0)');
				playlist.updateCount();
			} else {
				playlist.renamePlaylistClose();
			}
		});
	},
	
	renamePlaylistOpen: function() {
		if (! playlist.current_playlist) return;
		var playlist_id = playlist.current_playlist.id;
		
		$('#playlist_show h2 *').hide();
		$('#playlist_show h2')  .append('<div id="playlist_newname"><input type="text" size="20" id="playlist_newname_field" /> <a href="#" id="playlist_newname_save">Save</a> <a href="#" id="playlist_newname_cancel">Cancel</a></div>');
		$('#playlist_newname_field').val(playlist.current_playlist.name);
		
		$('#playlist_newname_field').focus(function(){ $(this).addClass('jsFocus'); }).blur(function(){ $(this).removeClass('jsFocus'); });
		
		$('#playlist_newname_cancel').click(playlist.renamePlaylistClose);
		$('#playlist_newname_save')  .click(playlist.renamePlaylist);
	},
	
	renamePlaylistClose: function() {
		if ($('#playlist_newname').length > 0) {
			$('#playlist_newname').remove();
			$('#playlist_show h2 *').show();
		}
	},
	
	removeVideoFromList: function(el) {
		var el = $(this);
		var li = el.parent()
		var id = li.data('playlist_id');
		
		li.empty().addClass('loading');
		
		playlist.makeRequest('removeVideos', {playlist: playlist.current_playlist.id, videos: id}, function(data) {
			// TODO: Check to make sure it was deleted
			
			li.slideUp('medium', function(){
				$(this).remove();
				playlist.updateCount();
			
				// Show 'no videos in this playlist' message, if necessary
				playlist.toggleUiMessages();
			});
		});
	},
	
	updateCount: function() {
		var count = $('#playlist_videos li').length;
		var id		= playlist.current_playlist.id;
		
		var title = $('#playlist_show_all [href=#edit-'+id+']').parents('li').find('.playlist-title');
		title.text(title.text().replace(/\([0-9]+\)/, '('+count+')'));
	},
	
	switchPlaylist: function(id) {
		// event
		if (typeof id == 'object') {	
			id = $(this).attr('href').replace(/[^0-9]/g, '');
		}
		
		$('#playlist_show_all').hide();
		$('#playlist_show').show().addClass('loading');
		
		// Add loading text
		$('#playlist_show h2 span').text('Loading...');
		$('#playlist_show a.rename').hide();
		
		playlist.makeRequest('get', {playlist: id}, function(data) {
			// Show Add links
			$('#user_videos a:contains(Add)').show();
			
			playlist.current_playlist = data;
			
			$('#playlist_videos').empty();
			
			for(var i=0;i<data.videos.length;i++) {
				playlist.addVideoToList(data.videos[i]);
			}
			
			playlist.addPlaylistOptions();
			
			if ($('#playlist_videos').children().length == 0) {
				$('#embed_playlist').hide();
			}
			
			// Fill in title
			$('#playlist_show h2 span').text(chomp(stripslashes(data.name)));
			$('#playlist_show h2 a').show();
			
			// Remove loading animation
			$('#playlist_show').removeClass('loading');
			
			// Show "rename" link
			$('#playlist_show a.rename').show();
			
			// Show 'no videos in this playlist' message, if necessary
			playlist.toggleUiMessages();
			
		});
	},
	
	updatePositions: function() {
		var videos = [];
		$('#playlist_videos li.video').map(function(i, el) {
			if(!$(el).hasClass('ui-sortable-placeholder')) {
				videos.push($(el).data('video').id);
			}
		});
		
		playlist.makeRequest('updateVideoPositions', {playlist: playlist.current_playlist.id, 'positions[]': videos});
	},
	
	nextVideos: function() {
		playlist.switchPage(playlist.current_video_page+1, playlist.filter_tags)
		return false;
	},
	
	prevVideos: function() {
		playlist.switchPage(playlist.current_video_page-1, playlist.filter_tags)
		return false;
	},
	
	videosShowLoading: function() {
		$('#your_videos_container .ui-message').remove();
	
		var height = $('#user_videos').height();
		
		if (height == 0) height = 100;
		
		$('#user_videos').addClass('loading').empty();
		
		if (height != 0) {
			$('#user_videos').css('height', height);
		}
	},
	
	switchPage: function(page, tags, callback) {
		if (! tags) tags = '';
		
		playlist.videosShowLoading();
		
		playlist.makeRequest('getUserVideos', {page: page, per_page: 10, tags: tags}, function(data) {
			playlist.fillVideos(data.videos);
			playlist.current_video_page = page;
			
			playlist.resetPagination(data);
			$('#user_videos').removeClass('loading').css('height', 'auto');
			
			if (! playlist.current_playlist) {			
				// Hide Add links
				$('#user_videos a:contains(Add)').hide();
			}
			if (callback) callback();
		});
	},
	
	resetPagination: function(data) {
		if(data.next) {
			$(".pagination a.next").show();
		} else {
			$(".pagination a.next").hide();
		}
		
		if(data.prev) {
			$(".pagination a.previous").show();
		} else {
			$(".pagination a.previous").hide();
		}
	},
	
	fillVideos: function(videos) {
		if (! videos) return false;
		var cont = $('#user_videos');
		cont.empty();
		for(var i=0; i<videos.length; i++) {
			cont.append(templates.user_video(videos[i]));
		}
	},
	
	addPlaylistOptions: function() {
		if ($('#playlist_options').length == 0) {
			$('<p id="playlist_options"></p>').insertAfter('#playlist_videos');
			
			$('<a href="../#playlist-'+playlist.current_playlist.id+'" title="Make a vidget with this playlist">Embed playlist</a>')
				.attr('id', 'embed_playlist')
					.appendTo('#playlist_options');
			$('<a href="#" title="Delete this playlist">Delete</a>')
				.click(playlist.deletePlaylist)
					.attr('id', 'delete_playlist').addClass('delete_link')
						.appendTo('#playlist_options');
		}
	},
	
	deletePlaylist: function(id) {
		if (typeof id == 'object') {
			var href = $(this).attr('href');
			href = href.replace(/^.+#/, ''); // I hate you, IE!
			id = href.replace(/[^0-9]/g, '');
		}
		
		if (! id) {
			id = playlist.current_playlist.id;
			if (! id) return false;
		}
		if (confirm("Are you sure you want to delete this playlist?")) {
	
			// Show "you have no playlists" message, if necessary
			playlist.toggleUiMessages();
			
			playlist.hideCurrent();
			$('#playlist_show_all [href=#edit-'+id+']').parents('li').slideUp('normal', function(){
				$(this).remove();
			});
			
			playlist.makeRequest('delete', {playlist: id});
		}
	},
	
	hideCurrent: function() {
		$('#playlist_show').hide();
		$('#playlist_show_all').show();
		$('#playlist_videos').empty();
		$('#playlist_show .ui-message').remove();
		$('#playlist_options').remove();
		
		playlist.renamePlaylistClose();
		
		// Hide Add links
	$('#user_videos a:contains(Add)').hide();
			
		playlist.current_playlist = false;
	},
	
	makeRequest: function(method, data, callback) {
		data.method = 'viddler.playlists.' + method;
		
		// Adding timestamp prevents weird caching problems in IE7
		var time = new Date();
		time = time.getTime();
		$.get('callback.php?time='+time, data, callback, 'json');
	},
	
	toggleUiMessages: function() {
		// Hide 'no playlists' message if there are playlists found
		if ($('#playlist_show_all ul li').length > 0) {
			$('#no-playlists-message').hide();
		} else {
			$('#no-playlists-message').show();
		}
		
		if (playlist.current_playlist) {
			switch ($('#playlist_show li').length) {
				case 0:
					// Show 'no videos in playlist message'
					if ($('#playlist-empty-message').length == 0) {
						$('<p id="playlist-empty-message" class="ui-message">There are no videos in this playlist. To add one, choose a video from the right and click the "add" button next to it.</p>')
							.insertAfter('#playlist_show h2')
								.hide().slideDown('medium');
					}
					$('#embed_playlist').fadeOut();
				break;
				case 1:
					// Hide 'no videos' message
					$('#playlist-empty-message').slideUp('medium', function(){
						$(this).remove();
					});
					// Hide 'reorder' message
					$('#reorder-message').slideUp('medium', function(){
						$(this).remove();
					});
					$('#embed_playlist').fadeIn();
				break;
			}
			
			// Show 'reorder' message
			if ($('#playlist_show li').length > 1 && $('#reorder-message').length == 0) {
				$('<p id="reorder-message" class="ui-message">Click and drag videos to reorder them</p>')
					.insertAfter('#playlist_show h2')
						.hide().slideDown('medium');
			}
		}
	},
	
	filterTagKeyup: function() {
			
		if ($(this).val() != '') {
			// Has the tag changed at all?
			if ($(this).val() != playlist.filter_tags) {
				playlist.filter_tags = $(this).val();
				// Show close link
				$('#tag_filter_container a').css('visibility', 'visible');
				
				playlist.videosShowLoading();
				if (playlist.timeout) clearTimeout(playlist.timeout);
				playlist.timeout = setTimeout(playlist.filterTag, 500);
			}
		} else {
			// Hide close link
			$('#tag_filter_container a').css('visibility', 'hidden');
			
			if (playlist.filter_tags != '') {
				playlist.filter_tags = '';
				playlist.switchPage(1);
			}
		}
	},
	
	filterTag: function() {
		var tag = $('#tag_filter').val();
		playlist.switchPage(1, tag, function() {
			if ($('#user_videos li').length == 0) {
				$('<div class="ui-message">No results found</div>').hide()
					.insertBefore('#user_videos')
						.slideDown();
			}
		});
	},
	
	bindEvents: function() {
		$("a.previous").click(playlist.prevVideos);
		$("a.next")    .click(playlist.nextVideos);
		

		$('#create_playlist') .click(playlist.create);
		$('#user_videos li a').click(playlist.addVideo);
		$('#playlist_select') .change(playlist.switchPlaylist);
		
		$('#playlist_videos').sortable({
			update: playlist.updatePositions
		});

		$('#playlist_show_all [href*=delete]').click(playlist.deletePlaylist);
		$('#playlist_show_all [href*=edit]')  .click(playlist.switchPlaylist);
		$('#playlist_show a:contains(Back)')  .click(playlist.hideCurrent);	
		$('#playlist_show a:contains(Rename)').click(playlist.renamePlaylistOpen);
		
		$('#tag_filter').keyup(playlist.filterTagKeyup);
		$('#tag_filter_container a').click(function(){
			$('#tag_filter').val('').keyup();
		});
	}
}

var templates = {
	playlist_video: function(video) {
		if (! video) return false;
		var delete_link = $('<a class="delete" href="#" title="Remove this video from the current playlist">Remove</a>');
		
		delete_link.click(playlist.removeVideoFromList);
		
		var img = $('<img />');
		img.attr('src', video.thumbnail_url);
		img.attr('width', '40');
		
		var el = $('<li class="video"><span class="video_list_title">' + video.title + '</span></li>');
		el.data("playlist_id", video.id);
		el.data("video", video);
		
		el.prepend(delete_link);
		el.prepend(img);
		
		return el;
	},
	
	user_video: function(video) {
		var link = $('<a href="#">Add</a>');
		link.click(playlist.addVideo);
		
		var img = $('<img />');
		img.attr('src', video.thumbnail_url);
		img.attr('width', '40');
		
		var el = $('<li><span class="video_list_title">' + video.title + '</span></li>');
		el.prepend(img);
		el.prepend(link);
		el.data("video", video);
		
		return el;
	}
}

// Gives string a character limit

function chomp(string, limit) {
	limit = limit ? limit : 34
	if (string.length > limit) {
		string = string.substr(0, limit-3);
		string = string.replace(/ +.?$/, '')+'...'
	}
	return string;
}

// Sanitize a string

function sanitize(string) {
	return string.replace(/[^a-z0-9\-.,!?'" ]/ig, '');
}

// Takes slashes out of a string

function stripslashes(string) {
	if (! string) string = '';
	return string.replace(/\\('|")/, '$1');
}