{* Шаблон корзины *}

<h1>
{if $cart->purchases}В корзине {$cart->total_products} {$cart->total_products|plural:'товар':'товаров':'товара'}
{else}Корзина пуста{/if}
</h1>
{if $cart->purchases}
<form method="post" name="cart" class="_preorder">
{* Список покупок *}
<table id="purchases" class="table table-striped">
    <tr>
        <th>Изображение</th>
        <th>Наименование</th>
        <th>Цена</th>
        <th>Кол-во</th>
        <th>Итого</th>
        <th>Удалить</th>
    </tr>
    {literal} <script>$.yEcommerce = [];</script> {/literal}
{foreach from=$cart->purchases item=purchase}
{literal}
	<script>
		var x = {/literal}{$purchase->variant|@json_encode nofilter}{literal}
		x.product = {/literal}{$purchase->product|@json_encode nofilter}{literal}
		$.yEcommerce.push( x );
	</script>
{/literal}
{literal}
<script src="https://www.google.com/recaptcha/api.js?render=6LegdywdAAAAADKhWf40ZE7xYCwRlvVg_mg3Ot0q"></script>
<script>
    grecaptcha.ready(function () {
        grecaptcha.execute('6LegdywdAAAAADKhWf40ZE7xYCwRlvVg_mg3Ot0q', { action: 'contact' }).then(function (token) {
            var recaptchaResponse = document.getElementById('recaptchaResponseCart');
            recaptchaResponse.value = token;
        });
    });
</script>
{/literal}

<tr>
	{* Изображение товара *}
	<td>
		{$image = $purchase->product->images|first}
		{if $image}
         <a href="/products/{$purchase->product->url}/"><img src="{$image->filename|resize:150:150}" alt="{$product->name|escape}"></a>
		{/if}
	</td>
	{* Название товара *}
	<td style="font-size: 120%">
         <a href="/products/{$purchase->product->url}/">{$purchase->product->name|escape}</a>
		{$purchase->variant->name|escape}
			<div class="features">
				{foreach from=$purchase->options item=opt key=ok}
					{assign var=f value=$features[$ok]}
					{assign var=opts value=$purchase->features[$ok]}
					<p>
						<label>{$f->name} </label>
						<span>
							{$opt}
						</span>
					</p>
				{/foreach}
			</div>
	</td>
	{* Цена за единицу *}
	<td>
		{($purchase->variant->price)|convert} {$currency->sign}
	</td>
	{* Количество *}
	<td>
		<select name="amounts[{$purchase->variant->id}]" class="amounts form-control" onchange="document.cart.submit();">
			{section name=amounts start=1 loop=$purchase->variant->stock+1 step=1}
			<option value="{$smarty.section.amounts.index}" {if $purchase->amount==$smarty.section.amounts.index}selected{/if}>{$smarty.section.amounts.index} {$settings->units}</option>
			{/section}
		</select>
	</td>
	{* Цена *}
	<td>
		{($purchase->variant->price*$purchase->amount)|convert} {$currency->sign}
	</td>
	{* Удалить из корзины *}
	<td>
         <a class="remove-from-cart" data-id="{$purchase->variant->id}" href="/cart/remove/{$purchase->variant->id}/" style="color:red !important;">
         <span class="glyphicon glyphicon-remove"></span>
		<!--<img src="design/{$settings->theme}/images/delete.png" title="Удалить из корзины" alt="Удалить из корзины">-->
		</a>
	</td>
</tr>
{/foreach}
{if $user->discount}
<tr>
	<th></th>
	<th>скидка</th>
	<th></th>
	<th></th>
	<th>
		{$user->discount}&nbsp;%
	</th>
	<th class="remove"></th>
</tr>
{/if}
{if $coupon_request}
<tr class="coupon">
	<th></th>
	<th colspan="3">Код купона или подарочного ваучера
		{if $coupon_error}
		<div class="message_error">
			{if $coupon_error == 'invalid'}Купон недействителен{/if}
		</div>
		{/if}
		<div>
		<input type="text" name="coupon_code" value="{$cart->coupon->code|escape}" class="coupon_code">
		</div>
		{if $cart->coupon->min_order_price>0}(купон {$cart->coupon->code|escape} действует для заказов от {$cart->coupon->min_order_price|convert} {$currency->sign}){/if}
		<div>
		<input type="button" name="apply_coupon"  value="Применить купон" onclick="document.cart.submit();">
		</div>
	</th>
	<th>
		{if $cart->coupon_discount>0}
		&minus;{$cart->coupon_discount|convert}&nbsp;{$currency->sign}
		{/if}
	</th>
	<th></th>
</tr>
{literal}
<script>
$("input[name='coupon_code']").keypress(function(event){
	if(event.keyCode == 13){
		$("input[name='name']").attr('data-format', '');
		$("input[name='email']").attr('data-format', '');
		document.cart.submit();
	}
});
</script>
{/literal}
{/if}
<tr>
	<th></th>
	<th></th>
	<th class="price" colspan="4">
		Итого:
		<span id="sub_price" style="display: inline;">{$cart->total_price}</span>
        <span id="subtotal_price"></span>&nbsp;{$currency->sign}
	</th>
</tr>
</table>
{* Связанные товары *}
{*
{if $related_products}
<h2>Так же советуем посмотреть</h2>
<!-- Список каталога товаров-->
<ul class="tiny_products">
	{foreach $related_products as $product}
	<!-- Товар-->
	<li class="product">
		<!-- Фото товара -->
		{if $product->image}
		<div class="image">
                 <a href="/products/{$product->url}"><img src="{$product->image->filename|resize:200:200}" alt="{$product->name|escape}"/></a>
		</div>
		{/if}
		<!-- Фото товара (The End) -->
		<!-- Название товара -->
         <h3><a data-product="{$product->id}" href="/products/{$product->url}">{$product->name|escape}</a></h3>
		<!-- Название товара (The End) -->
		{if $product->variants|count == 1}
		<!-- Выбор варианта товара -->
			<table>
			{foreach $product->variants as $v}
			<tr class="variant">
				<td>
					{if $v->name}<label class="variant_name" for="related_{$v->id}">{$v->name}</label>{/if}
				</td>
				<td>
					{if $v->compare_price > 0}<span class="compare_price">{$v->compare_price|convert}</span>{/if}
					<span class="price">{$v->price|convert} <span class="currency">{$currency->sign|escape}</span></span>
				</td>
				<td>
                                 <a href="/cart?variant={$v->id}">в корзину</a>
				</td>
			</tr>
			{/foreach}
			</table>
		<!-- Выбор варианта товара (The End) -->
		{else}
			Нет в наличии
		{/if}
	</li>
	<!-- Товар (The End)-->
	{/foreach}
</ul>
{/if}
*}
{*/*order-on-one-page*/*}
{literal}
<script>
    $(document).ready(function(){
      $("#deliveries .first").click();
    });
  function change_payment_method($id) {
      $("#delivery_payment_"+$id+" .pay_first").attr('checked','checked');
      $(".delivery_payment").css("display","none");
      $("#delivery_payment_"+$id).css("display","block");
      if($id == 2 || $id == 5){
      	$('._hide2').show();
      	$('._hide').hide();

      	$('._hide input').each(function(){
      		var t = $(this).attr('data-format');
      		$(this).attr('data-format2',t);
      		$(this).removeAttr('data-format');
      	});
      }else{
      	$('._hide').show();
      	$('._hide2').show();
      	$('._hide input').each(function(){
      		var t = $(this).attr('data-format2');
      		$(this).attr('data-format',t);
      		$(this).removeAttr('data-format2');
      	});
      }
      if($id == 1){
      	$('._hide2').hide();
      	$('._hide2 input').each(function(){
      		var t = $(this).attr('data-format');
      		$(this).attr('data-format2',t);
      		$(this).removeAttr('data-format');
      	});
 	}else{
 		if($id != 2 && $id != 5){
	      	$('._hide').show();
	      	$('._hide2').show();
	      	$('._hide2 input').each(function(){
	      		var t = $(this).attr('data-format2');
	      		$(this).attr('data-format',t);
	      		$(this).removeAttr('data-format2');
	      	});
      	}
      }
  }
</script>
{/literal}
{*/*/order-on-one-page*/*}
{* Доставка *}
{if $deliveries}
<h2>Выберите способ доставки:</h2>
<div id="deliveries" class="list-group well">
	{foreach $deliveries as $delivery}
	<div class="radio">
        <label for="deliveries_{$delivery->id}">
			<input {*/*order-on-one-page*/*}{if $delivery@first}class="first"{/if} onclick="change_payment_method({$delivery->id})"{*/*/order-on-one-page*/*} type="radio" name="delivery_id" value="{$delivery->id}" {if $delivery_id==$delivery->id}checked{elseif $delivery@first}checked{/if} id="deliveries_{$delivery->id}">
			{$delivery->name}
            {if $cart->total_price < $delivery->free_from && $delivery->price > 0}
				<span id="delivery_price_{$delivery->id}" class="price">({$delivery->price})</span>&nbsp;{$currency->sign}
			{elseif $cart->total_price >= $delivery->free_from}
				<span id="delivery_price_{$delivery->id}" class="price">(бесплатно)</span>
			{else}
				<span id="delivery_price_{$delivery->id}" class="price">{if $delivery->ems==1}(Выберите город){/if}</span>
			{/if}
			</label>

			</div>

			{if $delivery->ems==1}
            <div class="list-group-item">
				<p>Тарифы и сроки доставки можно рассчитать ниже: </p>
				<input type="hidden" name="weight" id="weight" value="{$cart->total_weight}" />
				<label for="city2">Выберите пункт назначения</label>
                <div class="col-sm-4">
				<select name="city2" id="city2" class="form-control">
					<option value="">Выбирать</option>
						{foreach $acity AS $k=>$c}
							<option value="{$k}">{$c}</option>
						{/foreach}
				</select>
                </div>
                <div style="clear: both"></div>
				<div id="ajax">
				</div>
            </div>
			{else}
			{if $delivery->description}<div class="list-group-item">{$delivery->description}</div>{/if}
			{/if}


	{/foreach}
</div>
{/if}
<div class="title" id="total" style="text-align:right;">Итого: <span>{$cart->subtotal_price|convert}</span>&nbsp;{$currency->sign}</div>
{*/*order-on-one-page*/*}
{if $deliveries}
    {foreach $deliveries as $delivery}
        {if $delivery->payment_methods}
            <div class="delivery_payment {if $delivery@first}first{/if}" id="delivery_payment_{$delivery->id}" style="display:none"  >
                <h2>Выберите способ оплаты</h2>
                <div id="deliveries" class="list-group well">
                    {foreach  $delivery->payment_methods as $payment_method}

                            <div class="radio">
                            {$total_price_with_delivery = $cart->total_price}
                            {if !$delivery->separate_payment && $cart->total_price < $delivery->free_from}
                                {$total_price_with_delivery = $cart->total_price + $delivery->price}
                            {/if}
                            <label for="payment_{$delivery->id}_{$payment_method->id}">
                            <input class="{if $payment_method@first}pay_first{/if}" type=radio name=payment_method_id value='{$payment_method->id}' {if $payment_method@first}checked{/if} id=payment_{$delivery->id}_{$payment_method->id}>
                            	{$payment_method->name}, к оплате <span class="ems_price">{$total_price_with_delivery|convert:$payment_method->currency_id}</span>&nbsp;{$all_currencies[$payment_method->currency_id]->sign}</label>
                            </div>
                            <div class="description">
                                {if $payment_method->description}<div class="list-group-item">{$payment_method->description}</div>{/if}
                            </div>

                    {/foreach}
                </div>
            </div>
        {/if}
    {/foreach}
{/if}
{*/*/order-on-one-page*/*}
{* Выбор способа оплаты *}
{*if $payment_methods && !$payment_method}
<h2>Выберите способ оплаты:</h2>
<ul id="deliveries" class="costs">
    {foreach $payment_methods as $payment_method}
        <li>
            <div class="checkbox">
                <input type=radio name=payment_method_id value='{$payment_method->id}' {if $payment_method@first}checked{/if} id=payment_{$payment_method->id}>
            </div>
            <h3><label for=payment_{$payment_method->id}>    {$payment_method->name}{*, к оплате {$cart->total_price|convert:$payment_method->currency_id}&nbsp;{$all_currencies[$payment_method->currency_id]->sign}*}</label></h3>
            {*<div class="description">
            {$payment_method->description}
            </div>
        </li>
    {/foreach}
</ul>
{/if*}
<div class="title">Адрес получателя</div>
<div id="adrcart" class="well">
<div class="form-horizontal cart_form" style="overflow: hidden;">
	{if $error}
	<div class="message_error">
		{if $error == 'empty_name'}Введите Имя{/if}
		{if $error == 'empty_name2'}Введите Фамилию{/if}
		{if $error == 'empty_email'}Введите email{/if}
		{if $error == 'empty_phone'}Введите Телефон{/if}
		{if $error == 'empty_country'}Введите Страну{/if}
		{if $error == 'empty_region'}Введите Регион{/if}
		{if $error == 'empty_city'}Введите Город{/if}
		{if $error == 'empty_city2'}Введите город в EMS{/if}
		{if $error == 'empty_indx'}Введите Индекс{/if}
		{if $error == 'empty_adress'}Введите Адрес Доставки{/if}
		{if $error == 'captcha'}Капча введена неверно{/if}
		{if $error == 'recaptcha'}Вы не прошли проверку защиты{/if}
	</div>
	{/if}
    <div class="form-group">
	<label for="name" class="col-sm-2 control-label">Имя*</label>
    <div class="col-sm-10"><input class="form-control" name="name" type="text" value="{$user->name}" data-format=".+" data-notice="Введите имя"/></div>
    </div>
    <div class="form-group _hide _hide2">
	<label for="name2" class="col-sm-2 control-label">Фамилия*</label>
    <div class="col-sm-10"><input class="form-control" name="name2" type="text" value="{$user->name2}" data-format=".+" data-notice="Введите фамилию" /></div>
    </div>
    <div class="form-group _hide">
	<label for="email" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10"><input class="form-control" name="email" type="text" value="{$user->email}"/></div>
    </div>
    <div class="form-group">
	<label for="phone" class="col-sm-2 control-label">Телефон*</label>
    <div class="col-sm-10"><input class="form-control" name="phone" type="text" value="{$user->phone}" data-format=".+" data-notice="Введите телефон"/></div>
    </div>
    <div class="form-group _hide _hide2">
	<label for="country" class="col-sm-2 control-label">Страна*</label>
    <div class="col-sm-10"><input class="form-control" name="country" type="text" value="{$user->country}" data-format=".+" data-notice="Введите страну"/></div>
    </div>
    <div class="form-group _hide _hide2">
	<label for="region" class="col-sm-2 control-label">Регион*</label>
    <div class="col-sm-10"><input class="form-control" name="region" type="text" value="{$user->region}" data-format=".+" data-notice="Введите регион"/></div>
    </div>
    <div class="form-group _hide">
	<label for="city" class="col-sm-2 control-label">Город*</label>
    <div class="col-sm-10"><input class="form-control" name="city" type="text" value="{$user->city}" data-format=".+" data-notice="Введите город"/></div>
    </div>
    <div class="form-group _hide _hide2">
	<label for="indx" class="col-sm-2 control-label">Индекс*</label>
    <div class="col-sm-10"><input class="form-control" name="indx" type="text" value="{$user->indx}" data-format=".+" data-notice="Введите индекс" /></div>
    </div>
    <div class="form-group _hide">
	<label for="address" class="col-sm-2 control-label" style="padding-left: 0;padding-right: 10px;">Адрес доставки*</label>
    <div class="col-sm-10"><input class="form-control" name="address" type="text" value="{$user->adress}" data-format=".+" data-notice="Введите адрес"/></div>
    </div>
    <div class="form-group">
	<label for="comment" class="col-sm-2 control-label">Комментарий к заказу</label>
    <div class="col-sm-10">
    <textarea class="form-control" name="comment" id="order_comment"></textarea>
    </div>
    </div>
    <div class="form-group">

    <!--<div class="col-sm-2"><div class="captcha"><img src="captcha/image.php?{math equation='rand(10,10000)'}" alt='captcha'/></div></div>
    <div class="col-sm-2"><input class="input_captcha form-control" id="comment_captcha" type="text" name="captcha_code" value="" data-format="\d\d\d\d" data-notice="Введите капчу"/></div>
	</div>-->
	<input type="hidden" name="cart-form" value="1">
    <input type="submit" name="checkout" class="button btn btn-danger pull-right" value="Оформить заказ" style="margin-right: 15px;">
    <input type="hidden" name="recaptcha_response" id="recaptchaResponseCart">
	</div>
</div>
</div>
</form>
{else}
  В корзине нет товаров
{/if}
</div>
<script>
      /*function select_delivery_method(method_id)
      {
        radiobuttons = document.getElementsByName('delivery_id');
        for(var i=0;i<radiobuttons.length;i++)
        {
          if(radiobuttons[i].value == method_id)
          {
            radiobuttons[i].checked = 1;
          }
        }
      var subtotal = parseFloat(document.getElementById('sub_price').innerHTML);
      var delivery = 0;
      if(document.getElementById('delivery_price_'+method_id))
        delivery = parseFloat(document.getElementById('delivery_price_'+method_id).innerHTML);
      total = subtotal+delivery;
         document.getElementById('subtotal_price').innerHTML = total;
      }*/
    </script>
    <script>
      //select_delivery_method(1);
    </script>
<script>
{literal}
  $(function() {
  /*$('.deliver li').click(function(){
if ($(this).is(":nth-child(2)")) {
   	$('.costs li:first-child').slideUp("slow");
	$('#payment_11').attr('checked', false);
        $('#payment_8').attr('checked', true);
   }
else {
   	$('.costs li:first-child').slideDown("slow");
	$('#payment_8').attr('checked', false);
    $('#payment_11').attr('checked', true);
}
})
*/
	$('select#city2').change(function(){
		$("div#ajax").html("Загрузка...");
		$('select#city2').parents('li').find('label span.price').text("Загрузка...");
		var city2 = $( "select#city2 option:selected" ).val();
		$.ajax({
			data: {to: city2, weight: $('input[name="weight"]').val()},
			url: "ajax/ems.php",
			dataType: 'json',
			success: function(data){
				var html = $(data);
				//var pr = parseInt(html.find('p span').text().replace(/\s+/g, ''));
				var pr = html.find('p span').text();
				$("div#ajax").html("");
				$("#ajax").append(data);
				$('select#city2').parents('li').find('label span.price').text(pr);
				calctotal();
			}
		});
	});
	function calctotal(){
		var total = parseInt($('table th.price > span').text().replace(/\s+/g, '')), radio;
		total = total?total:0;
		if (radio = $("input[type='radio']:checked")){
			var add = parseInt($(radio).parents('li').find('span.price').text().replace(/\s+/g, ''));
			//alert(add );
			add = (add)?(add):(0);
			total+=add;
            delivery_id = radio.val();
            if (delivery_id == 3) {
                $('#delivery_payment_' + delivery_id + ' span.ems_price').html(total);
            }
		}
		$('#total > span').text(total);
	}
	$('input[type=radio]').change(function() {
		calctotal();
	});
	calctotal();
});

var __form = {};
setInterval(function(){

	var phone = $('._preorder input[name=phone]').val();
	var email = $('._preorder input[name=email]').val();
	if(phone.length < 4 && email.length < 4) return;

	var form = $('._preorder').serializeArray(), _form = {};
	for(var i in form) _form[form[i].name] = form[i].value;
	$.each(_form, function(k, v){
		if(typeof __form[k] != 'undefined' && __form[k] == v) return;
		__form = _form;
		$.post('/ajax/orderTrack.php', _form );
		return false;
	});

}, 2000);

window.dataLayer = window.dataLayer || [];

$('.remove-from-cart').click(function(e){
	e.preventDefault();
	var id = $(this).attr('data-id');
	var href = $(this).attr('href');
	dataLayer.push({
		"ecommerce": {
			"remove": {
				"products": [eCommerceFindProductRemove(id, $.yEcommerce)]
			}
		}
	});

	document.location.href = href;
});


	function eCommerceFindProductRemove(id, products){
		var res = {};
		$.each(products, function(k, item){ if(item.id == id) res = item });
		return {
			id: id,
			name: res.product && res.product.name ? res.product.name : res.name
		}
	}

$(function(){
	new sxValidator({$el: '._preorder'});
})


{/literal}
 </script>