const UPGRADED_URL = "http://clikball.com/upgrade_complete";
(function() {
   var t = Cc['@mozilla.org/consoleservice;1'].
     getService(Ci.nsIConsoleService);

   var log = function log(x) { t.logStringMessage(x); };

   function $(id) { return document.getElementById(id); }

   var prefs = Cc['@mozilla.org/preferences-service;1'].
     getService(Ci.nsIPrefService).getBranch('extensions.hfl.');


})();

Cu.import("resource://hfl/service.js");

var surferati =
  (new function() {

  Cu.import("resource://hfl/twitter.js");
  Cu.import("resource://hfl/friendfeed.js");
  Cu.import("resource://hfl/startup.js");

  function $(x) { return document.getElementById(x); }

  var CLOSED = 0;
  var SMALL = 1;
  var LARGE = 2;
  var desiredSize = CLOSED;

  var scrollboxTargetHeight = 0;
  var scrollboxStartHeight = 0;
  var totalTime = 120;
  var animationTime = 0;
  var interval = 20;
  var closeTimer = null;
  var closeDelay = 14 * 1000;

  var prefs = Cc['@mozilla.org/preferences-service;1'].
   getService(Ci.nsIPrefService).getBranch('extensions.hfl.');

  var cs = Cc['@mozilla.org/consoleservice;1'].
    getService(Ci.nsIConsoleService);

// XXX stevel_start
  this.alertSvc = Cc["@mozilla.org/alerts-service;1"]
    .getService(Ci.nsIAlertsService);
// XXX stevel_end

  var log = function log(x) { cs.logStringMessage(x); };

  function os() {
    return Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS;
  }

  function currentWin() {
    var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
               .getService(Ci.nsIWindowMediator);
    return wm.getMostRecentWindow("navigator:browser");
  };

  this.panelShown = function() {
    $('surferatiPost-comment').focus();
    surferati.twitterUpdate();
    $('tablist').selectedIndex = 0;
    $('surferatiPost-external-twitter').checked = hfl.checkPref('twitter-default', false);
    $('surferatiPost-external-friendfeed').checked = hfl.checkPref('friendfeed-default', false);
  };

  this.search = function(text) {
    if (text.length < 3) {
      this.updateNotification();
      return false;
    }

    function onSuccess(items) {
      var self = this;
      var list = $("surferatiScrollboxList");

      while (list.childNodes.length > 0) {
        list.removeChild(list.firstChild);
      }
      $('surferatiScrollboxList').removeAttribute('debug');
      if (items.length == 0) {
        try {
          var noResults = document.createElement('label');
          noResults.setAttribute('value', "No results where found.");
          $('surferatiScrollboxList').appendChild(noResults);
        } catch (ex) {
          //alert(ex);
        }

      }

      for (var i=0; i<items.length; ++i) {
        try {
          var noti = document.createElement("surferatiNotification");
          var aLink = items[i];
          surferati.setLinkAtttributes(noti, aLink);
          list.appendChild(noti);
        } catch (ex) {
          alert(ex);
        }
        //if (list.childNodes.length == 0) list.appendChild(noti);
        //else list.insertBefore(noti, list.firstChild);
      }

      resizePanelTo(desiredSize);
    }
    function onError() {

    }
    hfl.search(text, onSuccess, onError)
  };

  this.populateFollowersDropDown = function() {
    var list = document.getElementById('followersList');
    while (list.childNodes.length > 0) {
      list.removeChild(list.lastChild);
    }
    function onSuccess(aData) {
      while (list.childNodes.length > 0) {
        list.removeChild(list.lastChild);
      }
      for(var i=0; i<aData.length; i++) {
        var listitem = document.createElement('listitem');
        listitem.setAttribute('label', aData[i].user.name);
        listitem.setAttribute('value', aData[i].user.id);
        list.appendChild(listitem);
      }
    }
    function onError(aResp) {
      log(aResp);
    }
    $("surferatiPost-SendButton").disabled = true;
    hfl.getFollowers(onSuccess, onError);
  };

  this.panelSend = function() {
    var radios = $("surferatiPost-lists");
    var url = $('surferatiPost-url').value;
    var title = $('surferatiPost-title').value;
    var comment = $('surferatiPost-comment').value;
    var receiver_id = null;
    var tabbox = $('tablist');

    var single_receiver = (tabbox.selectedIndex == 1);
    if (single_receiver) {
      receiver_id = $("followersList").selectedItem.value;
    } else {
      var user_id = $("surferatiPost-lists").selectedItem.getAttribute("user_id");
      var group_id = $("surferatiPost-lists").selectedItem.getAttribute("group_id");
    }

    function addStatus(aMsg) {
      while ($("surferatiPost-progress").childNodes.length) {
        $("surferatiPost-progress").removeChild($("surferatiPost-progress").firstChild);
      }
      var newDesc = document.createElement("description");
      newDesc.appendChild(document.createTextNode(aMsg));
      $("surferatiPost-progress").appendChild(newDesc);
    }

    function onSuccess() {
      addStatus("Finished Posting!");
      setTimeout(surferati.closePanel, 1000);
    }

    function onProgress(aPhase, aServiceName) {
      if (aPhase == "starting") {
        addStatus("Trying to post link to: " + aServiceName);
      }
      else {
        addStatus("Posted link to: " + aServiceName);
      }
      //alert("posted to " + aServiceName);
    }

    function onError(aServiceName) {
      //alert("Error posting to " + aServiceName);
      addStatus("Error posting to: " + aServiceName + ". Please verify that your  " + aServiceName + " login and password are correct.");
      setTimeout(surferati.closePanel, 3000);
    }

    var external_services = [];
    if (twitter.active() && $("surferatiPost-external-twitter").checked) {
      external_services.push("twitter");
    }
    if (friendfeed.active() && $("surferatiPost-external-friendfeed").checked) {
      external_services.push("friendfeed");
    }

    $('surferatiPost-deck').selectedIndex = 1;
    hfl.postClikball(url, title, comment, group_id, receiver_id, external_services, onSuccess, onProgress, onError);


    // FIXME: provide visual notification that the notification was sent
  };

  this.twitterUpdate = function() {
    $('surferatiPost-external-twitter').removeAttribute('class');
    if ($('surferatiPost-external-twitter').checked) {
      var chars_left = twitter.maxCharacters() - $('surferatiPost-comment').value.length;
      if (chars_left <= 0) {
        chars_left = 0;
        $('surferatiPost-external-twitter').setAttribute('class', 'error');
      }
      $('surferatiPost-external-twitter').setAttribute('label', 'Twitter (' +  chars_left + ' left)');
    } else {
      $('surferatiPost-external-twitter').setAttribute('label', 'Twitter');
    }
  };

  this.postInlineComment = function() {
    var textbox = $("surferatiComments-textbox")
    var button = $("surferatiComments-post")
    if (textbox.disabled) return;
    var clikball_id = this.selectedCBID;
    var title = this.selectedTitle;
    var group_id = this.selectedGroupId;
    var receiver_id = this.selectedReceiverId;
    if (receiver_id == hfl.USER_ID) {
      receiver_id = this.selectedUserId;
    }
    var url = this.selectedUrl;
    var comment = textbox.value;
    function onSuccess() {
      textbox.disabled = false;
      textbox.reset();
    }

    function onError() {
      textbox.disabled = false;
      //alert("error");
    }
    textbox.disabled = true;
    button.disabled = true;

    hfl.postComment(clikball_id, comment, onSuccess, onError);
  }

  this.closePanel = function() {
    $('surferatiPost-deck').selectedIndex = 0;
    $('surferatiPost').hidePopup();
    //$('surferatiPost-deck').selectedIndex = 1;
  };

  this.showLogin = function(event) {
    openUILinkIn('http://www.clikball.com/welcome', 'tab');
  };

  this.showUpgrade = function(event) {
    openUILinkIn('http://www.clikball.com/upgrade', 'tab');
  };

  this.showOptionsPanel = function() {
    window.openDialog('chrome://hfl/content/options.xul', 'clikballOptions', 'centerscreen,chrome,modal');
    return false;
  };

  this.onFollowerSelected = function(aObj) {
    $("surferatiPost-SendButton").disabled = false;
  };

  this.currentUrl = "";
  this.currentTitle = "";

  this.setupCurrentLink = function(event) {
    this.currentUrl = gBrowser.selectedBrowser.webNavigation.currentURI.spec;
    this.currentTitle = gBrowser.selectedBrowser.contentWindow.document.title;
    this.currentHeading = "Post a link to cliKball:"
  };

  this.setupLink = function(aLink, aTitle) {
    this.currentUrl = aLink;
    this.currentTitle = aTitle;
    this.currentHeading = "Comment on this link:";
  };

  this.showPanel = function(event) {
      if (hfl.NEED_UPGRADE) {
        surferati.showUpgrade();
        return;
      }
      if (!hfl.getLoginState()) {
        surferati.showLogin();
        return;
      }

      if (twitter.active() || friendfeed.active()) {
        $("surferatiPost-external-list").hidden = false;
        $("surferatiPost-external-setup").hidden = true;
        $("surferatiPost-external-twitter").hidden = !twitter.active();
        $("surferatiPost-external-friendfeed").hidden = !friendfeed.active();
      }
      else {
        $("surferatiPost-external-setup").hidden = false;
        $("surferatiPost-external-list").hidden = true;
      }

      var panel =  $("surferatiPost");
      var tabbox = $('tablist');
      //tabbox.selectedIndex = 0;
      $('surferatiPost-url').value = this.currentUrl;
      $('surferatiPost-title').value = this.currentTitle;
      $('surferatiPost-heading').value = this.currentHeading;
      $('surferatiPost-comment').reset();

      var rows = $('radioItems');
      while (rows.childNodes.length > 0) {
        rows.removeChild(rows.lastChild);
      }
      for (var i=0; i< hfl.LISTS.length; ++i) {
        var list = hfl.LISTS[i];
        if (i%2==0) {
          var row = document.createElement("row");
        } else {
          row = rows.lastChild;
        }

        rows.appendChild(row);
        var radio = document.createElement("radio");

        var count = list.memberships_count;
        if (i == 0) {
          radio.setAttribute("selected", true);
        }
        radio.setAttribute("label", list.name + " (" + count + ")");
        radio.setAttribute("user_id", list.user_id);
        radio.setAttribute("group_id", list.group_id);
        row.appendChild(radio);
      }
      panel.openPopup(null, 'after_start', document.width/2 - 200, 100);
  };

  this.closeNotifications = function() {
    surferati.hideDrilldown();
    resizePanelTo(CLOSED);
  };

  this.updateStats  = function(stats) {
    if (!stats) return;
    if (stats.fans_count != undefined) {
      $("broadcaster_clicksCount").setAttribute('value', stats.clicks_count + " Cliks");
      $("broadcaster_fansCount").setAttribute('value', stats.fans_count + " Followers");
    }
  };

  this.setLinkAtttributes  = function(aObj, aItem) {
    aObj.setAttribute("id", aItem.id);
    aObj.setAttribute("clikball_id", aItem.clikball_id);
    aObj.setAttribute("kind", aItem.kind);
    aObj.setAttribute("url", aItem.url);
    aObj.setAttribute('avatar', aItem.avatar);
    aObj.setAttribute('username', aItem.username);
    aObj.setAttribute('profile_url', aItem.profile_url);
    aObj.setAttribute('url_id', aItem.url_id);
    aObj.setAttribute('comments_count', parseInt(aItem.comments_count));
    aObj.setAttribute('user_id', aItem.user_id);
    aObj.setAttribute('group_url', aItem.group_url);
    aObj.setAttribute('group_name', aItem.group_name);
    aObj.setAttribute('group_id', aItem.group_id);
    aObj.setAttribute('receiver_id', aItem.receiver_id);
    aObj.setAttribute('receiver_username', aItem.receiver_username);
    aObj.setAttribute('receiver_profile_url', aItem.receiver_profile_url);
    aObj.setAttribute('sent_at', aItem.sent_at);
    aObj.setAttribute('comment', aItem.comment);
    aObj.setAttribute('title', aItem.title);
    aObj.setAttribute('clicks_count', aItem.clicks_count);
    aObj.setAttribute('cluster_id', aItem.cluster_id);
    aObj.setAttribute('cluster_size', aItem.cluster_size);
    aObj.setAttribute('clustered_by_url', aItem.clustered_by_url);
    aObj.setAttribute('original_poster_username', aItem.original_poster_username);
    aObj.setAttribute('original_poster_avatar', aItem.original_poster_avatar);
    aObj.setAttribute('original_poster_profile', aItem.original_poster_profile);
    aObj.setAttribute('original_poster_comment', aItem.original_poster_comment);
  };

  this.updateNotification = function() {
    var list = $("surferatiScrollboxList");
    while (list.childNodes.length > 0) {
      list.removeChild(list.firstChild);
    }
    var items = hfl.getRecent();

    for (var i=0; i<items.length; ++i) {
      var noti = document.createElement("surferatiNotification");
      var aLink = items[i];
      this.setLinkAtttributes(noti, aLink);
      list.appendChild(noti);
    }

    resizePanelTo(desiredSize);
    function hackbs() {
      for (var i=0;i<items.length;++i) {
        var n = nodes[i];
        n.setLink(items[i]);
      }
    }
  };

  function getHeightForTime(aTime) {
    var factor = 1 - (aTime / totalTime);
    var diff = scrollboxTargetHeight - scrollboxStartHeight;
    return scrollboxTargetHeight - (factor * factor * diff);
  };

  function hideNotification() {
    resizePanelTo(CLOSED);
  };

  function animateNotification() {
    var scrollbox = $("surferatiScrollbox");
    animationTime += interval;
    if (closeTimer) {
      window.clearTimeout(closeTimer);
      closeTimer = null;
    }
    if (animationTime < totalTime) {
      if (scrollbox.boxObject.height < scrollboxTargetHeight) {
        scrollbox.height = getHeightForTime(animationTime);
        window.setTimeout(animateNotification, interval);
      }
      else if (scrollbox.boxObject.height > scrollboxTargetHeight) {
        scrollbox.height = getHeightForTime(animationTime);
        window.setTimeout(animateNotification, interval);
      }
      return;
    }
    if (desiredSize == SMALL) {
      closeTimer = window.setTimeout(hideNotification, closeDelay);
    }
    else {
      if (surferati.isDrillDownShowing()) {
        $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-none;");
      }
      else {
        $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-vertical;");
      }
    }
    scrollbox.height = scrollboxTargetHeight;
  };

  function resizePanelTo(aSize) {
    var panel = $("surferatiNotification");
    var scrollbox = $("surferatiScrollbox");
    if (aSize == CLOSED) {
      scrollbox.height = 1;
      $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-none;");
    }
    else {
      var reset = false;
      if (desiredSize == CLOSED) {
        var bottombox = $("browser-bottombox");
        panel.openPopup(bottombox, 'before_end', -20);
        reset = true;
      }
      if (aSize == SMALL) {
        scrollToStart();
        $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-none;");
        setupAnimation(reset, scrollbox.boxObject.height, getSingleHeight());
      }
      if (aSize == LARGE) {
        setupAnimation(reset, scrollbox.boxObject.height, getFullHeight());
      }
      animateNotification();
    }

    desiredSize = aSize;
    if (desiredSize == LARGE) {
      $("surferatiScrollboxHeader-more").setAttribute("hidden", true);
      $("surferatiScrollboxHeader-less").removeAttribute("hidden");
    }
    else {
      $("surferatiScrollboxHeader-less").setAttribute("hidden", true);
      $("surferatiScrollboxHeader-more").removeAttribute("hidden");
    }
  };

  this.openLink = function(aEvent, aHref) {
    var where = whereToOpenLink(aEvent);
    if (!hfl.checkPref("behavior.openInCurrentWindow")) {
      where = 'tab';
    }
    openUILinkIn(aHref, where);
  };

  this.hideMostNotifications = function(event) {
    surferati.hideDrilldown();
    resizePanelTo(SMALL);
  };

  this.showAllNotifications = function(event) {
    resizePanelTo(LARGE);
  };

  function setupAnimation(aReset, aStartHeight, aTargetHeight) {
    if (aReset) {
      $("surferatiScrollbox").height = 0;
    }
    animationTime = 0;
    if (os() == "Darwin") animationTime = totalTime/2;
    scrollboxStartHeight = aStartHeight;
    scrollboxTargetHeight = aTargetHeight;
  };

  function getSingleHeight(event) {
    var header = $("surferatiScrollboxHeader");
    var firstNotification = $("surferatiScrollboxList").firstChild;
    if (!firstNotification) return 0;
    return firstNotification.boxObject.height + header.boxObject.height;
  };

  function scrollToStart() {
    try {
      var scrollbox = $("surferatiScrollboxList");
      var xpcomInterface
            = scrollbox.boxObject.QueryInterface(Ci.nsIScrollBoxObject);
      xpcomInterface.scrollTo(0,0);
    } catch(e) {}
  };

  function getFullHeight(event) {
    return 450;
  };

  this.notificationShown = function(event) {
    resizePanelTo(desiredSize);
//    document.commandDispatcher.focusedElement.focus();
  };

  this.onPotentialComment = function(item) {
    var comments = $("surferatiComments-scroll");
    if (this.selectedCBID) {
      if (this.selectedMode == "comment") {
        if (item.clikball_id == this.selectedCBID) {
          surferati.onNewComment(item);
        }
      }
      else {
        if (this.selectedUserId + '' == item.user_id + '') {
          surferati.onNewComment(item);
        }
      }
    }
  };

  this.selectedCBID  = null;
  this.selectedUrlId = null;
  this.selectedUserId = null;
  this.selectedClusteredByUrl = null;
  this.selectedTitle = null;
  this.selectedUrl = null;
  this.selectedByCommentButton = false;
  this.selectedGroupId = 0;
  this.selectedGroupName = 0;
  this.selectedGroupUrl = 0;
  this.selectedMode = 'link'; // or comment

  this.isDrillDownShowing = function() {
    return surferati.selectedCBID != null;
  };

  this.maybePostDrilldownClick = function() {
    if (this.selectedCBID && this.selectedMode == "comment") {
      hfl.postClick(this.selectedKind, this.selectedId, this.selectedCBID);
    }
  };

  this.showUserLinks = function(aObj, aClusterOnly) {
    $("surferatiPrivacy").hidden = true;
    this.selectedMode = 'link';
    this.selectedByCommentButton = false;
    $('surferatiDrilldownClusterHeading-username').setAttribute('value', aObj.getAttribute('username'));
    $('surferatiDrilldownClusterHeading-username').setAttribute('href', aObj.getAttribute('profile_url'));
    $('surferatiDrilldownClusterHeading').hidden = false;
    surferati.loadCurrentCluster(aClusterOnly);
  };

  this.updateCommentButton = function() {
    var tb = $("surferatiComments-textbox");
    var button = $("surferatiComments-post");

    if (tb.value.length == 0) {
      button.disabled = true;
    }
    else {
      button.disabled = false;
    }
  };

  function setDescription(aObject, aVal) {
    while (aObject.childNodes.length > 0) {
      aObject.removeChild(aObject.firstChild);
    }
    aObject.appendChild(document.createTextNode(aVal));
  }

  this.showComments = function(aObj) {
    this.selectedMode = 'comment';
    $('surferatiComments-new').hidden = false;
    $("surferatiComments-textbox").reset();
    $("surferatiDrilldown").removeAttribute('isGroup');
    $("surferatiDrilldown").removeAttribute('isPrivate');

    if(this.selectedReceiverId) {
      $("surferatiDrilldown").setAttribute('isPrivate', true);
      $("surferatiComments-post").setAttribute("label", "Send");
    }
    else if(this.selectedGroupId > 0) {
      $("surferatiDrilldown").setAttribute('isGroup', true);
      $("surferatiComments-post").setAttribute("label", "Send");
    }

    if (this.selectedGroupId) {
      $("surferatiPrivacy-image").setAttribute("class", "group-image");
      $("surferatiPrivacy").hidden = false;
      $("surferatiPrivacy-label").value = "These comments are private within: ";
      $("surferatiPrivacy-sentto").setAttribute("value", this.selectedGroupName);
      $("surferatiPrivacy-sentto").setAttribute("href", this.selectedGroupUrl);
    }
    else if (this.selectedReceiverId) {
      $("surferatiPrivacy-image").setAttribute("class", "lock-image");
      $("surferatiPrivacy").hidden = false;
      $("surferatiPrivacy-label").value = "This is a private conversation.";
      $("surferatiPrivacy-sentto").setAttribute("value", "");
    }
    else {
      $("surferatiPrivacy").hidden = true;
    }

    $("surferatiComments-new").removeAttribute("hidden");

    var link = $("surferatiDrilldownCommentsHeading-link");
    setDescription(link, aObj.getAttribute('title'));
    link.setAttribute("href", aObj.getAttribute("url"));

    this.loadComments(this.selectedCBID);
    this.updateCommentButton();

    $('surferatiDrilldownCommentsHeading').hidden = false;
    $('surferatiDrilldownCommentsHeading-avatar').setAttribute('src', aObj.getAttribute('original_poster_avatar'));
    $('surferatiDrilldownCommentsHeading-avatar').setAttribute('href', aObj.getAttribute('original_poster_profile'));

    $('surferatiDrilldownCommentsHeading-username').setAttribute('value', aObj.getAttribute('original_poster_username'));
    $('surferatiDrilldownCommentsHeading-username').setAttribute('href', aObj.getAttribute('original_poster_profile'));
    setDescription($('surferatiDrilldownCommentsHeading-comment'), aObj.getAttribute('original_poster_comment'));
  };

  this.showDrilldown = function(aObj, aSelectedByCommentButton, aShowUser) {
    $('surferatiDrilldownCommentsHeading-username').setAttribute('value', aObj.getAttribute('original_poster_username'));
    $('surferatiDrilldownCommentsHeading-username').setAttribute('href', aObj.getAttribute('original_poster_profile'));
    setDescription($('surferatiDrilldownCommentsHeading-comment'), aObj.getAttribute('original_poster_comment'));
  };

  this.showDrilldown = function(aObj, aSelectedByCommentButton, aShowUser) {
    $("surferatiNotification-search").hidden = true;
    $("surferatiComments-new").hidden = true;
    this.commentClickCount = 0;
    $("surferatiComments-macerror").setAttribute("hidden", true);
    this.showAllNotifications();
    this.selectedObj = aObj;
    this.selectedCBID = aObj.getAttribute("clikball_id");
    this.selectedKind = aObj.getAttribute("kind");
    this.selectedId = aObj.getAttribute("id");
    this.selectedUrlId    = parseInt(aObj.getAttribute("url_id"));
    this.selectedUserId = aObj.getAttribute("user_id");
    this.selectedUsername = aObj.getAttribute("username");
    this.selectedClusteredByUrl = aObj.getAttribute("clustered_by_url");
    this.selectedClusterId = aObj.getAttribute("cluster_id");
    this.selectedTitle = aObj.getAttribute("title");
    this.selectedUrl = aObj.getAttribute("url");
    this.selectedGroupUrl = aObj.getAttribute("group_url");
    this.selectedGroupName = aObj.getAttribute("group_name");
    this.selectedGroupId = parseInt(aObj.getAttribute("group_id"));
    this.selectedReceiverId = parseInt(aObj.getAttribute("receiver_id"));
    this.selectedByCommentButton = aSelectedByCommentButton;

    $("surferatiScrollboxList").setAttribute("maxheight", 0);
    $("surferatiDrilldown").setAttribute("maxheight", 400);
    $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-none;");
    $("surferatiComments-scroll").setAttribute("style", "overflow: -moz-scrollbars-vertical;");

    $('surferatiDrilldownClusterHeading').hidden = true;
    $('surferatiDrilldownCommentsHeading').hidden = true;
    if (aShowUser) {
      this.showUserLinks(aObj, false);
    }
    else if (this.selectedClusteredByUrl == 'true' || this.selectedByCommentButton) {
      this.showComments(aObj);
    }
    else {
      this.showUserLinks(aObj, true);
    }


  };

  this.loadComments = function(aClikballId) {
    var comments = $("surferatiComments-scroll");
    function onSuccess(aComments) {
      for (var i=0;i<aComments.length;++i) {
        surferati.onNewComment(aComments[i]);
      }
    }
    function onError() {
      alert("error loading comments");
    }
    while (comments.childNodes.length > 0) {
      comments.removeChild(comments.lastChild);
    }
    hfl.loadComments(aClikballId, onSuccess, onError);
  };

  this.loadCurrentCluster = function(aComments) {
    var comments = $("surferatiComments-scroll");
    function onSuccess(aComments) {
      try {
        for (var i=0;i<aComments.length;++i) {
          surferati.onNewComment(aComments[i]);
        }
      }
      catch(e) {
        alert(e);
      }
    }
    function onError() {
      alert("error loading comments");
    }
    while (comments.childNodes.length > 0) {
      comments.removeChild(comments.lastChild);
    }
    if (aComments) {
      hfl.loadCluster(surferati.selectedClusterId, onSuccess, onError);
    }
    else {
      hfl.loadRecent(surferati.selectedUserId, onSuccess, onError);
    }
  };

  this.hideDrilldown = function(event) {
    $("surferatiNotification-search").hidden = false;
    this.selectedCBID  = null;
    this.selectedUrlId = null;
    this.selectedUserId  = null;
    this.selectedClusteredByUrl  = null;
    $("surferatiScrollboxList").setAttribute("maxheight", 400);
    $("surferatiDrilldown").setAttribute("maxheight", 0);
    $("surferatiScrollboxList").setAttribute("style", "overflow: -moz-scrollbars-vertical;");
    $("surferatiComments-scroll").setAttribute("style", "overflow: -moz-scrollbars-none;");
  };

  this.statusClick = function(event) {
    if (hfl.NEED_UPGRADE) {
      surferati.showUpgrade();
      return;
    }
    if (!hfl.getLoginState()) {
      surferati.showLogin();
/*
      if (hfl.checkPref("firstrun.dontshow", false) != true) {
       surferati.openFirstRun();
      } else {
        surferati.showLogin();
      }
*/
      return;
    }
    if (desiredSize == LARGE) {
      resizePanelTo(CLOSED);
    }
    else {
      surferati.hideDrilldown();
      surferati.updateNotification();
      resizePanelTo(LARGE);
    }
  };

  this.onNewComment = function(item) {
    log( "ON NEW COMMENT");
    var comments = $("surferatiComments-scroll");
    if (surferati.selectedMode == 'link') {
      item.clustered_by_url = false;
    }
    else {
      if (item.clikball_id != surferati.selectedCBID) {
        return;
      }
      item.clustered_by_url = true;
    }

    var comment = document.createElement("surferatiComment");
    this.setLinkAtttributes(comment, item);


    if (surferati.selectedMode == 'comment') {
      comment.setAttribute("hide_title", true);
    }

    comments.appendChild(comment);

    var xpcomInterface
        = comments.boxObject.QueryInterface(Ci.nsIScrollBoxObject);
    xpcomInterface.ensureElementIsVisible(comment);
  };

  this.onNewItem = function(item) {
    var disabled = hfl.checkPref('notifications.disabled', false);
// XXX stevel_start
    dump("\n================================================\n");
    dump("New notification: " + item.username + " // " + item.title + "\n");
	dump("mode: " + this.selectedMode + "\n");
	var notificationText;
	if (this.selectedMode == "link") {
	  notificationText = item.username + " posted a new item: " +
		  item.title + "\n" + item.comment;
	} else {
	  notificationText = item.username + " posted a new comment on: " +
		  item.title + "\n" + item.comment;
	}
	dump(notificationText + "\n");
    try {
	  surferati.alertSvc.showAlertNotification(
			  "chrome://hfl/skin/icon-24.png",
			  "new cliKball item!",
			  notificationText);
	} catch (e) {
	  dump("Failed to make notification: " + e + "\n");
	}
    dump("================================================\n\n");
// XXX stevel_end
    if ((currentWin() == top) && !disabled) {
      surferati.updateNotification();
      if (desiredSize == LARGE) {
        resizePanelTo(LARGE);
      }
      else {
        resizePanelTo(SMALL);
      }
    }
    else if (desiredSize != CLOSED) {
      surferati.updateNotification();
    }

    this.onPotentialComment(item);
  };

  // stats.clicks_count, newStats.fans_count
  this.onNewStats = function(stats) {
    surferati.updateStats(stats);
  };

  this.onAuthChange = function(isLoggedIn) {
    if(isLoggedIn) {
      $('broadcaster_loginMessage').setAttribute('value', '');
    } else {
      $('broadcaster_loginMessage').setAttribute('value', 'Click to login.');
      $('broadcaster_fansCount').setAttribute('value', '');
      $('broadcaster_clicksCount').setAttribute('value', '');
      resizePanelTo(CLOSED);
    }
    if (hfl.NEED_UPGRADE) {
      $('broadcaster_loginMessage').setAttribute('value', 'Please Upgrade cliKball');
    }
  };

  this.commentClickCount = 0;
  this.focusHack = function(aObj) {
    if (os() == "Darwin") {
      if (++this.commentClickCount % 2 == 0) {
        $("surferatiComments-macerror").removeAttribute("hidden");
      }
    }
  };

  this.extensionUpdatedObserver = {
    observe: function(subject, topic, data) {
        subject.QueryInterface(Components.interfaces.nsIUpdateItem);
        if(topic == 'em-action-requested') {
          if (data == "item-installed") {
          }
          if (data == "item-upgraded") {
            prefs.setBoolPref('upgraded', true);
          }
        }
      }
  };

  this.observerService = Cc["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);


  function uninit() {
    // FIXME: do we need to remove the unload listener since the window is unloading?
    hfl.removeListener(surferati);
    surferati.observerService.removeObserver(surferati.extensionUpdatedObserver, "em-action-requested");
    window.removeEventListener('load', init, false);
    window.removeEventListener("unload", uninit, false);
  }

  function init() {
    var panel = $("surferatiNotification");
    panel.addEventListener("click", function(aEvent) {
      aEvent.stopPropagation();
      aEvent.preventBubble();
    }, false);
    surferati.observerService.addObserver(surferati.extensionUpdatedObserver, "em-action-requested", false);
    hfl.addListener(surferati);
    hfl.bootstrap(surferati);
    surferati.onNewStats(hfl.LAST_STATS);

    // Thanks to loucypher for this context menu code!
    var context = $("contentAreaContextMenu");
    context.addEventListener("popupshowing", function(aEvent) {
      // using global object 'gContextMenu'
      // see http://mxr.mozilla.org/seamonkey/source/browser/base/content/nsContextMenu.js
      // only show context menu item when right click on a link
      // and if the link protocol is valid, e.g. not 'javascript:' link
      if (hfl.getLoginState()) {
        var reg = /^https?|^ftp/i;
        gContextMenu.showItem("surferatiContextLink", gContextMenu.onLink && reg.test(gContextMenu.linkProtocol));
      }
    }, false);


    startup.runchecks();
  }
  // fixme this should be on window onload
  window.addEventListener('load', init, false);
  window.addEventListener("unload", uninit, false);
});



