{title}People{/title}
{add_bread_crumb}All{/add_bread_crumb}

<div id="project_people"></div>

<script type="text/javascript">
  $('#project_people').each(function() {
    var wrapper = $(this);
    var project_users = {$project_users|json nofilter};
    var companies = {$companies|json nofilter};
    var can_manage = {$can_manage|json nofilter};
    var can_see_contact = {$logged_user->getSystemPermission('can_see_contact_details')|json nofilter};
    var leader_id = {$active_project->getLeaderId()|json nofilter};
    
    var user_permissions_url = {$active_project->getUserPermissionsUrl('--USER-ID--')|json nofilter};
    var replace_user_url = {$active_project->getReplaceUserUrl('--USER-ID--')|json nofilter};
    var remove_user_url = {$active_project->getRemoveUserUrl('--USER-ID--')|json nofilter};
    
    /**
     * Rebuild users list
     *
     * @param Array users
     */
    var rebuild = function(users) {
      wrapper.empty();
      
      if(jQuery.isArray(users) && users.length) {
        
        /**
         * Return existing or create a new company table
         *
         * @param Integer company_id
         * @return jQuery
         */
        var get_company_table = function(company_id) {
          if(companies[company_id]) {
            var company_name = companies[company_id];
            var company_table = wrapper.find('#project_company_' + company_id);

            if(company_table.length < 1) {
              company_table = $('<table class="common" cellspacing="0" id="project_company_' + company_id + '">' + 
                '<thead><tr><th colspan="' + (can_manage ? 4 : 3) + '">' + company_name.clean() + '</th></tr></thead>' + 
                '<tbody></tbody>' + 
              '</table>').appendTo(wrapper);
            } // if
            
            return company_table;
          } // if
        }; // get_company_table

        App.each(users, function (i, user) {
          var company_table = get_company_table(user['user']['company_id']);

          if(company_table && company_table.length > 0) {

            // Project leader
            if(user['user']['id'] == leader_id) {
              var full_access = true;
              var removable = false;
              var role = '<span class="pill ok">' + App.lang('Leader') +'</span>';

              // People with admin permissions
            } else if(user['user']['is_administrator']) {
              var full_access = true;
              var removable = true;
              var role = App.lang('Full Access') + ' <span>(' + App.lang('Administrator') + ')</span>';

              // People with project management permissions
            } else if(user['user']['is_project_manager']) {
              var full_access = true;
              var removable = true;
              var role = App.lang('Full Access') + ' <span>(' + App.lang('Project Manager') + ')</span>';

              // No admin / PM members
            } else {
              var full_access = false;
              var removable = true;
              var role = user['role'].clean();
            } // if

            var row = $('<tr class=project_company_user" user_id="' + user['user']['id'] + '">' +
              '<td class="avatar"><img src="' + user['user']['avatar']['large'].clean() + '"></td>' +
              '<td class="name"><a href="' + user['user']['urls']['view'].clean() + '" class="project_company_user_name">' + user['user']['display_name'].clean() + '</a></td>' +
              '<td class="role">' + role + '</td>' +
              '</tr>').appendTo(company_table.find('tbody'));

            if(can_see_contact) {
              var contact_details = $('<ul class="project_company_user_contact_details"><li>' + App.lang('Email') + ': <a href="mailto:' + user['user']['email'].clean() + '">' + user['user']['email'].clean() + '</a></li></ul>').appendTo(row.find('td.name'));

              if(user['user']['im_type'] && user['user']['im_value']) {
                contact_details.append('<li>' + user['user']['im_type'].clean() + ': ' + user['user']['im_value'].clean() + '<li>');
              } // if
            } // if

            if(can_manage) {
              var options = $('<td class="options"></td>').appendTo(row);

              if(!full_access) {
                $('<a href="' + user_permissions_url.replace('--USER-ID--', user['user']['id']).clean() + '" title="' + App.lang("Change :user's Permissions", { 'user' : user['user']['first_name'] }) + '"><img src="' + App.Wireframe.Utils.imageUrl('icons/12x12/configure.png', 'environment') + '"/></a>').flyoutForm({
                  'success_event' : 'project_people_updated',
                  'width' : 450,
                  'success' : function() {
                    App.Wireframe.Flash.success('User permissions have been updated');
                  },
                  'error' : function() {
                    App.Wireframe.Flash.error('Failed to update user permissions. Please try again later');
                  }
                }).appendTo(options);
              } // if

              if(removable) {
                $('<a href="' + replace_user_url.replace('--USER-ID--', user['user']['id']).clean() + '" title="' + App.lang('Replace User') + '"><img src="' + App.Wireframe.Utils.imageUrl('icons/12x12/swap.png', 'environment') + '" /></a>').flyoutForm({
                  'success_event' : 'project_people_updated',
                  'width' : '500',
                  'success' : function(response) {
                    App.Wireframe.Flash.success('Selected user has been replaced on this project');
                  },
                  'error' : function() {
                    App.Wireframe.Flash.error('Failed to replace selected user on this project. Please try again later');
                  }
                }).appendTo(options);

                $('<a href="' + remove_user_url.replace('--USER-ID--', user['user']['id']).clean() + '" title="' + App.lang('Remove from Project') + '"><img src="' + App.Wireframe.Utils.imageUrl('icons/12x12/delete.png', 'environment') + '"/></a>').flyoutForm({
                  'success_event' : 'project_people_updated',
                  'width' : '500',
                  'success' : function(response) {
                    App.Wireframe.Flash.success('Selected user has been removed from this project');
                  },
                  'error' : function() {
                    App.Wireframe.Flash.error('Failed to remove selected user from this project. Please try again later');
                  }
                }).appendTo(options);
              } // if
            } // if
          } // if
        });
      } else {
        wrapper.append('<p class="empty_page">' + App.lang('There are no users assigned to this project') + '</p>');
      } // if
    }; // rebuild
    
    // People added event handler
    App.Wireframe.Events.bind('project_people_created.content', function (event, response) {
      rebuild(response);
      App.Wireframe.Flash.success('Selected people have been added to the project');
    });
    
    // People updated event handler
    App.Wireframe.Events.bind('project_people_updated.content', function (event, response) {
      rebuild(response);
    });
    
    // Initialize with existing list of users
    rebuild(project_users);
  });
</script>