
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Project task link functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

// Use this for all project task link functions
var ProjectTaskLinkDetailsRecordId = "";
var ProjectTaskPredecessorId = "";
var ProjectTaskSuccessorId = "";


function OpenProjectTaskLinkDetailsDialog(RecordId) {

    // Just in case this is open
    CloseLastDropdown();

    // Remember this for all project task link operations
    ProjectTaskLinkDetailsRecordId = RecordId;

    if (!RecordId) {
        ToastError("Task Links", "Select a project task record to view its incoming and outgoing links.");
        return;
    }

    var nDlgWidth = 900;
    var nDlgHeight = 575;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.95;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogTaskLinkDetails").igDialog({ modal: true, headerText: "Task Links", width: nDlgWidth, height: nDlgHeight, resizable: true, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogTaskLinkDetails").igDialog("open");

    CenterDialog("igDialogTaskLinkDetails");

    // Set up controls
    RefreshProjectTaskLinkDetailsDialog();
}


function OpenProjectTaskLinkTypeDialog() {

    // Just in case this is open
    CloseLastDropdown();

    if (!ProjectTaskLinkDetailsRecordId) {
        ToastError("Task Links", "Select a project task record to view its incoming and outgoing links.");
        return;
    }

    var nDlgWidth = 600;
    var nDlgHeight = 400;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.95;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogTaskLinkType").igDialog({ modal: true, headerText: "Task Link Type", width: nDlgWidth, height: nDlgHeight, resizable: true, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogTaskLinkType").igDialog("open");

    CenterDialog("igDialogTaskLinkType");

    // Set up controls
    RefreshProjectTaskLinkTypeDialog();
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the dialogs
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseTaskLinkDetailsDialog() {
    $("#igDialogTaskLinkDetails").igDialog("close");
    bTaskLinkDetailsDialogIsOpen = false;
    ProjectTaskLinkDetailsRecordId = "";
}

function IsTaskLinkDetailsDialogOpen() {
    return bTaskLinkDetailsDialogIsOpen;
}

function CloseTaskLinkTypeDialog() {
    $("#igDialogTaskLinkType").igDialog("close");
    bTaskLinkTypeDialogIsOpen = false;

    // Refresh the details with the the new values
    // LinkTypeDropdown
    // LagDaysTextBox
    var LinkType = $("#LinkTypeDropdown").val();
    var LagDays = $("#LagDaysTextBox").val();
    AjaxSetProjectTaskLinkType(LinkType, LagDays);
}

function IsTaskLinkTypeDialogOpen() {
    return bTaskLinkTypeDialogIsOpen;
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Refresh the dialogs
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function RefreshProjectTaskLinkDetailsDialog() {
    var DialogTaskLinkDetailsPartialView = $("#igDialogTaskLinkDetailsPartialView");
    AjaxRefreshProjectTaskLinkDetailsPartialView(DialogTaskLinkDetailsPartialView);
}

function RefreshProjectTaskLinkTypeDialog() {
    var DialogTaskLinkTypePartialView = $("#igDialogTaskLinkTypePartialView");
    AjaxRefreshProjectTaskLinkTypePartialView(DialogTaskLinkTypePartialView);
}





function OnTaskLinkDetailsClearAllLinks() {

    // Clear all project task links
    PopupYesNoWithCallback("Delete links", "Are you sure you wish to delete all links?\r\n\r\nThis cannot be undone!", AjaxClearAllProjectTaskLinks, null/*proceedobject*/);
}



/**
 * Called by ModelDialogTaskLinkDetails.BuildLinkGridHtml() "onclick" function
 * @param {any} ProjectTaskId
 * @param {any} LinkedProjectTaskId
 */
function OnAddDeleteProjectTaskLink(nPredecessorSection, ProjectTaskId, LinkedProjectTaskId) {

    // See ModelDialogTaskLinkDetails.BuildLinkGridHtml() for "onclick" function
    // Two project task ids indicates this is a "Delete" operation
    // LinkedProjectTaskId indicates this is a "Predecessor" operation
    // ProjectTaskId indicates this is a "Successor" operation
    var bPredecessorSection = (nPredecessorSection === "1");
    var PredecessorId = ProjectTaskId;
    var SuccessorId = LinkedProjectTaskId;
    var bHasPredecessorId = (PredecessorId !== null && PredecessorId !== '');
    var bHasSuccessorId = (SuccessorId !== null && SuccessorId !== '');
    var bProjectTaskIdIsEmpty = (ProjectTaskId === null || ProjectTaskId === '');
    var bLinkedProjectTaskIdIsEmpty = (LinkedProjectTaskId === null || LinkedProjectTaskId === '');
    var bDeleteLink = (bHasPredecessorId && bHasSuccessorId);
    var bAddLink = (bProjectTaskIdIsEmpty || !LinkedProjectTaskId);
    var bAddPredecessor = (bAddLink && (SuccessorId == ProjectTaskLinkDetailsRecordId));
    var bAddSuccessor = (bAddLink && (PredecessorId == ProjectTaskLinkDetailsRecordId));
    var bDelPredecessor = (bDeleteLink && (SuccessorId == ProjectTaskLinkDetailsRecordId));
    var bDelSuccessor = (bDeleteLink && (PredecessorId == ProjectTaskLinkDetailsRecordId));
    var AddSuccessorToProjectTaskId = (bAddPredecessor ? SuccessorId : ProjectTaskLinkDetailsRecordId);

    if (bDeleteLink) {
        PopupYesNoWithCallback("Delete link", "Are you sure you wish to delete the link?\r\n\r\nThis cannot be undone!", AjaxProjectTaskUnlinkSuccessor, { ProjectTaskPredecessorId: PredecessorId, ProjectTaskSuccessorId: SuccessorId });
        return;
    }

    if (bAddLink) {
        AjaxPopupProjectTaskLinkMenu(ProjectTaskLinkDetailsRecordId, bPredecessorSection);
        return;
    }
}

function OnEditProjectTaskLink(nPredecessorSection, PredecessorId, SuccessorId) {

    var bPredecessorSection = (nPredecessorSection === "1");
    ProjectTaskPredecessorId = PredecessorId;
    ProjectTaskSuccessorId = SuccessorId;
    OpenProjectTaskLinkTypeDialog();
}

function OnEditProjectTask(nPredecessorSection, ProjectTaskId, LinkedProjectTaskId) {

    // Edit the project task
    var PredecessorId = ProjectTaskId;
    var SuccessorId = LinkedProjectTaskId;
    var bPredecessorSection = (nPredecessorSection === "1");
    var EditProjectTaskId = (bPredecessorSection ? PredecessorId : SuccessorId);
    OpenEditRecordDialog(false/*bNewRecord*/, "stdata.BaseDataSet", "ProjectTasks", EditProjectTaskId);
}

/**
 * Called from popup menu containing project tasks to be linked
 * See: HomeController.GetProjectTaskLinkMenuItems()
 * A context menu is build with this function as the "PerformMenuActionName" and parameters
 * User clicks a task from the menu, and this function is called as a result
 * Use the parameters to determine how to link project tasks
 * @param {any} params
 */
function OnProjectTaskAddLink(ProjectTaskLinkParameters) {

    // Extact values from the menu choice
    // These values are created in HomeController.GetProjectTaskLinkMenuItems()
    var ProjectTaskId = ExtractParameterValueByName(ProjectTaskLinkParameters, "ProjectTaskId");
    var AddProjectTaskId = ExtractParameterValueByName(ProjectTaskLinkParameters, "AddProjectTaskId");
    var PredecessorSection = ExtractParameterValueByName(ProjectTaskLinkParameters, "PredecessorSection");

    // Good values?
    if (!ProjectTaskId)
        return;
    if (!AddProjectTaskId)
        return;
    if (typeof PredecessorSection === 'undefined')
        return;

    // Call Ajax to link the two tasks
    AjaxAddProjectTaskLink(ProjectTaskId, AddProjectTaskId, PredecessorSection);
}


/**
 * Called when user clicks "Links" image in Project Tasks page
 * This image indicates whether the task has incomming or outgoing link dependencies
 * I.e. Predecessors and successors
 * See stdata.ProjectTaskSet where image column is created
 * */
function OnProjectTaskLinkImageClicked(ContentType, sDbTable, sRecordId) {

    // Open task links dialog
    OpenProjectTaskLinkDetailsDialog(sRecordId);
}



function AjaxRefreshProjectTaskLinkDetailsPartialView(divElement) {

    if (!divElement)
        return;

    var params = {
        "ProjectTaskId": ProjectTaskLinkDetailsRecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxProjectTaskLinkDetailsPartialView/",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json", /*type of data sent to server*/
    }).done(function (data) {
        $(divElement).html(data);

        CenterDialog("igDialogTaskLinkDetails");

        // Enable or disable controls based on choices
        //FillProjectTaskLinkDetailsControls();
        //EnableProjectTaskLinkDetailsControls();
    });
}

function AjaxRefreshProjectTaskLinkTypePartialView(divElement) {

    if (!divElement)
        return;

    var params = {
        "ProjectTaskId": ProjectTaskLinkDetailsRecordId,
        "ProjectTaskPredecessorId": ProjectTaskPredecessorId,
        "ProjectTaskSuccessorId": ProjectTaskSuccessorId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxProjectTaskLinkTypePartialView/",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json", /*type of data sent to server*/
    }).done(function (data) {
        $(divElement).html(data);

        CenterDialog("igDialogTaskLinkType");
    });
}




function AjaxSetProjectTaskLinkType(LinkType, LagDays) {

    var params = {
        "ProjectTaskId": ProjectTaskLinkDetailsRecordId,
        "ProjectTaskPredecessorId": ProjectTaskPredecessorId,
        "ProjectTaskSuccessorId": ProjectTaskSuccessorId,
        "LinkType": LinkType,
        "LagDays": LagDays,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxSetProjectTaskLinkType",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {
                RefreshProjectTaskLinkDetailsDialog();

                // Refresh the grid contents to show project task changes
                RefreshSelectedContent();
            }
            else {
                ToastError("AjaxSetProjectTaskLinkType", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxSetProjectTaskLinkType", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


function AjaxClearAllProjectTaskLinks() {

    var params = {
        "ProjectTaskId": ProjectTaskLinkDetailsRecordId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxClearAllProjectTaskLinks",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {
                RefreshProjectTaskLinkDetailsDialog();

                // Refresh the grid contents to show project task changes
                RefreshSelectedContent();
            }
            else {
                ToastError("AjaxClearAllProjectTaskLinks", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxClearAllProjectTaskLinks", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


function AjaxProjectTaskUnlinkSuccessor(prompt, PredecessorAndSuccessorIds) {

    var params = {
        "ProjectTaskPredecessorId": PredecessorAndSuccessorIds.ProjectTaskPredecessorId,
        "ProjectTaskSuccessorId": PredecessorAndSuccessorIds.ProjectTaskSuccessorId,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxProjectTaskUnlinkSuccessor",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {
                RefreshProjectTaskLinkDetailsDialog();

                // Refresh the grid contents to show project task changes
                RefreshSelectedContent();
            }
            else {
                ToastError("AjaxProjectTaskUnlinkSuccessor", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxProjectTaskUnlinkSuccessor", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}



function AjaxPopupProjectTaskLinkMenu(ProjectTaskId, bPredecessorSection) {

    var AjaxCallerEvent = event;

    var params = {
        "ProjectTaskId": ProjectTaskId,
        "PredecessorSection": bPredecessorSection,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetProjectTaskLinkMenuItems",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {

                // Pop up menu items
                if (response.ContextMenuItems) {
                    var menuitems = JSON.parse(response.ContextMenuItems);
                    var menu = new ContextMenu(menuitems);
                    menu.display(AjaxCallerEvent);
                    return;
                }
            }
            else {
                ToastError("AjaxPopupProjectTaskLinkMenu", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxPopupProjectTaskLinkMenu", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}



function AjaxAddProjectTaskLink(ProjectTaskId, AddProjectTaskId, bPredecessorSection) {

    var params = {
        "ProjectTaskId": ProjectTaskId,
        "AddProjectTaskId": AddProjectTaskId,
        "PredecessorSection": bPredecessorSection,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxAddProjectTaskLink",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            if (response.Success) {
                RefreshProjectTaskLinkDetailsDialog();

                // Refresh the grid contents to show project task changes
                RefreshSelectedContent();

                // Got a problem?
                if (response.PromptTitle && response.PromptMessage) {
                    PopupErrorMessage(response.PromptTitle, response.PromptMessage);
                    return;
                }

            }
            else {
                ToastError("AjaxPopupProjectTaskLinkMenu", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxPopupProjectTaskLinkMenu", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


