app.controller('orderCtrl', ['$scope', '$rootScope', '$localStorage', 'requestServ', 'configServ', '$http', '$sce', '$location', '$filter',
		function($scope, $rootScope, $localStorage, requestServ, config, $http, $sce, $location, $filter) {
			$scope.orderEnd = false;
			$scope.orderProcess = false;
			$scope.numberOrder = '';
			$scope.formValidCheck = false;
			$scope.statusRequest = false;
			$scope.resultAgreement = '';
			$scope.showRulesSwitch = false;
			$scope.sce = $sce;
			$scope.noDelivery = false;
			$rootScope.PaySystem = $rootScope.UserInfo.restaurantInfo.currencies;
			var repeatUserAgreement = true;
			$scope.onlinePay = {};
			$scope.maskPhone = config.maskPhone;
			$scope.showMap = false;
			$scope.statusOrder = '';
			var oldLong = 0;
			var markers = [];



			/* для теста */
			$scope.currencyAll = {};
			$scope.payments = [{
				currency_id: '',
				extpay_id: '',
				amount: '',
				promised: false,
			}];

			$scope.addPayTest = function() {
				$scope.payments.push({
					currency_id: '',
					extpay_id: '',
					amount: '',
					promised: false,
				});
			}

			$scope.currencyChange = function(index) {


				$scope.currencyAll.forEach(function(value, i) {
					if (value.curid == $scope.payments[index].currency_id) {
						$scope.payments[index].extpay_id = value.name;
					}
				});



			}

			$scope.deleteTestPay = function(index) {

				$scope.payments.splice(index, 1);
			}

			$scope.paySendTest = function() {
				$scope.textErrorPay = '';
				$scope.textSuccessPay = false;
				$scope.textPay = 'Идет отправка';

				var options = {
					method: 'POST',
					data: {
						"visit_id": $scope.paramOrder.visit_id,
						"object_id": $rootScope.UserInfo.restaurantInfo.id,
						"payments": $scope.payments
					}
				};

				$scope.switchPage = 'load';

				requestServ.serverCall("/api/v1/payment", options, function(data) {
					$scope.switchPage = 'success';
					$scope.textPay = '';

					console.log(data);

					if(data.error) {
						 $scope.textErrorPay = data.value.details;

					} else {
						$scope.textSuccessPay = true;

						//console.log(data);



					}
				});
			};

			(function() {

				var options = {
					method: 'GET',
					param: {
						"objectId": $rootScope.UserInfo.restaurantInfo.id
					}
				};

				requestServ.serverCall("/api/v1/currency", options, function(data) {
					$scope.currencyAll = data.value.data;
				});
			})()


			/* для теста end */


			$scope.getPayStatus = function() {

				var options = {
					method: 'GET',
					param: {
						"visitId": $scope.dataArray.visit_id,
						"objectId": $scope.dataArray.object_id,
						//"billNumber": $scope.dataArray.visit_id + '_' + $scope.dataArray.object_id
					}
				};

				$scope.switchPage = 'load';

				requestServ.serverCall("/api/v1/assist/orderstate", options, function(data) {
					$scope.switchPage = 'load';

					if(data.error) {
						$scope.switchPage = 'hide';

						var options = {
							message: $rootScope.getLocale('Error checking payment status'),
							fullMessage: data.value,
							type: 'warning',
							callbackOk: function() {
								$scope.getPayStatus();
								$scope.switchPage = 'load';
								$rootScope.CloseError();
							},
							callbackCancel: function() {
								$rootScope.CloseError();
								$scope.switchPage = 'error';
							}
						};
						$rootScope.ShowErrorMessage(options);
					} else {
						$scope.switchPage = 'success';

						//console.log(data);

						$scope.dataArray.billnumber = data.value.data.bill_number;
						$scope.dataArray.textError = data.value.data.error;

					}
				});
			};


			$scope.initOrder = function() {
				if($rootScope.UserInfo.restaurantInfo.status == 'Inactive' || !$scope.isActiveDelivery()) {
					$scope.orderEnd = true;
				}

				if($rootScope.UserInfo.typeDelivery == 'delivery') {
					$scope.typeDeliveryVal = $rootScope.getLocale('Home delivery');
					$scope.addressDeliveryVal = $rootScope.UserInfo.addressDelivery.fullAddress;
					$scope.orderType = 1;
				} else if($rootScope.UserInfo.typeDelivery == 'restaurant') {
					$scope.typeDeliveryVal = $rootScope.getLocale('Pickup from the restaurant');
					$scope.addressRestaurantVal = $rootScope.UserInfo.restaurantInfo.address.formatted_address;
					$scope.orderType = 0;
				}

				$scope.finalOrder = {
					name: '',
					phone: '',
					email: '',
					payment: 0,
					timeDelivery: 'now',
					typeDelivery: $scope.typeDeliveryVal,
					addressDelivery: $scope.addressDeliveryVal,
					addressRestaurant: $scope.addressRestaurantVal,
					paymentSystem: 0,
					comment: '',
					rules: true
				};

				$scope.getShortChange();

				if(!$rootScope.CartInfo.cartList.length) {
					window.location.href = '#/cart';
				}
			};

			$scope.getShortChange = function() {
				var resultSumm = $rootScope.CartInfo.ResultSumm/100;
				var stepMini = 500;
				var stepMax = 5000;

				$scope.shortChangeArray = [];

				var floorNum = Math.floor(resultSumm / stepMini);
				var item = floorNum * stepMini + stepMini;
				var itemLast;
				addItem(item);

				if(!(floorNum % 2)) {
					item = floorNum * stepMini + stepMini * 2;
					addItem(item);
				}

				if(resultSumm > stepMax) {
					floorNum = Math.floor(resultSumm / stepMax);

					item = floorNum * stepMax + stepMax;
					addItem(item);
				}

				if(item < stepMax) {
					$scope.shortChangeArray.push(stepMax);
				}

				function addItem(value) {
					if(value != itemLast) {
						$scope.shortChangeArray.push(value);
						itemLast = value;
					}
				}
			};

			$scope.getInfoPaySystem = function() {

				if($rootScope.PaySystem[$scope.finalOrder.paymentSystem].id == 'ASSIST') {
					var params = {
						type: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].id,
						currency_id: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].currency_id,
						merchant_id: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].merchant_id,
						//visit_guid: $scope.paramOrder.visit_guid,
						visit_id: $scope.paramOrder.visit_id,
						seq_number: $scope.paramOrder.seq_number,
						object_id: $rootScope.UserInfo.restaurantInfo.id,
						amount: $scope.paramOrder.resultSumOrder,
						url_base: $location.$$absUrl.replace('#' + $location.$$url, '')
					};
					var stringParam = '';
					var separator = '';

					$.each( params, function(key, value) {
						stringParam += separator + key + '=' + value;
						separator = '&';
					});

					var urlServer = config.urlService + '/api/v1/assist';

					$scope.onlinePay = {
						type: params.type,
						merchantId: params.merchant_id,
						orderNumber: params.visit_id + '_' + $rootScope.UserInfo.restaurantInfo.id,
						resultSumOrder: $filter('filterPrice')(params.amount),
						currency: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].currency_code,
						urlAction: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].url + 'pay/order.cfm',
						urlReturnSuccess: urlServer + '?status=success&' + stringParam,
						urlReturnError: urlServer + '?status=error&' + stringParam
					};
				}
			};

			$scope.getInfoPaySystemRepeat = function() {


				var params = {
					type: 'ASSIST',
					currency_id: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].currency_id,
					merchant_id: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].merchant_id,
					//visit_guid: $scope.paramOrder.visit_guid,
					visit_id: $scope.paramOrder.visit_id,
					seq_number: $scope.paramOrder.seq_number,
					object_id: $rootScope.UserInfo.restaurantInfo.id,
					amount: $scope.paramOrder.resultSumOrder,
					url_base: $location.$$absUrl.replace('#' + $location.$$url, '')
				};
				var stringParam = '';
				var separator = '';

				$.each( params, function(key, value) {
					stringParam += separator + key + '=' + value;
					separator = '&';
				});

				var urlServer = config.urlService + '/api/v1/assist';

				$scope.onlinePay = {
					type: params.type,
					merchantId: params.merchant_id,
					orderNumber: params.visit_id + '_' + $rootScope.UserInfo.restaurantInfo.id,
					resultSumOrder: $filter('filterPrice')(params.amount),
					currency: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].currency_code,
					urlAction: $rootScope.PaySystem[$scope.finalOrder.paymentSystem].url + 'pay/order.cfm',
					urlReturnSuccess: urlServer + '?status=success&' + stringParam,
					urlReturnError: urlServer + '?status=error&' + stringParam
				};

			};


			$scope.isActiveDelivery = function() {
				var result = false;

				if(!$rootScope.UserInfo || !$rootScope.UserInfo.restaurantInfo || !$rootScope.UserInfo.restaurantInfo.delivery_period) {
					return result;
				}

				var begin = $rootScope.UserInfo.restaurantInfo.delivery_period.begin.split(':');
				var end = $rootScope.UserInfo.restaurantInfo.delivery_period.end.split(':');

				begin = parseInt(begin[0]) * 60 + parseInt(begin[1]);
				end = parseInt(end[0]) * 60 + parseInt(end[1]) - config.periodNoDelivery;

				var date = new Date();
				var currentTime = date.getHours() * 60 +  date.getMinutes();

				if(begin > end) {
					end = end + 24*60;
				}

				if(begin < currentTime && end > currentTime) {
					result = true;
				}

				return result;
			};

			$scope.getUserRules = function(options) {
				var currentLocal = config.local;

				if(options && options.local) {
					currentLocal = options.local;
				}

				$http.get('user-agreement/agreement-' + currentLocal + '.html?ver=1')
					.success(function (data) {
						$scope.resultAgreement = data;
					}).error(function(){
						if(config.defaultLocal != config.local && repeatUserAgreement) {
							$scope.getUserRules({ 'local': config.defaultLocal  });
							repeatUserAgreement = false;
						} else {
							$scope.resultAgreement = $rootScope.getLocale('No user agreement');
						}
					});
			};

			$scope.showRules = function() {

				if(!$scope.resultAgreement.length) {
					$scope.getUserRules();
				}
				$scope.showRulesSwitch = true;
			};

			$scope.formatDate = function(date) {
				var dd = $scope.helperFormat(date.getDate());
				var mm = $scope.helperFormat(date.getMonth() + 1);

				return date.getFullYear() + '-' + mm + '-' + dd;
			};

			$scope.helperFormat = function(value) {
				if (value < 10) {
					value = '0' + value;
				}

				return value;
			};

			$scope.getTimeDelivery = function(hours, minute) {
				$scope.timeDelivery = $rootScope.UserInfo.restaurantInfo.delivery_period;
				$scope.deliveryAllHours = [];
				var hoursStart = $scope.timeDelivery.begin.split(':');
				var hoursEnd = $scope.timeDelivery.end.split(':');
				var disabled = false;
				hoursStart = parseInt(hoursStart[0]);
				hoursEnd = parseInt(hoursEnd[0]);

				for (var i = hoursStart; i < hoursEnd; i++) {
					disabled = false;

					if (i < hours) {
						disabled = true;
					}

					$scope.deliveryAllHours.push({
						'value': i,
						'disabled': disabled
					});
				}

				$scope.finalOrder.timeDeliveryHour = hours;
				$scope.finalOrder.timeDeliveryMinutes = minute;
			};

			$scope.showSelectTime = function() {
				if($scope.finalOrder.timeDelivery == 'select') {
					var currentDate = new Date();
					var newMinute = '00';
					var addHours = config.addTimes;
					var currentHours = currentDate.getHours();
					var currentMinutes = currentDate.getMinutes();

					if(currentMinutes < 30) {
						newMinute = '30';
					} else {
						addHours += 1;
						newMinute = '00';
					}

					$scope.getTimeDelivery((parseInt(currentHours) + addHours).toString(), newMinute.toString());
				}
			};

			$scope.prepareData = function() {
				var subComment = '';
				var fullDate = new Date();
				var minutes = fullDate.getMinutes() > 9 ? fullDate.getMinutes() : '0' + fullDate.getMinutes();
				var addressUser = '';
				var deliveryTime = $scope.formatDate(fullDate) + 'T' + (fullDate.getHours() + config.addTimes) + ':' + minutes + ':00';


				if($scope.finalOrder.payment == 0) {
					subComment += $rootScope.getLocale('Payment by cash');
				} else if($scope.finalOrder.payment == 1) {
					subComment += $rootScope.getLocale('Payment by card');
				} else if($scope.finalOrder.payment == 2) {
					subComment += $rootScope.getLocale('Pay online');

					if($scope.finalOrder.paymentSystem == 0) {
						subComment += '. ' + $rootScope.getLocale('Payment through ASSIST');
					}
				}

				if($scope.finalOrder.shortChange && $scope.finalOrder.payment == 0) {
					subComment += '. ' + $rootScope.getLocale('Short change') + ' ' + $scope.finalOrder.shortChange + '. ';
				}


				if($scope.orderType) {
					addressUser = {
						"country": $rootScope.UserInfo.addressDelivery.country,
						"city": $rootScope.UserInfo.addressDelivery.city,
						"street": $rootScope.UserInfo.addressDelivery.street,
						"house": $rootScope.UserInfo.addressDelivery.house,
						"building": $rootScope.UserInfo.addressDelivery.housing,
						"entry": $rootScope.UserInfo.addressDelivery.porch,
						"entry_code": $rootScope.UserInfo.addressDelivery.intercom,
						"floor": $rootScope.UserInfo.addressDelivery.level,
						"apartments": $rootScope.UserInfo.addressDelivery.room,
						"lat": $rootScope.UserInfo.addressDelivery.lat,
						"lon": $rootScope.UserInfo.addressDelivery.lon,
					};
				}

				if($scope.finalOrder.timeDelivery == 'select') {
					deliveryTime = $scope.formatDate(fullDate) + 'T' + $scope.finalOrder.timeDeliveryHour + ':' + $scope.finalOrder.timeDeliveryMinutes + ':00';
				}

				var orderArray = [];
				var orderArrayTemp = [];
				var orderArrayModis = [];
				var tempSwitch = [];
				var countModi;

				$rootScope.CartInfo.cartList.forEach(function(value, i) {
					orderArrayModis = [];
					//console.log(value);

					value.modis.forEach(function(modisItem, i) {
						var typeModi = "m";

						if(value.type == "c") {
							typeModi = "cc";
						}

						if(modisItem.value) {
							countModi = modisItem.value || 1;
							orderArrayModis.push({
								"id": modisItem.id,
								"type": typeModi,
								"qnt": 1000 * countModi,
								"items": []
							});
						}
					});

					// для селектов подставляем выбраный элемент
					value.modisSelect.forEach(function(modisSelectItem, i) {
						tempSwitch[i] = true;

						orderArrayModis.forEach(function(modisItem, i) {
							if(modisSelectItem.id == modisItem.id && tempSwitch[i]) {
								modisItem.id = parseInt(modisSelectItem.value);
								tempSwitch[i] = false;
							}
						});
					});

					orderArrayTemp = {
						"id": value.product,
						"type": value.type,
						"qnt": parseInt(value.count) * 1000,
						"items": orderArrayModis
					};

					orderArray.push(orderArrayTemp);
				});


				var options = {
					method: 'POST',
					data: {
						"version_app": config.version,
						"objectid": $rootScope.UserInfo.restaurantInfo.id,
						"delivery_time": deliveryTime,  //"2016-09-20T22:00:00",
						"comment": subComment + ' ' + $scope.finalOrder.comment.toString(),
						"order_type": $scope.orderType, // 0 - самовывоз, 1 - доставка
						"pay_type": parseInt($scope.finalOrder.payment), // 0 - наличные курьеру, 1 - банковской картой курьеру, 2 - оплата онлайн через внешние системы
						"pay_online_type": ($scope.finalOrder.payment == 2) ? $scope.finalOrder.paymentSystem : '', // тип онлайн оплаты
						"client": {
							"phone": '7' + $scope.finalOrder.phone.replace(/[ {}()-]/g,""),
							"email": $scope.finalOrder.email,
							"ln": $scope.finalOrder.lastName,
							"fn": $scope.finalOrder.firstName
						},
						"address": addressUser,
						"order": orderArray
					}
				}
				return options;
			};

			$scope.calcOrder = function() {
 				if(!$scope.finalOrderForm.$valid) {
					$scope.formValidCheck = true;
					return false;
				}
				$scope.formValidCheck = false;
				$scope.orderProcess = true;
				var options = $scope.prepareData();
 				requestServ.serverCall("/api/v1/CalcOrder", options, function(data) {
					if(data.error) {
						console.log('calcOrder error');
						$rootScope.ShowErrorMessage({
							message: $rootScope.getLocale('Error sending. Try later'),
							fullMessage: data.value,
							type: 'error'
						});
						$scope.orderProcess = false;
					} else {
						$scope.statusRequest = data.value.status;
						$scope.orderProcess = false;
						if(data.value.status == 'Ok') {
							$scope.AmountForPay = data.value.data.Payments
							$rootScope.ShowPayments($scope.AmountForPay);
						}
					}
				});
			};

			/**
		 	* Генерим полный адресс на основе данных с сервера
		 	* @returns {string}
		 	*/
			function generateFullAddress(address) {
		    	var fullAddress = '';

            	fullAddress += address.city ? $rootScope.getLocale('City') + ' ' + address.city : '';
            	fullAddress += address.street ? ', ' + $rootScope.getLocale('Street') + ' ' + address.street.replace('ул. ', '') : '';
            	fullAddress += address.house ? ', ' + $rootScope.getLocale('House') + ' ' + address.house : '';
            	fullAddress += address.building ? ', ' + $rootScope.getLocale('Housing-building') + ' ' + address.building : '';
            	fullAddress += address.entry ? ', ' + $rootScope.getLocale('Access') + ' ' + address.entry : '';
            	fullAddress += address.entry_code ? ', ' + $rootScope.getLocale('Intercom') + ' ' + address.entry_code : '';
            	fullAddress += address.floor ? ', ' + $rootScope.getLocale('Level') + ' ' + address.floor : '';
            	fullAddress += address.apartments ? ', ' + $rootScope.getLocale('Room') + ' ' + address.apartments : '';

            	return fullAddress;
        	}


			$scope.saveOrder = function() {
				if(!$scope.finalOrderForm.$valid) {
					$scope.formValidCheck = true;
					return false;
				}

				$scope.formValidCheck = false;
				$scope.orderProcess = true;
                var options = $scope.prepareData();

				requestServ.serverCall("/api/v1/SaveDeliveryOrder", options, function(data) {
					if(data.error) {
						$rootScope.ShowErrorMessage({
							message: $rootScope.getLocale('Error sending. Try later'),
							fullMessage: data.value,
							type: 'error'
						});
						$scope.orderProcess = false;
					} else {
						$scope.statusRequest = data.value.status;
						$scope.orderEnd = true;
						$scope.orderProcess = false;

						if(data.value.status == 'Ok') {
							// выводим в консоль

							$scope.paramOrder = {
								resultSum: $rootScope.CartInfo.ResultSumm,
								numberOrder: data.value.data.seq_number + ' (' + data.value.data.visit_id + ')',
								visit_id: data.value.data.visit_id,
								seq_number: data.value.data.seq_number,
								visit_guid: data.value.data.visit_guid,
								resultSumOrder: data.value.data.unpaid_sum,
								discountSumOrder: parseFloat(data.value.data.discount_sum),
								travel_time: data.value.data.travel_time,
								rest_phone: data.value.data.rest_phone,
							};

							if(data.value.data.address && data.value.data.address.formatted_address) {
								$scope.paramOrder.addressDelivery = generateFullAddress(data.value.data.address);
							}

							if ($scope.UserInfo.typeDelivery == 'delivery' && $scope.finalOrder.payment != 2) {

								$scope.generateMap([
									{
										lat: $rootScope.UserInfo.addressDelivery.lat,
										lon: $rootScope.UserInfo.addressDelivery.lon
									},
									{
										lat: $rootScope.UserInfo.restaurantInfo.address.lat,
										lon: $rootScope.UserInfo.restaurantInfo.address.lon
									}
								]);

								$scope.getCoord({
									visitId: data.value.data.visit_id,
									objectId: $rootScope.UserInfo.restaurantInfo.id
								});
							}

							$scope.clearCart();
						} else {
							$scope.codeError = data.value.error[0].code;
							$scope.textError = data.value.error[0].text;
							$scope.detailsError = data.value.error[0].details;
						}
					}
				});
			};


			$scope.getCoord = function(options) {
				// получаем координаты курьера
				var optionsParam = {
					param: {
						'visitId': options.visitId,
						'objectId': options.objectId
					}
				};

				$scope.statusCourierCoord = '';

				requestServ.serverCall("/api/v1/courier", optionsParam, function(data) {
					var koeff = 1;
					if(data.error) {

						$scope.statusCourierCoord = 'error';

						$scope.orderProcess = false;
					} else {
						if(data.value.status == 'Ok') {

							if(data.value.data.courier_location && data.value.data.courier_location != null) {

								$scope.generateMap([
									{
										lat: $rootScope.UserInfo.addressDelivery.lat,
										lon: $rootScope.UserInfo.addressDelivery.lon
									},
									{
										lat: data.value.data.courier_location.lat,
										lon: data.value.data.courier_location.lon
									}
								]);

							} else {
								$scope.statusCourierCoord = 'error';
							}

							$scope.statusOrder = data.value.data.DlvStateName;

						} else {
							$scope.codeError = data.value.error[0].code;
							$scope.textError = data.value.error[0].text;
							$scope.detailsError = data.value.error[0].details;
							koeff = 2;
						}

					}

					setTimeout(function() {
						$scope.getCoord(options);
					}, config.timeOutGetCoord * koeff);

				});
			};

			//$scope.goPay = function() {
			//
			//		var dataPay = {
			//			Merchant_ID: paramOrder.merchantID,
			//			OrderNumber: paramOrder.visitId,
			//
			//			OrderAmount: paramOrder.resultSumOrder,
			//			OrderCurrency: paramOrder.currency,
			//
			//
			//			FirstName: finalOrder.firstName,
			//			LastName: finalOrder.lastName,
			//		}
			//
			//		$http({
			//			url: paramOrder.assistUrl,
			//			method: 'post',
			//			data: dataPay
			//		}).success(function( result ) {
			//
			//
			//
			//		}).error(function(data) {
			//
			//
			//		});
			//}

			$scope.initOrder();

			if($scope.orderType && $rootScope.CartInfo.ResultSumm < $rootScope.UserInfo.restaurantInfo.min_check_amount * 100) {
				$scope.noDelivery = true;
			}

			$scope.generateMap = function(options) {
				// показываем курьера на карте

				if(markers.length) {
					clearMarkers();
					markers = [];
				}

				var markersBounds = new google.maps.LatLngBounds();
				var latlng = [];
				var optionsMap = {
					zoom: 13
				};

				if($scope.map == undefined) {
					//console.log('generate map');
					$scope.map = new google.maps.Map(document.getElementById("map"), optionsMap);
					$scope.geocoder = new google.maps.Geocoder();
					$scope.marker = new google.maps.Marker({
						map: $scope.map,
						//draggable: true
					});
				}

				for(i = 0; i < 2; i++) {
					latlng[i] = new google.maps.LatLng(options[i].lat, options[i].lon);

					var point = {
						location: latlng[i],
					};

					if(i != 0) {
						point.icon = 'assets/img/car-icon.png';
					}

					addMarker(point);
				}

				function addMarker(options) {
					markersBounds.extend(options.location);

					var marker = new google.maps.Marker({
						position: options.location,
						map: $scope.map,
						icon: options.icon
					});
					markers.push(marker);
				}

				//$scope.map.setCenter(latlng[0]);

				function setMapOnAll(map) {
					for (var i = 0; i < markers.length; i++) {
						markers[i].setMap(map);
					}
				}

				function clearMarkers() {
					setMapOnAll(null);
				}

				$scope.map.fitBounds(markersBounds);
				$scope.showMap = true;
			};


			$scope.initMap = function() {
				var addMapScript = document.createElement('script');
				addMapScript.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&key=' + config.keyMapApiGoogle;
				document.body.appendChild(addMapScript);
			};

			$scope.initMap();

			$scope.initStatusPay = function() {
				$scope.switchPage = 'load';
				$scope.dataArray = $location.search();
				$scope.switchPage = $scope.dataArray.status;


				setTimeout(function(){
					if($scope.UserInfo.typeDelivery == 'delivery' && $scope.switchPage == 'success') {

						$scope.generateMap([
							{
								lat: $rootScope.UserInfo.addressDelivery.lat,
								lon: $rootScope.UserInfo.addressDelivery.lon
							},
							{
								lat: $rootScope.UserInfo.restaurantInfo.address.lat,
								lon: $rootScope.UserInfo.restaurantInfo.address.lon
							}
						]);
					}
				}, 1000);

				$scope.getCoord({
					visitId: $scope.dataArray.visit_id,
					objectId: $rootScope.UserInfo.restaurantInfo.id
				});
			};



		}]);

app.directive('dynamicFormAction', function() {
	return {
		restrict: 'A',
		scope: {
			'dynamicFormAction': '='
		},
		link: function(scope, el, attrs) {
			scope.$watch('dynamicFormAction', function (action) {
				el[0].action = action;
			});
		}
	};
});
