var StockTwitsNetworkBar = {
  update_feed: function(url, callback, num) {
    var google_feed_url = window.location.protocol + "//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;

    if (num) {
      google_feed_url += "&num=" + num;
    }

    $.getJSON(google_feed_url, function(data) {
      callback.call(this, data.responseData.feed);
    });
  },
  
  load_feed: function(feed_url) {
    var self = this;
    
    this.update_feed(feed_url, function(feed) {
      if (!feed) {
        return false;
      }
      
      $(document).ready(function() {
        var ticker = $('#ticker');

        // Because load_feed is called periodically, clear headline timer and reset items to load a new
        // set without interupting current title being shown.
        if (feed.entries.length > 0) {
          if (self.headline_timer) { clearInterval(self.headline_timer); }
          self.items = [];
        }

        for(var i=0; i<feed.entries.length; i++) {
          var entry = feed.entries[i];
          
          // Truncate title if larger than 80 characters
          if (entry.title.length > 80) {
            entry.title = entry.title.substring(0, 80) + "..";
          } 
          
          self.items.push('<li><a href="' + entry.link + '" target="_new">' + entry.title + '</a></li>');
        }
      
        self.headline();
      });
    }, 20);
    
    // Update feed in 5 minutes (300000 milliseconds)
    setTimeout(function() {
      self.load_feed(feed_url);
    }, 300000);
  },
  
  
  pause: function() {
    this.paused = true;
    if (this.headline_timer) { clearInterval(this.headline_timer); }
  },
  
  resume: function() {
    this.paused = true;
    this.headline();
  },
  
  headline: function() {
    var self = this;

    var item = $(this.items[this.current_item]).show();
    $('#ticker').html(item);
  
    this.headline_timer = setTimeout(function() {
      item.fadeOut("slow", function() {
        self.current_item = ++self.current_item % self.items.length;
        self.headline();
      });
    }, 8000);
    
    return true;
  },

  load: function() {
    var self = this;
    var feed_title = $("<a></a>").addClass('tickerIcon');
    var feed_url;

    this.paused = false;
    this.items = [];
    this.current_item = 0;
    this.headline_timer = null;
    this.feed_timer = null;
    
    if (document.st_useNewsFeed) {
      feed_title.addClass('arNow').attr('href', 'http://abnormalreturns.com/').html('AR Now');
      feed_url = "http://abnormalreturns.com/link/index.rss";
    } else {
      feed_title.addClass('stNews').attr('href', 'http://stocktwits.com/').html('Updates');
      feed_url = "http://stocktwits.com/streams/suggested?rss=1";
    }
    
    this.load_feed(feed_url);
    
    var utm_params = "?utm_medium=networkbar&utm_campaign=networkbar&utm_source=" + document.domain;
    var template_host = window.location.protocol + "//stocktwits.com/";
    
    var template = '<div id="stocktwitsNetwork"> \
      <div class="networkContent"> \
        <div class="tickerWrapper"> \
          <div class="tickerBox"> \
            <p class="tickerTitle"> \
              AR Now \
            </p> \
            <ul id="ticker"> \
            </ul> \
          </div> \
        </div><!-- end tickerWrapper --> \
        <div class="networkNavigator"> \
          <div class="networkHeader"> \
            StockTwits Network \
          </div><!-- end networkHeader --> \
          <div style="display:none;" id="stNetworkLinks" class="networkLinks"> \
            <ul> \
              <li> \
                <a href="http://stocktwits.com/' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/stcom.png" alt="StockTwits.com" />StockTwits.com</a> \
              </li> \
              <li> \
                <a href="http://chart.ly/' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/chartly.png" alt="Chart.ly" />Chart.ly</a> \
              </li> \
              <li> \
                <a href="http://abnormalreturns.com/' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/ar.png" alt="Abnormal Returns" />Abnormal Returns</a> \
              </li> \
              <li> \
                <a href="http://stocktwits.com/store' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/store.png" alt="StockTwits Store" />StockTwits Store</a> \
              </li> \
              <li> \
                <a href="http://stocktwits.com/premium' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/stnet.png" alt="StockTwits.net" />Premium Blog Network</a> \
              </li> \
              <li> \
                <a href="http://stocktwits.tv/' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/sttv.png" alt="StockTwits TV" />StockTwits TV</a> \
              </li> \
            <li> \
              <a href="http://stocktwits.com/goodies' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/goodies.png" alt="StockTwits Goodies" />StockTwits Goodies</a> \
            </li> \
			<li> \
              <a href="http://www.stocktwitsu.com' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/stu.png" alt="StockTwits U" />StockTwits U</a> \
            </li> \
			<li> \
              <a href="http://stocktwits.com/ir' + utm_params + '"><img src="' + template_host + 'networkbar/images/networkicons/stir.png" alt="StockTwits IR" />StockTwits Investor Relations</a> \
            </li> \
            </ul> \
          </div><!-- end networkLinks --> \
        </div><!-- end networkNavigator --> \
      </div><!-- end networkContent --> \
    </div><!-- end networkNavigation -->\n';

    $('head, body').ready(function() {
      $('head').append('<link rel="stylesheet" type="text/css" href="' + template_host + 'networkbar/styles.css?1266873505" />');
      $('body').css('margin-top', '29px').append(template);
    });
    
    $(document).ready(function() {
      $('p.tickerTitle').html(feed_title);
      $('#ticker').hover(function() {
        self.pause();
      }, function() {
        self.resume();
      });

      $('#stocktwitsNetwork .networkHeader').click(function() {
        $('#stNetworkLinks').trigger('hide_or_show');
      });

      var _st_hoverTimer = null;

      $('#stNetworkLinks').hover(function() {
        if (_st_hoverTimer) { 
          clearInterval(_st_hoverTimer);
        }
      }, function() {
        var self = this;

        if (_st_hoverTimer) { 
          clearInterval(_st_hoverTimer);
        }

        _st_hoverTimer = setTimeout(function() {
          $(self).hide();
        }, 2000);
      });
      
      $('#stocktwitsNetwork .networkHeader').hover(function() {
        if (_st_hoverTimer) {
          clearInterval(_st_hoverTimer);
        }
        return false;
      }, function() {
        $('#stNetworkLinks').trigger('mouseleave');
        return false;
      });

      $('#stNetworkLinks').bind('hide_or_show', function() {
        if ($(this).is(':visible')) {
          $(this).hide();
        } else {
          $(this).show();
        }
      });
    });    
  }
};

StockTwitsNetworkBar.load();