/**
 * This was heavily modified by Lasse Fister http://graphicore.de but all the glory goes to the guys below
 *
 * Picasa Webalbum Integration jQuery plugin
 * This library was inspired aon pwa by Dieter Raber
 * @name jquery.pwi.js
 * @author Jeroen Diderik - http://www.jdee.nl/
 * @revision 1.2.0
 * @date January 25, 2010
 * @copyright (c) 2009 Jeroen Diderik(www.jdee.nl)
 * @license Creative Commons Attribution-Share Alike 3.0 Netherlands License - http://creativecommons.org/licenses/by-sa/3.0/nl/
 * @Visit http://pwi.googlecode.com/ for more informations, duscussions etc about this library
 */
(function ($) {
    createDom = function (tag, attr, text)
    {
        if(typeof attr === "string")
        {
            attributes = {'class' : attr};
        }
        else
        {
            attributes = ('object' == typeof attr) ? attr : {};
        }
        if(text)
        {
            return $(document.createElement(tag)).attr(attributes).text(text);
        }
        return $(document.createElement(tag)).attr(attributes);
    }

    $.fn.pwx = function (settings)
    {

        var $self = this,
        settings = $.extend({}, $.fn.pwx.defaults, settings);
        var _initialize = function()
        {
            ts = new Date().getTime();
            settings.id = ts;
            $self.addClass('pwx_container');

            if( !settings.albumUrl && settings.username != '' && settings.album != '')
            {
                settings.albumUrl = 'http://picasaweb.google.com/data/feed/api'
                    + '/user/' + settings.username
                    + '/album/' + settings.album
            }
            if(!settings.albumUrl)
            {
                //throw 'Make sure you specify at least a username and an albumname or the albumurl';
                return false;
            }
            var regex = new RegExp('^http://picasaweb.google.com\/data\/feed\/api\/user\/([^\/]+)\/album\/([^\/]+)');
            var match = regex.exec(settings.albumUrl);
            if(!match)
            {
                throw 'albumUrl seems invalid';
                return false;
            }
            settings.username = match[1];
            settings.album = match[2];

            getAlbum();
            return false;
        }
        var formatDate = function ($dt)
        {
            var $today = new Date(Number($dt)),
            $year = $today.getUTCFullYear();
            if ($year < 1000) {
                $year += 1900;
            }
            return (settings.months[($today.getUTCMonth())] + " " + $today.getUTCDate() + ", " + $year);
        }
        var formatDateTime = function ($dt)
        {
            var $today = new Date(Number($dt));
            $year = $today.getUTCFullYear();
            if ($year < 1000) {
                $year += 1900;
            }
            if($today == "Invalid Date"){
                return $dt;
            }else{
                return ($today.getUTCDate() + "-" + ($today.getUTCMonth() + 1) + "-" + $year + " " + $today.getUTCHours() + ":" + ($today.getUTCMinutes() < 10 ? "0" + $today.getUTCMinutes() : $today.getUTCMinutes()));
            }
        }
        var photo = function (photo)
        {
            var $html, photo_date = "", description = "", $img_base = photo.content.src,
            $id_base = photo.gphoto$id.$t,
            description = (photo.summary ? photo.summary.$t : "");
            if(settings.photoCaptionLength > 0)
            {
                description = description.substring(0, settings.photoCaptionLength);
            }
            if(settings.showPhotoDate)
            {
                if( photo.exif$tags.exif$time ){
                    photo_date = formatDateTime(photo.exif$tags.exif$time.$t);
                }else if( photo.gphoto$timestamp ){
                    photo_date = formatDateTime(photo.gphoto$timestamp.$t);
                }else{
                    photo_date = formatDateTime(photo.published.$t);
                }
            }
            dateDesc = description + (photo_date ? ' ' + photo_date : '');

            return [createDom('li')
            .append(createDom('a', {
                href : $img_base
                    + "?imgmax="
                    + settings.photoSize,
                rel  : 'lb-' + settings.username,
                title : dateDesc
                })
                .append(createDom('img', {
                    src : $img_base
                        + "?imgmax=" + settings.thumbSize
                        + "&crop=" + settings.thumbCrop,
                    'class' : 'normal',
                    alt : dateDesc
                }))
            ),
            createDom('li')
                .append(createDom('img', {
                    src : $img_base
                        + "?imgmax=" + 48
                        + "&crop=" + settings.thumbCrop,
                    'class' : 'thumbnail',
                    alt : dateDesc
                }))
            //)
            ];
        }
        //the callback of getAlbum
        var album = function (j)
        {
            var $scPhotos, $scPhotosDesc,
            albumTitle = "", totalResults = j.feed.openSearch$totalResults.$t,
            $loc = j.feed.gphoto$location === undefined ? "" : j.feed.gphoto$location.$t,
            $ad = j.feed.subtitle === undefined ? "" : j.feed.subtitle.$t,
            $album_date = formatDate(j.feed.gphoto$timestamp === undefined ? '' : j.feed.gphoto$timestamp.$t),
            albumTitle = (j.feed.title === "undefined" || settings.albumTitle.length > 0) ? settings.albumTitle : j.feed.title.$t;
            $scPhotos = createDom('ol', 'items');
            $scThumbs = createDom('ol', 'items');
            for(var i in j.feed.entry)
            {
                var p = photo(j.feed.entry[i]);
                $scPhotos.append(p[0]);
                $scThumbs.append(p[1]);
            }
            settings.photostore[settings.album] = j;
            var $s = $('a[rel=lb-' + settings.username + ']', $scPhotos);
            if (typeof(settings.popupExt) === "function")
            {
                settings.popupExt($s);
            }
            else if (typeof(settings.onclickThumb) === "function")
            {
                $s.bind('click.pwx', clickThumb);
            }
            else if (typeof(settings.onclickThumb) != "function" && $.slimbox)
            {
                $s.slimbox(settings.slimbox_config);
            }
            if (settings.showAlbumDescription)
            {
                $scPhotosDesc = createDom('div', 'album_description')
                    .append(createDom('h3', null, albumTitle)
//                        .append(createDom('a',
//                            {
//                                href : ['http://picasaweb.google.com', settings.username, j.feed.gphoto$name.$t].join('/'),
//                                rel : 'alternative',
//                                title: settings.labels.picasa
//                            }, albumTitle) )
                    )
                    .append(createDom('p', 'details', totalResults+ " "+ ( (totalResults == "1") ? settings.labels.photo : settings.labels.photos) + (settings.showAlbumdate ? ", " + $album_date : "") + (settings.showAlbumLocation && $loc ? ", " + $loc : "")))
                    .append(createDom('p', 'description', $ad));
            }
            show(false, {data:createDom('div', 'scroll').append($scPhotos), thumbs: createDom('div', 'thumbscroll').append($scThumbs), description: $scPhotosDesc});

        }
        var clickThumb = function ()
        {
            settings.onclickThumb.call(this);
            return false;
        }
        var getAlbum = function ()
        {
            if (settings.photostore[settings.album])
            {
                album(settings.photostore[settings.album]);
            }
            else
            {
                var $url = settings.albumUrl
                    + '?kind=photo&alt=json'
                    + ((settings.authKey != "") ? "&authkey=" + settings.authKey : "");
                show(true, '');
                $.getJSON($url, 'callback=?', album);
            }
            return $self;
        }
        var show = function (loading, data)
        {
            if (loading) {
                document.body.style.cursor = "wait";
            } else {
                document.body.style.cursor = "default";
                gallery(data);
                 $self.children().remove()

                $self.append(data.description);
                $self.append(data.data);
                $self.append(data.thumbs);
            }
        }

        var scrollSetActive = function(scrollableApi, i)
        {
            var items = scrollableApi.getItems(),
            klass = scrollableApi.getConf().activeClass;

            items.removeClass(klass).eq(i).addClass(klass);
        }

        var gallery = function($data)
        {
            var imagesApi = $data.data.scrollable(
                {
                    size: 1,
                    speed: 200,
                    clickable: false,
                    loop: true,
                    item: 'li',
                    mousewheel: true
                });
            var imagesApi = $data.data.data("scrollable");
            var autoplay = $data.data.autoscroll({autoplay: false, api: true, interval : 3000});

            var timeOut, restartTimer = 6000;
            //var stopped = false;
            //initial timeout, so that we can see the first image for a momemnt

            var scrollStart = function()
            {
            //    if(stopped){return;}
                timeOut = setTimeout( autoplay.play, restartTimer);
            };

            var scrollStop = function()
            {
                clearInterval(timeOut);
                autoplay.stop();
            }
            scrollStart();
            $self.hover(function(evt){scrollStop()}, function(evt){scrollStart();});

            // stop autoplay when lightbox gets activated
            //links = $('a[rel=lb-' + settings.username + ']', $data.data);
            //links.click(function(){scrollStop();stopped = true;});
            // thumbnail scrollable
            var thumbsApi = $data.thumbs.scrollable(
                {
                    size: 1,
                    speed: 200,
                    clickable: false,
                    item: 'li',
                    mousewheel: true
                });
            var thumbsApi = $data.thumbs.data("scrollable");
            imagesApi.onBeforeSeek(function(evt, i)
            {
                var item = this.getItems().eq(i);

                scrollSetActive(thumbsApi, i);
                return thumbsApi.seekTo(i);
            });
            thumbsApi.getItems().each(function(i)
            {
                $(this).unbind('click.scrollable').bind('click.scrollable', function(evt)
                {
                    if($(evt.target).is('a')){ return; }
                    return imagesApi.seekTo(i);
                })
            });


            var apis = [imagesApi, thumbsApi], conf;
            for(var i in apis)
            {
                conf = apis[i].getConf();
                conf.resetSpeed = conf.speed;
            }
            apis[0].next(0).seekTo(0);
            for(var i in apis)
            {
                conf = apis[i].getConf();
                conf.speed = conf.resetSpeed;
            }
        }


        _initialize();
    }
    $.fn.pwx.defaults = {
        username: null,
        album: null,
        albumUrl: null,
        authKey: "",
        albums: [],
        albumCrop: 1,
        albumTitle: "",
        albumThumbSize: 160,
        albumMaxResults: 999,
        albumsPerPage: 10,
        albumStartIndex: 1,
        albumTypes: "public",
        page: 1,
        photoSize: 800,
        maxResults: 50,
        showPager: 'bottom', //'top', 'bottom', 'both'
        thumbSize: 72,
        thumbCrop: 0,
        onclickThumb: "",
        popupExt: "",
        showAlbumTitles: true,
        showAlbumdate: true,
        showAlbumPhotoCount: true,
        showAlbumDescription: true,
        showAlbumLocation: true,
        showSlideshowLink: true,
        showPhotoCaption: false,
        photoCaptionLength: 0,
        showPhotoDownload: false,
        showPhotoDate: true,
        labels: {
            photo: "photo",
            photos: "photos",
            albums: "Back to albums",
            slideshow: "Display slideshow",
            picasa: "the Album at Picasa",
            loading: "pwx fetching data...",
            page: "Page",
            prev: "Previous",
            next: "Next",
            devider: "|"
        },
        months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        slimbox_config: {
            loop: false,
            overlayOpacity: 1,
            overlayFadeDuration: 400,
            resizeDuration: 400,
            resizeEasing: "swing",
            initialWidth: 250,
            initlaHeight: 250,
            imageFadeDuration: 400,
            captionAnimationDuration: 400,
            counterText: "{x}/{y}",
            closeKeys: [27, 88, 67, 70],
            prevKeys: [37, 80],
            nextKeys: [39, 83]
        },
        //this is a cache, the returned json from getAlbum() is stored at photostore[settings.album]
        //we might store the albums at the url we got em photostore[url] that way these would be unique (two albums can have the same name when they are of different users)
        photostore: {},
        token: ""
    }
})(jQuery);

