<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Task.Master" Inherits="System.Web.Mvc.ViewPage<AdministratorConsole.Models.TaskController.NewViewModel>" %>

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.DevExpress().RenderScripts(Page, new Script { ExtensionSuite = ExtensionSuite.Editors }); %>
    <% Html.DevExpress().RenderStyleSheets(Page, new StyleSheet { ExtensionSuite = ExtensionSuite.Editors } ); %>
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery-ui-1.14.0.min.js" type="text/javascript"></script>
    <link href='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery.multiselect/jquery.multiselect.css' rel="stylesheet" type="text/css" /> 
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery.multiselect/jquery.multiselect.js" type="text/javascript"></script>
    <link href='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Content/Bootstrap/bootstrap.min.css?_v=<%=DateTime.UtcNow.Ticks %>' rel="stylesheet" type="text/css" />
    <% Html.RenderPartial("Task/TaskAutocompleteComboBox"); %>
    <% Html.RenderPartial("Task/TaskInputFunctions"); %>
    <% Html.RenderPartial("Task/TaskViewExpressionBuilder"); %>
    <script language="javascript" type="text/javascript">
        var taskSubmitted = false;
        
        function returnToMain() {
            clearWebTriggersessionStorage();
            window.location.href = "<%= Url.Action("TaskSchedules", "Task") %>";
        }
        
        function submitForm(runNewSchedule) {
            <% if (Model.TaskTargetModelWarning.HasValue) { %>
                if ($("#Scope").val().toLowerCase() == "file") {
                    var target = $("#Target").val().trim();

                    if (target == "*") {
                        $.ajax({
                        type: 'POST',
                            url: '<%= Url.Action("LoadCountModelsIncluded", "Task") %>',
                            data: {
                                projectId: $("#ProjectId").val(),
                                searchTerm: target
                            },
                            cache: false,
                            success: function (response) {
                                var includedFiles = JSON.parse(response);

                                if (includedFiles.length > <%= Model.TaskTargetModelWarning %>) {
                                    $.ajax({
                                        type: 'GET',
                                        url: '<%= Url.Action("GetConfirmSubmitTaskDialog", "Task") %>',
                                        data: {
                                            includedFileCount: includedFiles.length,
                                            runNewSchedule: ((runNewSchedule != null) && (runNewSchedule))
                                        },
                                        cache: false,
                                        success: function (response) {
                                            $("#modal-overlay").html(response);
                                        },
                                        complete: function () {
                                            showModelDialog();
                                        }
                                    });
                                }
                                else submitTask(runNewSchedule);
                            }
                        });
                    }
                    else submitTask(runNewSchedule);
                }
                else submitTask(runNewSchedule);
            <% } else { %>
                submitTask(runNewSchedule);
            <% } %>
        }

        function submitTask(runNewSchedule) {
            $("#validation-error").empty();
            $("#validation-error").hide();
            
            var validationResults = [];
            
            if (!validateInputtedTaskParameters()) {
                validationResults.push("All the required task inputs were not provided");
            }

            if (!isValidMaxDays()) {
                validationResults.push("The schedule days are greater than the maximum allowed.");
            }

            <% if (!string.IsNullOrEmpty(Model.NewTaskSchedule.Validation)) { %>
                try {
                    var validate = <%= Model.NewTaskSchedule.Validation %>;

                    validationResults = validate();
                }
                catch(err) {
                    console.log("Error validating task: " + err.toString());
                }
            <% } %>
                
            if (validationResults.length > 0) {
                $("#validation-error").show();
                $("#validation-error").html(validationResults.join("<br/>"));

                return;
            }

            finalizePostAction();
            collectWebTriggerData();

            <% if (Model.NewTaskSchedule.SelectedTaskTypeId == -1) { %>
                var scriptSequence = "";
                
                $(".sequence-script").each(function() {
                    if ($(this).attr("task-id")) scriptSequence += "," + $(this).attr("task-id");
                });

                if (scriptSequence .length > 0) scriptSequence = scriptSequence.substring(1);

                $("#TaskSequence").val(scriptSequence);
            <% } %>

            $(".taskScheduleOptionMultiselect").each(function (index, multiselect) {
                var value = "";
                $(multiselect).find('input').each(function (inputIndex, checkbox) {
                    if (checkbox.checked) {
                        value += $(checkbox).val() + "\n";
                    }
                });
                value = value.slice(0, -1);
                $("<input />").attr("type", "hidden")
                    .attr("name", multiselect.id)
                    .attr("value", value)
                    .appendTo("#NewTaskSchedule");
            });
            
            if (runNewSchedule) $('#NewTaskSchedule').attr('action', "<%= Url.Action("InsertAndRunTaskSchedule/" + Model.NewTaskSchedule.SelectedTaskTypeId, "Task") %>");

            if (!taskSubmitted) {
                taskSubmitted = true;
                
                $("#NewTaskSchedule").submit();
            }
        }
    </script>
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
        <div id="content">
            <% using (Html.BeginForm("InsertTaskSchedule/" + Model.NewTaskSchedule.SelectedTaskTypeId, "Task", FormMethod.Post, new { @id = "NewTaskSchedule" }))
                { %>
	            <div class="left-floating-panel"><h1>Setup Tasks</h1></div>
                <div class="right-floating-panel"><input type="button" value="Create" class="button" onclick="submitForm()" /></div>
                <div class="right-floating-panel"><input type="button" value="Create and Run" class="button" onclick="submitForm(true)" /></div>
                <div class="right-floating-panel"><input type="button" value="Cancel" class="button" onclick="returnToMain()" /></div>
                <div><input type="hidden" id="WebTriggerData" name="WebTriggerData" /></div>
                <div class="clear"></div>
                <div class="left-floating-panel"><h2><%= Html.Encode(Model.NewTaskSchedule.TaskTypeName)%></h2></div>
                <div class="right-floating-panel"><a href="<%= WebHelpHelper.GetWebHelpURL(((LicenseType)ViewData["LicenseType"])) %>index.htm#t=Admin_%26_Coordinators_Guide%2FProject_Setup%2FTasks%2FTasks_Setup.htm" target="_blank">Task Help</a></div>
                <div class="clear"></div>
                <% Html.RenderPartial("Task/NewTaskDetail", new NewTaskDetailViewModel(Model.NewTaskSchedule, Model.Projects, Model.TaskScopes, Model.TaskScheduleHours, Model.TaskScheduleMinutes, Model.PostActions, Model.DisabledPostTaskActions, Model.DefaultOnlyOnChange, maxDaysForWeeklyScheduledTasks: Model.MaxDaysForWeeklyScheduledTasks)); %>
                <% if (Model.NewTaskSchedule.SelectedTaskTypeId != -1)
                    { %>
                    <% if ((!String.IsNullOrEmpty(Model.NewTaskSchedule.HelpURL)) || (!String.IsNullOrEmpty(Model.NewTaskSchedule.ConfigHeader)))
                        { %>
                        <hr />
                    <% } %>
                    <div id="validation-error" class="validation-summary-error left-floating-panel" style="margin-bottom:15px;display:none;"></div>
                    <% if (!String.IsNullOrEmpty(Model.NewTaskSchedule.HelpURL))
                        { %>
                        <div class="right-floating-panel"><a href="<%= TaskHelper.GenerateTaskPluginHelpURL(((LicenseType)ViewData["LicenseType"]), Model.NewTaskSchedule.HelpURL) %>" target="_blank"><%= Html.Encode(Model.NewTaskSchedule.TaskTypeName)%> Help</a></div>
                    <% } %>
                    <div class="clear"></div>
                    <% if (!String.IsNullOrEmpty(Model.NewTaskSchedule.ConfigHeader))
                        { %>
                        <p><%= Html.Raw(Model.NewTaskSchedule.ConfigHeader) %></p>
                    <% } %>
                    <% if (AdministratorConsole.CustomTaskViewFactory.HasCustomView(Model.NewTaskSchedule.Name) && Model.NewTaskSchedule.TaskInputParameters.Count > 0) { %>
                        <% Html.RenderPartial(AdministratorConsole.CustomTaskViewFactory.GetCustomView(Model.NewTaskSchedule.Name), AdministratorConsole.CustomTaskViewFactory.GetCustomViewModel(Model.NewTaskSchedule)); %>
                    <%} else if ((Model.NewTaskSchedule.TaskInputParameters != null) && (Model.NewTaskSchedule.TaskInputParameters.Count > 0)) { %>
                        <% for (int i = 0; i < Model.NewTaskSchedule.TaskInputParameters.Count; i++)
                            { %>
                            <% Html.RenderPartial("Task/TaskScheduleInputParameter", new AdministratorConsole.Models.Shared.TaskController.TaskScheduleInputParameterViewModel() {
                                    TaskScheduleInputParameter = Model.NewTaskSchedule.TaskInputParameters[i],
                                    TaskScheduleParameters = Model.NewTaskSchedule.TaskScheduleParameters.ToList(),
                                    ParameterValue = Model.NewTaskSchedule.TaskInputParameters[i].ParameterDefault
                                }); %>
                        <% } %>
                        <div class="clear"></div>
                    <% } %>
                <% }
                    else
                    { %>
                    <hr />
                    <div id="super-task-sequence"></div>
                <% } %>
                <hr />
                <table class="standard-list full">
                    <tr>
                        <td><b>Notes</b></td>
                    </tr>
                    <tr>
                        <td><%= Html.TextArea("TaskNotes")%></td>
                    </tr>
                </table>
            <% } %>
        </div>
    </div>
    <script type="text/javascript">
        var allProjectTypes = {};
        <% foreach (Project project in Model.Projects) { %>
            <% if (ProjectTypeHelper.GetIsRevitServerProject(project.RevitServerVersion)) { %>
                allProjectTypes['<%= project.ExternalId %>'] = 'Revit';
            <% } else { %>
                allProjectTypes['<%= project.ExternalId %>'] = '<%= project.RevitServerVersion %>';
            <% } %>
        <% } %>

        function getProjectType()
        {
            if (allProjectTypes[$("#ProjectId").val()] != null) return allProjectTypes[$("#ProjectId").val()];
            else return "";
        } 

        <% if (Model.NewTaskSchedule.TaskInputParameters != null) { %>
            <% string currentParent = null; %>
        <% foreach (TaskScheduleInputParameter taskInputParameter in Model.NewTaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
            { %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Parent)) {  %>
                    <% TaskScheduleInputParameter parentParameter = Model.NewTaskSchedule.TaskInputParameters.SingleOrDefault(tip => tip.Name == taskInputParameter.Parent); %>

                    <% if (currentParent != taskInputParameter.Parent) { %>
                        <% if (currentParent != null) { %>});<% } %>
                        <% if ((parentParameter != null) && (String.IsNullOrEmpty(parentParameter.Autocomplete))) { %>
                            $("#<%= parentParameter.CleanedName %>").change(function(e) {
                        <% } else { %>
                            $("#<%= parentParameter.CleanedName %>_value").change(function(e) {
                        <% } %>
                        <% currentParent = parentParameter.Name; %>
                    <% } %>

                    <%= taskInputParameter.GenerateParentJavascriptIfCondition(parentParameter) %>
                <% } %>
            <% } %>
            <% if (currentParent != null) { %>});<% } %>
            <% foreach (TaskScheduleInputParameter taskInputParameter in Model.NewTaskSchedule.TaskInputParameters.OrderBy(tp => tp.Parent))
            { %>
                <% TaskScheduleInputParameter parentParameter = Model.NewTaskSchedule.TaskInputParameters.SingleOrDefault(tip => tip.Name == taskInputParameter.Parent); %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Parent)) {  %>
                    <%= taskInputParameter.GenerateParentJavascriptIfCondition(parentParameter) %>
                <% } %>
                <%= taskInputParameter.GenerateVisibilityIfCondition(ProjectTypeHelper.GetAllProjectTypeValues()) %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.ProjectType)) { %>
                    $("#ProjectId").change();
                <% } %>

                <% if (!String.IsNullOrEmpty(taskInputParameter.Scope)) {  %>
                    $("#Scope").change();
                <% } %>
            <% } %>
        <% } %>

        <% if (Model.NewTaskSchedule.SelectedTaskTypeId == -1) { %>
            function _getTaskSequence(scope) {
                $.ajax({
                    type: 'GET',
                    url: '<%= Url.Action("GetTaskSequence", "Task") %>',
                    data: {
                        source: "task",
                        projectId: $("#ProjectId").val(),
                        scope: scope
                    },
                    cache: false,
                    success: function (response) {
                        $('#super-task-sequence').empty();
                        $('#super-task-sequence').html(response);
                    }
                });
            }
                
            _getTaskSequence('<%= Model.TaskScopes.First() %>');

            $("#Scope").change(function() {
                _getTaskSequence($("#Scope option:selected").text());
            });

            $("#ProjectId").change(function() {
                _getTaskSequence($("#Scope option:selected").text());
            });
        <% } %>
    </script>
</asp:Content>
