
		function ready(fn) {
			  if (document.readyState != 'loading'){
				fn();
			  } else {
				document.addEventListener('DOMContentLoaded', fn);
			  }
			}
		 (function(){
			ready(function() {
                console.log('checking product..');
                
                var idx = $('form[action="/cart/add"] *[name="id"]:eq(0)').val();
                if ( idx == undefined ){
                    console.log('idx:'+ idx);
                    idx = $('form[action="/cart/add"] *[name="id"]:eq(0) option:selected').val();
                    if ( idx == undefined ){
                        idx=0;
                        //return false;
                    }
                }
                var product_handle_check = product_detail.handle;
                if (product_handle_check.substr(product_handle_check.length - 10) == 'customized'){
                    if ( typeof product_ori_id != undefined && typeof product_ori_handle != undefined ) {
                        console.log('redirection..');
                        $('body').html('<p>Loading..</p>');
                        //console.log('product_ori_id');
                        //console.log(product_ori_id);
                        var the_link_direct = '/apps/customify/view/' + product_ori_handle + '/' + product_ori_id + '?variant=' + idx + '&domain=' + window.location.hostname;
                        window.location = the_link_direct;
                        return false;
                    }
                }
                $('form[action="/cart/add"]').on('click', '#customify-link' , function(e){
                     e.preventDefault();
                            //console.log('customify link clicked');
        var inputQty = $( this ).closest('form').find('input[name=quantity]');
                            idx = $('select[name=id]').length > 0 ? $('select[name=id]').val() : $('input[name=id]').val();
                            var qty = '1';
                            qty = (inputQty.length > 0 && inputQty.val() != '') ? inputQty.val() : '1';
                            var the_link = '/apps/customify/view/' + $(this).data('handle') + '/' + $(this).data('product') + '?variant=' + idx + '&qty='+ qty + '&domain=' + window.location.hostname;
                            console.log(the_link);
                            window.location = the_link;
                            return false;
                })


				var result = {"status":"no","setting":{"keep_addtocart":"0","redirect_instant":0,"keep_buybutton":"1","customize_it":"Customize it","term_and_agreement":"I agree with the \u003Ca href='#'\u003Eterms and aggrement\u003C\/a\u003E.","is_onloadProduct":0,"form_type":0,"direct_styling":1,"canvas_mobile_float":0}}
				 if ( result.status == 'yes' )
						{
                            keep_addtocart = result.setting.keep_addtocart;
                            term_agreement = result.setting.term_agreement;
							keep_buybutton = result.setting.keep_buybutton;
                            redirect_instant = result.setting.redirect_instant;
                            canvas_mobile_float = result.setting.canvas_mobile_float;
                            direct_styling = result.setting.direct_styling;
                            form_type = result.setting.form_type;
                            if(result.setting.is_onloadProduct=='1'){

                                var htmlAppend = `<div id="cst-popup-gallery" class="cst-popup-container">
                                <div class="popup-content">
                                  <a href="#" class="close cst-close">&times;</a>
                                      <div class="container-main">
                                          <h3 class="txtLang">modules.designs</h3>
                                          <div class="item-filter pdrt">
                                              <form class="form" action="" method="">
                                                  <div class="float-left form-row span_6_of_12 float-left">
                                                      <input type="text" id="cst-search-gallery" name="search-item" class="cst-search-gallery input txtLang" placeholder="placeholder.search" />
                                                      <button type="button" class="btn-search"><i class="fa fa-search"></i></button>
                                                  </div>
                                                  <span class="txtLang"></span>
                                                  <div class="span_6_of_12 float-right">
                                                      <select id="cst-gallery-cat" class="select-cat cst-gallery-cat">
                                                      </select>
                                                  </div>
                                              </form>
                                          </div>
                                          <div id="cst-gallery-box" class="cst-gallery-box show-thumbnail gallery-thumbnail">
                                          </div>
                                      </div>
                                  </div>
                              </div>
                          <div class="cst-loader-container"><div class="loader-inner"><div id="loading"></div></div></div>`;
                          htmlAppend += `<div id="cst-popup-crop" class="cst-popup-container">
                                <div class="popup-content">
                                  <a href="#" class="close cst-close" id="crop-close">&times;</a>
                                      <div class="container-main">
                                          <h3 class="txtLang">Crop Image</h3>
                                          
                                          <div id="cst-crop-box" class="">
                                              <img src="" id="view_crop_image" />
                                          </div>
                                          <div class="crop-modal-footer">
                                              <button type="button" class="btn btn-secondary" id="crop-cancel" data-dismiss="modal">Cancel</button>
                                              <button type="button" class="btn btn-primary" id="crop">Crop</button>
                                          </div>
                                      </div>
                                  </div>
                              </div>
                          <div class="cst-loader-container"><div class="loader-inner"><div id="loading"></div></div></div>`;
                              
                          $('body').append(htmlAppend)

                          $(CST_ID).css('height','auto !important')
  
  
                          var style='';
                            style +='<link rel="stylesheet" href="https://d2hl1uvd5lolaz.cloudfront.net/cstassets/style-v2.1.min.css">';
                            style +='<link rel="stylesheet" href="https://d2hl1uvd5lolaz.cloudfront.net/cstassets/onload/css/cst-load-page-v1.2.min.css">';
                            style +='<link rel="stylesheet" href="https://d2hl1uvd5lolaz.cloudfront.net/cstassets/onload/css/cropper.css">';
                            
                            style +='<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">';
                        
                            var Element = '<div id="cst-simple-input" class="cst-row cstselector-wrapper"></div><div class="customify-form-row cst-row" style="margin-top:20px;">';
                            Element +='<div class="cst-col cst-col-separo cst-counter-odd">';
                            Element +='<div id="cst-btn-uploadimage" class="cst_btn_side cst_upload_image_side">';
                            Element +='<input type="file" accept="image/*" class="cst-upload_file cst-upload" name="upload_file[]">';
                            Element +='<label class="cst-label-center"><i class="material-icons notranslate">add_a_photo</i><span class="d_block txtLang">Add Image</span></label>';
                            Element +='</div>';
                            Element +='</div>';
                            Element +='<div class="cst-col cst-col-separo cst-counter-odd">';
                            Element +='<div id="cst-btn-addtext" class="cst_btn_side cst_add_text">';
                            Element +='<span class="cst-add_text_onload cst-label-center"><i class="material-icons notranslate">font_download</i><span class="d_block txtLang">Add text</span></span>';
                            Element +='</div>';
                            Element +='</div>';
                            Element +='<div class="cst-col cst-col-separo cst-counter-odd">';
                            Element +='<div id="cst-btn-gallery" class="cst_btn_side cst_add_gallery">';
                            Element +='<label class="cst-label-center"><i class="material-icons notranslate">perm_media</i><span class="d_block txtLang">Gallery</span></label>';
                            Element +='</div>';
                            Element +='</div>';
                            Element +='</div>';
                            $('head').append(style);
                            $(CST_SUBMIT).parents('form').prepend(Element)

                            $(CST_SUBMIT).parents('form').attr('id', 'customify_form');
                            $(CST_SUBMIT).removeClass(CST_SUBMITREMOVE_CLASS);
                            $(CST_SUBMIT).next().html("<div id='CST_SUBMIT_W' class='CST_SUBMIT_W'></div>");
                             $(CST_SUBMIT).attr('id', 'customify-addtocart');
                             $(CST_PRICE).attr('id', 'cst-price');

                              if($('.shopify-payment-button').length){
                                  $('.shopify-payment-button').remove();
                              }
  
                              // remove slider
                              $('.thumbnails-wrapper').remove();

                            //form type table
                            if(form_type=='1'){
                                document.dispatchEvent(new Event('cstVariantTable'))
                            }

                            if (term_agreement == '1'){
                                $('#customify-addtocart').before("<label id='check_taa_label' style='margin-bottom: 15px;display: block;padding-left: 20px;text-indent: -18px;'><input type='checkbox' id='check_taa' class='check_taa' required style='margin-right: 5px;cursor: pointer;'>"+result.setting.term_and_agreement+"</label>");
                            }
  
                              var url = '/apps/customify/view_onload_product/' + product_detail.handle + '/8507641561367';
                              $.get(url, function(data) {
                                    let counter_ = 0;
                                    if(typeof cstJquery.customizer == 'undefined'){
                                        counter_ = 5000;
                                    }

                                    setTimeout(function(){
                                        document.dispatchEvent(new Event('cstBeforeReady'))
                                        $(CST_ID).children().hide();
                                        $(CST_ID).css('position','relative')
                                        $(CST_ID).append("<div style='position: absolute; top:0;left:0;right:0;bottom:0;z-index:1;' id='cst-canvas'>"+data+"</div>");
    
                                        //move input quantity to inside the form
                                        // if ($('').length){
                                        //     $(' input').attr('id','Quantity');
                                        //     $(' input').attr('form','customify_form');
                                        //     let html_qty = $('').clone(true);
                                        //     $('').remove();
                                        //     html_qty.clone(true).insertBefore('');
                                        // }
                                        
                                        document.dispatchEvent(new Event('cstReady'))
                                        $('.loader-container').remove();
                                        setTimeout(function(){
    
                                            let htmlPreload = $('#cst-preload').html();
                                            $('#cst-preload').remove()
                                            $('#cst-simple-input').before().html(htmlPreload)
                                            let cstCanvasWidth = $('#left-side').width();
                                            let cstCanvasHeight = $('#left-side').height();
                                            let cstSliderHeight = 0;
                                            let totalHeight = 0;
                                            if($('.wrapper-switcher').length){
                                                cstSliderHeight = 50;
                                            }else{
                                                totalHeight += 20;
                                            }
                                            if(direct_styling === '2'){
                                                totalHeight += 50;
                                            }
                                            totalHeight += parseInt(cstSliderHeight)+parseInt(cstCanvasHeight);
                                            $(CST_ID).css('height',totalHeight+'px')
    
                                            if(canvas_mobile_float=="1"){
                                            // scroll event
                                            let hasApplyCss = false;
                                            let resetCss = false;
                                            var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
                                            if(width<420){
                                                window.addEventListener("scroll", function(event) {
                                          
                                                    var scroll_y = this.scrollY;
                                                    var scroll_x = this.scrollX;
                                                    if(scroll_y>=100 && hasApplyCss==false){
                                                        $('#left-side').css('position','fixed');
                                                        $('#left-side').css('top','0px');
                                                        $('#left-side').css('padding-top','40px');
                                                        $('#left-side').css('left','50%');
                                                        $('#left-side').css('transform','translateX(-50%)');
                                                        $('#left-side').css('background','white');
                                                        $('#left-side').css('z-index','99000');
                                                        hasApplyCss = true;
                                                        resetCss = false;
                                                    }
                                                    if(scroll_y<100 && resetCss==false){
                                                        hasApplyCss = false;
                                                        $('#left-side').css('position','unset');
                                                        $('#left-side').css('transform','unset');
                                                        $('#left-side').css('background','unset');
                                                        resetCss = true;
                                                    }
                                                });
                                            }}
                                        },500)
    
                                        setTimeout(function(){
                                            $('.cst-loader-container').addClass('hide');
                                            let counter = 0;
                                            if(typeof JSColor != 'undefined'){
                                                jscolor.install();
                                                if($('.cst-more-color').length){
                                                    $('.cst-more-color').each(function(){
                                                      counter++;
                                                      let id = 'cst-more-color-'+counter;
                                                      $(this).attr('id',id)
                                                      var picker = new JSColor('#'+id, {valueElement:'valueSpan',previewElement:'styleSpan', value: '0FF3FF',onInput: 'updatePColorElemen(this)'});
                                                    })
                                                }
                                                if($('#btn-picker').length){
                                                    var picker = new JSColor('#btn-picker', {valueElement:'valueSpan',previewElement:'styleSpan', value: '0FF3FF',onInput: 'updatePColor(this)'});
                                                }
    
                                            }else{
                                                $('.cst-more-color, #btn-picker').css('display','none')
                                            }
                                        },1000)   
                                    },counter_)
                              });
                              
                          }else{
                                document.dispatchEvent(new Event('cstHideQty'))
                                var the_link = '/apps/customify/view/' + product_detail.handle + '/' + product_detail.id + '?variant=' + idx + '&domain=' + window.location.hostname;
                                if ( redirect_instant == 1 ) {
                                window.location = the_link;
                                return false;
                                }
                                if ( $('#add-to-cart').length > 0 )
                                var the_button = $('#add-to-cart');
                                else if ( $('button[name=add]').length > 0 )
                                var the_button = $('button[name=add]');
                                else
                                var the_button =  $('form[action="/cart/add"] button[type="submit"]').length > 0 ? $('form[action="/cart/add"] button[type="submit"]') : $('form[action="/cart/add"] input[type="submit"]');
                                the_button.hide();
                                var the_class = the_button.attr('class');
                                if ( the_class != undefined ) {
                                the_class = the_class.replace('add-to-cart','');
                                the_class = the_class.replace('hidden','');
                                }
                                else
                                {
                                    the_class = 'btn button';
                                }
                                var the_style = '';
                                button_width = the_button.width() * 1;
                                if ( keep_addtocart == 1 ) {
                                    if ( button_width > 200 )
                                    the_style = 'style="clear: both; margin-top: 10px;"';
                                    else
                                    the_style = 'style="margin-left: 10px;"';
                                }
                                console.log('check wheter the customify custom container available..');
                                if ($('#customify-container').length > 0 )
                                {
                                the_class = $('#customify-container').data('class');
                                $('#customify-container').html('<a  data-handle="' + product_detail.handle + '"  data-product="' + product_detail.id + '"  id="customify-link" class="' + the_class + '" href="' + the_link + '" >' + result.setting.customize_it + '</a>');
                                }
                                else
                                {
                                $('<a ' + the_style + ' data-handle="' + product_detail.handle + '"  data-product="' + product_detail.id + '"  id="customify-link" class="' + the_class + '" href="' + the_link + '" >' + result.setting.customize_it + '</a>').insertAfter(the_button);
                                }
                                if(keep_buybutton == 0){
                                    $('.shopify-payment-button').css('display','none');
                                }
                                if ( the_button.attr('data-show') == undefined && keep_addtocart == 0 ) {
                                console.log('hide the add to cart');
                                $('form[action="/cart/add"] *[type="submit"]').hide();
                                the_button.hide();
                                $('body').append('<style>form[action="/cart/add"] *[type="submit"] { display:none!important; visibility: hidden }</style>');
                                document.dispatchEvent(new Event('cstHideAddToCart'))
                                }
                                else
                                the_button.show();
                                if (typeof customify_callback !== 'undefined' && typeof customify_callback === 'function') {
                                    customify_callback();
                                }
                            }


                          }
            })
        })();