﻿function InsuranceApplicationForm(options) {
	var self = this;
	this.options = options;
	this.Initialize();
}

InsuranceApplicationForm.instance = null;

InsuranceApplicationForm.CreateInstance = function (options, forceRecreate, actionSource, openForm) {
	if (InsuranceApplicationForm.instance == null || forceRecreate) {
		InsuranceApplicationForm.instance = new InsuranceApplicationForm(options);
	}
	if (openForm) {
		InsuranceApplicationForm.OpenInstance(actionSource);
	}
}

InsuranceApplicationForm.OpenInstance = function (actionSource) {
	if (InsuranceApplicationForm.instance != null) {
		InsuranceApplicationForm.instance.Open(actionSource);
	}
}

InsuranceApplicationForm.DeleteInstance = function () {
	InsuranceApplicationForm.instance = null;
}

InsuranceApplicationForm.prototype =
{
	isOpened: false,

	CreateEmptyUserProfile: function () {
		var result =
		{
			lastName: "", firstName: "", middleName: "",
			phoneCityCode: "", phoneNumber: "", email: ""
		};
		return result;
	},

	Initialize: function () {
		var f = FormInPopup_InsuranceRequest;

		f.trim = function () {
			var email = $('#popup input[name=Email]');
			var trimmed = email.val().replace(/^\s*|\s*$/g, "");
			email.val(trimmed);
			return false;
		}

		f.goToPage = this.options.submitHostUrl;

		// Initial quotation 
		var qc = this.options.initialQuotationCase;
		if (qc != null) {
			f.prototype.modeWithoutIncludedCases = false;
			f.prototype.orders[f.prototype.orders.length] =
			{
				insuranceProductType: qc.insuranceProductType,
				title: qc.displayName,
				name: "",
				summ: qc.premium,
				caseID: qc.caseID
			};
		}
		else {
			f.prototype.modeWithoutIncludedCases = true;
			f.prototype.insuranceProductType = this.options.insuranceProductType;
		}

		f.prototype.isAuth = !this.options.isUserAuthenticated;

		var userProfile = this.options.userProfile != null ? this.options.userProfile : this.CreateEmptyUserProfile();

		// Получение регионов для поля Регион нахождения организации/филиала
		var isOpo = f.prototype.insuranceProductType && (f.prototype.insuranceProductType.id == 'Opo' || 
			f.prototype.insuranceProductType.id == 'OpoHydraulicStructures' || 
			f.prototype.insuranceProductType.id == 'OpoMandatoryInsurance');
		
		var regions = {};		
		if (isOpo)	{
			$.ajax({
			  url: '/xml/regions.wbp',
			  success: function(data) { regions = data; },
			  async: false,
			  dataType: 'json'
			});
		}
		
		f.prototype.fields = [
			{
				name: "LastName", title: "Фамилия<span class=\"req\">*</span>", type: "string", req: true,
				container: "inputWrapper", errorTarget: "error", defaultValue: userProfile.lastName
			},
			{
				name: "FirstName", title: "Имя<span class=\"req\">*</span>", type: "string", req: true,
				container: "inputWrapper", errorTarget: "error", defaultValue: userProfile.firstName
			},
			{
				name: "MiddleName", title: "Отчество", type: "string", req: false,
				container: "inputWrapper", errorTarget: "error", defaultValue: userProfile.middleName
			}];
			
		f.prototype.rules = {
			LastName: { required: true, fio:true, rangelength: [2, 50] },
			FirstName: { required: true, fio:true, rangelength: [2, 50] },
			MiddleName: { fio:true, rangelength: [2, 50] }
		};
		
		if (isOpo) {			
			f.prototype.fields.push(	
				{
					name: "Region", title: "Регион нахождения организации/филиала<span class=\"req\">*</span>", cssClass: "popupSelect", type: "string", req: true,
					container: "inputWrapper", errorTarget: "error", 
					select: "true", values: regions
				});
			f.prototype.rules.Region = { required: true };
		}
		f.prototype.fields = f.prototype.fields.concat([			
			{
				name: "ContactPhoneCityCode", title: "Код города<span class=\"req\">*</span>", type: "int-chars", req: true,
				container: "inputWrapper", errorTarget: "phoneCodeError",
				defaultValue: userProfile.phoneCityCode,
				isPhoneCode: true
			},
			{
				name: "ContactPhoneNumber", title: "Телефон<span class=\"req\">*</span>", type: "phone", req: true,
				container: "inputWrapper", errorTarget: "error",
				defaultValue: userProfile.phoneNumber,
				phoneCode: "ContactPhoneCityCode",
				isPhone: true
			},
			{
				name: "Email", title: "Эл. почта", type: "email", req: { fn: FormInPopup_InsuranceRequest.trim, args: [{}] },
				container: "inputWrapper", errorTarget: "error", defaultValue: userProfile.email
			},
			{
				name: "ContactDate", title: "Предпочитаемая дата контакта<span class=\"req\">*</span>",
				type: "dateFromNow", req: true,
				container: "inputWrapper", errorTarget: "error"
			},
			{
				name: "Comment", title: "Комментарии<br/><span style=\"font-size:smaller\">(предпочитаемое время контакта, часовой пояс и др.)</span>", type: "string", req: false,
				container: "inputWrapper", errorTarget: "error", textarea: 'true'
			}			
		]);
		f.prototype.rules.ContactPhoneCityCode = { required: true, digits:true, rangelength: [3, 7] };
		f.prototype.rules.ContactPhoneNumber = { required: true, digits:true, validPhone: true };
		f.prototype.rules.Email = { email: true };
		f.prototype.rules.ContactDate = { required: true, date:true, min: new Date() };
		
		
		if (isOpo) {
			f.prototype.fields.push({
				name: "AttachedFile_100_1",  title: "Приложить файл (до 4 MБ)", fileUploaderNumber: 100, type: "string", req: false,
				container: "inputWrapper", errorTarget: "error", file: 'true'
			});
		} else {
			// Вводим проверку на то, что выбранная дата не является выходным днем для всех заявок, кроме ОПО
			f.prototype.rules.ContactDate.holiday = true;
		}

		if (this.options.disablePrivateCabinet) {
			f.prototype.strings.orderDescription = null;
			f.prototype.strings.orderHeader = "Расчеты";
			f.prototype.strings.quotationCaseIsAlreadyAddedToInsuranceApplication = "Расчет c ID = {0} уже был  отправлен с заявкой на страхование."
			f.prototype.strings.sheduleCaption = "Когда мы позвоним";
			f.prototype.strings.sheduleMessage = " мы всегда стремимся перезвонить вам сразу после получения заявки. Тем не менее, если вы оставили заявку после 18:00 (Мск) в будний день или в выходные, то мы свяжемся с вами на следующий будний день.";
		}
	},

	Open: function (actionSource) {
		if (!this.isOpened) {
			var self = this;
			this.isOpened = true;
			createPopupForm(FormInPopup_InsuranceRequest, actionSource, function () { self.isOpened = false; });
		}
	}
}

function FormInPopup_InsuranceRequest(fn_insert, actionSource) {
	actionSource = actionSource || 'Unknown';
	if (!window.InsuranceRequestAction) {
		window.InsuranceRequestAction = 'SubmitApplication';
	}
	var dublicate = this;
	var formId = "popupForm-" + String(Math.random()).substring(2);
	this.form = formId;
	
	var nodes = {
		container: $('<form method="post" enctype="multipart/form-data" action="' + ((FormInPopup_InsuranceRequest.goToPage) ? FormInPopup_InsuranceRequest.goToPage : '') + '/policierequest.wbp" id="' + formId + '" class="calculator" />'),
		submitName: '<input type="hidden" value="true" name="SubmitApplication" />',
		actionSource: "<input type='hidden' value='" + actionSource + "' name='ActionSource' />",
		Action: "<input type='hidden' value='" + InsuranceRequestAction + "' name='Action' />",
		fields: {
			container: $("<div class='section' />"),
			h: $("<h2>" + this.strings.contactsInfo + "</h2>"),
			wrapers: []
		},
		separator: $("<div class='separator' />"),
		order: {
			container: $("<div class='section' />"),
			includedCasesCount: '<input type="hidden" value="" name="IncludedCasesCount" id="includedCasesCountFld" />',
			h: $("<h2>" + this.strings.orderHeader + "</h2>"),
			desc: this.strings.orderDescription ? $("<p style='padding-left: 1px'>" + this.strings.orderDescription + "</p>") : null,
			ol: $("<ol class='order'> </ol>"),
			items: []
		}
	};
	
	
	// Данные для валидации заявки
	var validationObj = {
		onsubmit: true,
		errorElement: 'span',
		messages: {
			LastName: { required: 'Введите фамилию.', fio: 'Допускаются только буквы, тире и пробелы.', rangelength: 'От 2 до 50 символов.' },
			FirstName: { required: 'Введите имя.', fio: 'Допускаются только буквы, тире и пробелы.', rangelength: 'От 2 до 50 символов.' },
			MiddleName: { fio: 'Допускаются только буквы, тире и пробелы.', rangelength: 'От 2 до 50 символов.' },
			Region: { required: 'Выберите регион.' },
			Email: { email: 'Введите корректный адрес электронной почты.'},
			ContactPhoneCityCode: { required: 'Введите код города.', digits: 'Введите корректное число.', rangelength: 'Код города: от 3 до 7 символов.' },
			ContactPhoneNumber: { required: 'Введите номер телефона.', digits: 'Введите корректное число.', maxlength: 'Телефон должен содержать не более {0} символов.', validPhone: 'Введите правильный номер телефона - 10 цифр.' },
			ContactDate: { required: 'Введите предпочитаему дату контакта.', date: 'Введите корректную дату.', min: 'Дата не должна быть в прошлом.' }
		},
		highlight: function (element, errorClass, validClass) {
			$(element).addClass(this.settings.invalidFieldClass)
			.closest(this.settings.container).addClass(this.settings.containerErrorClass);
			fn_insert();
		},
		unhighlight: function (element, errorClass, validClass) {
			$(element).removeClass(this.settings.invalidFieldClass);
			var parent = $(element).closest(this.settings.container);
			if (parent.find("." + this.settings.invalidFieldClass).length == 0) {
				parent.removeClass(this.settings.containerErrorClass);
			}
			fn_insert();
		}		
	};

	if (InsuranceRequestAction !== 'AddFiles') {
		validationObj.rules = this.rules;
	}

	var caseIDLength = 7;

	this.fixPopupBordersHeight = function () {
		var newCont = $('#popup .content');
		var contHeight = newCont.height() + parseInt(newCont.css('padding-top')) + parseInt(newCont.css('padding-bottom'));
		$('#popup .contentLeft,#popup .contentRight').height(contHeight);
	};

	this.CreateAddAnotherQuotationSection = function () {
		return $('<div class="inputWrapper addCaseID"><label>Добавить еще один расчет</label><input id="idpolicieFld" value="" maxLength="' + caseIDLength + '"/><div class="error"/></div><div id="addButton" class="doSend addPolicieIDButton"><div class="left"><div class="right"><input id="addPolicieIDButton" type="button" value="Добавить"/><br/></div></div></div><div class="clear"/>');
	}

	this.CreateHiddenInput = function (name, value) {
		var elt = $("<input />");
		elt.attr("type", "hidden");
		elt.attr("name", name);
		elt.attr("value", value);
		return elt;
	}

	this.init = function () {
		var showOrders = !this.modeWithoutIncludedCases;
		var showInsuranceProductType = this.modeWithoutIncludedCases;

		var c = nodes.container;
		c.append(nodes.submitName);
		c.append(nodes.actionSource);
		c.append(nodes.Action);

		var initialInsuranceProductType;
		if (this.modeWithoutIncludedCases) {
			initialInsuranceProductType = this.insuranceProductType.id;
		}
		else if (this.orders.length > 0) {
			initialInsuranceProductType = this.orders[0].insuranceProductType;
		}
		c.append("<input type='hidden' value='" + initialInsuranceProductType + "' name='InitialInsuranceProductType' />");

		var sourcePageType = (typeof (isCalculatorPage) != "undefined" && isCalculatorPage) ? "CalculatorPage" : "NonCalculatorPage";
		c.append("<input type='hidden' value='" + sourcePageType + "' name='SourcePageType' />");

		c.append(this.CreateHiddenInput("IsPublicArea", typeof (isPublicArea) != "undefined" && isPublicArea));

		if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
			c.append("<style>#popup .calculator .error { display: none !important; } #popup .calculator .with-error .error {display: block !important; } </style>");
		}

		
		var isOpo = this.insuranceProductType && (this.insuranceProductType.id == 'Opo' || 
			this.insuranceProductType.id == 'OpoHydraulicStructures' || 
			this.insuranceProductType.id == 'OpoMandatoryInsurance');
			
		if (showInsuranceProductType) {
			var d = $("<div id='insuranceApplicationProductTypeSection' />");
			d.append("<h2>Заявка</h2>");
			d.append("<div class='inputWrapper'><label>" + (isOpo ? "Вид страхования" : "Продукт") + "</label><label id='insuranceApplicationProductType'>" + this.insuranceProductType.displayName + "</label></div>");
			d.append("<input type='hidden' value='" + this.insuranceProductType.id + "' name='InsuranceProductTypeID' />");
			d.append("<div class='clear' />");
			c.append(d);
		}
		
		if (InsuranceRequestAction !== 'AddFiles') {
			with (nodes.fields) {
				container.append(h);
				c.append(container);
			};
			nodes.fields.wrapers.push(fillFields(this.fields, nodes.fields.container));
			nodes.fields.container.append($("<div class='clear' />").css("height", "20px"));
		}

		if (showOrders) {
			if (InsuranceRequestAction !== 'AddFiles') c.append(nodes.separator);

			with (nodes.order) {
				container.append(h);
				if (isPublicArea) {
					container.append(desc);
				}
				container.append(ol);
				container.append(includedCasesCount);
				c.append(container);
			};

			nodes.order.items.push(fillOrder.call(this, ((InsuranceRequestAction !== 'AddFiles') ? this.orders : InitialInsuranceApplications[InitialInsuranceApplicationCaseId]), nodes.order.ol));

			if (isPublicArea) {
				var section = this.CreateAddAnotherQuotationSection();
				nodes.order.container.append(section);
			}
		}

		fn_insert(nodes.container);
		
		if (showOrders) {
			$('#includedCasesCountFld').val(this.orders.length);
		}

		// Включение валидации формы
		if ($.fn.validate){
			this.validator = $("#" + this.form).validate(validationObj);
			$.validator.addMethod('validPhone', function (value) {
				return $('#RequestContactPhoneCityCode').val().length + $('#RequestContactPhoneNumber').val().length == 10;
			}, '');
		}
		//$('#RequestContactPhoneCityCode, #RequestContactPhoneNumber').number();
		
		if (InsuranceRequestAction !== 'AddFiles') {
			var datepickerSelector = "";
			for (var key in FormInPopup_InsuranceRequest.prototype.needDatePicker.fields) {
				datepickerSelector += "#popup input[name='" + key + "']";
			}
			InputMasks.InitializeDatePicker($(datepickerSelector), new Date(), null, null, !isOpo);

			SetTextAreaMaxLengthChecking(".popupTextarea", 2500);
		}
		
		var m = $('<div />');	
		m.append($('<strong />').text(this.strings.sheduleCaption));
		m.append(this.strings.sheduleMessage).css('color', '#666666').css('width', '580px').css('margin', '8px 0 8px 1px');
		c.append("<div class='clear' />");
		c.append(m);		
		dublicate.fixPopupBordersHeight();
		
		if (showOrders) {
			if (isPublicArea) {
				var button = $('#addPolicieIDButton');
				var input = $('#idpolicieFld');

				button[0].thisObj = this;
				button.click(function () {
					if (dublicate.quotationNotFoundPopup != null) {
						dublicate.quotationNotFoundPopup.doHide();
					}

					button[0].thisObj = this;
					var inputWrapperElt = $(".addCaseID");
					var validationErrorElt = $(".error", inputWrapperElt);

					var caseID = input.val();

					var validationErrorMessage = null;

					if (caseID.length == 0) {
						validationErrorMessage = "Введите номер расчета.";
					}
					else if (!/^\d{7}$/.test(caseID)) {
						validationErrorMessage = "Номер расчета должен состоять из 7 цифр.";
					}

					if (validationErrorMessage != null) {
						validationErrorElt.show();
						validationErrorElt.text(validationErrorMessage);
						inputWrapperElt.addClass("with-error");
						dublicate.fixPopupBordersHeight();
					}
					else {
						validationErrorElt.hide();
						inputWrapperElt.removeClass("with-error");
						dublicate.fixPopupBordersHeight();

						dublicate.TryAddQuotationCase(caseID);
					}
				});
			}
			else {
				var allquotes;
				if (InsuranceRequestAction !== 'AddFiles') {
					allquotes = eval("(" + $.ajax({ type: "GET", url: '/xml/all_quotations.wbp', async: false }).responseText + ")");
				} else {
					allquotes = InitialInsuranceApplications[InitialInsuranceApplicationCaseId];
				}
				var ziz = $('#addPolicieIDButton')[0];
				for (var i = 0, l = allquotes.length; i < l; i++) {
					if (allquotes[i]['caseID'] != '') {
						dublicate.orders[dublicate.orders.length] = allquotes[i];
						$(nodes.order.ol).empty();
						fillOrder.call(dublicate, ((InsuranceRequestAction !== 'AddFiles') ? dublicate.orders : InitialInsuranceApplications[InitialInsuranceApplicationCaseId]), nodes.order.ol);
						$('#includedCasesCountFld').val(dublicate.orders.length);
					}
				};
			}
		}
	};

	this.FindQuotationCase = function (caseID) {
		var params = { CaseType: "Quotation", CaseID: caseID };
		var url = "/xml/quotations.wbp";

		var result;

		var ajaxOptions =
				{
					url: url,
					data: params,
					dataType: "json",
					async: false,
					success: function (data) { result = data; }
				};

		$.ajax(ajaxOptions);

		return result;
	},

	this.TryAddQuotationCase = function (caseID) {
		var findResult = this.FindQuotationCase(caseID);

		var errorMessage;

		if (findResult != null && findResult.caseData != null) {
			var data = findResult.caseData;

			if (data.insuranceApplicationCaseID != null) {
				errorMessage = this.strings.quotationCaseIsAlreadyAddedToInsuranceApplication;
			} else if(data.Compatibility == "IsObsolete") {
				errorMessage = this.strings.quotationCaseIsObsolete;			
			} else if(data.Compatibility == "IsIncompatibility"){
				errorMessage = this.strings.quotationCaseIsIncompatibility;				
			} else{
				var newOrder = true;
				for (var i = 0, arr = this.orders, l = arr.length; i < l; i++) {
					if (arr[i].caseID == data.caseID) {
						newOrder = false;
						break;
					}
				}

				if (newOrder) {
					this.orders[this.orders.length] = data;
					$(nodes.order.ol).empty();
					fillOrder.call(dublicate, ((InsuranceRequestAction !== 'AddFiles') ? dublicate.orders : InitialInsuranceApplications[InitialInsuranceApplicationCaseId]), nodes.order.ol);
					dublicate.fixPopupBordersHeight();
					$('#includedCasesCountFld').val(dublicate.orders.length);
				}
				else {
					errorMessage = this.strings.quotationCaseIsAlreadyAdded;
				}
			}
		}
		else {
			errorMessage = this.strings.quotationCaseNotFound;
		}

		if (!String.IsNullOrEmpty(errorMessage)) {
			var messagePopup = new PopUp('', 'alert', errorMessage.replace("{0}", caseID), 'Сообщение');
			messagePopup.modal = true;
			messagePopup.setButtonText({ 'ok': 'Да' });
			messagePopup.setContainer("userNotificationCalcPopup");

			this.quotationNotFoundPopup = messagePopup;
			this.quotationNotFoundPopup.show(this.quotationNotFoundPopup);
		}
	},

	this.finallize = function () {
		if (this.quotationNotFoundPopup != null) {
			this.quotationNotFoundPopup.doHide();
			$("#userNotificationCalcPopup").remove();
		}
	};

	this.requestPolicieData = function () {
		var id = $('#idpolicieFld').attr('value');
		var url = '/xml/quotations.wbp?CaseType=Quotation&CaseID=' + id;
		var response = $.ajax({ type: "GET", url: url, async: false });
		FormInPopup_InsuranceRequest.prototype.orders = eval("(" + response.responseText + ")");
		fillOrder.call(this, ((InsuranceRequestAction !== 'AddFiles') ? this.orders : InitialInsuranceApplications[InitialInsuranceApplicationCaseId]), nodes.order.ol);
	};

	function fillFields(data, parent) {
		var wraper, label, field, er, d, ret = [], needDatePicker;
		for (var i = 0, l = data.length; i < l; i++) {
			d = data[i];
			d.afterShowError = fn_insert;
			d.afterHideError = fn_insert;
			needDatePicker = FormInPopup_InsuranceRequest.prototype.needDatePicker(d.name);
			wraper = $("<div class='" + d.container + "' />");
			label = $("<label>" + d.title + "</label>");
			if (d.select) {
				input = $("<select class='" + (d.cssClass ? d.cssClass : "popupTimeSelect") + "' name='" + d.name + "' ></select>");
				input.append( $('<option value="">Выберите...</option>'));
				for (var k in d.values){
					input.append( $('<option value=\"' + (k ? d.values[k] : "") + '\">' + d.values[k] + '</option>'));
				}			
				//input += "</select>"
			} else if (d.textarea) {
				input = "<textarea class='popupTextarea' name='" + d.name + "' style='float: left;'></textarea><div class='clear'></div>";
			} else if (d.file) {
				input = "<input type='hidden' class='AttachedFilesCount' name='AttachedFilesCount_" + d.fileUploaderNumber + "' value='0' />";
				input += "<input type='file' class='AttachedFile' name='" + d.name + "' style='margin-top:0px; position:relative; top:14px;'" + ($.browser.mozilla ? "size='36'" : ($.browser.safari ? "" : "style='width:314px;'")) + "></input>";
			} else if (d.isPhoneCode) {
				continue;
			} else if (d.isPhone) {
				// Поиск соответствующего кода, среди полей
				var code;
				for (var j = 0, l = data.length; j < l; j++) {
					if ( data[j].name == d.phoneCode ) {
						code = data[j];
						break;
					};
				}
				
				if (code) {
					input = "<span class='inline'>+7 ( </span>";
					// Поле код города
					input += "<input class='phoneCode' name='" + code.name + "' id='Request" + code.name + "' type='text'";
					if (typeof (code.min) == "number") input += " minlength='" + code.min + "'";
					if (typeof (code.max) == "number") input += " maxlength='" + code.max + "'";
					input += ' onchange="' +
						"$('#RequestContactPhoneNumber').attr('maxlength', 10 - $(this).val().length)" +
						'" />';
					
					input += "<span class='inline'> ) </span>";				
				} else input = "";
				
				// Поле телефон
				input += "<input class='phone' name='" + d.name + "' id='Request" + d.name + "' type='text'";
				if (typeof (d.min) == "number") input += " minlength='" + d.min + "'";
				if (typeof (d.max) == "number") input += " maxlength='" + d.max + "'";
				input += " />";
				if (code) input += "<span class='" + code.errorTarget + "'></span>"; 
			} else {
				input = "<input name='" + d.name + "' type='text'";
				if (typeof (d.min) == "number") input += " minlength='" + d.min + "'";
				if (typeof (d.max) == "number") {
					input += " maxlength='" + d.max + "'";
				}
				if (d.name === "ContactPhoneNumber") {
					input += " id='RequestContactPhoneCityCode'";
				}
				if (d.name === "ContactPhoneCityCode") {
					input += ' onchange="' +
					"$('#RequestContactPhoneCityCode').attr('maxlength', 10 - $(this).val().length)" +
					'"';
				}
				if (typeof (d.defaultValue) == "string") input += " value='" + d.defaultValue + "'";
				input += " />";
				if (needDatePicker) {
					input += "<div class='datepickerButton datepickerButton-in-insurance-request'> </div>";
				}
			}
			input = $(input);

			er = $("<span class='" + d.errorTarget + "'></span>");
			wraper.append(label);
			wraper.append(input);
			wraper.append(er);
			if (d.file) {
				wraper.find(".AttachedFile").change(function(){
					$(this).parent().find('.AttachedFilesCount').val($(this).val() ? 1 : 0);
				});
			}
			if (d.select) {
				wraper.append("<div class='clear' />");
			}
			parent.append(wraper);
			ret.push(wraper);
		}

		return ret;
	};

	function fillOrder(data, parent) {
		var li,
			status,
				title, block,
					name, summ,
				toggler,
			files,
				fHeader, fList, fButton, filesCount;
		var d, ret = [];
		for (var i = 0, l = data.length; i < l; i++) {
			d = data[i];

			li = $("<li />");
			num = $("<span class='o-num'>" + (i + 1) + ".</span>");
			status = $("<span class='o-status' />");
			title = $("<strong class='o-title'>" + d.title + " (ID: " + d.caseID + ")</strong>");
			block = $("<span  class='o-fio-and-summ' />");
			name = $("<span class='o-name'>" + d.name + "</span>");
			summ = $("<span class='o-summ'><strong>" + Math.roundNumber(parseFloat(d.summ), 2) + "</strong>&#160;" + this.strings.orderCurrency + "</span>");
			filesCount = $("<input type='hidden' name='AttachedFilesCount_" + (i + 1) + "' value='0' />");
			if (!isPublicArea) {
				toggler = $("<a class='o-toggler'>" + this.strings.orderShow + "</a>");
			}
			files = $("<div class='order-files' />").css("display", "none");
			fHeader = $("<strong>" + this.strings.filesHeader + "</strong>");
			fList = $("<div />");
			fButton = $("<a>" + this.strings.filesAdd + "</a>");

			parent.append(
				li.append(
					status.append(num).append(title).append(
						block.append(name).append(summ)
					).append(toggler)
				).append(
					files.append(
						$("<div class='order-files-padding' />").append(fHeader).append(fList).append(fButton).append(filesCount)
					)
				).append(
					'<input type="hidden" name="IncludedCaseId_' + (i + 1) + '" value="' + d.caseID + '" />'
				).append('<input type="hidden" name="IncludedCaseType_' + (i + 1) + '" value="Quotation" />')
				.append('<input type="hidden" name="IncludedCaseInsuranceProductType_' + (i + 1) + '" value="' + d.insuranceProductType + '" />')
				.append('<input type="hidden" name="IncludedCaseInsuranceProgram_' + (i + 1) + '" value="' + d.InsuranceProgram + '" />')
			);

			//var fnAddFile = new FileList(toggler, fButton, files, fList, filesCount, "File"+d.caseID+"_", this.strings, fn_insert);
			var fnAddFile = new FileList(toggler, fButton, files, fList, filesCount, "AttachedFile_" + (i + 1), this.strings, fn_insert);

			ret.push(li);
		}
		return ret;

	}


	function FileList(toggler, addButton, container, filesContainer, filesCount, prefix, str, refresh) {
		if (!isPublicArea) {
			var count = 0;
			var visible = false;

			this.add = add;

			toggler[0].onclick = toggle;
			addButton[0].onclick = add;

			add();
		}

		function putCount() {
			for (var i = 0, arr = $("input", filesContainer), l = arr.length, summ = 0; i < l; i++) {
				if (arr[i].value != "") summ++;
			}
			filesCount[0].value = summ;
		}

		function add() {
			count++;
			var input = $("<input type='file' name='" + prefix + "_" + count + "' />")[0];
			var button = $("<img src='/media/system/imgs/delele-gray.gif' alt='Удалить' width='18' height='18' />")[0];
			var br = $("<br />")[0];
			filesContainer.append(input).append(button).append(br);
			input.onchange = putCount;
			button.onclick = function () {
				filesContainer[0].removeChild(input);
				filesContainer[0].removeChild(button);
				filesContainer[0].removeChild(br);
				if ($("input", filesContainer).length == 0) {
					hide();
					add();
				}
				count--;
				putCount();
				refresh();
			}
			refresh();
			putCount();
		}

		function hide() {
			if (!visible) return;
			container.css("display", "none");
			toggler.text(str.orderShow);
			visible = false;
			refresh();
		}

		function show() {
			if (visible) return;
			container.css("display", "block");
			toggler.text(str.orderHide);
			visible = true;
			refresh();
		}

		function toggle() {
			return (visible ? hide : show)();
		}

	}
}

FormInPopup_InsuranceRequest.prototype.needDatePicker = function (fieldName) {
	return FormInPopup_InsuranceRequest.prototype.needDatePicker.fields[fieldName];
};
FormInPopup_InsuranceRequest.prototype.needDatePicker.fields = { "ContactDate": true };

FormInPopup_InsuranceRequest.prototype.orders = [];
FormInPopup_InsuranceRequest.prototype.modeWithoutIncludedCases = false;

FormInPopup_InsuranceRequest.prototype.strings = {
	"contactsInfo": "Контактная информация",
	"orderHeader": "Расчеты и проекты полисов",
	"orderDescription": "Хотите создать заявку с дополнительными документами? (требуется авторизация)",
	"orderShow": "Подробнее",
	"orderHide": "Скрыть",
	"orderCurrency": "руб.",
	"filesHeader": "Дополнительные документы",
	"filesAdd": "Добавить документ",
	quotationCaseIsAlreadyAddedToInsuranceApplication: "Расчет/Проект полиса c ID = {0} уже был  отправлен с заявкой на страхование. Чтобы добавить документы по ранее отправленной заявке используйте форму деталей Расчета/Проекта полиса.",
	quotationCaseIsObsolete: "Расчет c ID = {0} является неактуальным и требует перерасчета.",
	quotationCaseIsIncompatibility: "Расчет c ID = {0} устарел и больше не поддерживается системой.",	
	quotationCaseNotFound: "Расчет c ID = {0} не найден. Проверьте, пожалуйста, корректность введенного номера расчета.",
	quotationCaseIsAlreadyAdded: "Расчет c ID = {0} уже добавлен в заявку.",
	sheduleMessage: " Мы всегда стремимся перезвонить вам сразу после получения заявки. Тем не менее, если вы оставили заявку после 18:00 (Мск) в будний день или в выходные, то мы свяжемся с вами на следующий будний день.",
	sheduleCaption: "Когда мы позвоним:"
};

// ?
FormInPopup_InsuranceRequest.prototype.fields = [
		{
			name: "LastName", title: "Фамилия", type: "string", req: true, min: 2, max: 50,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "FirstName", title: "Имя", type: "string", req: true, min: 2, max: 50,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "MiddleName", title: "Отчество", type: "string", req: true, min: 2, max: 50,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "ContactPhoneCityCode", title: "Код города", type: "int", req: true,
			container: "inputWrapper", errorTarget: "error",
			min: 3, max: 7,
			isPhoneCode: true
		},
		{
			name: "ContactPhoneNumber", title: "Телефон", type: "int", req: true,
			container: "inputWrapper", errorTarget: "error",
			min: {
				fn: FormInPopup_InsuranceRequest.prototype.dependStrongLength,
				args: [{ name: "ContactPhoneCityCode", role: "value" }, { value: 10}]
			},
			max: {
				fn: FormInPopup_InsuranceRequest.prototype.dependStrongLength,
				args: [{ name: "ContactPhoneCityCode", role: "value" }, { value: 10}]
			},
			phoneCode: "ContactPhoneCityCode",
			isPhone: true
		},
		{
			name: "Email", title: "E-mail", type: "email", req: true,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "ContactDate", title: "Предпочитаемая дата контакта", type: "date", req: false,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "ContactTimeBeginning", title: "Предпочитаемое время контакта С", type: "string", req: false,
			container: "inputWrapper", errorTarget: "error"
		},
		{
			name: "ContactTimeEnd", title: "Предпочитаемое время контакта По", type: "string", req: false,
			container: "inputWrapper", errorTarget: "error"
		}
	];
FormInPopup_InsuranceRequest.prototype.dependStrongLength = function (numInAnotherField, length) {
	return length - String(numInAnotherField).length;
}
// /?

function showPopupForm(validatePopupForm) {
	var popUp = new PopUp('', 'confirm', '', showPopupForm.strings.header);
	popUp.setButtonText(showPopupForm.strings.buttons);
	popUp.addResultListeners(validatePopupForm);
	popUp.show(popUp);
	return popUp;
}

showPopupForm.strings = {};
showPopupForm.strings.header = "Отправка заявки на страхование";
if (typeof (InsuranceRequestAction) === 'string' && InsuranceRequestAction === 'AddFiles') {
	showPopupForm.strings.header = "Дослать документы к заявке на страхование";
}
showPopupForm.strings.buttons = { "ok": "Отправить", "cancel": "Закрыть" };

var submitStarted = false;

function createPopupForm(class_formInPopup, actionSource, onClose) {
	var validatePopupForm =
	{
		popupNotify: function (okButton, evt) {
			if (!submitStarted) {
				var closeForm = true;

				if (okButton) {
					popUP.insert();

					var form = $('#' + formInPopup.form);
					if (($.fn.validate && form.valid()) || !$.fn.validate) {
						submitStarted = true;
						form.submit();
					}

					closeForm = false;
				}

				if (closeForm) {
					formInPopup.finallize();
					if (onClose) {
						onClose();
					};
				}
				else {
					evt.stop();
				}
			}
			else {
				evt.stop();
			}
		}
	};

	var popUP = showPopupForm(validatePopupForm);
	var formInPopup = new class_formInPopup(insert, actionSource);
	formInPopup.init();

	function insert(node) {
		return popUP.insert(node);
	}

	if (InsuranceRequestAction !== 'AddFiles') {
		var masks = new InputMasks();
		var contactDateInput = $("input[name=ContactDate]");
		contactDateInput.unmask().mask("39.19.9999");
		contactDateInput.val($.datepicker.formatDate("dd.mm.yy", (new Date())));
	}
}

function SetTextAreaMaxLengthChecking(selector, maxLength) {
	$(selector).keyup(function (event) {
		var el = $(this);

		var text = el.val();
		if (text.length > maxLength)
			el.val(text.substring(0, maxLength));

	}).bind("paste", function (e) {
		var el = $(this);

		if (maxLength != null) {
			setTimeout(
				function () {
					var text = el.val();
					if (text.length > maxLength)
						el.val(text.substring(0, maxLength));
				},
			0);
		}
	});
}

