/*******************************
 * 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 = jQuery("[rel^='photosets']");

    if (element.length) {
	
        // Init list
        var root = jQuery('<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) {
	// console.log('App.Flickr.Photoset.setList');
	// console.log(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 = jQuery('<li></li>')
                .append(jQuery('<div></div>').attr({id: photoset.id}).append(jQuery('<a></a>').attr({href: '#' + photoset.id}))
                .append(jQuery('<span></span>').append(jQuery('<abbr></abbr>').append(photoset.title._content))));
            jQuery('#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) {
	// console.log(photosetId);
    // Get random photo as thumbnail
    var random = Math.floor(Math.random() * photos.length);
    App.Flickr.Photo.getPhotoThumbnail(photos, random);
    // Prepare photo section
    jQuery('#' + photosetId + ' a').attr({id: photos[random].id});
    // Add event for lightbox
    jQuery('#' + 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 (!jQuery('#photo').length) {
        // Build elements
        jQuery('body').append(jQuery('<div></div>').attr({id: 'overlay'}));
				if (galleryLink){
					jQuery('body').append(jQuery('<div>' + galleryLink + '</div>').attr({id: 'photo-zoom'}).append(jQuery('<div></div>').attr({id: 'photo'})));	
				} else {
					jQuery('body').append(jQuery('<div></div>').attr({id: 'photo-zoom'}).append(jQuery('<div></div>').attr({id: 'photo'})));	
				}

        
        // Add events
        jQuery('#photo').click(function() { return false; });
        jQuery('#overlay').click(function() {
            jQuery('#photo-zoom').css('display', 'none');
            jQuery('#photo').css('display', 'none');
            jQuery('#overlay').css('display', 'none');
            return false;
        });

    } else {
        // Show elements
        jQuery('#photo-zoom').css('display', 'block');
        jQuery('#photo').css('display', 'block').empty();
        jQuery('#overlay').css('display', 'block');
    }
    // Add loading
    if (!jQuery('#photo-loading').length) {
        jQuery('#photo').append(jQuery('<div></div>').attr({id: 'photo-loading'}));
    } else {
        jQuery('#photo-loading').css('display', 'block');
    }
    // Build controls
    var previous = jQuery('<a class="prev"></a>').attr({href: '#'}).append('<<');
    previous.click(function() {
        App.Flickr.Photoset.getPhotoZoom(photos, (index + photos.length - 1) % photos.length);
        return;
    });
    var next = jQuery('<a class="next"></a>').attr({href: '#'}).append('>>');
    next.click(function() {
        App.Flickr.Photo.getPhotoZoom(photos, (index + 1) % photos.length);
        return;
    });

		if (jQuery.browser.msie && jQuery.browser.version < 80){
			
		} else {
			jQuery('#photo').append(jQuery('<div></div>').attr({id: 'photo-controls'}).append(previous).append(next));	
		}

    
    // Prepare photo section
    jQuery('#photo').append(jQuery('<a></a>').attr({id: photo.id}));
    // Add photo info
    // return;
    jQuery('#photo').append(jQuery('<span></span>').attr({id: 'photo-info'}).append('Photo ' + (index + 1) + ' of ' + photos.length).append(jQuery('<img></img>)').attr({src: '/wp-content/plugins/flickr/jquery.flickr/img/close.gif'}).click(function() {
        jQuery('#photo-zoom').css('display', 'none');
        jQuery('#photo').css('display', 'none');
        jQuery('#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 = jQuery('<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 = 120;
            var max_height = 120;
            // 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 = jQuery(window).width();
            var window_height = jQuery(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
            jQuery('#overlay').css('height', jQuery(document).height()).css('width', jQuery(document).width());
            jQuery('#photo').animate(
                {
                    width: photo.width + 'px',
                    height: photo.height + 'px'
                }, 'normal', 'linear', function() {
                    img.css('display', 'block');
                    // Hide loading
                    jQuery('#photo-loading').css('display', 'none');
                    // Add events
                    img.hover(
                        function() {
                            jQuery('#photo-controls').css('display', 'block');
                        },
                        function() {
                            jQuery('#photo-controls').css('display', 'none');
                        }
                    );
                    jQuery('#photo-controls').hover(
                        function() {
                            jQuery('#photo-controls').css('display', 'block');
                        },
                        function() {
                            jQuery('#photo-controls').css('display', 'none');
                        }
                    );
                    // Show info
                    jQuery('#photo').animate(
                        {
                            height: jQuery('#photo').height() + 22 + 'px'
                        }, 'normal', 'linear', function() {
                            jQuery('#photo-info').css('display', 'block');
                        }
                    );
                }
            );
            jQuery('#photo-zoom').animate({
                top: jQuery(window).scrollTop() + zoom_top,
                left: zoom_left,
                width: parseInt(photo.width) + 22
            });
            // Update controls
            jQuery('#photo-controls').css('width', photo.width + 'px');
            break;
    }
    // Update photo
    img.css('width', photo.width + 'px').css('height', photo.height).css('top', '-' + top + 'px').css('left', '-' + left + 'px');
    // Insert photo
    jQuery('#' + 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;
    jQuery.each(data, function(key, value) {
        url += "&" + key + "=" + value;
    });
    jQuery.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);
}

