{% extends "forms.html" %}
{% load forms %}
{% load applications %}


{% block title %}Step 4: Project Details{% endblock %}


{% block breadcrumbs %}
<div class="breadcrumbs">
    <a href='{% url "index" %}'>Home</a>&nbsp;›
    <a href="{% url 'kg_application_list' %}">Applications</a>&nbsp;›
    {{ application }}&nbsp;›
    Step 4: Project Details
</div>
{% endblock %}


{% block content %}
<div class="module">
    <h2>4. Project details</h2>

    <form method="post" action="." novalidate>{% csrf_token %}
        <div>
            <h3>Common</h3>
            {% form_as_div forms.common %}
        </div>

        <div class="hidden" id="form_new">
            <h3>New project details</h3>
            {% form_as_div forms.new %}
        </div>

        <div class="hidden" id="form_existing">
            <h3>Existing project details</h3>

            <input type="hidden" id="id_project" name="project" value="">

            <div class="form-row">
                <label for="id_terms">Project Leader/Project ID:</label>
                <input type="text" name="terms" id="id_terms" />
            </div>

            <div id="error_list">
                {% if forms.existing.project.errors %}
                <ul class="errorlist">
                    <li>No project selected.</li>
                </ul>
                {% endif %}
            </div>

            <div id="project_list">
            </div>

            <div id="selected_project">
            </div>

            <div>
                {% if application.make_leader %}
                <p>Request to become project leader.</p>
                {% else %}
                <p>Request to become ordinary member of project.</p>
                {% endif %}
            </div>
        </div>

        {% application_actions %}
    </form>
</div>

<script>
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.jCookie("csrftoken"));
        }
    }
});

$(document).ready(function(){
    // select dialog type

    function setup_existing() {
        $("#form_new").addClass("hidden");
        $("#form_existing").removeClass("hidden")
    }

    function setup_new() {
        $("#form_new").removeClass("hidden");
        $("#form_existing").addClass("hidden")
    }

    var t0_node = $("#id_application_type_0");
    var t1_node = $("#id_application_type_1");

    t0_node.change(function() {
        setup_existing()
    });
    t1_node.change(function() {
        setup_new()
    });

    var t0 = t0_node.prop('checked');
    var t1 = t1_node.prop('checked');
    {% if project %}
    select_project("{{project.pk}}", "{{project}}");
    {% endif %}
    if (t0) {
        setup_existing()
    }
    else if (t1) {
        setup_new()
    }

    // select existing project

    $("#id_terms").autocomplete({
        source:
            autocomplete_source,
        select:
            function( event, ui ) {
                if (ui.item) {
                    select_item(ui.item);
                }
            }
    });

    function autocomplete_source(request, response) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            cache: true,
            data:
                {
                    terms: request.term,
                    ajax: true
                },
            success:
                function(data) {
                    var node = $("#error_list").empty();
                    if (data.error) {
                        var list = $("<ul class='errorlist'></ul>").appendTo(node);
                        $("<li></li>")
                            .text(data.error)
                            .appendTo(list);
                        return
                    }

                    var projects = $.map( data.project_list, function( item ) {
                        return {
                            pk: item[0],
                            label: item[1],
                            value: item[1],
                            type: "project"
                        }
                    });

                    var leaders = $.map( data.leader_list, function( item ) {
                        return {
                            pk: item[0],
                            label: item[1],
                            value: item[1],
                            type: "leader"
                        }
                    });

                    var results = [].concat(projects, leaders);
                    response(results);
                },
            error:
                function(jqXHR, textStatus, errorThrown) {
                    alert(errorThrown)
                }
        });
    }

    function select_item(item) {
        var name = item.label;
        var pk = item.pk;

        if (item.type == "leader") {
            select_leader(pk, name)
        } else if (item.type == "project") {
            $("#project_list").empty();
            select_project(pk, name)
        }

    }

    function select_leader(leader_pk, leader_name) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            cache: true,
            data:
                {
                    leader: leader_pk,
                    terms: $("#id_terms").val(),
                    ajax: true
                },
            success:
                function(data, textStatus, jqXHR) {
                    void textStatus;
                    void jqXHR;
                    fill_projects(data, "Projects for leader "+leader_name)
                },
            error:
                function(jqXHR, textStatus, errorThrown) {
                    alert(errorThrown)
                }
        })
    }

    function select_project(pk, name) {
        $("#id_project").val(pk);
        $("#selected_project").html($("<p></p>")
            .addClass("selected")
            .text("Selected project: " +name))
    }


    function fill_projects(data, project_list_text) {
        var el_node = $("#error_list").empty();
        if (data.error) {
            var el_list = $("<ul class='errorlist'></ul>").appendTo(el_node);
            $("<li></li>")
                .text(data.error)
                .appendTo(el_list)
        }

        if (data.project_list != null) {
            var pl_node = $("#project_list").empty();
            var pl_list = null;
            if (data.project_list.length > 0) {
                $("<p></p>")
                    .text(project_list_text)
                    .appendTo(pl_node);
                pl_list = $("<ul></ul>")
                    .appendTo(pl_node)
            }
            for (var i=0; i<data.project_list.length; ++i) {
                var input = $("<input type='radio'></input>")
                    .attr("id", "id_project")
                    .attr("name", "tmp_project")
                    .attr("value", data.project_list[i][0])
                    .data("name", data.project_list[i][1])
                    .change(function(ev) {
                        void ev;
                        var project_name = $(this).data("name");
                        var project_pk = $(this).val();
                        select_project(project_pk, project_name);
                    });

                $("<li></li>")
                    .append(input)
                    .append($("<span></span>")
                        .text(data.project_list[i][1]))
                    .appendTo(pl_list)
            }
        }
    }

});
</script>
{% endblock %}
