;(function($) {
	var pagetype = window.pagetype || "";

	mindbox("async", {
		operation: "CustomerZoneDefinition",
		data: {
			customer: {
				area: {
					ids: {
						externalId: region_id
					}
				}
			}
		}
	});


	switch(pagetype){
		case 'home':            
			break;

		case 'category':
			if (pageid != ''){
				directCrm('performOperation', {
					operation: 'ViewCategory',
					data: {
						action: {
							productCategoryId: pageid
						}
					}
				});
			}
			break;

		case 'product':
			directCrm('performOperation', {
				operation: 'ViewProduct',
				data: {
					action: {
						productId: pageid
					}
				}
			});
			break;

		/*case 'purchase':
			directCrm('cart.clear');

			if(isOneClick){
				directCrm('identify', {
					operation: 'OneClick',
					identificator: {
						provider: 'mobilePhone',
						identity: orderphone
					},
					data: {
						firstName: ordername,
						settlement: settlement_var
					}
				});
			}else{
				if(isNewClient){
					mindbox("async", {
						operation: "CreateOrderReg",
						data: {
							customer: {
							  email: orderemail,
							  mobilePhone: orderphone,
							  firstName: ordername,
							  subscriptions: [
								{
								  brand: "Yourroom",
								  pointOfContact: "Email",
								  isSubscribed: subscribe
								}
							  ]
							},
							order: {
								ids: {
									externalSystemYourRoom1C: ordernumber,
								},
								totalPrice: totalvalue,
								lines: mindboxprods
							}
						}
					});
				}else{
					mindbox("async", {
						operation: "CreateOrder",
						data: {
							customer: {
							  mobilePhone: orderphone
							},
							order: {
								ids: {
									externalSystemYourRoom1C: ordernumber,
								},
								totalPrice: totalvalue,
								lines: mindboxprods
							}
						}
					});
				}
			}
			console.log("purchase mindbox oneclick="+isOneClick+" newclient="+isNewClient);
			break;*/
	}

	$(".subscribe__btn").on('click', function(e){
		var parentwrapp = $(this).closest(".subscribe"),
			email = $('input[type=email]', parentwrapp).val();

		if (email != ""){
			directCrm('identify', {
				operation: "SubscribeField",
				identificator: {
					provider: 'email',
					identity: email
				},
				data: {
					firstName: '',
					settlement: settlement_var
				}
			});

			$(".subscribe__title", parentwrapp).html("Спасибо,<br>Вы подписаны!");
			$(".subscribe__input-wrapper", parentwrapp).hide();
		}

		return;
	});

	// покупка
	$(".btn-buy").on('click', function(e){
		directCrm('cart.addProduct', {
			productId: $(this).data("productid"),
			quantity: 1,
			price: $(this).data("price").toFixed()
		});

		return;
	});

	// отзыв
	$('#modalAddComment input[type="submit"]').on('click', function(event) {
		var email = $('#modalAddComment input[name="user_email"]').val();
		
		if (email!=""){
			directCrm('identify', {
				operation: 'Review',
				identificator: {
					provider: 'email',
					identity: email
				},
				data: {
					firstName: $('#modalAddComment input[name="user_name"]').val(),
					settlement: settlement_var
				}
			});
		}

		return;
	});

	// feedback, send question
	$(document).on("click", "#feedbackModal .sendfeedback", function(){
		var email = $("#feedbackModal input[name=email]").val();
		if (email=="") return false;

		mindbox('async', {
			operation: 'SubFormVopros',
			data: {
				customer:{
					email: email,
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox #feedbackModal .sendfeedback operation SubFormVopros ' + email);

		return;
	});

	// eraser in card
	$(document).on("click", "#eraser-email-button", function(e){
		var email = $(".eraser-email").val().trim(),
			timer = 0;

		if (email == "") return false;
		
		directCrm('identify', {
			operation: 'subsEraser',
			identificator: {
				provider: 'email',
				identity: email
			},
			data: {
				firstName: '',
				settlement: settlement_var
			}
		});
	});

	// product subscribe send
	$(".prodListSubs").on('click', function(e){
		$('#prodsubscribe-send').attr('data-productid', $(this).data('productid'));
	});
	$("#prodsubscribe-send").on('click', function(e){
		var email = $("#subscribe_user_email").val(),
		    productid = productid || $(this).data('productid');

		if (email == ""){
			$("#subscribe_user_email").addClass("field__input_invalid");
			return;
		}

		mindbox("async", {
			operation: "subList",
			data: {
				customer: {
					email: email,
				},
				addProductToList: {
					product: {
						ids: {
							yourRoom1C: productid,
						}
					}
				}
			},
		});

		$("#modalProdSubscribe .modal-body").html('Спасибо за проявленный интерес, мы сообщим Вам на указанный email о поступлении товара или его аналога!');

	});

	// подписка на блог
	$('.blogSubscribe button[type="submit"]').on('click', function(event) {
		var articleId = $(this).data('articleid'),
		    op;

		op = articleId == 1508 ? "SubForm" : "subBlog"; // хард на статью акция

		mindbox('sync', {
			operation: op,
			data: {
				customer:{
					email:$('#blogEmail').val(),
					mobilePhone:"",
					fullName:$('#blogName').val(),
					customFields: {
						clientCity: settlement_var
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});
		console.log('mindbox operation ' + op + ' articleId=' + articleId);
	});

	// берем кредит на странице рассрочки
	$('[id^="kform"] button[name="submit"]').on('click', function(){
		var parentForm = $(this).closest("form"),
		    mail = $('input[name=click_email]', parentForm).val();

		if(mail != '' && checkMail(mail)){
			console.log('Send mindbox rassrochka');
			directCrm('identify', {
				operation: 'SubscribeDiscounts',
				identificator: {
					provider: 'email',
					identity: mail
				},
				data: {
					settlement: settlement_var,
					firstName:  '',
				}  

			});
		}
	});

	// станица оптовикам /optovikam
	$('#optovikam [type=submit]').on('click', function(){
		var parentForm = $(this).closest("form"),
		    mail = $('[name=mail]', parentForm).val();

		if(mail){
			directCrm('identify', {
              operation: 'Wholesale',
              identificator: {
                provider: 'email',
                identity: jQuery("input[name='mail']", parentForm).val()
              },
              data: {
                firstName: jQuery("input[name='name']", parentForm).val(),
                mobilePhone: jQuery("input[name='tel']", parentForm).val()
              }
            });
		}

	});

	// Отправить подарок другу
	$('.discountFriend button[type="submit"]').on('click', function(event) {
		mindbox('sync', {
			operation: 'giftSender',
			data: {
				customer:{
					email:$('#blogEmail').val(),
					fullName:$('#blogName').val(),
					customFields: {
						clientCity: settlement_var,
						friendName: $('#blogNameTo').val(),
						friendEmail: $('#blogEmailTo').val(),
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox operation giftSender');

		mindbox('sync', {
			operation: 'giftRecipient',
			data: {
				customer:{
					email:$('#blogEmailTo').val(),
					fullName:$('#blogNameTo').val(),
					customFields: {
						clientCity: settlement_var,
						friendName: $('#blogName').val(),
						friendEmail: $('#blogEmail').val(),
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox operation giftRecipient');
	});

	// франчайзи
	$('.contact-form-0 .btn-send').on('click', function(event) {
		var email = $('.contact-form-0 [name=email]').val();

		if(email == ''){
			return;
		}

		mindbox('async', {
			operation: 'ZapolnenieFormySendMessage',
			data: {
				customer:{
					email: email,
					fullName: $('.contact-form-0 [name=name]').val(),
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox .contact-form-0 operation ZapolnenieFormySendMessage');
	});

	$('.contact-form-1 .btn-send').on('click', function(event) {
		var email = $('.contact-form-1 [name=email]').val();
		
		if(email == ''){
			return;
		}

		mindbox('async', {
			operation: 'SubForm',
			data: {
				customer:{
					email: email,
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox .contact-form-1 operation SubForm');
	});

	/** 
	 * task #4068
	 * "Получите консультацию" Подписка форма на сайте
	 */
	$('[data-mindbox="SubFormconsulting"] .sendnotify, [data-mindbox="SubFormFreeConsultation"] .sendnotify').on('click', function(event) {
		var form = $(this).closest('form'),
		    phone = $('[name=phone]', form).val(),
		    operation = $(this).closest('[data-mindbox]').data('mindbox');
		
		if(phone == ''){
			return;
		}

		mindbox('async', {
			operation: operation,
			data: {
				customer:{
					mobilePhone: phone,
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox operation ' + operation);
	});

	// "Подобрать кухню" Подписка форма на сайте
	// "Заказать бесплатный проект" Подписка форма на сайте
	$('[data-mindbox="SubFormChoosekitchen"] .sendnotify, [data-mindbox="SubFormFreeProject"] .sendnotify').on('click', function(event) {
		var form = $(this).closest('form'),
		    phone = $('[name=phone]', form).val(),
		    email = $('[name=email]', form).val(),
			operation = $(this).closest('[data-mindbox]').data('mindbox');
		
		if(email == ''){
			return;
		}

		mindbox('async', {
			operation: operation,
			data: {
				customer:{
					email: email,
					mobilePhone: phone,
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox operation ' + operation);
	});

	// Заказать проект кухни он-лайн, форма
	$(document).on('click', '#orderProjectOnline .sendnotify', function(event) {
		var ktype = $('#orderProjectOnline [name=type]:checked').val(),
		    ktype_name = '',
			email = $('#orderProjectOnline [name=email]').val();
		
		if(email == ''){
			return;
		}

		switch (ktype) {
			case 2:
				ktype_name = 'Угловая (левая)';
				break;
			case 3:
				ktype_name = 'Угловая (правая)';
				break;
			case 4:
				ktype_name = 'П-образная';
				break;
		
			default:
				ktype_name = 'Прямая';
				break;
		}

		mindbox('async', {
			operation: 'SubFormPrice',
			data: {
				customer:{
					email: email,
					fullName:$('#orderProjectOnline [name=name]').val(),
					customFields: {
						clientCity: settlement_var,
						kitchenconfiguration: ktype_name,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox #orderProjectOnline .sendnotify operation SubFormPrice');

		return;
	});

	$(document).on('click', '#subs-footer-btn', function(event) {
		var email = $('[name=email_footer]').val();

		if(email == ''){
			return;
		}

		mindbox('async', {
			operation: 'SubFormPodpishites',
			data: {
				customer:{
					email: email,
					customFields: {
						clientCity: settlement_var,
					},
					subscriptions:[
						{brand:"Yourroom",pointOfContact:"Email"}
					]
				}
			}
		});

		console.log('mindbox #subs-footer-btn operation SubFormPodpishites ' + email);

		$("#subs-footer").html("<div class='h2 m-2'>Спасибо!</div>");
		return;
	});

	$(document).on('click', '.favorites img.not-fav, .favorites img.fav', function(event) {
		/*let price = ('pricenum' in window) ? pricenum : $(this).closest('.product-card').find('.btn-buy').data('price');*/
		let product_id = $(this).closest('.favorites').data('product'),
		    list_arr = [],
			fav_arr = [],
		    fav = $.cookie('favorites');

		if (fav){
			fav = JSON.parse(fav);
			fav_arr = Object.keys(fav);
		}

		if(fav_arr.length){
			for (let f of fav_arr) {
				list_arr.push({
					product: {
						ids: {
							yourRoom1C: f
						}
					},
					count: 1,
					pricePerItem: 1
				});
			}

			mindbox("async", {
				operation: "SetIzbrannoeItemList",
				data: {
					productList: list_arr
				},
				onSuccess: function() { },
				onError: function(error) { }
			});
	
			console.log('mindbox operation SetIzbrannoeItemList products: ' + fav_arr.length);

		}else{
			// delete all
			mindbox("async", {
				operation: "ResetIzbrannoeItemList",
				data: {},
				onSuccess: function() { },
				onError: function(error) { }
			});

			console.log('mindbox operation ResetIzbrannoeItemList');
		}
	});

}(jQuery));