﻿/*
* jQuery Flickr Gallery - jQuery plug-in
* Version 1.0, Released 2010.08.05
*
* Copyright (c) 2010 Simon Ovens (www.sointeractive.co.nz)
* inspired by Daniel MacDonald (www.projectatomic.com) jquery flickr 1.0
* Dual licensed GPL http://www.gnu.org/licenses/gpl.html 
* and MIT http://www.opensource.org/licenses/mit-license.php
*/

(function ($) {
    $.fn.flickrGallery = function (options) {

        var defaults = {
            api_key: null,                  // [string]    required, see http://www.flickr.com/services/api/misc.api_keys.html
            type: null,                     // [string]    allowed values: 'photoset', 'search', default: 'flickr.photos.getRecent'
            photoset_id: null,              // [string]    required, for type=='photoset'  
            user_id: null,                  // [string]    for type=='search' search by user id
            sort: 'date-posted-asc',        // [string]    for type=='search' allowed values: 'date-posted-asc', 'date-posted-desc', 'date-taken-asc', 'date-taken-desc', 'interestingness-desc', 'interestingness-asc', 'relevance'
            thumb_size: 's',                // [string]    allowed values: 's' (75x75), 't' (100x?), 'm' (240x?)
            size: null,                     // [string]    allowed values: 'm' (240x?), 'b' (1024x?), 'o' (original), default: (500x?)
            per_page: 100,                  // [integer]   allowed values: max of 500
            page: 1,     	                // [integer]   see paging notes
            photosetLiWidth: 120,           // {integer]   size of photoset Li (listitem) in px 
            api_url: null,                  // [string]    optional, custom url that returns flickr JSON or JSON-P 'photos' or 'photoset'
            api_callback: '?',              // [string]    optional, custom callback in flickr JSON-P response
            enableLightBox: true,           // [bool]      optional, enables lightbox, depency on the jquery.lightbox library here http://leandrovieira.com/projects/jquery/lightbox/ 
            lightBoxImagePath: '/image',    // [string]    path to lightbox images
            showPhotosetInfo: true,         // [bool]      only used if type = 'photosets', if true display photoset title and description
            tags: null,                     // [string]    optional, tags
            callback: null                  // [function]  optional, callback function applied to entire <ul>
        };

        var options = $.extend(defaults, options);

        return this.each(function () {
            $this = $(this);
            if (options.type == 'photoset') {
                //check to see if we have the photo set images loaded already
                if (($this.children('#setId') &&
                            $this.children('#setId').html() == options.photoset_id)) return false;
                $this.children().remove();
                $this.append('<span id="setId" style="display: none;">' + options.photoset_id + '</span>');
            }
            var list = $('<ul>').appendTo($this);
            var url = $.flickrGallery.format(options);
            $.getJSON(url, function (r) {
                if (r.stat != "ok") {
                    list = $('<ul>').appendTo($this);
                    for (i in r) {
                        $('<li>').text(i + ': ' + r[i]).appendTo(list);
                    }
                }
                else {
                    switch (options.type) {
                        case 'photosets':
                            for (var i = 0; i < r.photosets.photoset.length; i++) {
                                var photoset = r.photosets.photoset[i];
                                var onclickFunction = "getPhotosBySetId('" + photoset['id'] + "', "+ i +")";
                                var photoSetThumb = 'http://farm' + photoset['farm'] + '.static.flickr.com/' + photoset['server'] + '/' + photoset['primary'] + '_';
                                switch (options.thumb_size) {
                                    case 'm':
                                        photoSetThumb += photoset['secret'] + '_m.jpg';
                                        break;
                                    case 'b':
                                        photoSetThumb += photoset['secret'] + '_b.jpg';
                                        break;
                                    default:
                                        photoSetThumb += photoset['secret'] + '_s.jpg';
                                };
                                var photoSetInfo = '';
                                if (options.showPhotosetInfo) {
                                    photoSetInfo = '<div class="setinfocontainer">'
                                                    + '<div class="settitle">' + photoset.title._content + ' <span id="numberofphotos">(' + photoset["photos"] + ' photos)</span></div>'
                                                    + '<div class="setdescription">' + photoset.description._content + '</div>'
                                                    + '</div>';
                                }
                                list.append('<li style="width: ' + options.photosetLiWidth + 'px;"><a href="javascript:void(0)" onclick="' + onclickFunction + '" ' + options.attr + ' title="' + photoset.title._content
                                            + '"><img src="' + photoSetThumb + '" alt="' + photoset.title._content + '" /></a>' + photoSetInfo + '</li>');
                            }
                            break;
                        default:
                            if (options.type == 'photoset') r.photos = r.photoset;
                            // add hooks to access paging data
                            list.append('<input type="hidden" value="' + r.photos.page + '" />');
                            list.append('<input type="hidden" value="' + r.photos.pages + '" />');
                            list.append('<input type="hidden" value="' + r.photos.perpage + '" />');
                            list.append('<input type="hidden" value="' + r.photos.total + '" />');
                            for (var i = 0; i < r.photos.photo.length; i++) {
                                var photo = r.photos.photo[i];
                                // format thumbnail url
                                var thumb = 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + '_' + photo['secret'] + '_' + options.thumb_size + '.jpg';
                                //format image url
                                var image = 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + '_';
                                switch (options.size) {
                                    case 'm':
                                        image += photo['secret'] + '_m.jpg';
                                        break;
                                    case 'b':
                                        image += photo['secret'] + '_b.jpg';
                                        break;
                                    case 'o':
                                        if (photo['originalsecret'] && photo['originalformat']) {
                                            image += photo['originalsecret'] + '_o.' + photo['originalformat'];
                                            break;
                                        };
                                    default:
                                        image += photo['secret'] + '.jpg';
                                };
                                list.append('<li><a href="' + image + '" ' + options.attr + ' title="' + photo['title'] + '"><img src="' + thumb + '" alt="' + photo['title'] + '" /></a></li>');
                            };
                            if (options.enableLightBox) {
                                var imagePath = options.lightBoxImagePath;
                                $this.find("a").lightBox({
                                    imageLoading: imagePath + '/lightbox-ico-loading.gif',
                                    imageBtnClose: imagePath + '/lightbox-btn-close.gif',
                                    imageBtnPrev: imagePath + '/lightbox-btn-prev.gif',
                                    imageBtnNext: imagePath + '/lightbox-btn-next.gif',
                                    imageBlank: imagePath + '/lightbox-blank.gif'
                                });
                            }
                            if (options.callback) options.callback(list);
                    };
                };
            });
        });
    };

    // static function to format the flickr API url according to the plug-in settings 
    $.flickrGallery = {
        format: function (options) {
            var url = 'http://api.flickr.com/services/rest/?format=json&jsoncallback=' + options.api_callback + '&api_key=' + options.api_key;
            switch (options.type) {
                case 'photosets':
                    url += '&method=flickr.photosets.getList&user_id=' + options.user_id;
                    break;
                case 'photoset':
                    url += '&method=flickr.photosets.getPhotos&photoset_id=' + options.photoset_id;
                    break;
                case 'search':
                    url += '&method=flickr.photos.search&sort=' + options.sort;
                    if (options.user_id) url += '&user_id=' + options.user_id;
                    if (options.group_id) url += '&group_id=' + options.group_id;
                    if (options.tags) url += '&tags=' + options.tags;
                    if (options.tag_mode) url += '&tag_mode=' + options.tag_mode;
                    if (options.text) url += '&text=' + options.text;
                    break;
                default:
                    url += '&method=flickr.photos.getRecent';
            };
            if (options.size == 'o') url += '&extras=original_format';
            if (options.type != 'photosets') url += '&per_page=' + options.per_page + '&page=' + options.page;
            return url;
        }
    };
})(jQuery);
