/*
  @author: Jesse Andrews
  @email: anotherjesse@gamil.com
  @url: http://overstimulate.com
  @update: http://userscripts.org/jetpacks/1.js
  @title: Userscripts.org Message Status
  @description: Check if you have private messages on userscripts.org
  @version: 0.1

  Based on: http://jetpacks.benji-banned.ch/ by Benjamin Auer
*/


function USO() {}

USO.prototype = {
  open: function() {
    jetpack.tabs.open("http://userscripts.org/messages");
    jetpack.tabs[jetpack.tabs.length-1].focus();
  },

  notify: function(msg) {
    jetpack.notifications.show({
      title: "Userscripts.org",
      body: msg,
      icon: "http://userscripts.org/images/script_icon.png"
    });
  },

  update: function(doc) {
    var inst = this;
    doc = $(doc);
    $.ajax({
      type: "GET",
      url: inst.url,
      dataType: "xml",
      async: false,
      success: function(xml) {
        var count = parseInt($(xml).find('unread').text());
        if (count > inst.count) {
          inst.notify('New Messages! ('+(count-inst.count)+')');
        }
        inst.count = count;
        $(doc).find("#count").html(count);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {}
    });
  },
  count: 0,
  url: "http://userscripts.org/messages.xml"
};

jetpack.statusBar.append({
  html: <>
    <img src="http://userscripts.org/images/script_icon.png" style="margin-top: 2px" />
    <span id="count" style="font-weight:bold;font-size:10px;width:30px"></span>
    </>,
  width: 30,

  onReady: function (doc) {
    var uso = new USO(doc);
    $(doc).find("*").css({cursor:"pointer"});
    $(doc).click(function() { uso.open(); });
    uso.update(doc);
    setInterval( function() { uso.update(doc); }, 60*1000 );
  }
});