$(document).ready(function() {
	
	var apis = ['facebook'];
	
	$.each(apis, function(i, api){
		
		$('#'+api+'02').empty();
		
		$.getJSON('/assets/api/'+api+'/?jsoncallback=?',function(data) {
			
	
			var tmpls = [];
			
			$.each(data, function(i, entry){
				
				var tmpl = $('#'+api+'Template').html();
				
				$.each(entry, function(key, value){
					var r = new RegExp('{'+key+'}', "gi");
					tmpl = tmpl.replace(r,value);
				});
				
				tmpls.push(tmpl);
				
			});
			
			$('#'+api+'02').append(tmpls.join(''));
		
		});

	});
	
	/* This code is executed after the DOM has been completely loaded */
	
	var totWidth = 0;
	var positions = new Array();
	
	$('#slideshow div').each(function(i) {
		
		/* Traverse through all the slides and store their accumulative widths in totWidth */
		
		positions[i]= totWidth;
		totWidth += $(this).width();
		
		/* The positions array contains each slide's commulutative offset from the left part of the container */
		
		if(!$(this).width()) {
			alert("Please, fill in width & height for all your images!");
			return false;
		}
		
	});
	
	$('#slideshow').width(totWidth);

	/* Change the cotnainer div's width to the exact width of all the slides combined */

	$('#slideshowControl ul li a').click(function(e,keepScroll){

			/* On a thumbnail click */

			$('li.controlItem').removeClass('active').addClass('inactive');
			$(this).parent().addClass('active');
			
			var pos = $(this).parent().prevAll('.controlItem').length;
			
			$('#slideshow').stop().animate({marginLeft:-positions[pos]+'px'},450);
			/* Start the sliding animation */
			
			e.preventDefault();
			/* Prevent the default action of the link */
			
			
			// Stopping the auto-advance if an icon has been clicked:
			if(!keepScroll) clearInterval(itvl);
	});
	
	$('#slideshowControl ul li.controlItem:first').addClass('active').siblings().addClass('inactive');
	/* On page load, mark the first thumbnail as active */
	
	
	
	/*****
	 *
	 *	Enabling auto-advance.
	 *
	 ****/
	 
	var current = 1;
	
	function autoAdvance() 
	{
		if(current==-1) return false;
		
		$('#slideshowControl ul li a').eq(current%$('#slideshowControl ul li a').length).trigger('click',[true]);
		current++;
	}

	// The number of seconds that the slider will auto-advance in:
	
	var changeEvery = 5;

	var itvl = setInterval(function(){autoAdvance()},changeEvery*1000);

	/* End of customizations */
});
