/**
 * Select users widget
 */
App.widgets.SelectUsers = function() {
  
  // Public interface
  return {
    
    /**
     * Initialize select users widget
     *
     * @param String widget_id
     * @param String control_name
     * @param Object all_users
     */
    init : function(widget_id, control_name, all_users) {
      var widget = $('#' + widget_id);
      
      var users_list = widget.find('ul.users_list');
      var no_selected_users = widget.find('p.no_users_selected');
      
      widget.find('.assignees_button').click(function() {
        var selected_users = {};
        
        widget.find('input[type=hidden]').each(function() {
          var input = $(this);
          
          selected_users[parseInt(input.attr('value'))] = input.attr('user_display_name');
        });
        
        App.widgets.SelectUsersPopup.open(all_users, selected_users, function(response) {
          users_list.empty();
          widget.find('input[type=hidden]').remove();
          
          for(var user_id in response) {
            users_list.append('<li>' + response[user_id].clean() + '</li>');
            users_list.after('<input type="hidden" name="' + control_name + '[]" value="' + user_id + '" user_display_name="' + response[user_id].clean() + '" />');
          } // for
          
          if(users_list.find('li').length > 0) {
            no_selected_users.hide();
            users_list.show();
          } else {
            users_list.hide();
            no_selected_users.show();
          } // if
        });
        
        return false;
      });
    }
    
  };
  
}();

/**
 * Validate if we have users selected
 *
 * @param jQuery field
 * @param string caption
 */
window.select_users_value_present = function(field, caption) {
  if(field.find('ul.users_list li').length < 1) {
    return App.lang('Required');
  } // if
};