$(function() {
    $('ul.sortable').sortable({ axis: "y", stop: saveStatusOrder, handle: '.handle' });
    $('body').on('click', '.js-toggle-tasktypedescription', toggleDescription);
    $('body').on('click', '.js-showTypeDeletingDialog', function(){
        return showDeletingDialog($(this).attr('data-id'));
    });
    $('body').on('click', '.js-deleteTypeBtn', function() {
        return deleteTaskType($(this).attr('data-typeid'));
    });
    $('body').on('click', '.js-closeDeleteDialogBtn', function () {
        $('#deletingdialog').remove();
        return false;
    });

});

function toggleDescription() {
    toggle(this, '#fulldesc', TaskTypeResources.ReadNext, TaskTypeResources.Minimize);
    return false;
}

function saveStatusOrder() {
    var ids = $('ul.sortable').sortable('toArray');
    $.getJSON(base + 'tasktype.ivp/saveorder', { ids: ids, timestamp: new Date().toString() });
}

function showDeletingDialog(id) {
    $('#deletingdialogwrapper').remove();
    $('li[id=' + id + ']').append('<div id="deletingdialogwrapper" class="popupwrapper"><div id="deletingdialog" class="popup"></div></div>');
    $('#deletingdialog').load(base + 'tasktype/ShowTypeDeletingDialog/' + id, null, function () { $('#deletingdialogwrapper').show(); });
    return false;
}

function deleteTaskType(id) {
    $.getJSON(base + 'tasktype/delete/'+id,function(data) { taskTypeDeleted(data); });
    return false;
}

function taskTypeDeleted(result) {
    if (result.hasOwnProperty('IsOk') && !result.IsOk)
        alert(result.Description);
    else {
        $('#deletingdialogwrapper').remove();
        $('li[id=' + result.Data.Id + ']').remove();
    }
}
