$(function() {
	$('.playlist_item').click(function(){
		$('#playlistId').val($(this).attr('title'));
		$('#playlist_dis').text($(this).text());
	});

	$('#AddToPlaylistBtn').click(submitAction);

	$('#AddToPlaylistCancel').click(function(e) {
		$(this).parents('div.float-window').fadeOut('slow');
	});

	$('a.addToPlaylistlink').click(function(e) {
		var container = $("#addToPlaylistContainer");
		if (container.length) {
			e.preventDefault();
		}
		else {
			window.location.href = baseUrl+'user/login';
		}

		var pos = $(this).offset();
		$('#fileId').val($(this).attr('id').replace('add', ''));
		container.css('left', pos.left-50);
		container.css('top', pos.top-30);
		container.fadeIn("slow");
	});
});

function submitAction(e) {
	var errorContainer = $('#add_to_playlist_msg');
	errorContainer.css('display', 'none');
	var playlistId = $('#playlistId').val();
	var fileId = $('#fileId').val();

	if (!fileId) {
		return false;
	}

	if (!playlistId) {
		errorContainer.css('display', 'block');
		return false;
	}
	var input = this;
	$.post(
		baseUrl+'music/ajax_additemtoplaylist',
		{fileId:fileId, playlistId:playlistId},
		function(response) {
			var message;
			if (response.success) {
				if (response.message == 'exists') {
					message = 'File already presents in the playlist.';
				}
				else {
					message = 'File has been added to the playlist.';
				}
			}
			else {
				message = 'Some error has occured during the request. Please try again.';
			}
			$('#addToPlaylistFormContainer').css('display', 'none');
			$('#addToPlaylistMessageContainer').css('display', 'block');
			$('#addToPlaylistMessageContainer').text(message);
			setTimeout(function() {
					$('#addToPlaylistContainer').fadeOut('slow', function() {
						$('#addToPlaylistFormContainer').css('display', 'block');
						$('#addToPlaylistMessageContainer').css('display', 'none');
					})
				},
				3000
			);
		},
		'json'
	);

	return false;
}


