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

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

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

    // Public Variables and Methods
    $[nsp] = {
        defaultOptions: {
            matcher : RegExp('.+'),
            size    : 160,
												thmb_size    : 74,
            msg_loading_list : 'LAEN ALBUMEID...',
            msg_loading_album : 'LAEN PILTE...',
            msg_back : 'Tagasi',
            album_title_tag: '<div/>',
            thumb_id_prefix: 'pThumb_',
            thumb_tuner: null,
            thumb_finalizer: null,
            loading_animation: null,
            link_mapper: function(el){
                    return [
                        el.href,
                        '<a href="'+el.href+'">'+el.title+'</a>'
                    ]
                }
        }
    };
    $.fn[nsp] = function(user,opts) {
        var localOpts,
            Cache = {};

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

        function showOverview() {
            var $this,
                meta_opts,
                albumCount,
                $album_list,
                authkey = '';

            if ( Cache.__overview ){
                 Cache.__overview.show();
                 return;
            }
            $this = $(this);
            $this.empty();
            $this.append($('<br/>').css('clear','left'));
            meta_opts = localOpts;
            if ($.meta){
                meta_opts = $.extend({}, localOpts, $this.data());
            }
            albumCount = 0;
            $album_list = $('<div/>')
                .addClass('album-list')
                .append($('<p/>').addClass('gallery-album-loading').text(meta_opts.msg_loading_list));


            $this.prepend($album_list);

            function appendImage(i,item){
                var title,$div,$img;
                title = item.media$group.media$title.$t;
                if (title.match(meta_opts.matcher)){
                    albumCount++;
                    $img = $('<img/>')
                        .attr('title',title)
                        .attr('src',item.media$group.media$thumbnail[0].url)
                    $div = $('<div/>')
                        .addClass('album-cover')

                        .click(function () {
                           $album_list.hide();
                           showAlbum($this,meta_opts,item.gphoto$id.$t,title,item.gphoto$numphotos.$t);
                        })
                        .hover(
                            function () { $(this).css("cursor","pointer")},
                            function () { $(this).css("cursor","default")}
                        )
                        .append( $img )
                        .append(
                            $('<p/>')
                            .addClass('album-title')
                            .text(title)
                        )
																								.append(
                            $('<div/>').addClass('foward-button')
																												.append($('<span/>').text('VAATA PILTE')
                        )
																							)
                    $album_list.append($div);
                };
            }

            function renderAlbumList(data){
                var $albums,maxHeight=0;
                $album_list.empty();
        		if (data.feed && data.feed.entry){
    	            $.each(data.feed.entry,appendImage);
        		} else {
          		    $this.text('Hoiatus! Albumeid ei leitud kasutajalt ' + user);
		        }
                Cache.__overview = $album_list;
                $albums = $album_list.children();


                if (albumCount == 1){
                    $albums.eq(0).click();
                    return;
                }
                $('.album-title',$album_list)
                .each(function(){
                     var h = $(this).outerHeight();
                     if (h > maxHeight){
                        maxHeight = h
                     }
                })
                .each(function(){
                    $(this).height(maxHeight)
                });

            }


            if (meta_opts.authkey){
                authkey = '&authkey=' + meta_opts.authkey;
            }

    	    if (meta_opts.albumid) {
       	       showAlbum($this,meta_opts,meta_opts.albumid,'')
    	    }
	        else {
                $.getJSON('http://picasaweb.google.com/data/feed/api/user/'
                    + user + '?kind=album&access=visible' + authkey
                    + '&alt=json-in-script&thumbsize=' + meta_opts.size + 'c&callback=?',
                    renderAlbumList
               );
	        }
        };

        function showAlbum($this,meta_opts,album,title,photoCount){
            if ( Cache[album] ){
               Cache[album].show();
               return;
            };
											var i,$album,albumPics=[],$albumDiv,$tiitel,$loadingMsg;

											$album = $('<ul id="pildialbum"/>').addClass('jcarousel-skin-pika');

											$loadingMsg = $('<p/>').addClass('gallery-album-loading').text(meta_opts.msg_loading_album);
											$this.prepend($loadingMsg);
											if (title){
											 	 $tiitel = $(meta_opts.album_title_tag).addClass('gallery-album-title');
											 	 $tiitel.prepend($('<h2/>').text(title));
											 	 $tiitel.hide();
												 $this.prepend($tiitel);
            }

           function makeDiv(){
               $div = $('<li/>')
                   .width(meta_opts.thmb_size)
                   .height(meta_opts.thmb_size)
																			.css({'list-style-type': 'none'})
               if (meta_opts.loading_animation){
                   $div.css('background','url(' + meta_opts.loading_animation + ') no-repeat center center');
               }
               return $div;
            }

					  if (photoCount){
                for (i=0;i<photoCount;i++) {
                    $albumDiv = makeDiv();
                    $album.append($albumDiv);
                    albumPics.push($albumDiv);
                }
            }

            function appendImage(i,item){
               var title, $img, $div, $a;
               title = item.media$group.media$title.$t;
               $img = $(new Image());
               $img.load(function(){
                    if (meta_opts.thumb_tuner){
                        meta_opts.thumb_tuner($div,item);
                    }
                    $img.show();
               })
               .hide();
               $a = $("<a/>")
                   .attr("href",item.content.src)
                   .attr("title",title)
                   .append($img);

               if (($div = albumPics[i]) == undefined){
                    $div = makeDiv();
                    $album.append($div);
               }

               $div

                   .append($a);
               //alert(item.media$group.media$thumbnail[0].name);
               //$img.attr("src", item.media$group.media$thumbnail[0].url); // originaal
               $img.attr("src", item.content.src);

            }

            function renderAlbum(data){
                $.each(data.feed.entry,appendImage);

                $album.PikaChoose();
																$("a[rel='open-colorbox']").colorbox();
                $album.jcarousel({scroll:4,
									initCallback: function(carousel)
									{
										$(carousel.list).find('img').click(function() {
											//console.log($(this).parents('.jcarousel-item').attr('jcarouselindex'));
											carousel.scroll(parseInt($(this).parents('.jcarousel-item').attr('jcarouselindex')));
										});
									}
								});
								$tiitel.show();
                $loadingMsg.hide();

                if ($.fn.slimbox){
                    $('a',$album).slimbox({},meta_opts.link_mapper);
                }
                if (meta_opts.thumb_callback){
                    $('a',$album).each(meta_opts.thumb_callback);
                }
// */
// */
                Cache[album] = $album;
            }
            authkey = '';
            if (meta_opts.authkey){
               authkey = '&authkey=' + meta_opts.authkey;
            }
            $.getJSON('http://picasaweb.google.com/data/feed/api/user/'
                + user + '/albumid/'
                + album + '?kind=photo&access=visible' + authkey + '&alt=json-in-script&thumbsize='+meta_opts.size+'c&imgmax=800&callback=?',
                renderAlbum
            );
            $this.prepend($album);
        };

        return this.each(showOverview);

    };

})(jQuery);
