{#
    Copyright (c) 2015 Chintalagiri Shashank
    Released under the MIT license
#}

{% extends "base_templates/base.html" %}
{% import "parts/forms.html" as forms %}
{% block main %}

<p></p>

<h4>{{ pagetitle }}</h4>

<div class="row">
    <form method="POST">
    {{ form.hidden_tag() }}
    <div class="row" data-equalizer="fmain">
        <div class="small-12 large-5 columns" data-equalizer-watch="fmain">
            <fieldset>
                <legend>
                    Metadata
                </legend>
                <div class="row">
                    <div class="small-9 columns">
                        {{ forms.render_field(form.user, list="json-userlist", autocomplete="off") }}
                    </div>
                    <div class="small-3 columns">
                        {{ forms.render_field(form.rdate) }}
                    </div>
                </div>
                <div class="row">
                    <div class="small-12 columns">
                        {{ forms.render_field(form.indent_title, length="50") }}
                    </div>
                </div>
                <div class="row">
                    {{ form.indent_sno.hidden_tag() }}
                    <div class="small-4 columns text-center">
                        {{ forms.render_compact_switch(form.indent_sno.sno_generate, checked=True) }}
                    </div>
                    <div class="small-8 columns">
                        {{ forms.render_field(form.indent_sno.sno, autocomplete="off", readonly=True) }}
                    </div>
                </div>
                <div class="row">
                    <div class="small-12 large-6 columns">
                        {{ forms.render_field(form.indent_type) }}
                    </div>
                    <div class="small-12 large-6 columns">
                        {{ forms.render_field(form.parent_indent_sno) }}
                    </div>
                    <div class="small-12 large-6 columns">
                        {{ forms.render_field(form.prod_order_sno, autocomplete="off", list="json-prodordlist", placeholder="Specific Production Order") }}
                    </div>
                    <div class="small-12 large-6 columns">
                        {{ forms.render_field(form.root_order_sno, autocomplete="off", list="json-rootordlist", placeholder="Top-level order or project code") }}
                    </div>
                    {% if stage.auth_not_valid %}
                    <div {% if stage.auth_not_valid %}class="small-12 columns error"{% endif %}>
                        <small class="error">Unable to Validate Authorization Chain.</small>
                    </div>
                    {% endif %}
                </div>
                <div class="row">
                    <div class="small-12 columns">
                            {{ forms.render_field(form.indent_desc) }}
                    </div>
                </div>
            </fieldset>
        </div>
        <div class="small-12 large-7 columns" data-equalizer-watch="fmain">
            <fieldset id="component-rows">
                <legend>
                    Components
                </legend>
                <!-- COBOM Input Starts -->
                {% for component in form.components %}
                <div class="row component-row">
                    {{ component.hidden_tag() }}
                    <div class="small-8 columns">
                        {{ forms.render_clean_field(component.ident, list="json-identlist", autocomplete="off") }}
                    </div>
                    <div class="small-3 columns">
                        <div class="row collapse postfix-radius">
                            <div class="small-6 columns">
                                {{ forms.render_clean_field(component.qty, autocomplete="off") }}
                            </div>
                            <div class="small-6 columns">
                                <span class="postfix avail-qty"></span>
                            </div>
                        </div>
                    </div>
                    <div class="small-1 columns">
                        <a>
                            <div class="alert" id="delete-row[]">
                                <i class='fi-x'></i>
                            </div>
                        </a>
                    </div>
                </div>
                {% endfor %}
                <a>
                    <div class="button success small expand radius" id="add-row">
                        Add Row
                    </div>
                </a>
                <!-- COBOM Input Ends -->
            </fieldset>
        </div>
    </div>
    <div class="small-12 large-4 columns">
        <!--<input type="submit" class="button small expand radius" value="Check Auth Chain" disabled>-->
    </div>
    <div class="small-12 large-4 columns">
        <!--<input type="submit" class="button small expand radius" value="Check Availability">-->
    </div>
    <div class="small-12 large-4 columns">
        <input type="submit" class="button alert small expand radius" value="Create Indent">
    </div>
    </form>
</div>

<script>
    $(document).ready( function () {

        <!-- Ident List Starts -->

        // Load in the library information
        var dataList = document.getElementById('json-identlist');
        var request = new XMLHttpRequest();

        // Handle state changes for the request.
        request.onreadystatechange = function(response) {
          if (request.readyState === 4) {
            if (request.status === 200) {
              // Parse the JSON
              var jsonOptions = JSON.parse(request.responseText);

              // Loop over the JSON array.
              jsonOptions.idents.forEach(function(item) {
                // Create a new <option> element.
                var option = document.createElement('option');
                // Set the value using the item in the JSON array.
                option.value = item;
                // Add the <option> element to the <datalist>.
                dataList.appendChild(option);
              });
            }
          }
        };

        request.open('GET', '/gsymlib/idents.json', true);
        request.send();

        <!-- Ident List Ends -->

        <!-- User List Starts -->

        // Load in the library information
        var userDataList = document.getElementById('json-userlist');
        var userRequest = new XMLHttpRequest();

        // Handle state changes for the request.
        userRequest.onreadystatechange = function(response) {
          if (userRequest.readyState === 4) {
            if (userRequest.status === 200) {
              // Parse the JSON
              var jsonOptions = JSON.parse(userRequest.responseText);

              // Loop over the JSON array.
              jsonOptions.users.forEach(function(item) {
                // Create a new <option> element.
                var option = document.createElement('option');
                // Set the value using the item in the JSON array.
                option.value = item;
                // Add the <option> element to the <datalist>.
                userDataList.appendChild(option);
              });
            }
          }
        };

        userRequest.open('GET', '/user/all.json', true);
        userRequest.send();

        <!-- User List Ends -->

        <!-- ProdOrd List Starts -->

        // Load in the library information
        var prodDataList = document.getElementById('json-prodordlist');
        var prodRequest = new XMLHttpRequest();

        // Handle state changes for the request.
        prodRequest.onreadystatechange = function(response) {
          if (prodRequest.readyState === 4) {
            if (prodRequest.status === 200) {
              // Parse the JSON
              var jsonOptions = JSON.parse(prodRequest.responseText);

              // Loop over the JSON array.
              jsonOptions.snos.forEach(function(item) {
                // Create a new <option> element.
                var option = document.createElement('option');
                // Set the value using the item in the JSON array.
                option.value = item.sno;
                <!--option.label = item.title;-->
                // Add the <option> element to the <datalist>.
                prodDataList.appendChild(option);
              });
            }
          }
        };

        prodRequest.open('GET', '/production/orders.json', true);
        prodRequest.send();

        <!-- ProdOrd List Ends -->

        <!-- COBOM Input Starts -->

        $('#add-row').click(function() {
            lastrow = $( this ).closest('#component-rows').find('.component-row').last();
            row = lastrow.clone();
            elem_id = row.find(":input")[0].id;
            elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
            row.find(":input").each(function() {
                console.log(this);
                var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
                $(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
            });
            lastrow.after(row);
            $(document).foundation('abide', 'reflow');
            $(document).foundation('reflow');
        });

        $("#component-rows").on("click", ".component-row #delete-row\\[\\]", function(){
            nrows = $( this ).closest('#component-rows').find('.component-row').length;
            if (nrows > 1){
                $( this ).closest('.component-row').remove();
                $(document).foundation('abide', 'reflow');
                $(document).foundation('reflow');
            }
        });
        $("#component-rows").on("focusout", ".component-row input[name$='ident']", function(){
            var ctx = this;
            $.ajax({
                 type: "POST",
                 url: "/inventory/location/status.json",
                 contentType: "application/json; charset=utf-8",
                 async: true,
                 data: JSON.stringify({ident: $( this ).val()}),
                 dataType: "json",
                 success: function(data){
                    $( ctx ).closest('.component-row').find('span').text(data.qty);
                 }
            });
        });

        <!-- COBOM Input Ends -->

        <!-- Serial No Form Elements -->
        var indent_sno = $("#indent_sno-sno")[0].value
        $("#indent_sno-sno_generate").change(function(event) {
            var checkbox = event.target;
            if (checkbox.checked) {
                $("#indent_sno-sno")[0].value = indent_sno;
                $("#indent_sno-sno")[0].readOnly = true;
            } else {
                $("#indent_sno-sno")[0].readOnly = false;
            }
        });

        <!-- Date picker elements -->
        $('#rdate').fdatepicker({
            format: 'dd/mm/yyyy',
        });
    });
</script>

<datalist id="json-identlist"></datalist>
<datalist id="json-userlist"></datalist>
<datalist id="json-prodordlist"></datalist>
{% endblock %}
