/**
 * Select system permissions widget implementation
 */
jQuery.fn.selectSystemPermissions = function(s) {
  var settings = jQuery.extend({
    'name' : 'permissions', 
    'value' : null, 
    'permissions' : null, 
    'protect' : null
  }, s);
  
  if(typeof(settings['value']) != 'object' || settings['value'] == null) {
    settings['value'] = {};
  } // if
  
  return this.each(function() {
    var wrapper = $(this);
    
    var wrapper_id = wrapper.attr('id');
    
    var list = $('<div class="select_system_permissions_list"></div>').attr('id', wrapper_id + '_list').appendTo(wrapper);
    var description = $('<div class="select_system_permissions_permission_description" style="display: none"></div>').attr('id', wrapper_id + '_description').appendTo(wrapper);
    
    /**
     * Add permission definition to the list
     * 
     * @param String name
     * @param Object info
     * @param jQuery add_to
     */
    var add = function(name, info, add_to) {
      var permission_wrapper_id = add_to.attr('id') + '_' + name;
    
      // Permission checkbox and label
      var permission_wrapper = $('<div id="' + permission_wrapper_id + '" class="select_system_permissions_permission_wrapper"><label for="' + permission_wrapper_id + '_value"><input type="checkbox" name="' + settings['name'] + '[' + name + ']" id="' + permission_wrapper_id + '_value" value="1" /> <span>' + info['name'].clean() + '</span></label></div>').appendTo(add_to);
      var permission_checkbox = permission_wrapper.find('input[type=checkbox]');
      
      // See if this particular permission is protected
      if(typeof(settings['protect']) == 'object' && settings['protect']) {
        for(var i in settings['protect']) {
          if(settings['protect'][i] == name) {
            permission_checkbox.attr('protected', true);
            break;
          } // if
        } // if
      } // if
      
      // Permission description handling
      var show_permission_description_timer = false;
      
      permission_wrapper.find('label').hover(function(e) {
        var text_text = typeof(info['description']) == 'string' && info['description'] ? info['description'] : App.lang('Sorry, no description available');
        
        description.append('<b>' + info['name'].clean() + '</b>').append('<p>' + text_text.clean() + '</p>');
        
        show_permission_description_timer = setTimeout(function() {
          description.fadeIn();
        }, 200);
      }, function(e) {
        if(show_permission_description_timer) {
          clearTimeout(show_permission_description_timer);
        } // if
        
        description.empty().hide();
      });
      
      if(permission_checkbox.attr('protected') == true || (typeof(settings['value'][name]) != 'undefined' && settings['value'][name])) {
        permission_checkbox.attr('checked', 'checked');
      } // if
      
      // Subpermissions
      var subpermissions_wrapper = $('<div id="' + permission_wrapper_id + '_subpermissions" class="select_system_permissions_permission_subpermissions"></div>');
      
      for(var subpermission_name in settings['permissions']) {
        if(settings['permissions'][subpermission_name]['depends_on'] == name) {
          add(subpermission_name, settings['permissions'][subpermission_name], subpermissions_wrapper);
        } // if
      } // for
      
      if(subpermissions_wrapper.find('div.select_system_permissions_permission_wrapper').length > 0) {
        subpermissions_wrapper.appendTo(permission_wrapper);
        
        if(!permission_checkbox[0].checked) {
          subpermissions_wrapper.hide();
        } // if
      } // if
    }; // add
    
    for(var permission_name in settings['permissions']) {
      if(typeof(settings['permissions'][permission_name]['depends_on']) == 'undefined') {
        add(permission_name, settings['permissions'][permission_name], list);
      } // if
    } // for

    /**
     * Analyze click to each checkbox
     */
    $('input[type=checkbox]').each(function() {
      $(this).click(function() {
        if($(this).attr('protected')) { // protect some permissions from being removed
          App.Wireframe.Flash.success("Selected permission is protected in this role and it cannot be turned Off");
          return false;
        } else { // otherwise check if there are subpermissions that need to be shown or hidden & removed
          var subpermissions_wrapper = $(this).parent().parent().find('.select_system_permissions_permission_subpermissions');
          if (subpermissions_wrapper != undefined) {
            if($(this).attr('checked')) {
              subpermissions_wrapper.show();
            } else {
              subpermissions_wrapper.find('input[type=checkbox]').removeAttr('checked');
              subpermissions_wrapper.find('div.select_system_permissions_permission_subpermissions').hide();
              subpermissions_wrapper.hide();
            } // if
          }
        }
      });
    }); // each checkbox
  });
  
};