;(function($){
	$(document).ready(function()
	{
		var notificationTimeout;

		//Shows updated notification popup
		var updateNotification = function(task, notificationText, newClass){
			var notificationPopup = $('.notification-popup ');
			notificationPopup.find('.task').text(task);
			notificationPopup.find('.notification-text').text(notificationText);
			notificationPopup.removeClass('hide success');

			// If there is already a timeout running for hiding current popup, clear it.
			if(notificationTimeout)
			clearTimeout(notificationTimeout);
			// Init timeout for hiding popup after 3 seconds
			notificationTimeout = setTimeout(function(){
				notificationPopup.addClass('hide');
			}, 3000);
		};


		// Adds a new Task to the todo list
		var addTask = function()
		{
			// Get the new task entered by user
			var newTask = $('#new-task').val();
			// If new task is blank show error message

			if(newTask === '')
			{
				$('#new-task').addClass('error');
				$('.new-task-wrapper .error-message').removeClass('hidden');
			}
			else
			{
				var todoListScrollHeight = $('.task-list-body').prop('scrollHeight');

				// Clear the text in textarea
				$('#new-task').val('');
				// As a new task is added, hide the mark all tasks as incomplete button & show the mark all finished button
				$('#mark-all-finished').removeClass('move-up');
				$('#mark-all-incomplete').addClass('move-down');
				// Show notification
				updateNotification(newTask, 'adicionada à lista');
				// Smoothly scroll the todo list to the end
				$('.task-list-body').animate({ scrollTop: todoListScrollHeight}, 1000);

				//Categoria ativa
				categoriaativa = $("#new-task").data('tarefacatid');

				//Pedido AJAX adicionar tarefa
				$.ajax({
					url: "/app/elements/functions/actions.php",
					type: 'POST',
					data: {"acao": "adicionar_tarefa", "tarefacatid" : categoriaativa, "titulo" : newTask},
					cache: false,
					success: function(response)
					{
						$.ajax({
							url: "/app/elements/functions/ajax.php",
							type: 'POST',
							data: {"ajax": "obter_template_linha_tarefa", "tarefaid" : response, "p" : 'tarefas', "sp" : categoriaativa},
							cache: false,
							success: function(template)
							{
								$('#task-list').prepend(template);
								$.get( "/app/content/tarefas/tarefa_detalhes.php?tarefaid="+response, function( data )
								{
									$( "#task_window" ).html( data );
									$('[data-toggle="tooltip"]').tooltip();
								});
							}
						});
					}
				});
			}
		}

		// Closes the panel for entering new tasks & shows the button for opening the panel
		var closeNewTaskPanel = function(){
			$('.add-task-btn').toggleClass('visible');
			$('.new-task-wrapper').toggleClass('visible');
			if($('#new-task').hasClass('error')){
				$('#new-task').removeClass('error');
				$('.new-task-wrapper .error-message').addClass('hidden');
			}
		};


		// Shows panel for entering new tasks
		$('.add-task-btn').click(function() {
			var newTaskWrapperOffset = $('.new-task-wrapper').offset().top;
			$(this).toggleClass('visible');
			$('.new-task-wrapper').toggleClass('visible')

			// Focus on the text area for typing in new task
			$('#new-task').focus();
			// Smoothly scroll to the text area to bring the text are in view
			$('body').animate({
				scrollTop: newTaskWrapperOffset
			}, 1000);

		});

		// Deletes task on click of delete button
		$('#task-list').on('click', '.task-action-btn .delete-btn', function(){
			/*var task = $(this).closest('.task');
			var taskText = task.find('.task-label').text();
			var tarefaid = task.find('.tarefaclick').data('id');
			task.remove();
			updateNotification(taskText,' eliminada.');*/

			//Pedido AJAX (altera o título)
		/*	$.ajax({
				url: "/app/elements/functions/actions.php",
				type: 'POST',
				data: {"acao": "eliminar_tarefa", "tarefaid" : tarefaid},
				cache: false,
				success: function(response){
					$('#resposta').html(response);
					setTimeout(function() {  $('#resposta').html('');}, 5000);
				}
			});*/
		});

		// Task Complete - Botão lado direito
		/*$(document).on('click', '#task_complete', function() {
			$(this).toggleClass('task-completed');
			if($(this).hasClass('task-completed'))
			{
				$('#tar'+$(this).data('id')).addClass('completed');
				//Pedido AJAX tarefa concluída
				$.ajax({
					url: "/app/elements/functions/actions.php",
					type: 'POST',
					data: {"acao": "tarefa_concluida", "tarefaid" : $(this).data('id')},
					cache: false,
				});
			}
			else
			{
				$('#tar'+$(this).data('id')).removeClass('completed');
				//Pedido AJAX tarefa não completa
				$.ajax({
					url: "/app/elements/functions/actions.php",
					type: 'POST',
					data: {"acao": "tarefa_nao_concluida", "tarefaid" : $(this).data('id')},
					cache: false,
				});
			}
			$tarefaid = $(this).data('id');

			//Delay atualiza a coluna
			setTimeout(function()
			{
				$.get( "/app/content/tarefas/tarefa_detalhes.php?tarefaid="+$tarefaid, function( data )
				{
					$("#task_window").html( data );
					$('[data-toggle="tooltip"]').tooltip();
				});
			}, 200);
			return false;
		});*/

		// Marks a task as complete
		$('#task-list').on('click', '.task-action-btn .complete-btn', function(){
			/*var task = $(this).closest('.task');
			var taskText = task.find('.task-label').text();
			var tarefaid = task.find('.tarefaclick').data('id');
			var newTitle = task.hasClass('completed') ? 'Concluída' : 'Não concluída';

			$(this).attr('title', newTitle);
			if(task.hasClass('completed')) //Não concluída
			{
				$('#task_complete').toggleClass('task-completed');
				updateNotification(taskText, ' não concluída');
				//Pedido AJAX tarefa não completa
				$.ajax({
					url: "/app/elements/functions/actions.php",
					type: 'POST',
					data: {"acao": "tarefa_nao_concluida", "tarefaid" : tarefaid},
					cache: false,
				});
			}
			else //Concluída
			{
				$('#task_complete').toggleClass('task-completed');
				updateNotification(taskText, ' concluída.', 'success');
				//Pedido AJAX tarefa completa
				$.ajax({
					url: "/app/elements/functions/actions.php",
					type: 'POST',
					data: {"acao": "tarefa_concluida", "tarefaid" : tarefaid},
					cache: false,
				});
			}

			//Atualiza a coluna
			$.get( "/app/content/tarefas/tarefa_detalhes.php?tarefaid="+$(this).data('id'), function( data )
			{
				$("#task_window").html( data );
				$('[data-toggle="tooltip"]').tooltip();
			});

			task.toggleClass('completed');*/
		});

		// Adds a task on hitting Enter key, hides the panel for entering new task on hitting Esc. key
		$('#new-task').keydown(function(event)
		{
			// Get the code of the key that is pressed
			var keyCode = event.keyCode;
			var enterKeyCode = 13;
			var escapeKeyCode = 27;
			// If error message is already displayed, hide it.
			if($('#new-task').hasClass('error')){
				$('#new-task').removeClass('error');
				$('.new-task-wrapper .error-message').addClass('hidden');
			}
			// If key code is that of Enter Key then call addTask Function
			if(keyCode == enterKeyCode){
				event.preventDefault();
				addTask();
			}
			// If key code is that of Esc Key then call closeNewTaskPanel Function
			else if(keyCode == escapeKeyCode)
			closeNewTaskPanel();

		});

		// Add new task on click of add task button
		$('#add-task').click(addTask);
		// Close new task panel on click of close panel button
		$('#close-task-panel').click(closeNewTaskPanel);

		// Mark all tasks as complete on click of mark all finished button
		$('#mark-all-finished').click(function(){
			$('#task-list .task').addClass('completed');
			$('#mark-all-incomplete').removeClass('move-down');
			$(this).addClass('move-up');
			updateNotification('All tasks', 'marked as complete.', 'success');
		});

		// Mark all tasks as incomplete on click of mark all incomplete button
		$('#mark-all-incomplete').click(function(){
			$('#task-list .task').removeClass('completed');
			$(this).addClass('move-down');
			$('#mark-all-finished').removeClass('move-up');
			updateNotification('All tasks', 'marked as Incomplete.');
		});

		$( ".vertarefasconcluidas" ).click(function(event) {
			event.preventDefault();
			$.get( "/app/content/tarefas/tarefas_concluidas_lista.php?tarefacatid="+$(this).data('tarefacatid'), function( data )
			{
				$("#listagemtarefas").html( data );
			});
		});

	});
}(jQuery));
