// JavaScript Document
// Author: Andy Asberry, Ciphertek Systems, LLC
// Date: August 2010

$(document).ready(function() {

  var NEWSFLASH = {
	newsItems: null,
	numItems: 0,
	place: 0,
	fadeInLen: 2000,
	fadeOutLen: 300,
	interval: 12000,
	timer: null,
	setup: function() {
	  var NF = NEWSFLASH;
	  $.ajax({
		type: 'GET',
		url: '/ajax_assets/getNews.php',
		dataType: 'json',
		success: function(json) {
			NF.newsItems = json.newsItems;
			NF.numItems = json.newsItems.length;
			NF.place = 0;
			if (NF.numItems > 1) {
              NF.timer = setInterval(function() { NF.rotate() }, NF.interval);
			}
		}
	  });
	  $('#news_flash div').hover(
		 function(e) {
		   e.stopPropagation();
		   if (NF.numItems > 1) {
		     clearInterval(NF.timer);
			 $(this).css('cursor', 'progress');
		   }
		 },
		 function(e) {
		   e.stopPropagation();
		   if (NF.numItems > 1) {
		     NF.rotate();
		     NF.timer = setInterval(function() { NF.rotate() }, NF.interval);
			 $(this).css('cursor', 'auto');
		   }
		 }
	  );
	},
	rotate: function() {
		var NF = NEWSFLASH;
		NF.place++;
		if (NF.place >= NF.numItems) {
		  NF.place = 0;	
		}
		$('#news_flash div').fadeOut(NF.fadeOutLen, function() {
		   var title = NF.newsItems[NF.place].title + ' - <span>' + NF.newsItems[NF.place].date + '</span>';
		   var article = NF.newsItems[NF.place].article;
		   $(this).children('h4').html(title);
		   $(this).children('p').html(article);
		   $(this).fadeIn(NF.fadeInLen);
		});
	}	
  };
  
  NEWSFLASH.setup();

});
