/**
 * 共通処理
 */
$.extend({
	/**
	 * カーソル設定
	 */
	cursor: function(value) {
		if (!value) {
			value = 'auto';
		}
		document.body.style.cursor = value;
	}
});

$.fn.extend({
	/**
	 * Ajaxリンク
	 */
	setAjaxLink: function(success, type, error) {
		this.show();
		this.click(function() {
			$.cursor('wait');
			
			// エラー処理
			if (!error) {
				error = function(xhr, status, err) {
					$.cursor();
					try {
						eval('json = ' + xhr.responseText);
						alert(json.msg);
					} catch (e) {
						alert('エラーが発生しました。');
					}
				}
			}
			
			// Ajax
			var options = {
				url: $(this).attr('href'),
				data: {
					'_token': $('#token').val()
				},
				type: 'POST',
				dataType: type,
				success: success,
				error: error
			}
			$.ajax(options);
			return false;
		});
	},
	
	/**
	 * JSONリンク
	 */
	setJsonLink: function(callback) {
		this.setAjaxLink(function(json) {
			$.cursor();
			if (json.msg) {
				alert(json.msg);
			}
			if (callback) {
				callback(json);
			}
		}, 'json');
	},
	
	/**
	 * 行更新リンク
	 */
	setRowLink: function(callback) {
		var row = this.closest('tr');
		var success = function(html) {
			$.cursor();
			row.html(html);
			row.find('.ajax_row').each(function() {
				$(this).setRowLink();
			});
			if (callback) {
				callback();
			}
		}
		this.setAjaxLink(success, 'html');
	}
});

/**
 * 初期化
 */
$(function() {
	// Good投票
	$('.ajax_good').each(function() {
		var link = $(this);
		var good = link.prev('.good');
		link.setJsonLink(function(json) {
			if (json.good && good) {
				good.html(json.good);
			}
		});
	});
	
	// 通報
	$('.ajax_warning').setJsonLink();
	
	// 行更新
	$('.ajax_row').each(function() {
		$(this).setRowLink();
	});
	
	// 変更時submit
	$('.change_submit').change(function() {
		$(this).closest('form').submit();
	});
});

