var goingPage = '/';
var ictf = 0;

function ac_info(layer) {
	$('#achange'+layer).hide();
	$('#change'+layer).show();
	$('#addd_'+layer).hide();
}

function ac_close_submit() {
	$('#newaddress').hide();
	$('#ac_button_addaddress').show();
}

function ac_edit_submit() {
	addressid = $('#address_id').val();
	adres_city_id = $('#adres_city_id').val();
	adres_city = $('#adres_city').val();
	adres_street_id = $('#adres_street_id').val();
	adres_street = $('#adres_street').val();
	adres_house_id = $('#adres_house_id').val();
	adres_house = $('#adres_house').val();
	floor = $('#floor').val();
	flat = $('#flat').val();
	domofon = $('#domofon').val();
	postindex = $('#postindex').val();
	short_name = $('#short_name').val();
	bShow = false;
	
	if (adres_city_id && adres_city!='' && adres_street_id && adres_street!='' && adres_house_id && adres_house!='' && short_name!='') {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/ac_info.php",
			   data: {  
					'action': 'updateaddress',
					'id': addressid,
					'adres_city_id': adres_city_id,
					'adres_city': adres_city,
					'adres_street_id': adres_street_id,
					'adres_street': adres_street,
					'adres_house_id': adres_house_id,
					'adres_house': adres_house,
					'floor': floor,
					'flat': flat,
					'domofon': domofon,
					'postindex': postindex,
					'short_name': short_name
					},
			   dataType: "json",
			   timeout: 15000,
			   success: function(data){
					if (data.status=='OK') {
						//$('#ac_address_'+addressid).remove();
						//addresslist
						if (addressid>0) {
							//edit
						} else {
							sHTML = '<div class="sub-grey" id="ac_address_'+data.id+'">'+
	                        '<p>'+short_name+'</p>'+
	                        '<a href="javascript:;" onClick="ac_edit_address('+data.id+')" style="color:green">[ред]</a>'+ 
	                        '<a href="javascript:;" onClick="if (confirm(\'Вы уверены, что хотите удалить адрес?\')) ac_delete_address('+data.id+')" style="color:red">[x]</a></div>';
							$('#addresslist').append(sHTML);
						}
						
						$('#newaddress').hide();
						$('#ac_button_addaddress').show();
						$('#errormessagep').html('Данные изменены!');
						$('#errormodal').modal('open');
					}
					if (data.message!='') {
						$('#errormessagep').html(data.message);
						$('#errormodal').modal('open');
					}
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	} else {
		$('#errormessagep').html('Нужно обязательно указать Город, Улицу, Дом, Название адреса');
		$('#errormodal').modal('open');
	}
}
function cart_change_address() {
	selid = $( "#my_address" ).val();
	if (selid>0) {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/ac_info.php",
			   data: {  
					'action': 'editaddress',
					'id': selid
					},
			   dataType: "json",
			   timeout: 15000,
			   success: function(data){
					if (data.status=='OK') {
						$('#adres_city_id').val(data.address.city_id);
						$('#adres_city').val(data.address.city_name);
						$('#adres_street_id').val(data.address.street_id);
						$('#adres_street').val(data.address.street_name);
						$('#adres_house_id').val(data.address.house_id);
						$('#adres_house').val(data.address.house_name);
						$('#floor').val(data.address.floor);
						$('#flat').val(data.address.flat);
						$('#domofon').val(data.address.domofon);
						$('#postindex').val(data.address.postindex);
					}
					if (data.message!='') {
						$('#errormessagep').html(data.message);
						$('#errormodal').modal('open');
					}
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	}
}
function ac_edit_address(addressid) {

	//bShow = false;
	
	$('#address_id').val(0);
	$('#adres_city_id').val(0);
	$('#adres_city').val('');
	$('#adres_street_id').val(0);
	$('#adres_street').val('');
	$('#adres_house_id').val(0);
	$('#adres_house').val('');
	$('#floor').val('');
	$('#flat').val('');
	$('#domofon').val('');
	$('#postindex').val('');
	$('#short_name').val('');
	sTitle = "Новый адрес";
	
	if (addressid) {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/ac_info.php",
			   data: {  
					'action': 'editaddress',
					'id': addressid
					},
			   dataType: "json",
			   timeout: 15000,
			   success: function(data){
					if (data.status=='OK') {
						//$('#ac_address_'+addressid).remove();
						sTitle = 'Редактирование адреса'; 
						//alert(sTitle);
						$('#address_id').val(addressid);
						$('#adres_city_id').val(data.address.city_id);
						$('#adres_city').val(data.address.city_name);
						$('#adres_street_id').val(data.address.street_id);
						$('#adres_street').val(data.address.street_name);
						$('#adres_house_id').val(data.address.house_id);
						$('#adres_house').val(data.address.house_name);
						$('#floor').val(data.address.floor);
						$('#flat').val(data.address.flat);
						$('#domofon').val(data.address.domofon);
						$('#postindex').val(data.address.postindex);
						$('#short_name').val(data.address.short_name);
						
						$("#newaddressh").html(sTitle);
						$('#ac_button_addaddress').hide();
						$('#newaddress').show();
					}
					if (data.message!='') {
						$('#errormessagep').html(data.message);
						$('#errormodal').modal('open');
					}
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	} else {
		$("#newaddressh").html(sTitle);
		$('#ac_button_addaddress').hide();
		$('#newaddress').show();
	}
	
	
	
}


function ac_delete_address(addressid) {
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/ac_info.php",
		   data: {  
				'action': 'deleteaddress',
				'id': addressid
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.status=='OK') {
					$('#newaddress').hide();
					$('#ac_button_addaddress').show();
					$('#ac_address_'+addressid).remove();
				}
				if (data.message!='') {
					$('#errormessagep').html(data.message);
					$('#errormodal').modal('open');
				}
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function ac_field(field) {
	
	val = $('#'+field).val();
	
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/ac_info.php",
		   data: {  
				'action': 'changefield',
				'field': field,
				'value': val
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.status=='OK') {
					$('#'+field).val('');
					$('#ac_'+field).html(val);
					$('#achange'+field).show();
					$('#change'+field).hide();
					$('#addd_'+field).show();
				}
				if (data.message!='') {
					$('#errormessagep').html(data.message);
					$('#errormodal').modal('open');
				}
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function ac_change_phone() {
	phone = $('#change_phone').val();
	$('#cphonemessage').html('идет запрос кода.....');
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/ac_info.php",
		   data: {  
				'action': 'changephone',
				'phone': phone
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.message!='') {
					$('#cphonemessage').html(data.message);
				}
				if (data.status=='OK') {
					$('#changephone').hide();
					$('#changephonecode').show();
					$('#change_code').val('');
				}
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function ac_change_phone_confirm() {
	phone = $('#change_phone').val();
	code = $('#change_code').val();
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/ac_info.php",
		   data: {  
				action: 'changephoneconfirm',
				phone: phone,
				smscode: code
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  $('#changephone').hide();
				  $('#cphonemessage').hide();
				  $('#changephonecode').hide();
				  $('#change_phone').val('');
				  $('#change_code').val('');
				  $('#phonevalue').html(phone);
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#cphonemessage').html(data.message);
			  }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function ac_change_email() {
	email = $('#ac_email').val();
	if (email!='') {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/ac_info.php",
			   data: {  
					action: 'changeemail',
					email: email
					},
			   timeout: 15000,
			   dataType: "json",
			   success: function(data){
				   if (data.status=='OK') {
					   $('#ac_email').val('');
					   $('#changeemail').hide();
					   $('#achangeemail').show();
					   $('#errormessagep').html('Вам было выслано письмо со ссылкой на смену электронного адреса');
					   $('#errormodal').modal('open');
				   } else {
					   $('#errormessagep').html(data.message);
					   $('#errormodal').modal('open');
				   }
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				  
		       }
		});
	} else {
		$('#errormessagep').html('Вы не ввели email!');
		$('#errormodal').modal('open');
	}
}

function ac_change_pass() {
	oldpass = $('#oldpass').val();
	newpass = $('#newpass').val();
	cnewpass  = $('#cnewpass').val();
	bError = false;
	if (newpass!=cnewpass) {
		$('#errormessagep').html('Введенные новые пароли не совпадают!');
		$('#errormodal').modal('open');
		bError = true;
	} 
	if (!bError && newpass.length<8) {
		$('#errormessagep').html('Длина пароля не может быть меньше 8 символов!');
		$('#errormodal').modal('open');
		bError = true;
	} 
	if (!bError) {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/ac_info.php",
			   data: {  
					action: 'changepass',
					oldpass: oldpass,
					newpass: newpass,
					cnewpass: cnewpass,
					},
			   timeout: 15000,
			   dataType: "json",
			   success: function(data){
				   if (data.status=='OK') {
					   $('#oldpass').val('');
					   $('#newpass').val('');
					   $('#cnewpass').val('');
					   $('#changepass').hide();
					   $('#achangepass').show();
					   $('#errormessagep').html('Пароль был изменен!');
					   $('#errormodal').modal('open');
				   } else {
					   $('#errormessagep').html(data.message);
					   $('#errormodal').modal('open');
				   }
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				  
		       }
		});
	}
	
}

function CallPrint(strid) {
	  var prtContent = document.getElementById(strid);
	  var prtCSS = '<link rel="stylesheet" href="/design/default/css/style.css?v=15" type="text/css" />';
	  var WinPrint = window.open('','','left=50,top=50,width=800,height=640,toolbar=0,scrollbars=1,status=0');
	  WinPrint.document.write('<div id="print" class="contentpane">');
	  WinPrint.document.write(prtCSS);
	  WinPrint.document.write(prtContent.innerHTML);
	  WinPrint.document.write('</div>');
	  WinPrint.document.close();
	  WinPrint.focus();
	  WinPrint.print();
	  WinPrint.close();
	  prtContent.innerHTML=strOldOne;
	}

function checkAmount(ikey) {
	var amount = $('#amount'+ikey).val();
    var stock = $('#amount'+ikey).data('stock');
    if(stock != 1020304050){
        if(amount>stock){
            var newAmount = stock;
        }else{
            var newAmount = amount;
        }
    }else{
        var newAmount = amount;    
    }
    $('#amount'+ikey).val(newAmount);
    $('#AmountSend').click();
}

function number_format(number,decimals,dec_point,thousands_sep) {
    number  = number*1;//makes sure `number` is numeric value
    var str = number.toFixed(decimals?decimals:0).toString().split('.');
    var parts = [];
    for ( var i=str[0].length; i>0; i-=3 ) {
        parts.unshift(str[0].substring(Math.max(0,i-3),i));
    }
    str[0] = parts.join(thousands_sep?thousands_sep:',');
    return str.join(dec_point?dec_point:'.');
}

function reg_login_open() {
	$('#reg_register').hide();
	$('#reg_password').hide();
	$('#reg_login').fadeIn();
}


function reg_register_open() {
	$('#reg_login').hide();
	$('#reg_password').hide();
	$('#reg_register').fadeIn();
}

function reg_password_open() {
	$('#reg_login').hide();
	$('#reg_register').hide();
	$('#reg_password').fadeIn();
}

function alphabet_content_load(id) {
	$('#alphabet-content').empty();
	$('#alphabet-content').load("/classes/ajax/alphabet_content.php?id="+id);
} // end function alphabet_content_load

function addProductToFavoriteold(product_id) {
	$('#fav').modal('open');
	$('#favyesbutton').data('id',product_id);
} // end function addProductToFavorite


function enterModal(sPage = '/') {
	goingPage = sPage;
	$('#bpu').val(goingPage);
	$('#enter').modal('open');
} // end function addProductToFavorite


function reject_item(sop_id,order_id) {
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'rejectitem',
				sop_id: sop_id,
				order_id: order_id
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#rbb'+sop_id).hide();
				   $('#rbc'+sop_id).html('<div class="status_1">отменён</div>');
				   
				   if (data.order_cancel>0) {
					   $('#rbo'+data.order_cancel).html('отменён');
				   }
			   }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}
function setUserType(usertype) {
	$('#usertype').val(usertype);
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'saveusertype',
				usertype: usertype
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function check_rblock() {
	if ($('#f_opt_razgruzka').length>0) {
		if ($('#f_opt_razgruzka').attr('checked')=='checked') {
			$('#rblock').css({
			    display: 'inline-block'
			});
		} else {
			$('#rblock').hide();
		}
	}
}
function addProductToFavorite_proceedold() {
	//alert($('#favyesbutton').data('id'));
	fav=$('#favyesbutton').data('id')
    $.post( "/classes/ajax/Favourites.php", { favourite: fav },onAjaxSuccess);
	function onAjaxSuccess(data){
		$(".aptf"+fav).hide();
		$(".aptfg"+fav).show();
		$('#fav').modal('close');
		$('#favcount').html(data);
	}
} // end function addProductToFavorite_proceed


function deleteProductToFavorite(fav) {
    $.post( "/classes/ajax/Favourites.php", { delete: fav },onAjaxSuccess);
	function onAjaxSuccess(data){
		$(".aptf"+fav).show();
		$(".aptfg"+fav).hide();
		$('#favcount').html(data);
	}
} // end function addProductToFavorite_proceed


function SubF(ict) {
	//alert('hi');
	$('#sf'+ict).css({
	    display: 'block'
	});
	if (ictf) {
		$('#sf'+ictf).css({
		    display: 'none'
		});
	}
	ictf = ict;
}

function addProductToFavorite(product_id) {
	fav = product_id;
	$.post( "/classes/ajax/Favourites.php", { favourite: fav },onAjaxSuccess);
	function onAjaxSuccess(data){
		$(".aptf"+fav).hide();
		$(".aptfg"+fav).show();
		$('#favcount').html(data);
	}
} // end function addProductToFavorite
var acse_sortby = '';
function acse_filter(url) {
	let ibf = '';
	$('.acsebrand').each(function( index ) {
		 value = $(this).val();
		 checked = $(this).is(":checked");
		 if (value && checked) {
			 ibf = ibf+','+value;
		 }
	});

	min = $('#acse_min').val();
	max = $('#acse_max').val();
	$('#acse_main_body').html('');
	$.ajax({
		   type: "POST",
		   url: "/product/"+url,
		   data: {  
			   action: 'acse',
			   ibf: ibf,
			   min: min,
			   max: max,
			   sortby: acse_sortby
		   },
		   timeout: 15000,
		   success: function(data){
			   $('#acse_main_body').html(data);
			   //console.log(data);
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function goCheckSms() {
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'smsauthorizeconfirm',
				smscode: $('#smscode').val()
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  $('#button1').show();
				  $('#button2').show();
				  $('#authorize_block').hide();
				  $('#smsresult').html('');
				  if (data.gocart) {
				  	document.location.href='/cart/?action=order&goformorder=yes';
			  	  }
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#smsresult').html(data.message);
			  }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function goCheckPassword() {
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'smsauthorizeconfirmpassword',
				smspassword: $('#smspassword').val()
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  $('#button1').show();
				  $('#button2').show();
				  $('#authorize_block').hide();
				  $('#authresult').html('');
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#authresult').html(data.message);
			  }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function goSendSms() {
	
	$('#sendsmsbutton').hide();
	
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'smsauthorize'
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   $('#smsresult').html(data.message);
			  if (data.status=='OK') {
				  $('#smsresultgo').show();
				  $('#sendsmsbutton').show();
			  } else {
				  
			  }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function acse_reset(url, min, max) {
	$('.acsebrand').each(function( index ) {
		 $(this).prop("checked",false);
	});
	$('#acse_min').val(min);
	$('#acse_max').val(max);
	acse_filter(url);
}

function acse_gof(url,sFilter) {
	acse_sortby = sFilter;
	acse_filter(url);
}

/**
 *  <a href="javascript:;" class="sort_btn" onClick="acse_gof('bp');">лучшая цена</a> |
                            <a href="javascript:;" class="sort_btn" onClick="acse_gof('popularity');">популярность</a> |
                            <a href="javascript:;" class="sort_btn" onClick="acse_gof('new');">новинки</a> |
                            <a href="javascript:;" class="sort_btn" onClick="acse_gof('pricea');">цена

 */

function addToBasket(product_id, variant_id) {
	
	price1 = $('#price1_'+product_id).val();
	price2 = $('#price2_'+product_id).val();
	pimage = $('#pimage'+product_id).html();
	pname = $('#pname'+product_id).html();
	point_id = 0;
	if ($('#point_id').length>0) {
		point_id = $('#point_id').val();
	}
	
	amount = 1
	if ($('#amount').length>0) {
		amount = $('#amount').val();
	}
	//$('#aimage').html(pimage);
	//$('#aname').html(pname);
	//$('#aprice1').html(price1+' р.');
	//$('#aprice2').html(price2+' р.');
	$(".aptb"+product_id).html('<img src="/design/default/images/loader.gif" width=16px height=16px;>');
	$(".aptb"+product_id).unbind('click');
	
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
			   ajaxCart: 'ok', 
				variant: variant_id, 
				amounts: amount,
				design: 'new',
				point_id: point_id
		   },
		   timeout: 15000,
		   success: function(data){
			   //alert(data);
			   //$('#addb').modal('open');
			   $(".aptb"+product_id).hide();
			   $(".aptbg"+product_id).show();
			   $("#NCartInfo").html(data);
			   
			   $('.dropdown-trigger').dropdown();
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
} // end function addToBasket

function modalAdult() {
	//$//('#modaladult').modal('open',{
	//    backdrop: 'static',
	//    keyboard: false,
	//    opacity: 0.1
	//});
	const elem = document.getElementById('modaladult');
	const instance = M.Modal.init(elem, {dismissible: false,opacity:0.78});
	instance.open();

}


function adultCloseReject() {
	$('#modaladult').modal('close');
	document.location.href="/";
}
function adultCloseAccept() {
	$('#modaladult').modal('close');
	setCookie('f_adult',1,0,'/','.zibero.ru',1);
   $('.a_18').each(function( index ) {
		 $(this).removeClass('a_18');
	});
	
}

function addToBasketC(product_id, variant_id, size_id,color_id) {
	
	price1 = $('#price1_'+product_id).val();
	price2 = $('#price2_'+product_id).val();
	pimage = $('#pimage'+product_id).html();
	pname = $('#pname'+product_id).html();
	
	amount = 1
	if ($('#amount').length>0) {
		amount = $('#amount').val();
	}
	
	//$('#aimage').html(pimage);
	//$('#aname').html(pname);
	//$('#aprice1').html(price1+' р.');
	//$('#aprice2').html(price2+' р.');
	$(".aptb"+product_id).html('<img src="/design/default/images/loader.gif" width=16px height=16px;>');
	$(".aptb"+product_id).unbind('click');
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
			   ajaxCart: 'ok', 
				variant: variant_id, 
				amounts: amount,
				design: 'new',
				size_id: size_id,
				color_id: color_id
		   },
		   timeout: 15000,
		   success: function(data){
			   //alert(data);
			   //$('#addb').modal('open');
			   $(".aptb"+product_id).hide();
			   $(".aptbg"+product_id).show();
			   $("#NCartInfo").html(data);
			   
			   $('.dropdown-trigger').dropdown();
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
} // end function addToBasket

function addToBasketold(product_id, variant_id) {
	
	price1 = $('#price1_'+product_id).val();
	price2 = $('#price2_'+product_id).val();
	pimage = $('#pimage'+product_id).html();
	pname = $('#pname'+product_id).html();
	amount = 1
	
	$('#aimage').html(pimage);
	$('#aname').html(pname);
	$('#aprice1').html(price1+' р.');
	$('#aprice2').html(price2+' р.');
	$(".aptb"+product_id).html('<img src="/design/default/images/loader.gif" width=16px height=16px;>');
	$(".aptb"+product_id).unbind('click');
	
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
			   ajaxCart: 'ok', 
				variant: variant_id, 
				amounts: amount,
				design: 'new'
		   },
		   timeout: 15000,
		   success: function(data){
			   //alert(data);
			   $('#addb').modal('open');
			   $(".aptb"+product_id).hide();
			   $(".aptbg"+product_id).show();
			   $("#NCartInfo").html(data);
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
} // end function addToBasket


function SendPartnerCallbackForm() {
	var p_phone = $('#p_phone').val();
    var p_name = $('#p_name').val();
    var p_firmname = $('#p_firmname').val();
    if(p_phone != '' && p_name != ''  && p_firmname != ''){
    	
    	$.ajax({
 		   type: "POST",
 		   url: "/components/widgets/WCallBack/WCallBack.php",
 		   data: {  
 			  type: 'send', 
 			  phone: p_phone, 
 			  fio: p_name, 
 			  url: 'newpartnerform', 
 			  question: p_firmname,
 			  design: 'new'
 		   },
 		   timeout: 15000,
 		   dataType: "json",
 		   success: function(data){
 			   if (data.status=='OK') {
 				   $('#p_form').hide();
 				  $('#p_phone').val('');
 				  $('#p_name').val('');
 				  $('#p_firmname').val('');
 			   }
 			   $('#p_message').html(data.message);
 			  $('#p_message').css('color','yellow');
 		   },
 		   error: function(XMLHttpRequest, textStatus, errorThrown){
 			   alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
 	       }
    	});
    	
    }else{
        if(p_phone == '') { $('#p_phone').addClass('border-color-red'); }
        if(p_name == '') { $('#p_name').addClass('border-color-red'); }
        if(p_firmname == '') { $('#p_firmname').addClass('border-color-red'); }
    }
    
    return false;
} // end function SendCallBackForm

function SendCallBackForm() {
	var phone = $('#callbackphone').val();
    var fio = $('#callbackname').val();
    if(fio != '' && phone != ''){
    	
    	$.ajax({
 		   type: "POST",
 		   url: "/components/widgets/WCallBack/WCallBack.php",
 		   data: {  
 			  type: 'send', 
 			  phone: phone, 
 			  fio: fio, 
 			  url: 'newcallbackform', 
 			  question: 'callbackform',
 			  design: 'new'
 		   },
 		   timeout: 15000,
 		   success: function(data){
 			   $('#callbackform').html(data)
 		   },
 		   error: function(XMLHttpRequest, textStatus, errorThrown){
 			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
 	       }
    	});
    	
        //$(this).parents('#DialogCallBack').prepend('<div class="ajax-loader"></div>');
        //$(this).parents('#DialogCallBack').load("/components/widgets/WCallBack/WCallBack.php",{type: 'send', phone: phone, fio: fio, url: url, question: question}, function(){
        //    $('.ajax-loader').remove(); DialogCenter($(this));
        //});
    }else{
        if(phone == '') { $('#callbackphone').addClass('border-color-red'); }
        if(fio == '') { $('#callbackname').addClass('border-color-red'); }
    }
} // end function SendCallBackForm

/*
 * $.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'smsauthorize'
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   $('#smsresult').html(data.message);
			  if (data.status=='OK') {
				  $('#smsresultgo').show();
				  $('#sendsmsbutton').show();
			  } else {
				  
			  }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
 */
function send_sms(layer) {
	phone = $('#'+layer).val();
	$('#'+layer+'div').show();
	$('#'+layer+'msg').html('идет запрос кода.....');
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'smsauthorize',
				'phone': phone
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.message!='') {
					$('#'+layer+'msg').html(data.message);
				}	
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}


function ccard_send_sms() {
	phone = $('#p_reg_phone').val();
	//$('#'+layer+'div').show();
	$('#p_reg_phonemsg').html('идет запрос кода.....');
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'csmsauthorize',
				'phone': phone
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.message!='') {
					$('#p_reg_phonemsg').html(data.message);
				}	
				if (data.status=='OK') {
					$('#sms_code_phone').hide();
					$('#sms_code').show();
				}
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function ccard_check_sms() {
	phone = $('#p_reg_phone').val();
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'csmsauthorizeconfirm',
				'smscode': $('#partner_smspassword').val(),
				'phone': phone
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  	$('#partner_sms').hide();
				  	$('#partner_sms_done').show();
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#p_reg_phonemsg').html(data.message);
			  }
		   }, 
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function partner_send_sms() {
	phone = $('#p_reg_phone').val();
	//$('#'+layer+'div').show();
	$('#p_reg_phonemsg').html('идет запрос кода.....');
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'smsauthorize',
				'phone': phone
				},
		   dataType: "json",
		   timeout: 15000,
		   success: function(data){
				if (data.message!='') {
					$('#p_reg_phonemsg').html(data.message);
				}	
				if (data.status=='OK') {
					$('#sms_code_phone').hide();
					$('#sms_code').show();
				}
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function partner_check_sms() {
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'smsauthorizeconfirm',
				'smscode': $('#partner_smspassword').val()
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  	$('#partner_sms').hide();
				  	$('#partner_sms_done').show();
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#p_reg_phonemsg').html(data.message);
			  }
		   }, 
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function goCheckSMSLogin(layer) {
	phone = $('#'+layer).val();
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				'action': 'smsauthorizeconfirm',
				'smscode': $('#passwordphone').val(),
				'phone': phone
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			  
			  if (data.status=='OK') {
				  	document.location.href=goingPage;
			  } else {
				  //$('#sendsmsbutton').show();
				  $('#'+layer+'msg').html(data.message);
			  }
		   }, 
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
	});
}

function openRegions() {
	$('#city').modal({
	    backdrop: 'static',
	    keyboard: false  // to prevent closing with Esc button (if you want this too)
	});
	$('#city').modal('open');
}

var l_city = 0;
var l_street = 0;
var l_house = 0;
var d_in = 0;
var d_timeout = 0;

function cityd() {
	d_in = Math.round(new Date().getTime()/1000)
}

function checkLC() {
	//if (d_timeout == 0) {
		d_timeout = setTimeout('loadCitites()', 2000);
	//} else {
		
	//}
}


function cRedODND(fid,llid,country_id,city_id,country_name,city_name) {

	$('#nd_cities'+llid+'_'+fid).fadeOut(100);
	$('#nd_srs'+llid+'_'+fid+'_id').val(city_id);
	$('#nd_srs'+llid+'_'+fid).val(city_name);
			   
	return false;
}

function nd_check_fields(llid) {
	v1 = $('#nd_srs'+llid+'_0_id').val();
	v2 = $('#nd_srs'+llid+'_1_id').val();
	km = $('#nd_km').val();
	w = $('#nd_weight').val();
	p = $('#nd_price').val();
	if (v1!='' && v2!='' && km!='' && w!='' && p!='') {
		$("#nd_button_0").prop("disabled", false);
	} else {
		$("#nd_button_0").prop("disabled", false);
		$("#nd_button_0").prop("disabled", true);
	}
}

function cRedOD(llid,country_id,city_id,country_name,city_name) {
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				country_id: country_id,
				city_id:city_id,
				action: 'putdCity',
				delivery_id:llid
		   },
		   timeout: 15000,
		   success: function(data){
			   $('#cities'+llid).fadeOut(100);
			   if (data!='') {
				   $('#srr'+llid).html(data);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   
	       }
	});
	return false;
}


function pddDel(pdid,llid) { 
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'deldCity', 
				pdid:pdid,
				delivery_id:llid
		   },
		   timeout: 15000,
		   success: function(data){
			   $('#cities'+llid).fadeOut(100);
			   if (data!='') {
				   $('#srr'+llid).html(data);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   
	       }
	});
	return false;
}

function nd_dregion(layerid) {
	$('.select_region').hide();
	$("#nd_sr"+layerid).show();
	//при открытии закрывать остальные
	return false;
}

function dregion(layerid) {
	
	$('.select_region').hide();
	$.ajax({
		   type: "POST",
		   url: "/classes/FGLine.php",
		   data: {  
				action: 'getdCity',
				delivery_id:layerid
		   },
		   timeout: 15000,
		   success: function(data){
			   //$('#cities'+layerid).fadeOut(100);
			   if (data!='') {
				   $('#srr'+layerid).html(data);
			   } 
			   $("#sr"+layerid).show();
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   
	       }
	});
	
	//при открытии закрывать остальные
	return false;
	
}
function nd_loadDCitites(llid,fid) {
	thiscountry_search = $('#nd_srs'+llid+'_'+fid).val();
	//alert('#nd_srs'+llid+'_'+fid);
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/getDeliveryCities.php",
		   data: {  
				cid: 3159,
				s:thiscountry_search,
				opt:'delivery',
				llid: llid,
				opt: 'nd',
				fid: fid
				},
		   timeout: 15000,
		   success: function(data){
			   if (data!='') {
				   $('#nd_cities'+llid+'_'+fid).html(data);
				   $('#nd_cities'+llid+'_'+fid).css('position','relative !important');
				   $('#nd_cities'+llid+'_'+fid).fadeIn(100);
				   
			   } else {
				   $('#nd_cities'+llid+'_'+fid).fadeOut(100);
			   }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   
	       }
	});
}

function loadDCitites(llid) {

	$('#srr'+llid).empty();
	thiscountry_search = $('#srs'+llid).val();
	
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/getDeliveryCities.php",
		   data: {  
				cid: 3159,
				s:thiscountry_search,
				opt:'delivery',
				llid: llid
				},
		   timeout: 15000,
		   success: function(data){
			   if (data!='') {
				   $('#cities'+llid).html(data);
				   $('#cities'+llid).css('position','relative !important');
				   $('#cities'+llid).fadeIn(100);
				   
			   } else {
				   $('#cities'+llid).fadeOut(100);
			   }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   
	       }
	});
}

function loadCitites() {
	bAllow = true;
	//console.log('d_in',d_in);
	//if (d_in) {
	//	diff = Math.round(new Date().getTime()/1000)-d_in;
	//	//console.log('diff:',diff,' timeout:',d_timeout);
	//	if (diff>=1) {
	//		bAllow = true;
	//		d_in = Math.round(new Date().getTime()/1000);
	//	}
	//}
	if (bAllow) {
		l_city = 1;
		$('#cities_auto').empty();
		thiscountry_search = $('#adres_city').val();
		
		
		$('#streets_auto').empty();
		$('#adres_street').val('');
		$('#streets_auto').hide();
		$('#adres_street_id').val(0);
		$('#houses_auto').hide().empty();
		$('#adres_house').val('');
		$('#adres_house_id').val(0);
		$('#postindex').val('');
		
		
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/getDeliveryCities.php",
			   data: {  
					cid: 3159,
					s:thiscountry_search
					},
			   timeout: 15000,
			   success: function(data){
				   if (data!='') {
					   $('#cities_auto').html(data);
					   $('#cities_auto').css('position','relative !important');
					   $('#cities_auto').fadeIn(100);
					   
				   } else {
					   $('#cities_auto').fadeOut(100);
				   }
				   l_city = 0;
				   clearTimeout(d_timeout);
				   d_timeout = 0;
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   l_city = 0;
				   clearTimeout(d_timeout);
				   d_timeout = 0;
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	} else {
		   clearTimeout(d_timeout);
		   d_timeout = 0;
	}
}
function cRedO(country_id,city_id,country_name,city_name) {
	$('#cities_auto').fadeOut(100);
	$('#adres_city').val(city_name);
	$('#adres_city_id').val(city_id);
	return false;
}


function loadBIK() {
	thissearch = $('#bik_jur').val();
	if (thissearch.length==9) {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/getBIK.php",
			   data: {  
					s: thissearch,
					},
			   timeout: 15000,
			   dataType: "json",
			   success: function(data){
				   console.log(data);
				   if (data!=null) {
					   if (data.BIC!='') {
						   		/*
						   		 * 
						   		 * bankname_jur = NameP
						   		 * kschet_jur = Account
						   		 */
						   $('#bankname_jur').val(data.NameP);
						   $('#kschet_jur').val(data.Account);
					   } else {
						   $('#bankname_jur').val('');
						   $('#kschet_jur').val('');
					   }
				   } else {
					   $('#bankname_jur').val('');
					   $('#kschet_jur').val('');
				   }
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //
		       }
		});
	} else {
		$('#bankname_jur').val('');
		$('#kschet_jur').val('');
	}
}
//loadHouses
function loadHouses() {
	//if (l_house==0) {
		l_house = 1;
		$('#houses_auto').empty();
		thiscountry_search = $('#adres_house').val();
		//alert(thiscountry_search);
		
		$('#postindex').val('');
		
		street_id = $('#adres_street_id').val();
		city_id = $('#adres_city_id').val();
		//we can search houses without streets
		//if (street_id) {
			$.ajax({
				   type: "POST",
				   url: "/classes/ajax/getDeliveryHouses.php",
				   data: {  
						cid: 3159,
						s: thiscountry_search,
						street_id: street_id,
						city_id: city_id
						},
				   timeout: 15000,
				   success: function(data){
					   if (data!='') {
						   $('#houses_auto').html(data);
						   $('#houses_auto').css('position','relative !important');
						   $('#houses_auto').fadeIn(100);
						   
					   } else {
						   $('#houses_auto').fadeOut(100);
					   }
					   l_house = 0;
				   },
				   error: function(XMLHttpRequest, textStatus, errorThrown){
					   l_house = 0;
					   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
			       }
			});
		//}
	//}
}
function cRedO2(house_id, house_name,postindex) {
	$('#houses_auto').fadeOut(100);
	$('#adres_house').val(house_name);
	$('#adres_house_id').val(house_id);
	$('#postindex').val(postindex);
	return false;
}

function loadStreets() {
	//if (l_street==0) {
		l_street = 1;
		$('#streets_auto').empty();
		thiscountry_search = $('#adres_street').val();
		//alert(thiscountry_search);
		//exit;
		city_id = $('#adres_city_id').val();
		
		$('#houses_auto').hide().empty();
		$('#adres_house').val('');
		$('#adres_house_id').val(0);
		$('#postindex').val('');
		
		if (city_id) {
			$.ajax({
				   type: "POST",
				   url: "/classes/ajax/getDeliveryStreets.php",
				   data: {  
						cid: 3159,
						s: thiscountry_search,
						city_id: city_id
						},
				   timeout: 15000,
				   success: function(data){
					   if (data!='') {
						   $('#streets_auto').html(data);
						   $('#streets_auto').css('position','relative !important');
						   $('#streets_auto').fadeIn(100);
						   
					   } else {
						   $('#streets_auto').fadeOut(100);
					   }
					   l_street = 0;
				   },
				   error: function(XMLHttpRequest, textStatus, errorThrown){
					   l_street = 0;
					   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
			       }
			});
		}
	//}
}
function cRedO1(street_id, street_name) {
	$('#streets_auto').fadeOut(100);
	$('#adres_street').val(street_name);
	$('#adres_street_id').val(street_id);
	return false;
}

function loadRegion() {
	$('#cities_content').empty();
	thiscountry_id = $( "#country_id option:selected" ).val();
	thiscountry_search = $('#searchcity').val();
	console.log(thiscountry_id,thiscountry_search);
	
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/getCities.php",
		   data: {  
				cid: thiscountry_id,
				s:thiscountry_search
				},
		   timeout: 15000,
		   success: function(data){
			   $('#cities_content').html(data);	
			   //$('#searchcity').click(); 
			   //$('#searchcity').focus(); 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}


function load_item_tickets(order_id) {
	$('#tickets').empty();
	$('#tickets').load("/classes/ajax/load_item_tickets.php?id="+order_id);
}

function load_item_date(order_id) {
	$('#itemdate').load("/classes/ajax/load_item_date.php?id="+order_id);
}

function select_item_date_point(order_id) {
	pid = $('#point_id').val();
	$('#itemdate').load("/classes/ajax/load_item_date.php?id="+order_id+'&point_id='+pid, function(){
		load_item_tickets(order_id);
	});
}

function select_item_date_tovaroved(order_id) {
	tid = $('#tovaroved_id').val();
	$('#itemdate').load("/classes/ajax/load_item_date.php?id="+order_id+'&tovaroved_id='+tid);
}

function select_item_date_courier(order_id) {
	cid = $('#courier_id').val();
	$('#itemdate').load("/classes/ajax/load_item_date.php?id="+order_id+'&courier_id='+cid);
}

function save_pnumber(sop_id) {
	pnumber = $('#pnumber'+sop_id).val();
	//alert(pnumber);
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/save_pnumber.php",
		   data: {  
				sop_id: sop_id,
				pnumber:pnumber
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   //console.log(data);
			   if (data.status=='SUCCESS') {
				   //alert('here');
				   alert('Сохранено');
				   $('#pnumber'+sop_id).css('border','1px solid green');
				   load_item_tickets(data.order_id);
			   } else {
				   $('#pnumber'+sop_id).css('border','1px solid red');				   
			   }
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
}

function cRe(country_id,city_id,country_name,city_name) {
	//alert('clioc'); 
	setCookie('country_id',country_id,30*86400,'/','.zibero.ru',1);
	setCookie('city_id',city_id,30*86400,'/','.zibero.ru',1);
	$('#my_region_name').html(country_name+', '+city_name);
	$('#searchcity').val('');
	$('#city').modal('close');
	loadRegion();
	return false;
}

function setCookie (name, value, expires, path, domain, secure) {

	var todaydate=new Date();
	var expdate=new Date(todaydate.getTime()+expires*1000);
	expiresT=expdate.toGMTString();
	//alert(todaydate.toGMTString()+' '+expiresT);
      
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expiresT : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");

        //console.log(document.cookie);
}

function check_whereto() {
	where_return = $("input[name='where_return']:checked").val();
	if (where_return=='account') {
		$('#wbank').hide();
		$('#wcard').hide();
	}
	if (where_return=='card') {
		$('#wbank').hide();
		$('#wcard').show();
	}
	if (where_return=='bankaccount') {
		$('#wbank').show();
		$('#wcard').hide();
	}
}

function pinfo_remove_tag(id,l='t') {
	$('#'+l+'_'+id).remove();
}

function pinfo_remove_cat(id) {
	$('#c_'+id).remove();
	$('#cc_'+id).prop('checked',false);
}

function info_product_tags_add() {
	$('#tagadd').hide();
	$('#ttrigger').show();
	val = $('#tag_add').val();
	$('#tag_add').val('');
	
	val = val.replace('#','');
	val = val.replace('#','');
	
	const myArray = val.split(",");
	//console.log(myArray);
	
	if (myArray.length>0) {
		for (i=0;i<myArray.length;i++) {
			oneword = myArray[i].trim(); 
			if (oneword!='') {
				$('#tegslist').append('<div class="acc-info-product__teg tlsvx" id="t_'+pinfo_tag_count+'" onClick="pinfo_remove_tag('+pinfo_tag_count+');" data-title="'+oneword+'">'+oneword+'</div>');
				pinfo_tag_count++;
			}
		}
	}
	
}

function pinfocheckcd(id) {
	
	if (id==100) {
		check = $('#cd'+id).prop('checked');
		if (check) {
			$('#cd11').prop('checked',true);
			$('#cd13').prop('checked',true);
			$('#cd12').prop('checked',true);
			$('#cd14').prop('checked',true);
			$('#cd17').prop('checked',true);
			$('#cd15').prop('checked',true);
			pinfocheckallcd();
		} else {
			$('#cd11').prop('checked',false);
			$('#cd13').prop('checked',false);
			$('#cd12').prop('checked',false);
			$('#cd14').prop('checked',false);
			$('#cd17').prop('checked',false);
			$('#cd15').prop('checked',false);
			pinfocheckallcd();
		}
	} else {
		check = $('#cd'+id).prop('checked');
		if (check) {
			$('.cd'+id).css('opacity',0.3);
			$('.rcd'+id).hide();
			$('.icd'+id).attr('disabled','disabled');
			$('.icd'+id).attr('readonly', true);
		} else {
			$('.cd'+id).css('opacity',1);
			$('.rcd'+id).show();
			$('.icd'+id).removeAttr('disabled');
			$('.icd'+id).removeAttr('readonly');
		}
	}
}


function check_delivery_layers() {
	if (f_no_return) {
		$('#lvozvrat').hide();
		$('#lvozvratn').show();
	} else {
		$('#lvozvrat').show();
		$('#lvozvratn').hide();
	}
	//alert(f_only_express);
	if (f_only_express) {
		$('.cd11').hide(); $('.rcd11').hide();
		$('.cd13').hide(); $('.rcd13').hide();
		$('.cd12').hide(); $('.rcd12').hide();
		$('.cd14').hide(); $('.rcd14').hide();
		$('.cd17').hide(); $('.rcd17').hide();
		$('.cd15').hide(); $('.rcd15').hide();
		$('#lcd16').hide();
		$('#htl').hide();
	} else {
		$('.cd11').show(); $('.rcd11').show();
		$('.cd13').show(); $('.rcd13').show();
		$('.cd12').show(); $('.rcd12').show();
		$('.cd14').show(); $('.rcd14').show();
		$('.cd17').show(); $('.rcd17').show();
		$('.cd15').show(); $('.rcd15').show();
		$('#lcd16').show();
		$('#htl').show();
		
		if (f_nopost) {
			$('.cd13').hide(); $('.rcd13').hide();
		}
	}
}

function pinfocheckallcd() {
	pinfocheckcd(11);
	pinfocheckcd(13);
	pinfocheckcd(12);
	pinfocheckcd(14);
	pinfocheckcd(17);
	pinfocheckcd(15);
}

var current_property_id = 0;
var globalTimeout1 = null;
var current_group_id = 0;


function rem_adop(id) {
	$('#adop_'+id).remove();
	
	news = [];
	for (i=0;i<vsizes.length;i++) {
		element = vsizes[i];
		if (element[0]==id) {
			//skip
		} else {
			news.push(element);
		}
	}
	vsizes = news;
	console.log('after',vsizes);
}

function init_vsizes() {
	
	//addextraright
	
	if (vsizes.length>0) {
		sHTML = '';
		sHTML = sHTML + '<ul class="filters-lvl1">';
		
		for (i=0;i<vsizes.length;i++) {
			element = vsizes[i];
			sChecked = 'checked'; 
			//[24,"",10,"Белый","#FFFFFF","11.5"];
			sHTML = sHTML+ '<li id="adop_'+element[0]+'"><label><input '+sChecked+' type="checkbox"  onClick="rem_adop('+element[0]+');" class="filled-in"/><span>'+element[3]+' р. '+element[5]+' шт.: '+element[2]+' арт.: '+element[1]+'</span></label></li>';
		}
		sHTML = sHTML+ '<ul>';
		$('#addextraright').html(sHTML);
		
	}
}

function addextraoption() {
	color_id=$("input[name='color_id']:checked").val();
	size_id = $("input[name='size_id']:checked").val();
	addq = parseInt($("input[name='addq']").val());
	articul = $("input[name='addqa']").val();
	if (color_id>0 && size_id>0 && addq>0) {
		color_name=$("input[name='color_id']:checked").data('title');
		size_name = $("input[name='size_id']:checked").data('title');
		console.log(color_id,size_id,addq,articul,color_name,size_name);
		//       ?>vsizes[<?php echo $ik?>] = [<?php echo $arVals['id']?>,"<?php echo $arVals['articul']?>",<?php echo $arVals['quantity']?>,"<?php echo $arVals['color_name']?>","<?php echo $arVals['color_hex']?>","<?php echo $arVals['size_name']?>",<?php echo $arVals['color_id']?>,<?php echo $arVals['size_id']?>];<?php
		max_vid++;
		arTmp = [max_vid,articul,addq,color_name,'',size_name,color_id,size_id];
		vsizes.push(arTmp);
		init_vsizes();
		//console.log(arTmp);
		alert('Вариант-размер добавлен');
		$('html, body').animate({
            scrollTop: $("#addextraright").offset().top
        }, 2000); 
		
		
	} else {
		alert("Не все данные веедены");
	}
	
}

function construct_table_set() {
	if (table_set_id>0) {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/get_tableset.php",
			   data: {   
					id: table_set_id
					},
			   timeout: 15000,
			   dataType: "json",
			   success: function(data){
				   console.log('data loaded');
				   if (data.status=='SUCCESS') {
					   
					   $('#addextra').show();
					   $('#addextrai').hide();
					   
					   sHTML = '';
					   for(i=0;i<data.colors.length;i++) {
						   sHTML = sHTML + '<label class="checkbox '+data.colors[i].c+'">'+
										'<input class="checkbox__input" type="radio" value="'+data.colors[i].i+'" name="color_id" id="color_id'+data.colors[i].i+'" data-title="'+data.colors[i].n+'">'+
										'<span class="checkbox__text"><span></span></span>'+
									'</label>';
					   }
					   $('#addextracolors').html(sHTML);
					   
					   sHTML = '';
					   for(i=0;i<data.sizes.length;i++) {
						   sHTML = sHTML + '<label class="checkbox">'+
							'<input class="checkbox__input" type="radio" value="'+data.sizes[i].i+'" name="size_id" id="size_id'+data.sizes[i].i+'" data-title="'+data.sizes[i].n+'">'+
							'<span class="checkbox__text"><span>'+data.sizes[i].n+'</span></span>'+
							'</label>';
					   }
					   $('#addextrasizes').html(sHTML);
					   
					   init_vsizes();
					   
				   } else {
					   $('#addextra').hide();
					   $('#addextrai').show();
				   }
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	} else {
		   $('#addextra').hide();
		   $('#addextrai').show();
	   }
}

function savePInfo(section) {
	
	variant_id = $('#variant_id').val();
	product_id = $('#product_id').val();
	
	if (section=='general') {
		
		$('#bt_general').attr('DISABLED',true);
		$('#bt_general').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
		
		tags= '';
		$('.tlsvx').each(function(index,item){
		   tags = tags + ',' + $(item).data('title');
		});
		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				product_name: $('#product_name').val(),
				category: $('#category').val(),
				brand: $('#brand').val(),
				product_articul: $('#product_articul').val(),
				variant_articul_v: $('#variant_articul_v').val(),
				tags: tags
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_general').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
		
	} // general
	
	
	if (section=='price') {
		$('#bt_price').attr('DISABLED',true);
		$('#bt_price').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				price_v: $('#acc-15').val(),
				old_price_v: $('#old_price_v').val(),
				nds: $('input[name="nds"]:checked').val()
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_price').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // price
	
	if (section=='avail') {
		$('#bt_avail').attr('DISABLED',true);
		$('#bt_avail').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				stock_v: $('#acc-22').val()
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_avail').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // avail

	if (section=='info') {
		$('#bt_info').attr('DISABLED',true);
		$('#bt_info').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');

		rlf = 0;
		role_termolab = 0;
		role_gnvls = 0;
		hit = 0;
		f_cert = 0;
		if ($('#pt_1').is(":visible")) {
			rlf = 1;
			if ($('#role_termolab').is(":checked")) role_termolab=1;
			if ($('#role_gnvls').is(":checked")) role_gnvls = 1;
			if ($('#hit').is(":checked")) hit = 1;
		}
		if ($('#pt_1').is(":visible")) {
			f_cert = 1;
		}

		rkb = 0; one_volume=0;
		if ($('#kubatura').is(":visible")) {
			rkb = 1;
			one_volume = $('#one_volume').val();
		}

		properties = '';
		props.forEach((element, index /*, array */) => {
			//console.log(`a[${index}] = ${element}`);
			sChecked = '';
			properties = properties + index + ':';
			//console.log(element,index);
			if (typeof props[index] !== 'undefined') {
				for(i=0;i<props[index].length;i++) {
					el = props[index][i];
					properties = properties + el[0] + ',';
				}
			}
			properties = properties + ';';
		});

		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				description_product: $('#description_product').val(),
				width: $('#width').val(),
				height: $('#height').val(),
				depth: $('#height').val(),
				weightcargo: $('#weightcargo').val(),
				rlf: rlf,
				role_termolab: role_termolab,
				role_gnvls: role_gnvls,
				hit: hit,
				f_cert: f_cert,
				props: properties,
				rkb: rkb,
				one_volume: one_volume
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_info').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // info


	if (section=='media') {
		$('#bt_media').attr('DISABLED',true);
		$('#bt_media').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');

		var qqtgu='';
		var qqtgl='';
		var qqtgun='';
		var qqtgln='';

		$( ".qqtgu" ).each(function() {
			qqtgu = qqtgu + $( this ).val() + ';';
		});
		$( ".qqtgun" ).each(function() {
			qqtgun = qqtgun + $( this ).val() + ';';
		});
		$( ".qqtgl" ).each(function() {
			qqtgl = qqtgl + $( this ).val() + ';';
		});
		$( ".qqtgln" ).each(function() {
			qqtgln = qqtgln + $( this ).val() + ';';
		});

		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				video: $('#acc-20').val(),
				metadescription: $('#acc-21').val(),
				qqtgu: qqtgu,
				qqtgun: qqtgun,
				qqtgl: qqtgl,
				qqtgln: qqtgln
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_media').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // media
	
	
	if (section=='extra') {
		$('#bt_extra').attr('DISABLED',true);
		$('#bt_extra').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
		
		vsizess='';
		for(i=0;i<vsizes.length;i++) {
			el = vsizes[i];
			vsizess = vsizess + '' + el[0]+ ','+el[1]+ ','+el[2]+ ','+el[3]+ ','+el[4]+ ','+el[5]+ ','+el[6]+ ','+el[7]+';';
		} 
		
		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				vsizes: vsizess
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_extra').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // avail

	if (section=='delivery') {
		$('#bt_delivery').attr('DISABLED',true);
		$('#bt_delivery').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');

		vozvrat = 0;
		if (f_no_return) {
			vozvrat =0;
		} else {
			vozvrat = $('#vozvrat').val();
		}
		d = []
		d[11] = '';
		d[13] = '';
		d[12] = '';
		d[14] = '';
		d[17] = '';
		d[15] = '';
		d[16] = '';
		for (r=11;r<=17;r++) {
			if (typeof deliveries[r] !== 'undefined') {
				for (i=0;i<deliveries[r].length;i++) {
					el = deliveries[r][i];
					d[r] = d[r]+ el[0]+','+el[1]+';';
				}
			}
		}

		$.ajax({
		   type: "POST",
		   url: "/user/editproductbyv/"+variant_id,
		   data: {  
				action: 'putsection',
				section: section, 
				days11: $('#days11').val(),
				cd11: $('#cd11').is(":checked"),
				days13: $('#days13').val(),
				cd13: $('#cd13').is(":checked"),
				days12: $('#days12').val(),
				cd12: $('#cd12').is(":checked"),
				days14: $('#days14').val(),
				cd14: $('#cd14').is(":checked"),
				days17: $('#days17').val(),
				cd17: $('#cd17').is(":checked"),
				days15: $('#days15').val(),
				cd15: $('#cd15').is(":checked"),
				days16: $('#days16').val(),
				cd16: $('#cd16').is(":checked"),
				vozvrat: vozvrat,
				rd11: d[11],
				rd12: d[12],
				rd13: d[13],
				rd14: d[14],
				rd15: d[15],
				rd16: d[16],
				rd17: d[17]
		   },
		   timeout: 30000,
		   dataType: "json",
		   success: function(data){
			   if (data.status=='OK') {
				   $('#bt_delivery').html('отправлено на модерацию');
					//$('#bt_general').attr('DISABLED',false);
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			  
	       }
		});
	} // delivery
	
	
}

function _get_category_info(cid) {
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/get_category.php",
		   data: {  
				id: cid
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   console.log('data loaded');
			   if (data.status=='SUCCESS') {
				  /*
				   * <div class="acc-info-product__row sel">
									<label for="acc-11" class="acc-info-product__label">Формат товара</label>
									<select id="acc-11" name="form[]" class="form">
										<option value="1" selected="selected">Грузовой</option>
										<option value="2">Пункт №2</option>
										<option value="3">Пункт №3</option>
										<option value="4">Пункт №4</option>
									</select>
								</div>
				   */
				   $('#properties').empty();
				   
				   if (data.template_id==4) {
					   $('#kubatura').show();
				   }
				   if (data.template_id==1) {
					   $('#pt_1').show();
				   }
				   //alert(data.vozvrat);
				   $('#vozvrat').val(data.vozvrat);
				   console.log(data);
				   if (data.f_only_express>0) {
					   f_only_express = true;
				   }
				   if (data.f_no_return>0) {
					   f_no_return = true;
				   }
				   if (data.f_nopost>0) {
					   f_nopost = true;
				   }
				   if (data.table_set_id>0) {
					   table_set_id = data.table_set_id;
				   }
				   
				   check_delivery_layers();
				   
				   if (data.f_cert>0) {
					   $('#f_cert').show();
				   }
				   
				   current_group_id = 0;
				   
				   data.groups.forEach((element) => {
					   $('#properties').append('<h2>'+element.info.name+'</h2>');
					   if (current_group_id==0) {
						   current_group_id = element.info.id;
					   }
					   element.properties.forEach((myproperty) => {
						   sHTML='';
						   if (myproperty.type=='Select') {
							   sHTML = '<div class="acc-info-product__row sel">'+
									'<label for="acc-11" class="acc-info-product__label">'+myproperty.name+'</label>'+
									'<select id="acc-11" name="form[]" class="form">'+
									'</select>'
								'</div>';
						   }
						   if (myproperty.type=='Checkbox') {
							   
							   sValues = '';
							   
							   if (typeof props[myproperty.id] !== 'undefined') {
								   //console.log('props',props[myproperty.id]);
								   for(i=0;i<props[myproperty.id].length;i++) {
									   sValues= sValues+'<div class="acc-info-product__teg" id="pv'+props[myproperty.id][i][0]+'" onClick="pirpv('+myproperty.id+','+props[myproperty.id][i][0]+');">'+props[myproperty.id][i][1]+
									   '<input type=hidden name=pvs[] value="'+props[myproperty.id][i][0]+'">'+
									   '</div>';
								   }
							   }
							   
							   sHTML = '<div class="acc-info-product__row icon-info-prod">'+
									'<div class="acc-info-product__label">'+myproperty.name+'</div>'+
									'<div class="acc-info-product__tegs" id="property'+myproperty.id+'">'+sValues+
									'</div>'+
									'<div id="op'+myproperty.id+'" class="icon-info-prod-wrapper" onClick="_open_pv('+myproperty.id+');">'+
										'<svg class="" width="12" height="7" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 7L11.1962 0.25H0.803848L6 7Z" fill="black" /></svg>'+
									'</div>'+
								'</div>';
						   }
						   $('#properties').append(sHTML);
					   });
				   });
				   
				   construct_table_set();
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
	
}



function SearchPv(){  
	  pvkey=$('#pvkey').val();
	  if (pvkey.length>=1) {
		  _open_pv(current_property_id,pvkey);
	  }
}

function add_pv() {
	if (current_property_id>0) {
		pvkey=$('#pvkey').val();
   	    if (pvkey.length>=1) {
		  if (confirm('Вы действительно хотите добавить этот вариант?')) {
				$.ajax({
					   type: "POST",
					   url: "/classes/ajax/add_pv.php",
					   data: {  
						    id:current_property_id,
							search: pvkey
							},
					   timeout: 15000,
					   dataType: "json",
					   success: function(data){
						   console.log('data loaded');
						   if (data.status=='SUCCESS') {
							   vid = data.vid;
							   pid = current_property_id;
							   name = pvkey;
							   
							   sHTML = '<div class="acc-info-product__teg" id="pv'+vid+'" onClick="pirpv('+pid+','+vid+');">'+name+
							   '<input type=hidden name=pvs[] value="'+vid+'">'+
							   '</div>';
								$('#property'+pid).append(sHTML);
								x = [vid,''+name+''];
							
								if (typeof props[pid] !== 'undefined') {
									//nothing to do
								} else {
									props[pid] = [];
								}
								props[pid].push(x);
								
								SearchPv();
						   } 
					   },
					   error: function(XMLHttpRequest, textStatus, errorThrown){
						   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
				       }
				});
		  }
	    }
	}
}
function _open_pv(property_id,search='') {
	$('#filter-properties-list').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/get_pv.php",
		   data: {  
				id: property_id,
				search: search
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   console.log('data loaded');
			   if (data.status=='SUCCESS') {
				   
				   $('#filter-properties-list').empty();
				   sHTML = '';
				   sHTML = sHTML + '<ul class="filters-lvl1">';
				   data.groups.forEach((element) => {
					   sChecked = ''
					   if (typeof props[property_id] !== 'undefined') {
						   for(i=0;i<props[property_id].length;i++) {
							   if (props[property_id][i][0]==element.id) {
								   sChecked=' checked';
								   break;
							   }
						   }
					   }
					   sHTML = sHTML+ '<li><label><input '+sChecked+' type="checkbox" id="ppv_'+element.id+'" onClick="pict_pv('+property_id+','+element.id+');" class="filled-in"/><span id="pps_'+element.id+'">'+element.name+'</span></label></li>';
				   });
				   sHTML = sHTML+ '<ul>';
				   $('#filter-properties-list').append(sHTML);
				   
				   current_property_id = property_id;
				   
				   $('#pvkey').keyup(function(){
					  if(globalTimeout1 != null) clearTimeout(globalTimeout1);  
					  globalTimeout1 =setTimeout(SearchPv,200);  
				   });
				   
				   $('#filter-properties').show();
			   } 
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
} // end function _open_pv

function pict_pv(pid,vid) {
	isc = $('#ppv_'+vid).is(":checked");
	if (isc==true) {
		name = $('#pps_'+vid).html();
		sHTML = '<div class="acc-info-product__teg" id="pv'+vid+'" onClick="pirpv('+pid+','+vid+');">'+name+
		   '<input type=hidden name=pvs[] value="'+vid+'">'+
		   '</div>';
		$('#property'+pid).append(sHTML);
		x = [vid,''+name+''];
		
		if (typeof props[pid] !== 'undefined') {
			//nothing to do
		} else {
			props[pid] = [];
		}
		props[pid].push(x);
		console.log(props[pid],x);
	} else {
		pirpv(pid,vid);
	}
}

function pinfo_price(vid) {
	
	price_v = parseFloat($('#acc-15').val());
	old_price_v = parseFloat($('#acc-15').val());
	category = $('#category').val();
	
	
	if (price_v>0) {
		$('#cpldp').hide();
		$('#cpld').show();
		$.ajax({
			   type: "POST",
			   url: "/user/editproductbyv/"+vid,
			   data: {  
					action: 'getprice',
					price_v: price_v,
					old_price_v: old_price_v,
					category: category
					},
			   timeout: 30000,
			   dataType: "json",
			   success: function(data){
				   if (data.status=='OK') {
					   $('#acc-cp').val(data.price_club);
					   
				   } else {
					   $('#acc-cp').val('Ошибка');
				   }
					
					$('#cpldp').show();
					$('#cpld').hide();

			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				  
		       }
		});
	} 
	
}

function pirpv(pid,vid) {
	$('#pv'+vid).remove();
	$('#ppv_'+vid).prop('checked',false);
	
	
	//remove
	if (typeof props[pid] !== 'undefined') {
	   myarray = props[pid];
	   newar = [];
	   for(i=0;i<myarray.length;i++) {
		   console.log('element to del ',myarray[i][0],vid);
		   
		   if (myarray[i][0]==vid) {
			   //x = myarray.splice(i,i);
			   //console.log('splice',i,x);
			   //props[pid] = x;
			   //break;
		   } else {
			   newar.push(myarray[i]);
		   }
	   }
	   props[pid] = newar;
   }
   console.log(props[pid]);
}

function info_product_propadd_open() {
	$('#propaddbutton').hide();
	$('#propadd').show();
}

function info_product_propadd() {
	p_name = $('#new_p_name').val();
	p_value = $('#new_p_value').val();
	category = $('#category').val();
	
	if (p_name!='' && p_value!='') {
		$.ajax({
			   type: "POST",
			   url: "/classes/ajax/add_property.php",
			   data: {  
					name: p_name,
					value: p_value,
					category: category,
					group: current_group_id
					},
			   timeout: 15000,
			   dataType: "json",
			   success: function(data){
				   console.log('data loaded');
				   if (data.status=='SUCCESS') {
					   $('#propaddbutton').show();
					   $('#propadd').hide();
					   $('#new_p_name').val('');
					   $('#new_p_value').val('');
					   
					   pid = data.property_id;
					   
					   data.values.forEach((element) => {
						   //добавляем в массивы Значения для свойства
						   x = [element.id,''+element.name+''];
							if (typeof props[pid] !== 'undefined') {
								//nothing to do
							} else {
								props[pid] = [];
							}
							props[pid].push(x);
					   });
					   
					   sValues = '';
					   if (typeof props[pid] !== 'undefined') {
						   //console.log('props',props[myproperty.id]);
						   for(i=0;i<props[pid].length;i++) {
							   sValues= sValues+'<div class="acc-info-product__teg" id="pv'+props[pid][i][0]+'" onClick="pirpv('+pid+','+props[pid][i][0]+');">'+props[pid][i][1]+
							   '<input type=hidden name=pvs[] value="'+props[pid][i][0]+'">'+
							   '</div>';
						   }
					   }
					   
					   sHTML = '<div class="acc-info-product__row icon-info-prod">'+
						'<div class="acc-info-product__label">'+p_name+'</div>'+
						'<div class="acc-info-product__tegs" id="property'+pid+'">'+sValues+
						'</div>'+
						'<div id="op'+pid+'" class="icon-info-prod-wrapper" onClick="_open_pv('+pid+');">'+
							'<svg class="" width="12" height="7" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 7L11.1962 0.25H0.803848L6 7Z" fill="black" /></svg>'+
						'</div>'+
					'</div>';
				   
				   $('#properties').append(sHTML);
					   
				   } else {
					   alert(data.message);
				   }
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		});
	} else {
		alert('укажите название опции и значение(я)');
	}
}

function pict(cid) {
	isc = $('#cc_'+cid).is(":checked");
	if (isc==true) {
		name = $('#cs'+cid).html();
		$('#catslist').html('<div class="acc-info-product__teg sjd" id="c_'+cid+'">'+name+'<input type=hidden name=category id=category value="'+cid+'"></div>');
		_get_category_info(cid);
	} else {
		pinfo_remove_cat(cid);
	}
}

/**
 * init area
 */
var globalTimeout = null;

function SearchFuncBrand(){  
	  globalTimeout = null;  
	  brand_name=$('#brand_name').val();
	  
	  if (brand_name.length>2) {
		  $('#brends-drop').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
		  $('#brends-drop').show();
		  $.ajax({
			   type: "POST",
			   url: "/classes/ajax/get_brand.php",
			   data: {  
					name: brand_name,
					},
			   timeout: 15000,
			   dataType: "html",
			   success: function(data){
				   $('#brends-drop').html(data);
			   },
			   error: function(XMLHttpRequest, textStatus, errorThrown){
				   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
		       }
		  });
	  } else {
		  $('#brends-drop').hide();
	  }
}
function pinfo_sb(id,name) {
	$('#brand_name').val(name);
	$('#brand').val(id);
	$('#brends-drop').hide();
	
}


//delivery regions
var current_delivery_id = 0;
function open_region(delivery_id) {
	$('#regionkey').val('');
	$('#filter-region').show();
	$('#filter-region-list').empty();
	current_delivery_id = delivery_id;
	
	 $('#regionkey').keyup(function(){
	  if(globalTimeout1 != null) clearTimeout(globalTimeout1);  
	  globalTimeout1 =setTimeout(SearchRegion,200);  
     });
	 
} //end function open_region

function SearchRegion(){  
	  regionkey=$('#regionkey').val();
	  if (regionkey.length>=1) {
		  _open_region(current_delivery_id,regionkey);
	  }
}

function _open_region(delivery_id,search='') {
	$('#filter-region-list').html('<img src=//zibero.ru/design/newdesign/images/loader.gif border=0>');
	$.ajax({
		   type: "POST",
		   url: "/classes/ajax/get_dcity.php",
		   data: {  
				delivery_id: delivery_id,
				search: search
				},
		   timeout: 15000,
		   dataType: "json",
		   success: function(data){
			   console.log('data loaded',data);
			   if (data.status=='SUCCESS') {
				   
				   $('#filter-region-list').empty();
				   sHTML = '';
				   sHTML = sHTML + '<ul class="filters-lvl1">';
				   
				   data.groups.forEach((element) => {
					   sChecked = ''
						   
					   if (typeof deliveries[delivery_id] !== 'undefined') {
						   for(i=0;i<deliveries[delivery_id].length;i++) {
							   if (deliveries[delivery_id][i][0]==element.city_id) {
								   sChecked=' checked';
								   break;
							   }
						   }
					   }
					   sHTML = sHTML+ '<li><label><input '+sChecked+' type="checkbox" id="cityid'+delivery_id+'_'+element.city_id+'" onClick="pict_region('+delivery_id+','+element.city_id+');" class="filled-in"/><span id="cityids'+delivery_id+'_'+element.city_id+'">'+element.name+'</span> ('+element.title+') </label></li>';
				   });
				   sHTML = sHTML+ '<ul>';
				   $('#filter-region-list').append(sHTML);
				    
				   
			   } else {
				   sHTML = 'По Вашему запросу не найдено населенных пунктов';
				   $('#filter-region-list').empty();
				   $('#filter-region-list').append(sHTML);
			   }
			   
		   },
		   error: function(XMLHttpRequest, textStatus, errorThrown){
			   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
	       }
	});
} // end function _open_pv

function pict_region(delivery_id,city_id) {
	isc = $('#cityid'+delivery_id+'_'+city_id).is(":checked");
	if (isc==true) {
		name = $('#cityids'+delivery_id+'_'+city_id).html();
		sHTML = '<div class="acc-info-product__teg" id="pcity'+delivery_id+'_'+city_id+'" onClick="pirregion('+delivery_id+','+city_id+');">'+name+
		   '<input type=hidden name=cities'+delivery_id+'[] value="'+city_id+'">'+
		   '</div>';
		$('#rlist'+delivery_id).append(sHTML);
		x = [city_id,''+name+''];
		
		if (typeof deliveries[delivery_id] !== 'undefined') {
			//nothing to do
		} else {
			deliveries[delivery_id] = [];
		}
		deliveries[delivery_id].push(x);
		console.log(deliveries[delivery_id],x);
	} else {
		pirregion(delivery_id,city_id);
	}
}

function deliveries_init() {
	//console.log(deliveries);
	Object.entries(deliveries).forEach(entry => {
	  const [key, value] = entry;
	  for(i=0;i<value.length;i++) {
		  sHTML = '<div class="acc-info-product__teg" id="pcity'+key+'_'+value[i][0]+'" onClick="pirregion('+key+','+value[i][0]+');">'+value[i][1]+
		   '<input type=hidden name=cities'+key+'[] value="'+value[i][0]+'">'+
		   '</div>';
		  $('#rlist'+key).append(sHTML);
	  }
	});
}



function pirregion(delivery_id,city_id) {
	$('#pcity'+delivery_id+'_'+city_id).remove();
	$('#cityid'+delivery_id+'_'+city_id).prop('checked',false);
	//remove
	if (typeof deliveries[delivery_id] !== 'undefined') {
	   myarray = deliveries[delivery_id];
	   newar = [];
	   for(i=0;i<myarray.length;i++) {
		   console.log('element to del ',myarray[i][0],city_id);
		   
		   if (myarray[i][0]==city_id) {
			   //x = myarray.splice(i,i);
			   //console.log('splice',i,x);
			   //props[pid] = x;
			   //break;
		   } else {
			   newar.push(myarray[i]);
		   }
	   }
	   deliveries[delivery_id] = newar;
   }
   console.log(deliveries[delivery_id]);
}


function add_region() {
	/*if (current_delivery_id>0) {
		pvkey=$('#pvkey').val();
   	    if (pvkey.length>=1) {
		  if (confirm('Вы действительно хотите добавить этот вариант?')) {
				$.ajax({
					   type: "POST",
					   url: "/classes/ajax/add_pv.php",
					   data: {  
						    id:current_property_id,
							search: pvkey
							},
					   timeout: 15000,
					   dataType: "json",
					   success: function(data){
						   console.log('data loaded');
						   if (data.status=='SUCCESS') {
							   vid = data.vid;
							   pid = current_property_id;
							   name = pvkey;
							   
							   sHTML = '<div class="acc-info-product__teg" id="pv'+vid+'" onClick="pirpv('+pid+','+vid+');">'+name+
							   '<input type=hidden name=pvs[] value="'+vid+'">'+
							   '</div>';
								$('#property'+pid).append(sHTML);
								x = [vid,''+name+''];
							
								if (typeof props[pid] !== 'undefined') {
									//nothing to do
								} else {
									props[pid] = [];
								}
								props[pid].push(x);
								
								SearchPv();
						   } 
					   },
					   error: function(XMLHttpRequest, textStatus, errorThrown){
						   //alert('произошла ошибка загрузка формы. пожалуйста попробуйте снова');
				       }
				});
		  }
	    }
	}*/
}

$(document).ready(function(){

	
	$('.lazy').Lazy();
	
	$('.card_numeric_mask').mask('9999');
	
	//vozvrat
	if ($('#wbank').length>0) {
		check_whereto();
		$('#cardnumber').mask('9999 9999 9999 9999 99');
		$('#vbik').mask('999999999');
		$('#rs').mask('99999999999999999999');
	}
	//for order page
	check_rblock();
	
	$("#callbackphone").mask("+7 (999) 999-9999");
	//$("#passwordphone").mask("+7 (999) 999-9999");
	$("#phone").mask("+7 (999) 999-9999");
	
	if ($('#reg_phone').length>0) {
		$("#reg_phone").mask("+7 (999) 999-9999");
	}
	if ($('#p_phone').length>0) {
		$("#p_phone").mask("+7 (999) 999-9999");
	}
	
	if ($('.phone_masked').length>0) {
		$(".phone_masked").mask("+7 (999) 999-99-99");
	}
	if ($('.date_masked').length>0) {
		$(".date_masked").mask("99.99.9999");
	}
	
	loadRegion();
		
	 $('.tabs-prod').tabs({
         swipeable: true
    });
	 
	 //$('.images').HvrSlider();
	    $('.zoom').zoom();
    $('.imagess').each(function( index ) {
		 id = $(this).attr('id');
		 $('#'+id).HvrSlider();
		 console.log('hvr',id);
	});
	// Карусель товаров ----------------
	$('.scasepattern').each(function( index ) {
		 id = $(this).attr('id');
	     $("."+id).owlCarousel({
			itemsDesktop:     6,
			itemsDesktop:      [1920, 6],
			itemsDesktopSmall: [1400, 5],
			itemsMobile:       [420, 1],
			lazyLoad:true

		});
		$('.'+id+'-prev').click(function () {
			idd =  $(this).attr('id').match(/\d+/);
			$(".scase"+idd).trigger('owl.prev');
			return false;
		});
		$('.'+id+'-next').click(function () {
			idd =  $(this).attr('id').match(/\d+/);
			$(".scase"+idd).trigger('owl.next');
			return false;
		});
	});

	$('.scasepatternnew').each(function( index ) {
		 id = $(this).attr('id');
	     $("."+id).slick({
	         infinite: true,
	         slidesToShow: 4,
	         slidesToScroll: 4,
	         lazyLoad: 'ondemand'
	     });
	});
	
	$('.scasepatternnew6').each(function( index ) {
		 id = $(this).attr('id');
	     $("."+id).slick({
	         infinite: true,
	         slidesToShow: 6,
	         slidesToScroll: 6,
	         lazyLoad: 'ondemand'
	     });
	});

		
	//страница товара
	$('button.less').click(function(){
        var amount = $(this).parents('.buttons').find('input[name*=amount]').val();
        amount = amount*1-1;
        if(amount <= 0){amount = 1;}
        $(this).parents('.buttons').find('input[name*=amount]').val(amount);
        //$('#AmountSend').click();
       // console.log('lessmore',lessmorecs);
        if (typeof lessmorecs !== 'undefined' && lessmorecs) {
        	_check_amount();
        }
    });
    $('button.more').click(function(){
        var amount = $(this).parents('.buttons').find('input[name*=amount]').val();
        var stock = $(this).parents('.buttons').find('input[name*=amount]').data('stock');
        if(stock != 1020304050){
            if(stock < amount*1+1){
                var newAmount = amount*1;
            }else{
                var newAmount = amount*1+1;
            }
        }else{
            var newAmount = amount*1+1;    
        }
        $(this).parents('.buttons').find('input[name*=amount]').val(newAmount);
        if(newAmount*1 == amount*1){
            alert("На складе больше нет.");
        }else{
            //console.log($(this));
            //$('#AmountSend').click();
        }
        //console.log('lessmore',lessmorecs);
        if (typeof lessmorecs !== 'undefined' && lessmorecs) {
        	_check_amount();
        }
    });
    $('.buttons input[name*=amount]').change(function(){
        var amount = $(this).val();
        var stock = $(this).data('stock');
        if(stock != 1020304050){
            if(amount > stock){
                alert("На складе только "+stock);
                $(this).val(stock);
        //$('#AmountSend').click();
            }else{
                if(amount > 0){
        //$('#AmountSend').click();
                }
            }
        }
    });
    
    if ($('#OCOPhone').length>0) {
       $("#OCOPhone").mask("+7 (999) 999-9999");
	}
    if ($('#bik_jur').length>0) {
        $("#bik_jur").mask("999999999");
 	}
    if ($('#schet_jur').length>0) {
        $("#schet_jur").mask("99999999999999999999");
    }
    
    if ($('#kschet_jur').length>0) {
        $("#kschet_jur").mask("99999999999999999999");
    }
    if ($('#inn_jur').length>0) {
        $("#inn_jur").mask("999999999999");
    }
    if ($('#ogrn_jur').length>0) {
        $("#ogrn_jur").mask("999999999999999");
    }
    if ($('#okpo_jur').length>0) {
        $("#okpo_jur").mask("9999999999");
    }
    if ($('#vphone').length>0) {
        $("#vphone").mask("+7 (999) 999-9999");
 	}
    
    
    //if it is edit product form
    if ($('#acc-info-product-general').length>0) {
	    
    	$("#triger-open-filters").click(function () {
			$("#filter-category").toggleClass("active");
		});
	    
		//$("#triger-open-filters-region").click(function () {
		//	$("#filter-region").toggleClass("active");
		//});
		
		$("#triger-open-filters-region2").click(function () {
			$("#filter-region-promo").toggleClass("active");
		});
		
		$('#brand_name').keyup(function(){
		  if(globalTimeout != null) clearTimeout(globalTimeout);  
		  globalTimeout =setTimeout(SearchFuncBrand,200);  
		});   
		
		if ($('#category').length>0) {
			_get_category_info($('#category').val());
		}
		
		pinfocheckallcd();
		deliveries_init();
		check_delivery_layers();
    } //edit produrct form
    
    if ($('#fine-uploader-gallery').length>0) {
    	//alert('fineuploader');
    	$('#fine-uploader-gallery').fineUploader({
            template: 'qq-template-gallery',
            request: {
                endpoint: '/fu/endpoint.php'
            },
            thumbnails: {
                placeholders: {
                    waitingPath: '//zibero.ru/design/default/js/pluginfu/placeholders/waiting-generic.png',
                    notAvailablePath: '//zibero.ru/design/default/js/pluginfu/placeholders/not_available-generic.png'
                }
            },
            deleteFile: {
                enabled: true,
                method: 'POST',
                endpoint: '/fu/endpoint.php'
        	},
            validation: {
                allowedExtensions: ['jpeg','jpg'],
                itemLimit: 15,
                minSizeLimit: 16000,
                sizeLimit: 16000000  
            },
            messages: {
            	minSizeError: "Файл имеет слишком маленький размер",
            	sizeError: "файл имеет слишком большой размер"
            },
            callbacks: {
                onComplete: function(id, name, response) {
                    var serverPathToFile = response.uuid,
                        fileItem = this.getItemByFileId(id);
					
                    if (response.success) {
                        var viewBtn = qq(fileItem).getByClass("view-btn")[0];
                        viewBtn.setAttribute("value", serverPathToFile);
                        var viewBtn = qq(fileItem).getByClass("view-btn")[1];
                        viewBtn.setAttribute("value", name);
                    }
                }
            }
        });
    }
    
    //for edit product
    if ($('#fine-uploader-gallery-ep').length>0) {
    	//alert('fineuploader');
    	$('#fine-uploader-gallery-ep').fineUploader({

    		//debug: true,
            template: 'qq-template-gallery',
            request: {
                endpoint: '/fu/endpoint.php'
            },
            thumbnails: {
                placeholders: {
                    waitingPath: '//zibero.ru/design/default/js/pluginfu/placeholders/waiting-generic.png',
                    notAvailablePath: '//zibero.ru/design/default/js/pluginfu/placeholders/not_available-generic.png'
                }
            },
            deleteFile: {
                enabled: true,
                method: 'POST',
                endpoint: '/fu/endpoint.php'
        	},
            validation: {
                allowedExtensions: ['jpeg','jpg','png','gif'],
                itemLimit: 15,
                minSizeLimit: 16000,
                sizeLimit: 16000000  
            },
            formatFileName: function(filename) {
                return filename;
            },
            messages: {
            	minSizeError: "Файл имеет слишком маленький размер",
            	sizeError: "файл имеет слишком большой размер"
            },
            callbacks: {
                onComplete: function(id, name, response) {
                    var serverPathToFile = response.uuid,
                        fileItem = this.getItemByFileId(id);
					
                    if (response.success) {
                        var viewBtn = qq(fileItem).getByClass("view-btn")[0];
                        viewBtn.setAttribute("value", serverPathToFile);
                        var viewBtn = qq(fileItem).getByClass("view-btn")[1];
                        viewBtn.setAttribute("value", name);
                        var viewBtn = qq(fileItem).getByClass("f-filename")[0];
                        viewBtn.innerHTML = name;
                    }
                }
            }
        });
    	
    	$('#fine-uploader-gallery-lp').fineUploader({

    		//debug: true,
            template: 'qq-template-gallery-lp',
            request: {
                endpoint: '/fu/endpoint.php'
            },
            thumbnails: {
                placeholders: {
                    waitingPath: '//zibero.ru/design/default/js/pluginfu/placeholders/waiting-generic.png',
                    notAvailablePath: '//zibero.ru/design/default/js/pluginfu/placeholders/not_available-generic.png'
                }
            },
            deleteFile: {
                enabled: true,
                method: 'POST',
                endpoint: '/fu/endpoint.php'
        	},
            validation: {
                allowedExtensions: ['jpeg','jpg','png','gif','pdf','doc'],
                itemLimit: 15,
                minSizeLimit: 16000,
                sizeLimit: 16000000  
            },
            formatFileName: function(filename) {
                return filename;
            },
            
            messages: {
            	minSizeError: "Файл имеет слишком маленький размер",
            	sizeError: "файл имеет слишком большой размер"
            },
            callbacks: {
                onComplete: function(id, name, response) {
                    var serverPathToFile = response.uuid, fileItem = this.getItemByFileId(id);
                    if (response.success) {
                        var viewBtn = qq(fileItem).getByClass("view-btn")[0];
                        viewBtn.setAttribute("value", serverPathToFile);
                        var viewBtn = qq(fileItem).getByClass("view-btn")[1];
                        viewBtn.setAttribute("value", name);
                        var viewBtn = qq(fileItem).getByClass("f-filename")[0];
                        viewBtn.innerHTML = name;
                    }
                }
            }
        });
    	
    } ///edit pictures here
    
    
    $('.kategoryi').slick({
        infinite: true,
        slidesToShow: 5,
        slidesToScroll: 5,
        lazyLoad: 'ondemand'
    });
    
    $('.header-cat-slider').slick({
    	arrows: true,
		infinite: true,
		slidesToShow: 8,
		slidesToScroll: 1,
		variableWidth: true
	});

	
});
