(function ($) {
/**
 * @fileoverview トップ ブライダルフェアの日程表示数制御
 */

$(function () {
	$('.dateList').fairOnTop({
		amount: 6
	});
});

$.fairOnTop = function (element, options) {
	this.options = $.extend({}, this.options, options);
	this.$element = $(element);
	this._init();
}
$.fairOnTop.prototype = {
	options: {
		amount: 6,
		localToday: '',
		includeToday: true,
		nextClassName: ''
	},

	_init: function () {
		var self = this;

		var localToday = new Date();
		localToday.setHours(0);
		localToday.setMinutes(0);
		localToday.setSeconds(0);
		localToday.setMilliseconds(0);
		this.options.localToday = localToday;

		if (this.$element.hasClass('excToday')) {
			this.options.includeToday = false;
		}

		this.$element.find('dt').each(function (i) {
			try {
				var $el = $(this);
				var className = self._getClassAttrDate($el.attr('class'));
				self.options.nextClassName = self._getClassAttrDate(self.$element.find('dt').eq(i + 1).attr('class'));

				if (!className) {
					self._hide($el);
					return true;
				}

				var year = parseInt(className.slice(0, 4), 10);
				var month = parseInt(className.slice(4, 6), 10);
				var day = parseInt(className.slice(6, 8), 10);

				if (!self._checkDate(year, month, day)) {
					self._hide($el);
				} else if (self._isOld(year, month, day)) {
					self._hide($el);
				} else if (!self._hasNext()) {
					self._hide($el);
				} else if (!self._isGroup(className)) {
					self.options.amount--;
				} else {
					return true
				}

			} catch (e) {
			};
		});
	},

	_getClassAttrDate: function (className) {
		if (!className) {
			return false;
		}
		var matchDate = className.match('[0-9]{4}(?:0[0-9]|1[0-2])(?:[0-2][0-9]|3[0-1])');
		return matchDate? matchDate[0]? matchDate[0]: false: false;
	},

	_hide: function (element) {
		element.add(element.next('dd')).hide();
	},

	_isOld: function (year, month, day) {
		var localToday = this.options.localToday;
		var topicDate = new Date(year, month - 1, day);
		topicDate.setFullYear(year);
		topicDate.setMonth(month - 1);
		topicDate.setDate(day);

		if (this.options.includeToday) {
			if (localToday.getTime() <= topicDate.getTime()) {
				return false;
			}
		} else {
			if (localToday.getTime() < topicDate.getTime()) {
				return false;
			}
		}
		return true;
	},

	_hasNext: function () {
		if (this.options.amount) {
			return true;
		}
		return false;
	},

	_isGroup: function (className) {
		if (this.options.nextClassName === className) {
			return true;
		}
		return false;
	},

	_checkDate: function (year, month, day) {
		var d = new Date(year, month - 1, day);
		if (!d) {
			return false;
		} else if (d.getFullYear() !== year) {
			return false;
		} else if (d.getMonth() + 1 !== month) {
			return false;
		} else if (d.getDate() !== day) {
			return false;
		}
		return true;
	}
};
$.fn.fairOnTop = function (options) {
	return this.each(function () {
		new $.fairOnTop(this, options);
	});
};
})(jQuery);

