{% macro format_checkbox(admin, right, name, users, type) %}
    {% set id = right['base_id'] %}
    {% set class = 'base_id' %}
    {% if type == 'sbas' %}
      {% set id = right['sbas_id'] %}
      {% set class = 'sbas_id' %}
      {% set sbas_class = "" %}
    {% else %}
      {% set sbas_class = "inside_sbas_" ~ right['sbas_id'] %}
    {% endif %}

    {% set display = 'block' %}

    {% if right[name] != users|length and name != constant('\\ACL::ACCESS') and right[constant('\\ACL::ACCESS')] != users|length and type != 'sbas' %}
      {% set display = 'none' %}
    {% endif %}

    {% if right[name] == 0 %}
      {% set class = 'unchecked' %}
    {% elseif right[name] == users|length %}
      {% set class = 'checked' %}
    {% else %}
      {% set class = 'mixed' %}
    {% endif %}

  {% if name == 'access' %}
    {% if class != 'checked' and type == 'base' and app.getAclForUser(admin).has_access_to_base(id) is empty %}
      <div class="no_switch">
      </div>
    {% else %}
      <div style="display:{{display}}" class="{{class}} switch_right {{sbas_class}} {{type}} {{type}}_{{id}} right_{{name}}">
        <input class="{{class}}" name="{{name}}_{{id}}" value="" type="hidden"/>
       </div>
    {% endif %}
  {% else %}
    {% if class != 'checked' and type == 'base' and app.getAclForUser(admin).has_right_on_base(id, name) is empty %}
      <div class="no_switch">
      </div>
    {% elseif class != 'checked' and type == 'sbas' and app.getAclForUser(admin).has_right_on_sbas(id, name) is empty %}
      <div class="no_switch">
      </div>
    {% else %}
      <div style="display:{{display}}" class="{{class}} switch_right {{sbas_class}} {{type}} {{type}}_{{id}} right_{{name}}">
        <input class="{{class}}" name="{{name}}_{{id}}" value="" type="hidden"/>
       </div>
    {% endif %}
  {% endif %}
{% endmacro %}
<style>
  div.no_switch,
  div.switch_quota,
  div.switch_masks,
  div.switch_time,
  div.switch_right{
    background-repeat:no-repeat;
    background-position: center center;
    width:12px;
    height:12px;
    margin:0 auto;
  }
  div.no_switch{
    background-image:url(/assets/common/images/icons/ccoch5.gif);
  }
  div.switch_quota.mixed,
  div.switch_masks.mixed,
  div.switch_time.mixed,
  div.switch_right.mixed{
    background-image:url(/assets/common/images/icons/ccoch2.gif);
  }
  div.switch_quota.checked,
  div.switch_masks.checked,
  div.switch_time.checked,
  div.switch_right.checked{
    background-image:url(/assets/common/images/icons/ccoch1.gif);
  }
  div.switch_quota.unchecked,
  div.switch_masks.unchecked,
  div.switch_time.unchecked,
  div.switch_right.unchecked{
    background-image:url(/assets/common/images/icons/ccoch0.gif);
  }
  td.users_col{
    vertical-align:middle;
    text-align:center;
    width:23px;
    border:0px solid transparent;
  }
  .ui-datepicker{
    z-index:1500;
  }
</style>

<div>
  <div class="tabs PNB" style="bottom:40px;">
    <ul>
      <li>
        <a href="#rights_tab">{{ 'Rights' | trans }}</a>
      </li>
      {% if main_user is not empty and main_user.isTemplate is empty and main_user.isSpecial is empty %}
      <li>
        <a href="#user_infos_tab">{{ 'Infos' | trans }}</a>
      </li>
      {% endif %}
    </ul>
    <div id="rights_tab" class="" style="top:40px;">
      <form id="users_rights_form" method="post" action="{{ path('admin_users_rights_apply') }}">
        <input type="hidden" name="users" value="{{users_serial}}"/>
        <table style="width:100%;" cellspacing="0" cellpadding="0" border="0">
          <tr>
            <td>
              {% if main_user is not empty %}

                {% if main_user.isSpecial is not empty %}
                  {% if main_user.getLogin() == 'invite' %}
                      {{ 'Reglages:: reglages d acces guest' | trans }}
                  {% elseif main_user.getLogin() == 'autoregister' %}
                      {{ 'Reglages:: reglages d inscitpition automatisee' | trans }}
                  {% endif %}
                {% else %}
                  {% set display_name = main_user.getDisplayName() %}
                  {% trans with {'%display_name%' : display_name} %}Edition des droits de %display_name%{% endtrans %}
                {% endif %}
              {% else %}
                {% set number = users|length %}
                {% trans with {'%number%' : number} %}Edition des droits de %number% utilisateurs{% endtrans %}
              {% endif %}
            </td>
            <td style="text-align:right;">
              {{ 'Apply a template' | trans }}
              <select name="template">
                <option value="">{{ 'boutton::choisir' | trans }}</option>
                {% for template in templates %}
                    <option value="{{ template.getId() }}">{{ template.getLogin() }}</option>
                {% endfor %}
              </select>
               <button class="btn" type='button' id='reset_rights'>{{ 'Delete all users rights' | trans }}</button>
            </td>
          </tr>
        </table>
        <table cellspacing="0" cellpadding="0" border="0" style="table-layout: auto;width:820px;height:67px;bottom:auto;top:50px;" class="">
          <thead>
            <tr>
              <th style="width:122px;">

              </th>
              <th colspan="26">
                <img src="/assets/common/images/lng/inclin-{{app['locale']}}.png" style="width:698px"/>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>

              </td>
              <td colspan="26">

              </td>
            </tr>
          </tbody>
        </table>
        <div class="" style="bottom:40px;top:127px;overflow-y:auto;overflow-x:hidden;width:850px;">
          <table class="hoverable" cellspacing="0" cellpadding="0" border="0" style="table-layout: fixed;width:820px;">
      <!--      <thead>
              <tr>
                <th style="width:122px;">

                </th>
                <th colspan="26">
                  <img src="/assets/common/images/lng/inclin-{{app['locale']}}.gif" >
                </th>
              </tr>
            </thead>-->
            <tbody>
              {% set sbas = '' %}
              {% for rights in datas %}
              {% if rights['sbas_id'] != sbas %}
              {% set sbas = rights['sbas_id'] %}
              {% if loop.index != 1 %}
                <tr style="height:15px;">
                  <td></td>
                </tr>
              {% endif %}

              <tr>
                <td style="width:122px;overflow:hidden;white-space:nowrap;">
                  {{rights['sbas_id']|sbas_labels(app)}}
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_access"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_actif"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canputinalbum"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_candwnldpreview"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_nowatermark"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_candwnldhd"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_cancmd"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col">

                </td>
                <td class="users_col">
                  <div class="time_trigger time_sbas_{{rights['sbas_id']}}">
                    <img src="/assets/common/images/icons/user_details_gray.png" />
                    <input type="hidden" name="time_sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col">

                </td>
                <td>

                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canaddrecord"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canmodifrecord"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_chgstatus"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_candeleterecord"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_imgtools"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canadmin"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canreport"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_canpush"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_manage"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td class="users_col options">
                  <div>
                    &#x25bc;
                    <input type="hidden" name="right" value="right_modify_struct"/>
                    <input type="hidden" name="sbas_id" value="{{rights['sbas_id']}}"/>
                  </div>
                </td>
                <td style="text-align:center;width:19px;" title="{{ 'Allowed to publish' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::BAS_CHUPUB'), users, 'sbas')}}
                </td>
                <td style="text-align:center;width:19px;" title="{{ 'Manage Thesaurus' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::BAS_MODIF_TH'), users, 'sbas')}}
                </td>
                <td style="text-align:center;width:19px;" title="{{ 'Manage Database' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::BAS_MANAGE'), users, 'sbas')}}
                </td>
                <td style="text-align:center;width:19px;" title="{{ 'Manage DB fields' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::BAS_MODIFY_STRUCT'), users, 'sbas')}}
                </td>
                <td style="text-align:center;width:48px;"></td>
              </tr>
              {% endif %}
              <tr>
                <td style="overflow:hidden;white-space:nowrap;">
                  {{rights['base_id']|bas_labels(app)}}
                </td>
                <td class="users_col case_right_access" title="{{ 'Access' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::ACCESS'), users, 'base')}}
                </td>
                <td class="users_col case_right_actif" title="{{ 'Active' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::ACTIF'), users, 'base')}}
                </td>
                <td class="users_col case_right_canputinalbum" title="{{ 'Allowed to add in basket' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANPUTINALBUM'), users, 'base')}}
                </td>
                <td class="users_col case_right_candwnldpreview" title="{{ 'Access to preview' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANDWNLDPREVIEW'), users, 'base')}}
                </td>
                <td class="users_col case_right_nowatermark" title="{{ 'Remove watermark' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::NOWATERMARK'), users, 'base')}}
                </td>
                <td class="users_col case_right_candwnldhd" title="{{ 'Access to HD' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANDWNLDHD'), users, 'base')}}
                </td>
                <td class="users_col case_right_cancmd" title="{{ 'Allowed to order' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANCMD'), users, 'base')}}
                </td>
                <td class="users_col case_right_quota" title="{{ 'Set download quotas' | trans }}">
                  <div class="quota_trigger quota_{{rights['base_id']}} base_{{rights['base_id']}}">
                    {% if rights[constant('\\ACL::RESTRICT_DWNLD')] > 0 %}
                    <img src="/assets/common/images/icons/user_details_on.png" />
                    {% else %}
                    <img src="/assets/common/images/icons/user_details_off.png" />
                    {% endif %}
                    <input type="hidden" name="quota_base_id" value="{{rights['base_id']}}"/>
                  </div>
                </td>
                <td class="users_col case_right_time" title="{{ 'Set time restrictions' | trans }}">
                  <div class="time_trigger time_{{rights['base_id']}} base_{{rights['base_id']}}">
                    {% if rights['time_limited'] > 0 %}
                    <img src="/assets/common/images/icons/user_details_on.png" />
                    {% else %}
                    <img src="/assets/common/images/icons/user_details_off.png" />
                    {% endif %}
                    <input type="hidden" name="time_base_id" value="{{rights['base_id']}}"/>
                  </div>
                </td>
                <td class="users_col case_right_masks" title="{{ 'Set statuses restrictions' | trans }}">
                  <div class="masks_trigger quotatime_{{rights['base_id']}} base_{{rights['base_id']}}">
                    {% if rights['masks'] > 0 %}
                    <img src="/assets/common/images/icons/user_details_on.png" />
                    {% else %}
                    <img src="/assets/common/images/icons/user_details_off.png" />
                    {% endif %}
                    <input type="hidden" name="masks_base_id" value="{{rights['base_id']}}"/>
                  </div>
                </td>

                <td style="text-align:center;width:100px;"></td>

                <td class="users_col case_right_canaddrecord" title="{{ 'Allowed to add' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANADDRECORD'), users, 'base')}}
                </td>
                <td class="users_col case_right_canmodifrecord" title="{{ 'Allowed to edit' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANMODIFRECORD'), users, 'base')}}
                </td>
                <td class="users_col case_right_chgstatus" title="{{ 'Allowed to change statuses' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CHGSTATUS'), users, 'base')}}
                </td>
                <td class="users_col case_right_candeleterecord" title="{{ 'Allowed to delete' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANDELETERECORD'), users, 'base')}}
                </td>
                <td class="users_col case_right_imgtools" title="{{ 'Access to image tools' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::IMGTOOLS'), users, 'base')}}
                </td>
                <td class="users_col case_right_canadmin" title="{{ 'Manage users' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANADMIN'), users, 'base')}}
                </td>
                <td class="users_col case_right_canreport" title="{{ 'Allowed to access report' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANREPORT'), users, 'base')}}
                </td>
                <td class="users_col case_right_canpush" title="{{ 'Allowed to push' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::CANPUSH'), users, 'base')}}
                </td>
                <td class="users_col case_right_manage" title="{{ 'Manage collection' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::COLL_MANAGE'), users, 'base')}}
                </td>
                <td class="users_col case_right_modify" title="{{ 'Manage values lists' | trans }}">
                  {{_self.format_checkbox(app.getAuthenticatedUser(), rights, constant('\\ACL::COLL_MODIFY_STRUCT'), users, 'base')}}
                </td>
                <td colspan="5">

                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </form>
    </div>

    {% if main_user is not empty and main_user.isTemplate is empty and main_user.isSpecial is empty %}
    <div id="user_infos_tab" class="" style="top:40px;overflow:auto;">
      <form id="user_infos_form">
        <table>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur identifiant' | trans }}
            </td>
            <td>
              <input type="text" value="{{main_user.getLogin()}}" readonly="readonly" />
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur sexe' | trans }}
            </td>
            <td>
              <select name="gender">
                <option {% if main_user.getGender() == 0 %}selected="selected"{% endif %} value="0" >{{ 'admin::compte-utilisateur:sexe: mademoiselle' | trans }}</option>
                <option {% if main_user.getGender() == 1 %}selected="selected"{% endif %} value="1" >{{ 'admin::compte-utilisateur:sexe: madame' | trans }}</option>
                <option {% if main_user.getGender() == 2 %}selected="selected"{% endif %} value="2" >{{ 'admin::compte-utilisateur:sexe: monsieur' | trans }}</option>
              </select>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur prenom' | trans }}
            </td>
            <td>
              <input type="text" name="first_name" value="{{main_user.getFirstName()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur nom' | trans }}
            </td>
            <td>
              <input type="text" name="last_name" value="{{main_user.getLastName()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur email' | trans }}
            </td>
            <td>
              <input type="text" name="email" value="{{main_user.getEmail()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur adresse' | trans }}
            </td>
            <td>
              <input type="text" name="address" value="{{main_user.getAddress()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur code postal' | trans }}
            </td>
            <td>
              <input type="text" name="zip" value="{{main_user.getZipCode()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur ville' | trans }}
            </td>
            <td>
              <input type="text" value="{{ main_user.getGeonameId() }}" class="geoname_field" name="geonameid"
                     autocomplete="false"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur poste' | trans }}
            </td>
            <td>
              <input type="text" name="function" value="{{main_user.getJob()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur societe' | trans }}
            </td>
            <td>
              <input type="text" name="company" value="{{main_user.getCompany()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur activite' | trans }}
            </td>
            <td>
              <input type="text" name="activite" value="{{main_user.getActivity()}}"/>
            </td>
          </tr>

          <tr>
            <td>
              {{ 'admin::compte-utilisateur telephone' | trans }}
            </td>
            <td>
              <input type="text" name="telephone" value="{{main_user.getPhone()}}"/>
            </td>
          </tr>
          <tr>
            <td>
              {{ 'admin::compte-utilisateur fax' | trans }}
            </td>
            <td>
              <input type="text" name="fax" value="{{main_user.getFax()}}"/>
            </td>
          </tr>
        </table>
      </form>
    </div>
    {% endif %}
  </div>
  <div class="form-actions" style="">
    <button class="users_rights_valid btn btn-primary">{{ 'boutton::valider' | trans }}</button>
    <a href="{{ path('admin_users_search') }}" class="users_rights_cancel btn" style="text-decoration:none">{{ 'boutton::retour' | trans }}</a>
  </div>
</div>

<script type="text/javascript">

  $(document).ready(function() {

    function ini_edit_usrs() {
      $('.users_col.options').bind('click', function (event) {
        $('#users_check_uncheck').remove();
        event.stopPropagation();
        event.preventDefault();
        check_uncheck_menu($('input[name="right"]', $(this)).val(), $('input[name="sbas_id"]', $(this)).val(), $(this));
        return false;
      });

      $(document).unbind('click.usersoptions').bind('click.usersoptions', function (event) {
        $('#users_check_uncheck').remove();
      });

      $('table.hoverable tr').hover(
              function () {
                $(this).addClass('hovered');
              },
              function () {
                $(this).removeClass('hovered');
              }
      );

      $('table.hoverable td').hover(
              function () {
                var attr = $('input:first', this).attr('name');
                var right = attr ? attr.split('_').shift() : false;
                if (right)
                  $('td.case_right_' + right).addClass('hovered');
              },
              function () {
                var attr = $('input:first', this).attr('name');
                var right = attr ? attr.split('_').shift() : false;
                if (right)
                  $('td.hovered').removeClass('hovered');
              }
      );

      function user_click_box(event, element, status) {
        var newclass, newvalue, boxes;

        var $element = $(element);

        if ($element.hasClass('right_access')) {
          var base_id = $element.find('input').attr('name').split('_').pop();
          boxes = $('div.base_' + base_id + ':not(:first)');
        }

        if ((typeof status !== 'undefined' && status == 'checked') || (typeof status === 'undefined' && (($element.hasClass('mixed') === true) || ($element.hasClass('unchecked') === true)))) {
          newclass = 'checked';
          newvalue = '1';

          if (boxes)
            boxes.show();
        }
        else {
          newclass = 'unchecked';
          newvalue = '0';

          if (boxes)
            boxes.hide();
        }

        $element.find('input').val(newvalue);
        $element.removeClass('mixed checked unchecked').addClass(newclass);
      }

      $('#users_rights_form div.switch_right').bind('click', function (event) {
        user_click_box(event, $(this));
      });
      $('#right-ajax button.users_rights_valid').bind('click', function () {
        var datas = {
          users: $('#users_rights_form input[name="users"]').val(),
          values: $('#users_rights_form').serialize(),
          template: $('#users_rights_form select[name="template"]').val(),
          user_infos: $('#user_infos_form').serialize()
        };

        var callback = function (reset_before_apply) {
          datas.reset_before_apply = reset_before_apply;
          $.ajax({
            type: 'POST',
            url: '../admin/users/rights/apply/',
            dataType: 'json',
            data: datas,
            success: function (data) {
              if (!data.error)
                $('a.zone_editusers').trigger('click');
              else
                alert(data.message);
            }
          });
        };

        if (datas.template !== '') {
          dialogUserTemplate(callback);
        } else {
          callback('0');
        }

        return false;
      });

      $('#right-ajax .users_rights_cancel').bind('click', function () {
        var $this = $(this);
        $('#right-ajax').empty().addClass('loading').parent().show();
        $('#right').hide();
        $.get($this.attr('href'), function (data) {
          $('#right-ajax').removeClass('loading').html(data);
        });

        return false;
      });

      var time_buttons = {
        'Ok': function () {
          save_time();
        },
        'Cancel': function () {
          $('#time_dialog').dialog('close');
        }
      };
      $('#time_dialog').dialog({
        resizable: false,
        autoOpen: false,
        draggable: false,
        buttons: time_buttons,
        modal: true
      });
      var quota_buttons = {
        'Ok': function () {
          save_quotas();
        },
        'Cancel': function () {
          $('#quotas_dialog').dialog('close');
        }
      };
      $('#quotas_dialog').dialog({
        resizable: false,
        autoOpen: false,
        draggable: false,
        buttons: quota_buttons,
        modal: true
      });

      var masks_buttons = {
        'Ok': function () {
          save_masks();
        },
        'Cancel': function () {
          $('#masks_dialog').dialog('close');
        }
      };
      $('#masks_dialog').dialog({
        resizable: false,
        autoOpen: false,
        draggable: false,
        buttons: masks_buttons,
        width: 900,
        height: 300,
        modal: true
      });
      $('#users_rights_form .time_trigger').bind('click', function () {
        var base_id = $(this).find('input[name="time_base_id"]').val();
        if ('undefined' !== typeof base_id) {
          $.ajax({
            type: 'POST',
            url: '../admin/users/rights/time/',
            data: {
              users: $('#users_rights_form input[name="users"]').val(),
              base_id: base_id
            },
            success: function (data) {
              var dialog = $('#time_dialog');

              if (dialog.data("ui-dialog")) {
                dialog.html(data).dialog('open');
              }

              $('div.switch_time', dialog).bind('click', function (event) {
                var newclass, boxes;

                boxes = $(this).closest('form').find('input.datepicker');

                if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
                  newclass = 'checked';
                  boxes.removeAttr('readonly');
                }
                else {
                  newclass = 'unchecked';
                  boxes.attr('readonly', 'readonly');
                }

                $(this).removeClass('mixed checked unchecked').addClass(newclass);
              });
            }
          });
        } else {
          var sbas_id = $(this).find('input[name="time_sbas_id"]').val();

          $.ajax({
            type: 'POST',
            url: '../admin/users/rights/time/sbas/',
            data: {
              users: $('#users_rights_form input[name="users"]').val(),
              sbas_id: sbas_id
            },
            success: function (data) {
              var dialog = $('#time_dialog');

              dialog.html(data);
              dialog.dialog('open');

              $('div.switch_time', dialog).bind('click', function (event) {
                var newclass, boxes;

                boxes = $(this).closest('form').find('input.datepicker');

                if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
                  newclass = 'checked';
                  boxes.removeAttr('readonly');
                }
                else {
                  newclass = 'unchecked';
                  boxes.attr('readonly', 'readonly');
                }

                $(this).removeClass('mixed checked unchecked').addClass(newclass);
              });
            }
          });
        }
      });
      $('#users_rights_form .quota_trigger').bind('click', function () {
        var base_id = $(this).find('input[name="quota_base_id"]').val();
        $.ajax({
          type: 'POST',
          url: '../admin/users/rights/quotas/',
          data: {
            users: $('#users_rights_form input[name="users"]').val(),
            base_id: base_id
          },
          success: function (data) {
            var dialog = $('#quotas_dialog');

            if (dialog.data("ui-dialog")) {
              dialog.html(data).dialog('open');
            }

            $('div.switch_quota', dialog).bind('click', function (event) {
              var newclass, boxes;

              boxes = $(this).closest('form').find('input:text');

              if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
                newclass = 'checked';
                boxes.removeAttr('readonly');
              }
              else {
                newclass = 'unchecked';
                boxes.attr('readonly', 'readonly');
              }

              $(this).removeClass('mixed checked unchecked').addClass(newclass);
            });
          }
        });
      });

      $('#users_rights_form .masks_trigger').bind('click', function () {
        var base_id = $(this).find('input[name="masks_base_id"]').val();
        $.ajax({
          type: 'POST',
          url: '../admin/users/rights/masks/',
          data: {
            users: $('#users_rights_form input[name="users"]').val(),
            base_id: base_id
          },
          success: function (data) {
            $('#masks_dialog').html(data).dialog('open');

            $('.switch_masks').bind('click', function () {
              var currentclass, newclass;

              var bit = $(this).find('input[name="bit"]').val();
              currentclass = 'unchecked';
              if ($(this).hasClass('mixed')) {
                currentclass = 'mixed';
              }
              if ($(this).hasClass('checked')) {
                currentclass = 'checked';
              }
              switch (currentclass) {
                case 'mixed':
                default:
                  $('.bitnum_' + bit).removeClass('mixed checked unchecked').addClass('checked')
                  break;
                case 'unchecked':
                  $(this).removeClass('mixed checked unchecked').addClass('checked')
                  break;
                case 'checked':
                  if ($('.checked.bitnum_' + bit).length == 2) {
                    $(this).removeClass('mixed checked unchecked').addClass('unchecked')
                  }
                  else {
                    alert("admin::user:mask: vous devez cocher au moins une case pour chaque status");
                    return;
                  }
                  break;
              }

              var left = $('.bitnum_' + bit + '.bit_left');
              var right = $('.bitnum_' + bit + '.bit_right');

              var maskform = $('#masks_dialog form');
              var vand_and = $('input[name="vand_and"]', maskform);
              var vand_or = $('input[name="vand_or"]', maskform);
              var vxor_and = $('input[name="vxor_and"]', maskform);
              var vxor_or = $('input[name="vxor_or"]', maskform);

              var newbit_vand_and = newbit_vand_or = newbit_vxor_and = newbit_vxor_or = 0;

              if (left.length === 1 && right.length === 1) {
                if (left.hasClass('checked') && right.hasClass('unchecked')) {
                  newbit_vand_and = "1";
                  newbit_vand_or = "1";
                }
                else if (left.hasClass('unchecked') && right.hasClass('checked')) {
                  newbit_vand_and = "1";
                  newbit_vand_or = "1";
                  newbit_vxor_and = "1";
                  newbit_vxor_or = "1";
                }
                vand_and.val(vand_and.val().substr(0, 31 - bit) + newbit_vand_and + vand_and.val().substr(31 + 1 - bit));
                vand_or.val(vand_or.val().substr(0, 31 - bit) + newbit_vand_or + vand_or.val().substr(31 + 1 - bit));
                vxor_and.val(vxor_and.val().substr(0, 31 - bit) + newbit_vxor_and + vxor_and.val().substr(31 + 1 - bit));
                vxor_or.val(vxor_or.val().substr(0, 31 - bit) + newbit_vxor_or + vxor_and.val().substr(31 + 1 - bit));
              }
            });
          }
        });
      });


      function save_masks() {
        var cont = $('#masks_dialog');

        var maskform = $('#masks_dialog form');
        var base_id = $('input[name="base_id"]', maskform).val();
        var users = $('input[name="users"]', maskform).val();
        var vand_and = $('input[name="vand_and"]', maskform).val();
        var vand_or = $('input[name="vand_or"]', maskform).val();
        var vxor_and = $('input[name="vxor_and"]', maskform).val();
        var vxor_or = $('input[name="vxor_or"]', maskform).val();


        $.ajax({
          type: 'POST',
          url: '../admin/users/rights/masks/apply/',
          data: {
            users: users,
            base_id: base_id,
            vand_and: vand_and,
            vand_or: vand_or,
            vxor_and: vxor_and,
            vxor_or: vxor_or
          },
          success: function (data) {
            $('#masks_dialog').dialog('close');
          }
        });
      }


      function save_quotas() {
        var cont = $('#quotas_dialog');
        var base_id = $('input[name="base_id"]', cont).val();
        var users = $('input[name="users"]', cont).val();
        var droits = $('input[name="droits"]', cont).val();
        var restes = $('input[name="restes"]', cont).val();

        var switch_quota = $('.switch_quota', cont);

        if (switch_quota.hasClass('mixed'))
          return;

        var quota = 0;

        if (switch_quota.hasClass('checked'))
          quota = 1;

        $.ajax({
          type: 'POST',
          url: '../admin/users/rights/quotas/apply/',
          data: {
            act: "APPLYQUOTAS",
            users: users,
            base_id: base_id,
            quota: quota,
            droits: droits,
            restes: restes
          },
          success: function (data) {
            $('#quotas_dialog').dialog('close');
          }
        });
      }

      function save_time() {
        var cont = $('#time_dialog');
        var dmin = $('input[name="dmin"]', cont).val();
        var dmax = $('input[name="dmax"]', cont).val();
        var users = $('input[name="users"]', cont).val();
        var base_id = $('input[name="base_id"]', cont).val();
        var sbas_id = $('input[name="sbas_id"]', cont).val();

        var switch_time = $('.switch_time', cont);

        if (switch_time.hasClass('mixed'))
          return;

        var limit = 0;

        if (switch_time.hasClass('checked'))
          limit = 1;

        $.ajax({
          type: 'POST',
          url: '../admin/users/rights/time/apply/',
          data: {
            users: users,
            base_id: base_id,
            sbas_id: sbas_id,
            limit: limit,
            dmin: dmin,
            dmax: dmax
          },
          success: function (data) {
            $('#time_dialog').dialog('close');
          }
        });
      }

      function check_uncheck_menu(right, sbas_id, el) {
        var top = el.offset().top;
        var left = el.offset().left + 16;
        $('body').append('<div id="users_check_uncheck" style="position:absolute;top:' + top + 'px;left:' + left + 'px;">' +
        '<div class="checker" >' +
        language.check_all +
        '<input type="hidden" name="sbas_id" value="' + sbas_id + '"/>' +
        '<input type="hidden" name="right" value="' + right + '"/>' +
        '</div>' +
        '<div class="unchecker">' +
        language.uncheck_all +
        '<input type="hidden" name="sbas_id" value="' + sbas_id + '"/>' +
        '<input type="hidden" name="right" value="' + right + '"/>' +
        '</div></div>');

        $('#users_check_uncheck div').hover(
                function () {
                  $(this).addClass('hovered');
                },
                function () {
                  $(this).removeClass('hovered');
                }
        );
        $('#users_check_uncheck div.checker').bind('click', function (event) {
          event.stopPropagation();
          event.preventDefault();
          users_check(true, $('input[name="sbas_id"]', $(this)).val(), $('input[name="right"]', $(this)).val());
          $('#users_check_uncheck').remove();
        });
        $('#users_check_uncheck div.unchecker').bind('click', function (event) {
          event.stopPropagation();
          event.preventDefault();
          users_check(false, $('input[name="sbas_id"]', $(this)).val(), $('input[name="right"]', $(this)).val());
          $('#users_check_uncheck').remove();
        });

      }

      function users_check(bool, sbas_id, right) {
        var newclass;
        if (bool) {
          newclass = "checked";
        }
        else {
          newclass = "unchecked";
        }
        $('.inside_sbas_' + sbas_id + '.' + right + ':visible').each(function (i, n) {
          user_click_box(null, $(n), newclass);
        });
      }
    }

    ini_edit_usrs();

    $('div.tabs').tabs();

    $('#users_rights_form button#reset_rights').bind('click', function () {
      if (confirm("{{ 'Are you sure you want to reset rights?' | trans }}")) {
        var users = $('#users_rights_form input[name="users"]').val();

        $.ajax({
          type: 'POST',
          url: '/admin/users/rights/reset/',
          dataType: 'json',
          data: {
            users: users
          },
          success: function (data) {
            if (!data.error) {
              if (users === '') {
                return false;
              }

              $('#right-ajax').empty().addClass('loading');
              p4.users.sel = [];
              $.ajax({
                type: 'GET',
                url: '/admin/users/rights/',
                data: {
                  users: users
                },
                success: function (data) {
                  $('#right-ajax').removeClass('loading').html(data);
                }
              });

              return false;
            } else {
              alert(data.message);
            }
          }
        });
      }
    });
  });

  require([
    "jquery",
    "common/geonames"
  ], function ($, geonames) {
    var geocompleter = geonames.init($('#user_infos_tab input.geoname_field'), {
      "server": "{{ app['geonames.server-uri'] }}",
      "limit": 40
    });

  });

</script>
