/*******************************
 * Flickr'n'jQuery
 *******************************
 * Author: Mickael BLATIERE (blatiere@gmail.com)
 * Last update: 12/09
 ******************************/

App = {};
App.Flickr = {};
App.Flickr.Url = "http://api.flickr.com/services/rest/";

App.Flickr.start = function() {
    App.Flickr.Photoset.start();
}


/*******************************
 * PHOTOSETS
 ******************************/

App.Flickr.Photoset = {};

App.Flickr.Photoset.start = function() {
    var element = $("[rel^='photosets']");
    if (element) {
        // Init list
        var root = $('<ul></ul>').attr('id', 'photosets');
        element.append(root);
        // Init parameters
        App.Flickr.Photoset.userId = element.attr('id');
        var count = element.attr('rel').match('[0-9]+');
        if (count) {
            App.Flickr.Photoset.count = count;
        }
        // Get list
        App.Flickr.Photoset.getList();
    }
}

App.Flickr.Photoset.getList = function() {
    // Request data
    var method = "flickr.photosets.getList";
    App.Flickr.Request(method, {user_id: App.Flickr.Photoset.userId});
}

App.Flickr.Photoset.setList = function(photosets) {
    App.Flickr.Photoset.photosets = [];
    // Parse data
    var index = 0;
    var more = true;
    for (index; (!App.Flickr.Photoset.count || index < App.Flickr.Photoset.count) && more; index++) {
        var photoset = photosets[index];
        if (photoset) {
            App.Flickr.Photoset.photosets[index] = photoset;
            // Build list
            var element = $('<li></li>')
                .append($('<div></div>').attr({id: photoset.id}).append($('<a></a>').attr({href: '#' + photoset.id}))
                .append($('<span></span>').append($('<abbr></abbr>').append(photoset.title._content))));
            $('#photosets').append(element);
        } else {
            more = false;
        }
    }
    // Get photos foreach photosets
    App.Flickr.Photoset.getPhotos();
}

App.Flickr.Photoset.getPhotos = function() {
    var method = "flickr.photosets.getPhotos";
    var index = 0;
    for (index; index < App.Flickr.Photoset.photosets.length; index++) {
        // Request data from each photoset
        App.Flickr.Request(method, {photoset_id: App.Flickr.Photoset.photosets[index].id});
    }
}
App.Flickr.Photoset.setPhotos = function(photosetId, photos) {
    // Get random photo as thumbnail
    var random = Math.floor(Math.random() * photos.length);
    App.Flickr.Photo.getPhotoThumbnail(photos, random);
    // Prepare photo section
    $('#' + photosetId + ' a').attr({id: photos[random].id});
    // Add event for lightbox
    $('#' + photosetId).click(function() {
        App.Flickr.Photo.getPhotoZoom(photos, 0);
        return false;
    });
}


/*******************************
 * PHOTOS
 ******************************/

App.Flickr.Photo = {};

App.Flickr.Photo.getPhotoZoom = function(photos, index) {
    App.Flickr.Photo.Size = 4;
    // Get data
    var photo = photos[index];
    var method = "flickr.photos.getSizes";
    App.Flickr.Request(method, {photo_id: photo.id});
    // Init
    if (!$('#photo').length) {
        // Build elements
        $('body').append($('<div></div>').attr({id: 'overlay'}));
        $('body').append($('<div></div>').attr({id: 'photo-zoom'}).append($('<div></div>').attr({id: 'photo'})));
        // Add events
        $('#photo').click(function() { return false; });
        $('#overlay').click(function() {
            $('#photo-zoom').css('display', 'none');
            $('#photo').css('display', 'none');
            $('#overlay').css('display', 'none');
            return false;
        });
    } else {
        // Show elements
        $('#photo-zoom').css('display', 'block');
        $('#photo').css('display', 'block').empty();
        $('#overlay').css('display', 'block');
    }
    // Add loading
    if (!$('#photo-loading').length) {
        $('#photo').append($('<div></div>').attr({id: 'photo-loading'}));
    } else {
        $('#photo-loading').css('display', 'block');
    }
    // Build controls
    var previous = $('<a class="prev"></a>').attr({href: '#'}).append('<<');
    previous.click(function() {
        App.Flickr.Photoset.getPhotoZoom(photos, (index + photos.length - 1) % photos.length);
        return;
    });
    var next = $('<a class="next"></a>').attr({href: '#'}).append('>>');
    next.click(function() {
        App.Flickr.Photo.getPhotoZoom(photos, (index + 1) % photos.length);
        return;
    });
    $('#photo').append($('<div></div>').attr({id: 'photo-controls'}).append(previous).append(next));
    // Prepare photo section
    $('#photo').append($('<a></a>').attr({id: photo.id}));
    // Add photo info
    $('#photo').append($('<span></span>').attr({id: 'photo-info'}).append('Photo ' + (index + 1) + ' sur ' + photos.length).append($('<img></img>)').attr({src: 'css/img_flickr/close.gif'}).click(function() {
        $('#photo-zoom').css('display', 'none');
        $('#photo').css('display', 'none');
        $('#overlay').css('display', 'none');
        return false;
    })));
}

App.Flickr.Photo.getPhotoThumbnail = function(photos, index) {
    App.Flickr.Photo.Size = 3;
    // Get data
    var method = "flickr.photos.getSizes";
    App.Flickr.Request(method, {photo_id: photos[index].id});
}

App.Flickr.Photo.setPhoto = function(photo) {
    // Get photo
    photo = photo[App.Flickr.Photo.Size];
    var photoId = photo.url.match('[0-9]+');
    // Build element
    var img = $('<img></img>').attr({src: photo.source});
    // Calculate dimensions and positions
    var top = 0;
    var left = 0;
    switch (App.Flickr.Photo.Size) {
        // Thumbnail mode
        case 1:
        case 2:
        case 3:
            var max_width = 190;
            var max_height = 190;
            // Resize height
            if (photo.width < max_width) {
                photo.height = photo.height * max_width / photo.width;
                photo.width = max_width;
            }
            // Resize width
            if (photo.height < max_height) {
                photo.width = photo.width * max_height / photo.height;
                photo.height = max_height;
            }
            // Resample photo
            if (photo.width > max_width && photo.height > max_height) {
                if (photo.width < photo.height) {
                    photo.height = photo.height * max_width / photo.width;
                    photo.width = max_width;
                } else {
                    photo.width = photo.width * max_height / photo.height;
                    photo.height = max_height;
                }
            }
            // Sqare
            if (photo.width > max_width || photo.height > max_height) {
                if (photo.width > max_width) {
                    left = (photo.width - max_width) / 2;
                }
                if (photo.height > max_height) {
                    top = (photo.height - max_height) / 2;
                }
            }
            break;
        // Zoom mode
        case 4:
            var window_width = $(window).width();
            var window_height = $(window).height();
            var max_width = window_width - 100;
            var max_height = window_height - 150;
            // Resize photo
            if (photo.width > max_width || photo.height > max_height) {
                if (photo.width / photo.height > max_width / max_height) {
                    photo.height = photo.height * max_width / photo.width;
                    photo.width = max_width;
                } else {
                    photo.width = photo.width * max_height / photo.height;
                    photo.height = max_height;
                }
            }
            var zoom_left = (window_width - photo.width) / 2;
            var zoom_top = (window_height - photo.height - 50) / 2;
            img.css('display', 'none');
            // Update context
            $('#overlay').css('height', $(document).height()).css('width', $(document).width());
            $('#photo').animate(
                {
                    width: photo.width + 'px',
                    height: photo.height + 'px'
                }, 'normal', 'linear', function() {
                    img.css('display', 'block');
                    // Hide loading
                    $('#photo-loading').css('display', 'none');
                    // Add events
                    img.hover(
                        function() {
                            $('#photo-controls').css('display', 'block');
                        },
                        function() {
                            $('#photo-controls').css('display', 'none');
                        }
                    );
                    $('#photo-controls').hover(
                        function() {
                            $('#photo-controls').css('display', 'block');
                        },
                        function() {
                            $('#photo-controls').css('display', 'none');
                        }
                    );
                    // Show info
                    $('#photo').animate(
                        {
                            height: $('#photo').height() + 22 + 'px'
                        }, 'normal', 'linear', function() {
                            $('#photo-info').css('display', 'block');
                        }
                    );
                }
            );
            $('#photo-zoom').animate({
                top: $(window).scrollTop() + zoom_top,
                left: zoom_left,
                width: parseInt(photo.width) + 22
            });
            // Update controls
            $('#photo-controls').css('width', photo.width + 'px');
            break;
    }
    // Update photo
    img.css('width', photo.width + 'px').css('height', photo.height).css('top', '-' + top + 'px').css('left', '-' + left + 'px');
    // Insert photo
    $('#' + photoId).attr({id: ''}).prepend(img);
}


/*******************************
 * COMMON
 ******************************/

App.Flickr.Request = function(method, data) {
    var url = App.Flickr.Url + "?format=json&method=" + method + "&api_key=" + App.Flickr.ApiKey;
    $.each(data, function(key, value) {
        url += "&" + key + "=" + value;
    });
    $.getScript(url);
};

function jsonFlickrApi(rsp){
    if (rsp.stat != "ok") {
        console.log(rsp.message);
        return;
    }
    if (rsp.photosets) App.Flickr.Photoset.setList(rsp.photosets.photoset);
    if (rsp.photoset) App.Flickr.Photoset.setPhotos(rsp.photoset.id, rsp.photoset.photo);
    if (rsp.sizes) App.Flickr.Photo.setPhoto(rsp.sizes.size);
}

