/* Начальное кол-во для смены в карточке и корзине */
nimble.amount = 1;

 var listCountries = $.masksSort($.masksLoad("/templates/edu1c/js/maskedphones/data/phone-codes.json"), ['#'], /[0-9]|#/, "mask");
            var maskOpts = {
                inputmask: {
                    definitions: {
                        '#': {
                            validator: "[0-9]",
                            cardinality: 1
                        }
                    },
                    showMaskOnHover: false,
                    autoUnmask: false,
                    clearMaskOnLostFocus: false
                },
                match: /[0-9]/,
                replace: '#',
                listKey: "mask"
            };

			$(document).ready(function(){
            $('#phone').inputmask("remove");
			$('#phone').inputmasks($.extend(true, {}, maskOpts, {
                            list: listCountries
            }));
			});

$(document).ready(function(){
// Datepicker

	jQuery(function($){
		$.datepicker.regional['ru'] = {
			closeText: 'Закрыть',
			prevText: 'Предыдущий',
			nextText: 'Следующий',
			currentText: 'Сегодня',
			monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
			'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
			monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
			'Июл','Авг','Сен','Окт','Ноя','Дек'],
			dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
			dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
			dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
			weekHeader: 'Не',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional['ru']);
	});
	
	// Check all checkboxes when the one in a table head is checked:
		$('.check-all').click(function () {    
			 $('input:checkbox').prop('checked', this.checked);    
		 });
});

$(document).on('submit', '.fn-variants.nimble', function(e) {
	e.preventDefault();
	var product_id,
		variant,
		quantity;
	/* Вариант */
	if($(this).find('input[name=variant]:checked').size() > 0 ) {
		variant = $(this).find('input[name=variant]:checked').val();
	} else if($(this ).find('input[name=variant]').size() > 0 ) {
		variant = $(this).find('input[name=variant]').val();
	} else if($(this).find('select[name=variant]').size() > 0 ) {
		variant = $(this).find('select[name=variant]').val();
	}
	/* Кол-во */
	if($(this).find('input[name=amount]').size()>0) {
		quantity = $(this).find('input[name=amount]').val();
	} else {
		quantity = 1;
	}
	product_id = $(this).find('input[name=product_id]').val();
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/cart/set"+nimble.url_suffix,
		data: {
			"product_id": product_id, "quantity": quantity, "id": variant
		},
		success: function(data) {
			$("#cart_informer").load(location.href + " #ajax_cart");
		}
	} );
	/* Улеталка */
	transfer( $('#cart_informer'), $(this) );
});


$(document).on('click', '.fn-buy.nimble', function(e){
	e.preventDefault();
	product = parseInt( $( this ).data( 'id' ) );
	variant = parseInt( $( this ).data( 'variant' ) );
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/cart/set"+nimble.url_suffix,
		data: {
			"product_id": product, "quantity": 1, "id": variant
		},
		success: function(data) {
			$("#cart_informer").load(location.href + " #ajax_cart");
		}
	} );
	/* Улеталка */
	transfer( $('#cart_informer'), $(this) );
});

/* Смена варианта в превью товара и в карточке */
function fn_variant(myRadio) {
	var selected = $( myRadio ),
		parent = selected.closest( '.fn-product' ),
		price = parent.find( '.fn-price' ),
		cprice = parent.find( '.fn-old_price' ),
		cname = $( 'html' ).find( '.fn-variant-name' ),
		sku = parent.find( '.fn-sku' ),
		stock = parseInt( selected.data( 'stock' ) ),
		amount = parent.find( 'input[name="amount"]' ),
		camoun = parseInt( amount.val() );
	price.html( selected.data( 'price' ) );
	cname.html( selected.data( 'variantname' ) );
	amount.data('max', stock);
	/* Количество товаров */
	if ( stock < camoun ) {
		amount.val( stock );
	} else if ( nimble.amount > camoun ) {
		amount.val( nimble.amount );
	}
    else if(isNaN(camoun)){
        amount.val( nimble.amount );
    }
	/* Цены */
	if( selected.data( 'cprice' ) ) {
		cprice.html( selected.data( 'cprice' ) );
		cprice.parent().removeClass( 'hidden-xs-up' );
		if ( parent.hasClass( 'card' ) ) {
			cprice.parent().next().removeClass( 'col-xs-12' );
			cprice.parent().next().addClass( 'col-xs-6' );
		}
	} else {
		cprice.parent().addClass( 'hidden-xs-up' );
		if ( parent.hasClass( 'card' ) ) {
			cprice.parent().next().removeClass( 'col-xs-6' );
			cprice.parent().next().addClass( 'col-xs-12' );
		}
	}
	/* Артикул */
	if( typeof(selected.data( 'sku' )) != 'undefined' ) {
		sku.text( selected.data( 'sku' ) );
		sku.parent().removeClass( 'hidden-xs-up' );
	} else {
		sku.text( '' );
		sku.parent().addClass( 'hidden-xs-up' );
	}
	/* Предзаказ */
	if (stock == 0 && nimble.is_preorder) {
		parent.find('.fn-is_preorder').removeClass('hidden-xs-up');
		parent.find('.fn-is_stock, .fn-not_preorder').addClass('hidden-xs-up');
	} else if (stock == 0 && !nimble.is_preorder) {
		parent.find('.fn-not_preorder').removeClass('hidden-xs-up');
		parent.find('.fn-is_stock, .fn-is_preorder').addClass('hidden-xs-up');
	} else {
		parent.find('.fn-is_stock').removeClass('hidden-xs-up');
		parent.find('.fn-is_preorder, .fn-not_preorder').addClass('hidden-xs-up');
	}
}

/* Количество товара в карточке и корзине */
$( document ).on( 'click', '.fn-product-amount.nimble div', function() {
	var input = $( this ).parent().find( 'input' ),
		action;
	if ( $( this ).hasClass( 'plus' ) ) {
		action = 'plus';
	} else if ( $( this ).hasClass( 'minus' ) ) {
		action = 'minus';
	}
	amount_change( input, action );
} );

/* Функция добавления / удаления в папку сравнения */
$(document).on('click', '.fn-comparison.nimble', function(e){
	e.preventDefault();
	var button = $( this ),
		action = $( this ).hasClass( 'selected' ) ? 'delete' : 'add',
		product = parseInt( $( this ).data( 'id' ) );
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/comparison/set"+nimble.url_suffix,
		data: { 'id': product, 'action': action },
		success: function(data) {
			$("#comparison").load(location.href + " .ajax-comparison");
			/* Смена класса кнопки */
			if( action == 'add' ) {
                button.addClass( 'selected' );
			} else if( action == 'delete' ) {
                button.removeClass( 'selected' );
			}
			/* Смена тайтла */
			if( button.attr( 'title' ) ) {
				var text = button.data( 'result-text' ),
					title = button.attr( 'title' );
				button.data( 'result-text', title );
				button.attr( 'title', text );
				button.find('span').text( text );
			}
			/* Если находимся на странице сравнения - перезагрузить */
			if( $( '.fn-comparison_products' ).size() ) {
				window.location = window.location;
			}
		}
	} );
	/* Улеталка */
	if( !button.hasClass( 'selected' ) ) {
		transfer( $( '#comparison' ), $( this ) );
	}
});

/* Функция добавления / удаления в папку избранного */
$(document).on('click', '.fn-wishlist.nimble', function(e){
	e.preventDefault();
	var button = $( this ),
		action = $( this ).hasClass( 'selected' ) ? 'delete' : '';
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/wishlist/set"+nimble.url_suffix,
		data: { 'id': $( this ).data( 'id' ), 'action': action },
		success: function(data) {
			$("#wishlist").load(location.href + " .ajax-wishlist");
			/* Смена класса кнопки */
			if (action == '') {
				button.addClass( 'selected' )
			} else {
				button.removeClass( 'selected' )
			}
			/* Смена тайтла */
			if( button.attr( 'title' ) ) {
				var text = button.data( 'result-text' ),
					title = button.attr( 'title' );
				button.data( 'result-text', title );
				button.attr( 'title', text );
				button.find('span').text( text );
			}
			/* Если находимся на странице сравнения - перезагрузить */
			if( $( '.fn-wishlist-page' ).size() ) {
				window.location = window.location;
			}
		}
	} );
	/* Улеталка */
	if( !button.hasClass( 'selected' ) ) {
		transfer( $( '#wishlist' ), $( this ) );
	}
});


$(document).on('click', '.fn-comparison-training.nimble', function(e){
	e.preventDefault();
	var button = $( this ),
		action = $( this ).hasClass( 'selected' ) ? 'delete' : 'add',
		product = parseInt( $( this ).data( 'id' ) );
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/compare/set"+nimble.url_suffix,
		data: { 'id': product, 'action': action },
		success: function(data) {
			$("#comparison").load(location.href + " .ajax-comparison");
			/* Смена класса кнопки */
			if( action == 'add' ) {
                button.addClass( 'selected' );
			} else if( action == 'delete' ) {
                button.removeClass( 'selected' );
			}
			/* Смена тайтла */
			if( button.attr( 'title' ) ) {
				var text = button.data( 'result-text' ),
					title = button.attr( 'title' );
				button.data( 'result-text', title );
				button.attr( 'title', text );
				button.find('span').text( text );
			}
			/* Если находимся на странице сравнения - перезагрузить */
			if( $( '.fn-comparison_products' ).size() ) {
				window.location = window.location;
			}
		}
	} );
	/* Улеталка */
	if( !button.hasClass( 'selected' ) ) {
		transfer( $( '#comparison' ), $( this ) );
	}
});


/* Функция добавления / удаления в папку избранного */
$(document).on('click', '.fn-wishlist-training.nimble', function(e){
	e.preventDefault();
	var button = $( this ),
		action = $( this ).hasClass( 'selected' ) ? 'delete' : '';
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/wishes/set"+nimble.url_suffix,
		data: { 'id': $( this ).data( 'id' ), 'action': action },
		success: function(data) {
			$("#wishlist").load(location.href + " .ajax-wishlist");
			/* Смена класса кнопки */
			if (action == '') {
				button.addClass( 'selected' )
			} else {
				button.removeClass( 'selected' )
			}
			/* Смена тайтла */
			if( button.attr( 'title' ) ) {
				var text = button.data( 'result-text' ),
					title = button.attr( 'title' );
				button.data( 'result-text', title );
				button.attr( 'title', text );
				button.find('span').text( text );
			}
			/* Если находимся на странице сравнения - перезагрузить */
			if( $( '.fn-wishlist-page' ).size() ) {
				window.location = window.location;
			}
		}
	} );
	/* Улеталка */
	if( !button.hasClass( 'selected' ) ) {
		transfer( $( '#wishlist' ), $( this ) );
	}
});

/* Отправка купона по нажатию на enter */
$( document ).on( 'keypress', '.fn-coupon.nimble', function(e) {
	if( e.keyCode == 13 ) {
		e.preventDefault();
		ajax_coupon();
	}
} );

/* Отправка купона по нажатию на кнопку */
$( document ).on( 'click', '.fn-sub-coupon.nimble', function(e) {
	ajax_coupon();
} );

/* Document ready */
$(function(){
	
	//выбор даты доставки
	$('input[name="delivery_date"]').datepicker({
		regional:'ru'
	});

	/* Аяксовый фильтр по цене */
	if( $( '#fn-slider-price.nimble' ).size() ) {
		var slider_all = $( '#fn-slider-min, #fn-slider-max' ),
			slider_min = $( '#fn-slider-min' ),
			slider_max = $( '#fn-slider-max' ),
			current_min = slider_min.val(),
			current_max = slider_max.val(),
			range_min = slider_min.data( 'price' ),
			range_max = slider_max.data( 'price' ),
			link = window.location.href.replace( /\/page\/(\d{1,5})/, '' ),
			ajax_slider = function() {
				$.ajax( {
					type: "GET",
					url: link,
					data: {
						'ajax_price': 1,
						'min': slider_min.val(),
						'max': slider_max.val()
					},
					success: function(data) {
					window.location.assign(data);
					}
				} )
			};

		$( '#fn-slider-price.nimble' ).slider( {
			range: true,
			min: range_min,
			max: range_max,
			values: [current_min, current_max],
			slide: function(event, ui) {
				slider_min.val( ui.values[0] );
				slider_max.val( ui.values[1] );
			},
			stop: function(event, ui) {
				slider_min.val( ui.values[0] );
				slider_max.val( ui.values[1] );
                $('.col-lg-9').append('<div class="ajax_wait"></div>');
				ajax_slider();
			}
		} );

		slider_all.on( 'change', function() {
			$( "#fn-slider-price.nimble" ).slider( 'option', 'values', [slider_min.val(), slider_max.val()] );
			ajax_slider();
		} );
	}
	

	/* Показать / скрыть одинаковые характеристики в сравнении */
	$( document ).on( 'click', '.fn-show.nimble a', function(e) {
		e.preventDefault();
		$( '.fn-show.nimble a.active' ).removeClass( 'active' );
		$( this ).addClass( 'active' );
		if( $( this ).hasClass( 'unique' ) ) {
			$( '.cell.not_unique' ).hide();
		} else {
			$( '.cell.not_unique' ).show();
		}
	} );


	/* Если мы в подкатегории разворачивать категории родителей */
	if( $( '.fn-collapsed' ).size() ) {
		$( '.fn-collapsed' ).parent( '.nav-item' ).parents( '.nav-item' ).children( '.btn-catalog-collapse' ).removeClass('collapsed');
		$( '.fn-collapsed' ).parent( '.nav-item' ).parents( '.nav-item' ).children( '.collapse' ).addClass('in');
	}

	/* Переключатель способа оплаты */
	$( document ).on( 'click', '[name="payment_method_id"]', function() {
		$( '[name="payment_method_id"]' ).parent().removeClass( 'active' );
		$( this ).parent().addClass( 'active' );
	} )
});

/* Обновление блоков: cart_informer, cart_purchases, cart_deliveries */
function ajax_set_result(data) {
	$( '#cart_informer' ).html( data.cart_informer );
	$( '#fn-purchases' ).html( data.cart_purchases );
	$( '#fn-ajax_deliveries' ).html( data.cart_deliveries );
}

/* Аяксовое изменение кол-ва товаров в корзине */
function ajax_change_amount(object, variant_id, product_id) {
	var amount = $( object ).val(),
		coupon_code = $( 'input[name="coupon_code"]' ).val(),
		delivery_id = $( 'input[name="delivery_id"]:checked' ).val(),
		payment_id = $( 'input[name="payment_method_id"]:checked' ).val();
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/cart/update"+nimble.url_suffix,
		data: {"product_id": product_id, "quantity": amount, "id": variant_id},
		success: function(data) {
			if( data == 1 ) {
				$(".order-purchase-list").load(location.href + " .ajax-purchase-list");
				$("#cart_informer").load(location.href + " #ajax_cart");
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$(".cart-deliveries").load(location.href + " .ajax-cart-deliveries");
				$( '#deliveries_' + delivery_id ).trigger( 'click' );
				$( '#payment_' + delivery_id + '_' + payment_id ).trigger( 'click' );
			} else {
				$(".order-purchase-list").load(location.href + " .ajax-purchase-list");
				$("#cart_informer").load(location.href + " #ajax_cart");
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$(".cart-deliveries").load(location.href + " .ajax-cart-deliveries");
			}
		}
	} );
}

/* Функция изменения количества товаров */
function amount_change(input, action) {
	var max_val,
		curr_val = parseFloat( input.val() ),
		step = 1,
		id = input.data('id');
		product_id = input.data('product');
        if(isNaN(curr_val)){
            curr_val = nimble.amount;
        }

		/* Если включен предзаказ макс. кол-во товаров ставим 50 */
	if ( input.parent().hasClass('fn-is_preorder')) {
		max_val = 50;
	} else {
		max_val = parseFloat( input.data( 'max' ) )
	}
	
	/* Изменение кол-ва товара */
	if( action == 'plus' ) {
		input.val( Math.min( max_val, Math.max( 1, curr_val + step ) ) );
		input.trigger('change');
	} else if( action == 'minus' ) {
		input.val( Math.min( max_val, Math.max( 1, (curr_val - step) ) ) );
		input.trigger('change');
	} else if( action == 'keyup' ) {
		input.val( Math.min( max_val, Math.max( 1, curr_val ) ) );
		input.trigger('change');
	}
	nimble.amount = parseInt( input.val() );
	/* в корзине */
	if( $('div').is('#fn-purchases') && ( (max_val != curr_val && action == 'plus' ) || ( curr_val != 1 && action == 'minus' ) ) ) {
        ajax_change_amount( input, id, product_id );
	}
}

/* Функция анимации добавления товара в корзину */
function transfer(informer, thisEl) {
	var o1 = thisEl.offset(),
		o2 = informer.offset(),
		dx = o1.left - o2.left,
		dy = o1.top - o2.top,
		distance = Math.sqrt(dx * dx + dy * dy);

	thisEl.closest( '.fn-transfer' ).find( '.fn-img' ).effect( "transfer", {
		to: informer,
		className: "transfer_class"
	}, distance );

	var container = $( '.transfer_class' );
	container.html( thisEl.closest( '.fn-transfer' ).find( '.fn-img' ).parent().html() );
	container.find( '*' ).css( 'display', 'none' );
	container.find( '.fn-img' ).css( {
		'display': 'block',
		'height': '100%',
		'z-index': '2',
		'position': 'relative'
	} );
}

/* Аяксовый купон */
function ajax_coupon() {
	var coupon_code = $('input[name="coupon_code"]').val(),
		delivery_id = $('input[name="delivery_id"]:checked').val(),
		payment_id = $('input[name="payment_method_id"]:checked').val();
	/* ajax запрос */
	$.ajax( {
		type: "POST",
		url: "/ajax/cart/coupon"+nimble.url_suffix,
		data: {"coupon_code": coupon_code},
		success: function(data) {
			if( data == 1 ) {
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$( '#deliveries_' + delivery_id ).trigger( 'click' );
				$( '#payment_' + delivery_id + '_' + payment_id ).trigger( 'click' );
				$("#coupon-success").load(location.href + " .ajax-coupon-success");
			} else if(data == 2){
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$("#coupon-error").text('Сумма вашего заказа ниже минимальной суммы заказа для данного купона или купон уже использован или купон просрочен');
			} else if(data == 3){
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$("#coupon-error").text('Купон не найден');
			} else {
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
			}
		}
	} );
}

/* Изменение способа доставки */
function change_payment_method($id) {
	$( "#fn-delivery_payment_" + $id + " [name='payment_method_id']" ).first().trigger('click');
	$( ".fn-delivery_payment" ).hide();
	$( "#fn-delivery_payment_" + $id ).show();
	$( 'input[name="delivery_id"]' ).parent().removeClass( 'active' );
	$( '#deliveries_' + $id ).parent().addClass( 'active' );
	//$( 'input[name="delivery_date"]').prop( "disabled", true );
	//$( '.delivery-date_' + $id ).prop( "disabled", false );
}

function change_student_price($use_fix, $fiz_price, $legal_price, $only_student, $sudent_price){
	$id = $('input[name="type"]:checked').val();
	if($use_fix == 1 && $id == 0 && $("#is_student").is(':checked') == false){
	$('#itog-price').text($fiz_price);
	}
	if($use_fix == 1 && $id == 1){
	$('#itog-price').text($legal_price);
	}
	if($only_student == 1 && $id == 0 && $("#is_student").is(':checked') == true){
		$('#itog-price').text($sudent_price);
	}
}

/* Изменение способа доставки */
function change_payment_method_training($id, $use_fix, $fiz_price, $legal_price, $only_student, $sudent_price) {
	$( "#fn-delivery_payment_" + $id + " [name='payment_method_id']" ).first().trigger('click');
	$( ".fn-delivery_payment" ).hide();
	$( ".fn-delivery_payment_" + $id ).show();
	if($use_fix == 1 && $id == 0){
	$('#itog-price').text($fiz_price);
	}
	if($use_fix == 1 && $id == 1){
	$('#itog-price').text($legal_price);
	}
	if($only_student == 1 && $id == 0 && $("#is_student").is(':checked') == true){
	$('#itog-price').text($sudent_price);
	}
	if($id == 0){
	$("#oferta-link").attr("href", "https://uc1.1c.ru/oferta/");
	$("#oferta-link-unti").attr("href", "http://uc1.1c.ru/perepodgotovka-oferta/");
	}
	if($id == 1){
	$("#oferta-link").attr("href", "http://online.1c.ru/help/rules/public/");
	$("#oferta-link-unti").attr("href", "http://uc1.1c.ru/perepodgotovka-oferta-ur/");
	}
	//$( 'input[name="delivery_id"]' ).parent().removeClass( 'active' );
	//$( '#deliveries_' + $id ).parent().addClass( 'active' );
	//$( 'input[name="delivery_date"]').prop( "disabled", true );
	//$( '.delivery-date_' + $id ).prop( "disabled", false );
	$( '#payment_' + $id ).prop('checked', true);
	//$( '#payment_0').prop('checked', true);
}

/* Аяксовое удаление товаров в корзине */
function ajax_remove(variant_id, product_id) {
	var coupon_code = $('input[name="coupon_code"]').val(),
		delivery_id = $('input[name="delivery_id"]:checked').val(),
		payment_id = $('input[name="payment_method_id"]:checked').val();
	/* ajax запрос */
	$.ajax( {
		type: "POST", 
		url: "/ajax/cart/delete"+nimble.url_suffix,
		data: {"product_id": product_id, "id": variant_id},
		success: function(data) {
			if( data == 1 ) {
				$("#cart").load(location.href + " #ajax-cart");
				$(".order-purchase-list").load(location.href + " .ajax-purchase-list");
				$("#cart_informer").load(location.href + " #ajax_cart");
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$(".cart-deliveries").load(location.href + " .ajax-cart-deliveries");
				$( '#deliveries_' + delivery_id ).trigger( 'click' );
				$( '#payment_' + delivery_id + '_' + payment_id ).trigger( 'click' );
			} else {
				$("#cart").load(location.href + " #ajax-cart");
				$(".order-purchase-list").load(location.href + " .ajax-purchase-list");
				$("#cart_informer").load(location.href + " #ajax_cart");
				$(".purchase-full-coupon-price").load(location.href + " .ajax-purchase-full-coupon-price");
				$(".purchase-full-order-price").load(location.href + " .ajax-purchase-full-order-price");
				$(".cart-deliveries").load(location.href + " .ajax-cart-deliveries");
			}
		}
	} );
}

/* Формирование ровных строчек для характеристик */
function resize_comparison() {
	var minHeightHead = 0;
	$('.fn-resize' ).each(function(){
		if( $(this ).height() > minHeightHead ) {
			minHeightHead = $(this ).height();
		}
	});
	$('.fn-resize' ).height(minHeightHead);
	if ($('[data-use]').size()) {
		$('[data-use]').each(function () {
			var use = '.' + $(this).data('use');
			var minHeight = $(this).height();
			if ($(use).size()) {
				$(use).each(function () {
					if ($(this).height() >= minHeight) {
						minHeight = $(this).height();
					}
				});
				$(use).height(minHeight);
			}
		});
	}
}

/* В сравнении выравниваем строки */
$( window ).load( resize_comparison );

/* Звёздный рейтинг товаров */
$.fn.rater = function (options) {
	var opts = $.extend({}, $.fn.rater.defaults, options);
	return this.each(function () {
		var $this = $(this);
		var $on = $this.find('.rating_starOn');
		var $off = $this.find('.rating_starOff');
		opts.size = $on.height();
		if (opts.rating == undefined) opts.rating = $on.width() / opts.size;

		$off.mousemove(function (e) {
			var left = e.clientX - $off.offset().left;
			var width = $off.width() - ($off.width() - left);
			width = Math.ceil(width / (opts.size / opts.step)) * opts.size / opts.step;
			$on.width(width);
		}).hover(function (e) { $on.addClass('rating_starHover'); }, function (e) {
			$on.removeClass('rating_starHover'); $on.width(opts.rating * opts.size);
		}).click(function (e) {
			var r = Math.round($on.width() / $off.width() * (opts.units * opts.step)) / opts.step;
			$off.unbind('click').unbind('mousemove').unbind('mouseenter').unbind('mouseleave');
			$off.css('cursor', 'default'); $on.css('cursor', 'default');
			opts.id = $this.attr('id');
			opts.type = $this.attr('data-type');
			$.fn.rater.rate($this, opts, r);
		}).css('cursor', 'pointer'); $on.css('cursor', 'pointer');
	});
};

$.fn.rater.defaults = {
	postHref: location.href,
	units: 5,
	step: 1
};

$.fn.rater.rate = function ($this, opts, rating) {
	var $on = $this.find('.rating_starOn');
	var $off = $this.find('.rating_starOff');
	$off.fadeTo(600, 0.4, function () {
		$.ajax({
			url: opts.postHref,
			type: "POST",
			data: {type: opts.type, vote:rating, id:opts.id},
			complete: function (req) {
				if (req.status == 200) { /* success */
					opts.rating = parseFloat(req.responseText);

					if (opts.rating > 0) {
						opts.rating = parseFloat(req.responseText);
						$off.fadeTo(200, 0.1, function () {
							$on.removeClass('rating_starHover').width(opts.rating * opts.size);
							var $count = $this.find('.rating_count');
							$count.text(parseInt($count.text()) + 1);
							$this.find('.rating_value').text(opts.rating.toFixed(1));
							$off.fadeTo(200, 1);
						});
					}
					else if (opts.rating == -1) {
						$off.fadeTo(200, 0.6, function () {
							$this.find('.rating_text').text('Ошибка');
						});
					}
					else {
						$off.fadeTo(200, 0.6, function () {
							$this.find('.rating_text').text('Вы уже голосовали!');
						});
					}
				} else { /* failure */
					alert(req.responseText);
					$on.removeClass('rating_starHover').width(opts.rating * opts.size);
					$this.rater(opts);
					$off.fadeTo(2200, 1);
				}
			}
		});
	});
};

function changeReceiveBySection($id) {
    var radios = document.getElementsByClassName("delivery_"+$id);
    var pref = $id+"_div_RECEIVE_SERT_BY_";
    for (var i = 0; i < radios.length; i++) {
		 document.getElementById(pref + radios[i].getAttribute("divId")).style.display = (radios[i].checked ? '' : 'none');
    }
}

function change_polya_dostavka($id){
$( ".dop-polya-dostavka" ).hide();
$( "#dop-polya-dostavka_" + $id ).show();
$(".dop-polya-dostavka").find("input[type='text']").attr("disabled",true);
$( "#dop-polya-dostavka_" + $id ).find("input[type='text']").attr("disabled", false);
}

$(document).ready(function(){
	/*Разворачивает список видео в цифровом следе _отчет_*/
      $('.checkout_demand').on('click', '.show_edu_univer_videos', function(){
        var dataId = $(this).attr('data-id');
        var block = $('.watch-table-'+dataId);

        if(block.is(':visible')){
          block.hide();
          $(this).text("Подробнее ↓");
        }else{
          block.show();
          $(this).text("Свернуть ↑");
        }

        return false;
	});
	
})