/**
 * Firebug log wapper
 * 
 * @param value
 * @return
 */
function log(value)
{
    if (typeof console != "undefined") {
        console.log(value);
    }
}


/**
 * Flickrからのレスポンスオブジェクト
 */
var photos;

/**
 * サムネイルリスト
 */
var thumbnails;

/**
 * 現在の表示インデックス
 */
var current_index = 0;

/**
 * サムネイルのスクロールで１回あたりに上方向へ進む距離
 */
var scroll_interval = 0;

/**
 * 切替時間 (ms)
 */
var slide_time = 5 * 1000;

/**
 * 初回時の切替時間 (ms)
 */
var first_slide_time = slide_time * 2;

/**
 * タイマー処理のロック用
 */
var timer_lock = false;

/**
 * オートスライドタイマールーチン
 */
var scroll_timer = null;

/**
 * jQuery get callback 取得したアルバムIDの処理
 * 
 * @param photoset_id
 */
function setPhotoSetID(photoset_id)
{
    if (!photoset_id) {
        return;
    }
    
    // photosetの取得
    getPhotosFromPhotoSet(photoset_id, setPhotos);
};

/**
 * photoset取得時のcallback
 * 
 * @param data
 */
function setPhotos(data)
{
    
    if (!data) {
        return;
    }
    
    if (!data.photoset) {
        return;
    }
    
    photos = data.photoset.photo;
    
    // -- サムネイル画像の生成
    var ul = $('#list ul');
    thumbnails = new Array(photos.length);
    
    $('#list ul li.loading').remove();
    
    for ( var i = 0; i < photos.length; i++) {
        var img = $('<img>')
                        .attr('src', getResizeImageUrl('30', getThumbnailPhotoUrl(photos[i])))
                        .attr('id', 'thumbnail-' + i)
                        .css('width', '30px')
                        .css('height', '20px')
                        .click(photoScrollTo)
        				.hover(
	        				function() {
	        					$(this).addClass('hover');
	        				},
	        				function() {
	        					$(this).removeClass('hover');
	        			});
        
        thumbnails[i] = img;
        
        ul.append($('<li>').append(img));
    }
    
    // 最初のイメージをセレクト
    $('#list ul li:first img').addClass('active');
    
    // サムネイルのスクロールで１回あたりに上方向へ進む距離=(サムネイル画像全体の高さ-表示領域の高さ)/サムネイルの個数
    var img_height = $('#list li:not(.loading):first').height();
    scroll_interval = ((img_height * thumbnails.length) - $('#list').height()) / (thumbnails.length - 1);

    // 画像の読み込み
    current_index = 0;
    loadImage(current_index, hide_loading());
    
    // prev,nextイベントフック
    $('#photo_prev').click(prev);
    $('#photo_next').click(next);
    
    scroll_timer = jQuery.timer(first_slide_time, function(timer){
        
        if (timer_lock) {
            return false;
        }
        
        // intervalの変更
        if (timer.interval != slide_time) {
            timer.reset(slide_time);
        }
        
        current_index++;
        
        // 下まで行ったら上へ戻る
        if (thumbnails.length <= current_index) {
            current_index = 0;
        }
        
        loadImage(current_index);
    });
}

/**
 * クリックされた画像にスクロール  
 */
function photoScrollTo()
{
    if ($(this).attr('id').match(/thumbnail-([0-9]+)$/)) {
        moveTo((RegExp.$1) - 0);
    } else {
        return;
    } 
}

/**
 * 前の画像へ
 * @return
 */
function prev(){
    moveTo(current_index - 1);
    return false;
}

/**
 * 次の画像へ
 * @return
 */
function next(){
    moveTo(current_index + 1);
    return false;
}


/**
 * クリック等のイベントによる画像移動
 * 
 * @param idx
 * @return
 */
function moveTo(idx){
    
    if (timer_lock) {
        return false;
    }
    
    // タイマー処理を中断
    timer_lock = true;
    
    current_index = idx;
    if (current_index < 0) {
        current_index = 0;
    } else if (thumbnails.length <= current_index) {
        current_index = 0;
    }
    
    // loading表示
    show_loading();
    
    // メイン画像の準備
    loadImage(current_index, function(){
            hide_loading();
            // slide_time待つ
            scroll_timer.reset(slide_time);
        });
}

//マーカーを表示する
function showMaker(li) {
	$('.current_marker').remove();
	li.append(
		$('<img>')
			.attr('class', 'current_marker')
			.attr('src', './img/common/current_marker.gif')
			.css('opacity', '0.7')
	);
}

/**
 * 画像のロード
 * 
 * @param idx
 * @param callback
 * @return
 */
function loadImage(idx, callback) {
    
    timer_lock = true;
    
    var img = new Image()
    $(img).load(function(){
        
        // 画像追加
        $(this).attr('id', 'main-img-' + idx)
        .attr('alt', photos[idx].title)
        .css('z-index', 999 - idx)
        .css('opacity', 0.0)
        .appendTo('#cover .main-img');

        if($(this).height() < $(this).width()) {
            //横長の画像の場合
            $(this)
                .attr('width', '600')
                .removeAttr('height');
            $(this).css('left', 0);
            $(this).parent().css('marginTop', '92px');
        } else {
            //縦長の画像の場合
            $(this)
                .attr('height', '500')
                .removeAttr('width');
            $(this).css('left', (600 - $(this).width()) / 2);
            $(this).parent().css('marginTop', '37px');
        }

        // サムネイルをスクロール
        thumbnailScrollTo(idx);
        
        // 画像切替（クロスフェード）
        if ( $('#cover .active').size() > 0 ) {
            // 表示中の画像をフェードアウト + 削除
            $('#cover .active')
                .fadeTo(1000, 0.0, function(){ $(this).remove() })
                .css('z-index',999 - (thumbnails.length - 1));
            
            $(this)
                .addClass('active')
                .show()
                .fadeTo(1000, 1.0, function(){
                        if (typeof callback == 'function') {
                            callback(this);
                        }
                        setTitle(idx);
                        setMainHeight(idx);
                        timer_lock = false;
                    })
                .css('z-index', 1000);
            
        } else {
            // 最初の画像はそのまま表示
            $(this).addClass('active').css('z-index', 1000).css('opacity', 1.0).show();
            
            if (typeof callback == 'function') {
                callback(this);
            }
            
            setTitle(idx);
            setMainHeight(idx);
            
            timer_lock = false;
        }
        
    });
    img.src = getPhotoUrl(photos[idx]);
}

/**
 * 指定したindexのタイトル取得
 * @param idx
 * @return string
 */
function setTitle(idx) {
    $('#photo_title span').text(photos[idx].title);
}

/**
 * 画像領域の高さ調整
 * @param idx
 * @return
 */
function setMainHeight(idx){
    // 高さを調整
    var h = $('#main-img-' + idx).height() - 0;
    $('.main-img').height(h);
}

/**
 * 指定したindexのサムネイルへスクロール
 * @param idx
 * @return
 */
function thumbnailScrollTo(idx){
    
    // サムネイルのactiveを解除
    $('#list li:not(.loading) img.active').removeClass('active');

    // 現在のサムネイル画像の半透明化を解除
    thumbnails[idx].addClass('active');
    showMaker(thumbnails[idx].parent());
    
    // サムネイルのスクロール
    $('#list ul').animate({ top : -Math.ceil(scroll_interval * idx) + 'px' },{ duration : 'slow' });
    
}

/**
 * loading画像の表示
 * @return
 */
function show_loading() {
    $('#cover .active').remove();
    $('#cover .loading').show();
}

/**
 * loading画像を隠す
 * @return
 */
function hide_loading() {
    $('#cover .loading').hide();
    $('#cover .main-img img:first').addClass('active').css('opacity', 1.0).css('z-index', 1000);
    $('#cover .main-img').show();
}
