/**
 * Color Field control
 *
 * @require App.Wireframe.Events
 */
(function($) {
  
  /**
   * Public methods
   * 
   * @var Object
   */
  var public_methods = {
      
    /**
     * Initialise color field popup
     * 
     * @param Object options
     * @returns jQuery
     */
    init : function(options) {
      return this.each(function () {
        var wrapper = $(this);
        var wrapper_dom = this;
        
        this.id_data = {};
                
//        this.id_data.settings = jQuery.extend({
//          'id' : 'color_picker_' + (new Date().getTime()),
//        }, options);
        
        var field = $('<input type="text" />').appendTo(wrapper);
        field.attr('name', options.name);
        
        var picker = $('<div class="color_selector"><div></div></div>').insertAfter(field);
        var picker_color = picker.find('div');
        
        /**
         * Update field value, and picker background
         * 
         * @param String color
         * @return null
         */
        var update_color = function (color) {
          if (color[0] != '#') {
            color = '#' + color;
          } // if
          
          picker_color.css('backgroundColor', color);
          field.val(color.toUpperCase());
        }; // update_field
        
        picker.ColorPicker({
          'color' : options.value,
          'onShow' : function (color_popup) {
            $(color_popup).addClass('color_field_popup').show();
            return false;            
          },
          'onSubmit' : function (hsb, hex, rgb) {
            update_color(hex);
          },
          'onChange' : function (hsb, hex, rgb) {
            update_color(hex);          }
        });
        
        update_color(options.value);
      });
    }
  };
  
  
  ////////////////////////////////////////////////////////// PLUGIN INITIAL DATA ///////////////////////////////////////////////////////////  
  
  /**
   * Plugin name
   * 
   * @var String
   */
  var plugin_name = 'colorField';
        
  ///////////////////////////////////////////////////////// PLUGIN FRAMEWORK STUFF /////////////////////////////////////////////////////////
  /**
   * Register jQuery plugin and handle public methods
   * 
   * @param mixed method
   * @return null
   */
  $.fn[plugin_name] = function(method) { 
    if (public_methods[method]) {
      return public_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return public_methods.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist in jQuery.' + plugin_name);
    } // if
  };

})(jQuery);