app.controller('productsCtrl', ['$scope', '$rootScope', '$location', '$localStorage', 'requestServ', 'configServ', 'paginationConfig',
	function ($scope, $rootScope, $location, $localStorage, requestServ, configServ, paginationConfig) {

		// объявление переменных
		$scope.countProduct = [];
		$scope.priceProduct = [];
		$scope.resultPriceProduct = [];
		$scope.countSubProduct = {};
		$scope.disabledDecSubProduct = {};
		$scope.disabledIncSubProduct = {};
		$scope.modisSelect = {};
		$scope.priceSubProduct = {};
		$scope.resultPrice = [];
		$scope.maxValueProduct = 99;
		$scope.showMessage = false;
		$scope.idTimeout = '';
		$scope.lastIndex = 0;
		$scope.productInCategory = [];
		$scope.loadingMenu = false;
		$scope.loadingCart = false;
		$scope.loadingCatalog = false;
		$scope.loadRest = false;
		$scope.firstCategory = [];
		$scope.errorAdding = {};
		$scope.errorMinCount = {};
		$rootScope.loadCatalog = false;
		$rootScope.menuCategory = [];
		$rootScope.maxValueModi = [];
		$rootScope.maxValueModiGroup = {};
		$rootScope.currentCategory = '';
		$rootScope.menuCurrentCategory = [];
		$rootScope.menuCurrentCategory.item = [];
		$rootScope.GroupModi = {};
		$scope.restaurantArray = [];


		/* Локализация пагинации */
		paginationConfig.firstText = $rootScope.getLocale('First-page');
		paginationConfig.previousText = $rootScope.getLocale('Previous-page');
		paginationConfig.nextText = $rootScope.getLocale('Next-page');
		paginationConfig.lastText = $rootScope.getLocale('Last-page');

		// Настройки пагинации каталога
		$scope.currentPage = 1; // страница по умолчанию
		$scope.numPerPage = 6; // элементов на странице
		$scope.maxSize = 5; // max страниц в пагинации

		if ($rootScope.CartInfo.cartList.length) {
			$scope.lastIndex = $rootScope.CartInfo.cartList[$rootScope.CartInfo.cartList.length - 1].order;
		}

		$scope.addProductId = function (category) {
			category.items.forEach(function (item, i) {
				$scope.productInCategory[item.id] = item.dishes;

				if (item.items.length) {
					$scope.addProductId(item);
				} else {

					if (!$scope.firstCategory.length && $scope.firstCategory.id == undefined) {
						$scope.firstCategory = {
							id: item.id,
							name: item.name
						};
					}
				}
			});
		};

		$scope.GetResultPrice = function (index, idProduct, modisSelect, idCategory) {
			// получаем цену конкретного товара с модификаторами
			var modisSelect = modisSelect || false;
			var currentCategory = idCategory || $scope.currentCategory;

			$scope.resultPriceProduct[index] = $scope.priceProduct[idProduct];
			var allPriceProduct = $scope.priceSubProduct[idProduct];

			if (allPriceProduct && allPriceProduct.length) {
				allPriceProduct.forEach(function (item, i) {
					$scope.resultPriceProduct[index] =
						parseInt($scope.resultPriceProduct[index]) +
						parseInt($scope.countSubProduct[index][i] * $scope.priceSubProduct[idProduct][i]);
				});
			}

			var allPriceProductSelect = $scope.modisSelect[index];

			if (modisSelect) {
				var product = $scope.GetProduct(idProduct, currentCategory);
				if (product == undefined || product.modis == undefined) {
					return;
				}

				var allPriceProductSelectID = product.modis.selectModis;
				if (allPriceProductSelectID && allPriceProductSelectID.length) {
					product.modis.selectModis.forEach(function (item, i) {
						if (allPriceProductSelect[allPriceProductSelect[item.id]]) {
							$scope.resultPriceProduct[index] =
								parseInt($scope.resultPriceProduct[index]) +
								parseInt(allPriceProductSelect[allPriceProductSelect[item.id]]);
						}
					});
				}
			}
		};

		$scope.GetCategory = function (idCategory, name) {
			if ($rootScope.RestaurantMenu == undefined || $rootScope.RestaurantMenu.dishes == undefined || !$rootScope.RestaurantMenu.dishes.length) {
				return false;
			}

			$scope.currentCategory = idCategory;
			var nameCategory = name || '';
			var itemDishes = $rootScope.RestaurantMenu.dishes; // основные продукты
			var itemModis = $rootScope.RestaurantMenu.modifiers; // модификаторы
			var commonModis = $rootScope.RestaurantMenu.commonModifiers || {}; // модификаторы
			var tempArrayResult = [];

			//console.log('common');
			//console.log(commonModis);


			if ($rootScope.menuCategory[$scope.currentCategory] == undefined) {
				// если такой категории еще не создавалось
				$scope.productInCategory[idCategory].forEach(function (item, i) {
					var tempArray = itemDishes.filter(function (category) {
						return category.id == item;
					});

					if (tempArray[0] != undefined) {
						tempArrayResult.push(tempArray[0]);
					}
				});

				tempArrayResult.forEach(function (value, i) {
					// Базовые установки цен
					if (value != undefined && value.locres != undefined && value.locres.weight != undefined) {
						value.weight = value.locres.weight.split('/');
					}

					$scope.priceProduct[value.id] = value.price;
					$scope.resultPriceProduct[value.id] = value.price;
					$scope.countProduct[value.id] = 1;
					$scope.countSubProduct[value.id] = [];
					$scope.modisSelect[value.id] = [];
					$scope.priceSubProduct[value.id] = [];

					// проверяем на наличии модификаторов
					var addModis = $.grep(itemModis, function (item) {
						return item.id == value.modischeme;
					});

					addModis.forEach(function (modiGroup, indexModiGroup) {

						// разделяем модификаторы по типу
						if (modiGroup) {
							var selectModis = [];
							var inputModis = [];

							modiGroup.group.forEach(function (valueGroup, i) {

								if (valueGroup.downLimit == 1 && valueGroup.upLimit == 1) {
									// модификаторы в виде селектов
									selectModis.push(valueGroup);
									$scope.priceSubProduct[value.id][valueGroup.id] = 0;
									$scope.countSubProduct[value.id][valueGroup.id] = 1;

									valueGroup.modi.forEach(function (valueModi, i) {
										$scope.modisSelect[value.id][valueModi.id] = valueModi.price;
									});
								} else {
									// модификаторы в виде вводимых вручную текстовых полей
									inputModis.push(valueGroup);

									valueGroup.modi.forEach(function (valueModi, i) {
										$scope.countSubProduct[value.id][valueModi.id] = 0;
										$scope.priceSubProduct[value.id][valueModi.id] = valueModi.price;
									});
								}
							});

							if (commonModis[0]) {
								commonModis[0].group.forEach(function (itemCommonModis, indexCommonModis) {
									if (itemCommonModis.downLimit == 1 && itemCommonModis.upLimit == 1) {
										// модификаторы в виде селектов
										selectModis.push(itemCommonModis);
										$scope.priceSubProduct[value.id][itemCommonModis.id] = 0;
										$scope.countSubProduct[value.id][itemCommonModis.id] = 1;

										itemCommonModis.modi.forEach(function (valueModi, i) {
											$scope.modisSelect[value.id][valueModi.id] = valueModi.price;
										});
									} else {
										// модификаторы в виде вводимых вручную текстовых полей
										inputModis.push(itemCommonModis);

										itemCommonModis.modi.forEach(function (valueModi, i) {
											$scope.countSubProduct[value.id][valueModi.id] = 0;
											$scope.priceSubProduct[value.id][valueModi.id] = valueModi.price;
										});
									}
								});
							}

							modiGroup.selectModis = selectModis;
							modiGroup.inputModis = inputModis;
						}
					});


					if (!addModis.length) {
						// добавляем общие модификаторы (если обычных модификаторов не было добавлено)
						commonModis.forEach(function (modiGroup, indexModiGroup) {

							// разделяем модификаторы по типу
							if (modiGroup) {
								var selectModis = [];
								var inputModis = [];

								modiGroup.group.forEach(function (valueGroup, i) {

									if (valueGroup.downLimit == 1 && valueGroup.upLimit == 1) {
										// модификаторы в виде селектов
										selectModis.push(valueGroup);
										$scope.priceSubProduct[value.id][valueGroup.id] = 0;
										$scope.countSubProduct[value.id][valueGroup.id] = 1;

										valueGroup.modi.forEach(function (valueModi, i) {
											$scope.modisSelect[value.id][valueModi.id] = valueModi.price;
										});
									} else {
										// модификаторы в виде вводимых вручную текстовых полей
										inputModis.push(valueGroup);

										valueGroup.modi.forEach(function (valueModi, i) {
											$scope.countSubProduct[value.id][valueModi.id] = 0;
											$scope.priceSubProduct[value.id][valueModi.id] = valueModi.price;
										});
									}
								});

								modiGroup.selectModis = selectModis;
								modiGroup.inputModis = inputModis;
							}

							value.modischeme = 1;
						});
					}


					if (!$rootScope.isCart) {
						$scope.GetResultPrice(value.id, value.id);
					}

					if (addModis.length) {
						value.modis = addModis[0] || [];
					} else {
						value.modis = commonModis[0];
					}
				});

				$rootScope.menuCategory[$scope.currentCategory] = {
					name: nameCategory,
					items: tempArrayResult
				};
			}

			$rootScope.menuCurrentCategory = $rootScope.menuCategory[$scope.currentCategory];
			$scope.totalItems = $scope.menuCurrentCategory.items.length;

			$scope.updatePagination({
				currentPage: $scope.currentPage,
				numPerPage: $scope.numPerPage
			});

			$scope.defaultSelectPrice();
		};

		$scope.updatePagination = function (options) {
			var begin = ((options.currentPage - 1) * options.numPerPage);
			var end = begin + options.numPerPage;

			$scope.currentPage = options.currentPage;

			if ($rootScope.menuCurrentCategory.items != undefined) {
				$scope.filteredProducts = $rootScope.menuCurrentCategory.items.slice(begin, end);
			}
		};

		$scope.GetProduct = function (idProduct, idCategory) {
			// получаем продукт

			idCategory = idCategory || $scope.currentCategory; // текущая категория по умолчанию

			// ищем продукт в текущей выбранной категории
			var currentProduct;

			if ($rootScope.menuCategory[idCategory] == undefined) {
				$scope.GetCategory(idCategory);
			}

			$rootScope.menuCategory[idCategory].items.forEach(function (value, i) {
				if (value.id == idProduct) {
					currentProduct = value;
					currentProduct.category = idCategory;
				}
			});

			return currentProduct;
		};

		$scope.helpChange = function (value, idProduct, index, idModisCategory, idBlock) {
			if (value && value != 'null') {
				$('#' + idBlock).prop("checked", true).trigger('change');

				setTimeout(function () {
					$scope.modisSelect[index][idModisCategory] = value;
					$scope.GetResultPriceSelect(idProduct, index, idModisCategory, $scope.modisSelect[index][idModisCategory]);

					$scope.$apply();

				}, 100);
			}
		};

		$scope.GetResultPriceSelect = function (idProduct, index, idModisCategory, idModis) {
			if (idModis == 'null') {
				return false;
			}

			// определяем цену для выбранного селекта
			var result = 0;

			if (idModis) {
				result = $scope.priceSubProduct[idProduct][idModisCategory];
			}

			$scope.priceSubProduct[idProduct][idModisCategory] = result;
			$scope.GetResultPrice(index, idProduct, true);

			if ($rootScope.isCart) {
				$scope.updateProductCart(index, idProduct);
			}
		};

		$scope.defaultSelectPrice = function (options) {
			// меняем цену для элементов в селектами
			if ($rootScope.isCart) {
				return false;
			}

			//console.log($rootScope.isCart);

			$rootScope.menuCurrentCategory.items.forEach(function (value, i) {
				if (value.modis && value.modis.selectModis != undefined && value.modis.selectModis.length && value.modis.selectModis[0].modi.length) {

					//$scope.GetResultPriceSelect(value.id, value.id, value.modis.selectModis[0].id, value.modis.selectModis[0].modi[0].id);

				}
			});
		};


		$scope.addCart = function (options) {
			//event = event || [];

			var CartInfo = $rootScope.CartInfo;
			var arrayModis = [];
			var arrayModisSelect = [];

			if ($scope.countSubProduct[options.idProduct]) {
				$scope.countSubProduct[options.idProduct].forEach(function (value, i) {
					arrayModis.push({
						id: i,
						value: value
					})
				});
			}

			if ($scope.modisSelect[options.idProduct]) {
				$scope.modisSelect[options.idProduct].forEach(function (value, i) {
					arrayModisSelect.push({
						id: i,
						value: value
					})
				});
			}

			var inCartArray = false;
			var productAdd = false;

			// если товар уже в корзине
			CartInfo.cartList.forEach(function (valueCart, iCart) {
				if (valueCart.product == options.idProduct && !productAdd) {
					inCartArray = true;

					if (valueCart.modis.length == arrayModis.length) {
						valueCart.modis.forEach(function (itemModis, iModis) {
							if (itemModis.id != arrayModis[iModis].id || itemModis.value != arrayModis[iModis].value) {
								inCartArray = false;
							}
						});
					} else {
						inCartArray = false;
					}

					if (valueCart.modisSelect.length == arrayModisSelect.length) {
						valueCart.modisSelect.forEach(function (itemModis, iModis) {
							if (itemModis.id != arrayModisSelect[iModis].id || itemModis.value != arrayModisSelect[iModis].value) {
								inCartArray = false;
							}
						});
					} else {
						inCartArray = false;
					}

					if (inCartArray) {
						$rootScope.CartInfo.cartList[iCart].count = parseInt($rootScope.CartInfo.cartList[iCart].count)
							+ parseInt($scope.countProduct[options.idProduct]);
						productAdd = true;
					}
				}
			});

			// если продукта нет в корзине создаем новый
			if (!inCartArray) {
				$scope.lastIndex += 1;

				CartInfo.cartList.push({
					'type': options.typeProduct.substring(0, 1),
					'product': options.idProduct,
					'category': options.idCategory,
					'count': $scope.countProduct[options.idProduct],
					'modis': arrayModis,
					'modisSelect': arrayModisSelect,
					'order': $scope.lastIndex,
					'price': $scope.resultPriceProduct[options.idProduct]
				});
			}

			$rootScope.CartInfo.cartList = CartInfo.cartList;
			$scope.updateCartInfo();

			$scope.ShowInfo(options.idProduct);
		};

		$scope.updateCartInfo = function (updateModis, idProduct) {
			// обновление внешней информации о корзине для пользователя
			var totalPrice = 0;
			var totalCount = 0;
			var arrayModis = [];
			var arrayModisSelect = [];

			$rootScope.CartInfo.cartList.forEach(function (value, i) {
				totalCount = parseInt(totalCount) + parseInt(value.count);
				totalPrice = parseInt(totalPrice) + parseInt(value.count) * parseInt(value.price);
			});
			$rootScope.CartInfo.ResultSumm = totalPrice;
			$rootScope.CartInfo.ResultCount = totalCount;

			// обновление модификаторов
			if ($scope.countSubProduct[updateModis + 1]) {
				$scope.countSubProduct[updateModis + 1].forEach(function (value, i) {
					arrayModis.push({
						id: i,
						value: value
					})
				});

				$rootScope.CartInfo.cartList[updateModis].modis = arrayModis;
			}

			// обновление селектов-модификаторов
			if ($scope.modisSelect[updateModis + 1]) {
				$scope.modisSelect[updateModis + 1].forEach(function (value, i) {
					arrayModisSelect.push({
						id: i,
						value: value
					})
				});

				$rootScope.CartInfo.cartList[updateModis].modisSelect = arrayModisSelect;
			}

			$scope.saveCart();
		};

		$scope.ShowInfo = function (idProduct) {
			$scope.showMessage = true;
			$scope.nameCurrentProduct =
				angular.element('#product-' + idProduct)
					.find('.js-title-product')
					.text();

			clearTimeout($scope.idTimeout);
			$scope.idTimeout = setTimeout(function () {
				$scope.hideInfo();
			}, 5000);
		};

		$scope.hideInfo = function (event) {
			$scope.showMessage = false;

			if (!event) {
				$scope.$apply();
			}
		};

		$scope.toggleInfo = function (idProduct) {
			angular.element('#product-' + idProduct)
				.find('.more-info')
				.toggle()
				.end()
				.find('.hide-row')
				.slideToggle(300);
		};

		$scope.validValue = function (value, min, max) {
			var newValue = parseInt(value);

			if (newValue > parseInt(max)) {
				newValue = max;
			} else if (newValue < parseInt(min) || isNaN(newValue) || newValue < parseInt(min)) {
				newValue = min;
			}
			return newValue;
		};

		$scope.countInc = function (options) {
			var attr = options.element.parents('.wrapper-inc').find('.input-count')[0].attributes;
			var idProduct = options.idProductCart || options.idProduct;

			if (options.idSubProduct == undefined || options.idSubProduct == '') {
				$scope.countProduct[options.index] = $scope.validValue(
					parseInt($scope.countProduct[options.index]) + 1,
					attr.min.value,
					attr.max.value
				);
			} else {
				$scope.countSubProduct[options.index][options.idSubProduct] = $scope.validValue(
					parseInt($scope.countSubProduct[options.index][options.idSubProduct]) + 1,
					attr.min.value,
					attr.max.value
				);
			}

			$scope.GetResultPrice(options.index, idProduct, true, options.idCategory);

			if ($rootScope.isCart) {
				$scope.updateProductCart(options.index, idProduct);
			}
		};

		$scope.countDec = function (options) {
			var attr = options.element.parents('.wrapper-inc').find('.input-count')[0].attributes;
			var idProduct = options.idProductCart || options.idProduct;

			if (options.idSubProduct == undefined || options.idSubProduct == '') {
				$scope.countProduct[options.index] = $scope.validValue(
					parseInt($scope.countProduct[options.index]) - 1,
					attr.min.value,
					attr.max.value
				);
			} else {
				$scope.countSubProduct[options.index][options.idSubProduct] = $scope.validValue(
					parseInt($scope.countSubProduct[options.index][options.idSubProduct]) - 1,
					attr.min.value,
					attr.max.value
				);
			}

			$scope.GetResultPrice(options.index, idProduct, true, options.idCategory);

			if ($rootScope.isCart) {
				$scope.updateProductCart(options.index, idProduct);
			}
		};

		$scope.updateProductCart = function (index, idProduct) {
			var order;
			$rootScope.CartInfo.cartList.forEach(function (value, i) {
				if (value.order == index) {
					order = i;
				}
			});

			$rootScope.CartInfo.cartList[order].count = $scope.countProduct[index];
			$rootScope.CartInfo.cartList[order].price = $scope.resultPriceProduct[index];

			$scope.updateCartInfo(order, idProduct);
		};

		$scope.toSelectDelivery = function (link) {
			var options = {
				message: $rootScope.getLocale('Message delivery method for cleaning'),
				type: 'warning',
				callbackOk: function () {
					$location.path(link);
					$rootScope.CloseError();
				},
				callbackCancel: function () {
					$rootScope.CloseError();
				}
			};

			$rootScope.ShowErrorMessage(options);
		};

		$scope.afterLoad = function () {
			if ($scope.loadingMenu && $scope.loadCatalog) {
				if ($rootScope.isCart) {
					$scope.loadingCart = true;
					$scope.loadCart();
				} else {
					$scope.loadingCatalog = true;
					$scope.GetCategory($scope.firstCategory.id, $scope.firstCategory.name);
				}
			}
		};

		$scope.loadTreeCategory = function () {
			if (typeof ($rootScope.menutree) == 'object' && $rootScope.menutree.items != undefined && $rootScope.menutree.items.length) {
				$rootScope.loadCatalog = true;
				$scope.addProductId($rootScope.menutree);
				$scope.afterLoad();
			} else {
				var optionsMenu = {
					param: {
						'objectid': $rootScope.UserInfo.restaurantInfo.id,
						'lang': $rootScope.currentLocal
					}
				};

				// получаем дерево категорий
				requestServ.serverCall("/api/v1/menutree", optionsMenu, function (response) {
					if (response.error) {
						$rootScope.ShowErrorMessage({
							message: $rootScope.getLocale('Failed to get the tree menu. Return?'),
							fullMessage: response.value,
							type: 'warning',
							callbackOk: function () {
								if (!$scope.loadingMenu) {
									$scope.loadMenu();
								}
								$scope.loadTreeCategory();
								$rootScope.CloseError();
							},
							callbackCancel: function () {
								$location.path('/');
								$rootScope.CloseError();
							}
						});
					} else {
						$rootScope.loadCatalog = true;
						$rootScope.menutree = response.value.data.selectors[0];

						$scope.addProductId($rootScope.menutree);
						$scope.afterLoad();
					}
				});
			}
		};

		$scope.loadMenu = function () {
			if (typeof ($rootScope.RestaurantMenu) == 'object' && typeof ($rootScope.RestaurantMenu.dishes) == 'object' && $rootScope.RestaurantMenu.dishes != undefined) {
				$scope.loadingMenu = true;
				$scope.afterLoad();
			} else {
				var optionsMenu = {
					param: {
						'objectid': $rootScope.UserInfo.restaurantInfo.id,
						'lang': $rootScope.currentLocal
					}
				};

				requestServ.serverCall("/api/v1/dishes", optionsMenu, function (response) {
					if (response.error) {
						$rootScope.ShowErrorMessage({
							message: $rootScope.getLocale('Failed to get the menu. Return?'),
							fullMessage: response.value,
							type: 'warning',
							callbackOk: function () {
								if (!$scope.loadCatalog) {
									$scope.loadTreeCategory();
								}
								$scope.loadMenu();
								$rootScope.CloseError();
							},
							callbackCancel: function () {
								$location.path('/');
								$rootScope.CloseError();
							}
						});
					} else {
						$rootScope.RestaurantMenu = response.value.data;
						$scope.loadingMenu = true;
						$scope.afterLoad();
					}
				});
			}
		};

		$scope.getGroupModi = function (parentModi) {

			if ($scope.GroupModi[parentModi]) {
				return $scope.GroupModi[parentModi];
			}

			$scope.GroupModi[parentModi] = null;

			var itemModis = $rootScope.RestaurantMenu.modifiers;
			var commonModis = $rootScope.RestaurantMenu.commonModifiers || {};
			var allModi = itemModis.concat(commonModis);
			var needGroup = {};
			var needGroupTemp;

			allModi.forEach(function (value, i) {
				needGroupTemp = $.grep(value.group, function (item) {
					return item.id == parentModi;
				});

				if (needGroupTemp.length) {
					needGroup = needGroupTemp;
				}
			});

			if (needGroup[0].modi.length) {
				$scope.GroupModi[parentModi] = needGroup[0].modi;
			}

			return $scope.GroupModi[parentModi];
		};

		$scope.checkMaxValueGroup = function (options) {

			// проверка на максимальное количество в группе
			if (options.maxGroupCount) {
				if ($scope.countSubProduct[options.idProduct]) {
					var resultCount = 0;
					var modiGroup = $scope.getGroupModi(options.idParent);



					modiGroup.forEach(function (value, i) {
						resultCount += parseInt($scope.countSubProduct[options.idProduct][value.id]);
					});

					if (resultCount >= options.maxGroupCount) {
						$scope.disabledIncSubProduct[options.idProduct][options.idParent] = true;
					} else {
						$scope.disabledIncSubProduct[options.idProduct][options.idParent] = false;
					}
				}
			}
		};


		$scope.checkMinValueGroup = function (options) {
			// проверка на минимальное количество в группе
			var wrapperMin = options.element.parents('#product-' + options.attrs.idProduct).find('.js-sub-products-input');


			if (options.type == 'cart') {
				wrapperMin = options.element.find('.js-sub-products-input');
			}

			//angular.forEach(wrapperMin, function(valueBig, keyBig) {
			wrapperMin.each(function (keyBig, valueBig) {
				var itemGroup = $(valueBig);
				var resultCount = 0;

				itemGroup.find('input.input-count').each(function (item, value) {
					resultCount += parseInt($(value).val());
				});

				if (resultCount < itemGroup.data('min-value')) {
					$scope.errorMinCount[options.attrs.idProduct][itemGroup.data('parent-modi')] = true;
				} else {
					$scope.errorMinCount[options.attrs.idProduct][itemGroup.data('parent-modi')] = false;
				}

			});
		};


		$scope.checkProduct = function (options) {

			if ($scope.errorAdding[options.attrs.idProduct] == undefined) {
				$scope.errorAdding[options.attrs.idProduct] = false;
			}

			var item;
			options.element.parents('#product-' + options.attrs.idProduct)
				.find('.js-select-modis').each(function (i, value) {
					item = $(value);
					if (!item.val()) {
						item.addClass('h-error');
						$scope.errorAdding[options.attrs.idProduct] = true;
					}
				});

			$scope.checkMinValueGroup({
				element: options.element,
				attrs: options.attrs
			});
		};

		$scope.getRestaurants = function (onSuccess) {
			var optionsMenu = {
				param: {
					'corpid': configServ.corpId,
					'lang': $rootScope.currentLocal
				}
			};
			// получаем дерево категорий
			requestServ.serverCall("/api/v2/rests", optionsMenu, function (response) {
				if (response.error) {
					var options = {
						message: $rootScope.getLocale('Startup error restaurants list'),
						fullMessage: response.value,
						type: 'warning',
						callbackOk: function () {
							$scope.getRestaurants();
							$rootScope.CloseError();
						},
						callbackCancel: function () {
							$rootScope.CloseError();
							window.location.href = '#';
							//console.log('cancel');
						}
					};
					$rootScope.ShowErrorMessage(options);

				} else {
					$scope.restaurantArray = response.value.data.rests;
					$scope.loadRestaurant = false;

					if ($scope.restaurantArray.length == 1) {
						$scope.restaurantUser = $scope.restaurantArray[0].id.toString();
					}
					onSuccess();
				}
			});
		};

		$scope.loadRestsByZone = function() {
			if ($rootScope.UserInfo.restaurantInfo.address && $rootScope.UserInfo.restaurantInfo.id) {
				$scope.loadTreeCategory();
				$scope.loadMenu();
			} else {
				var lat = $rootScope.UserInfo.addressDelivery.lat;
				var lon = $rootScope.UserInfo.addressDelivery.lon;
				$scope.loadRest = true;

				if (lat != undefined) {
					lat = lat.toString().substr(0, 9);
					lon = lon.toString().substr(0, 9);
				} else {
					lat = lon = '';
				}

				var options = {
					method: 'POST',
					data: {
						"address": $rootScope.UserInfo.addressDelivery.fullAddress,
						"lat": lat.substr(0, 9),
						"lon": lon.substr(0, 9),
						"corpid": configServ.corpId,
						"default_object": configServ.objectId
					}
				};

				requestServ.serverCall("/api/v2/rests", options, function (response) {
					var optionsError = {
						message: $rootScope.getLocale('No delivery for address'),
						fullMessage: response.value,
						type: 'warning',
						callbackOk: function () {
							window.location.href = '#/select-address';
							$rootScope.CloseError();
						},
						callbackCancel: function () {
							$location.path('/');
							$rootScope.CloseError();
						}
					};

					if (response.error) {
						$rootScope.ShowErrorMessage(optionsError);
					} else {
						if (response.value.data.rests != undefined && response.value.data.rests.length) {
							$rootScope.UserInfo.restaurantInfo = response.value.data.rests[0];
							$scope.loadTreeCategory();
							$scope.loadMenu();
						} else {
							$rootScope.ShowErrorMessage(optionsError);
						}

					}

					$scope.loadRest = false;
				});
			}
		}

		$scope.initProducts = function () {

			if ($rootScope.UserInfo.typeDelivery == 'delivery') {

				if (configServ.typeRestaurants == 'local') {
					$rootScope.UserInfo.restaurantInfo.id = configServ.objectId;
					$scope.getRestaurants(function () {
						if (!$rootScope.UserInfo.restaurantInfo.address) {
							$scope.restaurantArray.forEach(function (item) {
								if (item.id == configServ.objectId) {
									$rootScope.UserInfo.restaurantInfo = item;
								};
							});
						};
						$scope.loadRestsByZone();
					});
				} else {
					$scope.loadRestsByZone();
				};

			} else if ($rootScope.UserInfo.typeDelivery == 'restaurant') {
				$scope.loadTreeCategory();
				$scope.loadMenu();
			}
		}
	}
]);


//app.directive("scroll", function ($window) {
//	return function(scope) {
//		angular.element($window).bind("scroll", function() {
//			if (this.pageYOffset >= 80) {
//				scope.fidexHeader = 'fixed-header';
//			} else {
//				scope.fidexHeader = '';
//			}
//			scope.$apply();
//		});
//	};
//});

app.directive('imageLoad', function () {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			//element.bind('load', function() {
			//	console.log('load ok');
			//});

			element.bind('error', function () {
				element.attr('src', 'assets/img/image-default.png');
			});
		}
	};
});

app.directive('changeCount', function () {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			element.bind('click', function () {

				if (element.hasClass('disabled')) {
					return false;
				}

				if (attrs.type == 'dec') {
					scope.countDec({
						element: element,
						index: attrs.index,
						idProduct: attrs.idProduct,
						idProductCart: attrs.idProductCart,
						idSubProduct: attrs.subProduct,
						idCategory: attrs.idCategory
					});
				} else if (attrs.type == 'inc') {

					scope.countInc({
						element: element,
						index: attrs.index,
						idProduct: attrs.idProduct,
						idProductCart: attrs.idProductCart,
						idSubProduct: attrs.subProduct,
						idCategory: attrs.idCategory
					});
				}

				if (attrs.idParent) {
					scope.checkMaxValueGroup({
						idProduct: attrs.idProduct,
						idParent: attrs.idParent,
						maxGroupCount: attrs.maxGroupCount
					});

					scope.errorMinCount[attrs.idProduct][attrs.idParent] = false;
				}

				scope.$apply();
			});
		}
	};
});

app.directive('checkErrorAdding', function () {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {

			element.bind('change', function () {
				element.removeClass('h-error');
				var item;
				var switchError = false;

				element.parents('#product-' + attrs.idProduct)
					.find('.js-select-modis').each(function (i, value) {
						item = $(value);
						if (!item.val()) {
							switchError = true;
						}
					});

				scope.errorAdding[attrs.idProduct] = switchError;
				scope.$apply();
			});
		}
	};
});

app.directive('productToCart', function () {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			element.bind('click', function () {
				scope.checkProduct({
					element: element,
					attrs: attrs
				});

				// если нет ошибок, то добавляем в корзину
				var errorMinCount = false;
				angular.forEach(scope.errorMinCount[attrs.idProduct], function (value, key) {
					if (value) {
						errorMinCount = true;
					}
				});

				if (!scope.errorAdding[attrs.idProduct] && !errorMinCount) {
					scope.addCart({
						idProduct: attrs.idProduct,
						idCategory: attrs.category,
						typeProduct: attrs.typeProduct
					});
				}

				scope.$apply();
			});
		}
	};
});



