// класс компонент для работы с "расписанием работы"
var scheduledWork = function(cont, options) {

	var that = this;

	that.cont = $(cont);
	that.contId = '#' + that.cont.attr('id');
	that.contPrefix = that.contId.replace(new RegExp( '__sheduleConteiner', 'gi' ), '');


	// выводит список выбранных дней во всплывающий слой.
	var displaySelectScheduled = function() {

		initSelectScheduleFormValue();

		$(options.scheduleBlock + ' input[type=button]').bind('click', function(e){
																	setScheduleTime();

																	$(options.scheduleBlock + ' input[type=button]').unbind('click');

																	$(options.scheduleBlock).hide();
																});

		$(options.scheduleBlock).css( 'left',  $( that.cont ).offset().left - 15).css( 'top', $( that.cont ).offset().top - 13);

		$(options.scheduleBlock).show();
	}

	// инициализирует выбранные дни в окне выбора графика работы
	var initSelectScheduleFormValue = function() {

		$(options.scheduleBlock + ' span.days').empty(); // очищаем старый список дней

		var weekDays = [];

		if ($(that.contId + ' input[type=checkbox]:checked').length == 0) {
			$(that.contId + ' input[type=checkbox]').attr('checked', true);
		}

		$(that.contId + ' input[type=checkbox]:checked').each( // просматриваем все выбранные дни недели
			function(i, val) {
				weekDays.push($(that.contId + ' label[for="' + $(this).attr('id') + '"]').text());
			}
		)

		$(options.scheduleBlock + ' span.days').text(weekDays.join(', '));

		if ($(that.contId + ' input[type=checkbox]:checked').length == 1) {
			fillFields($(that.contId + ' input[type=checkbox]:checked').val());
		} else {
			fillFields(false);
		}
	}

	// заполняет поля формы
	var fillFields = function(element) {

		if (element !== false && options.data[element]) {

			var timeStart = options.data[element]['timeStart'];
			var timeFinish = options.data[element]['timeFinish'];
			var lunchStart = options.data[element]['lunchStart'];
			var lunchFinish = options.data[element]['lunchFinish'];

			var setTimeStart = '';
			var setTimeFinish = '';

			var setLunchStart = '';
			var setLunchFinish = '';

			var setDayOf = true;
			var setWithoutLunch = true;

			if (timeStart.length > 3 && timeFinish.length > 3) {

				setTimeStart = timeStart;
				setTimeFinish = timeFinish;
				setDayOf = false;

				if (lunchStart.length > 3 && lunchFinish.length > 3) {
					setLunchStart = lunchStart;
					setLunchFinish = lunchFinish;
					setWithoutLunch = false;
				} else if (lunchStart == '' && lunchFinish == '') {
					setWithoutLunch = false;
				}


			} else if (timeStart == '' && timeStart == '') {

				setDayOf = false;
				setWithoutLunch = false;
			}

			///alert('INIT:' + timeStart + '---' + timeFinish + '---' + lunchStart + '---' + lunchFinish + "\n\n" + setTimeStart + '---' + setTimeFinish + '---' + setLunchStart + '---' + setLunchFinish);

			$(options.timeStart).val(setTimeStart);
			$(options.timeFinish).val(setTimeFinish);
			$(options.lunchStart).val(setLunchStart);
			$(options.lunchFinish).val(setLunchFinish);

			if (setDayOf === true) {
				setWithoutLunch = false;
			}

			$(options.dayOff).attr('checked', setDayOf);
			$(options.withoutLunch).attr('checked', setWithoutLunch);

			if (setDayOf === true) {

				$(options.timeStart).attr('disabled', 'disabled');
				$(options.timeFinish).attr('disabled', 'disabled');
				$(options.lunchStart).attr('disabled', 'disabled');
				$(options.lunchFinish).attr('disabled', 'disabled');

				$(options.withoutLunch).attr('disabled', 'disabled');

			} else {

				$(options.timeStart).removeAttr('disabled');
				$(options.timeFinish).removeAttr('disabled');
				$(options.withoutLunch).removeAttr('disabled');

				if (setWithoutLunch === true) {
					$(options.lunchStart).attr('disabled', 'disabled');
					$(options.lunchFinish).attr('disabled', 'disabled');
				} else {
					$(options.lunchStart).removeAttr('disabled');
					$(options.lunchFinish).removeAttr('disabled');
				}
			}
		} else {

			$(options.dayOff).attr('checked', false).removeAttr('disabled');
			$(options.withoutLunch).attr('checked', false).removeAttr('disabled');

			$(options.timeStart).removeAttr('disabled').val('09:00');
			$(options.timeFinish).removeAttr('disabled').val('18:00');
			$(options.lunchStart).removeAttr('disabled').val('13:00');
			$(options.lunchFinish).removeAttr('disabled').val('14:00');
		}
	}

	// задает выбранные значения
	var setScheduleTime = function() {

		$(that.contId + ' input[type=checkbox]:checked').each( // просматриваем все выбранные дни недели
			function(i, val) {
				var timeStart = $(options.timeStart).val();
				var timeFinish = $(options.timeFinish).val();
				var lunchStart = $(options.lunchStart).val();
				var lunchFinish = $(options.lunchFinish).val();

				if ($(options.dayOff).attr('checked')) {

					timeStart = 100;
					timeFinish = 100;
					lunchStart = '';
					lunchFinish = '';

				} else if ($(options.withoutLunch).attr('checked')) {
					lunchStart = 100;
					lunchFinish = 100;
				} else {

					if (timeStart == '' || timeFinish == '') {
						timeStart = '';
						timeFinish = '';
						lunchStart = '';
						lunchFinish = '';
					} else if (lunchStart == '' || lunchFinish == '') {
						lunchStart = '';
						lunchFinish = '';
					}
				}

				//alert('SET:' + 'for:' + $(this).val() + '---' + timeStart + '---' + timeFinish + '---' + lunchStart + '---' + lunchFinish + '^)::'+ options.lunchFinish + ':v:' + $(options.lunchFinish).val());

				options.data[$(this).val()] = { 'timeStart': timeStart, 'timeFinish': timeFinish, 'lunchStart': lunchStart, 'lunchFinish': lunchFinish};
			}
		)

		$(that.contPrefix + '__schedule').val($.serialize(options.data));

		initScheduleTime();
	}

	// инициализирует текст рядом с днем недели
	var initScheduleTime = function() {

		$.each(options.data, function(i, val) {

			var message = '';
			var timeStart = val['timeStart'];
			var timeFinish = val['timeFinish'];
			var lunchStart = val['lunchStart'];
			var lunchFinish = val['lunchFinish'];

			if (timeStart == '') {
				message = '';
			} else if (timeStart == 100) {
				message = 'выходной'
			} else {
				message = 'с ' + timeStart;

				if (timeFinish.length > 3) {
					message += ' до ' + timeFinish;

					if (lunchStart.length > 3 && lunchFinish.length > 3) {
						message += ' (обед с ' + lunchStart + ' до ' + lunchFinish + ')';
					} else if (lunchStart == 100) {
						message += ' (без обеда)';
					}

				} else {
					message = '';
				}
			}

			///var textElement = $(that.contId + ' a[name^=text_]').get(i - 1);

			var textElement = that.contPrefix + '__weekday_' + i;

			if (message.length) {
				//$(textElement).addClass('dotted')
			} else {
				//$(textElement).removeClass('dotted')
				message = 'Не указан';
			}

			$(textElement).text(message);
		});
	}

	// определяет один единственный день
	var selectWeekDay = function(obj) {

		$(that.contId + ' input[type=checkbox]').attr('checked', false); // убираем отметку со всех дней

		 $(that.contPrefix + '__' + $(obj).attr('name')).attr('checked', true); // отмечаем выбранный день

		displaySelectScheduled();
	}

	var getData = function() {

		return options.data;
	}

	$(that.contId + ' a[selected=yes]').attr('href', 'javascript:void(null);').bind('click', function(e){ selectWeekDay(this); } );

	$(that.contId + ' div.schedule-selector-link a').attr('href', 'javascript:void(null);').bind('click', function(e){ displaySelectScheduled(); } );

	initScheduleTime();

	return {'getData': getData};
}

jQuery.fn.scheduledWork = function(options, data) {

	options = options || {};
	options.data = (typeof data == 'object') ? data : {};
	options.scheduleBlock = options.scheduleBlock || '#schedule-block';
	options.timeStart = options.timeStart || '#timeStart';
	options.timeFinish = options.timeFinish || '#timeFinish';
	options.lunchStart = options.lunchStart || '#lunchStart';
	options.lunchFinish = options.lunchFinish || '#lunchFinish';
	options.dayOff = options.dayOff || '#day-off';
	options.withoutLunch = options.withoutLunch || '#without-lunch';

	return new scheduledWork(this, options);
}

// деактивирует все поля ввода, если выбран "выходной"
function disableInputsHoliday(obj) {
	if (obj.checked) {
		$('#timeStart,#timeFinish').attr('disabled', 'disabled').val('');
		$('#lunchStart,#lunchFinish').attr('disabled', 'disabled').val('');
		$('#without-lunch').attr('disabled', 'disabled').attr('checked', false);
	} else {
		$('#timeStart,#timeFinish').removeAttr('disabled').val('');
		$('#lunchStart,#lunchFinish').removeAttr('disabled').val('');
		$('#without-lunch').removeAttr('disabled');
	}
}

// деактивирует поля ввода, если выбран "без обеда"
function disableInputsLunch(obj){
	if (obj.checked) {
		$('#lunchStart,#lunchFinish').attr('disabled', 'disabled').val('');
	} else {
		$('#lunchStart,#lunchFinish').removeAttr('disabled').val('');
	}
}