$(function() {
  $.getJSON("http://www.colourlovers.com/api/palettes/top?jsonCallback=?",
    { hueOption: "blue, violet", numResults: 10,
      orderCol: "numVotes", sortBy: "desc" },
    function(palettes) {
      $("#palettes").empty();
      $.each(palettes, function(i,palette) {
        var paletteEl = $("<div class='palette'></div>")
          .addClass("palette")
          .append("<a href='http://colourlovers.com/palette/"+palette.id+"/'>"
            +palette.title+"</a> ")
          .append(palette.numVotes + " votes")
          .appendTo($("#palettes"));
        $.each(palette.colors, function(i,color) {
          paletteEl.append(
             $("<div class='colorStrip'>&nbsp;</div>")
            .css("background", "#" + color)
            .click(function() { showColor(this, color); })
          );
        });
      });
    }
  );
});

function showColor(colorStrip, color) {
  $(colorStrip).html("Loading ...");
  $.getJSON(
    "http://www.colourlovers.com/api/color/"+color+"?jsonCallback=?",
    function(colors) {
      var color = colors[0];
      $(colorStrip).html(
      "<div class='colorDetail'>"
          + "<a href='" + color.url + "'>" + color.title + "</a>"
          + " Hex: #" + color.hex + ", "
          + " Hue: " + color.hsv.hue  + ", "
          + " Votes: " + color.numVotes
      +"</div>");
    }
  );
}
