// JavaScript Document
// DOCUMENT NAME:	el-latest-news-script.js
// DESCRIPTION:		This script will generate the latest news displayed on the 
//					homepage for the Eagle Lake Website. The script retrieves
//					the information using JSON from dapper.com. The information 
//					then displayed on the page one item at a time with a fade (in out)
//					transition.

//Class to control the latest news
EL_LatestNews = function(itemCount){
	//PROPERTIES
	
	//stores data from dapper
	this.items = new Array();
	//total number of items
	this.itemCount = itemCount;
	//current element
	this.currentItem = 0;
	//timer for animations
	this.timer = "";
	
	
	//METHODS
	
	//initializing method
	this.init = function(){
		var ele = this;
		ele.addHTMLElements();
		ele.getNews();
		ele.setMouseOverEvents();
	}
	
	//retrieves the data
	this.getNews = function(){
		var ele = this;
		$.ajax({
			url: "http://www.dapper.net/transform.php?dappName=EagleLakeCampNews&transformer=JSON&extraArg_callbackFunctionWrapper=?&applyToUrl=http%3A%2F%2Fwww.navigators.org%2Fus%2Fministries%2Feaglelake%2Fnews",
			dataType: "jsonp",
			success: function(data){
				$.each(data.fields.Title, function(i,itemObj){
					if ( i > (ele.itemCount - 1) ) return false;
					var tempArray = [itemObj.href, itemObj.value];
					ele.items.push(tempArray);
				});
				ele.fadeStoryIn(ele.items[0][1], ele.items[0][0], 0);
			}
		});
	}
	
	//adds HTML elements to display news
	this.addHTMLElements = function(){
		$("#social_links").after('<a href="" style="text-decoration: none;"><div id="latestNewsContainer" style="text-decoration: none;"><h4 style="text-decoration: none;">Latest News</h4><p style="text-decoration: none;"></p><div class="bottomCap"></div></div></a>');
	}
	
	//fades story in
	this.fadeStoryIn = function(title, href){
		var ele = this;
		$("#latestNewsContainer").parent().attr("href", href);
		$("#latestNewsContainer p").css("display", "none").html(title).fadeIn('fast',function(){
			ele.startTimer();
		});
	}
	
	//fades story out
	this.fadeStoryOut = function(callback){
		$("#latestNewsContainer p").fadeOut('fast', callback);
	}
	
	//starts timer
	this.startTimer = function(){
		var ele = this;
		var nextItem = parseInt(ele.currentItem + 1);
		if(nextItem >= ele.itemCount){
			nextItem = 0;
		}
		var title = "";
		var href = "";
		$.each(ele.items, function(i, itemObj){
			if(i == nextItem){
				title = itemObj[1];
				href = itemObj[0];
			}
		});
		ele.currentItem = nextItem;
		ele.timer = setTimeout(function(){
			ele.fadeStoryOut(function(){
				ele.fadeStoryIn(title, href);
			});
		}, 5000);
	}
	
	//set mouseover events for timer pause
	this.setMouseOverEvents = function(){
		var ele = this;
		$("#latestNewsContainer").hover(function(){
			clearTimeout(ele.timer);
		},function(){
			ele.startTimer();
		});
	}
	
	//call to the initializing method
	this.init();
}
