{% load i18n %}
<script type="text/javascript">

  function permissionsString(form, type) {
    var anonymousPermissions, authenticatedPermissions, levels;
    if (typeof form === 'string'){
      form = $(form);
    }
    var data = form.serializeObject();

    if (type == "maps") {
      levels = {
          'readonly': 'map_readonly',
          'readwrite': 'map_readwrite',
          'admin': 'map_admin',
          'none': '_none'
      };
    } else if (type == "layers"){
      levels = {
          'admin': 'layer_admin',
          'readwrite': 'layer_readwrite',
          'readonly': 'layer_readonly',
          'none': '_none'
      };
    } else if (type == "documents"){
      levels = {
          'admin': 'document_admin',
          'readwrite': 'document_readwrite',
          'readonly': 'document_readonly',
          'none': '_none'
      };
    }

    if (data["viewmode"] === "ANYONE") {
      anonymousPermissions = levels['readonly'];
    } else {
      anonymousPermissions = levels['none'];
    }

    if (data["editmode"] === "REGISTERED") {
      authenticatedPermissions = levels['readwrite'];
    } else if (data["viewmode"] === 'REGISTERED') {
      authenticatedPermissions = levels['readonly'];
    } else {
      authenticatedPermissions = levels['none'];
    }

    var perUserPermissions = [];
    if (data["editmode"] === "LIST") {
      var editusers = form.find("input[name=editusers]").select2("val");
      if (editusers instanceof Array) {
        $.each(editusers, function(index, value) {
          perUserPermissions.push([value, levels["readwrite"]]);
        });
      } else {
        perUserPermissions.push([editusers, levels["readwrite"]]);
      }
    }

    var perGroupPermissions = [];
    {% if GROUPS_APP %}
    if (data["editmode"] === "LIST") {
      var editgroups = form.find("input[name=editgroups]").select2("val");
      if (editgroups instanceof Array) {
        $.each(editgroups, function(index, value) {
          perGroupPermissions.push([value, levels["readwrite"]]);
        });
      } else {
        perGroupPermissions.push([editgroups, levels["readwrite"]]);
      }
    }
    {% endif %}

    var manageusers = form.find("input[name=manageusers]").select2("val");
    if (manageusers) {
      if (manageusers instanceof Array) {
        $.each(manageusers, function(index, value) {
          perUserPermissions.push([value, levels["admin"]]);
        });
      } else {
        perUserPermissions.push([manageusers, levels["admin"]]);
      }
    }

    {% if GROUPS_APP %}
    var managegroups = form.find("input[name=managegroups]").select2("val");
    if (managegroups) {
      if (managegroups instanceof Array) {
        $.each(managegroups, function(index, value) {
          perGroupPermissions.push([value, levels["admin"]]);
        });
      } else {
        perGroupPermissions.push([managegroups, levels["admin"]]);
      }
    }
    {% endif %}

    return {
        anonymous: anonymousPermissions,
        authenticated: authenticatedPermissions,
        users: perUserPermissions,
        groups: perGroupPermissions
    };
  };

  $(function() {

    $('#permissions-body').ready(function(){
      {% if layer != "none" and document != "none" %}
      $.ajax(
        "{% if layer %}{% url "resource_permissions" 'layer' layer.id %}{% elif map %}{% url "resource_permissions" 'map' map.id %}{% elif document %}{% url "resource_permissions" 'document' document.id %}{% endif %}",
        {
          success: function(data){
            var perms = $.parseJSON($.parseJSON(data).permissions);
            if ("anonymous" in perms){
              $('#perms_view_anyone').attr("checked", "checked");
            }
            if ("authenticated" in perms){
              if (!("anonymous" in perms)){
                $('#perms_view_registered').attr("checked", "checked");
              }
              if (perms["authenticated"].split('_')[1] === 'readwrite'){
                $('#perms_edit_registered').attr("checked", "checked");
              }
            } else if (!("anonymous" in perms)){
              $('#perms_view_editors').attr("checked", "checked");
            }
            if (!("authenticated" in perms) || perms['authenticated'].split('_')[1] === 'readonly'){
              $('#perms_edit_list').attr("checked", "checked");
              var users = [];         
              for (var key in perms["users"]){
                users.push(key);
              }
              $("#perms_edit_editusers").val(users.join());
              {% if GROUPS_APP %}
              var groups = [];
              for (var key in perms["groups"]){
                groups.push(key);
              }
              $("#perms_edit_editgroups").val(groups.join());
              {% endif %}
            }
            var admins = [];
            for (var key in perms["users"]){
              if(perms["users"][key].split('_')[1] === 'admin'){
                admins.push(key);
              }
            }
            {% if GROUPS_APP %}
            var group_admins = [];
            for (var key in perms["groups"]){
              if(perms["groups"][key].split('_')[1] === 'admin'){
                group_admins.push(key);
              }
            }
            $("#perms_edit_managegroups").val(group_admins.join());
            addSelectGroups();
            {% endif %}
            $("#perms_edit_manageusers").val(admins.join());
            addSelectUsers();
          }
        }
      );
      {% else %}
      addSelectUsers();
      {% if GROUPS_APP %}
      addSelectGroups();
      {% endif %}
      {% endif %}
    });
    
    function addSelectUsers(){
      $("input.user-select").select2({
        placeholder: '{% trans "Choose one or more users..." %}',
        minimumInputLength: 1,
        multiple: true,
        width: 'element',
        ajax: {
          url: "{% url "account_ajax_lookup" %}",
          dataType: "json",
          type: "POST",
          data: function (term, page) {
            return {
              query: term,
            };
          },
          results: function (data, page) {
            return {results: data.users};
          }
        },
        id: userID,
        formatResult: userFormatResult,
        formatSelection: userFormatSelection,
        initSelection: function(element, callback) {
          var data = [];
          var val = element.val().split(",");
          $(element.val().split(",")).each(function (index,value) {
              data.push({username: value});
          });
          callback(data);
        }
      });
    }

    {% if GROUPS_APP %}
    function addSelectGroups(){
      $("input.group-select").select2({
        placeholder: '{% trans "Choose one or more groups..." %}',
        minimumInputLength: 1,
        multiple: true,
        width: 'element',
        ajax: {
          url: "{% url "account_ajax_lookup" %}",
          dataType: "json",
          type: "POST",
          data: function (term, page) {
            return {
              query: term,
            };
          },
          results: function (data, page) {
            return {results: data.groups};
          }
        },
        id: groupID,
        formatResult: groupFormatResult,
        formatSelection: groupFormatSelection,
        initSelection: function(element, callback) {
          var data = [];
          var val = element.val().split(",");
          $(element.val().split(",")).each(function (index,value) {
              data.push({name: value});
          });
          callback(data);
        }
      });
    }
    {% endif %}
    
    function userID(user) {
      return user.username;
    }

    {% if GROUPS_APP %}
    function groupID(group) {
      return group.name;
    }
    {% endif %} 

    function userFormatResult(user) {
      return user.username;
    }

    function userFormatSelection(user) {
        return user.username;
    }

    {% if GROUPS_APP %}
    function groupFormatResult(group) {
      return group.name;
    }

    function groupFormatSelection(group) {
        return group.name;
    }
    {% endif %}

    var toggle_buttons = function() {
      if ($("input.asset-selector:checked").length) {
        $(".asset-modifier").removeClass("disabled");
      } else {
        $(".asset-modifier").addClass("disabled");
      }
    };

    $("input.asset-selector").live("change", toggle_buttons);
    toggle_buttons();

    var perms_submit = function() {
      var form = $(this);
      var action = form.attr("action");

      var permissions = permissionsString(form, {% if layer %}'layers'{% elif map %}'maps'{% elif document %}'documents'{% endif %});
      $.ajax(
        {
          type: "POST",
          url: action,
          data: JSON.stringify(permissions),
          success: function(data) {
            $("#modal_perms").modal("hide");
          }
        }
      );
      return false;
    };

    $("#perms_submit").click(function(){
        $("#permission_form").submit();
    });
    {% if layer or map or document %}
    $("#permission_form").submit({% if layer or map or document %}perms_submit{% else %}batch_perms_submit{% endif %});
    {% endif %}
  });
</script>
