/* BEGIN: jQuery вспомогательный метод для заполнения вып. списка */
$.fn.fill = function(arr, emptyText, optionCallback) {
	optionCallback = optionCallback || function(val) { return '<option>' + val + '</option>'; };
	var options = arr && emptyText != null ? '<option value="">' + emptyText + '</option>' : '';
	$.each(arr, function(key, val) {
		options += optionCallback(val, key);
	});
	this.html(options);
	if (arr.length === 1) {
		try { this.val(arr[0]); } catch (e) { if (window.console) console.error(e); } // fix for ie6
	}
	return this.attr('disabled', arr.length <= 1 && emptyText != null);
};
/* END: jQuery вспомогательный метод для заполнения вып. списка */

/* Vzr */
VzrChangeDetector = function(formName, htmlTarget) {
	_self = this;
	_formName = formName;
	_target = htmlTarget;
	_isFirstChange = true;
	this.Initialize();
}

VzrChangeDetector.prototype = {
	fieldsAndEvents: [
		{ selector: 'input[type=text]', events: 'focusout paste' },
		{ selector: 'input[type=checkbox]', events: 'change' },
		{ selector: 'input[type=radio]', events: 'change' },
		{ selector: 'select', events: 'change select' }
	],
	Initialize: function() {
		var form = $(_formName);
		for (var i = 0; i < _self.fieldsAndEvents.length; i++) {
			var pair = _self.fieldsAndEvents[i];
			form.delegate(pair.selector, pair.events, _self.SomeChanged);
		}
	},

	SomeChanged: function() {
		Utils.debug('VzrChangeDetector fired');
		var form = $(_formName);
		var targ = $(_target);
		var mustDo = true;
		if ($('#cancelTrip_enabled').is(':checked') && $('#cancellationInsuranceMoneyValueFld').val().length <= 0 && _isFirstChange) {
			mustDo = false;
			_isFirstChange = false;
			$('#cancellationInsuranceMoneyValueFld').focus();
		} else {
			form.validate(); //!!
			mustDo = form.valid()
		}
		if (mustDo != false) {
			$('#formSubmitType').val("CalculateQuotation");
			$.post("/products/private_person/tour/abroad/calc/vzr_quot.wbp", form.serialize(),
					   function(messageText) {
					   	targ.html(messageText);
					   });
		}
	}
}

VzrTravelerCloneableHandler = function() { };
VzrTravelerCloneableHandler.prototype = {
	init: function() { },
	OnBeforeCloning: function(clone) {
		var birthdayInput = $("*[name^='Travelers_BirthDay']", clone);
		InputMasks.ClearDatePicker(birthdayInput);
	},
	OnAfterCloning: function(clone) {
		var birthdayInput = $("*[name^='Travelers_BirthDay']", clone);
		InputMasks.InitializeDatePickerForBirthday(birthdayInput, 3, 80);
	},
	initializeClone: function(clone) {
		var ageInput = $("*[name^='Travelers_Age']", clone);
		var birthdayInput = $("*[name^='Travelers_BirthDay']", clone);
		ageInput.numeric();
		InputMasks.InitializeDatePickerForBirthday(birthdayInput, 3, 80);
		
		var ageAndBirthdaySync = clone.data("ageAndBirthdaySync");
		if (ageAndBirthdaySync != null) {
			ageAndBirthdaySync.initialize(ageInput, birthdayInput);
		} else {
			ageAndBirthdaySync = new StartDateAndDurationSync(ageInput, birthdayInput);
			clone.data("ageAndBirthdaySync", ageAndBirthdaySync);
		}
		
		var remove = $('.delete', clone);
		if (clone.attr("cloneIndex") == 0) {
			remove.hide();
		} else {
			remove.show();
		};
		var add = $('.add', clone);
		if (clone.attr("cloneIndex") == 0) {
			add.show();
		} else {
			add.hide();
		};
		
		var deleteOnClone = $('.deleteOnClone', clone);
		if (clone.attr("cloneIndex") != 0) {
			deleteOnClone.remove();
		};
		
		$(".with-error", clone).removeClass("with-error");
		$(".invalid", clone).removeClass("invalid");
		$(".error", clone).remove();
	}
}

var territoryIsCis = function (territoryId) {
	territoryId = territoryId || $('#territoryFld').val();
	var countryIds = territoryCountries[territoryId];
	return territoryId == cisId || ($.isArray(countryIds) && $.inArray(countryIds[0], territoryCountries[cisId]) >= 0);
};

var isSingleTour = function (termId) {
	termId = termId || $('#TermFld').val();
	return termId == 0;
};

var calcInsuranceEndDate = function () {
	var termId = $('#TermFld').val();
	if (isSingleTour(termId)) {
		return Date.parse($('#insuranceTill').val());
	} else {
		var insuranceFrom = Date.parse($('#insuranceFrom').val());
		return insuranceFrom
			? insuranceFrom.addDays(termDays[termId])
			: null;
	}
};

/* Vzr */
Vzr = function (stepNum) {
	this['initializeStep' + stepNum].call(this);
};
Vzr.prototype = {
	/* Параметры валидации */
	/* Для первой страницы */
	validationObj1: {
		onsubmit: false,
		rules: {
			TerritoryID: {
				required: true
			},
			CountryIDSelect: {
				//validSelect: true
				required: '#countrySelect:visible'
			},
			InsurancePeriod_Beginning: {
				required: true,
				date: true,
				min: Date.now()
			},
			InsurancePeriod_End: {
				required: '#insuranceTill:visible',
				date: true,
				min: function () {
					if (!$('#insuranceTill').is(':visible')) return Date.parse($('#insuranceTill').val());
					var insuranceFrom = Date.parse($('#insuranceFrom').val());
					return insuranceFrom ? insuranceFrom : "dependency-mismatch";
				},
				max: function (value, element, param) {
					if (!$('#insuranceTill').is(':visible')) return Date.parse($('#insuranceTill').val());
					var insuranceFrom = Date.parse($('#insuranceFrom').val());
					return insuranceFrom ? insuranceFrom.addDays(territoryIsCis() ? 30 : 365) : "dependency-mismatch";
				}
			},
			Travelers_BirthDay1: {
				required: true,
				date: true,
				max: Date.now(),
				min: function () {
					var insuranceTo = calcInsuranceEndDate() || Date.now();
					return insuranceTo.addYears(isSingleTour() ? -76 : -66).addDays(1);
				}
			}
		},
		messages: {
			TerritoryID: {
				required: "Выберите территорию."
			},
			CountryIDSelect: {
				required: "Выберите страны."
			},
			InsurancePeriod_Beginning: {
				required: "Введите дату начала срока страхования.",
				date: "Введите дату начала срока страхования.",
				min: "Дата не может быть меньше текущей даты."
			},
			InsurancePeriod_End: {
				required: "Введите дату окончания срока страхования.",
				date: "Введите дату окончания срока страхования.",
				min: "Конечная дата должна быть больше начальной.",
				max: function () {
					return territoryIsCis()
						? "Для стран СНГ договоры страхования на срок более 31 дня не заключаются."
						: "Договоры страхования на срок  более 1 года не заключаются."
				}
			},
			Travelers_BirthDay1: {
				required: "Введите дату рождения.",
				min: function () {
					return isSingleTour()
					? "Договоры страхования не заключаются с лицами старше 75 лет."
					: "Договоры страхования с многократными поездками не заключаются с лицами старше 65 лет."
				},
				max: "Дата рождения не может быть больше текущей даты."
			}
		}
	},

	/* Для блока заявки второй страницы */
	validationObj2: {
		rules: {
			FullName: {
				required: true,
				fio: true,
				rangelength: [2, 30]
			},
			CityCode: {
				required: true,
				rangelength: [3, 6],
				digits: true
			},
			Phone: {
				required: true,
				rangelength: [4, 7],
				digits: true,
				validPhone: true
			},
			Comment: {
				required: false,
				maxlength: 500
			}
		},
		messages: {
			FullName: {
				required: "Введите имя.",
				fio: "Разрешено использовать только буквы и тире.",
				rangelength: "От 2 до 30 символов."
			},
			CityCode: {
				required: "Введите код города.",
				rangelength: "От 3 до 6 символов.",
				digits: "Введите корректное число."
			},
			Phone: {
				required: "Введите номер телефона.",
				rangelength: "От 4 до 7 символов.",
				digits: "Введите корректное число.",
				validPhone: "Суммарная длина кода и номера телефона должна быть 10 цифр."
			},
			Comment: {
				maxlength: "Максимум 500 символов"
			}
		}
	},

	/* Для второй страницы "Добавить защиту от дополнительных рисков"*/
	validationObj3: {
		rules: {
			CancellationInsuranceMoneyValue: {
				required: '#cancelTrip_enabled:checked',
				min: function () { return $('#cancelTrip_enabled').is(':checked') ? 500 : $('#cancellationInsuranceMoneyValueFld').val(); },
				max: function () { return $('#cancelTrip_enabled').is(':checked') ? 3000 : $('#cancellationInsuranceMoneyValueFld').val(); }
			},
			CancelTripNationality: {
				required: function () { return $('#CancelTripNationalityOther').is(':checked') && $('#cancelTrip_enabled').is(':checked') }
			}
		},
		messages: {
			CancellationInsuranceMoneyValue: "Введите сумму в диапазоне от 500 до 3000.",
			CancelTripNationality: "Выберите гражданство."
		}
	},
	/* Конец параметров валидации */

	initializeStep1: function () {
		numPad = new NumPad();
		var inputMasks = new InputMasks();

		/* DELETION CONFIRMATION POPUP */
		var deleteConfirm = new PopUp('', 'confirm', '<p>Вы уверены что хотите удалить элемент?</p>', '')
		deleteConfirm.setButtonText({ 'ok': 'Да', 'cancel': 'Нет' });
		var ButtonCallback = function () { };
		ButtonCallback.prototype.popupNotify = function (b, o) {
			if (b) {
				CalcActionButtons.setCalculateQuotationState();
			}
		}
		deleteConfirm.addResultListeners(new ButtonCallback());
		/* END DELETION CONFIRMATION POPUP */

		/* Create deletable and closeable element*/
		var closeable = new Closeable(deleteConfirm);
		var hintsToClones = {};
		hintsToClones.init = function () {
			new Hint();
		}
		// Handler for birthday and age sync.
		var vzrTravelerCloneableHandler = new VzrTravelerCloneableHandler();
		/* Create cloneable element*/
		var cloneable = new Cloneable('#addTravelerPattern', //pattern to clone
								'#addTraveler', //action button to place cloned elements
								new Array(closeable, numPad, inputMasks, vzrTravelerCloneableHandler, hintsToClones), //binding functionality to newly cloned elements
								'#inpt_Travelers_Count', //Counter Field selector
								49 //Clone max count.
							);
		cloneable._setActionContainer($('#addButton'));
		$('#addButton').click(CalcActionButtons.setCalculateQuotationState);
		closeable.setCallback(cloneable); //callback to reduce number of cloned elements in cloneable Object

		InputMasks.InitializeDatePicker($('#insuranceFrom'), new Date(), null, function () { $('#insuranceFrom').focus(); });
		InputMasks.InitializeDatePicker($('#insuranceTill'), new Date(), null, function () { $('#insuranceTill').focus(); });

		for (var i = 2; i <= 50; i++) {
			this.validationObj1.rules['Travelers_BirthDay' + i] = this.validationObj1.rules.Travelers_BirthDay1;
			this.validationObj1.messages['Travelers_BirthDay' + i] = this.validationObj1.messages.Travelers_BirthDay1;
		}

		$('#vzrCalc').submit($.proxy(function () {
			var validator = $('#vzrCalc').validate(this.validationObj1);
			if (!validator.form()) return false;
			// Перед отправкой формы
			$('#TermFld').removeAttr('disabled');
			// Фикс бага, из-за которого при открытом меню и клике на Далее, не сохраняются выбранные страны
			var result = true;
			$('.ui-autocomplete-input').each(function (i, elem) {
				var autocomplete = $(elem).data('autocomplete');
				if (autocomplete && autocomplete.menu.element && autocomplete.menu.element.is(':visible')) {
					result = false;
					return false;
				}
			});
			return result;
		}, this));

		$('#territoryFld').combobox({ specialClass: 'territoryFldCombobox' });
		$('#sportFld').combobox({ specialClass: 'TermFldCombobox' });

		/* Инициализация контролов */
		$('#territoryFld').select($.proxy(this.territoryChanged, this)); //.change(this.territoryChanged);
		$('#countryFld').select(function () {
			var values = "";
			var sel = $('#countryFld').children('option:selected');
			for (var i = 0; sel.length > i; i++) {
				if (i > 0) values += ";";
				values += $(sel[i]).attr('value');
			}
			$('#CountryID').val(values);
		});

		$('#documentCollapser').click(function () {
			if ($('#travelDescription').is(':visible')) {
				$('#travelDescription').hide('fast');
			} else {
				$('#travelDescription').show('fast');
			}
		});

		$('#TermFld').select(this.termChanged);

		$('#insuranceSumFld').change(this.applyInsuranceSumWarning);

		this.territoryChanged();
		if (travelInsuranceMoneyID) {
			$("#insuranceSumFld").val(travelInsuranceMoneyID);
		}
		this.termChanged();
		this.applyInsuranceSumWarning();
		this.setTermState();

		/* Мультиселект */
		// Перемещаем значения из хидден-поля CountryID в мультиселект 
		var ids = $('#CountryID').val().split(";");
		this.fillCountrySelect(ids);
		/* Конец мультиселекта */
	},

	fillCountrySelect: function (selectedIds) {
		var territoryId = $('#territoryFld').val();
		var countryList = countries[territoryId];
		$('#countryFld option').remove();

		if (countryList) {
			$.each(countryList, function (i, cont) {
				$('<option value="' + i + '"' + (selectedIds && $.inArray(i, selectedIds) > -1 ? ' selected="selected"' : '') + '>' + cont + '</option>').appendTo($('#countryFld'));
			});
		}
		$('#countryFld').combobox();
	},

	territoryChanged: function () {
		var territoryId = $('#territoryFld').val();
		var sumId = $('#insuranceSumFld').val();

		// Если для данной территории есть список стран - показываем комбобокс
		if (countries[territoryId]) {
			this.fillCountrySelect();
		} else {
			$('#countrySelect, #CountryID').val('');
		}
		$('#countrySelect').toggle(countries[territoryId] != null);


		var countryIds = territoryCountries[territoryId];
		var limit;
		if ($.isArray(countryIds)) {
			limit = countryLimits[countryIds[0]];
		}
		// Для стран, которых нет в справочнике мин сумма - 3000 и только евро
		limit = limit || { "EUR": 2 };

		$('#EUR').attr('disabled', !limit.EUR);
		$('#USD').attr('disabled', !limit.USD);
		var $enabled = $('#EUR:enabled,#USD:enabled');
		if ($enabled.length === 1) {
			$enabled.attr('checked', 'checked');
		}

		var m = [];
		if (territoryIsCis()) {
			m.push(limit.USD); // hardcode for CIS

			$('#TermFld').val(0).attr('disabled', 'disabled');
		} else {
			var minSumId = limit.EUR || limit.USD || 1;
			for (var id in insuranceSums) {
				if (id >= minSumId) {
					m.push(id);
				}
			}

			$('#TermFld').removeAttr('disabled');
		}

		$('#insuranceSumFld').fill(m.sort(), null, function (id) { return '<option value="' + id + '">' + insuranceSums[id] + '</option>'; });
		if (sumId && $.inArray(sumId, m) >= 0) {
			$('#insuranceSumFld').val(sumId)
		}

		this.setTermState();
	},

	setTermState: function () {
		if (territoryIsCis()) {
			$('#TermFld').val('0').select().change().attr('disabled', 'disabled');
		} else {
			$('#TermFld').removeAttr('disabled');
		}
		$('#TermFld').combobox({ buttonText: "", autocomplete: false, specialClass: 'TermFldCombobox' });
		this.applyInsuranceSumWarning();
	},

	termChanged: function () {
		var isSingle = isSingleTour();
		$('#singleTourBox').toggle(isSingle);
		$('#multipleTours').val(!isSingle);
		//if (!isSingle) $('#insuranceTill').val('');
		$("#insuranceFrom,#insuranceTill,input:text[name^='Travelers_BirthDay']").valid();
	},

	applyInsuranceSumWarning: function () {
		var showWarning = $('#insuranceSumFld option:selected').text().replace(' ', '') >= 100000;
		$('#insuranceSumWarning').toggle(showWarning);
	},

	initializeStep2: function () {
		var isChangingInInit = false; // Если во время инициализации произошли изменения в UI - в конце запускаем обновление премии

		$.validator.addMethod('validPhone', function (value) {
			return $('#CityCode').val().length + $('#Phone').val().length == 10;
		}, '');

		$('textarea.textarHelper')
		.focus(function () {
			if ($(this).val() == $(this).attr('defaultValue')) {
				$(this).val('');
				$(this).removeClass('helperEnable');
			}
		})
		.blur(function () {
			if ($.trim($(this).val()) == '') {
				$(this).val($(this).attr('defaultValue'));
				$(this).addClass('helperEnable');
			}
		});

		new FormSubmit();
		var cUtils = new CalcUtils()
		cUtils.watchCalcChanges();
		new InputMasks();

		$('#cancellationInsuranceMoneyValueFld').change(this.applyCancelTripFormWarning);

		$('.formCollapser').click(function () {
			$(this).closest('.inputWrapper').nextAll('.riskAboutDocument').toggle();
		});

		$('#cancelTrip_enabled').change($.proxy(this.checklCancelTripAllowed, this));

		var cancelTripDeforeUpdate = $('#cancelTrip_enabled').is(':checked');

		$('#lossbag_enabled, #civilliability_enabled, #accident_enabled, #cancelTrip_enabled').change(function () {
			$(this).closest('.inputWrapper').nextAll('.riskParameters').toggle($(this).is(':checked'));
		}).change();

		isChangingInInit = cancelTripDeforeUpdate != $('#cancelTrip_enabled').is(':checked');

		$('#SubmitApplication').click(this.submitApplication);

		$('#lossbagProgramFld').combobox({ specialClass: 'nationalityCombobox' });
		$('#accidentTypesFld').combobox({ specialClass: 'nationalityCombobox' });
		$('#cancelTripTypesFld').combobox({ specialClass: 'nationalityCombobox' });
		$('#CancelTripNationality').combobox({ specialClass: 'nationalityCombobox' });

		$('input:radio.nationality').change(this.cancelTripNationalityTypeChanged);
		$('#cancelTripTypesFld').select(this.applyCancelTripFormWarning);

		this.changeDetector = new VzrChangeDetector('#vzrRisk', '#vzr_sum');

		this.applyCancelTripFormWarning();

		if (this.changeDetector && isChangingInInit) this.changeDetector.SomeChanged();

		$('#appForm').validate(this.validationObj2);
		$('#vzrRisk').validate(this.validationObj3);
	},

	checklCancelTripAllowed: function () {
		if ($('#cancelTrip_enabled').is(':checked')) {
			var fiveDayWarning = Date.parse($('#insuranceFrom').val()) < Date.now().addDays(4);
			var elderlyManWarning = false;
			var insuranceTo = calcInsuranceEndDate();
			var limit = insuranceTo ? insuranceTo.addYears(-66) : null;
			$.each(travelers, function (i, traveler) {
				if (Date.parse(traveler.birthday) < limit) {
					elderlyManWarning = true;
					return false;
				}
			});

			$('#elderlyManWarning').toggle(elderlyManWarning);
			$('#fiveDayWarning').toggle(fiveDayWarning);
			if (elderlyManWarning || fiveDayWarning) {
				$('#cancelTrip_enabled').removeAttr('checked');
				return false;
			}
			return true;
		}
	},

	cancelTripNationalityTypeChanged: function () {
		$('#vzrRisk').validate().element('#CancelTripNationality');
		$(this).siblings('select').attr('disabled', $(this).val() == 'True').combobox({ specialClass: 'nationalityCombobox' });
	},

	applyCancelTripFormWarning: function () {
		var typeLetter = $('#cancelTripTypesFld option:selected').text().toUpperCase();
		var showWarning = typeLetter.indexOf('D') > -1 || typeLetter.indexOf('E') > -1;
		if (!showWarning && typeLetter.indexOf('C') > -1) {
			var insSum = $('#cancellationInsuranceMoneyValueFld').val();
			showWarning = insSum >= 2001 || travelers.length > 1;
		}
		$('#cancelTripFormWarning').toggle(showWarning);
	},

	submitApplication: function () {
		$("#appForm").validate();
		$("#vzrRisk").validate();
		if (!$("#appForm").valid() || !$("#vzrRisk").valid()) {
			return false;
		}
		$('#SubmitApplication').disableBtn();
		$('#back').disableBtn();
		var comment = $('#Comment').val();
		if (comment == $('#Comment').attr('defaultValue')) {
			comment = '';
		}
		$.ajax({
			type: 'POST',
			url: '/policierequest.wbp',
			data: {
				SubmitApplication: true,
				ActionSource: 'CalculatorButton',
				SourcePageType: 'CalculatorPage',
				IsPublicArea: true,
				InitialInsuranceProductType: 'Travel',
				FullName: $('#FullName').val(),
				ContactPhoneCityCode: $('#CityCode').val(),
				ContactPhoneNumber: $('#Phone').val(),
				Comment: comment,
				AttachedFilesCount_1: 0,
				IncludedCaseType_1: 'Quotation',
				IncludedCaseId_1: $('#CaseID').val(),
				IncludedCaseInsuranceProductType_1: 'Travel',
				IncludedCasesCount: 1
			},
			success: function (data) {
				var result = $(data).find('#borderedData');
				$('#borderedData').replaceWith(result);
			},
			dataType: 'html',
			contentType: 'application/x-www-form-urlencoded;charset=utf-8'
		});
	}
}


