(function($){

    $.albums = {
        albumId: null,
        photoId: null
    };

    $.albums.setAlbumId = function(id){
        $.albums.albumId = id;
    }

    $.albums.setPhotoId = function(id){
        $.albums.photoId = id;
    }

    /**
     * 指定の写真にフォーカスを合わせる
     */
    $.fn.forcusPhoto = function() {

        var thumbnail = this;
        $(thumbnail).activateThumbnail($(thumbnail).parents('.scrollable'));
        $('.social').slideUp();

        //写真を表示する
        var url = $(this).children('img').data('photoUrl');
        $('#view').showPhoto(url, function(img){
            $('#photo_title a').setPhotoTitle($(thumbnail).attr('id'), function(){
                 // ソーシャルボタンの切換
                var shareTitle = $('#photo_title a').text() + ' - ' + document.title;
                $('.social>.tweet').socialbutton('twitter', {
                    button: 'horizontal',
                    via: 'photoaraki'
                });
                $('.social>.tumblr').socialbutton('tumblr', {
                    button: '../img/tumblr.gif',
                    title: shareTitle});
                $('.social').slideDown();
            })
            .attr('href', '#!/photoset' + $(thumbnail).data('photosetId') + '_' + $(thumbnail).attr('id'));

            $(thumbnail).showMarker();
            location.hash = $('#photo_title a').attr('href');
        });

        // first_slide_time待ってからタイマーロッックを解除
        $(this).parents('.scrollable').lockAutoSlide($.gallery.firstSlideTime);
    }

    /**
     * アルバムにフォーカスを合わせる
     */
    $.fn.forcusAlbum = function(target){

        this.activateThumbnail(target);

        //フォトセットから写真一覧を取得し、サムネイルを表示する
        var _photoSet = this.data('photoSet');

        //既に表示されているサムネイルを削除
        $('.items', target).empty();

        //サムネイルを取得、設定
        for(var i=0; i<_photoSet.photo.length; i++) {

            //写真のURL
            var url = $.flickr.getPhotoUrl(_photoSet.photo[i]);

            //サムネイル画像のURL
            var resizeUrl = $.gallery.getResizeImageUrl('65', url);

            var div = $('<div>').append(
                $('<img>')
                .attr('src', resizeUrl)
                .css('width', 65)
                .data('photoUrl', url)
                )
            .attr('class', 'photo')
            .attr('id', _photoSet.photo[i].id)
            .data('photosetId', _photoSet.id)
            .css('opacity', 0.3)
            .click(function(){
                $(this).forcusPhoto();
            });

            div.setThumbnailHover();

            $(target).data('scrollable').addItem(div);
        }

        // マーカーをセット
        $(this).showMarker();
        // スクロール位置を調整
        $(target).resetScroll();

        if ($.albums.photoId != null && $('#' + $.albums.photoId, target).size() > 0) {
            // 指定IDの写真をクリック
            $('#' + $.albums.photoId, target).click();
            // オートスライドを停止
            $(target).data('autoSlide').stop();

        } else {
            // 一番最初の写真をクリック
            if ($('.items .photo', target).size() > 0) {
                $('.items .photo:first', target).click();
            }
        }
    };

    /**
     * エレメントにphotset情報をセット
     */
    $.fn.setAlbum = function(album, params) {

        if (!album) return;

        var defaults = {
            activate: false,
            context: '#album_scroll'
        };
        params = $.extend({}, defaults, params);

        var element = this;
        var box = params.context;

        // Photosetの情報を取得して
        $.flickr.getPhotosFromPhotoSet(album.id, function(data){

            // アルバムの表紙絵を設定する
            var img = $('<img>')
            .css('width', '65px')
            .css('height', '40px')
            .attr('src', $.gallery.getResizeImageUrl('65',
                $.flickr.getPhotoUrl($.flickr.getPrimaryPhoto(data))));

            // idをセット
            $(element).attr('id', 'ps_' + album.id)
            .append(img)
            .append($('<a>').text(album.title).attr('href', '#photoset' + album.id));

            // loading画像の消去
            if ($('.loading', box).size() > 0) {
                $('.loading', box).remove();
                box.parents('.controller').height(20);
                box.height(0);
            }

            if ( box.height() < 400 ) {
                // srcrollの高さ調整
                var appendHeight = element.height() + 10;
                box.parents('.controller').height(box.parents('.controller').height() + appendHeight);
                box.height(box.height() + appendHeight);
            }
            
            // photosetの情報を保存しておく
            element.data('photoSet', data.photoset);

            if ($.albums.albumId == album.id) {
                element.click();
            }

        });
    }

    /**
     * アルバムの読み込み
     */
    $.fn.setAlbums = function(albums, params) {

        if (!albums) return;

        var defaults = {
            context: this,
            photoTarget: '#photo_scroll'
        };
        params = $.extend({}, defaults, params);

        for (var i = 0; i < albums.length; i++) {

            var div = $('<div>')
            .attr('class', 'album')
            .css('opacity', 0.3)
            .click(function(){
                $(this).forcusAlbum(params.photoTarget);
            })
            .setThumbnailHover();

            $(this).data('scrollable').addItem(div);

            div.setAlbum(albums[i], params);

        }

    };
})(jQuery);

/**
 * 初期化処理
 */
var initGallery = function(){
    // == スクロールをセット
    var scrollOptions = {
        vertical: true,
        mousewheel: true,
        next: '.nextPage',
        prev: '.prevPage',
        size: 3
    };

    $("#album_scroll").scrollable(scrollOptions);
    $("#photo_scroll").scrollable(scrollOptions);

}

/**
 * アルバムの読み出し
 */
var setupGallery = function(data, status, xhr){

    $.albums.setAlbumId(data[0].id);

    // photoset[0-9]+形式のアンカーが設定されている場合
    if (location.hash.match(/^#(?:!\/)?photoset([0-9]+)(?:_([0-9]+))?$/)) {
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == RegExp.$1) {
                // 指定のphotoSetIdが存在する場合
                $.albums.setAlbumId(data[i].id);
            }
        }
        if (RegExp.$2.length > 0) {
            // photoIdの指定
            $.albums.setPhotoId(RegExp.$2);
        }
    }

    $('#album_scroll').setAlbums(data);

    // オートスライド処理
    $('#photo_scroll').autoSlide($.gallery.slideTime, $.gallery.firstSlideTime);
}
