/**
 * 受信トレイ
 */
(function($) {
	$.fn.wsTray = function(config) {
		config = jQuery.extend({
			api: '/api/',
			projects: {},
			labels: {},
			selected: {
				project: 'all',
				label: 'tray'
			}
		}, config);

		var c = {
			message: $('<span class="message"></span>'),
			emptyTray: '<div class="tray-body-empty">からっぽ！</div>',
			defaultProjects: [{
				id: 'all',
				name: 'すべてのプロジェクト'
			}],
			defaultLabels: [{
				id: 'tray',
				label: '受信トレイ',
				color: '#006600',
				backgroundColor: '#eeffee'
			}, {
				id: 'all',
				label: 'すべてのチケット',
				color: 'inherit',
				backgroundColor: 'inherit'
			}, {
				id: 'nolabel',
				label: 'ラベルのないチケット',
				color: 'inherit',
				backgroundColor: 'inherit'
			}],
		};

		var f = {
			setProjectId: function(id, item) {
				config.selected.project = id;
				item.parents('.tray-items').children('.tray-item').removeClass('tray-item-selected');
				item.addClass('tray-item-selected');
			},
			setLabelId: function(id, item) {
				config.selected.label = id;
				item.parents('.tray-items').children('.tray-item').removeClass('tray-item-selected');
				item.addClass('tray-item-selected');
			},
			success: function(data, body) {
				if (data && data.length > 0) {
					body.html(f.toHtml(data));
				} else {
					body.html(f.emptyTray);
				}
				body.find('.shrink').wsShrink();
				body.find('.overflow-hidden').each(function() {
					var html = $(this).html();
					$(this).attr('title', $(this).text()).html('&nbsp;');
					var height = $(this).height();
					$(this).css({ display: 'block', height: height + 'px', overflow: 'hidden' }).html(html);
				});
				body.find('.unread').each(function() {
					if ($(this).val() == '1') {
						$(this).parents('.tray-list-tr').addClass('tray-list-tr-unread');
					}
				});
				body.find('a').click(function(e) {
					e.stopPropagation();
				});
				body.parents('.tray-main').wsCheckbox({
					all: 'checkbox-all',
					chk: 'checkbox',
					row: 'tray-list-tr',
					rowSelected: 'tray-list-tr-selected'
				});
			},
			reload: function(body) {
				f.getData(f.success, body, config.selected.project, config.selected.label)
			},
			doAction: function(body, action) {
				f.setMessage('');
				var ids = [];
				body.find('input.checkbox:checked').each(function() {
					ids.push($(this).attr('action'));
				});
				if (ids.length > 0) {
					if (action == 'archive') {
						f.doArchive(f.success, body);
					}
					f.reload(body);
				} else {
					f.setMessage("チケットを選択して下さい。");
				}
			},
			getData: function(callback, target, project, label) {
				$.ajax({
					url: config.api + 'ticket',
					type: 'POST',
					data: {
						projectId: project,
						labelId: label
					},
					dataType: 'json',
					cache: false,
					success: function(json, dataType) {
						callback(json, target);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert(textStatus);
					}
				});
			},
			doArchive: function(callback, target) {
				$.ajax({
					url: config.api + 'archive',
					type: 'POST',
					data: data,
					dataType: 'json',
					cache: false,
					success: function(json, dataType) {
						callback(json, target);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert(textStatus);
					}
				});
			},
			toHtml: function(data) {
				var html = $('<div></div>');
				var table = $('<table></table>');
				table.addClass('tray-list-table');
				var tbody = $('<tbody></tbody>');
				for (var i = 0; i < data.length; i++) {

					// テンプレート
					var r = $(
						'<tr class="tray-list-tr">' +
							'<td class="tray-list-td tray-list-td-checkbox">' +
								'<input type="checkbox" class="checkbox" />' +
								'<input type="hidden" class="unread" />' +
							'</td>' +
							'<td class="tray-list-td tray-list-td-assigned assigned"></td>' +
							'<td class="tray-list-td tray-list-td-subject subject">' +
								'<span class="labels"></span>' +
								'<span class="id"></span>' +
								'<span class="status"></span>' +
								'<span class="title"></span>' +
								'<span class="description"></span>' +
							'</td>' +
							'<td class="tray-list-td tray-list-td-datetime datetime"></td>' +
						'</tr>'
					);

					// データ
					r.find('.checkbox').attr('action', data[i].id);
					r.find('.unread').val(data[i].isUnread?"1":"0");
					if (data[i].assigned) {
						r.find('.assigned').text(data[i].assigned.name);
						r.find('.assigned').wrapInner('<div class="shrink"></div>');
					}
					if (data[i].labels) {
						for (var ii = 0; ii < data[i].labels.length; ii++) {
							var label = $('<span class="label"></span>');
							label.text(data[i].labels[ii].label);
							label.css({
								color: data[i].labels[ii].color,
								backgroundColor: data[i].labels[ii].backgroundColor
							});
							r.find('.labels').append(label);
						}
					}
					r.find('.id').text('[' + data[i].project.code + '#' + data[i].id + ']');
					r.find('.status').text('(' + data[i].status.label + ')');
					r.find('.title').text(data[i].title);
					r.find('.description').text(data[i].description);
					r.find('.subject').wrapInner('<a href="' + data[i].url + '"></a>')
					r.find('.subject').wrapInner('<div class="overflow-hidden"></div>');
					r.find('.datetime').attr('title', f.formatDatetimeFull(data[i].modifyDatetime)).text(f.formatDatetime(data[i].modifyDatetime));

					tbody.append(r);
				}
				table.append(tbody);
				html.append(table);
				return html.html();
			},
			formatDatetimeFull: function(date) {
				var target = new Date();
				target.setTime(date);
				return new DateFormat('yyyy/MM/dd HH:mm:ss').format(target);
			},
			formatDatetime: function(date) {
				var now = new Date();
				var target = new Date();
				target.setTime(date);
				var diff = now - target;
				if (diff < 86400000 && diff > -86400000) {
					return new DateFormat('H:mm').format(target);
				}
				if (now.getYear() != target.getYear()) {
					return new DateFormat('yyyy年').format(target);
				}
				return new DateFormat('M月d日').format(target);
			},
			setMessage: function(message) {
				f.message.text(message);
			}
		};

		$(this).each(function() {

			// メイントレイ
			var main = $('<div></div>');
			main.addClass('tray-main');
			var handler = $('<div></div>');
			handler.addClass('tray-handler');
			var body = $('<div></div>');
			body.addClass('tray-body');
			body.html(f.emptyTray);

			handler.html(
				'<input type="checkbox" class="checkbox-all" />' +
				'<input type="button" class="do-archive" value="アーカイブ" />' +
				'<input type="button" class="do-tray" value="受信トレイへ移動" />' +
				'<input type="button" class="do-read" value="既読にする" />' +
				'<input type="button" class="do-unread" value="未読にする" />'
			);
			handler.find('.do-archive').click(function(e) {
				e.stopPropagation();
				f.doAction(body, 'archive');
			});
			main.append(handler);
			main.append(body);
			main.append(handler.clone());
			handler.append(f.message);

			// メニュー
			var menu = $('<div></div>');
			menu.addClass('tray-menu');

			// プロジェクト
			var pItems = $('<ul></ul>');
			pItems.addClass('tray-items');
			var projects = $.merge(f.defaultProjects, config.projects);
			for (var i = 0; i < projects.length; i++) {
				var item = $('<li></li>');
				item.addClass('tray-item');
				item.text(projects[i].name);
				item.attr('action', projects[i].id);
				item.wrapInner('<div class="shrink"></div>');
				item.mouseover(function() {
					$(this).addClass('tray-item-active');
				}).mouseout(function() {
					$(this).removeClass('tray-item-active');
				}).click(function(e) {
					e.stopPropagation();
					f.setProjectId($(this).attr('action'), $(this));
					f.reload(body);
				});
				pItems.append(item);
			}
			f.setProjectId(config.selected.project, pItems.find('.tray-item[action="' + config.selected.project + '"]'));
			menu.append(pItems);

			// ラベル
			var lItems = $('<ul></ul>');
			lItems.addClass('tray-items');
			var labels = $.merge(f.defaultLabels, config.labels);
			for (var i = 0; i < labels.length; i++) {
				var item = $('<li></li>');
				item.addClass('tray-item');
				item.text(labels[i].label);
				item.attr('action', labels[i].id);
				item.wrapInner('<div class="shrink"></div>');
				item.mouseover(function() {
					$(this).addClass('tray-item-active');
				}).mouseout(function() {
					$(this).removeClass('tray-item-active');
				}).click(function(e) {
					e.stopPropagation();
					f.setLabelId($(this).attr('action'), $(this));
					f.reload(body);
				});
				lItems.append(item);
			}
			f.setLabelId(config.selected.label, lItems.find('.tray-item[action="' + config.selected.label + '"]'));
			menu.append(lItems);

			$(this).append(menu);
			$(this).append(main);
			$(this).find('.shrink').wsShrink();

			f.reload(body);
		});

	}
})(jQuery);
