//photosetの情報を保存しておく配列
var photoset = Array();

//現在選択されているアルバム
var currentAlbum = -1;
var currentThumbnail = -1;

//サムネイルに割り当てられたIDからPhotoを取得する
function getCurrentPhoto() {
	return photoset[currentAlbum].photoset.photo[currentThumbnail];
}

//選択された画像のサイズ情報を設定する。
function setSize(data) {
	$('#type').empty();
	for(var i=0; i<data.length; i++) {
		$('#type').append($('<option>').text(data[i].size).attr('id', data[i].id));
	}
	
	//ダウンロードフォームを表示する
	$('#download_form').show('fast');
}

//サムネイルがクリックされたときの処理を行う
function thumbnailClick() {

	activate($(this));
	
	//現在選択されているサムネイルの番号
	currentThumbnail = $(this).children('img').attr('id');
	
	//写真を表示する
	var url = getPhotoUrl(getCurrentPhoto());
	showPhoto(url);
	
	//サイズ情報を取得する
	//サイズが取得できるまではダウンロードフォームを隠す
	$('#download_form').hide();
	$.getJSON('./freedownload_photo_sizes/size/' + getCurrentPhoto().id, setSize);
	
	setPhotoTitle($(this));
	showPhotoMarker($(this));
}

function forcusAlbum(album) {
	activate(album);
	
	//フォトセットから写真一覧を取得し、サムネイルを表示する
	currentAlbum = album.attr('id');
	var set = photoset[currentAlbum].photoset;
	
	//既に表示されているサムネイルを削除
	$('#photo_scroll .items').empty();
	
	//サムネイルを取得、設定
	for(var i=0; i<set.photo.length; i++) {
		//写真のURL
		var url = getPhotoUrl(set.photo[i]);
		//サムネイル画像のURL
		var resizeUrl = getResizeImageUrl('65', url);
		
		var div = $('<div>').append(
			$('<img>')
				.attr('src', resizeUrl)
				.attr('id', i)
				.css('width', 65)
		)
		.attr('class', 'photo')
		.attr('id', set.photo[i]['id'])
		.css('opacity', 0.3)
		.click(thumbnailClick);
		setThumbnailHover(div);

		$('#photo_scroll .items').append(div);
	}
	
	showAlbumMarker(album);
	photoScrollReset();
	
    // 一番最初の写真をクリック
    if ($('#photo_scroll .items').size() > 0) {
        $('#photo_scroll .items div:first').click();
    }
}

//アルバムがクリックされたときの処理を行う
function clickAlbum() {
	forcusAlbum($(this));
}

//ギャラリーに表示するアルバムをセットする
function setGalleryAlbum(album) {
	if(!album)return;
	
	var div = $('<div>')
		.attr('class', 'album')
		.css('opacity', 0.3)
		.click(clickAlbum);
	
	setThumbnailHover(div);
	
	$('#album_scroll div.items:first').append(div);
	
	//Photosetの情報を取得して
	getPhotosFromPhotoSet(album.id, function(data){
		
		//アルバムの表紙絵を設定する
		var img = $('<img>')
			.css('width', '65px')
			.css('height', '40px')
			.attr('src', getResizeImageUrl('65', getPhotoUrl(getPrimaryPhoto(data))));
		div
			.attr('id', photoset.length)
			.append(img)
			.append($('<span>').text(album.title));

	    // loading画像の消去
        if ($('#album_scroll .loading').size() > 0) {
            $('#album_scroll .loading').remove();
            $('#album_controll').height(20);
            $('#album_scroll').height(0);
        }
        
        if ( $('#album_scroll').height() < 400 ) {
            // srcrollの高さ調整
            var appendHeight = div.height() + 10;
            $('#album_controll').height($('#album_controll').height() + appendHeight);
            $('#album_scroll').height($('#album_scroll').height() + appendHeight);
        }

		//photosetの情報を保存しておく
		photoset.push(data);
		
		if (photoset.length == 1) {
            // 最初のアルバムであればクリック
            forcusAlbum(div);
        }
	});
};

function setGallery(data) {
	for(var i=0; i<data.length; i++) {
		setGalleryAlbum(data[i]);
	}
};

function initGallery() {
	$.getJSON('./freedownloadsAlbums/', setGallery);
};

//サイズを選んでダウンロードボタンを押したとき
function confilmClick() {
	//確認画面に現在選択されている写真を表示する
	//選択しているかどうか調べる
	if(!$('#view img').attr('src'))return;
		
	$('#download_image')
		.attr('src', $('#view img').attr('src'))
		.css('width', '200px');
}

//overlay
var confilm;
var thanks;

function requestFinished(data) {
	if (!data.success) {
	    // 処理に失敗した場合
	}
    $('#thanks .messages').html(data.message);
}

//確認画面でダウンロードをクリックしたとき
function downloadClick() {
    $('#thanks .messages').html('ダウンロードファイルを生成しています...');
    
	var mail = $('#email_address').val();
	var id = $('option:slected').attr('id');
	$.post('./freedownload_requests/request/', {"data[FreedownloadRequest][freedownload_photo_size_id]": id, "data[FreedownloadRequest][email]": mail}, requestFinished, 'json');

	// 確認画面を閉じる
	confilm.close();
	
	//フォームの内容を消去する
	$('#agree_check').attr('checked', '');
	$('#download_submit').attr('disabled', 'true');
	$('#email_address').val('');
}

$(function() {
	$('#album_next').click(
			function() {
				$("div.scrollable").scrollable({api: true}).next();
			}
	);
	
	initScroll();	
	initGallery();
	
	//オーバーレイ
	confilm = $('#submit').overlay({
	    expose: '#000', oneInstance: false, api: true,
	    onBeforeLoad: function(){ confilmClick(); $('select').hide(); },
	    onBeforeClose: function(){$('select').show();}
    });
	thanks = $('#download_submit').overlay({
	    expose: '#000', oneInstance: false, api:true,
	    onBeforeLoad: function(){ downloadClick(); $('select').hide(); },
	    onBeforeClose: function(){$('select').show();}
   });
	
	//規約に同意ボタン
	$('#agree_check').click(function(data){
	    $('#download_submit').attr('disabled', !$(this).attr('checked'));
	});
});
