EnVisageOnline/Main/Source/EnVisage/Scripts/Plugins/projectDependency.js

706 lines
35 KiB
JavaScript

/* ===========================================================
* projectDependency.js
* ===========================================================
* Copyright 2017 Prevu
* ========================================================== */
(function ($) {
"use strict"; // jshint ;_;
/* projectDependency CLASS DEFINITION
* ====================== */
var projectDependency = function (element, options) {
this.init(element, options);
};
projectDependency.prototype = {
constructor: projectDependency,
init: function (element, options) {
var plugin = this;
plugin.$options = options;
plugin.$container = $(element);
plugin.$modal = plugin.$container.find('.modal').appendTo('body');
plugin.$modalContent = plugin.$modal.find('.modal-content');
plugin.$dependencyContainer = plugin.$modalContent.find('.dependency-container');
if (!plugin.$options.namePrefix) {
plugin.$options.namePrefix = plugin.$container.find('.name-prefix').data('value');
}
if (!plugin.$options.editUrl) {
throw "Required edit URL not set. Init project dependency control cannot be performed.";
}
if (!plugin.$options.getItemsUrl) {
throw "Required get items URL not set. Init project dependency control cannot be performed.";
}
// wrap modal content with form
plugin.$form = $('<form name="frmDependency"></form>');
plugin.$modalContent.contents().appendTo(plugin.$form);
plugin.$form.appendTo(plugin.$modalContent);
plugin.$modal.modalDialogForm();
plugin.$editForm = {
ddlType: plugin.$modalContent.find('.dep-type').select2({
allowClear: false,
minimumResultsForSearch: -1
}).on("change", function () {
plugin.onChangeType();
}),
ddlProject: plugin.$modalContent.find('.dep-project').select2({
allowClear: false
}).on("change", function () {
validateDependenciesWrapper(plugin);
}),
hdId: plugin.$modalContent.find('.hdId'),
hdSourceId: plugin.$modalContent.find('.hdSourceId'),
hdTargetId: plugin.$modalContent.find('.hdTargetId'),
hdName: plugin.$modalContent.find('.hdName'),
btnSave: plugin.$modalContent.find('button.btnSave').buttonLocker({
click: function () {
saveButtonClicked(plugin);
}
}),
btnDelete: plugin.$modalContent.find('button.btnDelete').buttonLocker({
click: function () {
deleteButtonClicked(plugin);
}
})
};
plugin.$dataset = [];
plugin.$table = $("<table class='table table-striped table-bordered tbl-dependency'>" +
"<thead><tr>" +
"<th style='width:100px'>Dependency</th>" +
"<th>Projects</th>" +
"<th style='width:120px'>Start Date</th>" +
"<th style='width:120px'>End Date</th>" +
"</tr></thead>" +
"<tbody><tr class='empty'><td colspan='4' style='text-align:center;'>There are no dependencies for this project or part.</td></tr></tbody>" +
"</table>").on('resize', function () {
clearTimeout(plugin.rsz);
plugin.rsz = setTimeout(function () { plugin.resize(); }, plugin.resizeTimeout);
}).appendTo(plugin.$container);
plugin.$addButton = $('<a class="btn btn-xs btn-success lockable" title="Add project dependency" style="margin-left:5px;"><i class="fa fa-plus"></i></a>')
.appendTo(plugin.$container.find('label:eq(0)')).buttonLocker({
click: function () {
var node = $('tr').data('source', {
SourceProjectId: plugin.$options.projectId
}).data('rowtype', 0);
plugin.openEditForm(node);
}
});
plugin.$loader = plugin.$container.find('.loadRotator');
if (!plugin.$options.projectId || plugin.$options.projectId === C_EMPTY_GUID) {
plugin.$table.find('tbody tr td').text('You will be able to create dependencies after the project has been saved.');
plugin.$addButton.attr('disabled', 'disabled');
} else {
plugin.loadProjectDependencies();
}
if (typeof plugin.$options.initCallback === 'function') {
plugin.$options.initCallback(plugin.$dataset);
}
$(document).on('refresh.projectDependency', plugin, function () {
plugin.loadProjectDependencies();
});
return true;
},
initResolveForm: function () {
var plugin = this;
if (!plugin.$modalContent.resolveForm) {
console.error("Required /Scripts/Plugins/resolveForm.js plugin is not included.");
} else {
if (plugin.$options.projectId && plugin.$options.projectId !== C_EMPTY_GUID) {
if (plugin.$dependencyContainer.data('resolveForm'))
plugin.$dependencyContainer.resolveForm('destroy');
plugin.$dependencyContainer.resolveForm({
projectId: plugin.$options.projectId,
minStartDate: plugin.$options.minStartDate,
maxEndDate: plugin.$options.maxEndDate,
postRenderCallback: function (valid, hasConflicts) {
plugin.dependencyValidationCallback(valid, hasConflicts);
}
});
setCurrentItemDeleted(plugin);
}
}
},
resize: function () {
var plugin = this;
var width = parseInt((plugin.$table.width() - 120 - 120 - 100) * 0.9);
plugin.$table.find('.wrap').css('width', width + 'px');
},
addItem: function (obj) {
var plugin = this;
if (!plugin.$dataset) {
throw "Dataset not set. Add dependency operation cannot be performed.";
}
var itemIndex = plugin.$dataset.length;
plugin.$dataset.push(obj);
var row = plugin.renderRow(obj);
plugin.$table.append(row);
plugin.$table.append(plugin.renderProjectRows(obj.Items, obj.Type));
$.each(obj.Items, function (index, dataItem) {
var hiddenContainer = $('<div data-dependency="' + dataItem.Id + '"/>').appendTo(plugin.$container);
$('<input type="hidden" name="' + plugin.$options.namePrefix + '[' + itemIndex + '].Id" data-dependency-id value="' + dataItem.Id + '">').appendTo(hiddenContainer);
$('<input type="hidden" name="' + plugin.$options.namePrefix + '[' + itemIndex + '].SourceProjectId" data-dependency-sourceId value="' + dataItem.SourceProjectId + '">').appendTo(hiddenContainer);
$('<input type="hidden" name="' + plugin.$options.namePrefix + '[' + itemIndex + '].TargetProjectId" data-dependency-targetId value="' + dataItem.TargetProjectId + '">').appendTo(hiddenContainer);
$('<input type="hidden" name="' + plugin.$options.namePrefix + '[' + itemIndex + '].Type" data-dependency-type value="' + dataItem.Type + '">').appendTo(hiddenContainer);
});
},
renderRow: function (item) {
var plugin = this;
var row = $('<tr></tr>');
$('<td></td>').append(item.DependencyTypeDisplayName).appendTo(row);
var projectTd = $('<td></td>');
//var containerDiv = $('<div style="width:90%;"></div>').appendTo(projectTd);
var overflowDiv = $('<div class="wrap" style="width:100px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;"></div>').appendTo(projectTd);
for (var index = 0; index < item.Items.length; index++)
{
var obj = item.Items[index];
if (index > 0)
overflowDiv.append(', ');
if (obj.Level !== 0)
$('<span><i>' + obj.Name + '</i></span>').appendTo(overflowDiv);
else
$('<a href="javascript:void(0);" class="lockable">' + obj.Name + '</a>').data('source', obj).data('rowtype', item.Type).on('click', function (event) {
plugin.openEditForm(this);
}).appendTo(overflowDiv);
}
projectTd.appendTo(row);
$('<td></td>').append(item.StartDate).appendTo(row);
$('<td></td>').append(item.EndDate).appendTo(row);
row.on('click', function (event) {
if (event && event.target && event.target.tagName === 'A')
return;
plugin.toggleRow(item, plugin.$table.length);
})
return row;
},
renderProjectRows: function (items, type) {
var plugin = this;
if (!items)
return [];
var rows = [];
for (var index = 0; index < items.length; index++) {
var obj = items[index];
var row = $('<tr></tr>').attr('class', 'type' + type).hide();
$('<td></td>').appendTo(row);
var projectTd = $('<td></td>');
if (obj.Level !== 0)
$('<span><i>' + obj.Name + '</i></span>').appendTo(projectTd);
else
$('<a href="javascript:void(0);">' + obj.Name + '</a>').data('source', obj).data('rowtype', type).on('click', function (event) {
plugin.openEditForm(this);
}).appendTo(projectTd);
projectTd.appendTo(row);
$('<td></td>').append(obj.StartDate === null ? '' : DateTimeConverter.msFormatAsUtcString(obj.StartDate)).appendTo(row);
$('<td></td>').append(obj.EndDate === null ? '' : DateTimeConverter.msFormatAsUtcString(obj.EndDate)).appendTo(row);
rows.push(row);
}
return rows;
},
toggleRow: function (item, rowIndex) {
var plugin = this;
if (!item || !rowIndex)
return;
var row2Append = plugin.$table.find('tbody tr').eq(rowIndex);
if (!row2Append)
return;
var rows = plugin.$table.find('tbody tr.type' + item.Type);
var expanded = row2Append.data('expanded');
if (!expanded)
{
row2Append.data('expanded', true);
rows.fadeIn('slow');
} else {
row2Append.data('expanded', false);
rows.fadeOut('slow');
}
},
loadProjectDependencies: function () {
// prepare plugin for ajax call
var plugin = this;
plugin.state = 0; //'loading'
var request = getAntiXSRFRequest(plugin.$options.getItemsUrl);
request.method = 'GET';
request.data = {
id: plugin.$options.projectId,
sessionKey: plugin.$options.sessionKey,
};
// update ui accordingly
startLoading(plugin);
try {
$.ajax(request).success(function (data, status, headers, config) {
plugin.$dataset = [];
$.each(data, function (index, obj) {
plugin.addItem(obj);
});
if (plugin.$dataset.length === 0) {
plugin.$table.find('tbody tr.empty').show();
} else {
plugin.reenumerateItems();
plugin.$table.find('tbody tr.empty').hide();
}
plugin.state = 1; //'loaded'
stopLoading(plugin);
}).error(function (data, status, headers, config) {
console.debug('loadProjectDependencies', request.url, request.data);
console.error('An error occurred in loadProjectDependencies method');
showErrorModal('Project dependency loading error', 'We are sorry but there was an error while loading project dependencies from the server, please try again later. If the error continues, contact administrators to fix the problem');
plugin.state = 2; //'error'
stopLoading(plugin);
});
} catch (e) {
console.debug('loadProjectDependencies', request.url, request.data);
console.error('An error occurred in loadProjectDependencies method while loading project dependencies');
showErrorModal();
stopLoading(plugin);
}
},
reenumerateItems: function () {
var plugin = this;
plugin.$container.find('[data-dependency]').each(function (index, item) {
$(this).find('[data-dependency-id]').prop('name', plugin.$options.namePrefix + "[" + index + "].Id");
$(this).find('[data-dependency-sourceId]').prop('name', plugin.$options.namePrefix + "[" + index + "].SourceProjectId");
$(this).find('[data-dependency-targetId]').prop('name', plugin.$options.namePrefix + "[" + index + "].TargetProjectId");
$(this).find('[data-dependency-type]').prop('name', plugin.$options.namePrefix + "[" + index + "].Type");
});
},
openEditForm: function (element) {
var item = $(element).data('source');
var type = $(element).data('rowtype');
var plugin = this;
if (item) {
plugin.$editForm.hdId.val(item.Id);
plugin.$editForm.hdSourceId.val(item.SourceProjectId);
plugin.$editForm.hdTargetId.val(item.TargetProjectId);
plugin.$editForm.hdName.val(item.Name);
var oldValue = parseInt(plugin.$editForm.ddlType.val());
if (!item.Id) {
plugin.$editForm.btnDelete.hide();
plugin.$modalContent.find('h4.modal-title').text('Add Dependency');
}
else {
plugin.$editForm.btnDelete.show();
plugin.$modalContent.find('h4.modal-title').text('Edit Dependency');
}
plugin.$editForm.ddlType.select2('val', type);
plugin.onChangeType().done(function () {
plugin.$modal.modalDialogForm('show');
});
}
$.validator.unobtrusive.parseDynamicContent(plugin.$form);
plugin.initResolveForm();
},
onChangeType: function () {
var plugin = this;
try {
var type = plugin.$editForm.ddlType.val();
var selectedProjectId = null;
if (plugin.$options.projectId === plugin.$editForm.hdSourceId.val())
selectedProjectId = plugin.$editForm.hdTargetId.val();
else
selectedProjectId = plugin.$editForm.hdSourceId.val();
plugin.$editForm.ddlProject.select2('disable');
plugin.$editForm.ddlProject.select2('val', '');
plugin.$editForm.ddlProject.children().remove();
plugin.$editForm.ddlProject.append($('<option value="">Select a project</option>'));
return $.ajax({
url: plugin.$options.getProjectsUrl + '?type=' + type + '&projectId=' + plugin.$options.projectId +
'&sessionKey=' + plugin.$options.sessionKey,
cache: false,
dataType: "json",
method: 'GET',
success: function (result, status, headers, config) {
if (result)
{
$.each(result, function (index, obj) {
var option = $('<option value="' + obj.ProjectId + '">' + obj.ProjectName + '</option>');
option.data('start-date', obj.ScenarioStartDate);
option.data('end-date', obj.ScenarioEndDate);
plugin.$editForm.ddlProject.append(option);
});
// set selected value if any
if (selectedProjectId)
{
if (plugin.$editForm.ddlProject.find("option[value='" + selectedProjectId + "']").length) {
plugin.$editForm.ddlProject.val(selectedProjectId).trigger("change");
} else {
// Create the DOM option that is pre-selected by default
var newState = new Option(plugin.$editForm.hdName.val(), selectedProjectId, true, true);
// Append it to the select
plugin.$editForm.ddlProject.append(newState).trigger('change');
}
}
validateDependenciesWrapper(plugin);
}
},
error: function (data, status, headers, config) {
console.debug('onChangeType', type, plugin.$options.projectId);
console.error('An error occurred in onChangeType method');
showErrorModal('Loading projects error', 'We are sorry but there was an error while loading projects, please try again later. If the error continues, contact administrators to fix the problem', '000017');
},
complete: function () {
plugin.$editForm.ddlProject.select2('enable');
}
});
} catch (e) {
console.error('An error occurred trying to load projects');
showErrorModal(null, null, '000018');
plugin.$editForm.ddlProject.select2('enable');
}
},
dependencyValidationCallback: function (valid, hasConflicts) {
var plugin = this;
if (hasConflicts || !valid)
plugin.$dependencyContainer.show();
else
plugin.$dependencyContainer.hide();
plugin.$modalContent.find('.dependency-warnings ul li:gt(0)').remove();
var resolveWarnings = plugin.$dependencyContainer.find('.resolve-warnings');
resolveWarnings.find('ul li').appendTo(plugin.$modalContent.find('.dependency-warnings ul'));
resolveWarnings.hide();
plugin.$dependencyContainer.find('.tbl-conflicts p').hide();
},
destroy: function () {
var e = $.Event('destroy');
this.$container.trigger(e);
if (e.isDefaultPrevented())
return;
this.$container
.off('.projectDependency')
.removeData('projectDependency');
this.$dataset = null;
this.$table.off('resize');
this.$table = null;
this.$loader = null;
this.$addButton = null;
this.$editForm.ddlType = null;
this.$editForm.ddlProject = null;
this.$editForm.hdId = null;
this.$editForm.hdSourceId = null;
this.$editForm.hdTargetId = null;
this.$editForm.btnSave = null;
this.$editForm.btnDelete = null;
this.$editForm.hdName = null;
this.$editForm = null;
this.$dependencyContainer.resolveForm('destroy');
this.$modalContent = null;
this.$modal = null;
this.$container = null;
},
//saveItem: function (item) {
// var plugin = this;
// var typeItem = null;
// // find a row with the same dependency time in the dependency grid
// for (var i = 0; i < plugin.$dataset.length; i++) {
// if (plugin.$dataset[i].Type === item.Type) {
// typeItem = plugin.$dataset[i];
// break;
// }
// }
// // if no row with this type yet then let's create it
// if (!typeItem) {
// typeItem = {
// Type: item.Type,
// DependencyTypeDisplayName: getTypeDisplayName(item.Type)
// };
// plugin.$dataset.push(typeItem);
// }
// // fill row with new data
// if (!typeItem.Items)
// typeItem.Items = [];
// var subItem = null;
// // find a project item with the same id in the row's items
// for (var j = 0; j < typeItem.Items.length; j++) {
// if (typeItem.Items[j].Id === item.Id) {
// subItem = typeItem.Items[j];
// break;
// }
// }
// // if no sub item with this Id yet then let's create it
// if (!subItem) {
// subItem = {
// Id: item.Id,
// Type: item.Type,
// StartDate: item.StartDate,
// EndDate: item.EndDate,
// SourceProjectId: item.SourceProjectId,
// TargetProjectId: item.TargetProjectId,
// Name: item.Name
// };
// typeItem.Items.push(subItem);
// } else {
// subItem.Type = item.Type;
// subItem.StartDate = item.StartDate;
// subItem.EndDate = item.EndDate;
// subItem.SourceProjectId = item.SourceProjectId;
// subItem.TargetProjectId = item.TargetProjectId;
// subItem.Name = item.Name;
// }
// setCalculatedFields(typeItem);
// plugin.state = 0; //'loading'
// startLoading(plugin);
// $.each(plugin.$dataset, function (index, obj) {
// plugin.renderRow(obj);
// });
// if (plugin.$dataset.length < 1) {
// plugin.$table.find('tbody tr.empty').show();
// } else {
// plugin.reenumerateItems();
// plugin.$table.find('tbody tr.empty').hide();
// }
// plugin.state = 1; //'loaded'
// stopLoading(plugin);
//}
};
function startLoading(plugin) {
plugin.$table.find('tbody tr:not(.empty)').remove();
plugin.$table.hide();
plugin.$addButton.hide();
plugin.$loader.show();
}
function stopLoading(plugin) {
plugin.$loader.hide();
plugin.$addButton.show();
plugin.$table.show();
}
function deleteButtonClicked(plugin) {
var url = '';
try {
url = plugin.$options.deleteUrl + '?Id=' + plugin.$editForm.hdId.val() + '&sessionKey=' + plugin.$options.sessionKey;
blockUI();
var request = getAntiXSRFRequest(url);
$.ajax(request).success(function (result, status, headers, config) {
handleAjaxResponse(result, function () {
plugin.$container.trigger('refresh.projectDependency');
plugin.$modal.modalDialogForm('hide');
}, null, null, plugin.$modalContent.find('form'));
unblockUI();
}).error(function (data, status, headers, config) {
console.debug('deleteButtonClicked', request.url, request.data);
console.error('An error occurred in deleteButtonClicked method');
showErrorModal('Project dependency delete error', 'We are sorry but there was an error while deleting project dependency, please try again later. If the error continues, contact administrators to fix the problem', '000015');
unblockUI();
});
} catch (e) {
console.debug('deleteButtonClicked', plugin);
console.error('An error occurred trying to save project dependency');
showErrorModal(null, null, '000016');
unblockUI();
}
};
//function setCalculatedFields(typeItem) {
// var newStartDate = undefined;
// var newEndDate = undefined;
// for (var i = 0; i < typeItem.Items.length; i++) {
// var item = typeItem.Items[i];
// if (!newStartDate || item.StartDate < newStartDate)
// newStartDate = item.StartDate;
// if (!newEndDate || item.EndDate > newEndDate)
// newEndDate = item.EndDate;
// }
// if (typeItem.Type === 0/* || typeItem.Type == 100 || typeItem.Type == 101*/)
// typeItem.StartDate = DateTimeConverter.msFormatAsLocalString(newStartDate);
// else
// typeItem.StartDate = '';
// if (typeItem.Type === 1)
// typeItem.EndDate = DateTimeConverter.msFormatAsLocalString(newEndDate);
// else
// typeItem.EndDate = '';
//};
// obsolete, to be used for client side editing of dependencies
//function saveButtonClickedJs() {
// var plugin = this;
// if (!plugin)
// return;
// var type = plugin.$editForm.ddlType.val();
// var selectedProjectOption = plugin.$editForm.ddlProject.find('option').filter(function () { return this.selected });
// var newItem = {
// Id: plugin.$editForm.hdId.val(),
// Type: parseInt(plugin.$editForm.ddlType.val()),
// SourceProjectId: type >= 100 ? plugin.$editForm.ddlProject.val() : plugin.$options.projectId,
// TargetProjectId: type < 100 ? plugin.$editForm.ddlProject.val() : plugin.$options.projectId,
// StartDate: parseInt(selectedProjectOption.data('start-date')),
// EndDate: parseInt(selectedProjectOption.data('end-date')),
// Name: selectedProjectOption.text(),
// };
// plugin.$container.trigger('update.projectDependency', [newItem]);
// plugin.$modal.modal('hide');
//};
function saveButtonClicked(plugin) {
try {
if (!plugin.$form.valid())
return false;
validateDependenciesWrapper(plugin, function (valid, hasConflicts) {
if (!valid)
return;
var type = parseInt(plugin.$editForm.ddlType.val());
var selectedProjectOption = plugin.$editForm.ddlProject.find('option').filter(function () { return this.selected });
var originalSourceId = plugin.$editForm.hdSourceId.val();
var originalTargetId = plugin.$editForm.hdTargetId.val();
var newItem = {
Id: plugin.$editForm.hdId.val() || C_EMPTY_GUID,
Type: type,
SourceProjectId: plugin.$options.projectId,
TargetProjectId: plugin.$editForm.ddlProject.val(),
StartDate: parseInt(selectedProjectOption.data('start-date')),
EndDate: parseInt(selectedProjectOption.data('end-date')),
Name: selectedProjectOption.text(),
SessionKey: plugin.$options.sessionKey
};
// if new item does not have target projectid then do not save anything
if (!newItem.TargetProjectId)
return false;
// if current project 'starts after' target project then we need to switch source and target and save it as 'starts before'
if (1 === newItem.Type) {
// if type is 1 ('starts after') then save it as 'starts before' because this is the same type but just different direction
// so we just need to switch source and target and save it with type = 0
newItem.Type = 0;
var s = newItem.SourceProjectId;
newItem.SourceProjectId = newItem.TargetProjectId;
newItem.TargetProjectId = s;
}
newItem.ResolveConflicts = plugin.$dependencyContainer.data('resolveForm').getData();
blockUI();
var request = getAntiXSRFRequest(plugin.$options.editUrl, newItem, plugin.$modalContent.find('form [name=__RequestVerificationToken]'));
$.ajax(request).success(function (result, status, headers, config) {
handleAjaxResponse(result, function () {
plugin.$container.trigger('refresh.projectDependency');
plugin.$modal.modalDialogForm('hide');
}, null, null, plugin.$modalContent.find('form'), 'model.');
unblockUI();
}).error(function (data, status, headers, config) {
console.debug('saveButtonClicked', request.url, request.data);
console.error('An error occurred in saveButtonClicked method');
showErrorModal('Project dependency saving error', 'We are sorry but there was an error while saving project dependency, please try again later. If the error continues, contact administrators to fix the problem', '000013');
unblockUI();
});
});
} catch (e) {
console.debug('saveButtonClicked', newItem);
console.error('An error occurred trying to save project dependency');
showErrorModal(null, null, '000014');
unblockUI();
}
};
function setCurrentItemDeleted(plugin) {
var projectId = null;
if (plugin.$options.projectId === plugin.$editForm.hdSourceId.val())
projectId = plugin.$editForm.hdTargetId.val();
else
projectId = plugin.$editForm.hdSourceId.val();
if (!plugin.$modalContent.find('.dep-type').select2('val').length || !projectId) {
return;
}
// if form is not valid
if (!plugin.$form.valid()) {
return;
}
var type = parseInt(plugin.$editForm.ddlType.val());
var originalSourceId = plugin.$editForm.hdSourceId.val();
var originalTargetId = plugin.$editForm.hdTargetId.val();
var selectedProjectOption = plugin.$editForm.ddlProject.find('option').filter(function () { return this.selected });
var newItem = {
Id: Math.uuid(),
Type: type,
SourceProjectId: plugin.$options.projectId,
TargetProjectId: projectId,
ProjectId: projectId,
StartDate: parseInt(selectedProjectOption.data('start-date')),
EndDate: parseInt(selectedProjectOption.data('end-date')),
IsDeleted: true,
IsNew: false
};
// if current project 'starts after' target project then we need to switch source and target and save it as 'starts before'
if (1 === newItem.Type) {
// if type is 1 ('starts after') then save it as 'starts before' because this is the same type but just different direction
// so we just need to switch source and target and save it with type = 0
newItem.Type = 0;
var tmpId = newItem.SourceProjectId;
newItem.SourceProjectId = newItem.TargetProjectId;
newItem.TargetProjectId = tmpId;
}
plugin.$items2Exclude = [newItem];
};
function validateDependenciesWrapper(plugin, fnCallback) {
// if dependency is not set
var projectId = plugin.$editForm.ddlProject.val();
if (!plugin.$modalContent.find('.dep-type').select2('val').length || !projectId) {
plugin.dependencyValidationCallback(true);
plugin.$dependencyContainer.hide();
return;
}
// if form is not valid
if (!plugin.$form.valid()) {
plugin.dependencyValidationCallback(true);
plugin.$dependencyContainer.hide();
return;
}
var type = parseInt(plugin.$editForm.ddlType.val());
var originalSourceId = plugin.$editForm.hdSourceId.val();
var originalTargetId = plugin.$editForm.hdTargetId.val();
var selectedProjectOption = plugin.$editForm.ddlProject.find('option').filter(function () { return this.selected });
var newItem = {
Id: Math.uuid(),
Type: type,
SourceProjectId: plugin.$options.projectId,
TargetProjectId: projectId,
ProjectId: projectId,
StartDate: parseInt(selectedProjectOption.data('start-date')),
EndDate: parseInt(selectedProjectOption.data('end-date')),
IsNew: true,
IsDeleted: false
};
// if current project 'starts after' target project then we need to switch source and target and save it as 'starts before'
if (1 === newItem.Type) {
// if type is 1 ('starts after') then save it as 'starts before' because this is the same type but just different direction
// so we just need to switch source and target and save it with type = 0
newItem.Type = 0;
var tmpId = newItem.SourceProjectId;
newItem.SourceProjectId = newItem.TargetProjectId;
newItem.TargetProjectId = tmpId;
}
plugin.$dependencyContainer.resolveForm('setDeletedItems', plugin.$items2Exclude);
plugin.$dependencyContainer.resolveForm('setNewItems', [newItem]);
plugin.$dependencyContainer.resolveForm('validate', [null, null, fnCallback]);
}
/* projectDependency PLUGIN DEFINITION
* ======================= */
$.fn.projectDependency = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('projectDependency'),
options = $.extend({}, $.fn.projectDependency.defaults, $this.data(), typeof option === 'object' && option);
if (!data) $this.data('projectDependency', (data = new projectDependency(this, options)));
if (typeof option === 'string')
data[option].apply(data, [].concat(args));
});
};
$.fn.projectDependency.defaults = {
editUrl: '/Project/EditDependency',
deleteUrl: '/Project/DeleteDependency',
getItemsUrl: '/Project/GetDependencies',
getProjectsUrl: '/Project/GetProjects',
projectId: null,
sessionKey: null,
initCallback: null,
editCallback: null,
removeCallback: null,
namePrefix: null,
maxProjectCount: 3,
resizeTimeout: 100,
minStartDate: null,
maxEndDate: null
};
$.fn.projectDependency.Constructor = projectDependency;
}(jQuery));