{% load i18n admin_modify admin_static %}

{% block extrahead %}
<style>
  h2.nested {
      background: none;
      background-color: #AA0;
      color: white;
      font-size: 11px;
      font-weight: bold;
      margin: 0;
      padding: 2px 5px 3px;
      text-align: left;
  }

  tr {
    background: none repeat scroll 0 0 #EDF3FE;
  }

  tr.nested {
    background: none repeat scroll 0 0 #FFE;
  }

  tr.nested-empty {
    display: none;
  }

</style>
{% endblock %}

<div class="inline-group" id="{{ inline_admin_formset.formset.prefix }}-group">
  <div class="tabular inline-related {% if forloop.last %}last-related{% endif %}">
{{ inline_admin_formset.formset.management_form }}
<fieldset class="module">
   <h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2>
   {{ inline_admin_formset.formset.non_form_errors }}
   <table>
     <thead><tr>
     {% for field in inline_admin_formset.fields %}
       {% if not field.widget.is_hidden %}
         <th{% if forloop.first %} colspan="2"{% endif %}{% if field.required %} class="required"{% endif %}>{{ field.label|capfirst }}</th>
       {% endif %}
     {% endfor %}
     {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %}
      
     </tr></thead>

     <tbody>
     {% for inline_admin_form in inline_admin_formset %}
        {% if inline_admin_form.form.non_field_errors %}
        <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
        {% endif %}
        <tr class="{% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last %} empty-form{% endif %}"
             id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
        <td class="original">
          {% if inline_admin_form.original or inline_admin_form.show_url %}<p>
          {% if inline_admin_form.original %} {{ inline_admin_form.original }}{% endif %}
          {% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %}
            </p>{% endif %}
          {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
          {{ inline_admin_form.fk_field.field }}
          {% spaceless %}
          {% for fieldset in inline_admin_form %}
            {% for line in fieldset %}
              {% for field in line %}
                {% if field.is_hidden %} {{ field.field }} {% endif %}
              {% endfor %}
            {% endfor %}
          {% endfor %}
          {% endspaceless %}
        </td>
        {% for fieldset in inline_admin_form %}
          {% for line in fieldset %}
            {% for field in line %}
              <td class="{{ field.field.name }}">
              {% if field.is_readonly %}
                  <p>{{ field.contents }}</p>
              {% else %}
                  {{ field.field.errors.as_ul }}
                  {{ field.field }}
              {% endif %}
              </td>
            {% endfor %}
          {% endfor %}
        {% endfor %}
        {% if inline_admin_formset.formset.can_delete %}
          <td class="delete">{% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }}{% endif %}</td>
        {% endif %}
        </tr>
        {% if inline_admin_formset.inlines %} 
                {% for nested in inline_admin_form.form.inlines %} 
                {% if forloop.first %}
                <tr class="nested">
                  <td colspan="{{ inline_admin_form.field_count }}">
                {% endif %}
                    {% include 'common/admin/nested.html' %} 
                {% if forloop.last %}
                </td>
                {% endif %}
                {% endfor %} 
        </tr>
        {% endif %}
     {% endfor %}
     </tbody>
   </table>
</fieldset>
  </div>
</div>

<script type="text/javascript">

/**
 * Django admin inlines
 *
 * Based on jQuery Formset 1.1
 * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
 * @requires jQuery 1.2.6 or later
 *
 * Copyright (c) 2009, Stanislaus Madueke
 * All rights reserved.
 *
 * Spiced up with Code from Zain Memon's GSoC project 2009
 * and modified for Django by Jannis Leidel
 *
 * Licensed under the New BSD License
 * See: http://www.opensource.org/licenses/bsd-license.php
 */
(function($) {
  $.fn.formset = function(opts) {
    var options = $.extend({}, $.fn.formset.defaults, opts);
    var updateElementIndex = function(el, prefix, ndx) {
      var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
      var replacement = prefix + "-" + ndx;
      if ($(el).attr("for")) {
        $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
      }
      if (el.id) {
        el.id = el.id.replace(id_regex, replacement);
      }
      if (el.name) {
        el.name = el.name.replace(id_regex, replacement);
      }
    };
    var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").attr("autocomplete", "off");
    var nextIndex = parseInt(totalForms.val());
    var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off");
    // only show the add button if we are allowed to add more items,
        // note that max_num = None translates to a blank string.
    var showAddButton = maxForms.val() == '' || (maxForms.val()-totalForms.val()) > 0;
    $(this).each(function(i) {
      $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
    });
    if ($(this).length && showAddButton) {
      var addButton;
      var addNestedButton;
      if (($(this).attr("tagName") == "TR")) {
        // If forms are laid out as table rows, insert the
        // "add" button in a new table row:
          var numCols = this.eq(0).children().length;
          $(this).parent().append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="javascript:void(0)">' + options.addText + "</a></tr>");
          addButton = $(this).parent().find("tr:last a");
      } else {
        // Otherwise, insert it immediately after the last form:
        $(this).filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>");
        addButton = $(this).filter(":last").next().find("a");
      }

      addButton.click(function() {
        var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS");
        var template = $("#" + options.prefix + "-empty");
        var row = template.clone(true);
        row.removeClass(options.emptyCssClass)
            .addClass(options.formCssClass)
            .attr("id", options.prefix + "-" + nextIndex);
        if (row.is("tr")) {
          // If the forms are laid out in table rows, insert
          // the remove button into the last table cell:
          row.children(":last").append('<div><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></div>");
        } else if (row.is("ul") || row.is("ol")) {
          // If they're laid out as an ordered/unordered list,
          // insert an <li> after the last list item:
          row.append('<li><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></li>");
        } else {
          // Otherwise, just insert the remove button as the
          // last child element of the form's container:
          row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></span>");
        }
        row.find("*").each(function() {
          updateElementIndex(this, options.prefix, totalForms.val());
        });
        // Insert the new form when it has been fully edited
        row.insertBefore($(this).parent().parent());
        // Update number of total forms
        $(totalForms).val(parseInt(totalForms.val()) + 1);
        nextIndex += 1;
        // Hide add button in case we've hit the max, except we want to add infinitely
        if ((maxForms.val() != '') && (maxForms.val()-totalForms.val()) <= 0) {
          addButton.parent().hide();
        }

        // The delete button of each row triggers a bunch of other things
        row.find("a." + options.deleteCssClass).click(function() {
          // Remove the parent form containing this button:
          var row = $(this).parents("." + options.formCssClass);
          row.remove();
          nextIndex -= 1;
          // If a post-delete callback was provided, call it with the deleted form:
          if (options.removed) {
            options.removed(row);
          }
          // Update the TOTAL_FORMS form count.
          var forms = $("." + options.formCssClass);
          $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
          // Show add button again once we drop below max
          if ((maxForms.val() == '') || (maxForms.val()-forms.length) > 0) {
            addButton.parent().show();
          }
          // Also, update names and ids for all remaining form controls
          // so they remain in sequence:
          for (var i=0, formCount=forms.length; i<formCount; i++)
          {
            updateElementIndex($(forms).get(i), options.prefix, i);
            $(forms.get(i)).find("*").each(function() {
              updateElementIndex(this, options.prefix, i);
            });
          }
          return false;
        });

        // START OF ADDING NESTED

        var empty = $('.nested')[0];
        var new_items = $(empty).clone().insertBefore($(this).parent().parent());

        var updateNestedElementParentIndex = function(el, prefix, ndx) {
          if ($(el).attr("for")) {
            $(el).attr("for", $(el).attr("for").replace(prefix + '-0', prefix + '-' + ndx));
          }
          if (el.id) {
            el.id = el.id.replace(prefix + '-0', prefix + '-' + ndx)
          }
          if (el.name) {
            el.name = el.name.replace(prefix + '-0', prefix + '-' + ndx)
          }
        };
        
        new_items.find("*").each(function() {
          updateNestedElementParentIndex(this, "{{ inline_admin_formset.formset.prefix }}", nextIndex-1);
        });

        

        // END OF ADDING NESTED

        // If a post-add callback was supplied, call it with the added form:
        if (options.added) {
          options.added(row);
        }
        return false;
      });
    }
    return this;
  }

  $.fn.formset_nested = function(opts) {
    var options = $.extend({}, $.fn.formset_nested.defaults, opts);
    var updateElementIndex = function(el, prefix, ndx) {
      if ($(el).attr("for")) {
        $(el).attr("for", $(el).attr("for").replace('__prefix__', ndx));
      }
      if (el.id) {
        el.id = el.id.replace('__prefix__', ndx);
      }
      if (el.name) {
        el.name = el.name.replace('__prefix__', ndx);
      }
    };
    var reorderElementIndex = function(el, base, ndx) {

      if ($(el).attr("for")) {
        var string = $(el).attr("for");
      }
      if (el.id) {
        var string = el.id;
      }
      if (el.name) {
        var string = el.name;
      }

      if(string){
        var last = string.lastIndexOf('-');
        var substring = string.substring(0, last);
        var postfix = string.substring(last, string.length);
        var prefix = substring.substring(0, substring.lastIndexOf('-')+1);
        var new_string = prefix + ndx + postfix;
      }

      if ($(el).attr("for")) {
        $(el).attr("for", new_string);
      }
      if (el.id) {
        el.id = new_string;
      }
      if (el.name) {
        el.name = new_string;
      }
      
    };
    var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").attr("autocomplete", "off");
    var nextIndex = parseInt(totalForms.val());
    var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off");
    // only show the add button if we are allowed to add more items,
        // note that max_num = None translates to a blank string.
    var showAddButton = maxForms.val() == '' || (maxForms.val()-totalForms.val()) > 0;
    $(this).each(function(i) {
      $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
    });
    if ($(this).length && showAddButton) {
      var addButton;
      var addNestedButton;
      if (($(this).attr("tagName") == "TR")) {
        // If forms are laid out as table rows, insert the
        // "add" button in a new table row:
          $(this).parent().parent().parent().filter('td').append('<a href="javascript:void(0)">' + options.addText + "</a>");
          addNestedButton = $(this).parent().parent().parent().find("a");
      } else {
        // Otherwise, insert it immediately after the last form:
        //$(this).filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>");
        //addButton = $(this).filter(":last").next().find("a");
      }

      addNestedButton.click(function() {
        // id_scenariocondition_set-TOTAL_FORMS
        // id_scenariocondition_set-0-scenarioconditionscore_set-TOTAL_FORMS
        totalForms = $(this).parent().find('input[name*="TOTAL_FORMS"]');
        nextIndex = parseInt(totalForms.val());//$("#id_" + options.prefix + "-TOTAL_FORMS");
        var template = $(this).prev().find("tr.nested-empty");
        var row = template.clone(true);
        row.removeClass(options.emptyCssClass)
            .addClass(options.formCssClass);
        if (row.is("tr")) {
          // If the forms are laid out in table rows, insert
          // the remove button into the last table cell:
          row.append('<td><div><a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + "</a></div></td>");
        }

        row.find("*").each(function() {
          updateElementIndex(this, options.prefix, nextIndex);
        });

        // Insert the new form when it has been fully edited
        row.insertBefore($(template));
        // Update number of total forms
        $(totalForms).val(parseInt(totalForms.val()) + 1);
        nextIndex += 1;
        // Hide add button in case we've hit the max, except we want to add infinitely
        if ((maxForms.val() != '') && (maxForms.val()-totalForms.val()) <= 0) {
          addButton.parent().hide();
        }

        // The delete button of each row triggers a bunch of other things
        row.find("a." + options.deleteCssClass).click(function() {
          // Remove the parent form containing this button:
          var row = $(this).parent().parent().parent();
          totalForms = $(row).parent().parent().parent().find('input[name*="TOTAL_FORMS"]');
          nextIndex = parseInt(totalForms.val()-1);//$("#id_" + options.prefix + "-TOTAL_FORMS");
          row.remove();
          
          // Update the TOTAL_FORMS form count.
          $(totalForms).val(nextIndex);

          // Show add button again once we drop below max
          if ((maxForms.val() == '') || (maxForms.val()-forms.length) > 0) {
            addNestedButton.parent().show();
          }
          
          // Also, update names and ids for all remaining form controls
          // so they remain in sequence:
          $.each($(totalForms).parent().find('tbody tr').not('.nested-empty'), function(index, value) { 
            $(value).find("*").each(function() {
              reorderElementIndex(this, options.prefix, index);
            });
          });
          //for (var i=0; i<nextIndex; i++)
          //{
          //  updateElementIndex($(forms).get(i), options.prefix, i);
          //}
          return false;
        });
        // If a post-add callback was supplied, call it with the added form:
        if (options.added) {
          options.added(row);
        }
        return false;
      });
    }
    return this;
  }
  /* Setup plugin defaults */
  $.fn.formset.defaults = {
    prefix: "form",         // The form prefix for your django formset
    addText: "add another",     // Text for the add link
    deleteText: "remove",     // Text for the delete link
    addCssClass: "add-row",     // CSS class applied to the add link
    deleteCssClass: "delete-row", // CSS class applied to the delete link
    emptyCssClass: "empty-row",   // CSS class applied to the empty row
    formCssClass: "dynamic-form", // CSS class applied to each form in a formset
    added: null,          // Function called each time a new form is added
    removed: null,
    nested: false         // Function called each time a form is deleted
  }

  /* Setup nested plugin defaults */
  $.fn.formset_nested.defaults = {
    prefix: "form",         // The form prefix for your django formset
    addText: "add another",     // Text for the add link
    deleteText: "remove",     // Text for the delete link
    addCssClass: "add-row",     // CSS class applied to the add link
    deleteCssClass: "delete-row", // CSS class applied to the delete link
    emptyCssClass: "empty-row",   // CSS class applied to the empty row
    formCssClass: "dynamic-form", // CSS class applied to each form in a formset
    added: null,          // Function called each time a new form is added
    removed: null,
    nested: true         // Function called each time a form is deleted
  }

})(django.jQuery);



(function($) {
    $(document).ready(function($) {
        var rows = "#{{ inline_admin_formset.formset.prefix }}-group .tabular.inline-related tbody tr";
        var rows_nested = "#{{ inline_admin_formset.formset.prefix }}-group .tabular.inline-related tbody tr.nested";
        
        var alternatingRows = function(row) {
            $(rows).not(".add-row").removeClass("row1 row2")
                .filter(":even").addClass("row1").end()
                .filter(rows + ":odd").addClass("row2");
        }
        var reinitDateTimeShortCuts = function() {
            // Reinitialize the calendar and clock widgets by force
            if (typeof DateTimeShortcuts != "undefined") {
                $(".datetimeshortcuts").remove();
                DateTimeShortcuts.init();
            }
        }
        var updateSelectFilter = function() {
            // If any SelectFilter widgets are a part of the new form,
            // instantiate a new SelectFilter instance for it.
            if (typeof SelectFilter != "undefined"){
                $(".selectfilter").each(function(index, value){
                  var namearr = value.name.split('-');
                  SelectFilter.init(value.id, namearr[namearr.length-1], false, '{% static "admin" %}');
                });
                $(".selectfilterstacked").each(function(index, value){
                  var namearr = value.name.split('-');
                  SelectFilter.init(value.id, namearr[namearr.length-1], true, '{% static "admin" %}');
                });
            }
        }
        var initPrepopulatedFields = function(row) {
            row.find('.prepopulated_field').each(function() {
                var field = $(this);
                var input = field.find('input, select, textarea');
                var dependency_list = input.data('dependency_list') || [];
                var dependencies = [];
                $.each(dependency_list, function(i, field_name) {
                  dependencies.push('#' + row.find(field_name).find('input, select, textarea').attr('id'));
                });
                if (dependencies.length) {
                    input.prepopulate(dependencies, input.attr('maxlength'));
                }
            });
        }
        $(rows).not("tr.nested").formset({
            prefix: "{{ inline_admin_formset.formset.prefix }}",
            addText: "{% blocktrans with inline_admin_formset.opts.verbose_name|title as verbose_name %}Add another {{ verbose_name }}{% endblocktrans %}",
            formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
            deleteCssClass: "inline-deletelink",
            deleteText: "{% trans "Remove" %}",
            emptyCssClass: "empty-form",
            removed: alternatingRows,
            added: (function(row) {
                initPrepopulatedFields(row);
                reinitDateTimeShortCuts();
                updateSelectFilter();
            })
        });
        $(rows_nested).formset_nested({
            prefix: "{{ inline_admin_formset.formset.prefix }}",
            addText: "Add nested entry",
            formCssClass: "dynamic-{{ inline_admin_formset.formset.prefix }}",
            deleteCssClass: "inline-deletelink",
            deleteText: "{% trans "Remove" %}",
            emptyCssClass: "nested-empty",
            removed: alternatingRows,
            added: (function(row) {
                initPrepopulatedFields(row);
                reinitDateTimeShortCuts();
                updateSelectFilter();
            })
        });
    });
})(django.jQuery);
</script>
