function number_format(number,decimals,dec_point,thousands_sep){
	number=(number+'').replace(/[^0-9+\-Ee.]/g,'');
	var n=!isFinite(+number)?0:+number,
	prec=!isFinite(+decimals)?0:Math.abs(decimals),
	sep=(typeof thousands_sep==='undefined')?',':thousands_sep,
	dec=(typeof dec_point==='undefined')?'.':dec_point,
	s='',
	toFixedFix=function(n,prec){
		var k=Math.pow(10,prec);
		return ''+Math.round(n*k)/k;
	};
	s=(prec?toFixedFix(n,prec):''+Math.round(n)).split('.');
	if(s[0].length>3){
		s[0]=s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,sep);
	}
	if((s[1]||'').length<prec){
		s[1]=s[1]||'';
		s[1]+=new Array(prec-s[1].length+1).join('0');
	}
	return s.join(dec);
}
function add_to_card(el,form_data,form){
	$.ajax({
		type:'post',
		url:'/ajax.php?page_type=basket&action=add',
		data:form_data,
		beforeSend:function(){
			$('#cart_animation').css({'display':'block','opacity':'1'});
		},
		success:function(r){
			var result=JSON.parse(r);
			$('#cart span').html(result['products_count']);
			$('#cart_animation').animate({opacity:0},1000,false,function(){$('#cart_animation').css({'display':'none'});});
			/*
			window.dataLayer.push({
				"ecommerce":{
					"add":{
						"products":[
							{
								"id":form.data('id'),
								"name":form.data('name'),
								"price":form.data('price'),
								"brand":form.data('brand'),
								"category":form.data('category'),
								"quantity":form_data.n,
							}
						]
					}
				}
			});
			*/
		}
	});
	animate_picture(el,'#cart');
	return false;
}
function add_to_card_popup(form_data){
	$.ajax({
		type:'post',
		url:'/ajax.php?page_type=basket&action=add',
		data:form_data,
		beforeSend:function(){
			$.fancybox.showLoading();
		},
		success:function(r){
			var result=JSON.parse(r);
			$('#cart span').html(result['products_count']);
			$.fancybox({'content':'<div class="cart_added"><h1>Товар добавлен в корзину</h1><div class="button"><a onclick="$.fancybox.close();">Продолжить покупки</a></div><div class="button"><a href="/basket.html">Оформить заказ</a></div></div>'});
		},
		complete:function(){
			$.fancybox.hideLoading();
		}
	});
	return false;
}
function delete_from_cart(el,del_key,a){
	$.ajax({
		type:'post',
		url:'/ajax.php?page_type=basket&action=delete&'+del_key+'=1',
		success:function(r){
			var result=JSON.parse(r);
			products_count=result['products_count'];
			global_price=result['global_price'];
			global_weight=result['global_weight'];
			global_bonus=result['global_bonus'];
		}
	});
	el.css({'background-color':'#e03c42'});
	el.find('.cart_delete').css({'border':'2px solid #ffffff'});
	el.animate({opacity:0.1},900,false,function(){
		var new_global_price=number_format(global_price.toString(),0,'.',' ');
		if($('.cart_items ul li').length>1){
			$('#products_count').html(products_count);
			$('#global_bonus').html(global_bonus);
			$('#cart_global_price').val(global_price);
			$('#cart_global_weight').val(global_weight).change();
			$('#global_price').html(new_global_price);
			el.remove();
		}else{
			el.parent().remove();
			$('.cart_summary').remove();
			$('.cart_form').remove();
			$('.cart_title').html('В корзину не добавлено ни одного товара');
		}
		$('#cart span').html(products_count);
	});
	/*
	window.dataLayer.push({
		"ecommerce":{
			"remove":{
				"products":[
					{
						"id":a.data('id'),
						"name":a.data('name'),
						"price":a.data('price'),
						"brand":a.data('brand'),
						"category":a.data('category'),
						"quantity":a.data('count'),
					}
				]
			}
		}
	});
	*/
}
function update_cart(form){
	$.ajax({
		url			:	'/ajax.php?page_type=basket&action=update',
		type		:	form.attr('method'),
		data		:	form.serialize(),
		beforeSend	:	function(){$.fancybox.showLoading();},
		success		:	function(r){
							var result=JSON.parse(r);
							$('#products_count').html(result['products_count']);
							$('#global_bonus').html(result['global_bonus']);
							$('#cart_global_price').val(result['global_price']);
							$('#cart_global_weight').val(result['global_weight']).change();
							$('#global_price').html(number_format(result['global_price'],0,'.',' '));
							$('#cart span').html(result['products_count']);
						},
		complete	:	function(){
							$.fancybox.hideLoading();
						}
	});
}
$(document).ready(function(){
	$('.catalog_form,.details_form').on('submit',function(){
		var catalog_colors_count=$('#color_changer').length;
		var catalog_sizes_count=($('#select_size').find($("option")).length)-1;
		if(($('#cart_color').val()==0&&catalog_colors_count>0)||($('#cart_size').val()==0&&catalog_sizes_count>0)){
			var message='';
			if($('#cart_color').val()==0&&catalog_colors_count>0){
				$('.item_colors_title').css('color','#e03c42');
				message+="Выберите цвет товара\n";
			}
			else{
				$('.item_colors_title').css('color','#212121');
			}
			if($('#cart_size').val()==0&&catalog_sizes_count>0) {
				$('.item_sizes_title').css('color','#e03c42');
				message+="Выберите размер товара\n";
			}
			else{
				$('.item_sizes_title').css('color','#212121');
			}
			alert(message);
			return false;
		}
		else{
			$('.item_colors_title').css('color','#212121');
			$('.item_sizes_title').css('color','#212121');
		}
		if($(this).hasClass('details_form')){
			add_to_card($('#detail_photo'),$(this).serialize(),$(this));
		}
		else{
			add_to_card($(this).closest('.item').find('.image_'+$(this).data('item')),$(this).serialize(),$(this));
		}
		//add_to_card_popup($(this).serialize());
		return false;
	});
	$('.catalog_form,.details_form,.cart_form form').on('submit',function(){
		var yandex_id=$(this).data('counter');
		var yandex_goal=$(this).data('goal')
		if(yandex_id!=''&&yandex_goal!=''){
			//window['yaCounter'+yandex_id].reachGoal(yandex_goal);
			ym(yandex_id,'reachGoal',yandex_goal);
			//ga('send','event','cart',yandex_goal);
			//gtag('event',yandex_goal);
		}
	});
	$('input[name=n]').bind("change keyup input click",function(){
		if(this.value.match(/[^0-9]/g)){
			this.value=this.value.replace(/[^0-9]/g,'');
		}
	});
	function basket_n(el,n){
		el.closest('li').find('.summ').html(number_format((el.closest('li').find('a.cart_delete').attr('data-price')*n),0,'.',' ')+' <i class="fa fa-rub"></i>');
		el.closest('li').find('.cart_delete').attr('data-count',n);
		update_cart(el.closest('form'));
	}
	(function($){
		$.widget("ui.onDelayedClick",{
			_init:function(){
				var self=this;
				$(this.element).click(function(){
					if(typeof(window['clickTimeout'])!="undefined"){
						window.clearTimeout(clickTimeout);
					}
					var handler=self.options.handler;
					window['clickTimeout']=window.setTimeout(function(){
						handler.call(self.element)
					},self.options.delay);
				});
			},
			options:{
				handler:$.noop(),
				delay:500
			}
		});
	})(jQuery);
	$('.btnplus').onDelayedClick({
		handler:function(){
			var on=$(this).prev("input").val()*1;
			var n=on+1;
			$(this).prev("input").val(n).change();
			//basket_n($(this),n);
		}
	});
	$('.btnminus').onDelayedClick({
		handler:function(){
			var on=$(this).next("input").val()*1;
			var n=on-1;
			n=n<1?1:n;
			$(this).next("input").val(n).change();
			//basket_n($(this),n);
		}
	});
	$('.cart_items .n input[type=text]').on('change',function(){
		basket_n($(this),$(this).val());
	});
	$('.cart_delete').click(function(){
		del_key=$(this).data('key');
		delete_from_cart($(this).closest('li'),del_key,$(this));
		return false;
	});
	$('#radio_individual').click(function(){
		$('.legal').addClass('hide');
		$('.individual').removeClass('hide');
	});
	$('#radio_legal').click(function(){
		$('.individual').addClass('hide');
		$('.legal').removeClass('hide');
	});
	$('.orders_history a.details').click(function(){
		var order=$(this).attr('data-id');
		$('.orders_history tr[data-order='+order+']').toggleClass('open');
	});
	$('#color_changer li').click(function(){
		$('#cart_color').val($(this).attr('rel'));
		$('#color_changer li').removeClass('active');
		$(this).addClass('active');
	});
	$('select[name=city]').on('click',function(){
		$(this).data('pvz','')
	});
	$(".cart_form select").chosen({width:"100%",no_results_text:"Ничего не найдено"});
	$('.individual_delivery input').change(function(){
		$('.delivery_price').addClass('hide').find('.res_value').html('');
		$('.delivery_term').addClass('hide').find('.res_value').html('');
		var global_price=$('#cart_global_price').val();
		$('#global_price').html(number_format(global_price,0,'.',' '));
		$('#cdek_delivery_calc_price,#sber_delivery_calc_price').val(0);
		$('#cdek_delivery_calc_term,#sber_delivery_calc_term').val('');
		//$('#cdek_delivery_calc_price').val(0);
		//$('select[name=city],select[name=pvz],select[name=city_cdek],select[name=city_sber],select[name=pvz_sber]').val(0);
		if($(this).val()==2){
			$('.individual_address').removeClass('hide');
		}
		else{
			$('.individual_address').addClass('hide');
		}
		if($(this).val()==3){
			$('.individual_pvz').removeClass('hide');
			$('.individual_pvz select').attr('required','required').change();
		}
		else{
			$('.individual_pvz').addClass('hide');
			$('.individual_pvz select').removeAttr('required');
		}
		if($(this).val()==4){
			$('.individual_courier').removeClass('hide');
			$('.individual_courier select,.individual_courier>input[type=text]').attr('required','required').change();
		}
		else{
			$('.individual_courier').addClass('hide');
			$('.individual_courier select,.individual_courier>input[type=text]').removeAttr('required');
		}
		if($(this).val()==5){
			$('.individual_sber').removeClass('hide');
			$('.individual_sber select').attr('required','required').change();
		}
		else{
			$('.individual_sber').addClass('hide');
			$('.individual_sber select').removeAttr('required');
		}
		if($(this).val()==6){
			$('.individual_sbercourier').removeClass('hide');
			$('.individual_sbercourier select,.individual_sbercourier>input[type=text]').attr('required','required').change();
		}
		else{
			$('.individual_sbercourier').addClass('hide');
			$('.individual_sbercourier select,.individual_sbercourier>input[type=text]').removeAttr('required');
		}
		$('.cart_form select').trigger("chosen:updated");
	});
	$('select[name=city]').on('change',function(){
		var pvz=$(this).data('pvz');
		$.ajax({
			url:'/index.php',
			type:'get',
			datatype:'json',
			data:{CityCode:$(this).val()},
			success:function(response){
				var points='';
				points+='<option value="" data-id="0">Выбрать ПВЗ</option>';
				$.each(response,function(count,option){
					points+='<option value="'+option.Code+'" data-id="'+option.id+'">'+option.Name+'</option>';
				});
				$('select[name=pvz]').html(points);
				if(pvz>=''){
					$('select[name=pvz]').val(pvz).change();
				}
				$('select[name=pvz]').trigger("chosen:updated");
			}
		});
	});
	$('select[name=pvz]').on('change',function(){
		$('.cdek_pvz_price').html('');
		$('#cdek_delivery_calc_price').val(0);
		$('#cdek_delivery_calc_term').val('');
		var city=$('select[name=city]').val();
		var weight=$('#cart_global_weight').val();
		if(city>0){
			$.ajax({
				type:'post',
				url:'/index.php?ajax_action=cdek_calc',
				data:{type:'pvz',to:city,weight:weight},
				beforeSend:function(){
				},
				success:function(r){
					console.log(r);
					try{
						var result=JSON.parse(r);
						$('.delivery_price').removeClass('hide').find('.res_value').html(result.delivery_sum+' <i class="fa fa-rub"></i>');
						$('.delivery_term').removeClass('hide').find('.res_value').html(result.period_min+'-'+result.period_max+' дн.');
						//$('.cdek_pvz_price').html('Стоимость доставки <strong>'+result.delivery_sum+' руб.</strong> Срок: <strong>'+result.period_min+'-'+result.period_max+' дн.</strong>');
						$('#cdek_delivery_calc_price').val(result.delivery_sum);
						$('#cdek_delivery_calc_term').val(result.period_min+'-'+result.period_max+' дн.');
						var global_price=$('#cart_global_price').val();
						$('#global_price').html(number_format((global_price*1+result.delivery_sum*1),0,'.',' '));
					}
					catch(e){
					}
				}
			});
		}
	});
	$('select[name=city_cdek]').on('change',function(){
		$('.cdek_courier_price').html('');
		$('#cdek_delivery_calc_price').val(0);
		$('#cdek_delivery_calc_term').val('');
		var city=$('select[name=city_cdek]').val();
		var weight=$('#cart_global_weight').val();
		if(city>0){
			$.ajax({
				type:'post',
				url:'/index.php?ajax_action=cdek_calc',
				data:{type:'courier',to:city,weight:weight},
				beforeSend:function(){
				},
				success:function(r){
					console.log(r);
					try{
						var result=JSON.parse(r);
						$('.delivery_price').removeClass('hide').find('.res_value').html(result.delivery_sum+' <i class="fa fa-rub"></i>');
						$('.delivery_term').removeClass('hide').find('.res_value').html(result.period_min+'-'+result.period_max+' дн.');
						//$('.cdek_courier_price').html('Стоимость доставки <strong>'+result.delivery_sum+' руб.</strong> Срок: <strong>'+result.period_min+'-'+result.period_max+' дн.</strong>');
						$('#cdek_delivery_calc_price').val(result.delivery_sum);
						$('#cdek_delivery_calc_term').val(result.period_min+'-'+result.period_max+' дн.');
						var global_price=$('#cart_global_price').val();
						$('#global_price').html(number_format((global_price*1+result.delivery_sum*1),0,'.',' '));
					}
					catch(e){
					}
				}
			});
		}
	});
	//$("select.chosen").chosen({width:"100%",no_results_text:"Ничего не найдено"});
	//$("select[name=city_sber]").chosen({width:"100%",no_results_text:"Ничего не найдено"});
	//$("select[name=pvz_sber]").chosen({width:"100%",no_results_text:"Ничего не найдено"});//,disable_search:true
	$('select[name=city_sber]').on('change',function(){
		var point=$(this).data('point');
		var kladr_id=$(this).val();
		//$.fancybox.showLoading();
		$('select[name=pvz_sber]').html('<option value="" data-point="">Выбрать ПВЗ</option>');
		if(kladr_id>0){
			$.ajax({
				url:'/index.php',
				type:'get',
				datatype:'json',
				data:{kladr_id:kladr_id},
				success:function(response){
					var points='';
					$.each(response,function(count,option){
						points+='<option value="'+option.id+'" data-point="'+option.id+'" data-courier="'+option.courier+'">'+option.name+'</option>';
					});
					$('select[name=pvz_sber]').append(points);
					if(point>=''){
						$('select[name=pvz_sber]').val(point).change();
					}
					$('select[name=pvz_sber]').trigger("chosen:updated");
				}
			});
		}
		//$('select[name=pvz_sber]').trigger("chosen:updated");
		//$.fancybox.hideLoading();
	});
	$('select[name=pvz_sber]').on('change',function(){
		var weight=$('#cart_global_weight').val();
		var price=$('#cart_global_price').val();
		var kladr_id=$('select[name=city_sber]').val();
		var courier=$(':selected',this).attr("data-courier");
		if(kladr_id>0){
			$.ajax({
				type:'get',
				url:'/index.php?ajax_action=shiptor_calc',
				data:{kladr_id:kladr_id,weight:weight,price:price,courier:courier},
				beforeSend:function(){
				},
				success:function(r){
					try{
						var result=JSON.parse(r);
						console.log(result);
						if(result['result']['methods'].length>0){
							var calc_price=Math.ceil(result['result']['methods'][0]['cost']['total']['sum']);
							var calc_term=result['result']['methods'][0]['days'];
							$('.delivery_price').removeClass('hide').find('.res_value').html(calc_price+' <i class="fa fa-rub"></i>');
							$('.delivery_term').removeClass('hide').find('.res_value').html(calc_term);
							//$('.sber_delivery_calc_price').html('Стоимость доставки <strong>'+calc_price+' руб.</strong> Срок: <strong>'+calc_term+'</strong>');
							$('#sber_delivery_calc_price').val(calc_price);
							$('#sber_delivery_calc_term').val(calc_term);
							var global_price=$('#cart_global_price').val();
							$('#global_price').html(number_format((global_price*1+calc_price*1),0,'.',' '));
						}
						else{
							$('.delivery_price').addClass('hide').find('.res_value').html('');
							$('.delivery_term').addClass('hide').find('.res_value').html('');
							var global_price=$('#cart_global_price').val();
							$('#global_price').html(number_format(global_price,0,'.',' '));
							//$('.sber_delivery_calc_price').html('Невозможно доставить заказ в выбранный пункт выдачи');
							$('#sber_delivery_calc_price').val(0);
							$('#sber_delivery_calc_term').val('');
						}
					}
					catch(e){
					}
				}
			});
		}
	});
	$('#cart_global_weight').on('change',function(){
		var delivery=$('.delivery_var:checked').val();
		if(delivery==3){
			$('select[name=pvz]').change();
		}
		if(delivery==4){
			$('select[name=city_cdek]').change();
		}
	});
	$('.promo_set').on('click',function(){
		var res='';
		var promo=$('input[name=promo]').val();
		var price=$('#cart_global_price').val();
		var promo_price=0;
		if(promo!=''){
			$.ajax({
				url:'/index.php',
				type:'get',
				datatype:'json',
				data:{checkpromo:promo},
				success:function(response,i){
					if(response.discount>0||response.amount>0){
						if(response.discount>0){
							promo_price=price*response.discount/100;
							res='Скидка '+response.discount+'% - '+promo_price+'руб.';
						}
						if(response.amount>0&&response.amount>promo_price){
							promo_price=response.amount;
							res='Скидка - '+promo_price+'руб.';
						}
					}
					else{
						res='Промокод не найден';
					}
					$('.promo_set').next('span').html(res);
				}
			});
		}
		else{
			$(this).next('span').html('Укажите промокод!');
		}
	});
	$('.cart_form input[required=required]').on('change',function(){
		if($(this).val()!=''){
			$(this).removeClass('error');
		}
	});
	$('.cart_form .group .next a').on('click',function(){
		var err=0;
		$(this).closest('.group').find('input[required=required]').each(function(){
			if($(this).val()==''){
				$(this).addClass('error');
				err++;
			}
		});
		if(err==0){
			var group=$(this).data('next');
			$('.cart_form .group,.cart_steps .step').removeClass('active');
			for(i=1;i<=group;i++){
				$('.cart_steps .step'+i).addClass('active');
			}
			$('.cart_form .group'+group).addClass('active');
		}
		return false;
	});
});
