;(function($)
{
	$.calc = $.calc || {};

	$.fn.extend({
		osago: function(options, args)
		{
			var args = Array.prototype.slice.call(arguments, 1);

			return this.each(function()
			{
				if (typeof options == "string")
				{
					var calc = $.data(this, "osago-calc");

					calc[options].apply(calc, args);
				}
				else if (!$(this).is(".osago-calc"))
				{
					$.data(this, "osago-calc", new $.calc.osago(this, options));
				}
			});
		},
		initialize: function()
		{
			this.osago("initialize", null);
		}
	});

	$.calc.osago = function(container, options)
	{
		_self = this;
		this.element = container;
		this.options = options = $.extend({}, $.calc.osago.defaults, options);
		this.options.init = true;

		$(container).addClass("osago-calc");

		numPad = new NumPad();
		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());
		closeable = new Closeable(deleteConfirm);

		var inputMasks = new InputMasks();

		var hintsToClones = {};
		hintsToClones.init = function()
		{
			new Hint();
		}

		this.options.cloneable = new Cloneable('#addDriverPattern',
						'#addDriver',
						new Array(closeable, numPad, inputMasks, new DriverElement(this.options.utils), hintsToClones),
						'#driversToUseVihcle',
						4
					);
		this.options.cloneable._setActionContainer("#addButton");
		$("#addButton").click(function()
		{
			CalcActionButtons.setCalculateQuotationState();
		});
		this.options.cloneable._syncClonesCount();
		closeable.setCallback(this.options.cloneable);

		var retrieveCitiesCallback = function(value)
		{
			var data = $.CalcDataProvider.GetRegionCitiesForOsagoSync(value);
			return data;
		}

		var regionCities = new DependOptions('#regionData', '#cityData', 'city');
		regionCities.setCallback(retrieveCitiesCallback);
		regionCities._do(this.options.vehicleUsageDestinationCityID);

		var dateBeforeNowInputs = $(
			"*[name='QuotationCriteria_VehicleInfo_Passport_IssuedWhen']");
		InputMasks.InitializeDatePicker(dateBeforeNowInputs, null, new Date());

		var birthdayInputs = $(
			"*[name='InvolvedPersons_Insurant_BirthDay']" +
			", *[name='InvolvedPersons_Owner_BirthDay']");
		InputMasks.InitializeDatePickerForBirthday(birthdayInputs, 18, null);

		var dateAfterNowInputs = $(
			"*[name='QuotationCriteria_InsurancePeriod_Beginning']" +
			",*[name='QuotationCriteria_InsurancePeriod_End']" +
			",*[name^='QuotationCriteria_UsagePeriods_Beginning']" +
			",*[name^='QuotationCriteria_UsagePeriods_End']" +
			",*[name='PolicyProjectCriteria_AppliedWhen']");
		InputMasks.InitializeDatePicker(dateAfterNowInputs, new Date(), null);
		
		$("#ownerTypeInput, #vehicleType, #otherCountries").change(this.checkVehicleTrailerCondition);
		this.checkVehicleTrailerCondition();
	};

	$.calc.osago.prototype =
	{
		initialized: false,
		options: null,
		ctlVehicleType: null,
		ctlVehicleVendor: null,
		ctlVehicleModel: null,

		initialize: function()
		{
			//if (_self.options.isPolicyProjectMode)
			if ($('a[name="policieProject"]').length)
			{
				this.ctlVehicleType = $('#vehicleType');
				this.ctlVehicleVendor = $('#vehicleVendors');
				this.ctlVehicleModel = $('#vehicleModels');
				
				this.ctlVehicleModel[0].disabled = 'disabled';

				this.ctlVehicleVendor.change(function() { _self.GetModels(); });
				this.ctlVehicleType.change(function() { _self.GetVendors(); })
					.change();
			}

			$('.powerunits').bind("change", CalcUtils.prototype.powerUnits.setPowerUnits);
			$('#Horsepower').bind("keyup", CalcUtils.prototype.powerUnits.convertHPtoKwt)
							.bind("focus", CalcUtils.prototype.powerUnits.convertHPtoKwt);
			$('#Kilowatt').bind("keyup", CalcUtils.prototype.powerUnits.convertKwttoHP)
						  .bind("focus", CalcUtils.prototype.powerUnits.convertKwttoHP);

			$('#PhysicalPerson')[0].thisObj = this;
			$('#JuridicalPerson')[0].thisObj = this;

			if ($('#ownerTypeInput').val() == 'PhysicalPerson')
			{
				this.phisicalRestrictionState = $("#noRestrictions").checked();
			};

			$('#ownerType li').click(function()
			{
				$('#ownerType li').removeClass('active');
				$('#ownerTypeInput').attr('value', this.id).change();
				$('#' + this.id).addClass('active');
			});

			$("#vehicleType").bind("change", this.vehicleTypeChange);
			$("#followtoreg").bind("click", this.followToRegionClick);
			$("#otherCountries").bind("click", this.otherCountryClick);
			$("#PhysicalPerson").bind("click", this.physicalPersonClick);
			$("#JuridicalPerson").bind("click", this.juridicalPersonClick);
			$("#noRestrictions").bind("click", this.noRestrictionClick);
			this.options.cloneable._reinit();
			this.options.init = true;
			this.refresh();
			this.options.init = false;

			if (this.options.debug)
			{
				$(this).attr('action', '?debug=1');
			}
			new FormSubmit();

			$(".formCollapser").collapser({ container: '.collapsableForm' }, null);
			$("#Horsepower, #Kilowatt, #numberOfSeats, #vehicleInfoWeight").numeric();

			$('#PhysicalPersonIns').click(
					function()
					{
						this.className = 'active';
						$('#JuridicalPersonIns').removeClass();
						$('#insTypeInput').attr('value', 'PhysicalPerson');
						$('#INNCertProjectCont').hide();
						$('#dateOfBirthCertProjectCont').show();
						$('input[name*=InvolvedPersons_Insurant_PersonRegistrationDocument_TypeName]').attr('value', 'Паспорт');
					}
				);

			$('#JuridicalPersonIns').click(
					function()
					{
						this.className = 'active';
						$('#PhysicalPersonIns').removeClass('active');
						$('#insTypeInput').attr('value', 'JuridicalPerson');
						$('#INNCertProjectCont').show();
						$('#dateOfBirthCertProjectCont').hide();
						$('input[name*=InvolvedPersons_Insurant_PersonRegistrationDocument_TypeName]').attr('value', 'Свидетельство о регистрации');
					}
				);
				
			if ($('#insTypeInput').val() === 'JuridicalPerson'){
				$('#JuridicalPersonIns').triggerHandler('click');
			}
			
			var UsagePeriods_Beginning = $('.UsagePeriods input[name^="QuotationCriteria_UsagePeriods_Beginning"]'),
				UsagePeriods_End = $('.UsagePeriods input[name^="QuotationCriteria_UsagePeriods_End"]'),
				counter = $('input[name="QuotationCriteria_UsagePeriods_Count"]');
			
			counter.val(0);
			UsagePeriods_Beginning.each(function(){
				var el = $(this),
					parent = el.parents('.UsagePeriods'),
					counterVal = (counter.val()) ? parseInt(counter.val()) : 0,
					secondInput = UsagePeriods_End.filter('input[name="QuotationCriteria_UsagePeriods_End' + this.name.substring(this.name.length - 1) + '"]');
				if (/^\d{2}\.\d{2}\.\d{4}$/.test(this.value) && /^\d{2}\.\d{2}\.\d{4}$/.test(secondInput.val())){
					parent[0].UsagePeriod = true;
					counter.val(counterVal + 1);
				}
			});
				
			UsagePeriods_Beginning.add(UsagePeriods_End).bind('change keyup', function(e){
				var el = $(this),
					parent = el.parents('.UsagePeriods'),
					counterVal = (counter.val()) ? parseInt(counter.val()) : 0,
					secondInput = (this.name.indexOf('QuotationCriteria_UsagePeriods_Beginning') !== -1) ? UsagePeriods_End : UsagePeriods_Beginning,
					secondInputName = (this.name.indexOf('QuotationCriteria_UsagePeriods_Beginning') !== -1) ? 'QuotationCriteria_UsagePeriods_End' : 'QuotationCriteria_UsagePeriods_Beginning';
				if (/^\d{2}\.\d{2}\.\d{4}$/.test(this.value)){
					var secondPeriodPart = secondInput.filter('input[name="' + secondInputName + this.name.substring(this.name.length - 1) + '"]');
					if (/^\d{2}\.\d{2}\.\d{4}$/.test(secondPeriodPart.val()) && parent[0].UsagePeriod !== true){
						parent[0].UsagePeriod = true;
						counter.val(counterVal + 1);
					}
				} else {
					if (parent[0].UsagePeriod === true){
						parent[0].UsagePeriod = false;
						counter.val(counterVal - 1);
					}
				}
			});
			
			var QuotationCriteria_InsurancePeriod_End = $('input[name="QuotationCriteria_InsurancePeriod_End"]'),
				otherCountries = $('#otherCountries'),
				followtoreg = $('#followtoreg');
			
			/*if (followtoreg.checked() || otherCountries.checked()){
				QuotationCriteria_InsurancePeriod_End[0].removeAttribute('readonly');
				QuotationCriteria_InsurancePeriod_End.next('.datepickerButton').show();
			}*/
			
			$('input[name="QuotationCriteria_InsurancePeriod_Beginning"]').bind('change keyup', function(e){
				if (/^\d{2}\.\d{2}\.\d{4}$/.test(this.value)){
					var val = this.value.split('.');
					val = new Date(val[2], val[1] - 1, val[0]);
					
					if (otherCountries.checked()){
						var InsuranceLength = parseInt($('select[name="QuotationCriteria_InsurancePeriodID"]').eq(1).val()),
							month = true;
						if (InsuranceLength === 1){
							InsuranceLength = 15;
							month = false;
						} else if (InsuranceLength === 2){
							InsuranceLength = 1;
						} else {
							InsuranceLength = InsuranceLength - 1;
						}
						
						if (!month){
							val.setDate(val.getDate() + InsuranceLength);
						} else {
							val.setMonth(val.getMonth() + InsuranceLength);
						}
					} else if (followtoreg.checked()) {
						val.setDate(val.getDate() + 20);
					} else {
						val.setFullYear(val.getFullYear() + 1);
						val.setDate(val.getDate() - 1);
					}
					
					val = [
						(val.getDate().toString().length === 1) ? '0' + val.getDate() : val.getDate(),
						(val.getMonth().toString().length === 1) ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1),
						val.getFullYear()
					]
					
					QuotationCriteria_InsurancePeriod_End.val(val.join('.'));
				} else {
					QuotationCriteria_InsurancePeriod_End.val('');
				}
			}).change();
			
			var catTSval = $('#vehicleType option:selected').val(),
				catTS = $('#catTS');
			
			if (catTS.length){
				switch(catTSval){
					case '1':
						catTSval = 'A';
						break;
					case '2':
						catTSval = 'B';
						break;
					case '3':
						catTSval = 'C';
						break;
					case '4':
						catTSval = 'D';
						break;
					default:
						catTSval = '';
						break;
				}
				
				if (catTSval) {
					catTSval = 'Категория ' + catTSval;
				}
				catTS[0].initialValue = catTSval;
				catTS.val(catTSval);
			}

			this.initialized = true;
			Utils.debug("Calc data is loaded.");
			CalcUtils.prototype.watchCalcChanges();
			$('#ownerType li').click(CalcActionButtons.setCalculateQuotationState);
		},

		getIsPhysicalPerson: function()
		{
			return $("#ownerTypeInput").val() == "PhysicalPerson";
		},

		vehicleTypeChange: function()
		{
			_self.refresh();
		},
		// Следование к месту регистрации
		followToRegionClick: function(e)
		{
			$("#otherCountries").check('off');
			$("#" + $("#ownerTypeInput").val()).click();
			_self.refresh();
		},

		// Зарегистрировано в иностранном государстве
		otherCountryClick: function(e)
		{
			$("#followtoreg").check('off');
			$("#noRestrictions").check('on');
			if (!$("#otherCountries").checked())
			{
				$("#" + $("#ownerTypeInput").val()).click();
			}
			_self.refresh();
		},

		updateUsageTerritory: function()
		{
			if ($("#followtoreg").checked() || $("#otherCountries").checked())
			{
				$("#usageDestination").hide();
				$("#usageDestination").disable();
			}
			else
			{
				$("#usageDestination").show();
				$("#usageDestination").enable();
			}
		},

		updateForeignCountry: function()
		{
			if ($("#otherCountries").checked())
			{
				$("#foreignContainer").show();
				$("#foreignContainer").enable();
			}
			else
			{
				$("#foreignContainer").hide();
				$("#foreignContainer").disable();
			}
		},

		physicalPersonClick: function()
		{
			$("#ownerTypeInput").val('PhysicalPerson');
			var state = 'off';
			if ($("#otherCountries").checked())
			{
				state = 'on';
			}
			else
			{
				if (this.thisObj.phisicalRestrictionState)
					state = 'on';
			}
			$("#noRestrictions").check(state);
			if (!_self.options.init)
				_self.refresh();
		},
		juridicalPersonClick: function()
		{
			if (!$("#otherCountries").checked())
			{
				this.thisObj.phisicalRestrictionState = $("#noRestrictions").checked();
			}
			$("#ownerTypeInput").val('JuridicalPerson');
			$("#noRestrictions").check('on');
			if (!_self.options.init)
				_self.refresh();
		},

		noRestrictionClick: function()
		{
			$('#PhysicalPerson')[0].thisObj.phisicalRestrictionState = $("#noRestrictions").checked();
			_self.refresh();
		},

		updateOwners: function()
		{
			if (this.options.init)
			{
				if (!this.getIsPhysicalPerson())
				{
					$("#noRestrictions").check('on');
				}
				$("#" + $("#ownerTypeInput").val()).click();
			}
		},
		// Обновляем подписи в секции для ввода водителей при смене типа владельца.
		updateDriverLabels: function()
		{
			if ($("#noRestrictions").checked())
			{
				$("#lblNumberOfLossesCont").text("Количество аварий, произошедших в период действия предыдущего полиса");
				$("#lblInsuranceClass").text("Класс собственника на начало действия предыдущего полиса ОСАГО");
				/*				$("#lblNumberOfLossesCont").hide();
				$("#lblNumberOfLossesNoRestrictionCont").show();
				$("#lblInsuranceClass").hide();
				$("#lblInsuranceClassNoRestriction").show();*/
			}
			else
			{
				$("#lblNumberOfLossesCont").text("Количество страховых случаев, произошедших по вине данного водителя в период действия предыдущего полиса");
				$("#lblInsuranceClass").text("Класс на начало действия предыдущего полиса ОСАГО");
				/*				$("#lblNumberOfLossesCont").show();
				$("#lblNumberOfLossesNoRestrictionCont").hide();
				$("#lblInsuranceClass").show();
				$("#lblInsuranceClassNoRestriction").hide();*/
			}
			new Hint();
		},

		// Обновляем секцию "Срок страхования"
		updateDurationOfInsurance: function()
		{
			if ($("#followtoreg").checked())
			{
				$("#durationOfInsurance").show();
				$("#durationOfInsurance").enable();
			}
			else
			{
				$("#durationOfInsurance").hide();
				$("#durationOfInsurance").disable();
			}
			if ($("#otherCountries").checked())
			{
				$("#durationOfInsuranceOtherCountry").enable().show();
			}
			else
			{
				$("#durationOfInsuranceOtherCountry").hide().disable();
			}
		},

		// Обновляем секцию "Период использования"
		updateYearsOfusageCont: function()
		{
			if (!$("#followtoreg").checked() && !$("#otherCountries").checked())
			{
				if (!this.getIsPhysicalPerson())
				{
					$("#yearsOfusageCont").hide();
					$("#yearsOfusageCont").disable();
					$("#yearsOfusageContJuridicial").show();
					$("#yearsOfusageContJuridicial").enable();
				}
				else
				{
					$("#yearsOfusageCont").show();
					$("#yearsOfusageCont").enable();
					$("#yearsOfusageContJuridicial").hide();
					$("#yearsOfusageContJuridicial").disable();
				}
			}
			else
			{
				$("#yearsOfusageCont").hide();
				$("#yearsOfusageCont").disable();
				$("#yearsOfusageContJuridicial").hide();
				$("#yearsOfusageContJuridicial").disable();
			}
		},

		updateRestrictions: function()
		{
			if ($("#otherCountries").checked() || !this.getIsPhysicalPerson())
			{
				if (this.options.init)
					$("#noRestrictions").check('on');
				//$("#noRestrictions").disable();
				$("#noRestrictions").parent().hide();
			}
			else
			{
				//$("#noRestrictions").enable();
				$("#noRestrictions").parent().show();
			}
			if ($("#noRestrictions").checked())
			{
				_self.options.cloneable.empty(1);
				$('#addButton').hide();
				$('#addButton').disable();
			}
			else
			{
				if (this.options.cloneable.clones.length != this.options.cloneable.maxClonesNumber)
				{
					$('#addButton').show();
					$('#addButton').enable();
				}
				else
				{
					$('#addButton').hide();
					$('#addButton').disable();
				}
			}
		},

		updateDriverAge: function()
		{
			var vehicleType = $('#vehicleType').val();
			var showFlag = this.getIsPhysicalPerson()
				&& !$("#noRestrictions").checked()
				&& !$("#otherCountries").checked()
				&& vehicleType != 8 && vehicleType != 9 && vehicleType != 10;
			if (showFlag)
			{
				$("#vihcleDrivers .doubleInputWrapper").show();
				$("#vihcleDrivers .doubleInputWrapper").enable();
				$("#vihcleDrivers .doubleInputWrapper > *").show();
			}
			else
			{
				$("#vihcleDrivers .doubleInputWrapper").hide();
				$("#vihcleDrivers .doubleInputWrapper").disable();
				$("#vihcleDrivers .doubleInputWrapper > *").hide();
			}
		},

		upadteBonusMalus: function()
		{
			if ($("#otherCountries").checked() || $("#followtoreg").checked())
			{
				$("#vihcleDrivers div.cloneable .inputWrapper").hide();
				$("#vihcleDrivers div.cloneable .inputWrapper").disable();
			}
			else
			{
				for (var i = 1; i <= _self.options.cloneable.clones.length; i++)
				{
					$("#firstYearOSAGO" + i).parent().show();
					$("#firstYearOSAGO" + i).parent().enable();

					if (!$("#firstYearOSAGO" + i).checked())
					{
						$('#PreviousContractNumberOfLossesCont' + i).show();
						$('#PreviousContractNumberOfLossesCont' + i).enable();
						$('#PreviousContractInsuranceClassCont' + i).show();
						$('#PreviousContractInsuranceClassCont' + i).enable();
					}
					else
					{
						$('#PreviousContractNumberOfLossesCont' + i).hide();
						$('#PreviousContractNumberOfLossesCont' + i).disable();
						$('#PreviousContractInsuranceClassCont' + i).hide();
						$('#PreviousContractInsuranceClassCont' + i).disable();
					}
				}
			}
		},

		updateVehicleInfo: function()
		{
			var vehicleTypeID = $("#vehicleType").val();

			if (jQuery.inArray(vehicleTypeID, this.options.allowEnginePowerVehcleTypeIds) != -1)
			{
				$("#enginePower").show();
				$("#enginePower").enable();
			}
			else
			{
				$("#enginePower").hide();
				$("#enginePower").disable();
			}

			if (jQuery.inArray(vehicleTypeID, this.options.allowUsedVehcleTypeIds) != -1)
			{
				$("#aimofUseCont").show();
				$("#aimofUseCont").enable();
			}
			else
			{
				$("#aimofUseCont").hide();
				$("#aimofUseCont").disable();
			}

			if (jQuery.inArray(vehicleTypeID, this.options.allowMaxWeightContVehcleTypeIds) != -1)
			{
				$("#maxWeightCont").show();
				$("#maxWeightCont").enable();
			}
			else
			{
				$("#maxWeightCont").hide();
				$("#maxWeightCont").disable();
			}

			if (jQuery.inArray(vehicleTypeID, this.options.alowSeatcAmountVehcleTypeIds) != -1)
			{
				$("#seatcAmountCont").show();
				$("#seatcAmountCont").enable();
			}
			else
			{
				$("#seatcAmountCont").hide();
				$("#seatcAmountCont").disable();
			}
		},

		updateVehicleDrivers: function()
		{
			if (jQuery.inArray($("#vehicleType").val(), this.options.allowVehicleDriversVehcleTypeIds) != -1)
			{
				$("#vihcleDrivers").show();
				$("#vihcleDrivers").enable();
			}
			else
			{
				$("#vihcleDrivers").hide();
				$("#vihcleDrivers").disable();
			}
		},

		updatepowerUnits: function()
		{
			if ($("#powerUnitsType").val() === "Horsepower" && $("#Horsepower").val() !== "") {
				$("#Kilowatt").val(CalcUtils.prototype.powerUnits.convertHPtoKwt($("#Horsepower").val()));
			}
		
			if ($("#powerUnitsType").val() === "Kilowatt" && $("#Kilowatt").val() !== "") {
				$("#Horsepower").val(CalcUtils.prototype.powerUnits.convertKwttoHP($("#Kilowatt").val()));
			}
		},
		refresh: function()
		{
			this.updateVehicleInfo();
			this.updatepowerUnits();
			this.updateUsageTerritory();
			this.updateForeignCountry();
			this.updateOwners();
			this.updateDriverLabels();
			this.updateDurationOfInsurance();
			this.updateYearsOfusageCont();
			this.updateVehicleDrivers();
			this.updateRestrictions();
			this.updateDriverLabels();
			this.updateDriverAge();
			this.upadteBonusMalus();
		},

		checkVehicleTrailerCondition: function()
		{
			if ($('#ownerTypeInput').val() == 'PhysicalPerson'
				&& parseInt($("#vehicleType").val()) == 8
				&& !$("#otherCountries").checked())
			{
				$('#VehicleTrailerConditionWarning').show();
				CalcActionButtons.setCalculationImpossibleState($("#VehicleTrailerConditionWarning div").text());
			}
			else
			{
				$('#VehicleTrailerConditionWarning').hide();
				CalcActionButtons.clearCalculationImpossibleState();
			}
		},

		GetVendors: function()
		{
			this.ctlVehicleVendor.empty();
			this.ctlVehicleModel.empty();

			var selectedVendorID = this.initialized ? null : this.options.vehicleVendorID;

			var self = this;
			var completedCallback = function(data, isSuccesful)
			{
				if (isSuccesful)
				{
					var vendors = new DependOptions('#vehicleType', '#vehicleVendors', 'vendors');
					vendors.setCallback(function()
					{
						return data;
					});
					vendors._do(selectedVendorID);
					vendors.node.onchange = null;
					self.ctlVehicleVendor.change();
				}
			};

			$.CalcDataProvider.GetVehicleVendorsWithoutTypes(completedCallback, this.ctlVehicleType.val(), selectedVendorID);
		},

		GetModels: function()
		{
			this.ctlVehicleModel.empty();

			var vehicleVendorID = parseInt(this.ctlVehicleVendor.val());
			var selectedModelID = this.initialized ? null : this.options.vehicleModelID;

			if (!isNaN(vehicleVendorID))
			{
				var self = this;
				var completedCallback = function(resultJson, isSuccesful)
				{
					if (isSuccesful)
					{
						self.ctlVehicleModel[0].disabled = null;
						bindSelectBox("#vehicleModels", resultJson["models"][vehicleVendorID], 
							function(e) { 
								return e.active;
							}, 
							function(e) { 
								return e.id; 
							}, 
							function(e) { 
								return e.text; 
							}
						);
					}
				};

				$.CalcDataProvider.GetVehicleModels(completedCallback, this.ctlVehicleType.val(), vehicleVendorID, selectedModelID);
			} else {
				this.ctlVehicleModel[0].disabled = 'disabled';
			}
		},

		dummy: null
	};

	$.extend($.calc.osago, {
		defaults: {
			debug: false,
			utils: new CalcUtils(),
			allowEnginePowerVehcleTypeIds: ['2'],
			allowVehicleDriversVehcleTypeIds: ['1', '2', '3', '4', '5', '6', '7'],
			allowUsedVehcleTypeIds: ['2', '4'],
			allowMaxWeightContVehcleTypeIds: ['3'],
			alowSeatcAmountVehcleTypeIds: ['4']
		}
	});

})(jQuery);

var showCalculateQuotationCont = true;

DriverElement = function(utils) {
	this._calcUtils = utils;
};

DriverElement.prototype = {
	init: function(caller) {
		for (var i = 1; i <= caller.clones.length; i++) {
			var clone = caller.clones[i - 1];
			var ageInput = $("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_Age']", clone);
			var birthdayInput = $("*[name^='InvolvedPersons_PhysicalPerson_BirthDay']", clone);

			ageInput.numeric();
			var ageAndBirthdaySync = $.data(clone, "calc-driver-age");
			if (ageAndBirthdaySync != null) {
				ageAndBirthdaySync.initialize(ageInput, birthdayInput)
			}
			else {
				ageAndBirthdaySync = new StartDateAndDurationSync(ageInput, birthdayInput);
				$.data(clone, "calc-driver-age", ageAndBirthdaySync);
			}

			var expyersInput = $("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_DrivingExperienceYears']", clone);
			var startexpyersInput = $("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_DrivingExperienceStartDate']", clone);

			expyersInput.numeric();
			var expYearsSync = $.data(clone, "calc-driver-exp-yers");
			if (expYearsSync != null) {
				expYearsSync.initialize(expyersInput, startexpyersInput)
			}
			else {
				expYearsSync = new StartDateAndDurationSync(expyersInput, startexpyersInput);
				$.data(clone, "calc-driver-exp-yers", expYearsSync);
			}
			$("*[id^='firstYearOSAGO']", clone).bind("click", function(ev) {
				var eventElem = $(ev.currentTarget);
				var owner = eventElem.parents("fieldset");
				
				if (eventElem.checked())
				{
					$("*[id^='PreviousContractNumberOfLossesCont']", owner).hide().disable();
					$("*[id^='PreviousContractInsuranceClassCont']", owner).hide().disable();
				}
				else
				{
					$("*[id^='PreviousContractNumberOfLossesCont']", owner).show().enable();
					$("*[id^='PreviousContractInsuranceClassCont']", owner).show().enable();
				}
			});
		}
	},	

	OnBeforeCloning: function(clone)
	{
		var dateInputs = $("*[name^='InvolvedPersons_PhysicalPerson_BirthDay'], *[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_DrivingExperienceStartDate']", clone);
		InputMasks.ClearDatePicker(dateInputs);
	},

	OnAfterCloning: function(clone)
	{
		this.initializeClone(clone);
	},

	initializeClone: function(clone)
	{
		InputMasks.InitializeDatePickerForBirthday($("*[name^='InvolvedPersons_PhysicalPerson_BirthDay']", clone), 18, null);
		InputMasks.InitializeDatePicker($("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_DrivingExperienceStartDate']", clone), null, new Date());
	},
	
	OnInit: function(clone) {
		$("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_PreviousContractInsuranceClass']", clone).val("3");
		$("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_PreviousContractNumberOfLosses']", clone).val("0");
		var firstYearOSAGO = $("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_FirstYearOfUse']", clone);
		if ($('#firstYearOSAGO1').is(':enabled:checked')) {
			$("*[id^='PreviousContractNumberOfLossesCont'],*[id^='PreviousContractInsuranceClassCont']", clone).show().enable();
			$("*[name^='QuotationCriteria_AdmittedDrivers_DriverInfo_FirstYearOfUse']", clone).removeAttr("checked");
		}
	}
};

DependOptions.prototype._do = function(dependentValue)
{
	var id = this.node.id;
	var dispatcher = {};
	var dataName = this.dataType;

	var data = this.callBack(this.node.value);
	var fullList = data[dataName];
	var list = fullList[this.node.value];
	if (!list)
		return;

	this.depNode.options.length = 0;
	if (list.length == 0)
	{
		//opt = document.createElement("option");
		//opt.value = this.node.value;
		//opt.innerHTML = this.node.value;
		//this.depNode.appendChild(opt);
		$(this.depNode).parent().css('display', 'none')
	}
	else
	{
		for (var i = 0, l = list.length, opt; i < l; i++)
		{
			if (list[i])
			{
				opt = document.createElement("option");
				opt.value = list[i][0];
				opt.innerHTML = list[i][1];

				if (dependentValue != null)
				{
					if (dependentValue == opt.value)
					{
						opt.selected = 'selected';
					}
				}

				this.depNode.appendChild(opt);
			}
		}
		$(this.depNode).parent().css('display', 'block')
	}
}

