jQuery(function(){
  if (jQuery('#news-items').length > 0) {
    jQuery("<div/>").attr("id", "news-item").appendTo("#news-items");
    jQuery.getJSON("/news_items.json", null, function(data) {
      headlines = jQuery.map(data, function(val, i) {
        return val.headline
      });
      jQuery("#news-item").newsRotator({ "headlines" : headlines, "url" : "/news_items" });
    });
  }
});


(function($) {
  $.fn.newsRotator = function(settings) {
    var config = { 'headlines': null, "url" : null };
    var next = null
    if (settings) $.extend(config, settings);
    var spinner = function(container, headlines, next) {
      if (headlines.length == 0) return
      if (next == null || next >= headlines.length) next = 0
      $(container).fadeOut("normal", function() {
        headline = $("<a/>").attr("href", "javascript:void(0);").click(function(){loadPage(config.url);}).html(headlines[next])
        $(this).html(headline).fadeIn("normal", function() {
          if (headlines.length > 1) {
            $(this).animate({opacity: 1.0}, 5000, function() {
              spinner(container, headlines, next + 1)
            })
          }
        })
      })
    }
    this.each(function() {
      spinner(this, config.headlines)
    });
    return this;
  };
})(jQuery);
