if (typeof(Ficia) == 'undefined') Ficia = {};
if (typeof(Ficia.Widget) == 'undefined') Ficia.Widget = {};

/*
 * 左にあるアルバムリストの管理
 */
Ficia.Widget.AlbumList = function(args){
	this.album = args.album;
	this.photo = args.photo;
	this.is_gallery = args.is_gallery;
	this.user_id = args.user_id;
	this.viewer_user_id = args.viewer_user_id;
	this.sorted = [];
	this.init();
};

(function(){
Ficia.Widget.AlbumList.prototype = {
	list: {},
	length: 0,

	init: function(){
	},

    current_list_id: function(type){
		if (!this.is_gallery) {
			// for member page
			if (type == "share") {
				return '#share_albums';
			} else if (type == "public") {
				return '#public_albums';
			}
		} else {
			// for gallery
			return '#left_viewer';
		}
	},

	// clear the album list DOM
	clear: function(){
		if (!this.is_gallery) {
			$('#share_albums').remove();
			$('#public_albums').remove();
		} else {
			$('#left_viewer').remove();
		}
		this.list = {};
		this.length--;
	},

	// add album
	add: function(id, attr, type){
		var self = this;
		var item = new Ficia.Widget.AlbumList.Item({
			photo: self.photo,
			id: id,
			attr: attr,
			type: type,
			album: self.album,
			user_id: self.user_id,
			viewer_user_id: self.viewer_user_id,
			is_gallery: self.is_gallery,
			sort_index: self.length,
			list: self
		});
		item.create();
		self.list[id] = item;
		self.sorted[self.length] = item;
		self.length++;

		// ficia/Facebook/flickr 等における、共有状態をあらわすアイコンを表示するバルーンの設定
		if (!self.photo.is_member_view) {
			item.add_icons();
		}

		// アルバムとアルバムの間のセパレータを追加
		if (this.is_gallery && this.length == 1) {
			var before = $('<div class="album_list_separator"></div>');
			$(self.current_list_id(type)).
				append(
					before.
						attr('id', 'album_list_separator-before')
				);
			before.droppable({
				tolerance: 'pointer',
				hoverClass: "dropped_separator-hover",
				accept: function(draggable){
					if (draggable.hasClass('thumbnail_album')) return true;
					return false;
				},
				drop: function(e, ui){ self.drop_separator(ui.draggable.attr('id').replace('album-', ''), 'before') }
			});
		}

		$(self.current_list_id(type)).append(item.dom);

		if (this.is_gallery) {
			var after  = $('<div class="album_list_separator"></div>');
			$(self.current_list_id(type)).
				append(
					after.
						attr('id', 'album_list_separator-'+id)
				);
			after.droppable({
				tolerance: 'pointer',
				hoverClass: "dropped_separator-hover",
				accept: function(draggable){
					if (draggable.hasClass('thumbnail_album')) return true;
					return false;
				},
				drop: function(e, ui){ self.drop_separator(ui.draggable.attr('id').replace('album-', ''), id) }
			});
		}
	},

	// drop event
	drop_photo: function(id, cb){
		if (this.list[id]) this.list[id].drop(cb);
	},

	open: function(id){
		if (!this.list[id]) return;
		this.list[id].open();
	},

	// remove album
	remove: function(id){
		if (!this.list[id]) return;
		this.list[id].dom.remove();
		this.remove_separator(id);
		this.sorted.splice(this.list[id].sort_index, 1);
		var sort_index = this.list[id].sort_index;
		delete this.list[id];
		this.length--;

		// 削除した要素以降の sort_index を付け直す
		for (var idx = sort_index; idx < this.length;idx++) {
			this.sorted[idx].sort_index = idx;
		}
	},

	get_attr: function(id){
		if (!this.list[id]) return;
		return this.list[id].attr;
	},

	// attribute を変更
	chage_attr: function(aattr){
		
	},

	change_title: function(id, title){
		if (!this.list[id]) return;
		return this.list[id].change_title(title);		
	},

	// アルバムとアルバムの間にドロップする為の要素 
	// 実質 index が変化してなければ何もしない 
	drop_separator: function(from_id, to_id){
		if (from_id == to_id) return;

		var obj = this.list[from_id];
		var from_idx = obj.sort_index;
		var to_idx;
		if (to_id == 'before') {
			to_idx = 0;
		} else {
			to_idx = this.list[to_id].sort_index + 1;
		}
		if (from_idx == to_idx || from_idx == to_idx -1) return; // 一つ上、もしくは一つ下

		// ajax 
		var self = this;
		$.ajax({
			url : "/album/" + this.user_id + "/" + from_id  + "/attribute/sort",
			type : "put",
			data: {
				from: from_idx,
				to:   (from_idx < to_idx) ? to_idx - 1 : to_idx
			},
			dataType: "json",
			cache: false,
			success : function(data){
				if (data.msg != 'ok') return;

				// index 並び替え
				if (from_idx < to_idx) {
					to_idx--;
					for (var idx = from_idx;idx < to_idx;idx++) {
						var f = idx + 1;
						self.sorted[idx] = self.sorted[f];
						self.sorted[idx].sort_index = idx;
					}
				} else {
					for (var idx = from_idx;idx > to_idx;idx--) {
						var f = idx - 1;
						self.sorted[idx] = self.sorted[f];
						self.sorted[idx].sort_index = idx;
					}
				}
				self.sorted[to_idx] = obj;
				obj.sort_index = to_idx;

				// dom 並び替え
				$('#album_list_separator-'+to_id).
					after($('#album_list_separator-'+from_id)).
					after($('#album-'+from_id));
			}
		});
	},
	remove_separator: function(id){
		$('#album_list_separator-'+id).remove();		
	},


	// 上から idx 番目に表示してる album の object を返す
	get_by_index: function(idx){
		return this.sorted[idx];
	},

	_: ''
};

Ficia.Widget.AlbumList.Item = function(args){
	this.id    = args.id;
	this.attr  = args.attr;
	this.type  = args.type;
	this.album = args.album;
	this.user_id = args.user_id;
	this.viewer_user_id = args.viewer_user_id;
	this.is_gallery = args.is_gallery;
	this.photo = args.photo;
	this.sort_index = args.sort_index;
	this.list = args.list;
	this.init();
};

Ficia.Widget.AlbumList.Item.prototype = {
	dom: null,

	init: function(){
	},

	create: function(){
		this.dom = $(document.createElement("div"));
		this.dom.addClass("thumbnail_album").
			addClass(self.type == 'share_user' ? 'sharelist_menu' : 'album_menu').
			attr("id", "album-" + this.id).
			text( this.attr.album_title );
		this.add_events();
	},

	// album の DOM にイベントを付ける
	add_events: function(){
		var self = this;
		var target = self.dom;
		// クリックしたらアルバムの写真を表示
		target.click(function (e) {
			e.preventDefault();
			self.open();
		});

		// member_url もしくは share_user のアルバム表示モードの時はこれ以降処理しない
		if (!self.is_gallery || self.type == 'share_user') return;

		// 写真をドロップされた時の対応
		target.droppable({
			self:self,
			tolerance: 'pointer',
			hoverClass: "dropped-hover",
			accept: function(draggable){
				if (draggable.hasClass('thumbnail_album')) {
					// album in album
					// return true;
				}
				if (target.hasClass("active")) return false;
				return draggable.hasClass("photo_thumbnail_image_selected") || draggable.hasClass("photo_thumbnail_image_selected_inslide");
			},
			drop: function(e, ui){
				if (ui.draggable.hasClass('thumbnail_album')) {
					// アルバム
				} else {
					// 写真
					self.drop();
				}
			}
		});

		// ドラッグする (アルバムの中に入れたり、アルバムとアルバムの間に入れたり)
		target.draggable({
			appendTo: '#left_viewer',
			axis: 'y',
			cursor: "move",
			opacity: 0.5,
			scroll: true,
			helper: function() {
				return target.clone().addClass('active');
			},
			stop: function(){
			}
			//helper: 'clone'
		});
	},

	add_icons: function(){
		var self = this;
		var attr = this.attr;
		var item = this.dom;
		if (!((attr.external_site != undefined && attr.external_site != 0) || (attr.access_level != undefined && attr.access_level > 1))) return;

		item.addClass('album_menu_share enablemenu').removeClass('album_menu');
		var msg = '';
		if (attr.access_level > 1) {
			msg += '<img src="/common/images/small_icons/icon_ficia.png" />';
		}
		if (attr.external_site & 1) {
			msg += '<img src="/common/images/small_icons/icon_facebook.png" />';
		}
		if (attr.external_site & 2) {
			msg += '<img src="/common/images/small_icons/icon_flickr.png" />';
		}
		balloon_install(item, msg, 'l', 30);
	},

	// album を開く
	open: function(){
		this.attr.photos = null;
		if (this.user_id == this.viewer_user_id) {
			$('#photo_menu_set_photo_list').show();
		} else {
			$('#photo_menu_set_photo_list').hide();
		}
		// AlbumList.open()
		this.album.open({ album: this.attr });
		// sort_type を設定
		$('#sort-by-shoot').removeClass('enablemenu').addClass('disablemenu');
		$('#sort-by-upload').removeClass('enablemenu').addClass('disablemenu');
		switch (this.attr.sort_type*1) {
			case 1:
			case 2: {
				$('#sort-by-upload').addClass('enablemenu').removeClass('disablemenu');
				break;
			}
			case 3:
			case 4: {
				$('#sort-by-shoot').addClass('enablemenu').removeClass('disablemenu');
				break;
			}
			default: {
				break;
			}
		}
	},

	// 写真がドロップされた
	drop: function(cb){
		var self = this;
		// lightbox on
		modal_message_open('アルバムを追加しています');

		var query = self.photo.generate_photo_select_query();
		$.ajax({
			url : "/album/" + self.user_id + "/" + self.id,
			type : "post",
			data: query,
			dataType: "json",
			cache: false,
			success : function(data){
				// lightbox off
				modal_message_close();
				modal_alert_open(data.add_count + '個アルバムに追加しました');
				if (data.msg == "ok") {
					//全部登録できた
					if (cb && typeof(cb) == 'function') cb(data);
				}
			}
		});
	},

	change_title: function(title){
		this.attr.album_title = title;
		this.dom.text(title);
	},

	_: ''
};

})();
