(function($) {

    $.fn.randomBanner =
    	function(options) {
    		// Initialize settings.
            var settings = {
	            'url': 'banners.json'
	        };
            if (options) $.extend(settings, options);

            // Retrieve banner content.        
            var banners;
            
	        $.ajax({
			    type: 'GET', url: settings.url, dataType: 'json', async: false,
			    success:
		            function(data) {
			            banners = data.banners;
					}
			});
    	
	        // For each matched element add a randomly chosen banner.
        	return this.each(function() {
    			$.renderBanner(this, $.pickRandomBanner(banners));
        	});
    	};

    $.renderBanner =
    	function(container, banner) {
    	
    		var image = $('<img />')
				.attr('src', banner.src)
				.attr('alt', banner.alt)
				.css('width', '468px')
				.css('height', '60px');
    		
    		if (banner.href != null) {
				$(container).append(
					$('<a></a>')
						.attr('href', banner.href)
						.attr('target', '_blank')
						.append(image));
    		} else {
				$(container).append(image);
    		}
    	};
    
    $.pickRandomBanner =
    	function(banners) {
    	    var banner = null;
    	    var attempts = 100;
    	    var random;
    	    
    	    while (banner == null && attempts > 0) {
    	    	random = Math.round(Math.random() * (banners.length - 1));
			    if (banners[random].used != 'yes') {
			    	banner = banners[random];
	        		banner.used = 'yes';
			    }
			    attempts--;
    	    }
    	    
    	    if (banner == null) {
    	    	banner = banners[random];
    	    }
			return banner;
    	};
    	
})(jQuery);