 V = 0.95
 P = V * (1 - S)
 
+hex = (c) ->
+  h = c.toString 16
+  "#{if h.length < 2 then '0' else ''}#{h}"
+
 # generated colors will have constant saturation and value
 hue2rgb = (hue) ->
   i = Math.floor hue * 6
   f = hue * 6 - i
   q = V * (1 - f * S)
   t = V * (1 - (1 - f) * S)
-
   [r, g, b] = switch i % 6
     when 0 then [ V, t, P ]
     when 1 then [ q, V, P ]

#    ({tabs: [ { windowId } ] }) ->
#      chrome.windows.update windowId, drawAttention: yes

document.querySelector '#add'
  .addEventListener 'click', ({screenX, screenY}) ->
    storage.get (items) ->
      create "edit.html?color=#{encodeURIComponent pickNewColor (
          color for {color} in items)}", screenX, screenY

update = ->
  storage.get (items) ->
    hats = document.querySelector '#hats'
    # start with empty div
    while hats.firstChild

    for { color, name }, i in items
      do (color, name, i) ->
        hats.insertAdjacentHTML 'beforeend', "
          <button id=hat-#{i} class=open style='background-color:#{color}'
              draggable=true title='Open new window with this hat'>
            <span>#{name}</span>
            <div>
              <img class=edit title=Edit src=icons/edit.png />
              <img class=delete title=Delete src=icons/delete.png />
            </div>
          </button>"
    document.querySelector 'button'
      .focus()

# has to be window; not sure why
window.addEventListener 'focus', update

document.addEventListener 'click',
  ({screenX, screenY, target: {className, id, parentNode: {parentNode}}}) ->
    if className is 'open'
      # XXX drag and drop!
      [ ..., id ] = id.split '-'
      alert "hat #{id}"
      window.close()
    else
      { id, style } = parentNode
      [ ..., id ] = id.split '-'
      id = parseInt id
      if className is 'delete'
        # XXX might want to confirm before deleting?
        items.splice id, 1
        storage.set items, update
      else if className is 'edit'
        create "edit.html?index=#{id}&color=#{
            encodeURIComponent bg2rgb style.backgroundColor}&name=#{
            encodeURIComponent parentNode.querySelector('span').innerText}",
          screenX, screenY

document.querySelector '#add'
  .addEventListener 'click', ({screenX, screenY}) ->
    create "edit.html?color=#{encodeURIComponent pickNewColor (
        color for {color} in items)}", screenX, screenY
