{% if slice_id %}

<a href="/admin/core/instance/add/?_to_field=id&slice={{ slice_id }}" id="add_instance_advanced"
onclick="return addInstanceClicked(this);">
Add Instance
</a>
<input type="hidden" id="instance_advanced" name="instance_advanced" onchange="console.log('changed');" value="initial">

<script>

// ugly - poll for django to change "instance_advanced", and it it does, then refresh the
// page so the instance list gets updated.
var last_instance_advanced = $("#instance_advanced").val();
checkInstanceAdvanced = function() {
    cur = $("#instance_advanced").val();
    if (cur != last_instance_advanced) {
        last_instance_advanced = cur;
        location.reload();
   }
};

setInterval(function() { checkInstanceAdvanced(); }, 1000);

function showAddInstancePopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    var href = triggeringLink.href;
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=1080,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

function formIsDirty(form) {
  console.log(form);
  for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == "checkbox" || type == "radio") {
      if (element.checked != element.defaultChecked) {
        return true;
      }
    }
    else if (type == "hidden" || type == "password" ||
             type == "text" || type == "textarea") {
      if (element.value != element.defaultValue) {
        return true;
      }
    }
    else if (type == "select-one" || type == "select-multiple") {
      for (var j = 0; j < element.options.length; j++) {
        if (element.options[j].selected !=
            element.options[j].defaultSelected) {
          return true;
        }
      }
    }
  }
  return false;
}

function addInstanceClicked(link) {
    if (formIsDirty($("#slice_form")[0])) {
        console.log("dirty!!");
        alert("Slice has modified fields. Please save the slice before adding instances.");
        return false;
    } else {
        return showAddInstancePopup(link);
    }
}

</script>

{% else %}

Please save this slice before adding Instances.

{% endif %}
