(function($) {
	var _options = {
		oneOpened: false,
		onlyOneOpened: false,
		firstOpened: false
	};
	var titleHandler = function() {
		var item = $(this).parents('.ddlist-item'), list = item.parents('.ddlist');
		var wasOpened = item.hasClass('ddlist-item-opened');
		var withEffects = !list.hasClass('without-effects');
		
		list.find('.ddlist-item-group').removeClass('ddlist-item-group-opened');

		if (list.hasClass('ddlist-onlyone') || wasOpened) {
			list.find('.ddlist-item-opened').removeClass('ddlist-item-opened').find('.ddlist-body').hide(withEffects ? 'fast' : null);
			if (wasOpened) {
				return;
			}
		}
		
		item.addClass('ddlist-item-opened').find('.ddlist-body').toggle(withEffects ? 'fast' : null);
		
		if (item.hasClass('ddlist-item-opened')) {
			item.parents('.ddlist-item-group').addClass('ddlist-item-group-opened');
		}
	};
	var titleHandler_oneOpened = function() {
		var item = $(this).parents('.ddlist-item'), list = item.parents('.ddlist');

		list.find('.ddlist-item-group').removeClass('ddlist-item-group-opened');

		if (list.hasClass('ddlist-onlyone')) {
			item.nextAll('.ddlist-item-opened').removeClass('ddlist-item-opened').find('.ddlist-body').hide('fast');
			item.prevAll('.ddlist-item-opened').removeClass('ddlist-item-opened').find('.ddlist-body').hide('fast');
		}
		if (item.hasClass('ddlist-item-opened') && list.find('.ddlist-item-opened').size() > 1) {
			item.removeClass('ddlist-item-opened').find('.ddlist-body').hide('fast');
		} else {
			item.parents('.ddlist-item-group').addClass('ddlist-item-group-opened');
			item.addClass('ddlist-item-opened').find('.ddlist-body').show('fast');
		}
		list.find('.ddlist-item').removeClass('ddlist-item-one');
		var opened = list.find('.ddlist-item-opened')
		if (opened.size() == 1) {
			opened.addClass('ddlist-item-one');
		}
	};
	$.ddlist = function(obj, options) {
		obj = $(obj).addClass('ddlist-inited');
		obj.find('.ddlist-title').click(options.oneOpened? titleHandler_oneOpened: titleHandler);
		obj.find('.ddlist-item').removeClass('ddlist-item-opened').find('.ddlist-body').hide('fast');
		if (options.firstOpened) {
			$(obj).find('.ddlist-item .ddlist-title:first').click();
		}
	};
	$.fn.ddlist = function(options) {
		options = $.extend(_options, options || {});
		this.each(function() {
			$.ddlist(this, options);
		});
	}
})(jQuery);

jQuery(document).ready(function() {
	jQuery('.ddlist.ddlist-first:not(.ddlist-one)').ddlist({firstOpened: true, oneOpened: false});
	jQuery('.ddlist.ddlist-one:not(.ddlist-first)').ddlist({firstOpened: true, oneOpened: true});
	jQuery('.ddlist:not(.ddlist-one):not(.ddlist-first)').ddlist({firstOpened: false, oneOpened: false});
});

