(function($) {

	//Attach this new method to jQuery  
    $.fn.extend({   
          
        //----------------------------------------------------------//
        // Title: Haven't decided on a name
        // Author: Jordan Brown
        // Company: MediaFuel
        // Date: 09/22/10
        //----------------------------------------------------------//
         
        facebookAlbums: function(id, options, callback) {
			
			var defaults = {
				link: false,
				limit: 5
			}
		
			var options = $.extend(defaults, options);
			
			return this.each(function() {
			
				var o = options;
				
				var obj = $(this);
				var finished = new Array();
				var links = new Array();
				var titles = new Array();
				
				$.ajax({
					type: "GET",
					url: "https://graph.facebook.com/"+id+"/albums&limit="+o.limit,
					dataType: "jsonp",
					success: function(json) {
						for (var i = 0; i < o.limit; i++) {
						
							links.push(json.data[i].id);
							titles.push(json.data[i].name);
							
							getCoverPhoto(i, json.data[i].cover_photo);
							
							
							
						}
						
						if (typeof callback == 'function') { // make sure the callback is a function
					        callback.call(this); // brings the scope to the callback
					    }
					    
					    var interval = self.setInterval(function() {
							if (o.limit == finished.length) {
								writeHTML();
								window.clearInterval(interval);
							}
						},300);
					    
					}
					
				});
				
				getCoverPhoto = function(i, coverPhotoID) {
					$.ajax({
						type: "GET",
						url: "https://graph.facebook.com/"+coverPhotoID,
						dataType: "jsonp",
						success: function(json) {
							link = json.picture;
							finished[i] = json.picture;
						}
					});
				}
				
				writeHTML = function() {
					var lis = "";
					var totalWidth = 0;
					var link = ""; 
					
					for (var i = 0; i < finished.length; i++) {
						if (finished[i] == undefined)
							continue;
						lis += "<li><a href=\"?id="+links[i]+"\" title=\""+titles[i]+"\"><img src=\""+finished[i]+"\" alt=\"\" />"+titles[i]+"</a></li>";
					}
					var htmlBox = "<ul>";
					htmlBox += lis;
					htmlBox += "</ul>";
					obj.html(htmlBox);
					
				};
			
			});
			
		}
		
	});	
				
})(jQuery);
