// epoch time から文字列の日時表記に変換する
function epoch2date (time, splitter){
	var date = new Date();
	date.setTime(Number(time)*1000);

	var year  = date.getFullYear();
	var month = date.getMonth() + 1;
	if (month < 10) month = "0" + month;
	var day   = date.getDate();
	if (day < 10) day = "0" + day;

	return year + splitter + month + splitter + day;
}

function epoch2datetime (time){
	var date = new Date();
	date.setTime(Number(time)*1000);

	var year    = date.getFullYear();
	var month   = date.getMonth() + 1;
	if (month < 10) month = "0" + month;
	var day     = date.getDate();
	if (day < 10) day = "0" + day;
	var hours   = date.getHours();
	if (hours < 10) hours = "0" + hours;
	var minutes = date.getMinutes();
	if (minutes < 10) minutes = "0" + minutes;
	var seconds = date.getSeconds();
	if (seconds < 10) seconds = "0" + seconds;

	return year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
}

// メッセージをlightboxな感じで表示する
function modal_message_open(message){
	$('#wait_message_label').html(message);
	$('#wait_message_panel').show();
	
	//$('#modal-message-overlay').show();
	//$('#modal-message-window').html(message).show();
}
function modal_message_close(){
	$('#wait_message_panel').hide();
	//$('#modal-message-overlay').hide();
	//$('#modal-message-window').hide();
}

//アラート
function modal_alert_open(message){
	$('#modal-alert-overlay').show();
	$('#modal-alert-label').html(message);
	$('#modal-alert-window').show();
}

//バルーン
function balloon_open(message, parent, position, offset){
	var label_css = {};
	if (position == 'l') {
		label_css.left = parent.offset().left;
	} else {
		label_css.left = parent.offset().left;
	}
	if (!offset) { offset = 40; }
	label_css.top = parent.offset().top - offset;

	var msg = message;
	if (typeof(message) == 'function') {
		msg = message();
	}
	$('#balloon_text_' + position).html(msg);
	$('#balloon_label_' + position).css(label_css);
	if (position == 'r') {
		var original_left = label_css.left;
		while (1) {
			var last_width = $('#balloon_label_' + position).width();
			label_css.left = original_left - last_width + 10;
			$('#balloon_label_' + position).css(label_css);
			$('#balloon_text_' + position).html(msg);
			if (last_width == $('#balloon_label_' + position).width()) break;
		}
	}

	$('#balloon_label_' + position).show();
}
function balloon_close(position){
	$('#balloon_label_' + position).hide();
}
function balloon_install (dom, msg, position, offset) {
	var t_id = null;
	dom.mousemove(function (e) {
		e.preventDefault();
		if (t_id === null && dom.hasClass('enablemenu')) {
			t_id = setTimeout(function(){ balloon_open(msg, dom, position, offset) }, 100);
		}
	});
	dom.mouseout(function (e) {
		e.preventDefault();
		clearTimeout(t_id);
		t_id = null;
		balloon_close(position);
	});
}


// load swf
function load_swfobject(id, url, width, height, par, version, not_install_cb){
	var att = {
		data:   url,
		width:  width,
		height: height
	};

	if (swfobject.hasFlashPlayerVersion(version)) {
		return swfobject.createSWF(att, par, id);
	} else if (swfobject.getFlashPlayerVersion().major) {
		/* 古いバージョン */
		att.data = "/common/expressInstall.swf";
		return swfobject.showExpressInstall(att, {}, id);
	} else {
		/* install されていない */
		if (not_install_cb && typeof not_install_cb == 'function') return not_install_cb();
	}
}

//イメージをロードする。
function _loadImageSetMargin(img, max, wOfImage, hOfImage){
	var margin;
	if (wOfImage > hOfImage) {
		hOfImage = max / wOfImage * hOfImage;
		wOfImage = max;
		margin = (max - hOfImage) / 2;
		if (margin) img.css({'padding-top':margin+'px', 'padding-bottom':margin+'px'});
	} else {
		wOfImage = max / hOfImage * wOfImage;
		hOfImage = max;
		margin = (max - wOfImage) / 2;
		if (margin) img.css({'padding-left':margin+'px', 'padding-right':margin+'px'});
	}
}
function loadImage(img, src, max, obj, callback, noimagesrc){
	var imgObj = null;
	var loop_count = 0;

	var onload = function(){
		var imgObj = new Image();
		imgObj.src = img.attr('src');
		var wOfImage = imgObj.width;
		var hOfImage = imgObj.height;

		// widthとheightが取得出来なかったらretryする
		if (!(wOfImage && hOfImage)) {
			loop_count++;
			if (loop_count > 100) {
				// 100回retryしてもだめだったら諦める
				img.show();
			} else {
				setTimeout(onload, 100);
			}
			if (callback) {
				// 先にcallbackを実行しちゃう
				callback(img);
				callback = false;
			}
			return;
		}

		_loadImageSetMargin(img, max, wOfImage, hOfImage);

		if (wOfImage && hOfImage) {
			img.width(wOfImage);
			img.height(hOfImage);
			if (obj) {
				obj.width  = wOfImage;
				obj.height = hOfImage;
			}
		}

		img.show();
		if (callback) callback(img);
	};

	imgObj = new Image();
	imgObj.src = src;

	img.error(function(){
		img.attr("src", noimagesrc);
	});
	if (imgObj.width) {
		// キャッシュなどにより、既に画像が読み込まれている
		img.hide();
		img.attr("src", src);
		setTimeout(onload, 1);
	} else {
		imgObj = null;
		img.unbind('load');
		img.load(onload);
		img.hide();
		img.attr("src", src);
	}
}


//PhotoList ========================================================
function PhotoList(args){
	this.base_path      = args.base_path;
	this.user_id        = args.user_id;
	this.img_base_url   = args.img_base_url;
	this.static_base_uri = args.static_base_uri;
	this.viewer_user_id = args.viewer_user_id;
	this.is_member_view = args.is_member_view;

	this.thumnail_imagesize = 90;
	if ($.browser.msie) {
		// IE は photo_thumbnail_image の border の数値が加算されるので、width/height/marginを調整する
		this.thumnailsize           = 94;
		this.thumnail_margin_right  = 8;
		this.thumnail_margin_bottom = 33;
	} else {
		this.thumnailsize           = 90;
		this.thumnail_margin_right  = 10;
		this.thumnail_margin_bottom = 35;
	}
}
PhotoList.prototype = {
	base_path: null,
	user_id: null,
	img_base_url: null,
	static_base_uri: null,
	viewer_user_id: null,
	album: null, // 今現在表示中のアルバム
	gallery: null, // gallery の AlbumList が置かれている
	album_list: null, // member page の AlbumList が置かれている
	is_good_checked: false,//パフォーマンス向上のため
	is_comment_checked: false,
	is_photo_loading: false, // 詳細画像のロード中
	is_paging: false, // ページング機能を使うモード
	is_photoviewer: false, // 現在 preview mode かどうか
	is_print: false, // プリントする写真を表示する mode かどうか

	slide_photo_list: null,//スライドショー中の写真群
	slide_photo_selected_index: -1,
	current_photo: null, // 現在プレビューしてる photo object
	current_photo_css: "",//現在の写真サイズcss
	current_target: "gallery",
	current_target_args: "",
	photo_list_scrollTop:0,

	photo_list: [],// 現在のphoto情報のデータをリストで持つ
	page_list: [],// 取り込んだページのリスト
	thumnail_status_list: [],// サムネイルのDOMのステータスリスト
	show_page_list: [],// 表示されてるページのリスト
	load_page_list: [],// ロードされてるページのリスト

	page_items: 50,// 1 page 当りの photo の数
	thumnailsize: 90,//サムネイルサイズ
	thumnail_margin_right: 10,
	thumnail_margin_bottom: 35,
	thumnail_datediv_height: 16,
	thumnail_datediv_height_padding: 5,
	thumnail_width: 90 + 10,
	slidebar_thumnail_width: 90,
	slidebar_thumnail_margin: 10,
	slidebar_center_id: 0,// スライドバーの真ん中の写真ID
	slidebar_first_id:0, 
	slidebar_last_id:0, 
	
	// サムネイル画像のサイズ情報
	thumnail_height: 0,
	thumnail_cols: 0,
	thumnail_rows: 0,
	thumnail_items: 0,// 1画面当りで表示可能な画像数

	margin_views: 0.1, // 描画領域の上下何ページ分でpreloadしておくか
	current_center_id: -1, // 現在真ん中に描画されている画像のID
	current_first_id: -1, // 現在一番最初に表示されている写真ID
	current_last_id: -1, // 現在一番最後に表示されている写真ID
	current_focus_id: null, // 選択中のID (キーバインドで動かすに対象になる)

	// photolist_view の高さ調整のDIV
	photolist_top_space: 0,
	photolist_bottom_space: 0,
	photolist_height: 0,

	by_date: {}, // 日付別に写真のidxの最初と最後を覚えておく
	
	//選択系
	SELECT_ACTION_CLICK:0,
	SELECT_ACTION_CLICK_WITH_SHIFT:1,
	SELECT_ACTION_CLICK_WITH_CONTROL:2,
	SELECT_ACTION_ALL:3,
	SELECT_ACTION_CLICK_ON_DATE:4,
    
	SELECT_IMAGE_CLASS:"photo_thumbnail_image_selected",
	select_actions:[],
	select_actions_shift_on: false, // これにfalase以外の場合は、shift key 選択中である
	key_select_actions_shift_on: false, // キーバインドで範囲選択を行う時の最初の写真

	// 写真種別
	PHOTO_TYPE_PHOTO: 1,
	PHOTO_TYPE_VIDEO: 2,

	//タグs
	user_tags:null,

	//日付選択系
	current_date_labels: {},

	permalink_manager: null,
	menuicon_manager: null,
	print_manager: null,

	get_album_list_object: function(){
		if (this.gallery) return this.gallery;
		return this.album_list;
	},

	// AlibumList.last_open_args.sorttype の エイリアス
	current_sort: function(){
		if (this.gallery) return this.gallery.last_open_args.sorttype;
		return AlbumList.DEFAULT_ALBUM_SORT;
	},

	create_photo_url: function(size, photo){
		var photo_id;
		if (photo.edit_count) {
			photo_id = photo.photo_id + '.' + photo.edit_count;
		} else {
			photo_id = photo.photo_id;
		}
		var url;
		if (this.gallery && this.gallery.show_member_url) {
			url = this.img_base_url.replace(/^http:\/\/.+\.pst\./, 'http://' + this.gallery.show_member_url + '.pst.') + size + '/' + photo_id + '.jpg';
		} else {
			url = this.img_base_url + size + '/' + photo_id + '.jpg';
		}
		if (photo.type == this.PHOTO_TYPE_VIDEO) {
			url = url.replace(/^http:\/\/(.+)\.pst\./, "http://$1.vst.");
			if (size == 'o' || size == 'f') {
				url = url.replace(/\.jpg$/, ".flv");
			}
		}
		return url;
	},

	//slide -----------------------------------------
	add_photo2slide: function(id, parent, allw, isPrepend){
		var photo = this.photo_list[id];
		if (!photo) return null;
		var img = $(document.createElement('img'));
		img.css({'margin-right':this.slidebar_thumnail_margin+'px'});
		img.addClass("slideshow_thumbnail");
		img.attr("id", "slidebar-photo-" + id);
		var src = this.create_photo_url('s', photo);
		if (isPrepend) {
			parent.prepend(img);
		} else {
			parent.append(img);
		}
		img.attr("width", this.slidebar_thumnail_width);
		loadImage(img, src, this.slidebar_thumnail_width, null, null, this.static_base_uri + 'common/images/thumbnail_default.jpg');
		var self = this;
		img.click(function (e) {
			self.show_photo(id);

			var dif = id - self.slidebar_center_id;
			var current_id = id;
			var last_id = self.slidebar_last_id+dif;
			var first_id = self.slidebar_first_id+dif;

			var index;
			if (dif > 0) {
				//足りない分の読み込みと余分なところの削除
				for (index = self.slidebar_last_id+1;index <= last_id && index < self.total;index++) {
					self.add_photo2slide(index, parent, allw);
				}
				for (index = self.slidebar_first_id;index < first_id && index < self.total;index++) {
					if (0 > index) {
						continue;
					}
					var uiid = "slidebar-photo-" + index;
					$("#"+uiid).remove();
				}
				if (self.is_paging) {
					// ページング方式の場合は、次のページのデータが取れてなければ取得しておく
					if (self.gallery) {
						self.gallery.load_next_page(current_id);
					} else {
						self.album_list.load_next_page(current_id);
					}
				}
			} else {
				for (index = self.slidebar_first_id-1;index >= first_id && index >= 0;index--) {
					self.add_photo2slide(index, parent, allw, true);
				}
				for (index = self.slidebar_last_id;index > last_id && index >= 0;index--) {
					if (self.total <= index) {
						continue;
					}
					$("#slidebar-photo-" + index).remove();
				}
			}
			self.centering_slidebar(parent, first_id);

			self.slidebar_center_id = current_id;
			self.slidebar_first_id = first_id;
			self.slidebar_last_id = last_id;
		});
		return img;
	},

	// 横一列に並んでる画像の数を取得する
	line_of_items: function(){
		var first_id = this.current_first_id;
		if (first_id < 0) return Math.floor(( $("#photolist_viewer").width() / (this.thumnail_width)));

		var id;
		var last_id = this.current_last_id;
		var last_cols = cols = 0;
		var last_top = $("#photo-" + first_id).position().top;
		for (id = first_id; id <= last_id; id++) {
			var top = $("#photo-" + id).position().top;
			if (top != last_top) {
				if (last_cols) break;
				last_cols = cols;
				cols = 0;
			}
			cols++;
			last_top = top;
		}
		return cols;
	},

	resize: function(){
		if (this.total === undefined) return;
		$("#photolist_viewer").height(10);

		var total            = this.total;
		var cols             = this.line_of_items();
		this.thumnail_cols   = cols;
		this.thumnail_rows   = Math.ceil( total / cols );
		var thumnail_height  = ( this.thumnailsize + this.thumnail_margin_bottom + this.thumnail_datediv_height + this.thumnail_datediv_height_padding );
		this.thumnail_height = thumnail_height;

		var viewer_height = $("#photolist_viewer_area").height();
		this.thumnail_items = Math.ceil( viewer_height / thumnail_height ) * cols;

		this.photolist_bottom_space = this.thumnail_rows * thumnail_height;
		this.resize_photolist_space();

		$("#photolist_viewer").height( this.thumnail_rows * this.thumnail_height  );
	},
	resize_photolist_space: function(){
		if (this.is_paging) {
			$("#photolist_top_space").height( this.photolist_top_space );
			$("#photolist_bottom_space").height( this.photolist_bottom_space );
			$("#photo-list").height( this.photolist_height );
		} else {
			$("#photolist_top_space").height( 0 );
			$("#photolist_bottom_space").height( 0 );
		}
	},

	// 指定されたphoto indexが中央に来るようにスクロールする
	centering: function(index) {
	//    this.resize();

		var current_line = Math.floor( index / this.thumnail_cols );
		var first_last = this.get_current_first_and_last_id();
		var rows       = Math.floor( (first_last[1] - first_last[0] + 1) / this.thumnail_cols );
		//if (current_line > this.thumnail_rows - rows) current_line -= (rows / 2.5);
		var scrollTop = Math.floor(this.thumnail_height * current_line);
		if (scrollTop < 0) scrollTop = 0;

		var area = $("#photolist_viewer_area");
		area.scrollTop(scrollTop);
	},

	start_photoviewer: function(){
		this.is_photoviewer = true;
		var area = $("#photolist_viewer_area");
		this.photo_list_scrollTop = area.scrollTop();

		$("#photolist_contents").hide();
		$("#photodetail_contents").show();
		if (this.is_print) {
			$("#photo_preview_menu").hide();
		} else {
			$("#photo_preview_menu").show();
		}
	},

	show_photo_is_permalink: false,
	end_photoviewer: function(from_album_open){
		this.is_photoviewer = false;
		$('#photo-caption-content').hide();
		if (this.show_photo_is_permalink && !from_album_open) {
			// permalink mode は reopen のみ
			if (this.gallery) {
				this.gallery.reopen();
			} else if (this.album_list) {
				this.album_list.reopen();
			}
			return;
		}
		if (!from_album_open) {
			if (this.gallery) {
				this.gallery.set_permalink_current_album({ current_center_id: this.current_center_id });
			} else if (this.album_list) {
				this.album_list.set_permalink_current_album({ current_center_id: this.current_center_id });
			}
		}

		$("#photolist_contents").show();
		$("#photodetail_contents").hide();

		this.select_actions = [];
		this.select_actions_shift_on = false;

		if (this.slide_photo_selected_index < 0) {
			this.resize();
			return;
		}

		this.addSelectAction({id:this.slide_photo_selected_index,type:this.SELECT_ACTION_CLICK});
		this.mark_showing_photos_if_selected();

		var photo = this.photo_list[this.slide_photo_selected_index];
		if (this.current_first_id <= this.slide_photo_selected_index && this.slide_photo_selected_index <= this.current_last_id && photo && photo.img) {
			//この写真が表示エリアに入っていればそのまま。
			var sOfPhoto = photo.img.offset().top;
			var hOfPhoto = photo.img.height();
			var eOfPhoto = sOfPhoto+hOfPhoto;
			var pane = $("#photolist_viewer_area");
			var sOfPane = pane.offset().top+hOfPhoto;
			var eOfPane = sOfPane+pane.height()-hOfPhoto;

			// safari と mozilla で取れる値が違うのね。。
			if (jQuery.browser.safari === true) {
				sOfPhoto -= this.photo_list_scrollTop;
				eOfPhoto -= this.photo_list_scrollTop;
				if ((sOfPane <= sOfPhoto && sOfPhoto <= eOfPane) ||
					(sOfPane <= eOfPhoto && eOfPhoto <= eOfPane)) {
					//入ってた。
					var area = $("#photolist_viewer_area");
					area.scrollTop(this.photo_list_scrollTop);
				} else {
					//現在表示されている写真のサムネイルの高さまでスクロールする
					this.centering(this.slide_photo_selected_index);
					this.resize();
				}
			} else {
				if (!((sOfPane <= sOfPhoto && sOfPhoto <= eOfPane) ||
					(sOfPane <= eOfPhoto && eOfPhoto <= eOfPane))) {
					this.centering(this.slide_photo_selected_index);
					this.resize();
				}
			}
		} else {
			//現在表示されている写真のサムネイルの高さまでスクロールする
			this.centering(this.slide_photo_selected_index);
			this.resize();
		}
		this.current_focus_id = this.slide_photo_selected_index;
	},

	centering_slidebar:function(bar, first_id) {
		var slidebar_thumnail_width = this.slidebar_thumnail_width;
		var slidebar_thumnail_margin = this.slidebar_thumnail_margin;
		var all_thumbnail_width = slidebar_thumnail_width + slidebar_thumnail_margin + 2;
		var slidebar_width          = $("#slideshow_viewer").width();
		var slidebar_cols           = Math.floor(slidebar_width / (all_thumbnail_width));
		var half_cols               = Math.floor(slidebar_cols / 2);
		//センタリング
		var zure = first_id < 0 ? half_cols+first_id+0.5 : half_cols+0.5;
		var left = (slidebar_width/2 - zure*all_thumbnail_width);
		bar.css({ "left": left + 'px'});
	},
	
	show_slidebar: function(lr){
		var slidebar_thumnail_width = this.slidebar_thumnail_width;
		var slidebar_thumnail_margin = this.slidebar_thumnail_margin;
		//2 is border
		var all_thumbnail_width = slidebar_thumnail_width + slidebar_thumnail_margin + 2;
		var slidebar_width          = $("#slideshow_viewer").width();
		var slidebar_cols           = Math.floor(slidebar_width / (all_thumbnail_width));
		var half_cols               = Math.floor(slidebar_cols / 2);
		var total                   = this.total;
		var center_id               = this.slidebar_center_id;
		var index_id                = this.slide_photo_selected_index;
		
		if (lr < 0) {
			center_id += Math.floor(slidebar_cols / 2);
			if (center_id < 0) center_id = 0;
		} else if (lr > 0) {
			center_id -= Math.floor(slidebar_cols / 2);
			if (center_id >= total) center_id = total - 1;
		} else {
			center_id  = index_id;
		}
		this.slidebar_center_id = center_id;

		var first_id = center_id - half_cols;
		var last_id  = center_id + half_cols;
		this.slidebar_first_id = first_id;
		this.slidebar_last_id = last_id;

		var target   = $("#slideshow_photo_list");
		target.empty();

		var self = this;
		for (var id = first_id;id <= last_id && id < total;id++) {
			if (id < 0) continue;
			var img = this.add_photo2slide(id, target, all_thumbnail_width);
			if (img === null) continue;
			if (index_id == id) {
				img.addClass('slideshow_thumbnail_selected');
				continue;
			}
		}
		//センタリング
		this.centering_slidebar(target, first_id);

		if (this.is_paging) {
			// ページング方式の場合は、次のページのデータが取れてなければ取得しておく
			if (this.gallery) {
				this.gallery.load_next_page(center_id);
			} else {
				this.album_list.load_next_page(center_id);
			}
		}
	},

	show_nextphoto: function(){
		// if (this.is_photo_loading) return; // 写真のload待ちすると不安定なのでload待ちしないようにしてみる

		if (this.is_paging) {
			// ページング方式の場合は、次のページのデータが取れてなければ取得しておく
			if (this.gallery) {
				this.gallery.load_next_page(this.slide_photo_selected_index);
			} else {
				this.album_list.load_next_page(this.slide_photo_selected_index);
			}
		}
		if (this.slide_photo_selected_index == this.total - 1) {
			return;
		}
		this.show_photo(this.slide_photo_selected_index + 1);
	},

	show_backphoto: function(){
		// if (this.is_photo_loading) return; // 写真のload待ちすると不安定なのでload待ちしないようにしてみる

		if (this.is_paging) {
			// ページング方式の場合は、次のページのデータが取れてなければ取得しておく
			if (this.gallery) {
				this.gallery.load_next_page(this.slide_photo_selected_index);
			} else {
				this.album_list.load_next_page(this.slide_photo_selected_index);
			}
		}
		if (this.slide_photo_selected_index === 0) {
			return;
		}
		this.show_photo(this.slide_photo_selected_index - 1);
	},

	caption_last_opne_time: 0,
	show_caption: function(caption){
		var self = this;
		var first_line = caption.split("\n").shift();
		if (!first_line) return;
		var text_container = $('#photo-caption');
		text_container.text(first_line);

		var container = $('#photo-caption-content');
		var state = 2; // 0 = close, 1 = open, 2 = running
		container.fadeTo(10, 1, function(){ state = 1 });
		container.show();
		container.unbind('mouseover').unbind('mouseout');
		text_container.unbind('mouseover').unbind('mouseout');

		self.caption_last_opne_time = (new Date).getTime() + 1600;
		setTimeout(function(){
			if ((new Date).getTime() < self.caption_last_opne_time) return;
			container.fadeTo(200, 0, function(){ state = 0 });

			// mouse over で caption だすのは、自動的に一度閉じてから
			var is_child_open = true;
			var open = function(){
				is_child_open = false;
				if (state != 0) return;
				state = 2;
				container.fadeTo(10, 1, function(){ state = 1 });
			};
			var close = function(){
				// 子 DOM の上に乗ってるかもしれなくて is_child_open = true になるかもしれないので 100msec 待ってみる
				setTimeout(function(){
					if (state != 1) return;
					if (is_child_open) return;
					state = 2;
					container.fadeTo(200, 0, function(){ setTimeout(function(){ state = 0 }, 100) });
				}, 100);
			};
			container.mouseover(open).mouseout(close);
			text_container.mouseover(function(e){ is_child_open = true; e.stopPropagation(); }).mouseout(function(e){e.stopPropagation()});
		}, 1800);
	},
	fit_stuff: function (target, wOfTarget, hOfTarget) { // 動画/写真がぴったりくるように element をリサイズする
		// set style
		if (is_full_display) {
			$('#photo_image_container').css({'position':'fixed', 'width':'100%', 'height':'100%', 'background-color':'#000' });
			target.css({ 'position':'fixed', 'top':'20px', 'left':'30px' });
		} else {
			$('#photo_image_container').css({'position':'absolute', 'width':'', 'height':'', 'background-color':'' });
			target.css({ 'position':'', 'top':'0px', 'left':'0px' });
		}

		var container = $("#photodetail_contents");
		var wOfContainer = container.width();
		var hOfContainer = container.height();
		if (is_full_display) {
			wOfContainer = $('body').width()  + 150;
			hOfContainer = $('body').height() + 150;
		}	
		var hmax = hOfContainer-100;
		var wrate = wOfTarget / wOfContainer;
		var hrate = hOfTarget / hmax;
		if (wOfTarget > wOfContainer || hOfTarget > hmax) {
			if (wrate > hrate) {
				if (wOfTarget > wOfContainer) {
					hOfTarget = wOfContainer / wOfTarget * hOfTarget;
					wOfTarget = wOfContainer;
				}
			} else {
				if (hOfTarget > hmax) {
					wOfTarget = hmax / hOfTarget * wOfTarget;
					hOfTarget = hmax;
				}
			}
		}
		var xOfTarget = (wOfContainer - wOfTarget) / 2;
		var yOfTarget = (hOfContainer - hOfTarget) / 2;
		target.width(wOfTarget-1);
		target.height(hOfTarget-1);
		//dump("fitPhotoImage:"+wOfTarget+"  "+hOfTarget+"  "+wOfContainer+" "+hOfContainer+"\n");
		if (is_full_display) {
			$("#photo_image_container").css({'top':'0px','left':'0px'});
			yOfTarget -= 50;
			xOfTarget -= 75;
			target.css({'top':yOfTarget+'px','left':xOfTarget+'px'});
		} else {
			$("#photo_image_container").css({'top':yOfTarget+'px','left':xOfTarget+'px'});
		}
		
		// for wait image
		var photodetail_contents = $("#photodetail_contents");
		xOfTarget = (photodetail_contents.width()  / 2) - 32;
		yOfTarget = (photodetail_contents.height() / 2) - 32;
		$("#photo_image_loading_wait").css({'top':yOfTarget+'px','left':xOfTarget+'px'});
	},
	fit_video: function () { // 動画ウィンドウをリサイズする
		var target = $("#video_container");
        var w = target.data('width');
        var h = target.data('height');
        var VIDEO_PLAYER_WIDTH = 295;
        if (w < VIDEO_PLAYER_WIDTH) {
            h = h * (VIDEO_PLAYER_WIDTH / w);
            w = VIDEO_PLAYER_WIDTH;
        }
		this.fit_stuff(target, w, h);
	},
	show_photo: function(id, args){
		$('#photo-caption-content').hide();
		var self = this;
		if (!args) args = {};

		var photo;
		if (args.is_permalink) {
			// permalink mode では前後のつながりが無いので スライドショーと左右矢印を消す
			photo = id;
			id = -1;
			self.photo_list[id] = photo;
			self.photo_list[id].attribute = photo;
			self.show_photo_is_permalink = true;
			$('#slide_display').hide();
			$('#btn_back').hide();
			$('#btn_next').hide();
		} else {
			photo = self.photo_list[id];
			self.show_photo_is_permalink = false;
			//$('#slide_display').show();
			$('#btn_back').show();
			$('#btn_next').show();
		}
		self.select_actions = [];
		self.select_actions_shift_on = false;
		self.addSelectAction({id:id,type:self.SELECT_ACTION_CLICK});
		if (!photo) return;
		this.current_photo = photo;

		var change_permalink = function(){};
		if (self.permalink_manager) {
			change_permalink = function(){
				if (self.album) {
					self.permalink_manager.changeMode('album-photo', { album_id: self.album.album_id, photo_id: photo.photo_id });
				} else {
					self.permalink_manager.changeMode('photo', { photo_id: photo.photo_id });
				}
			};
		}
		change_permalink();


		self.is_photo_loading = true;
		self.slide_photo_selected_index = id;
		var src = self.create_photo_url('m', photo);

		if (photo.type == self.PHOTO_TYPE_VIDEO) {
			$("#photo_image_loading_wait").show();
			$("#video_container").hide();
			$('#photo_image').hide();
			$('#photo_image_loader')
				.unbind('error')
				.unbind('load'); // dummy data

			var create_video_swf = function (img) {
				swfobject.createSWF(
					{
						data:"/common/swf/FLVScrubber.swf?" + (new Date).getTime(),
						width:"",
						height:""
					},{
						"movie":"/common/swf/FLVScrubber.swf",
						"allowFullScreen":"true",
						"wmode":"transparent",
						"FlashVars": "file="+self.create_photo_url('f', photo) + "&previewImage="+src
					},"video_container");
				$('#video_container').
					data('width', img.width()).
					data('height', img.height()).
					show();
				self.fit_video();
				$("#photo_image_loading_wait").hide();
			};
			var img = $('#video_image_loader');
			img.hide()
				.unbind('load')
				.unbind('error')
				.css({'width':'', 'height':''})
				.error(function () {
					$("#video_container").hide();
					$("#photo_image_loading_wait").hide();

					$('#photo_image').
						css({'width':'', 'height':''}).
						attr("src", self.static_base_uri + 'common/images/movie_default.jpg').
						show();
				})
				.attr("src", src);
			if (img.width()) {
				create_video_swf(img);
			} else {
				img.load(function () { create_video_swf($(this)) });
			}
			self.previous_is_video = true;
		} else {
			$("#video_container").hide();
			var loader = $("#photo_image_loader");
			if (loader.attr("src") != src || self.previous_is_video) {
				$("#photo_image_loading_wait").show();
				$("#photo_image").hide();
				
				loader.unbind('load')
					.load(function(){
						$("#photo_image_loading_wait").hide();
						$("#photo_image")
							.hide()
							.css({'width':'', 'height':''})
							.attr("src", src);
					})
					.error(function(){
						$("#photo_image_loading_wait").hide();
						$("#photo_image")
							.hide()
							.css({'width':'', 'height':''})
							.attr("src", self.static_base_uri + 'common/images/photo_default.jpg');
					})
					.attr("src", src);

				if (self.previous_is_video) {
					$('#photo_image').load();
					self.previous_is_video = false;
				}
			}
		}

		// attribute load & show caption
		if (photo.attribute) {
			if (photo.attribute.caption) self.show_caption(photo.attribute.caption);
		}  else {
			var url = '/photo/' + self.user_id + '/' + photo.photo_id + '/attribute';
			if (self.base_path) url = self.base_path + url;
			$.ajax({
				url : url,
				type : "get",
				dataType: "json",
				cache: false,
				success : function(data){
					photo.attribute = data;
					if (data.caption) {
						self.show_caption(data.caption);
						change_permalink();
					}
				}
			});
		}

		if (!args.is_permalink) {
			// 次の画像を先読み
			$("#photo_image_next_loader").attr("src", "/common/nowloading.png");
			if (id + 1 < self.total - 1) {
				$("#photo_image_next_loader").attr("src", self.create_photo_url('m', self.photo_list[id + 1]));
			}

			// 前の画像を先読み
			$("#photo_image_back_loader").attr("src", "/common/nowloading.png");
			if (id > 0) {
				$("#photo_image_back_loader").attr("src", self.create_photo_url('m', self.photo_list[id - 1]));
			}
		}

		//グッド数およびコメント数の表示
		if (photo.photo_good_count === 0) {
			$("#good-onephoto-count").text("");
		} else {
			$("#good-onephoto-count").text(photo.photo_good_count);
		}
		if (photo.photo_comment_count === 0) {
			$("#comment-onephoto-count").text("");
		} else {
			$("#comment-onephoto-count").text(photo.photo_comment_count);
		}

		if (this.album == null) {
			// ギャラリーへ戻るを出す
			$('#back-album').addClass('enablegallery');
		} else {
			$('#back-album').removeClass('enablegallery');
		}

		// ダウンロードリンク変更
		var menuicon = self.menuicon_manager;
        if (
			(self.gallery && ((self.gallery.show_user_id == self.user_id) || (self.gallery.attribute && self.gallery.attribute.download))) ||
			(self.album_list && self.album_list.attribute && self.album_list.attribute.download)
		) {
			menuicon.show_with(menuicon.TYPE_PHOTO_PREVIEW_MENU, ["download"]);
			var url = src.replace('/m/', '/download/o/').replace(/\.\d+\.jpg/, '.jpg');
					if (photo.type == this.PHOTO_TYPE_VIDEO) {
						url = url.replace(/\.jpg$/, '.flv');
					}
			$('#photo-download').attr('href', url);
		} else {
			menuicon.hide_with(menuicon.TYPE_PHOTO_PREVIEW_MENU, ["download"]);
		}

		// ゴミ箱 と 情報管理ボタンは、共有アルバムを見ている時は消す
		if (self.gallery) {
			if (self.gallery.show_user_id == self.user_id) {
				menuicon.show_with(menuicon.TYPE_PHOTO_PREVIEW_MENU, ["hide_sharealbum"]);
			} else {
				menuicon.hide_with(menuicon.TYPE_PHOTO_PREVIEW_MENU, ["hide_sharealbum"]);
			}
		}

		if (!args.is_permalink) {
			// スライドショーのフォーカス変える
			$(".slideshow_thumbnail_selected").removeClass("slideshow_thumbnail_selected");
			$("#slidebar-photo-" + id).addClass("slideshow_thumbnail_selected");
		}
	},

	//slide -----------------------------------------

	// 現在表示されるべきpage番号を作る
	get_current_page: function(){
		var photolist_viewer = $("#photolist_viewer_area");
		var scrolltop        = photolist_viewer.scrollTop();
		var rows             = Math.floor( scrolltop / this.thumnail_height );
		var items            = rows * this.thumnail_cols;
		return Math.floor( items / this.page_items );
	},

	// 表示領域の一番上の行数を計算する
	get_toprow: function(){
		var top = Math.floor( $("#photolist_viewer_area").scrollTop() / this.thumnail_height ) - 1;
		if (top < 0) top = 0;
		return top;
	},

	// 現在の真ん中に表示されている画像IDを求める
	get_current_center_id: function(){
		return ((this.get_toprow()) * this.thumnail_cols) + Math.floor(this.thumnail_items / 2);
	},

	// 現在の画面位置に対応した最初と最後の写真IDを返す
	get_current_first_and_last_id: function(){
		// 非表示領域の空DIVの高さを調整
		var thumnail_height  = this.thumnail_height;
		var thumnail_rows    = this.thumnail_rows;
		var thumnail_cols  = this.thumnail_cols;
		var top_row          = this.get_toprow();

		// 表示するダミー画像のIDリストを求める
		var thumnail_items = this.thumnail_items;
		var total          = this.total;
		var margin_views   = this.margin_views;

		var base_id  = (top_row * thumnail_cols);
		var first_id = base_id - Math.ceil(thumnail_items * margin_views);
		first_id     = Math.floor(first_id / thumnail_cols) * thumnail_cols;
		if (first_id < 0) first_id = 0;

		var last_id  = base_id + Math.ceil(thumnail_items * (margin_views + 1)) + thumnail_cols;
		last_id      = (Math.ceil(last_id / thumnail_cols) * thumnail_cols) - 1;
		if (last_id >= total) last_id = total - 1;

		// #photo-list の高さを求める
		this.photolist_height = Math.ceil((last_id - first_id) / thumnail_cols) * thumnail_height;
		if (this.photolist_height < 0) this.photolist_height = 0;

		// 高さ変更
		this.photolist_top_space = Math.floor(first_id / thumnail_cols) * thumnail_height;
		this.photolist_bottom_space = ((thumnail_rows - top_row) * thumnail_height) - this.photolist_height;

		if (this.photolist_bottom_space < 0) this.photolist_bottom_space = 0;

		this.resize_photolist_space();

		return [first_id, last_id];
	},

	// permalink に index を追加
	set_center_index_permalink: function(){
		if (this.gallery) {
			this.gallery.set_permalink_current_album({ current_center_id: this.current_center_id })
		} else if (this.album_list) {
			this.album_list.set_permalink_current_album({ current_center_id: this.current_center_id } )
		}
	},

	// スクロールに合わせてpreloadする画像を変更する
	is_dummy_image_loading_on_scroll_running: false,
	dummy_image_loading_on_scroll: function(){
		if (this.is_dummy_image_loading_on_scroll_running) return;
		this.is_dummy_image_loading_on_scroll_running = true;

		//真ん中のidが変化あるまで何もしない
		var current_center_id = this.current_center_id;
		if (current_center_id < 0) {
			this.is_dummy_image_loading_on_scroll_running = false;
			return;
		}
		var center_id      = this.get_current_center_id();
		if (center_id == current_center_id) {
			this.is_dummy_image_loading_on_scroll_running = false;
			return;
		}
		var ret      = this.get_current_first_and_last_id();
		var first_id = ret[0];
		var last_id  = ret[1];

		var current_first_id = this.current_first_id;
		var current_last_id  = this.current_last_id;

		if (last_id < current_first_id || first_id > current_last_id) {
			// 現在の表示領域より大きく動いたら全部描画しなおし
			this.dummy_image_loading_to_current();
			this.is_dummy_image_loading_on_scroll_running = false;
			return;
		}


		// 高さがずれたので不要な行を削除して、ダミー画像を追加する
		var list = $("#photo-list");
		var add_list = [];
		var id;
		var photo;
		var div;
		if (center_id < current_center_id) {// 上に移動
			// 下を削除
			for (id = last_id + 1;id <= current_last_id;id++) {
				$("#photo-" + id).remove();
				photo = this.photo_list[id];
				if (!photo) continue;
				photo.is_loaded = false;
				if (photo.is_loading) {
					photo.is_loading = false;
					this.current_add_photo_proc--;
				}
			}

			// 上を追加
			for (id = current_first_id - 1;id >= first_id;id--) {
				div = this.create_photo_container(id);
				if (div === null) continue;

				// データ取得済みなら画像を差し替え
				photo = this.photo_list[id];
				if (photo) {
					photo.is_loaded   = false;
					photo.is_queueing = false;
					add_list.push({ id: id, photo: photo });
				}
				list.prepend(div);
			}

		} else { // 下に移動
			// 上を削除
			for (id = current_first_id;id < first_id;id++) {
				$("#photo-" + id).remove();
				photo = this.photo_list[id];
				if (!photo) continue;
				photo.is_loaded = false;
				if (photo.is_loading) {
					photo.is_loading = false;
					this.current_add_photo_proc--;
				}
			}

			// 下を追加
			for (id = current_last_id + 1;id <= last_id;id++) {
				div = this.create_photo_container(id);
				if (div === null) continue;

				// データ取得済みなら画像を差し替え
				photo = this.photo_list[id];
				if (photo) {
					photo.is_loaded   = false;
					photo.is_queueing = false;
					add_list.push({ id: id, photo: photo });
				}
				list.append(div);
			}
		}


		this.current_first_id  = first_id;
		this.current_last_id   = last_id;
		this.current_center_id = center_id;

		this.is_dummy_image_loading_on_scroll_running = false;

		if (!add_list.length) return;

		// 表示領域の真ん中からレンダリングされるように並び替える
		add_list = add_list.sort(function(a, b){
			var a2 = Math.abs(a.id - center_id);
			var b2 = Math.abs(b.id - center_id);
			if (a2 == b2) return 0;
			return (a2 < b2) ? -1 : 1;
		});

		this.add_paging_photo_manager(add_list);

		this.set_center_index_permalink();
		return;
	},

	// スクロールされた位置にあるべきdummy要素を作成
	dummy_image_loading_to_current: function(){

		var list = $("#photo-list");
		list.empty();

		var ret       = this.get_current_first_and_last_id();
		var first_id  = ret[0];
		var last_id   = ret[1];
		var center_id = this.get_current_center_id();

		this.current_center_id = center_id;
		this.current_first_id  = first_id;
		this.current_last_id   = last_id;

		// ダミー画像の表示
		var photo_list = this.photo_list;
		var add_list = [];
		for (var id = first_id;id <= last_id;id++) {
			var div = this.create_photo_container(id);
			if (div === null) continue;

			// データ取得済みなら画像を差し替え
			var photo = photo_list[id];
			if (photo) {
				photo.is_loaded   = false;
				photo.is_queueing = false;
				add_list.push({ id: id, photo: photo });
			}
			list.append(div);
		}

		this.current_add_photo_proc = 0;
		if (!add_list.length) return;

		// 表示領域の真ん中からレンダリングされるように並び替える
		add_list = add_list.sort(function(a, b){
			var a2 = Math.abs(a.id - center_id);
			var b2 = Math.abs(b.id - center_id);
			if (a2 == b2) return 0;
			return (a2 < b2) ? -1 : 1;
		});

		this.add_paging_photo_manager(add_list);

		this.set_center_index_permalink();
	},

	// 画面中に表示されるべき画像のpage番号のリストを返す
	get_current_page_list: function(){
		var self = this;
		var list = [];

		var thumnail_cols  = this.thumnail_cols;
		var thumnail_items = this.thumnail_items;
		var page_items     = self.page_items;
		var margin_views   = this.margin_views;
		var margin_items   = Math.ceil(margin_views * thumnail_items);
		var margin_pages   = Math.ceil(margin_items / page_items);

		var center_page = self.get_current_page();
		var page        = center_page - margin_pages;
		var view_pages = Math.ceil( thumnail_items / page_items ) + margin_pages;
		if (page < 0) {
			page = 0;
			--view_pages;
		}
		//alert([thumnail_cols,thumnail_items,page_items,margin_views,margin_items,margin_pages,center_page,page,view_pages].join("\n"));

		var total = self.total;
		for (var count = 0;count <= view_pages;count++) {
			var p = page + count;
			if (p * page_items > total) break;
			list.push(p);
		}


		list = list.sort(function(a, b){
			var a2 = Math.abs(a - center_page);
			var b2 = Math.abs(b - center_page);
			if (a2 == b2) return 0;
			return (a2 < b2) ? -1 : 1;
		});

		return list;
	},

	// 指定された画像IDはレンダリング対象かどうかを調べる
	is_display: function(id){
		var photolist_viewer = $("#photolist_viewer_area");
		var scrolltop        = photolist_viewer.scrollTop();
		var top_rows         = Math.floor( scrolltop / this.thumnail_height );

		var first_id = top_rows * this.thumnail_cols;
		var last_id  = first_id + this.thumnail_items + this.thumnail_items - 1;

		return (first_id <= id && id <= last_id) ? true : false;
	},

	_nowloading_image_cache: null,
	_nowloading_image: function(){
		if (this._nowloading_image_cache === null) {
			this._nowloading_image_cache = $("<IMG/>").
				addClass("photo_nowloading_image").
				attr("src", "/common/images/loading_default.gif");
		}
		return this._nowloading_image_cache;
	},

	create_photo_container: function(id){
		// すでにDOMがある場合は追加しない
		if (!$("#photo-" + id).get()) return null;

		var hOfDiv = this.thumnailsize + this.thumnail_datediv_height + this.thumnail_datediv_height_padding;
		return $("<DIV/>").
			addClass("photo_thumbnail").
			css({
				width          : this.thumnailsize + 'px',
				height         : hOfDiv + 'px',
				'margin-right' : this.thumnail_margin_right + 'px',
				'margin-bottom': this.thumnail_margin_bottom + 'px'
			}).
			attr("id", "photo-" + id).
			append(this._nowloading_image().clone());
	},

	// 現在のページで表示するのに必要なphotoデータをload
	load_current_page: function(open_count){
		var page_list = this.get_current_page_list();
		if (this.gallery) {
			this.gallery.load_page(page_list, false, open_count);
		} else {
			this.album_list.load_page(page_list, false, open_count);
		}
	},

	// ajaxで取ってきたphoto_listをqueueしながら画像表示
	add_photo_queue: [],
	add_photo_queue_running: false,
	reset_photo_queue: function(){
		this.add_photo_queue         = [];
		this.add_photo_queue_running = false;
	},
	// ギャラリー用のmanager
	add_gallery_photo_manager: function(photo_list, page, is_not_show){
		var self = this;
		var page_items = self.page_items;

		var first_id = this.current_first_id;
		var last_id  = this.current_last_id;

		if (photo_list) {
			// 新規に取ってきたpage
			if (is_not_show) {
				$.each(photo_list, function(i){
					var photo           = photo_list[i];
					photo.is_loaded     = false;
					var id              = (page * page_items) + i;
					photo.id            = id;
					self.photo_list[id] = photo;
				});
				return;
			} else {
				$.each(photo_list, function(i){
					var photo         = photo_list[i];
					photo.is_loaded   = false;
					photo.is_queueing = true;

					var id              = (page * page_items) + i;
					photo.id            = id;
					self.photo_list[id] = photo;
					if (first_id > id || last_id < id) return;
					self.add_photo_queue.push(id);
				});
			}
		} else if (!is_not_show) {
			// 取得済みのpageなので表示してない画像がなければ何もしない
			var last = (page + 1 ) * page_items;
			if (last > self.total) last = this.total;
			for (var count = page * page_items;count < last;count++) {
				if (first_id > count || last_id < count) continue;
				var photo = self.photo_list[count];
				if (photo) {
					if (!photo.is_loaded) {
						photo.is_queueing = true;
						self.add_photo_queue.push(count);
					}
				}
			}
		}

		self.add_photo_next();
	},

	// 全選択モードかどうか
	is_select_action_all: function(){
		return this.select_actions.length > 0 && this.select_actions[0].type == this.SELECT_ACTION_ALL;
	},

	//現在選択されている全てのIDを返す
	get_selected_photos: function(){
		var self = this;
		var photo_id_list = {};
		var selectedphotos = this.get_marked_photos_exceptall();
		var id;
		if (this.is_select_action_all()) {
			var checked_photo_id_list = {};
			for (v in selectedphotos) {
				if (!self.photo_list[selectedphotos[v]]) continue;
				id = self.photo_list[selectedphotos[v]].photo_id;
				checked_photo_id_list[id] = id;
			}
			$.each(this.photo_list, function(i){
				if (!self.photo_list[i]) return;
				id = self.photo_list[i].photo_id;
				if (checked_photo_id_list[id]) return;
				photo_id_list[id] = id;
			});
		} else {
			for (v in selectedphotos) {
				if (!self.photo_list[selectedphotos[v]]) continue;
				id = self.photo_list[selectedphotos[v]].photo_id;
				photo_id_list[id] = id;
			}
		}
		return photo_id_list;
	},

	// photo_selectクエリを作成する
	generate_photo_select_query: function(){
		var self = this;
		var is_select_action_all = self.is_select_action_all();

		// targetを作る
		var target;
		var target_args = '';
		if (self.album === null) {
			target      = self.current_target;
			target_args = self.current_target_args;
		} else {
			target      = 'album';
			target_args = self.album.album_id;
		}

		// photo_pairを作る
		var photo_pair_list = [];
		if (self.select_actions.length && self.select_actions[0].type === self.SELECT_ACTION_CLICK_ON_DATE) {
			// 日付選択
			var action = self.select_actions[0];
			photo_pair_list.push(action.first_photo_id + "=" + action.last_photo_id);
		} else {
			var selectedphotos = self.get_marked_photos_exceptall();
			if (selectedphotos.length == 1 && !is_select_action_all) {
				// single
				return {
					target: target,
					target_args: target_args,
					range: 'single',
					photo: self.photo_list[selectedphotos[0]].photo_id
				};
			}

			var last_idx  = null;
			var first_idx = null;

			// photo_pair のリストを作る
			var photo_pair_finalizer = function(){
				if (first_idx === null) {
					// single
					photo_pair_list.push(self.photo_list[last_idx].photo_id);
				} else {
					// pair
					photo_pair_list.push(self.photo_list[first_idx].photo_id + '=' + self.photo_list[last_idx].photo_id);
				}
				first_idx = null;
			};

			if (selectedphotos.length > 0) {
				for (v in selectedphotos) {
					var idx = Number(selectedphotos[v]);
					if (last_idx !== null) {
						if (last_idx + 1 == idx) {
							// 連番
							if (first_idx === null) first_idx = last_idx;
						} else {
							photo_pair_finalizer();
						}
					}
					last_idx = idx;
				}
				photo_pair_finalizer();
			}
		}
		var photo_pair = photo_pair_list.join(',');

		var order = self.current_sort() ? self.current_sort() : 'upload_desc';
		return {
			target: target,
			target_args: target_args,
			order: order,
			range: is_select_action_all ? 'all' : 'any',
			photo_pair: photo_pair
		};
	},

	// album tag search 用の manager 全てを出す
	add_photo_manager: function(photo_list){
		var self = this;
		var list = $("#photo-list");
		self.add_photo_queue = [];

		$.each(photo_list, function (i) {
			var div = self.create_photo_container(i);
			if (div === null) return;
			list.append(div);

			var photo = photo_list[i];
			photo.is_loaded   = false;
			photo.is_queueing = true;

			self.photo_list[i] = photo_list[i];
			self.add_photo_queue.push(i);
		});
		self.add_photo_next();
	},
	// ページングのダミー画像からの差し替え用
	add_paging_photo_manager: function(photo_list){
		var self = this;
		var list = $("#photo-list");
		self.add_photo_queue = [];

		$.each(photo_list, function (i) {
			var obj = photo_list[i];
			obj.photo.is_loaded   = false;
			obj.photo.is_queueing = true;
			self.add_photo_queue.push(obj.id);
		});
		self.add_photo_next();
	},


	// 画像メタデータを元に画像を表示する
	max_add_photo_proc: 6,
	current_add_photo_proc: 0,
	add_photo_next: function(){
		if (self.add_photo_queue_running) return;

		this.add_photo_queue_running = true;

		// 表示領域の真ん中からレンダリングされるように並び替える
		var center_id = this.get_current_center_id();
		this.add_photo_queue = this.add_photo_queue.sort(function(a, b){
			var a2 = Math.abs(a - center_id);
			var b2 = Math.abs(b - center_id);
			if (a2 == b2) return 0;
			return (a2 < b2) ? -1 : 1;
		});

		if (this.add_photo_queue.length) {
			var first_id = this.current_first_id;
			var last_id  = this.current_last_id;
			if (this.current_add_photo_proc < 0) this.current_add_photo_proc = 0;

			var max = this.max_add_photo_proc;
			while (this.current_add_photo_proc < max) {
				if (this.add_photo_queue.length < 1) {
					this.add_photo_queue_running = false;
					return;
				}

				var id = this.add_photo_queue.shift();
				if (this.is_paging && (first_id > id || last_id < id)) continue;

				this.current_add_photo_proc++;
				this.add_photo(id);
			}
			return;
		}

		this.add_photo_queue_running = false;
	},

	_add_photo_return: function(flag){
		this.current_add_photo_proc--;
		if (flag && this.current_add_photo_proc < this.max_add_photo_proc) this.add_photo_next();
		return false;
	},
	add_photo: function(id){
		if (id === null) {
			return this._add_photo_return();
		}
		var self = this;

		var photo         = self.photo_list[id];
		if (!photo) return self._add_photo_return();

		photo.is_queueing = false;
		if (photo.is_loaded) {
			return self._add_photo_return();
		}
		photo.is_loaded = false;

		var div_container = $("#photo-" + id);        
		if (div_container.html() === null) {
			return self._add_photo_return();
		}

		// マークを付ける
		photo.is_loaded = true;

		// 画像を正しい物に入れ替える
		var img = $(document.createElement('img')).
			addClass("photo_thumbnail_image");
		photo.is_loading = true;

		loadImage(img, self.create_photo_url('s', photo), self.thumnail_imagesize, photo, function(obj){
			photo.is_loading = false;
			self.add_photo_attach_objects(div_container, photo, id, img);
			self._add_photo_return(true);
		}, self.static_base_uri + 'common/images/thumbnail_default.jpg');
		$("#photo-" + id + " .photo_nowloading_image").remove();
		if (photo.type == self.PHOTO_TYPE_VIDEO) {
			img.addClass("video"); // base.css img.video
		}

		//日付選択系処理 ---------------
		if (this.is_print) {
			this.add_photo_attach_print(div_container, id);
		} else {
			if (this.album == null) {
				// gallery
				this.add_photo_attach_dategroup(div_container, id);
			} else {
				var sorttype = 0;
				if (this.gallery && this.gallery.widget) {
					sorttype = this.gallery.widget.get_attr(this.album.album_id).sort_type;
				}
				if (sorttype >= 1 && sorttype <= 4) {
					// date sorted album
					var album_list = self.get_album_list_object();
					var sort = {
						"1": album_list.SORT_UPLOAD_ASC,
						"2": album_list.SORT_UPLOAD_DESC,
						"3": album_list.SORT_SHOOT_ASC,
						"4": album_list.SORT_SHOOT_DESC
					}[sorttype];
					this.add_photo_attach_dategroup(div_container, id, sort);
				} else {
					self.add_photo_attach_datelabel(div_container, id).addClass("photo-datelabel-base disablemenu");
				}
			}
		}


		// 動画なら動画アイコンを表示する
		if (photo.type == self.PHOTO_TYPE_VIDEO) {
			div_container.append(
				$(document.createElement('div')).
					addClass('movie-icon')
			);
		}

		div_container.append(img);
		return true;
	},

	add_photo_attach_datelabel: function(div_container, id){
		var datediv = $(document.createElement('div')).
			addClass("iconmenu photo-datelabel photo-datelabel-clickable").
			css({margin: '0px', height: this.thumnail_datediv_height + "px"}).
			attr("id", "photo-datelabel-" + id);
		div_container.append(datediv);
		return datediv;
	},

	// 日付グルーピングの要素を追加する
	add_photo_attach_dategroup: function(div_container, id, album_sort){
		var self = this;
		var photo = self.photo_list[id];

		var datediv = self.add_photo_attach_datelabel(div_container, id);
		if (album_sort) {
			datediv.removeClass("photo-datelabel-clickable");
		}

		// 日付を表示する
		var date;
		var iconsrc;
		var i;
		var date_type;
		var current_sort = album_sort || self.current_sort();
		var get_album_list_object = self.get_album_list_object();
		if (current_sort == get_album_list_object.SORT_SHOOT_ASC || current_sort == get_album_list_object.SORT_SHOOT_DESC) {
			date = epoch2date(photo.shoot, "/");
			if (album_sort) {
				datediv.addClass("photo-datelabel-base photo-datelabel-shoot-unclickable");
			} else {
				datediv.addClass("photo-datelabel-base photo-datelabel-shoot");
			}
			iconsrc = "/common/images/small_icons/camera_grayscale.png";
			date_type = 'shoot';
		} else {
			date = epoch2date(photo.upload, "/");
			iconsrc = "/common/images/small_icons/upload_grayscale.png";
			if (album_sort) {
				datediv.addClass("photo-datelabel-base photo-datelabel-upload-unclickable");
			} else {
				datediv.addClass("photo-datelabel-base photo-datelabel-upload");
			}
			date_type = 'upload';
		}
		photo.date_label = date;

		var label_has_id = self.current_date_labels[date];
		var new_display_id = null;
		var old_display_id = null;
		var display_date_label = true;
		if (label_has_id !== undefined) {
			if (label_has_id === id) {
				// ラベルを表示すべき写真
				new_display_id = id;
			} else if (label_has_id > id) {
				// これから表示するidより小さいidの時は大きい方のidでの日付表示を消しておく
				new_display_id = id;
				old_display_id = label_has_id;
			} else {
				// 既に対象のものが処理されているので、何もしない
			}
		} else {
			new_display_id = id;
		}


		// new_display_id から +-2個分の写真の日付を作っておく
		var photos = self.photo_list;
		for (i = new_display_id - 2 ; i < new_display_id + 2 ; i++) {
			if (i <= 0) continue;
			if (!photos[i]) continue;
			if (photos[i].date_label != undefined) continue;
			photos[i].date_label = epoch2date(photos[i][date_type], '/');
		}

		var set_dateend = function (id) {
			$("#photo-datelabel-" + id).
				removeClass("disablemenu enablemenu").
				addClass("disablemenuend");
			photos[id].is_dateend = true;
		};

		if (!photos[id + 1] && photos[id-1] && photos[id-1].date_label && photos[id-1].date_label == date) {
			// 最後のIDっぽくて一つ前の写真も同じ日付なら end にする
			set_dateend(id);
		}


		if (old_display_id !== null) {
			$("#photo-datelabel-" + old_display_id).
				text("").
				removeClass("enablemenu").
				addClass("disablemenu").
				unbind('click');
		}
		if (new_display_id !== null) {
			var date_class = "date_class_" + date.replace(/\//g, "");
			datediv.text(date).
				removeClass("disablemenuend").
				addClass(date_class);
			if (!album_sort) {
				datediv.addClass("enablemenu");
			}

			if (
				self.current_date_labels[date] && photos[new_display_id + 1] && photos[new_display_id + 2] &&
				photos[new_display_id + 1].date_label && photos[new_display_id + 2].date_label &&
				photos[new_display_id + 1].date_label == date &&
				photos[new_display_id + 2].date_label != date
			) {
				// 一つ先の写真が同じ date で且つ、二つ先の写真の date が違う時だけ一つ先の写真を end 扱いにする
				set_dateend(new_display_id + 1);
			}

			self.current_date_labels[date] = new_display_id;

			if (
				self.current_date_labels[date] && photos[new_display_id - 1] && photos[new_display_id - 2] &&
				photos[new_display_id - 1].date_label && photos[new_display_id - 2].date_label &&
				photos[new_display_id - 2].date_label != date &&
				photos[new_display_id - 2].date_label == photos[new_display_id - 1].date_label
			) {
				// 二つ前の写真が違う date で且つ、一つ前と二つ前の写真の date が同じなら一つ前の写真を end 扱いにする
				set_dateend(new_display_id - 1);
			}
		} else {
			if (photos[id].is_dateend) {
				set_dateend(id);
			} else {
				$("#photo-datelabel-" + id).addClass("disablemenu");
			}
			return;
		}
	},

	add_photo_attach_objects: function(div_container, photo, id, img){
		var self = this;

		//選択を早くするために、お互いの参照を持つ。
		photo.img = img;
		photo.id = id;
		div_container.attr("index", id);
		self.mark_photo_if_selected(id, img);
		img.data("id", id);

		// print mode では、以下の処理は不要
		if (self.is_print) return;

		// good comment
		var view  = $(document.createElement('div')).addClass("view");
		photo.infoview = view;

		// グッド数およびコメント数がゼロの場合は表示しない。
		if (photo.photo_comment_count !== 0) {
			var comment  = $(document.createElement('div')).
				addClass("view_comment").
				append( $(document.createElement('span')).
						  addClass("view_comment_label").
						  text(photo.photo_comment_count)
					  );
			view.append(comment);
			//safari は要素がちゃんと親についてないと、hide() が効かない。
			if (false === this.is_comment_checked) {
				//comment.hide();
				//for safari
				comment.css({'display':'none'});
			}
			photo.commentview = comment;
		}
		if (photo.photo_good_count !== 0) {
			var good  = $(document.createElement('div')).
				addClass("view_good").
				append( $(document.createElement('span')).
						addClass("view_good_label").
						text(photo.photo_good_count)
					  );
			view.append(good);
			if (false === this.is_good_checked) {
				//全体の制御は、gallery.js に。
				//good.hide();
				good.css({'display':'none'});
			}
			photo.goodview = good;
		}
		div_container.append(view);

		var target = img;
		var selected = this.SELECT_IMAGE_CLASS;
		
		//機能を装着
		var countdiv = null;
		
		//メンバービューでは選択しない。自分の写真じゃ無い時も表示しない
		if (!self.is_member_view && self.gallery.show_user_id == self.user_id) {
			target.draggable({
				appendTo: '#wrapper',
//				containment: 'window',
				cursor: "move",
				cursorAt: {top:50,left:50},
				opacity: 0.6,
				scroll: false,
				
				start: function(e, ui){
					$("#left_viewer > .album_menu").addClass("album_menu_disablehover").removeClass("album_menu");
					$("#left_viewer > .album_menu_share").addClass("album_menu_share_disablehover").removeClass("salbum_menu_share");
					var num = 1;
					if (!target.hasClass(selected)) {
						// 選択中の写真以外をドラッグしたので選択解除
						self.unmark_showingphotos();
						self.addSelectAction({id:id,type:self.SELECT_ACTION_CLICK});
						self.mark_photo_if_selected(id, target);
					} else {
						num = self.get_marked_photos_count();
					}
					if (countdiv) {
						countdiv.text(num);
					}

					// show easy sharing
					$('#easy_sharing_container').show();
				},
				//helper: 'clone',
				helper: function() {
					//独自クローンを返すっす。
					var container  = $(document.createElement('div'));
					container.addClass("photo_thumbnail_clone");
					var imgclone = target.clone();
					imgclone.removeClass(selected);
					container.append(imgclone);
					if (!countdiv) {
						countdiv = $(document.createElement('div'));
						countdiv.addClass("view_dragcount");
					}
					container.append(countdiv);
					return container;
				},
				drag: function(e, ui){
				},
				stop: function(e, ui){
					$("#left_viewer > .album_menu_disablehover").removeClass("album_menu_disablehover").addClass("album_menu");
					$("#left_viewer > .album_menu_share_disablehover").removeClass("album_menu_share_disablehover").addClass("album_menu_share");

					// hide easy sharing
					$('#easy_sharing_container').hide();
				}
			});

		}
	},

	click_thumbnail_image: function(e, id, target){
		var self = this;
		var selected = self.SELECT_IMAGE_CLASS;
		if (!self.is_member_view && self.gallery.show_user_id == self.user_id) {
			self.key_select_actions_shift_on = false;
			if (self.select_actions.length && self.select_actions[0].type === self.SELECT_ACTION_CLICK_ON_DATE) {		
				// 日付選択は、他の選択系と共存できない
				self.select_actions = [];
				self.select_actions_shift_on = false;

				// 選択解除
				$("#photo-list > div.photo_thumbnail > ."+self.SELECT_IMAGE_CLASS).removeClass(self.SELECT_IMAGE_CLASS);
				self.current_focus_id = null;
			}


			if (self.select_actions.length === 0) {
				// shift key 選択のリセット
				self.select_actions_shift_on = false;
			}

			if (e.shiftKey) {
				// shift key は範囲選択として使う
				if (self.select_actions_shift_on === false && !self.is_select_action_all()) {
					// 最初の選択開始
					self.select_actions_shift_on = id;
					self.addSelectAction({id:id,type:self.SELECT_ACTION_CLICK});
				} else {
					// 選択完了
					self.addSelectAction({
						first_id: self.select_actions_shift_on,
						last_id:  id,
						type:     self.SELECT_ACTION_CLICK_WITH_SHIFT
					});
					self.select_actions_shift_on = false;
				}
				self.mark_showing_photos_if_selected();
			} else if (e.metaKey) {
				// meta keyは選択中は選択解除、非選択では選択になる
				self.addSelectAction({id:id,type:self.SELECT_ACTION_CLICK_WITH_CONTROL});
				if (self.mark_photo_if_selected(id, target) || self.is_select_action_all()) {
					self.select_actions_shift_on = id;
				} else {
					self.select_actions_shift_on = false;
				}
			} else {
				// ノーマルのクリックは、選択解除してクリックした写真のみ選択
				self.select_actions = [];
				self.addSelectAction({id:id,type:self.SELECT_ACTION_CLICK});
				self.mark_showing_photos_if_selected();
				self.select_actions_shift_on = id;
			}
			self.current_focus_id = id;
		} else {
			$("#photo-list > div.photo_thumbnail > ."+selected).removeClass(selected);
			target.addClass(selected);
			self.current_focus_id = id;
		}
	},

	dbclick_thumbnail_image: function(e, id){
		this.start_photoviewer();
		this.show_photo(id);
	},

	// 日付ラベルのクリック処理
	click_thumbnail_datelabel: function(e, target){
		e.preventDefault();
		var datestring = target.text();
		if (datestring.length == 0) return;
		var self = this;

		// クリック処理を行うfunction
		var click_action = function(first_photo_id, last_photo_id){
			// 日付選択は、他の選択系と共存できない
			self.select_actions = [];

			// 選択完了
			self.addSelectAction({
				first_photo_id: first_photo_id,
				last_photo_id:  last_photo_id,
				date_label:     datestring,
				type:           self.SELECT_ACTION_CLICK_ON_DATE
			});
			self.mark_showing_photos_if_selected();
			self.enablePhotoAction(); // 削除/tagを実行可能にする
		};

		// クリックした日付の最初と最後のphoto_idをajaxで取得する
		var date = datestring.split("/").join("");

		if (self.by_date[date]) {
			// 日付のphoto_id listは取得済み
			click_action(self.by_date[date].first_id, self.by_date[date].last_id);
		} else {
			var sort = self.current_sort() || self.get_album_list_object().DEFAULT_ALL_SORT;
			$.ajax({
				url : "/photo/" + self.user_id + "/range_of/" + date + "/" + sort,
				type : "get",
				dataType: "json",
				cache: false,
				success : function(data){
					if (data.msg == "ng") {
						return;
					}
					self.by_date[date] = data; // cache
					click_action(data.first_id, data.last_id);
				}
			});
		}
	},

	// プリント写真の枚数表示など
	add_photo_attach_print: function(div_container, id){
		var div = $("<DIV/>").
			addClass("photo-printlabel").
			css({height: this.thumnail_datediv_height + "px"}).
			attr("id", "photo-printlabel-" + id);
		this.print_manager.set_printlabel_text(div, id);
		div_container.append(div);
	},

	clearSelectActions: function() {
		this.select_actions = [];
		this.select_actions_shift_on = false;
		this.key_select_actions_shift_on = false;
		var selected = this.SELECT_IMAGE_CLASS;
		$("#photo-list > div.photo_thumbnail > ."+selected).removeClass(selected);
		this.disablePhotoAction();
	},

	enablePhotoAction: function(){
		var menuicon = this.menuicon_manager;
		if (this.is_print) {
			menuicon.selected(menuicon.TYPE_PHOTO_PRINT_MENU);
			menuicon.selected(menuicon.TYPE_PHOTO_PRINT_ORDER_MENU);
		} else {
			menuicon.selected(menuicon.TYPE_PHOTO_MENU);
		}
	},
	disablePhotoAction: function(){
		var menuicon = this.menuicon_manager;
		if (this.is_print) {
			menuicon.unselected(menuicon.TYPE_PHOTO_PRINT_MENU);
			menuicon.unselected(menuicon.TYPE_PHOTO_PRINT_ORDER_MENU);
		} else {
			menuicon.unselected(menuicon.TYPE_PHOTO_MENU);
		}
	},
	addSelectAction: function(action) {
		this.select_actions.push(action);
		if (this.get_marked_photos_count() > 0) {
			this.enablePhotoAction();
		} else {
			this.disablePhotoAction();
		}
	},
	removeSelectAction: function(id) {
		var self = this;
		var actions = [];
		$.each(self.select_actions, function(i){
			var data = self.select_actions[i];
			if (data.id != id) actions.push(data);
		});
		self.select_actions = actions;
		if (this.get_marked_photos_count() === 0) {
			this.disablePhotoAction();
		}
	},
	
	unmark_showingphotos: function() {
		this.clearSelectActions();
	},

	// select_actions の queue を辿って、選択されてるべきphoto idリストを返す
	get_marked_photos_exceptall: function() {
		var self = this;
		var selectedphotos = {};
		for (var i = 0; i < self.select_actions.length; i++) {
			var action = self.select_actions[i];
			switch (action.type) {
				case self.SELECT_ACTION_ALL: {
					break;
				}
				case self.SELECT_ACTION_CLICK: {
					selectedphotos[action.id] = true;
					break;
				}
				case self.SELECT_ACTION_CLICK_WITH_SHIFT: {
					var first_id = action.first_id;
					var last_id  = action.last_id;
					if (first_id > last_id) {
						var tmp  = first_id;
						first_id = last_id;
						last_id  = tmp;
					}

					for (var id = first_id; id <= last_id; id++) {
						selectedphotos[id] = true;
					}
					break;
				}
				case self.SELECT_ACTION_CLICK_WITH_CONTROL: {
					if (selectedphotos[action.id] === true) {
						selectedphotos[action.id] = false;
					} else {
						selectedphotos[action.id] = true;
					}
					break;
				}
				case self.SELECT_ACTION_CLICK_ON_DATE: {
					// generate_photo_select_query では呼び出されなくて
					// get_marked_photos_count でしか使われない予定なので、数量分の空データの配列を返す
					// とりあえず、選択中の要素のDOM elementを返す
					return $("."+self.SELECT_IMAGE_CLASS).get();
					break;
				}
				default: { break; }
			}
		}

		var ret = [];
		$.each(selectedphotos, function(i){
			if (selectedphotos[i]) ret.push(i);
		});
		ret.sort(function(a,b){ return Number(a) - Number(b); });
		return ret;
	},
	
	get_marked_photos_count: function() {
		var self = this;
		if (self.select_actions.length === 0) {
			return 0;
		}
		var previousclickaction = null;
		var selectedphotos = this.get_marked_photos_exceptall();
		var count = selectedphotos.length;
		if (this.is_select_action_all()) count = this.total - count;
		return count;
	},
	
	mark_showing_photos_if_selected: function() {
		if (this.select_actions.length === 0) {
			return;
		}
		var current_first_id = this.current_first_id;
		var current_last_id  = this.current_last_id;
		if (current_first_id < 0 || current_last_id < 0) return;
		for (var i = current_first_id; i <=  current_last_id;i++) {
			if (!this.photo_list[i]) continue;
			var photoimg = this.photo_list[i].img;
			this.mark_photo_if_selected(i, photoimg);
		}
	}, 

	// id の photo が選択中か調べる
	is_selected_photo: function(id) {
		var isselected = false;
		var previousclickaction = null;
		var self = this;
		var is_selected_photo = this.is_select_action_all();
		for (var i = 0; i < self.select_actions.length; i++) {
			var action = self.select_actions[i];
			switch (action.type) {
				case self.SELECT_ACTION_ALL: {
					isselected = true;
					break;
				}
				case self.SELECT_ACTION_CLICK: {
					if (action.id == id) {
						isselected = true;
					}
					previousclickaction = action;
					break;
				}
				case self.SELECT_ACTION_CLICK_WITH_SHIFT: {
					var first_id = action.first_id;
					var last_id  = action.last_id;
					if (first_id > last_id) {
						var tmp  = first_id;
						first_id = last_id;
						last_id  = tmp;
					}
					if (id >= first_id && id <= last_id) {
						if (is_selected_photo) {
							isselected = false;
						} else {
							isselected = true;
						}
					}
					break;
				}
				case self.SELECT_ACTION_CLICK_WITH_CONTROL: {
					if (action.id == id) {
						isselected = !isselected;
					}
					break;
				}
				case self.SELECT_ACTION_CLICK_ON_DATE: {
					// 日付選択 同じ日付だったら ok
					var photo = self.photo_list[id];
					if (photo.date_label == action.date_label) {
						isselected = true;
					}
					break;
				}
				default: { break; }
			}
		}
		return isselected;
	},
	
	mark_photo_if_selected: function(id, ui) {
		if (!ui) {
			return null;
		}
		var isselected = this.is_selected_photo(id);
		var selected = this.SELECT_IMAGE_CLASS;
		if (isselected === true) {
			ui.addClass(selected);
		} else {
			ui.removeClass(selected);
		}
		return isselected;
	},

	update_photo_count_label: function() {
		$("#photo_count_box").text(this.total);
		$('#photo_count_container').removeClass('photo_count');
		$('#photo_count_container').removeClass('photo_count2');
		$('#photo_count_container').removeClass('photo_count3');

		if (this.gallery && this.gallery.show_user_id != this.user_id) {
			$('#photo_count_container').addClass('photo_count3');
		} else if (this.album === null) {
			$('#photo_count_container').addClass('photo_count');
		} else {
			$('#photo_count_container').addClass('photo_count2');
		}
		$('#photo_count_container').show();
	},
	
	permalink_listener: function(permalink, mode, args) {
	},

	select_all: function(){
		this.select_actions = [];
		this.select_actions_shift_on = false;
		this.addSelectAction({type:photo_list.SELECT_ACTION_ALL});
		this.mark_showing_photos_if_selected();
	},

	clear: function(){
		var self = this;
		if (self.is_photoviewer) self.end_photoviewer(1);
		this.is_good_checked = $('#good-button').hasClass("checked");
		this.is_comment_checked = $('#comment-button').hasClass("checked");

		this.total = 0;
		$("#photo_count_box").text("0");
		$("#photo-list").empty();

		this.photo_list           = [];
		this.page_list            = [];
		this.thumnail_status_list = [];
		this.show_page_list       = [];
		this.load_page_list       = [];
		this.by_date              = {};
		this.unmark_showingphotos();

		this.is_paging        = false;
		this.is_photo_loading = false;
		this.add_photo_queue_running = false;

		this.current_center_id = -1;
		this.current_first_id  = -1;
		this.current_last_id   = -1;
		this.current_focus_id  = null;

		this.select_actions          = [];
		this.select_actions_shift_on = false;
		this.key_select_actions_shift_on = false;

		/*
		// sort順と選択したtagをクリアすると正しい物が取れなくなる
		this.current_target      = "gallery";
		this.current_target_args = "";
		*/

		this.current_date_labels = {};

		this.current_add_photo_proc = 0;

		this.photo_list_scrollTop = 0;
		$("#photolist_viewer_area").scrollTop(this.photo_list_scrollTop);
		
		this.resize_photolist_space();
	}
};
//===============================================================
/* album list class */
function AlbumList(args){
	this.base_path      = args.base_path;
	this.user_id        = args.user_id;
	this.show_user_id   = args.user_id;
	this.img_base_url   = args.img_base_url;
	this.viewer_user_id = args.viewer_user_id;
	this.photo_list     = args.photo_list;

	this.DEFAULT_ALL_SORT   = this.SORT_SHOOT_DESC;
	this.DEFAULT_ALBUM_SORT = this.SORT_UPLOAD_ASC;

	this.sort_default   = args.sort_default || this.DEFAULT_ALL_SORT;

	this.is_gallery = (args.base_path ? false : true);

	this.widget = new Ficia.Widget.AlbumList({
		album: this,
		photo: args.photo_list,
		user_id: args.user_id,
		viewer_user_id: args.viewer_user_id,
		is_gallery: this.is_gallery
	});
}
AlbumList.prototype = {
	DATE_TYPE_SHOOT: "shoot",
	DATE_TYPE_UPLOAD: "upload",

	SORT_SHOOT_ASC: "shoot_asc",
	SORT_SHOOT_DESC: "shoot_desc",
	SORT_UPLOAD_ASC: "upload_asc",
	SORT_UPLOAD_DESC: "upload_desc",

	base_path: null,
	user_id: null,
	show_user_id: null, // 表示中の画像データを持ってるユーザ
	show_nickname: null,
	show_member_url: null,
	img_base_url: null,
	viewer_user_id: null,
	photo_list: null,
	list: [],    
	attribute: null,
	last_open_args: {},
	current_album: null,

	permalink_manager: null,
	menuicon_manager: null,


	isValidDateType: function(datetype) {
		if (this.DATE_TYPE_SHOOT == datetype) {
			return true;
		} else if (this.DATE_TYPE_UPLOAD == datetype) {
			return true;
		} else {
			return false;
		}
	},

	// 現在のIDの次のページを取得する
	load_next_page: function(id){
		var page_items = this.photo_list.page_items;

		// 次のページ
		var next_id = id + page_items;
		if (next_id <= this.photo_list.total) {
			var next_page = Math.floor(next_id / page_items);
			if (!this.photo_list.load_page_list[next_page]) {
				this.load_page([next_page], true);
			}
		}

		// 前のページも取得する
		var prev_id = id - page_items;
		if (prev_id >= 0) {
			var prev_page = Math.floor(prev_id / page_items);
			if (!this.photo_list.load_page_list[prev_page]) {
				this.load_page([prev_page], true);
			}
		}
	},

	// ajax で p page データを取ってきて img タグを作成する
	load_page: function(page_list, is_not_show, open_count){
		var self = this;
	
		var url = "/photo/list/" + self.show_user_id;

		var data = { order: self.last_open_args.sorttype }; 

		if (self.last_open_args.tags) {
			data.tags = self.last_open_args.tags.join("\t");
		}
		// 日付絞り込み条件
		if (self.isValidDateType(self.last_open_args.datetype)) {
			//配列から文字列へ
			var args = self.last_open_args;
			data.datetype = args.datetype;
			data.year     = args.year;
			data.mon      = args.mon;
			data.day      = args.day;
		}

		if (self.photo_list.album) {
			url += '/' + self.photo_list.album.album_id;
			data = {};
		}

		if (self.photo_list.is_print) {
			url = "/photo/" + self.show_user_id + "/print/queue";
		}

		var loader;
		loader = function(page){
			if (page === null) return;
			if (self.photo_list.load_page_list[page] == -1) {
				// 既に読み込みリクエスト中
				loader(page_list.shift());
				return;
			}
			if (!self.photo_list.load_page_list[page]) {
				self.photo_list.load_page_list[page] = -1;
				data.page = page;
				$.ajax({
					url : url,
					type : "get",
					dataType: "json",
					data : data,
					cache: false,
					success : function(data){
						if (open_count && open_count != self.open_count) return;
						if (self.last_open_args.album && self.last_open_args.album.album_id != data.album_id) return; // 開きたいアルバムじゃない
						if (data.photo_list) {
							var list = data.photo_list;
							self.photo_list.add_gallery_photo_manager(data.photo_list, page, is_not_show);
						}
						self.photo_list.load_page_list[page] = 1;
					}
				});
			} else if (self.photo_list.load_page_list[page] <= self.photo_list.page_items) {
				// 表示してない要素があるかもしれないので、一応managerに処理させる
				self.photo_list.add_gallery_photo_manager(null, page);
			}
			loader(page_list.shift());
		};
		page_list.push(null);
		loader(page_list.shift());
	},

	reopen: function(args){
		if (!args) args = {};
		this.photo_list.clear();
		if (this.last_open_args.album) this.last_open_args.album.photos = null;
		var open_args = this.last_open_args;
		if (args.tmp_default_index) open_args.tmp_default_index = args.tmp_default_index;
		if (args.sorttype) open_args.sorttype = args.sorttype;
		this.open(open_args);
	},
	open_count: 0,
	next_default_index: 0,
	skip_open: false,
	open: function(args){
		var self = this;
		if (args === null) args = {};
		$('#album_link').hide();
		$('#photo_link').hide();
		$('#album_link-box').hide();
		$('#photo_link-box').hide();
		if (self.skip_open) {
			if (self.permalink_manager) {
				self.permalink_manager.callTrigger('skip-list-open');
				return;
			}
		}
		var tmp_default_index = 0;
		if (args.tmp_default_index) {
			tmp_default_index = args.tmp_default_index;
			delete args.tmp_default_index;
		} else if (self.next_default_index) {
			tmp_default_index = self.next_default_index;
			delete self.next_default_index;
		}

		if (!args.album) {
			if (args.is_print) {
				if (args.order_name) {
					modal_message_open('過去の注文データを開いています');
				} else {
					modal_message_open('プリントを開いています');
				}
			} else {
				modal_message_open('ギャラリーを開いています');
			}
			self.current_album = null;
		} else {
			modal_message_open('アルバムを開いています');
			self.current_album = args.album;
		}
		
		self.photo_list.reset_photo_queue();
		self.open_count++;

		self.last_open_args = args;
		if (self.permalink_manager) {
			self.set_permalink_current_album({ current_center_id: tmp_default_index });
		}

		if (args.album) {
			args.srottype = self.DEFAULT_ALBUM_SORT;
		} else {
			if (!args.sorttype) {
				args.sorttype = self.sort_default;
			} else {
				self.sort_default = args.sorttype;
			}
		}
		// sort のアイコン変更
		if (args.sorttype == self.SORT_SHOOT_ASC || args.sorttype == self.SORT_SHOOT_DESC) {
			$('#sort-by-shoot').removeClass('disablemenu').addClass('enablemenu');
			$('#sort-by-upload').removeClass('enablemenu').addClass('disablemenu');
		} else {
			$('#sort-by-shoot').removeClass('enablemenu').addClass('disablemenu');
			$('#sort-by-upload').removeClass('disablemenu').addClass('enablemenu');
		}

		var url = "/photo/list/" + self.show_user_id;
		if (args.album)	url = url + "/" + args.album.album_id;
		if (args.is_print) {
			if (args.order_name) {
				url = "/photo/" + self.show_user_id + "/print/order/" + args.order_name + "/items";
			} else {
				url = "/photo/" + self.show_user_id + "/print/queue";
			}
		}

		if (self.show_user_id == self.user_id) {
			var menuicon = self.menuicon_manager;
			if (args.album) {
				menuicon.selected(menuicon.TYPE_ALBUM_MENU);
			} else {
				menuicon.unselected(menuicon.TYPE_ALBUM_MENU);

				// 全選択が有効かどうか
				if (args.tags || self.isValidDateType(args.datetype)) {
					//有効
					menuicon.enable_with(menuicon.TYPE_ALBUM_MENU, ["selectall"]);
				} else {
					//ギャラリーで何の絞り込みもない。
					menuicon.disable_with(menuicon.TYPE_ALBUM_MENU, ["selectall"]);
				}
			}
		}

		if (args.is_print) {
			$("#setting").hide();
		} else if (args.album) {
			$("#setting").show();
			$("#setting-find").hide();

			// 最初は、全部の sort アイコンは無効にしとく
			if (!args.sorttype) {
				$('#sort-by-shoot').removeClass('enablemenu').addClass('disablemenu');
				$('#sort-by-upload').removeClass('enablemenu').addClass('disablemenu');
			}
		} else {
			$("#setting").show();
			$("#setting-find").show();
		}

		//------------------------------------------------


		if (self.base_path) url = self.base_path + url;

		self.slide_photo_selected_index = -1;
		self.photo_list.end_photoviewer(1);
		self.photo_list.clear();
		self.photo_list.resize();

		//既にアルバムがロードされているのなら。
		if (args.album && args.album.photos) {
			var photos = new Array();
			var i;
			for (i = 0; i < args.album.photos.length; i++) {
				photos.push(args.album.photos[i]);
			}
			//ソート
			var sortor;
			if (args.sorttype == self.SORT_SHOOT_ASC) {
				sortor = function(photo1, photo2) { return(photo1.shoot - photo2.shoot); };
			} else if (args.sorttype == self.SORT_SHOOT_DESC) {
				sortor = function(photo1, photo2) { return(photo2.shoot - photo1.shoot); };
			} else if (args.sorttype == self.SORT_UPLOAD_ASC) {
				sortor = function(photo1, photo2) { return(photo1.upload - photo2.upload); };
			} else {
				sortor = function(photo1, photo2) { return(photo2.upload - photo1.upload); };
			}
			photos.sort(sortor);

			self.photo_list.total = photos.length;
			self.photo_list.update_photo_count_label();
			self.photo_list.add_photo_manager(photos);
			self.photo_list.resize();
			modal_message_close();
			return;
		}

		/* 右側の領域に指定されたアルバムの写真を敷き詰める */
		/*  null だったら全部の写真 */
		var data = { order: args.sorttype || '' }; 
		if (args.tags) {
			//配列から文字列へ
			data.tags = args.tags.join("\t");
		}
		// 日付絞り込み条件
		if (self.isValidDateType(args.datetype)) {
			//配列から文字列へ
			data.datetype = args.datetype;
			data.year     = args.year;
			data.mon      = args.mon;
			data.day      = args.day;
		}

		self.photo_list.is_paging = true;

		self.update_attribute(args.album);
		data.mode = 'head'; // 最初の一回目はデータの数とか取るだけにとどめる
		data.page = 0;
		(function(open_count){
		$.ajax({
			url : url,
			type : "get",
			dataType: "json",
			data : data,
			cache: false,
			success : function(obj){
				if (args.album && args.album.album_id != obj.album_id) return; // 開きたいアルバムじゃない
				$(".active").removeClass("active");
				var title_album = $("#title_album");

				title_album.removeClass("title_album_gallery title_album_album title_album_share title_album_print");
				self.photo_list.is_print = false;
				if (args.is_print) {
					// プリントカートの中の写真
					self.photo_list.is_print = true;
					self.photo_list.album = null;
					self.photo_list.total = obj.total;
					self.photo_list.page = 0;
					self.photo_list.page_list[self.photo_list.page] = true;
					title_album.text("プリント");
					title_album.addClass("title_album_print");
				} else if (!args.album) {
					self.photo_list.album = null;
					self.photo_list.total = obj.total;
					self.photo_list.page = 0;
					self.photo_list.page_list[self.photo_list.page] = true;
					title_album.text("ギャラリー");
					title_album.addClass("title_album_gallery");
					$("#open-gallery").addClass("active");
				} else {
					self.photo_list.album = args.album;
					self.photo_list.total = obj.total;
					self.photo_list.page = 0;
					self.photo_list.page_list[self.photo_list.page] = true;
					$("#album-" + args.album.album_id).addClass("active");
					if (self.show_nickname) {
						title_album.addClass("title_album_share");
						title_album.text(self.show_nickname + 'さんのアルバム「' + args.album.album_title + '」');
					} else {
						title_album.addClass("title_album_album");
						title_album.text(args.album.album_title);
					}

					// ficia/外部サイトでの共有具合を表示
					if (!this.is_member_view) {
                        // hide all
                        $.each(['ficia', 'facebook', 'flickr'], function (i, n) {
							$('#album-shared-in-'+n).hide();
                        });

						if (args.album.access_level > 1) {
							$('#album-shared-in-ficia').show();
						}
						if (args.album.external_site & 1) {
							$('#album-shared-in-facebook').show();
						}
						if (args.album.external_site & 2) {
							$('#album-shared-in-flickr').show();
						}
					}
				}

				if (obj.photo_list && obj.total) {
					//update
					if (args.album) {
						args.album.photos = obj.photo_list;
					}
					self.photo_list.update_photo_count_label();
					self.photo_list.dummy_image_loading_to_current();

					// 0 page 目のデータとしてセット
					if (open_count == self.open_count && !self.photo_list.load_page_list[0]) {
						self.photo_list.add_gallery_photo_manager(obj.photo_list, 0, false);
						self.photo_list.load_page_list[0] = 1;
					}

					// 他のページ分も取得して表示 もし連打とかで上の 0 page 目のデータセットされてなくても、 load_current_page が再チャレンジしてくれる
					self.photo_list.load_current_page(self.open_count);
				} else {
					self.photo_list.total = 0;
					self.photo_list.add_photo_manager(new Array());
					self.photo_list.update_photo_count_label();
				}
				if (args.callback) args.callback();
				self.photo_list.resize();
				if (tmp_default_index) self.photo_list.centering(tmp_default_index);
				modal_message_close();

				// album の写真のデータが読めたよ
				if (self.permalink_manager) self.permalink_manager.callTrigger('album-photos-loaded');
			}
		});
		}(self.open_count));
	},


	can_external_tweet: null,
	is_share_album: null,
	update_attribute: function(album){
		/* アルバムの属性を取得する */
		var self = this;
		self.attribute = null;
		if (!album) return;

		var attribute_url = "/album/" + self.show_user_id + "/" + album.album_id + '/attribute';
		if (self.base_path) url = self.base_path + attribute_url;
		$.ajax({
			url : attribute_url,
			type : "get",
			dataType: "json",
			cache: false,
			success : function(data){
				self.attribute = data;
				var show_link = false;
				if (!$('#open-share').hasClass('enablemenu') && self.attribute && (self.attribute.access_level == 3 || album.access_level == 3)) {
					self.can_external_tweet = true;
					show_link = true;
				} else {
					self.can_external_tweet = false;
					if (self.is_gallery) {
						show_link = true;
					}
				}
				if (self.attribute && (self.attribute.access_level >= 2 || album.access_level >= 2)) {
					self.is_share_album = true;
				} else {
					self.is_share_album = false;
				}
				if (show_link) {
					$('#album_link').show();//.css({ opacity: 0.7 });
					$('#photo_link').show();//.css({ opacity: 0.7 });
				}
			}
		});
		return;
	},

	/* アルバムリストを開き type=admin なら右側に全部の写真を表示する */
	open_album_queue_num: 0,
	open_album_list: function(type, args){
		var self = this;
		self.open_album_queue_num++;
		if (args && args.show_nickname) {
			self.show_nickname = args.show_nickname;
		} else {
			self.show_nickname = null;
		}
		if (args && args.show_member_url) {
			self.show_member_url = args.show_member_url;
		} else {
			self.show_member_url = null;
		}
		if (args && args.show_user_id) {
			self.show_user_id = args.show_user_id;
			self.widget.user_id = args.show_user_id;
		} else {
			self.show_user_id = self.user_id;
			self.widget.user_id = self.user_id;
			// album-list をクリア
			self.clear();
		}

		/* 左のエリアに全てのアルバムを並べる */
		var force_access_level = null;
		var url = "/album/";
		if (type == "share") {
			url += "share_";
		} else if (type == "gallery") {
			url += "gallery_";
		} else {
			force_access_level = 3;
		}
		url += "list/" + self.show_user_id;

		if (self.base_path) url = self.base_path + url;
		$.ajax({
			url : url,
			type : "get",
			dataType: "json",
			cache: false,
			success : function(data){
				$.each(data, function (i) {
					if (!data[i]) {
						return;
					}
					if (data[i].access_level === undefined && force_access_level !== null) data[i].access_level = force_access_level;
					self.widget.add(
						data[i].album_id,
						{
							album_id:        data[i].album_id,
							album_title:     data[i].album_title, 
							album_details:   data[i].album_details, 
							album_thumbnail: data[i].album_thumbnail,
							photo_count:     data[i].album_photo_count,
							external_site:   data[i].external_site,
							access_level:    data[i].access_level,
							sort_type:       data[i].sort_type
						},
						type
					);
				});
				self.open_album_queue_num--;
				if (self.open_album_queue_num <= 0) {
					// album open 完了
					if (self.permalink_manager) self.permalink_manager.callTrigger('album-open');
				}
			}
		});
	},

	set_permalink_current_album: function(opts){
		var self = this;
		if (!self.permalink_manager) return;
		var args = self.last_open_args;
		if (opts) {
			if (opts.current_center_id) args.current_center_id = opts.current_center_id;
		}
		if (args.album) {
			self.permalink_manager.changeMode('album', args);
		} else {
			self.permalink_manager.changeMode('gallery', args);
		}
		if (opts) {
			delete args.current_center_id;
		}
	},
	permalink_listener: function(permalink, mode, args) {
		var self = this;
		if (mode != 'detection' && self.photo_list.gallery) {
			if ($('#open-share').hasClass('enablemenu')) {
				// gallery の時に共有リストがアクティブなら
				permalink.path = 'following';
				return;
			}
		}

		// サムネイルリスト上部の微調整
		var cols = self.photo_list.thumnail_cols;
		if (args.current_center_id) {
			args.current_center_id -= Math.floor(cols / 2);
			if (args.current_center_id <= cols * 2) args.current_center_id = 0;
		}

		switch (mode) {
		case 'album':
			var path = 'album/' + args.album.album_id;
			if (args.current_center_id) path += '?index=' + args.current_center_id;
			permalink.path = path;
			break;
		case 'album-photo':
			var path = 'album-photo/' + args.album_id + '/' + args.photo_id;
			permalink.path = path;
			break;
		case 'gallery':
			var path = 'list';
			if (args.current_center_id) path += '?index=' + args.current_center_id;
			permalink.path = path;
			break;
		case 'photo':
			var path = 'photo/' + args.photo_id;
			permalink.path = path;
			break;
		case 'detection':
			// permalink 用の写真表示をする
			var open_photo = function(photo_id) {
				var url = '/photo/' + self.show_user_id + '/' + photo_id + '/attribute';
				if (self.base_path) url = self.base_path + url;
				$.ajax({
					url : url,
					type : "get",
					dataType: "json",
					cache: false,
					success : function(data){
						if (data.photo_id == photo_id) {
							self.photo_list.start_photoviewer();
							self.photo_list.show_photo(data, { is_permalink: true });
						}
					}
				});
			};

			if ((args.path == '' || args.path == 'list') && self.photo_list.gallery) {
				// gallery
				if (args.params && args.params.index) {
					self.next_default_index = args.params.index;
				}
				return { mode: 'gallery' };
			} else if (args.path_list[0] == 'album' && (args.path_list.length == 2 || args.path_list.length == 5)) {
				// accept: /gallery/#album/:album_id
				// accept: /gallery/#album/:album_id/dialog/share/flickr
				// album open
				var album_id = args.path_list[1];
				permalink.lock_listener = true;
				var tmp_open_list = function(c, opts){
					permalink.lock_listener = false;
					var target = $('#album-' + album_id);
					if (target.attr('id')) {
						// open album
						mode_lock = true;
						if (args.params && args.params.index) {
							self.next_default_index = args.params.index;
						}
						target.click();
						if (args.path_list.length == 5 && args.path_list[4] == 'flickr') {
							permalink.addTrigger('album-photos-loaded', function(c, opts){
								var share_album_button = $('#share-album');
								if (share_album_button) {
									share_album_button.click();
								}
								var album_tab_flickr = $('#album-tab-flickr');
								if (album_tab_flickr) {
									album_tab_flickr.click();
								}
							});
						}
						c.mode_lock = false;
					} else {
						// アルバムが無かった
						self.permalink_manager.changeMode('top', {});
					}
				};

				if (self.photo_list.gallery) {
					// gallery の中では、最初に gallery が開くので、そのイベントと album-open のイベント両方通らないと開かない
					var event_count = 0;
					permalink.addTrigger('skip-list-open', function(c, opts){
						self.skip_open = false;
						event_count++;
						if (event_count == 2) {	
							tmp_open_list(c, opts);
						}
					});
					permalink.addTrigger('album-open', function(c, opts){
						event_count++;
						if (event_count == 2) {
							tmp_open_list(c, opts);
						}
					});
					self.skip_open = true;
				} else {
					// member page はそのまま開く
					permalink.addTrigger('album-open', tmp_open_list);
				}
				return { mode: 'album' };
			} else if (args.path_list[0] == 'album-photo' && args.path_list.length == 3) {
				// album open してから写真を開く
				var album_id = args.path_list[1];
				var photo_id = args.path_list[2];
				permalink.lock_listener = true;
				permalink.addTrigger('album-open', function(c, opts){
					permalink.lock_listener = false;
					var target = $('#album-' + album_id);
					if (target.attr('id')) {
						// album attribute が準備出来たら写真を開く
						permalink.addTrigger('album-photos-loaded', function(c, opts){
							open_photo(photo_id);
						});
						// open album	
						c.mode_lock = true;
						target.click();
						c.mode_lock = false;
					} else {
						// アルバムが無かった
						self.permalink_manager.changeMode('top', {});
					}

				});
				return { mode: 'album-photo' };
			} else if (args.path_list[0] == 'photo' && args.path_list.length == 2) {
				// gallery から開いた写真
				var photo_id = args.path_list[1];
				permalink.lock_listener = true;
				permalink.addTrigger('album-open', function(c, opts){
					permalink.lock_listener = false;
					open_photo(photo_id);
				});
				return { mode: 'photo' };
			}


			break;
		default:
			break;
		}
	},

	clear: function(){
		$("#left_viewer").empty();
	}
};

// ajax のエラー処理。画面遷移が発生してる時に error が出ないようにする
(function(){
	var is_unloading = false;
	var last_error_time = 0;
	$(window).unload(function(e){
		is_unloading = true;
	});
	$(document.body).bind('ajaxError', function(e,xhr,s){
		if (is_unloading) return;
		var now = new Date()*1;
		if (now - last_error_time < 10000) return;
		last_error_time = now;
		if (xhr.status == 503) {
			$('#maintenance_message').dialog_open();
		} else {
			setTimeout(function(){
				if (is_unloading) return;
				alert("サーバとの通信でエラーが発生しました。お手数ですが一度ログアウト後、再度ログインを行ってください。 [" + xhr.status + "]");
			}, 200);
		}
	});
})();

jQuery.extend({
	httpData: function( xhr, type, s ) {
		var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";
			
		// Allow a pre-filtering function to sanitize the response
		// s != null is checked to keep backwards compatibility
		if( s && s.dataFilter )
			data = s.dataFilter( data, type );

		// The filter can actually parse the response
		if( typeof data === "string" ){

			// If the type is "script", eval it in global context
			if ( type == "script" )
				jQuery.globalEval( data );

			// Get the JavaScript object, if JSON is used.
			if ( type == "json" ) {
				data = data.replace('while (1);', ''); // add
				data = window["eval"]("(" + data + ")");
			}
		}
		
		return data;
	}
});


// live event の登録
$(document).ready(function(){
	// サムネイル
	$('#photo-list > div.photo_thumbnail > img.photo_thumbnail_image').
		live('click', function(e){
			if (!photo_list) return;
			var target = $(this);
			photo_list.click_thumbnail_image(e, target.data('id'), target);
		}).
		live('dblclick', function(e){
			if (!photo_list) return;
			photo_list.dbclick_thumbnail_image(e, $(this).data('id'));
		});

	// サムネイルの選択をクリアする
	$('#photolist_viewer').live('click', function(e){
		if ($(e.target).is('#photo-list > div.photo_thumbnail > img.photo_thumbnail_image'))
			return;
		photo_list.unmark_showingphotos();
	});

	// 日付ラベルのクリック
	$('#photo-list > div.photo_thumbnail > div.photo-datelabel-clickable').
		live('click', function(e){
			if (!photo_list) return;
			var target = $(this);
			photo_list.click_thumbnail_datelabel(e, target);
		});
});

/* * * * */
function installCommentCheckboxMethods() {
	var target;
	$('#comment-button').click(function (e) {
		e.preventDefault();
		target = $('#comment-button');
		photo_list.is_comment_checked = !target.hasClass("checked");
		if (photo_list.is_comment_checked) {
			target.removeClass("unchecked").addClass("checked");
			$(".view_comment").show()
		} else {
			target.removeClass("checked").addClass("unchecked");
			$(".view_comment").hide();
		}
	}).click();
}
function installGoodCheckboxMethods() {
	var target;
	$('#good-button').click(function (e) {
		e.preventDefault();
		target = $('#good-button');
		photo_list.is_good_checked = !target.hasClass("checked");
		if (photo_list.is_good_checked) {
			target.removeClass("unchecked").addClass("checked");
			$(".view_good").show();
		} else {
			target.removeClass("checked").addClass("unchecked");
			$(".view_good").hide();
		}
	}).click();
}



$(document).ready(function () {
	// 画像貼付け HTML のサイズ変更 UI
	$("#photo_link-html-edit-start").click(function(e){
		e.preventDefault();
		var photo_link = $("#photo_link-html");
		var win = window.open(
			'/contents/tools/photo_html_maker.html',
			'photo_link_html_edit_window',
			'width=550,menubar=no,toolbar=no,location=no,scrollbars=yes,dependent=yes'
		);
	}).css({color:'#88f',cursor:'pointer'});
});


function generate_outer_photo_link_html(obj){
	var style = '';
	if (obj.width  && obj.width  != '0') style += 'width:'  + obj.width  + ';';
	if (obj.height && obj.height != '0') style += 'height:' + obj.height + ';';
	var src = obj.src;
	if (obj.width <= 240 && obj.height <= 240) {
		if (obj.width <= 90 && obj.height <= 90) {
			src = src.replace('/m/', '/s/');
		} else {
			src = src.replace('/m/', '/p/');
		}
	}
	return '<a href="' + obj.uri +'" target="_blank"><img src="' + src +'" title="' + obj.title + '" alt="' + obj.title + '" style="border:0;' + style +  '" /></a>';
}

// Local Variables:
// tab-width: 4
// indent-tabs-mode: t
// End:
