/**
 * Select homescreen widget type behavior
 */
jQuery.fn.selectHomescreenWidgetType = function(s) {
  var settings = jQuery.extend({
    'types' : null
  }, s);
  
  return this.each(function() {
    var wrapper = $(this);
    var wrapper_id = wrapper.attr('id');
    
    var types_wrapper = $('<div class="homescreen_widget_types"></div>').appendTo(wrapper);
    var type_details_wrapper = $('<div class="homescreen_widget_type_details"></div>').appendTo(wrapper);
    
    for(var group_name in settings['types']) {
      var group_wrapper = $('<div class="homescreen_widget_types_group" widget_group_name="' + group_name.clean() + '"></div>').appendTo(types_wrapper);
      
      group_wrapper.append('<p>' + group_name.clean() + ':</p>');
      
      for(var type_class in settings['types'][group_name]) {
        var type_wrapper = $('<div class="homescreen_widget_type"></div>').appendTo(group_wrapper);
        var type_id = wrapper_id + '_' + type_class;
        
        $('<input type="radio" name="homescreen_widget[type]" value="' + type_class +'" id="' + type_id + '">').click(function() {
          var input = $(this);
          
          var group_name = input.parent().parent().attr('widget_group_name');
          var current_type_class = input.attr('value');
          
          if(type_details_wrapper.attr('currently_selected') == current_type_class) {
            return;
          } // if
          
          type_details_wrapper.empty().append('<h3>' + settings['types'][group_name][current_type_class]['name'].clean() + '</h3>').attr('currently_selected', current_type_class);
          
          if(settings['types'][group_name][current_type_class]['description']) {
            type_details_wrapper.append('<div class="homescreen_widget_type_description">' + settings['types'][group_name][current_type_class]['description'] + '</div>');
          } // if
          
          if(settings['types'][group_name][current_type_class]['options']) {
            type_details_wrapper.append('<div class="homescreen_widget_type_options">' + settings['types'][group_name][current_type_class]['options'] + '</div>');
          } // if
          
        }).appendTo(type_wrapper);
        
        type_wrapper.append('<label for="' + type_id + '">' + settings['types'][group_name][type_class]['name'].clean() + '</label>');
      } // for
    } // for
    
    // And select first one
    types_wrapper.find('input[type=radio]:first').click();
  });
  
};