/* 
 * file: ImageExtractor.js
 * 	Support for extracting image urls from tweets.
 */
var ImageExtractor = {
	/*
	 * Invokes the ExtractorServlet to return images for a set of URLs
	 * @param urls An array of URLs, or a single url
	 * @param callback A function which receives the returned images.
	 * @param [onError] Optional parameter, a callback which is invoked upon error
	 */
	'findImages' : function(urls, callback, onError) {
		// Make array if not
		if(urls.constructor === String) { urls = [urls]; }

		// Perform Ajax request
		$.ajax({
			url : "/image-extractor.json",
			data : {
				'urls' : urls.join(', ')
			},
			success : function(response) {
				if(response !== null && response.success) {				
					callback(response.cargo);
				} else {
					if(onError !== undefined) onError(response.errors);
				}
			},
			error : function() {
				if(onError !== undefined) onError();
			}
		});
	}
};

function ajaxifyThumbnails(selector) {
	$(selector).not('.thumb-ajaxed').each(function () {	
		var element = $(this);
			
		element.addClass('thumb-ajaxed');

		var urls = new Array();
		
		element.children('a').each(function() {
			urls.push(
				$(this).attr("href")
			);
		});

		ImageExtractor.findImages(
			urls, 
			function(imageData) {
				for(var url in imageData) {
					var imageURL = imageData[url];

					if(imageURL !== null) {
						element.append(
							$("<img>").attr("src", imageURL)
						);
					}
				}
			}, 
			function() {
			
			}
		);
	});
};

