(function($) {
  /*  
    flickrThumbs plugin
    by matas@soundcloud.com 
    search for images on flickr based on given tags, and load thumbs into the selected node
    usage $('#container').flickrThumbs('cats', options);
    
    @searchTags: one or more (comma separated) tags
    @options: optional parameters
      size: number of thumbs to display
      tagmode: tag mode when using multiple tags, possible values: 
        'any' (will display photos with at least one on the tags specified in searchTags), 
        'all' (will only display photos tagged with each and every one of the tags specified by tags)
      wrap: will wrap every link into given container
      animated: if true (default) fades out the container before load, then fades it in, after all images are loaded
    
  */
  var settings;  
  $.fn.flickrThumbs = function(searchTags, callerSettings) {
    return this.each(function(){
      
      settings = $.extend({
            size: 9,
            tagmode: 'any',
            wrap: '',
            animated: true
      }, callerSettings || {});
      
      var $target = (settings.animated) ? $(this).fadeOut(1) : $(this);
      
      $.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?', {
          tags: searchTags,
          tagmode: settings.tagMode
        }, function(data){
          var picsLoaded = 0;
          var picsToLoad = Math.min(settings.size, data.items.length);
          
          for(var i = 0; i < picsToLoad; i = i + 1){
            var item = data.items[i];
            $('<a href="' + item.link +'"></a>')
            .append('<img src="' + item.media.m.replace('_m.','_s.') + '" title="' + item.title + '" alt="A photo on Flickr: ' + item.title + '" />')
            //.wrap(settings.wrap) ff bug found by eric
            .appendTo($target);
          }
          
          // fade in after all images are loaded
          if(settings.animated){
            $target.find('img').load(function(){
              picsLoaded = picsLoaded + 1;
              if(picsLoaded === picsToLoad){ 
                $target.fadeIn('slow'); 
              }
            });
          }
          
        }
      ); 
    });
  };
})(jQuery);

$(function() {
  
	// load flickr pics after window is loaded
	$(window).load(function(){
	  $('#sidebar .flickrbadge .container').append('<div></div>').find('div').flickrThumbs('soundcloud');
	});
	
});
