{extends "ordering.tpl"}

{block "content"}
   {$deliveryType = $body->getDeliveryType()}
   {$column_class = "col-md-6 col-xxs-12"}
   {ifmodule COMPONENTS}
      {$modal_login = path('kupshop_components_modal_modal', ['template' => 'login'])}
   {/ifmodule}

   {if $tpl_vars.ordering_user_v == "2"}
      {include 'ordering/ordering.user.v2.tpl'}
   {else}
      {block 'login-block'}
         {if $ctrl.logged}
            <p class="logged-as">{t}Jste přihlášený jako uživatel {/t}{$ctrl.name} {$ctrl.surname} ({$ctrl.login}).</p>
            <input type="hidden" name="invoice[email]" value="{$ctrl.login}">
         {else}
            <div class="cart-user-login">
               <p class="title-default">{t}Máte již svůj účet?{/t}</p>
               <p>{t}Pokud jste u nás již nakupovali a máte svůj účet, přihlaste se.{/t}</p>
               <hr>
               <a href="{url s=login}" class="btn btn-primary cart-signin" data-wpj-modal="{$modal_login}" data-wpj-modal-type="side">{t}Přihlásit se{/t}</a>
            </div>
         {/if}
      {/block}
      <div class="cart-user-form-wrapper">
         {if !$ctrl.logged}
            {block 'form-header'}
               {block "form-header-tabs"}
                  <div class="cart-user-form-header">
                     <p class="title-default">{t}Jste tu poprvé?{/t}</p>
                     <ul class="nav nav-tabs" role="tablist">
                        <li class="nav-item">
                           <a href="#register" class="nav-link email-register{if $body->register} active{/if}" role="tab" data-toggle="tab"
                              title="{t}Chci se registrovat{/t}">
                              {t}Chci se registrovat{/t}
                           </a>
                        </li>
                        <li class="nav-item nav-item-toggle{if !$body->register} toggled{/if}"></li>
                        <li class="nav-item">
                           <a href="#without-register" class="nav-link email-unregister{if !$body->register} active{/if}" role="tab"
                              data-toggle="tab" title="{t}Nákup bez registrace{/t}">
                              {t}Nákup bez registrace{/t}
                           </a>
                        </li>
                     </ul>
                     <hr>
                  </div>
               {/block}
               <div class="row signinrow">
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="iemail">{t}E-mail{/t}</label>
                        <input type="email" name="invoice[email]" value="{$body.invoice.email}" id="iemail"
                               class="form-control smartform-instance-invoice smartform-email"
                               data-bv-notempty="true" data-cart="noreload" required>
                     </div>
                  </div>

                  <div class="{$column_class} cart-user-mailcheck">
                     <div id="email-text"></div>
                  </div>
               </div>
               <div class="row" data-passwords{if !$body->register} style="display: none;"{/if}>
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="password">{t}Heslo{/t}</label>
                        <input type="password" name="password" id="password" value="{$body->register}"
                               class="form-control" autocomplete="new-password"
                               data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="6"
                               {if !$body->register}disabled{/if}>
                     </div>
                  </div>
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="passwordAgain">{t}Heslo znovu{/t}</label>
                        <input type="password" name="passwordAgain" id="passwordAgain" value="{$body->register}"
                               class="form-control" autocomplete="new-password"
                               data-bv-notempty="true" data-bv-stringlength="true" data-bv-identical="true"
                               data-bv-identical-message="Hesla se neshodují" data-bv-identical-field="password"
                               {if !$body->register}disabled{/if} >
                     </div>
                  </div>
               </div>
            {/block}
         {/if}

         {block "form-personal-data-address-wrapper"}
            <div class="row personal-data">
               <div class="{$column_class}">
                  <p class="title-default">{t}Kontaktní údaje{/t}</p>

                  <div class="form-group required">
                     <label for="iname">{t}Jméno{/t}</label>
                     <input type="text" name="invoice[name]" id="iname" class="form-control" value="{$body.invoice.name}"
                            data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="2" required>
                  </div>
                  <div class="form-group required">
                     <label for="isurname">{t}Příjmení{/t}</label>
                     <input type="text" name="invoice[surname]" id="isurname" class="form-control"
                            value="{$body.invoice.surname}"
                            data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="2" required>
                  </div>
                  <div class="form-group required">
                     <label for="iphone">{t}Telefon{/t}</label>
                     <input type="text" name="invoice[phone]" id="iphone"
                            class="form-control smartform-instance-invoice smartform-phone-number" value="{$body.invoice.phone}"
                            data-bv-notempty="true" data-bv-phone="true" required
                        {if !($deliveryType and $deliveryType->isInPerson()) || $inpersonRequireAddress}
                        data-bv-phone-country="invoice[country]"
                        {else}
                        data-bv-phone-country="{$ctrl.active_country}"
                        {/if}>
                  </div>
               </div>

               {* skryt fakturacni adresu pokud je osob. odber a neni nastavene vyzadovani adresy pri os. odberu, napr. KK *}
               {block "personal-data-address"}
                  {if (!$deliveryType || !$deliveryType->isInPerson()) || $inpersonRequireAddress}
                     <div class="{$column_class}">
                        <p class="title-default">{t}Fakturační adresa{/t}</p>

                        {block "invoice-street"}
                           <div class="form-group required">
                              <label for="istreet">{t}Ulice a č.p.{/t}</label>
                              <input type="text" name="invoice[street]" id="istreet"
                                     class="form-control smartform-instance-invoice smartform-address-street-and-number"
                                     value="{$body.invoice.street}" required{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-invoice-street
                                     data-bv-notempty="true" data-bv-regexp="true" pattern=".*\S+\s+[0-9]+.*|.*\S+[0-9]+\s+.*"
                                     data-bv-regexp-message="{t}Doplňte prosím číslo popisné{/t}"{if $tpl_vars.disallowEditB2B} readonly{/if}>
                           </div>
                        {/block}
                        <div class="zip-group">
                           <div class="form-group required">
                              <label for="izip">{t}PSČ{/t}</label>
                              <input type="text" name="invoice[zip]" id="izip"
                                     class="form-control smartform-instance-invoice smartform-address-zip" value="{$body.invoice.zip}"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if}
                                     data-bv-notempty="true" data-bv-zipcode="true" data-bv-zipcode-country="invoice[country]" required
                                     data-field-invoice-zip{if $tpl_vars.disallowEditB2B} readonly{/if}>
                           </div>
                           <div class="form-group required">
                              <label for="icity">{t}Město{/t}</label>
                              <input type="text" name="invoice[city]" id="icity"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if}
                                     class="form-control smartform-instance-invoice smartform-address-city" value="{$body.invoice.city}"
                                     data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="2" required
                                     data-field-invoice-city{if $tpl_vars.disallowEditB2B} readonly{/if}>
                           </div>
                        </div>
                        {block "invoice-country"}
                           <div class="form-group required">
                              <label for="icountry">{t}Stát{/t}</label>
                              {if $tpl_vars.delivery_country_picker}
                                 <a href="/{$body.steps.delivery.url}" class="cart-country-link">{t}Jiný stát?{/t}</a>
                              {/if}
                              <select class="form-control" id="icountry" name="invoice[country]"
                                      {if $cfg.Order.Countries|count == 1 || $tpl_vars.delivery_country_picker || $tpl_vars.disallowEditB2B}readonly{/if}>
                                 {html_options options=$cfg.Order.Countries selected=$body.invoice.country|default:$ctrl.active_country}
                              </select>
                           </div>
                        {/block}
                     </div>
                     {* <div class="col-xxs-12" data-invoice-state-field style="{if $body.invoice.country|default:$ctrl.active_country != 'IT'}display: none;{/if}">
                         <div class="form-group">
                            <label for="invoice[state]">{t}Region{/t}</label>
                            <input type="text" name="invoice[state]" id="invoice[state]" class="form-control" value="{$body.invoice.state}" data-field-invoice-countycode>
                         </div>
                      </div>*}

                     {block "invoice-custom-data"}{/block}
                  {/if}
               {/block}
            </div>
         {/block}
         {* nejdriv check zda existuje deliverytype *}
         {* skryt fakt. adresu pokud deliverytype nevyzaduje dor. adresu (napr. balik na postu) *}
         {if !$deliveryType || $deliveryType->getDelivery()->requiresDeliveryAddress()}
            <div class="form-group">
               <label for="different-address" class="custom-control custom-checkbox">
                  <input type="hidden" name="different_address" value="0">
                  <input class="custom-control-input" type="checkbox" name="different_address"
                         data-opener="#different-address-content" id="different-address"
                         {if $body.delivery.name}checked{/if}>
                  <span class="custom-control-indicator"></span>
                  {t}Dodání na jinou adresu nebo do zaměstnání{/t}
                  <span class="clear-alt-address" style="display: none;">smazat</span>
               </label>
            </div>
            <div class="opener-content" id="different-address-content"
                 style="display:{if $body.delivery.name}block{else}none{/if}">
               {block 'form-delivery-address'}
                  <p class="title-default">{t}Dodací adresa{/t}</p>
                  <div class="row">
                     <div class="{$column_class}">
                        <div class="form-group required">
                           <label for="name">{t}Jméno{/t}</label>
                           <input type="text" name="delivery[name]" id="name" class="form-control"
                                  value="{$body.delivery.name}" autocomplete="off"
                                  data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="3">
                        </div>
                        <div class="form-group required">
                           <label for="surname">{t}Příjmení{/t}</label>
                           <input type="text" name="delivery[surname]" id="surname" class="form-control"
                                  value="{$body.delivery.surname}" autocomplete="off"
                                  data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="3">
                        </div>
                        {*<div class="form-group">
                           <label for="firm">{t}Firma{/t}</label>
                           <input type="text" name="delivery[firm]" id="firm" class="form-control"
                                  value="{$body.delivery.firm}" autocomplete="off"
                                  data-bv-stringlength="true" data-bv-stringlength-min="3">
                        </div>*}
                        <div class="form-group">
                           <label for="phone">{t}Telefon{/t}</label>
                           <input type="text" name="delivery[phone]" id="phone" class="form-control" value="{$body.delivery.phone}"
                                  autocomplete="off" data-bv-phone="true"
                              {if !($deliveryType and $deliveryType->isInPerson()) || $inpersonRequireAddress}
                              data-bv-phone-country="delivery[country]"
                              {else}
                              data-bv-phone-country="{$ctrl.active_country}"
                              {/if}>
                        </div>
                     </div>
                     <div class="{$column_class}">
                        {block "delivery-street"}
                           <div class="form-group required">
                              <label for="street">{t}Ulice a č.p.{/t}</label>
                              <input type="text" name="delivery[street]" id="street"
                                     class="form-control smartform-instance-delivery smartform-address-street-and-number"
                                     value="{$body.delivery.street}"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-delivery-street
                                     data-bv-notempty="true" data-bv-regexp="true" pattern=".*\S+\s+[0-9]+.*|.*\S+[0-9]+\s+.*"
                                     data-bv-regexp-message="{t}Doplňte prosím číslo popisné{/t}">
                           </div>
                        {/block}
                        <div class="zip-group">
                           <div class="form-group required">
                              <label for="zip">{t}PSČ{/t}</label>
                              <input type="text" name="delivery[zip]" id="zip"
                                     class="form-control smartform-instance-delivery smartform-address-zip" value="{$body.delivery.zip}"
                                 {if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-delivery-zip data-bv-notempty="true" data-bv-zipcode="true"
                                     data-bv-zipcode-country="delivery[country]">
                           </div>
                           <div class="form-group required">
                              <label for="city">{t}Město{/t}</label>
                              <input type="text" name="delivery[city]" id="city"
                                     class="form-control smartform-instance-delivery smartform-address-city"
                                     value="{$body.delivery.city}"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-delivery-city
                                     data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="2">
                           </div>
                        </div>
                        <div class="form-group required">
                           <label for="country">{t}Stát{/t}
                              {if $tpl_vars.delivery_country_picker}
                                 <a href="/{$body.steps.delivery.url}" class="cart-country-link">{t}Jiný stát?{/t}</a>
                              {/if}
                           </label>
                           <select class="form-control" id="country" name="delivery[country]" autocomplete="off"
                                   {if $cfg.Order.Countries|count == 1}readonly{/if}>
                              {html_options options=$cfg.Order.Countries selected=$body.delivery.country|default:$ctrl.active_country}
                           </select>
                        </div>
                     </div>

                     {block "delivery-custom-data"}{/block}
                  </div>
               {/block}
            </div>
         {/if}

         {* pokud je os. odběr, vymazat del. adress, mohla zbyt z předchozího průchodu košíkem *}
         {if $deliveryType and ($deliveryType->isInPerson() or $deliveryType->isVirtual())}
            <input type="hidden" name="delivery[name]" value="">
            <input type="hidden" name="delivery[surname]" value="">
            <input type="hidden" name="delivery[firm]" value="">
            <input type="hidden" name="delivery[street]" value="">
            <input type="hidden" name="delivery[city]" value="">
            <input type="hidden" name="delivery[zip]" value="">
            <input type="hidden" name="delivery[country]" value="">
         {/if}
         {block 'firm-address-checkbox'}
            <div class="form-group">
               <label for="firm-address" class="custom-control custom-checkbox">
                  <input type="hidden" name="firm_address" value="0">
                  <input type="checkbox" name="firm_address" id="firm-address" class="custom-control-input"
                         data-opener="[data-firm-address]" {$body.invoice.firm|checked}>
                  <span class="custom-control-indicator"></span>
                  {t}Nakupuji na firmu (IČ, DIČ){/t}
                  <span class="clear-alt-address" style="display: none;">{t}smazat{/t}</span>
               </label>
            </div>
         {/block}
         <div class="opener-content" style="display:{if $body.invoice.firm}block{else}none{/if}"
              data-firm-address>
            {block 'firm-address'}
               <p class="title-default">{t}Firemní údaje{/t}</p>
               <div class="row">
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="ifirm">{t}Název firmy{/t}</label>
                        <input type="text" name="invoice[firm]" id="ifirm" class="form-control smartform-company-name"
                               value="{$body.invoice.firm}"
                               autocomplete="off"
                               data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="3"
                               {if $tpl_vars.disallowEditB2B}readonly{/if}>
                     </div>
                  </div>
                  {if $showCopyEmail}
                     <div class="{$column_class}">
                        <div class="form-group">
                           <label for="icopy_email">{t}E-mail pro fakturaci{/t}</label>
                           <input type="email" name="invoice[copy_email]" id="icopy_email"
                                  class="form-control smartform-instance-invoice smartform-email"
                                  value="{$body.invoice.copy_email}">
                        </div>
                     </div>
                  {/if}
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="iico">{t}IČO{/t}</label>
                        <input type="number" name="invoice[ico]" id="iico"
                               class="form-control disable-spinner smartform-company-registration-number"
                               value="{$body.invoice.ico}" autocomplete="off"
                               data-bv-notempty="true" data-bv-stringlength="true" data-bv-stringlength-min="8"
                               data-bv-stringlength-max="10" {if $tpl_vars.disallowEditB2B}readonly{/if}>
                     </div>
                  </div>
                  <div class="{$column_class}">
                     <div class="form-group">
                        <label for="idic">{t}DIČ{/t}</label>
                        <input type="text" name="invoice[dic]" id="idic" class="form-control smartform-company-vat-number"
                               value="{$body.invoice.dic}"
                               autocomplete="off"
                               data-bv-vat="true" data-bv-vat-country="invoice[country]" {if $tpl_vars.disallowEditB2B}readonly{/if}>
                     </div>
                  </div>
                  <div class="{$column_class} dic-notify">
                     <p>{t escape=false}Vyplníte-li platné zahraniční DIČ,<br> objednávka bude osvobozena od DPH.{/t}</p>
                  </div>
               </div>
            {/block}

            {* mam osobni odber (nevyzaduje zadani adresy), chci fakturu na firmu *}
            {if $deliveryType and $deliveryType->isInPerson() and !$inpersonRequireAddress}
               <div class="row">
                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="istreet">{t}Ulice a č.p.{/t}</label>
                        <input type="text" name="invoice[street]" id="istreet"
                               class="form-control smartform-instance-invoice smartform-address-street-and-number"
                               value="{$body.invoice.street}"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-invoice-street
                               data-bv-notempty="true" data-bv-regexp="true" pattern=".*\S+\s+[0-9]+.*|.*\S+[0-9]+\s+.*"
                               data-bv-regexp-message="{t}Doplňte prosím číslo popisné{/t}"{if $tpl_vars.disallowEditB2B} readonly{/if}>
                     </div>
                  </div>
                  <div class="col-lg-3 col-sm-6 col-xxs-12">
                     <div class="form-group required">
                        <label for="icity">{t}Město{/t}</label>
                        <input type="text" name="invoice[city]" id="icity"
                               class="form-control smartform-instance-invoice smartform-address-city"
                               value="{$body.invoice.city}"{if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-field-invoice-city
                               data-bv-notempty="true" data-bv-stringlength="true"
                               data-bv-stringlength-min="2"{if $tpl_vars.disallowEditB2B} readonly{/if}>
                     </div>
                  </div>
                  <div class="col-xl-2 col-lg-3 col-sm-6 col-xxs-12">
                     <div class="form-group required">
                        <label for="izip">{t}PSČ{/t}</label>
                        <input type="text" name="invoice[zip]" id="izip"
                               class="form-control smartform-instance-invoice smartform-address-zip" value="{$body.invoice.zip}"
                           {if $dbcfg.smartform == "Y" or $dbcfg.here_autocomplete == "Y"} autocomplete="off"{/if} data-bv-notempty="true" data-bv-zipcode="true" data-field-invoice-zip
                               data-bv-zipcode-country="invoice[country]"{if $tpl_vars.disallowEditB2B} readonly{/if}>
                     </div>
                  </div>

                  <div class="{$column_class}">
                     <div class="form-group required">
                        <label for="icountry">{t}Stát{/t}
                           {if $tpl_vars.delivery_country_picker}
                              <a href="/{$body.steps.delivery.url}" class="cart-country-link">{t}Jiný stát?{/t}</a>
                           {/if}
                        </label>
                        <select class="form-control c-select custom-select" id="icountry" name="invoice[country]"
                                autocomplete="off" {if $cfg.Order.Countries|count == 1 || $tpl_vars.disallowEditB2B}readonly{/if}>
                           {html_options options=$cfg.Order.Countries selected=$body.invoice.country|default:$ctrl.active_country}
                        </select>
                     </div>
                  </div>

                  {*<div class="col-xxs-12" data-delivery-state-field style="{if $body.delivery.country|default:$ctrl.active_country != 'IT'}display: none;{/if}">
                     <div class="form-group">
                        <label for="delivery[state]">{t}Region{/t}</label>
                        <input type="text" name="delivery[state]" id="delivery[state]" class="form-control" value="{$body.delivery.state}" data-field-delivery-countycode>
                     </div>
                  </div>*}
               </div>
            {/if}
         </div>
      </div>
   {/if}

   {block 'order-note'}
      <div class="row">
         <div class="col-xxs-12">
            <div class="form-group">
               <label for="noteUser" class="title-default">{t}Poznámka k objednávce{/t}</label>
               <textarea name="noteUser" rows="5" id="noteUser" class="form-control">{$body.note}</textarea>
            </div>
         </div>
      </div>
   {/block}

   {block "ordering-user-gdpr"}
      {if $tpl_vars.btns_in_sidebar}
         {include "ordering/ordering.gdpr.tpl"}
      {/if}
   {/block}
{/block}

{block 'cart-footer'}
   <div class="cart-footer">
      {include "ordering/ordering.pricebox.tpl" transport=1}
   </div>
{/block}

{block 'cart-btns'}
   {if !$tpl_vars.btns_in_sidebar}
      {if array_key_last($cfg.Order.Steps) == $body.actualStep}
         {include "ordering/ordering.btns.tpl" submitName='SubmitOrder' valueNext='{t}Potvrdit objednávku{/t}'}
      {else}
         {include "ordering/ordering.btns.tpl" submitName='OrderNext' valueNext='summary'}
      {/if}
   {/if}
{/block}


{block "js-dynamic-load" append}
   <script>
      var $form = $('#cart');
      var foxEntryActive = false;

      {block "form-validation"}
      $form.one('input', 'input', function () {
         if (typeof Foxentry === "object" && Foxentry.isReady() && Foxentry.getRequestsUsageData()) {
            console.log('FE active');

            foxEntryActive = true;

            const $submitBtn = $('button[type="submit"]');

            // disable button when user submit the form.
            $form.submit(function (e) {
                  // button should be enabled in a moment when user submit form
                  if ($submitBtn.prop('disabled')) {
                     $submitBtn.prop('disabled', false);
                  }

                  /* This code disables the submit button after the form is submitted,
                  preventing being stuck on the same page and avoiding multiple form submissions
                   */
                  setTimeout(() => {
                     $(this).find('[type=submit]').prop('disabled', true);
                  }, 0);

                  return true;
               });
         } else {
            console.log('BSV active');

            $form.bootstrapValidator({
               feedbackIcons: {
                  valid: 'fa fa-check fc fc-check',
                  invalid: 'fa fa-remove fc fc-remove',
                  validating: 'fa fa-refresh fc fc-refresh',
               },
            }).on('change', '[data-bv-notempty]', function (event) {
               var $this = $(event.target),
                  elementName = $this.attr('name');

               $(event.target.form)
                  // Get the bootstrapValidator instance
                  .data('bootstrapValidator')
                  // Mark the field as not validated, so it'll be re-validated when the user change date
                  .updateStatus(elementName, 'NOT_VALIDATED', null)
                  // Validate the field
                  .validateField(elementName);
            }).on('validationError.validator.bv', function (e, data) {
               $('.cart-btns .last.success').removeClass('success')
               // Disable multiple error messages for one field
               data.element.data('bv.messages')
                  // Hide all the messages
                  .find('.help-block[data-bv-for="' + data.field + '"]').hide()
                  // Show only message associated with current validator
                  .filter('[data-bv-validator="' + data.validator + '"]').show();
            }).on('success.form.bv', function () {
               $('.cart-btns .last').addClass('success')
            }).on('submit', function () {
               var err = $form.find('.has-error').first();
               if (err.length && !wpj.domUtils.isInView(err)) {
                  wpj.domUtils.scrollTo(err);
               }

               if ($('.signinrow.invalid-email').length) {
                  wpj.domUtils.scrollTo($('.signinrow.invalid-email'));
                  return false;
               }

               return true;
            });

            if (typeof enablePasswordValidation === "function") {
               enablePasswordValidation({if $body->register}true{else}false{/if});
            }
         }
      });

      {block "doCheckEmail"}

      {block "cartMessages"}
      {$cartMessage_newAccount = "{t}Registrace má své výhody{/t}. <a href='{url s=user act=new}' class='email-register'>{t}Vytvořit účet{/t}</a>?"}
      {$cartMessage_checkEmail = "{t}Jste si jistí správností e-mailové adresy?{/t}"}
      {$cartMessage_existingAccount = "{t}Již u nás máte účet{/t}. <a href='{url s=login}' class='cart-signin' data-wpj-modal='{$modal_login}'  data-wpj-modal-type='side'>{t}Přihlaste se{/t}</a>"}
      {$cartMessage_invalidDomain = "{t escape=js}Zkontrolujte si prosím emailovou adresu. Tato doména neexistuje.{/t}"}
      {/block}

      function doCheckEmail() {
         var email = $('#iemail').val(),
            message = '',
            regexp = {literal}/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i{/literal},
            $parent = $('#iemail').closest('.signinrow');

         if (!regexp.test(email)) {
            message += "";
            showMessage(message);
         } else {
            var data = {
               'email': email,
            };
            $.post('/launch.php?s=ajax&type=email', data, function (data) {
               var isValid = data.validDomain;

               if (data.found) {
                  message = "{$cartMessage_existingAccount nofilter}";
               } else if (!isValid) {
                  message = "{$cartMessage_invalidDomain}";
               } else {
                  message = "";
               }

               $parent.toggleClass('invalid-email', !isValid).find('.has-feedback')
                  .toggleClass('has-success', isValid).toggleClass('has-error', !isValid);

               showMessage(message);
            }, 'json');
         }
      }

      function checkEmail() {
         if (typeof $form.data('bootstrapValidator') === 'object') {
            wpj.domUtils.resetTimer('iemail', 500, doCheckEmail);
         }
      }

      var $message = $('#email-text');
      var $passwords = $('#passwords');

      function showMessage(message) {
         $message.html('<p>' + message + '</p>');
         if (message) {
            $message.show();
         } else {
            $message.hide();
         }
      }

      {/block}

      var $email = $('#iemail');

      $email.on('keydown input change', checkEmail);

      if ($email.val()) {
         $email.change();
      }

      {if !$ctrl.logged}
      {block "password-validation"}
      {block "register-js"}
      {if $tpl_vars.ordering_user_v == "2"}
      $form.on('change', '#new-account', function () {
         var $field = $('#password')
         $field.prop('disabled', !$(this).prop('checked'));
         enablePasswordValidation($(this).prop('checked'));
         return false;
      });

      $form.on('click', '[data-toggle-password]', function (e) {
         var $pw_field = $('#password');
         if ($pw_field.attr('type') == 'password') {
            $pw_field.attr('type', 'text');
            $(this).html('{t}Skrýt{/t}');
         } else {
            $pw_field.attr('type', 'password');
            $(this).html('{t}Zobrazit{/t}');
         }
         return false;
      });
      {else}
      $form.on('click', '.email-register, .email-unregister', function () {
         var $fields = $('#password, #passwordAgain'),
            register = $('[data-toggle="tab"].active').is('.email-register');

         $('[data-toggle="tab"]').toggleClass('active');
         $('.nav-item-toggle').toggleClass('toggled');
         $('[data-passwords]').toggle();

         $fields.val('').prop('disabled', register);

         if (typeof $form.data('bootstrapValidator') === 'object') {
            $form.data('bootstrapValidator').resetForm();
            //wpj.domUtils.crossFade($message, $passwords);
            enablePasswordValidation(!register);
         }

         return false;

      })
      {/if}

      $form.on('click', '.cart-signin', function () {
         $('#login').login('setEmail', $email.val());
      });
      {/block}

      function enablePasswordValidation(enable) {
         $form.bootstrapValidator('enableFieldValidators', 'password', enable);
         {if $tpl_vars.ordering_user_v != "2"}
         $form.bootstrapValidator('enableFieldValidators', 'passwordAgain', enable);
         {/if}
      }
      {/block}
      {/if}

      $('[name=\'invoice[country]\'], [name=\'delivery[country]\']').on('change', function () {
         //   $('body').trigger('countryChanged', [$(this)]);
         if (typeof $form.data('bootstrapValidator') === 'object') {
            $form.data('bootstrapValidator').resetForm();
            $form.bootstrapValidator('validate');
         }
      });

      {* Opětovné enablovaní submitu pokud vypnu nákup na firmu nebo dodání na jinou adresu *}
      $form.on('change', '#different-address, #firm-address, #new-account', function () {
         if (typeof $form.data('bootstrapValidator') === 'object') {
            $form.data('bootstrapValidator').resetForm();
         }
      });
      {/block}

      {* tlacitko 'smazat' u doruc. adresy a firmy *}
      $form.on('click', '.clear-alt-address', function () {
         var target = $(this).siblings('input[type=checkbox]').attr('data-opener');
         $(target).find('input').val('');
      });

      {* Openers *}
      wpj.domUtils.initOpeners();
   </script>
{/block}

{block analytics append}
   {if $dbcfg.analytics.foxentry.ID}
      {get_contexts country=1 assign="country_contexts"}
      {$active_country = $country_contexts.country->getActive()}
      {if $active_country.id|in_array:['CZ', 'SK', 'PL']}
         <!-- Foxentry start -->
         <script type="text/javascript" async>
            var Foxentry;
            (function () {
               var e = document.querySelector("script"), s = document.createElement('script');
               s.setAttribute('type', 'text/javascript');
               s.setAttribute('async', 'true');
               s.setAttribute('src', 'https://cdn.foxentry.cz/lib');
               e.parentNode.appendChild(s);
               s.onload = function () {
                  Foxentry = new FoxentryBase('{$dbcfg.analytics.foxentry.ID}');
               }
            })();
         </script>
         <!-- Foxentry end -->
      {/if}
   {/if}

   {include "components/block.smartForm.tpl"}
{/block}
