{get_contexts currency=1 language=1 country=1 assign="contexts"}
{$activeCountry = $contexts.country->getActive()}
{$activeCurrency = $contexts.currency->getActive()}
{$activeLang = $contexts.language->getActive()}

{if isDevelopment() && $dbcfg.analytics.google_tag_manager.reallyRun != 'Y'}
   {assign var="gtmId" scope="global" value='GTM-PFLLL74'}
{else}
   {assign var="gtmId" scope="global" value=$dbcfg.analytics.google_tag_manager.ID}
{/if}

{if $smarty.get.skip_gtm !== null}
   {assign var="gtmId" scope="global" value=false}
{/if}

{if $dbcfg.analytics.google_tag_manager.gtm_dl_version == 2 || (getAdminUser() && $dbcfg.analytics.google_tag_manager.gtm_dl_version == 1)}
{strip}
{if $gtmId}
    {switch $gtm_type}
        {case "gtm"}
            {get_gtm_data assign='GTM'}
               <script>
                page_data = {$GTM|json_encode:32 nofilter};
                page_data['page']['layout'] = window.innerWidth  > 991 ? 'web' : window.innerWidth > 543 ? 'tablet' : 'mobil';

                {ifmodule JS_SHOP}
                if (typeof userData === 'undefined') {
                   var userData = wpj.getCookie('jsShopGtmUser');
                   var userDataParsed = null;
                   if(userData) {
                      userDataParsed = JSON.parse(userData);
                      wpj.onReady.push(function () {
                         wpj.storage.cookies.removeItem('jsShopGtmUser');
                      });
                   } else {
                      userData = localStorage.getItem('js-shop-gtm-user');
                      if(userData) {
                         userDataParsed = JSON.parse(userData).data;
                      }
                   }
                }

                if (userDataParsed) {
                   page_data.user = userDataParsed;
                }

                {/ifmodule}

                {* Standardni page data *}
               dataLayer.push(page_data);
            </script>

            {if $GTM && $GTM.page->type == 'product'}
              {* Pokud preklikavam mezi variantami, nebo se nacita stranka s produktem/variantou, posilat product impressions *}
              <script src="{static_url url="/common/static/wpj/wpj.gtm.js"}?v2"></script>

              <script>
                 var urlParams = new URLSearchParams(window.location.search);
                 var hash = location.href.split("#")[1] || urlParams.get('id_variation') || "{array_key_first($body.product.variations.variations)}";

              {* Variation impressions  *}
              {if $body.product && $body.product.variations.variations|count}
                 {* Pole pro pripravu dat pro varianty *}
                 gtm_prva = {  };
                 {* Zakladni data stranky *}

                 {get_price_computer assign='priceComputer'}
                 {foreach $body.product.variations.variations as $variation}
                     {if $variation.delivery_time_index != '-1'}
                         gtm_prva[{$variation.id}] = {
                            'id': '{$body.product.id}_{$variation.id}',
                            'idVariation': '{$variation.id}',
                            'idProduct': '{$body.product.id}',
                            'EAN': '{$variation.ean}',
                            'variationName': '{$variation.title|trim|escape:javascript}',
                            'code': '{$variation.code}',
                            'price': {$priceComputer->getPrice($variation.productPrice)},
                            'variationCode': '{$variation.variationCode}',
                            'productCode': '{$body.product.productCode}',
                         };
                     {/if}
                 {/foreach}

                 {* Odeslani impressions *}
                 wpj.onReady.push(function () {
                    $('input[name^=IDvariation], select#IDvariation').on('change', function () {
                       gtm_getDetailImpressions($(this).val(), 'detailImpressionsVariation');
                    });

                    if (hash != "") {
                       variation = gtm_getVariation(hash);

                       product = $.extend(page_data['products'], variation);
                       page_data = $.extend(page_data, { 'products':  product });
                    }

                    gtm_getDetailImpressions(hash, 'detailImpressions');
                 });
              {else}
                  {* Product impressions *}
                  gtm_getDetailImpressions(hash, 'detailImpressions');
              {/if}
               </script>
            {/if}

            {if $body.steps}
                {get_gtm_data type='ecommerce' method='Checkout' assign='ecommerce' data=['body' => $body]}
            {/if}

            {if $body.orderSent}
                {get_gtm_data type='ecommerce' method='Purchase' assign='ecommerce' data=['body' => $body]}
            {/if}

            {if $slider}
                {get_gtm_data type='ecommerce' method='PromotionImpression' assign='ecommerce' data=['slider' => $slider]}
            {/if}

           {if $GTM && $GTM.page->type === 'searchResult'}
               {get_gtm_data type='ecommerce' method='SearchResult' assign='ecommerce'}
           {/if}

            {if $ecommerce}
                <script>dataLayer.push({$ecommerce|json_encode:32 nofilter});</script>
            {/if}


           <script>
              wpj.onReady.push(function () {
                 [ 'logout', 'registration', 'login', 'newsletter_subscribe'].forEach(function (type) {
                    let cookieValue = wpj.storage.cookies.getItem('gtm_'+type);

                    if (cookieValue === null) {
                       return;
                    }
                    wpj.storage.cookies.removeItem('gtm_'+type);

                    cookieValue = JSON.parse(cookieValue);

                    let valueData;
                    if (type === 'newsletter_subscribe') {
                       valueData = { ...cookieValue };
                    } else if (cookieValue instanceof Array) {
                       valueData = { data: cookieValue };
                    } else {
                       valueData = { value: cookieValue };
                    }
                     window.dataLayer.push({
                        event: 'success' +  gtm_ucfirst(type),
                           ...valueData
                     });
                 });
              });
              function gtm_ucfirst(str) {
                   if (!str || typeof str !== 'string') return str;
                   return str.charAt(0).toUpperCase() + str.slice(1);
               }
           </script>
        {/case}

            <script>
        {case "form_conversion"}
                var formData = { };
                $.each($this.serializeArray(), function() {
                   formData[this.name] = this.value;
                });
                dataLayer.push({
                    event: "successSendForm",
                    formData: formData
                });
        {/case}
            </script>

        {case "addToCart"}
            {if $dbcfg.analytics.google_tag_manager.active_fe_events != 'Y'}
               {get_gtm_data method='AddToCart'  type='ecommerce' assign='ecommerce' data=['addedToCart' => $addedToCart]}
               <script>dataLayer.push({$ecommerce|json_encode:32 nofilter});</script>
            {/if}
        {/case}

        {case "addToWishList"}
            {get_gtm_data method='AddToWishList'  type='ecommerce' assign='ecommerce' data=['addedToWishList' => $addedToWishList]}
            <script>
               dataLayer.push({$ecommerce|json_encode:32 nofilter});
            </script>
        {/case}

        {case "dummy"}
         {* Dummy case, protoze nemuze bejt pred {/switch} nebo {default} jako posledni </script>, pada to pak na kompilaci. *}
        {/case}

        {default}
            {if $slider}
                {get_gtm_data type='ecommerce' method='PromotionImpression' assign='ecommerce' data=['slider' => $slider]}
            {/if}

            {if $ecommerce}
                <script>dataLayer.push({$ecommerce|json_encode:32 nofilter});</script>
            {/if}
    {/switch}
{/if}
{/strip}
{else}
     {include "[GTMOldBundle]/block.old_gtm.tpl"}
{/if}
