<py:if test="True" xmlns:py="http://genshi.edgewall.org/"
  xmlns:xi="http://www.w3.org/2001/XInclude"
  py:strip="">

<py:if test="hasattr(c, 'package_create_slug_api_url')">
<script type="text/javascript">
//<![CDATA[
(function($){
    $.fn.ajaxCreateSlug = function(name, url) {
        var title = this;
        var updater = {
            init: function(title, name) {
                // Add a new element where the validity of the package name can be displayed
                this.name_field = name;
                this.title_field = title; 
                this.name_field.parent().append('<div id="package_name_valid_msg"></div>');
                this.title_field.blur(this.title_change_handler())
                this.title_field.keyup(this.title_change_handler())
                this.name_field.keyup(this.name_change_handler());
                this.name_field.blur(this.name_blur_handler());
                this.url = url;
            },
            title_change_handler: function() {
                var self = this;
                return function() {
                    if (!self.name_changed && self.title_field.val().replace(/^\s+|\s+$/g, '')) {
                        self.update(self.title_field.val(), function(data) {self.name_field.val(data.name)});
                    }
                }
            },
            name_blur_handler: function() {
                var self = this;
                return function() {
                    // Reset if the name is emptied
                    if (!self.name_field.val().replace(/^\s+|\s+$/g, '')){
                        self.name_changed = false;
                        $('#package_name_valid_msg').html('');
                    } else {
                        self.update(self.name_field.val(), function(data) {
                            self.name_field.val(data.name)
                        });
                    }
                };
            },
            name_change_handler: function() {
                var self = this;
                return function() {
                    // Reset if the name is emptied
                    if (!self.name_field.val().replace(/^\s+|\s+$/g, '')){
                        self.name_changed = false;
                        $('#package_name_valid_msg').html('');
                    } else {
                        self.name_changed = true;
                        self.update(self.name_field.val(), function(data) {
                            if (self.name_field.val().length >= data.name) {
                                self.name_field.val(data.name);
                            }
                        });
                    }
                };
            },
            // Keep a variable where we can store whether the name field has been
            // directly modified by the user or not. If it has, we should no longer
            // fetch updates.
            name_changed: false,

            // Create a function for fetching the value and updating the result
            perform_update: function(value, on_success){
                var self = this;
                $.ajax({
                    url: self.url,
                    data: 'title=' + value,
                    dataType: 'jsonp',
                    type: 'get',
                    jsonpCallback: 'callback',
                    success: function (data) {
                        if (on_success) {
                            on_success(data);
                        }
                        var valid_msg = $('#package_name_valid_msg');
                        if (data.valid) {
                            valid_msg.html('<span style="font-weight: bold; color: #0c0">This package name is available!</span>');
                        } else {
                            valid_msg.html('<span style="font-weight: bold; color: #c00">This package name is already used, please use a different name</span>');
                        } 
                    }
                });
            },
            // We only want to perform the update if there hasn't been a change for say 200ms
            timer: null,
            update: function(value, on_success) {
                var self = this;
                if (this.timer) {
                    clearTimeout(this.timer)
                };
                this.timer = setTimeout(function () {
                    self.perform_update(value, on_success)
                }, 200);
            }
        }
        updater.init(title, $(name), url);
        return title;
    };
})( jQuery );

$(document).ready(function() {
    $('#Package--title').ajaxCreateSlug('#Package--name', '${c.package_create_slug_api_url}');
});

//]]>
</script>
</py:if>


  <py:def function="form_fields(field_group)">
    <?python 
      fields = []
      for field in c.fieldset.render_fields.itervalues():
        if field.metadata.get('field_group', None) in (None, field_group):
          fields.append(field)
      need_labels = False
      for field in fields:
        if field.requires_label:
          need_labels = True
          break
    ?>
    <py:choose test="need_labels">
      <dl py:when="True">
        <py:for each="field in fields">
          <py:if test="field.metadata.get('field_group', None) in (None, field_group)">
            <py:if test="field.requires_label">
              <dt>
                <label class="${field.is_required() and 'field_req' or 'field_opt'}" for="${field.renderer.name}">
                  ${[field.label_text, c.fieldset.prettify(field.key)][int(field.label_text is None)]}
                </label>
              </dt>
            </py:if>
            <dd>
              ${h.literal(field.render())}
            </dd>
            <py:if test="field.metadata.has_key('basic_instructions') and not field.is_readonly()">
              <dd class="instructions basic">${field.metadata['basic_instructions']}</dd>
            </py:if>
            <py:if test="field.metadata.has_key('further_instructions') and not field.is_readonly()">
              <dd class="instructions further">${field.metadata['further_instructions']}</dd>
            </py:if>
            <py:if test="field.metadata.has_key('hints') and not field.is_readonly()">
              <dd class="hints">${field.metadata['hints']}</dd>
            </py:if>
            <dd py:for="error in field.errors" class="field_error">${_(error)}</dd>    

            <py:if test="c.fieldset.focus == field or c.fieldset.focus is True">
              <py:if test="not field.is_readonly()">
                <script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
    if (!$('#preview').length) {
        $("#${field.renderer.name}").focus();
    }
});
//]]>
                </script>
              </py:if>
            </py:if>
          </py:if>
        </py:for>
      </dl>
      <py:otherwise test="">
        <py:for each="field in fields">
          ${h.literal(field.render())}
        </py:for>
            <py:if test="field.metadata.has_key('basic_instructions')">
              <div class="instructions basic">${field.metadata['basic_instructions']}</div>
            </py:if>
            <py:if test="field.metadata.has_key('further_instructions')">
              <div class="instructions further">${field.metadata['further_instructions']}</div>
            </py:if>
            <py:if test="field.metadata.has_key('hints')">
              <div class="hints">${field.metadata['hints']}</div>
            </py:if>
            <div py:for="error in field.errors" class="field_error">${_(error)}</div>

            <py:if test="c.fieldset.focus == field or c.fieldset.focus is True">
              <py:if test="not field.is_readonly()">
                <script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
    $("#${field.renderer.name}").focus();
});
//]]>
                </script>
              </py:if>
            </py:if>
      </py:otherwise>
    </py:choose>
  </py:def>

</py:if>
