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

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <script src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Scripts/jquery-tokeninput/jquery.tokeninput.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var revitServerTypes = [];
        <% foreach (ProjectType projectType in ProjectTypeHelper.GetAllRevitProjectTypes()) { %>
            revitServerTypes.push("<%= projectType.Value %>");
        <% } %>

        function refreshPojectDetail() {
            loadProjectDetail($("#RevitServerVersion").val());
        }

        function loadImportModelsFromBrowseWindow() {
            if ($("#ProjectContents_import").is(":checked")) {
                $.ajax({
                    type: 'GET',
                    url: '<%= Url.Action("GetBrowseFolders", "Project") %>',
                    data: {
                        targetInput: "ImportModelsFrom",
                        workingDirectory: $("#ImportModelsFrom").val()
                    },
                    cache: false,
                    success: function (response) {
                        $("#modal-overlay").html(response);
                    },
                    complete: function () {
                        showModelDialog();
                    }
                });
            }
        }

        function loadProjectDetail(projectType) {
            $("#project-detail-container").empty();
            $("#project-detail-container").html("<br/><table><tr><td style='width:170px;'>&nbsp;</td><td><img src='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading.gif' title='Loading' /></td></tr></table><br/>");

            var projectDetailString = '<%= Url.Action("AddProjectDetail", "RevitServer") %>';
            var data = {
                revitServerVersion: projectType
            };
            if (revitServerTypes.indexOf(projectType) == -1) {
                projectDetailString = window.location.href.substring(0, window.location.href.indexOf("/Project/Add")) + "/" + projectType + "/AddProjectDetail";
                data = {};
            }

            $.ajax({
                type: 'GET',
                url: projectDetailString,
                data: data,
                cache: false,
                success: function (response) {
                    $('#project-detail-container').html(response);
                },
                error: function (response) {
                    $('#project-detail-container').html("<table><tr><td style='width:170px;'>&nbsp;</td><td><b>Error loading project details</b></td></tr></table>");
                },
            });
        }

        function checkImportAvailable() {
            if ($("#ProjectContents_import").is(":checked")) {
                $("#ImportModelsFrom").removeAttr("readonly");
            }
            else {
                $("#ImportModelsFrom").val("");
                $("#ImportModelsFrom").attr("readonly", "true");
            }
        }

        function validateAddForm() {
            $("#new-project-validation").empty();

            var cppRequiredFields = $('#project-parameters-container input.cpp_required').filter(function () { return $(this).val() == ""; }).length;

            if (cppRequiredFields > 0) {
                $("#new-project-validation").html("Project parameters marked with a * require a value");
                return;
            }

            if ($("#Name").val().length == 0) {
                $("#new-project-validation").html("Projects require a name");
                return;
            }

            if (validateAdditional()) {
                $("#project-tags").val("");

                var tags = $("#project-tags-select").tokenInput("get"),
                    tagString = "";

                for (var i = 0; i < tags.length; i++) {
                    tagString += tags[i].name.replace(/,/g, " ");
                    if (i != (tags.length - 1)) tagString += ",";
                }

                $("#project-tags").val(tagString);

                // Add the additional parameters required for each project type
                $("#AdditionalParameters").val(JSON.stringify(getAdditionalParameters()));

                $("#add-project-btn").hide();
                $("#add-project-loading").show();

                $("#add-project-form").submit();
            }
        }

        window.onload = function () {
            var nameInput = document.getElementById("Name");
            if (nameInput != null) nameInput.focus();

            $("#source-project").change(function () {
                var selectedProject = $(this).val();

                $("#copy-from-select-container").html("<br/><img src='<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading.gif' title='Loading' />");

                if (selectedProject != "-1") {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetProjectAttributes") %>',
                        data: {
                            projectId: selectedProject
                        },
                        cache: false,
                        success: function (response) {
                            $("#copy-from-select-container").html(response);
                        }
                    });
                }
                else $("#copy-from-select-container").empty();
            });

            $("#project-tags-select").tokenInput("<%= Url.Action("GetProjectTags", "Project") %>", {
                theme: "facebook",
                queryParam: "searchTerm",
                prePopulate: [],
                allowFreeTagging: true,
                tokenValue: "name"
            });

            $("#token-input-project-tags-select").keydown(function (e) {
                if ((e.keyCode === 220) || (e.keyCode === 191)) e.preventDefault();
            });

            <% if (Model.AvailableProjectTypes.Count() > 0) { %> loadProjectDetail('<%= Model.AvailableProjectTypes.First().Value %>');<% } %>
        };
    </script>
    <div id="content-wrap">
	    <div id="content" class="full">
	        <h1><%= TextHelper.GetText("New Project") %></h1>
            <div id="new-project-validation" class="validation-error-content"></div>
            <% if (!String.IsNullOrEmpty(Model.AddProjectMessage)) { %>
                    <div><%= Html.Raw(Model.AddProjectMessage) %></div>
                <% } %>
            <br />
            <% if (Model.AvailableProjectTypes.Length > 0) { %>
                <% using (Html.BeginForm("Insert", "Project", FormMethod.Post, new { id = "add-project-form" })) { %>
                    <input type="hidden" id="AdditionalParameters" name="AdditionalParameters" />
                    <table>
                        <tr>
                            <td align="left" style="width:170px;">Name:</td>
                            <td align="left"><%= Html.TextBox("Name", Model.NewProject.Name, new { @class = "standard-textbox"  })%></td>
                        </tr>
                        <tr>
                            <td align="left" style="width:170px;">Number:</td>
                            <td align="left"><%= Html.TextBox("Number", Model.NewProject.Number, new { @class = "standard-textbox"  })%></td>
                        </tr>
                        <tr>
                            <td align="left" style="width:170px;">Office:</td>
                            <!--<td align="left"><%= Html.TextBox("Office", Model.NewProject.Office, new { @class = "standard-textbox"  })%></td>-->
                            <td align="left"><%= Html.DropDownList("OfficeId", new SelectList(Model.AvailableOffices, "Id", "Name", Model.NewProject.OfficeId), new {  @class = "standard-textbox" })  %></td>
                        </tr>
                        <tr>
                            <td align="left" style="width:170px;">Address:</td>
                            <td align="left"><%= Html.TextBox("Location", Model.NewProject.Location, new { @class = "standard-textbox", @placeHolder = "Address, Town, State Zip" })%></td>
                        </tr>
                        <tr>
                            <td align="left" style="width:170px;">Tags:</td>
                            <td align="left"><input type="hidden" id="project-tags" name="ProjectTags" /><input type="text" id="project-tags-select" /></td>
                        </tr>
                        <tr>
                            <td align="left" style="width:170px;">Secured:</td>
                            <td align="left"><input type="checkbox" name="IsSecure" value="1" /></td>
                        </tr>
                        <% if (Model.AvailableProjectTypes != null) { %>
                            <tr>
                                <td align="left" style="width:170px;">Type:</td>
                                <td align="left"><%= Html.DropDownList("RevitServerVersion", new SelectList(Model.AvailableProjectTypes, "Value", "Name", Model.NewProject.RevitServerVersion), new { @onchange = "refreshPojectDetail();", @class = "standard-textbox" })%></td>
                            </tr>
                        <% } %>
                    </table>
                    <div id="project-detail-container"></div>

                    <%-- Project Parameters Stuff --%>
                    <% Html.RenderPartial("Partials/AddProjectParametersForm", Model.ProjectParameters); %>

                    <div id="copy-from-container">
                        <table>
                            <tr>
                                <td align="left" style="width:170px;">Copy From:</td>
                                <td>
                                    <select id="source-project" name="sourceProject">
                                        <option value="-1"> - None - </option>
                                        <% foreach (Project project in Model.AvailableProjects)
                                            { %>
                                            <option value="<%= project.ExternalId%>"><%= project.Name%></option>
                                        <% } %>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td align="left" style="width:170px;">&nbsp;</td>
                                <td id="copy-from-select-container"></td>
                            </tr>
                        </table>
                    </div>
                    <br />
                    <div id="add-project-container">
                        <div id="add-project-btn" class="right-floating-panel"><input type="button" value="<%= TextHelper.GetText("Create Project") %>" class="button" onclick="validateAddForm()" /></div>
                        <div id="add-project-loading" class="right-floating-panel" style="display:none;"><img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/loading-snake.gif" alt="Loading" /></div>
                        <div class="clear"></div>
                    </div>
                    <br />
                <% } %>
            <% } else { %>
                <div><%= TextHelper.GetText("Unable to add a project, no project types are available.") %></div>
            <% } %>
        </div>
    </div>
</asp:Content>
