/**************************************************************************
 * Name:   EmbedPicasaGallery
 * Author: Tobias Oetiker <tobi@oetiker.ch>
 * Date:   2009/09/10
 * Demo:   http://tobi.oetiker.ch/photo/

 * $Id: jquery.EmbedPicasaGallery.js 238 2009-09-21 07:32:04Z oetiker $
 **************************************************************************/
/**************************************************************************
 Description:
 
 This little script asks picasa web for a list of albums and for a list
 of pictures in the album. It then emits a series of <div class="pic-thumb"/>
 elements containing thumbnail images. The divs are inserted inside the element
 marked with a particular id. Clicking on an album will display thumbnails of the
 images in the album and clicking on a thumbnail will show the image itself
 using slimbox.
 
 The script itself uses jQuery (http://www.jquery.org) and slimbox2
 (http://www.digitalia.be/software/slimbox2) to work. So you have to load
 these two guys before loading the gallery script. You can load them in the
 header or the body of the document, this does not matter.
 
  <script type="text/javascript" src="js/jquery.js"></script>
  <link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
  <script type="text/javascript" src="slimbox2.js"></script>
  <script type="text/javascript" src="js/jquery.EmbedPicasaGallery.js"></script>

 Once loaded, call the picasaGallery function. This activates the
 code. With the id argument you tell it, where to put the gallery.

  <script type="text/javascript">
  jQuery(document).ready(function() {
   jQuery("#images").EmbedPicasaGallery('oetiker',{
      matcher:            /./,        // string or regexp to match album title
      size:               '72'        // thumbnail size (32, 48, 64, 72, 144, 160)
      msg_loading_list :  'Loading list from PicasaWeb',
      msg_loading_album : 'Loading album from PicasaWeb',
      msg_back :          'Back',
      album_title_tag: '<h2/>'
   });
  });
  </script>

 Finally inside the document, add a div tag with the id set to the name
 chosen above.
 
 <span id="images"></div>

 To have the elements show up horyzontally stacked and not vertiaclly use css 

**********************************************************************************/

(function($) {
    // setup a namespace for us
    var nsp = 'EmbedPicasaBanner';

    // Public Variables and Methods
    $[nsp] = {
        defaultOptions: {
            matcher : RegExp('.+'),
            size    : 72,
            msg_loading_list : 'Loading list from PicasaWeb',
            msg_loading_album : 'Loading album from PicasaWeb',
            msg_back : 'Back',
            album_title_tag: '<h2/>',
            max_thumbs: 10,
            max_sample: 20,
            tags: '',
            callback: ''
        }       
    };

    // Private Variables and Functions in the _ object
    // note that this will refer to _ unless you
    // call using the call or apply methods
    var _ = {
    };

    $.fn[nsp] = function(user,opts) {
        var localOpts = $.extend( 
            {}, // start with an empty map
            $[nsp].defaultOptions, // add defaults
            opts // add options
        );
        var Cache = {};

        function showOverview() {
            if ( Cache.__overview ){
                Cache.__overview.show();
                return;
            }
            var $this = $(this);
            if ( ! Cache.__original ){
                Cache.__original = $this.clone(true);
            }

            $this.after($('<div/>').addClass('banner_info'));

            var meta_opts = localOpts;
            if ($.meta){
                meta_opts = $.extend({}, localOpts, $this.data());
            }
 			
            //for ($i=1; $i<meta_opts.max_thumbs; $i++) {
            //	$this.after($('<div/>').css('clear','left'));
        	//}
            
            $this.html(meta_opts.msg_loading_list);
            //$this.text(meta_opts.msg_loading_list);
            var albumCount = 0;
            
            
           function appendImage(i, item){
	           //alert(item.media$group.media$title.$t);
               var title = item.media$group.media$title.$t;
               var description = item.media$group.media$description.$t;
               //alert(item.content.src);
               var a = $("<div/>")
               	   .addClass("bannerImage")
               	   .css("background-image", "url("+item.content.src+")");
                   //.attr("href",item.content.src)
                   //.attr("title",description)
                  // .append(
                        $("<img/>")
                       // .attr("src", item.media$group.media$thumbnail[0].url)
                        /*.css({'border-width': '0px',
                              width : meta_opts.size + 'px',
                              height : meta_opts.size + 'px' 
                         })*/
                   // );
                var b = $("<p class='desc'>" + description + "</p>")
                //.addClass("info")
                //	.html("<p>" + description + "</p>");
                $this.append(a
                    //$("<div/>")
                    /*.css({
                       float: 'left',
                       'margin-right': '0px',
                       'margin-bottom': '0px'
                    })*/
                    .append(b)
                );
            }
            
            function renderLatestList(data, meta_opts){
	            $this.empty();
	            var cnt = data.feed.entry.length;
	            
	            var thumb_key = [];
	            if (cnt <= meta_opts.max_thumbs) {
		           $.each(data.feed.entry,appendImage);
	            } else {
		            while (thumb_key.length < meta_opts.max_thumbs) {
		            	var randomnum = Math.floor(Math.random()*cnt);
		            	if ($.inArray(randomnum, thumb_key) == -1) {
		            		thumb_key.push(randomnum);
	            		}
	            	}
		            
	            	//alert(thumb_key.length);
	                
	                for (var i=0; i < thumb_key.length; i++) {
		                appendImage(thumb_key[i], data.feed.entry[thumb_key[i]]);
	                }
                }
                var f = meta_opts.callback;
                if (typeof f == "function") f(); else alert(f);
                
                
                //alert(meta_opts.callback);
                //if( $.isFunction($.fn.meta_opts.callback) ){
	                //meta_opts.callback;
               // }
               
                
                //$.each(data.feed.entry,appendImage);     
                /*          
	            function linkMapper(el){
	                return [
	                    el.href,
	                    '<a href="'+el.href+'">'+el.title+'</a>'
	                ]
	            }
	
	            if ($.fn.slimbox){
	                $('a',$this).slimbox({},linkMapper);
	            }
				*/
	           Cache[this] = $this;

                if (albumCount == 1){
                    $this.children().eq(0).click();
                    return;
                }
                var maxHeight = 0;
               
                Cache.__overview = $this;
            }
			
            function processTags(meta_opts) {
	            if (meta_opts.tags == '') return "";
				var keywords = meta_opts.tags.replace(/ /gi,"%20");
				//alert (keywords);
				var tags_arr = keywords.split(",");
				var tags_str = "&tag=";
				for (i=0;i<tags_arr.length;i++) {
					if ($.trim(tags_arr[i]) != "") {
						tags_str +=  '"' + $.trim(tags_arr[i]) + '"%2C';
					}
				}
				//alert(tags_str);
			    return tags_str;
			    

            }
            $.getJSON('http://picasaweb.google.com/data/feed/api/user/' 
                + user + '?kind=photo&access=public&alt=json-in-script&thumbsize=' + meta_opts.size + 'c&imgmax=800&max-results=' + meta_opts.max_sample + processTags(meta_opts) + '&callback=?',
                function(data) {
	                //alert(meta_opts);
	                renderLatestList(data, meta_opts)
	            }
            );
        };


        return this.each(showOverview);
    };
})(jQuery);

