﻿Ext.ns("eKonx.RieltObjectsEditor");

eKonx.RieltObjectsEditor.Create = function (rowData)
{
	var isCreatedOEditAll = (rowData.CreatedByUserID == eKonx.Cache.User.ID || eKonx.CurrentUser.Permissions.CanEditAllRieltObjects);
	if (!eKonx.Cache.FormOptions)
	{
		eKonx.Cache.FormOptions = [];
	}
	if (!eKonx.Cache.FormOptions[rowData.RieltObjectTypeID])
	{
		eKonx.Cache.FormOptions[rowData.RieltObjectTypeID] = [];
	}
	if (!eKonx.Cache.FormOptions[rowData.RieltObjectTypeID][rowData.BusinessActionTypeID])
	{
		eKonx.Cache.FormOptions[rowData.RieltObjectTypeID][rowData.BusinessActionTypeID] = eKonx.Json(
			"Cache/GetFormFields",
			{
				BusinessActionTypeID: rowData.BusinessActionTypeID,
				RieltObjectTypeID: rowData.RieltObjectTypeID
			});
	}

	var w = new Ext.Window(
	{
		width: 700,
		height: 500,
		modal: true,
		resizable: false,
		title: eKonx.Cache.FormOptions[rowData.RieltObjectTypeID][rowData.BusinessActionTypeID].Title,
		items:
		[
			{
				xtype: "tabpanel",
				border: false,
				activeTab: 0,
				height: 443,
				items:
				[
					rieltForm = new eKonx.FormProcessor(
					{
						readUrl: "Objects/GetRealEstateObject",
						saveUrl: "Objects/SaveRealEstateObject",
						FormOptions: eKonx.Cache.FormOptions[rowData.RieltObjectTypeID][rowData.BusinessActionTypeID],
						title: "Информация об объекте",
						//layout: "fit",
						//height: 415,
						//autoHeight: true,
						autoScroll: true,
						params: { id: rowData.ID },
						listeners:
						{
							formCreating: function (frmCfg)
							{
								if (frmCfg.area.NestedPropertyName == 'Owner')
								{
									frmCfg.tools = frmCfg.tools || [];
									frmCfg.tools.push(
									{
										id: 'search',
										qtip: 'Найти владельца в адресной книге',
										handler: function (ev, toolEl, panel)
										{
											if (isCreatedOEditAll)
											{
												//lookup user
											}
										}
									});
								}
								return true;
							},
							formCreated: function (frm)
							{
								var notOwnerAndNotSeller = !(eKonx.CurrentUser.Permissions.CanEditAllRieltObjects || eKonx.CurrentUser.ID == rowData.CreatedByUserID);
								if (notOwnerAndNotSeller)
								{
									frm.on("afterrender", function ()
									{
										frm.makeFieldsReadOnly();
									});
								}
								//seller is disabled forever
								if (frm.area.NestedPropertyName == 'Seller')
								{
									frm.on("afterrender", function ()
									{
										frm.makeFieldsReadOnly();
									});
								}

								//hide fields which is not visible
								if (frm.area.NestedPropertyName == "Address")
								{
									frm.on("afterrender", function ()
									{
										eKonx.RieltObjectsEditor.CascadeAddress(frm);
										if (notOwnerAndNotSeller)
										{
											frm.findBy(function (fld)
											{
												if (fld.dataIndex == "BuildingLetter" ||
												fld.dataIndex == "BuildingNumber" ||
												fld.dataIndex == "Street")
												{
													fld.hideContainer();
												}
												return false;
											});
										}
									});
								}
								if (frm.area.NestedPropertyName == 'Owner')
								{
									if (notOwnerAndNotSeller)
									{
										frm.on("afterrender", function ()
										{
											frm.hide();
										});
									}
								}
							},
							fieldChanged: function (fld, value)
							{
								if (eKonx.CurrentUser.Permissions.CanChangeRieltObjectsStatus)
								{
									verified.enable();
								}
							}
						}
					}),
					uploader = new eKonx.FileUploader(
					{
						height: 415,
						title: eKonx.Res.Common.Files,
						getFileListUrl: eKonx.Urls.RieltObjects.GetFilesList,
						getFileListParams: { AddressID: rowData.ID },
						onServerAction: "eKonx.Controllers.ObjectsController.FileAction",
						AddressID: rowData.ID,
						onServerActionArgs:
						{
							AddressID: rowData.ID
						}
					})
				]
			}
		],
		bbar:
		[
			"->",
			'-',
			verified = new Ext.Button(
			{
				text: 'Проверен',
				iconCls: 'silk-accept',
				width: 90,
				disabled: !(rowData.Verified === false && eKonx.CurrentUser.Permissions.CanChangeRieltObjectsStatus),
				handler: function ()
				{
					rieltForm.Data.SetVerified = true;
					this.disable();
				}
			}),
			'-',
			{
				text: "Сохранить",
				iconCls: "icon-save",
				disabled: !isCreatedOEditAll,
				width: 90,
				handler: function ()
				{
					rieltForm.save(
						function ()
						{
							//before submit
							//debugger;
							return { obj: Ext.util.JSON.encode(rieltForm.Data) };
						},
						function ()
						{
							eKonx.Mediator.fireEvent(eKonx.Events.RieltObjectChanged, rieltForm.Data);
							if (Ext.state.Manager.get("doNotShowobjectSaveSuccessDialog") !== true)
							{
								Ext.Msg.show(
								{
									title: 'Сохранение',
									msg: 'Объект сохранён',
									icon: Ext.Msg.INFO,
									buttons:
									{
										ok: 'Ok',
										cancel: 'Больше не показывать'
									},
									minWidth: 300,
									fn: function (buttonId)
									{
										if (buttonId == 'cancel')
										{
											Ext.state.Manager.set("doNotShowobjectSaveSuccessDialog", true);
										}
									}
								});
							}
						});
				}
			},
			"-",
			{
				text: "Выход",
				iconCls: "silk-cancel",
				width: 90,
				handler: function ()
				{
					w.close();
				}
			}
		]
	});
	uploader.Load();
	return w;
}


eKonx.RieltObjectsEditor.CascadeAddress = function (frm)
{
	var countryCombo = null, country = null;
	var regionCombo = null, region = null;
	var cityCombo = null, city = null;
	var areaCombo = null;
	frm.findBy(function (fld)
	{
		if (fld.dataIndex == "CountryID") countryCombo = fld;
		if (fld.dataIndex == "RegionID") regionCombo = fld;
		if (fld.dataIndex == "CityID") cityCombo = fld;
		if (fld.dataIndex == "AdministrativeAreaID") areaCombo = fld;
	});
	//debugger;
	regionCombo.setParent(
		countryCombo,
		function (parent, v)
		{
			country = eKonx.Cache.Countries.findByID(v);
			if (!Ext.isDefined(country.Regions))
			{
				country.Regions = eKonx.Json("Cache/GetRegions", { CountryID: v });
			}
			return country.Regions;
		});

	//cityCombo.store.reader.getRoot = function (o) { return o; };
	cityCombo.setParent(
		regionCombo,
		function (parent, v)
		{
			region = country.Regions.findByID(parent.getValue());
			if (!Ext.isDefined(region.Cities))
			{
				region.Cities = eKonx.Json("Cache/GetCities", { RegionID: v });
			}
			return region.Cities;
		});

	//areaCombo.store.reader.getRoot = function (o) { return o; };
	areaCombo.setParent(
		cityCombo,
		function (parent, v)
		{
			city = region.Cities.findByID(v);
			if (!Ext.isDefined(city.AdministrativeAreas))
			{
				city.AdministrativeAreas = eKonx.Json("Cache/GetAdministrativeAreas", { CityID: v });
			}
			return city.AdministrativeAreas;
		});

	//countryCombo.setValue(countryCombo.getValue());
	//GetAdministrativeAreas
}
