/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 */
$(function() {
	var
		periodsEl = $('#content .periods'),
		cloneEl = periodsEl.find('.period'),
		periodLinksEl = $('#content .period_links'),
		counter = 0,
		current = 0;

	cloneEl.find('.manage_period .field .pseudo').click(add);
	cloneEl.find('.manage_period .label .pseudo').click(remove);
	periodLinksEl.find('select').change(function() {
		change(periodLinksEl.find('select').val());
	});

	function change(value) {
		periodsEl.find('.period').addClass('hidden');
		periodsEl.find('.period').eq(value).removeClass('hidden');
		current = value;
	}

	function add() {
		counter++;
		periodsEl.find('.period').addClass('hidden');

		var
			periodEl = cloneEl.clone(),
			labelEl,
			fieldEl;

		labelEl = periodEl.find('.date_field label');
		labelEl.attr('for', labelEl.attr('for') + '_' + counter);
		fieldEl = periodEl.find('.date_field select').eq(0);
		fieldEl.attr('id', fieldEl.attr('id') + '_' + counter);

		labelEl = periodEl.find('.time_field label');
		labelEl.attr('for', labelEl.attr('for') + '_' + counter);
		fieldEl = periodEl.find('.time_field select').eq(0);
		fieldEl.attr('id', fieldEl.attr('id') + '_' + counter);

		labelEl = periodEl.find('.studio label');
		labelEl.attr('for', labelEl.attr('for') + '_' + counter);
		fieldEl = periodEl.find('.studio select').eq(0);
		fieldEl.attr('id', fieldEl.attr('id') + '_' + counter);

		periodEl.find('.manage_period .field .pseudo').click(add);
		periodEl.find('.manage_period .label .pseudo').click(remove);

		periodEl.removeClass('hidden').appendTo(periodsEl);
		current = periodsEl.find('.period').length - 1;

		var optionEl = $('<option></option');
		optionEl.appendTo(periodLinksEl.find('select'));

		updateState();
	}

	function remove() {
		periodsEl.find('.period').eq(current).remove();
		periodLinksEl.find('select option').eq(current).remove();

		var els = periodsEl.find('.period');

		if (current > els.length - 1) {
			current = els.length - 1;
		}

		els.eq(current).removeClass('hidden');
		change(current);

		updateState();
	}

	function updateState() {
		var periodsEls = periodsEl.find('.period');

		if (1 < periodsEls.length) {
			periodsEls.find('.manage_period .label').css('visibility', 'visible');
		} else {
			periodsEls.find('.manage_period .label').css('visibility', 'hidden');
		}

		var optionsEls = periodLinksEl.find('select option');

		optionsEls.each(function(index) {
			$(this).text(index + 1);
			$(this).attr('value', index);

			if (index == current) {
				periodLinksEl.find('select').val(index);
				$(this).attr('selected', 'selected');
			} else {
				$(this).removeAttr('selected');
			}
		});

		if (1 < optionsEls.length) {
			periodLinksEl.css('visibility', 'visible');
		} else {
			periodLinksEl.css('visibility', 'hidden');
		}
	}
});
