
$.blockUI.defaults.overlayCSS = { backgroundColor: '#000', opacity: '0.7' };

Pager = function (obj) {
	return (this instanceof arguments.callee) ? this.init(obj) : new Pager(obj);
};
Pager.prototype = {
	init : function (data) {
		this.data = {
			total  : +data.total,
			offset : +data.offset,
			limit  : +data.limit
		}
		this.total_pages  = Math.ceil( data.total  / data.limit);
		this.current_page = Math.floor(data.offset / data.limit) + 1;
	},

	format : function (parent, callback) {
		var current_page = this.current_page;
		var total_pages  = this.total_pages;
		if (total_pages > 1) {
			if (current_page > 1) {
				$("<li class='prev'><a href='#'>前へ</a></li>")
					.find('a').attr('href', callback(current_page - 1)).end().appendTo(parent);;
			}

			for (var i = 1; i <= total_pages; i++) {
				if (i == current_page) {
					$("<li class='prev'><strong>"+i+"</strong></li>").appendTo(parent);
				} else {
					$("<li class='prev'><a href='#'>前へ</a></li>")
						.find('a').attr('href', callback(i)).text(i).end().appendTo(parent);
				}
			}

			if (current_page < total_pages) {
				$("<li class='prev'><a href='#'>次へ</a></li>")
					.find('a').attr('href', callback(current_page + 1)).end().appendTo(parent);
			}
		}
		return this;
	}
};

CommentForm = function (obj) {
	return (this instanceof arguments.callee) ? this.init(obj) : new CommentForm(obj);
};
CommentForm.prototype = {
	init : function (obj) {
	},

	show : function () {
		CommentForm.current_form = this;
		var params = {};
		params[Comment.type_map[Comment.type]] = Comment.current_id;
		CommentForm.current_form.next(CommentForm.loading);
		$.get('/' + Comment.type + '/comment_form', params, this.next);
	},

	next : function (data) {
		var callee = arguments.callee;
		var boxes  = $('.displayBox');
		var whole  = $(data);
		ApplyRollover(whole.get(0));

		whole.css({
			position : 'absolute',
			width    : '700px',
			top      : '0',
			left     : '0'
		})
		.find('form')
			.css('display', 'inline')
			.submit(function () {
				var action = $(this).attr('action');
				var method = $(this).attr('method');
				var string = $(this).serialize();
				$(this).find('input, textarea, select').attr('disabled', 'disabled');
				CommentForm.current_form.next(CommentForm.loading);
				$.ajax({
					type    : method || "get",
					url     : action,
					data    : string,
					success : callee
				});
				return false;
			})
		.end()
		.append(
			$("<a href='javascript:void(0)' title='close'>閉じる</a>").css({
				position: "absolute",
				top: "20px",
				right: "10px"
			})
		)
		.find('a:has(img[src*="close"]), a[title="close"]')
			.click(function () {
				$.blockUI.impl.boxCallback = null;
				$.blockUI.impl.boxRemove();
				Comment.update();
				return false;
			})
		.end()
		.find("a")
			.each(function () {
				this.href = String(this.href).replace("backurl=", "backurl=" + encodeURIComponent(location.href));
			})
		.end()
		.appendTo('#container').displayBox({}, function () {
			return confirm('閉じてもよろしいですか?');
		});

		var area = $("textarea[name='comment']");
		if (area) {
			var header = whole.find("h3");
			var len = 300;
			var title = header.text();

			var id, rest;
			area.
				focus(function () {
					id = setInterval(function () {
						nrest = len - area.val().length;
						if (nrest != rest) {
							rest = nrest;
							whole.find("div.caution").remove();
							if (rest < 0) {
								header.text( title );
								header.after('<div class="caution">300文字以内で入力してください</div>');
							} else {
								header.text( title + " （残り:" + rest + "文字）" );
							}
						}
					}, 500);
				}).
				blur(function () {
					clearInterval(id);
				});
		}

		boxes.remove();
	}
};

CommentForm.loading = [
	'<div id="float">',
		//'<div id="floatTop"><img src="/img/float/box_float_01_t.png" border="0" width="700" height="5" alt="" /></div>',
		'',
		'<div id="floatMain">',
		'<div id="floatLoding"><img src="/img/float/ajax-loader.gif" border="0" width="32" height="32" alt="Loading" /></div>',
		'</div>',
		'',
		//'<div id="floatBottom"><img src="/img/float/box_float_01_b.png" border="0" width="700" height="5" alt="" /></div>',
	'</div>',
].join('');

Comment = function (obj) {
	return (this instanceof arguments.callee) ? this.init(obj) : new Comment(obj);
};
Comment.prototype = {
	init : function (obj) {
		this.obj = obj;
	},

	format : function () {
		var obj = this.obj;
		var ret = $(Comment.template);

		ret.find("div.photo img").attr({
			src: obj.file_url,
			alt: obj.comment_text || ''
		});

		if (obj.profile_url) {
			ret.find("div.name a").attr('href', obj.profile_url).empty().append(obj.nickname);
		} else {
			ret.find("div.name").empty().append(obj.nickname);
		}

		var type = "";

		if (obj.member_id) {
			ret.find("div.type img").attr({
				src: '/img/event/ico_career_' + String(+obj.run_history + 100).slice(1) + '.gif',
				alt: type.toUpperCase()
			});
		} else {
			ret.find("div.type img").remove();
		}

		var star_container = ret.find('div.star');
		var star     = star_container.find('img:first').clone();
		var star_btn = star_container.find('a').clone();

		(function mkstar () {
			var cls = (obj.star > 10) ? 'runner' :
			          (obj.star >  5) ? 'athlete' :
			          'jogger';

			star_container.empty();

			for (var i = 0; i < obj.star; i++) {
				star_container.append(star.clone().attr('src', "/img/event/ico_star_"+cls+".gif"));
			}
			star_container.append('('+obj.star+')');

			ret.find('div.boxCommentL img').attr({
				src: '/img/event/box_cmt_l_'+cls+'.gif',
				alt: type.toUpperCase()
			});

			var comment = obj.comment.replace(/[<>&"]/g, function (m) {
				return ({ "<":"&lt;", ">":"&gt", "&":"&amp;", '"':"&quot;"})[m];
			}).replace(/\n/g, '<br/>');

			ret.find('div.boxComment')
				.find('> div:nth-child(1) img').attr({
					src: '/img/event/box_cmt_t_'+cls+'.gif',
					alt: ''
				}).end()
				.find('> div:nth-child(2)').attr('class', cls)
					.find('div:first').empty().append(comment).end()
					.find('div.date').text(obj.commented_at).end()
				.end()
				.find('> div:nth-child(3) img').attr({
					src: '/img/event/box_cmt_b_'+cls+'.gif',
					alt: ''
				}).end();


			star_container.append(star_btn.clone().click(function () {
				if (isLoggedIn()) {
					var cookie_name = ['c',Comment.current_id, 's',  obj.comment_id].join("");
					if (CookieManager.ok(cookie_name)) {
						CookieManager.add(cookie_name);
						$.getJSON('/api/' + Comment.type + '/star', { comment_id: obj.comment_id }, function (json) {
							CookieManager.add(cookie_name);
							if (json.star) {
								obj.star++;
								mkstar();
							}
						});
					}
				} else {
					showLoginBox();
				}

				return false;
			}));
		})();

		ApplyRollover(ret.get(0));

		return ret;
	}
};
Comment.template = [
	'<li>',
		'<div class="wrapper">',
			'<div class="commentLeft">',
				'<div class="photo" id="square"><img border="0" alt="" src=""/></div>',
				'<div class="name"><a href="#"></a></div>',
				'<div class="type"><img width="54" height="20" border="0" alt="" src=""/></div>',
			'</div>',
			'<div class="commentRight wrapper">',
				'<div class="boxCommentL"><img width="8" height="11" border="0" alt="" src="/img/event/box_cmt_l_runner.gif"/></div>',
				'<div class="boxComment">',
					'<div><img width="598" height="5" border="0" alt="" src="/img/event/box_cmt_t_runner.gif"/></div>',
					'<div class="runner">',
						'<div>text</div>',
						'<div class="wrapper">',
							'<div class="date">2008.01.01 00:00</div>',
							'<div class="star"><img width="13" height="13" border="0" alt="スター" src="/img/event/ico_star_runner.gif"/>',
							'(3)',
							'<a href="#"><img width="145" height="17" border="0" alt="このコメントを評価する" src="/img/event/btn_staradd.gif" class="btn"/></a>',
							'</div>',
						'</div>',
					'</div>',
					'<div><img width="598" height="5" border="0" alt="" src="/img/event/box_cmt_b_runner.gif"/></div>',
				'</div>',
			'</div>',
		'</div>',
	'</li>'
].join('');


Comment.limit      = 20;
Comment.current_id = null;
Comment.type_map = {
	"voice"    : "topic_id",
	"event"    : "event_id",
	"magazine" : "magazine_id",
	"guide"    : "guide_column_id",
	"life"     : "life_column_id"
};

Comment.update = function (page) {
	if (!page) page = Comment.pager.current_page;
	page -= 1;
	var params = {
		offset   : Comment.limit * page,
		limit    : Comment.limit
	};
	params[Comment.type_map[Comment.type]] = Comment.current_id;

	$.get(
		'/api/' + Comment.type + '/comment',
		params,
		function (data) { try {
			data = eval('('+data+')');
			Comment.update_comments(data.data || []);
			Comment.update_pager(data.pager);
			log(data);
			$('div.selectLimit').css("visibility", data.data && data.data.length ? "visible" : "hidden");
		} catch (e) { log(e) } }
	);
};

Comment.update_comments = function (data) {
	var parent = $('ul.commentList').empty();
	$.each(data, function () {
		Comment(this).format().appendTo(parent);
	});
};

Comment.update_pager  = function (data) {
	var parent = $('#pane2Left ul.pages').empty();

	Comment.pager = Pager(data).format(parent, function (num) {
		return 'javascript:Comment.update('+num+');$.scrollTo("#commentList")';
	});
};

Comment.init = function (opts) {
	Comment.current_id = opts.id || 1;
	Comment.type       = opts.type;
	Comment.update(opts.page || 1);
	Comment.form       = new CommentForm(Comment);

	$('div.btnComment a').click(function () {
		Comment.form.show();
		return false;
	});

	$('#selLimit').change(function () {
		Comment.limit = Number($(this).val());
		Comment.update(1);
		$.scrollTo("#commentList")
	});
};


$(function () {
	var path = location.pathname.split('/');
	if (path[2] == 'detail') {
		Comment.init({
			type : path[1],
			id   : path[3],
			page : 1
		});
	}
	
// update on Feb. 22, 2010
	GoalForm = function (obj) {
		return (this instanceof arguments.callee) ? this.init(obj) : new GoalForm(obj);
	};
	GoalForm.prototype = {
		init : function (obj) {
		},

		show : function () {
			GoalForm.current_form = this;
			var params = {};
			params[Goal.type_map[Goal.type]] = Goal.current_id;
			GoalForm.current_form.next(GoalForm.loading);
			$.get('/' + Goal.type + '/goal_form', params, this.next);
		},

		next : function (data) {
			var callee = arguments.callee;
			var boxes  = $('.displayBox');
			var whole  = $(data);
			ApplyRollover(whole.get(0));

			whole.css({
				position : 'absolute',
				width    : '700px',
				top      : '0',
				left     : '0'
			})
			.find('form')
				.css('display', 'inline')
				.submit(function () {
					var action = $(this).attr('action');
					var method = $(this).attr('method');
					var string = $(this).serialize();
					$(this).find('input, textarea, select').attr('disabled', 'disabled');
					GoalForm.current_form.next(GoalForm.loading);
					$.ajax({
						type    : method || "get",
						url     : action,
						data    : string,
						success : callee
					});
					return false;
				})
			.end()
			.append(
				$("<a href='javascript:void(0)' title='close'>閉じる</a>").css({
					position: "absolute",
					top: "20px",
					right: "10px"
				})
			)
			.find('a:has(img[src*="close"]), a[title="close"]')
				.click(function () {
					$.blockUI.impl.boxCallback = null;
					$.blockUI.impl.boxRemove();
					Goal.update();
					return false;
				})
			.end()
			.find("a")
				.each(function () {
					this.href = String(this.href).replace("backurl=", "backurl=" + encodeURIComponent(location.href));
				})
			.end()
			.appendTo('#container').displayBox({}, function () {
				return confirm('閉じてもよろしいですか?');
			});

			var area = $("textarea[name='comment']");
			if (area) {
				var header = whole.find("h3");
				var len = 300;
				var title = header.text();

				var id, rest;
				area.
					focus(function () {
						id = setInterval(function () {
							nrest = len - area.val().length;
							if (nrest != rest) {
								rest = nrest;
								whole.find("div.caution").remove();
								if (rest < 0) {
									header.text( title );
									header.after('<div class="caution">300文字以内で入力してください</div>');
								} else {
									header.text( title + " （残り:" + rest + "文字）" );
								}
							}
						}, 500);
					}).
					blur(function () {
						clearInterval(id);
					});
			}

			boxes.remove();
		}
	};

	GoalForm.loading = [
		'<div id="float">',
			//'<div id="floatTop"><img src="/img/float/box_float_01_t.png" border="0" width="700" height="5" alt="" /></div>',
			'',
			'<div id="floatMain">',
			'<div id="floatLoding"><img src="/img/float/ajax-loader.gif" border="0" width="32" height="32" alt="Loading" /></div>',
			'</div>',
			'',
			//'<div id="floatBottom"><img src="/img/float/box_float_01_b.png" border="0" width="700" height="5" alt="" /></div>',
		'</div>',
	].join('');

	Goal = function (obj) {
		return (this instanceof arguments.callee) ? this.init(obj) : new Goal(obj);
	};
	Goal.prototype = {
		init : function (obj) {
			this.obj = obj;
		},

		format : function () {
			var obj = this.obj;
			var ret = $(Goal.template);

			ret.find("div.photo img").attr({
				src: obj.file_url,
				alt: obj.comment_text || ''
			});

			if (obj.profile_url) {
				ret.find("div.name a").attr('href', obj.profile_url).empty().append(obj.nickname);
			} else {
				ret.find("div.name").empty().append(obj.nickname);
			}

			var type = "";

			if (obj.member_id) {
				ret.find("div.type img").attr({
					src: '/img/event/ico_career_' + String(+obj.run_history + 100).slice(1) + '.gif',
					alt: type.toUpperCase()
				});
			} else {
				ret.find("div.type img").remove();
			}

			var star_container = ret.find('div.star');
			var star     = star_container.find('img:first').clone();
			var star_btn = star_container.find('a').clone();

			(function mkstar () {
				var cls = (obj.star > 10) ? 'runner' :
				          (obj.star >  5) ? 'athlete' :
				          'jogger';

				star_container.empty();

				for (var i = 0; i < obj.star; i++) {
					star_container.append(star.clone().attr('src', "/img/event/ico_star_"+cls+".gif"));
				}
				star_container.append('('+obj.star+')');

				ret.find('div.boxCommentL img').attr({
					src: '/img/event/box_cmt_l_'+cls+'.gif',
					alt: type.toUpperCase()
				});

				var comment = obj.comment.replace(/[<>&"]/g, function (m) {
					return ({ "<":"&lt;", ">":"&gt", "&":"&amp;", '"':"&quot;"})[m];
				}).replace(/\n/g, '<br/>');

				ret.find('div.boxComment')
					.find('> div:nth-child(1) img').attr({
						src: '/img/event/box_cmt_t_'+cls+'.gif',
						alt: ''
					}).end()
					.find('> div:nth-child(2)').attr('class', cls)
						.find('div:first').empty().append(comment).end()
						.find('div.date').text(obj.commented_at).end()
					.end()
					.find('> div:nth-child(3) img').attr({
						src: '/img/event/box_cmt_b_'+cls+'.gif',
						alt: ''
					}).end();


				star_container.append(star_btn.clone().click(function () {
					if (isLoggedIn()) {
						var cookie_name = ['c',Goal.current_id, 's',  obj.comment_id].join("");
						if (CookieManager.ok(cookie_name)) {
							CookieManager.add(cookie_name);
							$.getJSON('/api/' + Goal.type + '/star', { comment_id: obj.comment_id }, function (json) {
								CookieManager.add(cookie_name);
								if (json.star) {
									obj.star++;
									mkstar();
								}
							});
						}
					} else {
						showLoginBox();
					}

					return false;
				}));
			})();

			ApplyRollover(ret.get(0));

			return ret;
		}
	};
	Goal.template = [
		'<li>',
			'<div class="wrapper">',
				'<div class="commentLeft">',
					'<div class="photo" id="square"><img border="0" alt="" src=""/></div>',
					'<div class="name"><a href="#"></a></div>',
					'<div class="type"><img width="54" height="20" border="0" alt="" src=""/></div>',
				'</div>',
				'<div class="commentRight wrapper">',
					'<div class="boxCommentL"><img width="8" height="11" border="0" alt="" src="/img/event/box_cmt_l_runner.gif"/></div>',
					'<div class="boxComment">',
						'<div><img width="598" height="5" border="0" alt="" src="/img/event/box_cmt_t_runner.gif"/></div>',
						'<div class="runner">',
							'<div>text</div>',
							'<div class="wrapper">',
								'<div class="date">2008.01.01 00:00</div>',
								'<div class="star"><img width="13" height="13" border="0" alt="スター" src="/img/event/ico_star_runner.gif"/>',
								'(3)',
								'<a href="#"><img width="145" height="17" border="0" alt="このコメントを評価する" src="/img/event/btn_staradd.gif" class="btn"/></a>',
								'</div>',
							'</div>',
						'</div>',
						'<div><img width="598" height="5" border="0" alt="" src="/img/event/box_cmt_b_runner.gif"/></div>',
					'</div>',
				'</div>',
			'</div>',
		'</li>'
	].join('');


	Goal.limit      = 20;
	Goal.current_id = null;
	Goal.type_map = {
		"voice"    : "topic_id",
		"event"    : "event_id",
		"magazine" : "magazine_id",
		"guide"    : "guide_column_id",
		"life"     : "life_column_id"
	};

	Goal.update = function (page) {
		if (!page) page = Goal.pager.current_page;
		page -= 1;
		var params = {
			offset   : Goal.limit * page,
			limit    : Goal.limit
		};
		params[Goal.type_map[Goal.type]] = Goal.current_id;

		$.get(
			'/api/' + Goal.type + '/comment',
			params,
			function (data) { try {
				data = eval('('+data+')');
				Goal.update_comments(data.data || []);
				Goal.update_pager(data.pager);
				log(data);
				$('div.selectLimit').css("visibility", data.data && data.data.length ? "visible" : "hidden");
			} catch (e) { log(e) } }
		);
	};

	Goal.update_comments = function (data) {
		var parent = $('ul.commentList').empty();
		$.each(data, function () {
			Goal(this).format().appendTo(parent);
		});
	};

	Goal.update_pager  = function (data) {
		var parent = $('#pane2Left ul.pages').empty();

		Goal.pager = Pager(data).format(parent, function (num) {
			return 'javascript:Goal.update('+num+');$.scrollTo("#commentList")';
		});
	};

	Goal.init = function (opts) {
		Goal.current_id = opts.id || 1;
		Goal.type       = opts.type;
		Goal.update(opts.page || 1);
		Goal.form       = new GoalForm(Goal);

		$('p.goalbtn a').click(function () {
			Goal.form.show();
			return false;
		});

		//$('#selLimit').change(function () {
		//	Goal.limit = Number($(this).val());
		//	Goal.update(1);
		//	$.scrollTo("#commentList")
		//});
	};

//	$(function () {
//		Comment.init({
//			type : "life",
//			id   : <?php echo ... ?>,
//			page : 1
//		});
//	});
});

