/**
 * Created by Cyan on 3/28/2016.
 */

var lastSprintId;

$(document).ready(function() {
    loadAllFixedEvents();

    // Get sprints
    getSprints();

    // Get backlog tasks
    getSprintBacklogTasks();

    loadSprintsEvents();
    loadSprintBacklogEvents();
});

function loadAllFixedEvents() {
    // Select tab
    $('.nav li.active').removeClass('selected');
    $('#sprints-tab').addClass('selected');

    // Search sprint
    // TODO
    $('.search-bar .input-group-btn').click(getGenericBacklogTasks);

    // Add sprint
    $('.add-sprint-btn').unbind('click');
    $('.add-sprint-btn').click(createSprint);

    // Get tasks by search for sprints
    $('.content-left .search-bar .search').click(getGenericSprints);

    // Remove search for sprints
    $('.content-left .search-bar .remove-search').click(removeSprintsSearch);

    // Get tasks by search for backlog
    $('.content-right .search-bar .search').click(getGenericBacklogTasks);

    // Remove search for backlog
    $('.content-right .search-bar .remove-search').click(removeBacklogSearch);
}

function loadComunEvents() {
    // Drag and drop
    $(function() {
        $("#sortable_backlog, .sortable_sprint").sortable({
            connectWith: ".connectedSortable",

            receive: function(event, ui) {
                // From backlog or another sprint to sprint
                if ($(this).closest('.sprint').length > 0 && ui.sender != ui.item) {
                    dropTaskToSprint(ui.item);

                    // From backlog
                    if ($(ui.sender).hasClass('backlog-list')) {

                    } else {
                        // From another sprint
                        decreaseProgressBar($(ui.sender).closest('.sprint').find('.sprint-progress'), $(ui.item).find('.task-state option:selected').val());
                    }
                } else {
                    // Cancel
                    $("#sortable_backlog, .sortable_sprint").sortable("cancel");
                    showErrorMessage('Can not drop the task from the same sprint or backlog.');
                }
            },

            start: function(event, ui) {
                lastSprintId = $(ui.item).closest('.sprint').find('.sprint-title-content').text();
            },

            stop: function(event, ui) {
                // From backlog to backlog
                if (ui.item.closest('#sortable_backlog').length > 0) {
                    $("#sortable_backlog").sortable("cancel");
                } else if (lastSprintId == $(ui.item).closest('.sprint').find('.sprint-title-content').text()) {
                    // To sprint
                    $(".sortable_sprint").sortable("cancel");
                }
            }
        }).disableSelection();
    });
}

// SPRINTS events
function loadSprintsEvents() {
    // Sprints acordeon
    $('.sprint-header').unbind('click');
    $('.sprint-header').click(acordeonExtraContent);

    // Delete sprint
    $('.delete-sprint').unbind('click')
    $('.delete-sprint').click(deleteSprint);

    // Update start date
    $('input.start-date').unbind('focusout');
    $('input.start-date').focusout(updateSprintStartDate);

    // Update end date
    $('input.end-date').unbind('focusout');
    $('input.end-date').focusout(updateSprintEndDate);

    // Update total capacity
    $('input.total-capacity').unbind('focusout');
    $('input.total-capacity').focusout(updateSprintTotalCapacity);

    // Update members
    $('input.sprints-members').unbind('focusout');
    $('input.sprints-members').focusout(updateSprintMembers);

    // Show task remove
    $('.sprint .sprint-tasks .remove-sprint-task').show();

    // Remove sprint task
    $('.sprint .sprint-tasks .remove-sprint-task').unbind('click');
    $('.sprint .sprint-tasks .remove-sprint-task').click(removeSprintTask);

    // Start sprint
    $('button.sprint-state.btn-secondary').unbind('click');
    $('button.sprint-state.btn-secondary').click(startSprint);

    // Complete sprint
    $('button.sprint-state.btn-primary').unbind('click');
    $('button.sprint-state.btn-primary').click(completeSprint);
}

// SPRINTS ajax
function getGenericSprints() {
    var id = $('.sprints-search-bar .form-control').val();

    if (!id) {
        getSprints();
    } else {
        getSprintById(id);
    }
}

function getSprintById(id) {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprints/searchById",
        data: {"searchField" : id.toString()},
        success: function(data){
            $('div.sprints-content').html(data);
            loadComunEvents();
            loadSprintsEvents();
            loadSprintBacklogEvents();
        },

        error: function(e){
            showErrorMessage('Can not get the sprints.');
        }
    });
}

function getSprints() {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprints/getAll",
        success: function(data){
            $('div.sprints-content').html(data);
            loadComunEvents();
            loadSprintsEvents();
            loadSprintBacklogEvents();
        },

        error: function(e){
            showErrorMessage('Can not get the sprints.');
        }
    });
}

function removeSprintsSearch() {
    $('.sprints-search-bar .form-control').val('');
    getSprints();
}

function createSprint(event) {
    event.preventDefault();

    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'text/plain'
        },
        url: "/sprint/insert",
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "OK") {
                getSprints();
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not create the sprint.');
        }
    });
}

function deleteSprint(event) {
    event.preventDefault();
    event.stopPropagation();

    var token = $("input[name='_csrf']").val();
    var id = $(this).parent().find('.sprint-title-content').text();

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'text/plain'
        },
        url: "/sprint/delete",
        data: id,
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "OK") {
                getSprints();
                getSprintBacklogTasks();
                showSuccessMessage(data['message']);
            } else {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not delete the sprint.');
        }
    });
}

function updateSprintStartDate(event) {
    event.preventDefault();
    event.stopPropagation();

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.panel-body').find('.sprint-title-content').text();
    var startDate = $(this).val();

    request["id"] = id;
    request["startDate"] = startDate;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateStartDate",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the start date.');
        }
    });
}

function updateSprintEndDate(event) {
    event.preventDefault();
    event.stopPropagation();

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.panel-body').find('.sprint-title-content').text();
    var endDate = $(this).val();

    request["id"] = id;
    request["endDate"] = endDate;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateEndDate",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the end date.');
        }
    });
}

function updateSprintTotalCapacity(event) {
    event.preventDefault();
    event.stopPropagation();

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.panel-body').find('.sprint-title-content').text();
    var capacity = $(this).val();

    request["id"] = id;
    request["totalCapacity"] = capacity;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateTotalCapacity",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the capacity.');
        }
    });
}

function updateSprintMembers(event) {
    event.preventDefault();
    event.stopPropagation();

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.panel-body').find('.sprint-title-content').text();
    var members = $(this).val();

    request["id"] = id;
    request["members"] = members;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateMembers",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the members.');
        }
    });
}

function startSprint(event) {
    event.stopPropagation();

    var sprintElem = $(this).closest('.sprint');

    if ($(sprintElem).find('.sprint-tasks > li').size() == 0) {
        showErrorMessage('The sprint dosent cotain any task.');
        return;
    }

    if ($('.sprint.started').size() > 0) {
        showErrorMessage('You can have only one sprint in progress.');
        return;
    }

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(sprintElem).find('.sprint-title-content').text();
    var startDate = $(sprintElem).find('input.start-date').val();
    var endDate = $(sprintElem).find('input.end-date').val();
    var totalCapacity = $(sprintElem).find('input.total-capacity').val();
    var members = $(sprintElem).find('input.sprints-members').val();

    request["id"] = id;
    request["startDate"] = startDate;
    request["endDate"] = endDate;
    request["totalCapacity"] = totalCapacity;
    request["members"] = members;
    request["state"] = "S";

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateState",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            } else {
                $(sprintElem).find('button.sprint-state').removeClass('btn-secondary');
                $(sprintElem).find('button.sprint-state').addClass('btn-primary');
                $(sprintElem).find('button.sprint-state').text('Complete sprint');
                $(sprintElem).find('button.sprint-state').unbind('click');
                $(sprintElem).find('button.sprint-state').click(completeSprint);

                $(sprintElem).find('.sprint-info-editable').hide();
                $(sprintElem).find('.sprint-info-fixed .start-date-content').text($(sprintElem).find('.sprint-info-editable input.start-date').val());
                $(sprintElem).find('.sprint-info-fixed .start-end-content').text($(sprintElem).find('.sprint-info-editable input.end-date').val());
                $(sprintElem).find('.sprint-info-fixed .total-capacity-content').text($(sprintElem).find('.sprint-info-editable input.total-capacity').val());
                $(sprintElem).find('.sprint-info-fixed .sprints-members-content').text($(sprintElem).find('.sprint-info-editable input.sprints-members').val());
                $(sprintElem).find('.sprint-info-fixed').show();

                $(sprintElem).removeClass('not-started');
                $(sprintElem).removeClass('completed');
                $(sprintElem).addClass('started');

                // Hide remove task btn
                $(sprintElem).find('.remove-sprint-task').hide();
            }
        },
        error: function(data) {
            showErrorMessage('Can not start the sprint.');
        }
    });
}

function completeSprint(event) {
    event.stopPropagation();

    var sprintElem = $(this).closest('.sprint');

    if ($(sprintElem).find('.sprint-tasks > li').size() == 0) {
        showErrorMessage('The sprint dosent cotain any task.');
        return;
    }

    var request = {};
    var token = $("input[name='_csrf']").val();
    var id = $(sprintElem).find('.sprint-title-content').text();
    var startDate = $(sprintElem).find('input.start-date').val();
    var endDate = $(sprintElem).find('input.end-date').val();
    var totalCapacity = $(sprintElem).find('input.total-capacity').val();
    var members = $(sprintElem).find('input.sprints-members').val();

    request["id"] = id;
    request["startDate"] = startDate;
    request["endDate"] = endDate;
    request["totalCapacity"] = totalCapacity;
    request["members"] = members;
    request["state"] = "C";

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateState",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            } else {
                $(sprintElem).find('button.sprint-state').removeClass('btn-primary');
                $(sprintElem).find('button.sprint-state').addClass('btn-info');
                $(sprintElem).find('button.sprint-state').text('Sprint completed');
                $(sprintElem).find('button.sprint-state').unbind('click');

                $(sprintElem).removeClass('not-started');
                $(sprintElem).removeClass('started');
                $(sprintElem).addClass('completed');

                // Show remove task btn
                $(sprintElem).find('.remove-sprint-task').show();
            }
        },
        error: function(data) {
            showErrorMessage('Can not complete the sprint.');
        }
    });
}

function increaseProgressBar(progressBarObj, taskState) {
    var tasksSize = parseInt($(progressBarObj).find('input.all-tasks').val()) + 1;
    $(progressBarObj).find('input.all-tasks').val(tasksSize);

    if ("Blocked" === taskState) {
        var progressSize = parseInt($(progressBarObj).find('input.bloqued-tasks').val()) + 1;
        $(progressBarObj).find('input.bloqued-tasks').val(progressSize);
    } else if ("In progress" === taskState) {
        var progressSize = parseInt($(progressBarObj).find('input.in-progress-tasks').val()) + 1;
        $(progressBarObj).find('input.in-progress-tasks').val(progressSize);
    } else if ("Done" === taskState) {
        var progressSize = parseInt($(progressBarObj).find('input.done-tasks').val()) + 1;
        $(progressBarObj).find('input.done-tasks').val(progressSize);
    }

    var bloquedStarted = $(progressBarObj).find('input.bloqued-tasks').val();
    var bloquedWidth = (bloquedStarted / tasksSize * 100);
    $(progressBarObj).find('.progress-bar-danger').width(bloquedWidth + "%");

    var inProgress = $(progressBarObj).find('input.in-progress-tasks').val();
    var inProgressWidth = (inProgress / tasksSize * 100);
    $(progressBarObj).find('.progress-bar-striped').width(inProgressWidth + "%");

    var done = $(progressBarObj).find('input.done-tasks').val();
    var doneWidth = (done / tasksSize * 100);
    $(progressBarObj).find('.progress-bar-success').width(doneWidth + "%");
}

function decreaseProgressBar(progressBarObj, taskState) {
    var tasksSize = parseInt($(progressBarObj).find('input.all-tasks').val()) - 1;
    $(progressBarObj).find('input.all-tasks').val(tasksSize);

    if (tasksSize == 0) {
        $(progressBarObj).find('input.bloqued-tasks').val(0);
        $(progressBarObj).find('input.in-progress-tasks').val(0);
        $(progressBarObj).find('input.done-tasks').val(0);

        $(progressBarObj).find('.progress-bar-danger').width("0%");
        $(progressBarObj).find('.progress-bar-striped').width("0%");
        $(progressBarObj).find('.progress-bar-success').width("0%");
    } else {
        if ("Blocked" === taskState) {
            var progressSize = parseInt($(progressBarObj).find('input.bloqued-tasks').val()) - 1;
            $(progressBarObj).find('input.bloqued-tasks').val(progressSize);
        } else if ("In progress" === taskState) {
            var progressSize = parseInt($(progressBarObj).find('input.in-progress-tasks').val()) - 1;
            $(progressBarObj).find('input.in-progress-tasks').val(progressSize);
        } else if ("Done" === taskState) {
            var progressSize = parseInt($(progressBarObj).find('input.done-tasks').val()) - 1;
            $(progressBarObj).find('input.done-tasks').val(progressSize);
        }

        var bloquedStarted = $(progressBarObj).find('input.bloqued-tasks').val();
        var bloquedStartedWidth = (bloquedStarted / tasksSize * 100);
        $(progressBarObj).find('.progress-bar-danger').width(bloquedStartedWidth + "%");

        var inProgress = $(progressBarObj).find('input.in-progress-tasks').val();
        var inProgressWidth = (inProgress / tasksSize * 100);
        $(progressBarObj).find('.progress-bar-striped').width(inProgressWidth + "%");

        var done = $(progressBarObj).find('input.done-tasks').val();
        var doneWidth = (done / tasksSize * 100);
        $(progressBarObj).find('.progress-bar-success').width(doneWidth + "%");
    }
}

function recalculateProgressBar(sprint) {
    var allTasks = $(sprint).find('.sprint-tasks .item').size();
    var bloquedTasks = $(sprint).find('.sprint-tasks .item option:selected:contains("Blocked")').size();
    var inProgressTasks = $(sprint).find('.sprint-tasks .item option:selected:contains("In progress")').size();
    var doneTasks = $(sprint).find('.sprint-tasks .item option:selected:contains("Done")').size();

    $(sprint).find('input.all-tasks').val(allTasks);
    $(sprint).find('input.bloqued-tasks').val(bloquedTasks);
    $(sprint).find('input.in-progress-tasks').val(inProgressTasks);
    $(sprint).find('input.done-tasks').val(doneTasks);

    var bloquedWidth = (bloquedTasks / allTasks * 100);
    $(sprint).find('.progress-bar-danger').width(bloquedWidth + "%");

    var inProgressWidth = (inProgressTasks / allTasks * 100);
    $(sprint).find('.progress-bar-striped').width(inProgressWidth + "%");

    var doneWidth = (doneTasks / allTasks * 100);
    $(sprint).find('.progress-bar-success').width(doneWidth + "%");
}

function dropTaskToSprint(item) {
    var id = $(item).find('.item-ref-content').text().substring(1);
    var sprint = $(item).closest('.sprint-panel').find('.sprint-title-content').text();
    var taskState = $(item).find('.task-state option:selected').val();
    var progressBarObj = $(item).closest('.sprint-panel').find('div.sprint-progress');

    var request = {};
    var token = $("input[name='_csrf']").val();

    request["sprint"] = sprint;
    request["id"] = id;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateTaskSprint",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            } else {
                increaseProgressBar(progressBarObj, taskState);
                $(item).find('.remove-sprint-task').show();
                $(item).find('.remove-sprint-task').unbind('click');
                $(item).find('.remove-sprint-task').click(removeSprintTask);
            }
        },
        error: function(data) {
            showErrorMessage('Can not add the task to the sprint.');
        }
    });
}

function removeSprintTask(event) {
    event.preventDefault();
    event.stopPropagation();

    var element = $(this).closest('.item');
    var request = {};
    var token = $("input[name='_csrf']").val();

    request["id"] = $(this).parent().parent().find('.item-ref-content').text().substring(1);

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprint/updateTaskSprint",
        data: JSON.stringify(request),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if (data['state'] === "KO") {
                showErrorMessage(data['message']);
            } else {
                $(element).hide();
                var taskState = $(element).find('.task-state option:selected').val();
                var progressBarObj = $(element).closest('.sprint-panel').find('div.sprint-progress');
                decreaseProgressBar(progressBarObj, taskState);
                $(element).remove();

                getSprintBacklogTasks();
            }
        },
        error: function(data) {
            showErrorMessage('Can not remove the task from the sprint.');
        }
    });
}











// BACKLOG events
function loadSprintBacklogEvents() {
    // Task acordeon
    $('.panel-heading').unbind('click');
    $('.panel-heading').click(acordeonExtraContent);

    // Stop events for selects of task
    $('.task-state select').unbind('click');
    $('.task-state select').click(function(event) {
        event.stopPropagation();
        event.preventDefault();
    });

    // Stop events for points of task
    $('input#points').unbind('clicks');
    $('input#points').click(function(event) {
        event.stopPropagation();
        event.preventDefault();
    });

    // On cost change
    $('.task-cost input#points').unbind('change');
    $('.task-cost input#points').change(updateCost);

    // Update Assigned to
    $('.assigned-member select').unbind('change');
    $('.assigned-member select').change(updateAssignedTo);

    // Update state
    $('.task-state select').unbind('change');
    $('.task-state select').change(updateState);

    // Tag on hover
    $('.tag-element').hover(function() {
        $(this).find('.delete-tag').show();
    }, function() {
        $(this).find('.delete-tag').hide();
    });

    // Remove tag
    $('.tag-element').click(removeTag);

    // Show add tag
    $('.glyphicon-plus').click(function() {
        $(this).siblings('input#addTag').show();
        $(this).siblings('input#addTag').focus();
        $(this).hide();
    });

    // Add tag - focus out
    $('input#addTag').focusout(addTag);
}

// BACKLOG ajax
function getGenericBacklogTasks() {
    var tags = $('.backlog-search-bar .form-control').val().replace(/\s{2,}/g, ' ');

    if (!tags) {
        getSprintBacklogTasks();
    } else if (tags.indexOf("#") == 0) {
        getSearchBacklogTasksById(tags.substring(1));
    } else {
        tags = tags.split(' ');
        getSearchBacklogTasksByTags(tags);
    }
}

function getSprintBacklogTasks() {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprints/backlogTasks",
        success: function(data){
            $('div.backlog-content').html(data);
            loadSprintBacklogEvents();
            loadComunEvents();
        },

        error: function(e){
            showErrorMessage('Can not gett the backlog tasks.');
        }
    });
}

function getSearchBacklogTasksById(tag) {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprints/backlogSearchById",
        async: true,
        data: {"searchField" : tag.toString()},
        success: function(data){
            $('div.backlog-content').html(data);
            loadSprintBacklogEvents();
        },

        error: function(e){
            showErrorMessage('Can not get the tasks.');
        }
    });
}

function getSearchBacklogTasksByTags(tags) {
    var token = $("input[name='_csrf']").val();

    $.ajax({
        type: "GET",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/sprints/backlogSearchByTags",
        data: {"searchField" : tags.toString()},
        success: function(data){
            $('div.backlog-content').html(data);
            loadSprintBacklogEvents();
        },

        error: function(e){
            showErrorMessage('Can not get the tasks.');
        }
    });
}

function removeBacklogSearch() {
    $('.backlog-search-bar .form-control').val('');
    getSprintBacklogTasks();
}

function updateCost(event) {
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var cost = $(this).val();

    if (cost < 0 || cost > 300) {
        showErrorMessage('The cost must be bettwen 0 and 300.');
        return;
    }

    var task = {};
    task['id'] = id.substring(1);
    task['points'] = cost;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskCost",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the cost.');
        }
    });
}

function updateAssignedTo(event) {
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var email = $(this).find('option:selected').val();

    var task = {};
    task['id'] = id.substring(1);
    task['assignedTo'] = email;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskAssignTo",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            }
        },
        error: function(data) {
            showErrorMessage('Can not assign the member to the task.');
        }
    });
}

function updateState(event) {
    event.preventDefault();
    event.stopPropagation();

    var taskObj = $(this).closest('.item');

    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var state = $(this).find('option:selected').val();

    var task = {};
    task['id'] = id.substring(1);
    task['state'] = state;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/updateTaskState",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                if (state == 'Blocked') {
                    $(taskObj).find('.panel').removeClass('panel-info');
                    $(taskObj).find('.panel').addClass('panel-default');
                } else if ($(taskObj).closest('#sortable_backlog').size() > 0 && state == 'Done') {
                    $(taskObj).hide();
                    $(taskObj).remove();
                } else {
                    $(taskObj).find('.panel').removeClass('panel-default');
                    $(taskObj).find('.panel').addClass('panel-info');
                }

                if ($(taskObj).closest('.sprint').size() > 0) {
                    recalculateProgressBar($(taskObj).closest('.sprint'));
                }
            }
        },
        error: function(data) {
            showErrorMessage('Can not update the state of the task.');
        }
    });
}

function addTag(event) {
    var inputObj = $(this);
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var totalTags = $(this).parent().find('.label').length;
    var tag = $(this).val().replace(/\s{2,}/g, ' ');

    // Hide the input and show the add tag label
    $(this).hide();
    $(this).val('');
    $(this).siblings('.glyphicon-plus').show();

    if (tag.trim()) {
        tag = tag.split(' ');
    } else {
        return;
    }

    if (totalTags > 2) {
        showErrorMessage('You can have only 3 tags.');
        return;
    } else if (tag.length > 1) {
        showErrorMessage('You have to insert only one tag.');
        return;
    }

    var task = {};
    task['id'] = id.substring(1);
    task['tags'] = tag;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/addTaskTag",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                addTagElement(inputObj, tag[0]);
            }
        },
        error: function(data) {
            showErrorMessage('Can not add the tag.');
        }
    });
}

function addTagElement(input, tagName) {
    var tagElement = "<div class='tag-element'>" +
                        "<span class='label label-warning'>" +
                            "<span class='tag-name'>" + tagName + ' ' + "</span>" +
                            "<span class='glyphicon glyphicon-remove delete-tag' style='display: none'></span>" +
                        "</span>" +
                    "</div>";

    if ($(input).parent().find('.tag-element').size() > 0) {
        $(input).parent().find('.tag-element:last').after(tagElement);
    } else {
        $(input).parent().prepend(tagElement);
    }

    // Tag on hover
    $(input).parent().find('.tag-element:last').hover(function() {
        $(this).find('.delete-tag').show();
    }, function() {
        $(this).find('.delete-tag').hide();
    });

    // Add remove tag event
    $(input).parent().find('.tag-element:last').click(removeTag);
}

function removeTag(event) {
    var tagObj = $(this);
    var token = $("input[name='_csrf']").val();
    var id = $(this).closest('.item').find('.item-ref-content').text();
    var tag = $(this).text().trim().replace(/\s{2,}/g, ' ').split(' ');

    var task = {};
    task['id'] = id.substring(1);
    task['tags'] = tag;

    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': token,
            'Content-Type':'application/json'
        },
        url: "/backlog/deleteTaskTag",
        data: JSON.stringify(task),
        dataType: "json",
        timeout: 100000,
        success: function(data) {
            if ("KO" == data['state'])  {
                showErrorMessage(data['message']);
            } else {
                $(tagObj).hide();
                $(tagObj).remove();
            }
        },
        error: function(data) {
            showErrorMessage('Can not delete the tag.');
        }
    });
}

// COMUN FUNCTIONS
function acordeonExtraContent(event) {
    var extraContent = $(this).siblings('.extra-content');

    if ($(extraContent).hasClass('hidden')) {
        $(extraContent).show();
        $(extraContent).removeClass('hidden');
        $(extraContent).addClass('showing');
    } else {
        $(extraContent).hide();
        $(extraContent).removeClass('showing');
        $(extraContent).addClass('hidden');
    }

    event.stopPropagation();
    event.preventDefault();
}