     @select.after(@picker)
     @sync_picker_with_select()
 
-  sync_picker_with_select: ->
+  sync_picker_with_select: () ->
     for option in @picker_options
       if option.is_selected()
         option.mark_as_selected()
       else
         option.unmark_as_selected()
 
-  create_picker: ->
+  create_picker: () ->
     @picker =  $("<ul class='thumbnails image_picker_selector'></div>")
     @picker_options = (new ImagePickerOption(option, this, @opts) for option in @select.find("option"))
     for option in @picker_options
       continue if !option.has_image()
       @picker.append( option.node )
     @picker
+
+  has_implicit_blanks: () ->
+    (option for option in @picker_options when (option.is_blank() && !option.has_image())).length > 0
+
+  selected_values: () ->
+    if @multiple
+      @select.val() || []
+    else
+      [@select.val()]
+
+  toggle: (imagepicker_option) ->
+    old_values = @selected_values()
+    if @multiple
+      if imagepicker_option.value() in @selected_values()
+        imagepicker_option.option.prop("selected", false)
+      else
+        imagepicker_option.option.prop("selected", true)
+    else
+      if @has_implicit_blanks() && imagepicker_option.is_selected()
+        @select.val("")
+      else
+        @select.val(imagepicker_option.value())
+    new_values = @selected_values()
+    unless both_array_are_equal(old_values, new_values)
+      @select.change()
+      @opts.changed() if @opts.changed?
+
 
 class ImagePickerOption
   constructor: (option_element, @picker, @opts={}) ->

    @multiple       = @select.attr("multiple") == "multiple"
    @build_and_append_picker()

  has_implicit_blanks: ->
    (option for option in @picker_options when (option.is_blank() && !option.has_image())).length > 0

  build_and_append_picker: ->
    @select.hide() if @opts.hide_select
    @select.change {picker: this}, (event) ->
      event.data.picker.sync_picker_with_select()

#

jQuery.fn.extend({
  imagepicker: (opts = {}) ->
    this.each () ->
      select = $(this)
      select.next("ul.image_picker_selector").remove()
      select.data "picker", new ImagePicker(this, sanitized_options(opts))
      opts.initialized() if opts.initialized?
})

sanitized_options = (opts) ->
  default_options = {
    hide_select:  true,
    show_label:   false,
    initialized:  undefined,
    changed:      undefined,
    clicked:      undefined,
    selected:     undefined,
  }
  jQuery.extend(default_options, opts)

both_array_are_equal = (a,b) ->
  $(a).not(b).length == 0 && $(b).not(a).length == 0

class ImagePicker
  constructor: (select_element, @opts={}) ->
