var twitter = jetpack.lib.twitter
jetpack.future.import("slideBar");

jetpack.slideBar.append({
  onReady: function(slide) {
    $("input", slide.contentDocument.body).keyup(function(event) {
      var term = jQuery.trim( $(this).val().toLowerCase() );
      if ( term ) {
        jetpack.lib.twitter.search({
          q: term,
          rpp: 8,
          show_user: true,
          success: function (data, status) {
            var list = $("<ul></ul>", slide.contentDocument.body);
            $.each(data.results, function(i,tweet){
              // TODO: Parser les pseudos, les #tags, mettre en gras le mot récherché
              // TODO: Put a throbber to indicate activity
              // TODO: Ouvrir les liens dans l'onglet
              var tweetHtml =
                "<li>"
                +"<div class=\"avatar\"><a href=\"http://twitter.com/"+tweet.from_user+"\"><img src=\""+tweet.profile_image_url+"\" /></a></div>"              
                +"<div class=\"msg\"><a href=\"http://twitter.com/"+tweet.from_user+"\">"+tweet.from_user+"</a>: "+tweet.text+"</div>"
                +"<div class=\"info\">"+tweet.created_at+"</div>"
                +"</li>";
              $(list).append(tweetHtml);
            });
            $("#results", slide.contentDocument.body).children().remove();
            $("#results", slide.contentDocument.body).append(list);
          },
          error: function (xhr, errMsg, errObj) console.error(xhr.responseText)
        });
      } else {
        $("#results", slide.contentDocument.body).children().remove();
      }
    });
  },
  width: 400,
  persist: true,
  icon: "http://tb4.fr/labs/jetpack/veille/icon.png",
  html: <>
    <style><![CDATA[
    body {
      font-family:Helvetica,sans-serif;
      background: rgb(214, 221, 229);
      font-size:14px;
      line-height:17px;
    }
    input {
      width: 100%;
    }
    img {
      border: none;
    }
    ul {
      padding: 0;
    }
    li {
      list-style-type: none;
      border-bottom:1px dashed gray;
      margin:0;
      overflow:hidden;
      padding:15px 5px;
    }
    li div.avatar {
      float:left;
      height:48px;
      overflow:hidden;
      width:48px;
    }
    li .msg {
      margin-bottom:5px;
      margin-left:58px;
    }
    li .info {
      color:#777;
      font-size:13px;
      margin-left:58px;
    }
    li .source a {
      font-style:italic;
      text-decoration:none;
    }
    ]]></style>
    <body>
      <div><form id="search"><input type="text" /></form></div>
      <div id="results"></div>
    </body>
  </>
});