/**********************************************************************
 210 Simcoe - Featured Articles Carousel - JavaScript
 
 author    : Sandra Mansour
 date      : 13-Jul-2011
 file name : jquery.carousel.js
 purpose   : this plugin is based on jquery and requires it to be
 			 included prior to inclusion of this file.
 **********************************************************************/

(function($){
	/***
	 Carousel() constructor
	 ***/
	$.fn.Carousel = function(method)
	{
		if (methods[method])
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
	};
	
	/***
	 Constant Variables
	 ***/
	ARTICLE_PATH = "/article/";
	
	/***
	 Variables
	 ***/
	_navigation_div_id 		= "PU52-CarouselNav";		//[string] the object ID of the navigation Div
	_article_div_id    		= "PU52-CarouselArticle";	//[string] the object ID of the article Div
	_loading_div	   		= null;						//[object] the loading Div element
	_intervalId 			= 0;						//[integer] the interval (timer) id
	_curr_article_id		= 1;						//[integer] the index of the current article
	_prev_article_id		= 0;						//[integer] the index of the previous article
	_transition_in_progress = false;					//[boolean] indicates that a transition is in progress

	/***
	 Carousel Methods
	 ***/
	var methods = {
		/***
		 function init()
		 	initializes the "Articles Carousel": pulls featured articles from the database
		 	using JSON and adds the elements to 'this' DIV
		 ***/
		init: function()
		{
			return this.each(function(){
				var speed = 500;
				var carouselDiv = $(this);
				
				_loading_div = getLoadingDiv();
				$(carouselDiv).append(_loading_div); //display the loading text

				//get JSON from the articles controller:
				$.getJSON("/articles/get_featured", function(data) {
					//iterate through the Articles to display:
					$.each(data, function(i,item){					
						var curr_url = item.Article.title.replace(/ /g, '-').toLowerCase();
						var articleDiv = document.createElement("div");
						articleDiv.id = _article_div_id + i;
						articleDiv.className = "article" + (i == 0 ? " selected" : "");
						articleDiv.innerHTML = "<img src='img/" + item.Image[0].file_name + "' width='" + item.Image[0].width + "' height='" + item.Image[0].height + "' alt_text='" + item.Article.title + "' />" +
											   "<h1><a href=\"" + ARTICLE_PATH + curr_url + "\">" + item.Article.title + "</a></h1>" +
											   (item.Article.sub_title ? "<h3>" + item.Article.sub_title + "</h3>" : "") +
											   "<p class='author'>By " + item.Article.author + "</p>" +
											   "<p class='body'>" +
											   		smartSubstr(item.Article.body, 400) + "<br /><br />" +
											   		"<a href=\"" + ARTICLE_PATH + curr_url + "\">Read more</a>" +
											   "</p>" +
											   "<div class='clear'></div>";
						$(carouselDiv).append(articleDiv);
					});

					//add the navigation squares:
					var navDiv = document.createElement("div");
					navDiv.className = "carouselNavigation";
					navDiv.innerHTML = "";
					for (i=0; i < data.length; i++)
					{
						navDiv.innerHTML += "<span id='" + _navigation_div_id + i + "'" + (i == 0 ? " class='selected'" : "") +
												" onclick=\"$('#PU52-ArticleCarousel').Carousel('play', { 'count' : " + data.length + ", " +
																							             "'speed' : " + speed + ", " +
																							             "'stop'  : true, " +
																							             "'stop_id' : " + i + " });\"" +
											"></span>";
					}
					$(navDiv).innerHTML += "<div class='clear'></div>";
					$(carouselDiv).append(navDiv);
				
					$(_loading_div).remove(); //hide the loading div
					
					//fade in the first aricle and start playing:
					$('#PU52-ArticleCarousel div.selected').fadeIn(speed);
					_intervalId = setInterval(function() { $('#PU52-ArticleCarousel').Carousel('play', { 'count' : data.length, 'speed' : speed }); }, 3000);
				});
			});
		},

		/***
		 function play()
		 	fades in the next article.
		 ***/		
		play: function(opts)
		{
			var options = {	'count'		: 0,		//[integer] the number of articles Carousel contains
							'speed' 	: 0,		//[integer] the speed of the player in milliseconds
							'stop'  	: false,	//[boolean] should we stop this player?
							'stop_id'	: -1		//[integer] this is the ID to stop the player at
						  };
			
			return this.each(function(){
				if (opts) //apply the custom options
					$.extend(options, opts);

				// this ensures that the player does not skip ahead and regulates the process
				if (!_transition_in_progress)
				{
					_transition_in_progress = true;

					//if stop is true and stop_id is not -1, then clear the interval and stop at the selected article
					if (options['stop'] && options['stop_id'] != -1)
					{
						if (_intervalId != 0)
						{
							clearInterval(_intervalId);
							_intervalId = 0;
						}
						_curr_article_id = options['stop_id'];
					}
					else if (_curr_article_id >= options['count'])
							_curr_article_id = 0;
										
					//set the z-index for this article and the previous article.
					//the current article gets precendence over the previous article!
					for (i=0; i < options['count']; i++)
						$("#" + _article_div_id + i).css('z-index', (i == _curr_article_id ? 10 : 1));
					
					//fade in the current article
					$("#" + _article_div_id + _curr_article_id).fadeIn(options['speed'], function() {
						//hide the previous article
						if (_prev_article_id != -1)
							$("#" + _article_div_id + _prev_article_id).hide();
						
						//select the correct navigation box:
						for (j=0; j < options['count']; j++)
							$("#" + _navigation_div_id + j).removeClass('selected');
						$("#" + _navigation_div_id + _curr_article_id).addClass('selected');
	
						//set the previous article ID and increment the current article ID:
						_prev_article_id = _curr_article_id;
						if (!options['stop'])
							_curr_article_id++;

						//transition can now end
						_transition_in_progress = false;
					});
				}
			});
		}
	};
	
	/***
	 function getLoadingDiv()
	 this function creates the Loading DIV element
	 ***/
	function getLoadingDiv()
	{
		//create the div element:
		var loadingDiv 		 = document.createElement("div");
		loadingDiv.className = "loading";
		
		//create the image element:
		var loadingImg 	  = document.createElement("img");
		loadingImg.src 	  = "/articles/img/loader.gif";
		loadingImg.width  = 50;
		loadingImg.height = 50;
		loadingImg.alt 	  = "Loading...";
		
		//append the image element to the div element:
		loadingDiv.appendChild(loadingImg);

		return loadingDiv;
	}
	
	/***
  	 function smartSubstr
  	 this function ensure words are not cut off when using the substring() function
	 ***/
	function smartSubstr(text, len)
	{
		text = text.substring(0, len);
		text = text.substring(0, text.lastIndexOf(' ')) + "...";
		return text;
	}
})(jQuery);
