/**
 * A Plugin for jQuery which creates a Simple Carousel. To be used in combination with PHP File & an External JSON File.
 * @author Abdullah Rubiyath <itsalif [at] gmail [dot] com>
 * @copyright GPL. 
 * version 2
 * Usage: $('.featuredDiv').simpleCarousel('pathtoJSONfile');
 * 
 * As of now, the only animation available is fade effect, in future I will add more effects
 * @param
 * fileName : 
 * params
 *   timer : The timer in milliseconds after which the carousel function is called back
 *   index : the item index 
 *   delay : the animation delay
 * 
 */

 (function($) {		
	$.fn.simpleCarousel = function(fileName, params) {
		var $this = $(this);
		var cTimer;
		if( !params ) { params = { timer: 5000, index: 1, delay: 1000 }; }
		return this.each(function() {
			$this.next().children('a').click(function() {
				window.clearTimeout(cTimer);
				$(this).parent().children('class$=on').removeClass('on');
				carousel( fileName, { 
					index :  $(this).parent().children().index(this) , 
					timer : params.timer				
					});
				return false;
				});
				cTimer = window.setTimeout( function() { carousel(fileName, params); }, params.timer );  
		});
			
		function carousel(fileName,  params ) {
			$.getJSON(fileName, function(data) {
			  $this.animate( {	'opacity' : 0 }, params.delay, 
			  	function() {	
				   	params.index = (!params.index && params.index!=0) ? 1 : params.index%data.entry.length;			  
					if( data.entry[params.index].type == "image" ) {
						$(this).html( $('<a></a>').attr({
							'title' : data.entry[params.index].title ,
							'href'  : data.entry[params.index].url
						}).append( $('<img />').attr({
							'src'   : data.entry[params.index].src,
							'alt'   : data.entry[params.index].title
						}) ) );
					} else {
						$(this).load(data.entry[params.index].src);
					}
						/** taking care of JS -ve Modulu **/			
					$(this).next().children('a').eq( params.index==0 ? data.entry.length-1 : params.index-1 ).removeClass("on");
					$(this).next().children('a').eq(params.index).addClass('on');
					++params.index;
					window.clearTimeout(cTimer);
					cTimer = window.setTimeout( function() { carousel(fileName, params); }, params.timer );   									
				}).animate({ 'opacity' : 1 }, params.delay);
			});
				
		}		
	}	
}) (jQuery);