// partpay-widget-shopify.js
(function(){
    "use strict";
    var $;

    
    var calculator = function($script) {        
    	if(typeof $script.attr('src')!=="undefined" && $("#partPayCalculatorWidget1").length === 0){
            var logo = 'partpay_new.png';
            if(typeof getParam($script.attr('src'), 'logoType')!=="undefined" && getParam($script.attr('src'), 'logoType')==='2'){
                logo = 'Payflex_purple.png';
            }
        var html = '<div id="partPayCalculatorWidget1"><div id="partPayCalculatorWidgetText">Or split into 4x <span id="freetext">interest-free</span> <br> payments  <span class="partPayCalculatorWidgetTextFromCopy"></span> <span id="partPayCalculatorWidgetLearn">Learn&nbsp;more</span></div><img id="partPayCalculatorWidgetLogo" src="https://widgets.payflex.co.za/assets/'+logo+'"><div id="partPayCalculatorWidgetDialog" role="dialog"><div class="partPayCalculatorWidgetDialogOuter"><div class="partPayCalculatorWidgetDialogInner"><img id="partPayCalculatorWidgetDialogClose" src="https://widgets.payflex.co.za/assets/cancel-icon.png" alt="Close"><div class="partPayCalculatorWidgetDialogHeading"><div class="partPayCalculatorWidgetDialogHeadingLogo"><img src="https://widgets.payflex.co.za/assets/Payflex_purple.png"></div><div class="partPayCalculatorWidgetDialogHeadingTitle"><div>No interest, no fees,</div><div>4x instalments over 6 weeks</div></div></div><div class="partPayCalculatorWidgetDialogHowItWorksTitle">How it works</div><div class="partPayCalculatorWidgetDialogHowItWorksDesc"><span class="heavyBasketText">Payflex lets you get what you need now, but pay for it over four interest-free instalments. You pay 25% upfront, then three payments of 25% over the following six weeks.</div></span><div class="partPayCalculatorWidgetDialogHowItWorks"><div class="partPayCalculatorWidgetDialogHowItWorksBody"><div><div class="nuumberingarea"><strong>1</strong></div></div><p>Shop Online<br>and fill your cart</p></div><div class="partPayCalculatorWidgetDialogHowItWorksBody"><div><div class="nuumberingarea"><strong>2</strong></div></div><p>Choose Payflex at checkout</p></div><div class="partPayCalculatorWidgetDialogHowItWorksBody"><div><div class="nuumberingarea"><strong>3</strong></div></div><p>Get approved and <br> pay <span class="paypercentage">25% </span>today <br> with your debit <br> or credit card </p><div id="heavybasketnote" style="font-size:13px"></div></div><div class="partPayCalculatorWidgetDialogHowItWorksBody"><div><div class="nuumberingarea"><strong>4</strong></div></div><p>Pay the remainder <br> over 6-weeks.<br> No interest. <br> No fees.</p></div></div><br style="border-bottom: dotted 1px #CECFD1"><div class="partPayCalculatorWidgetDialogFooter"><div class="partPayCalculatorWidgetDialogFooterBody"><ul><li>You must be over<br>18 years old</li><li>You must have a valid<br>South African ID</li><li>You must have a debit or credit card<br>issued by Mastercard, Visa or Amex </li></ul></div><div class="partPayCalculatorWidgetDialogFooterLinks">Still want more information? <a href="http://www.payflex.co.za/#howitworks/" target="_blank">Click here</a></div></div></div></div></div></div>';
        var css = '@font-face{font-family:\'Montserrat\';font-style:normal;font-weight:400;src:local(\'Montserrat Regular\'),local(\'Montserrat-Regular\'),url(https://fonts.gstatic.com/s/montserrat/v13/JTUSjIg1_i6t8kCHKm459Wlhzg.ttf) format(\'truetype\')}@font-face{font-family:\'Montserrat\';font-style:normal;font-weight:500;src:local(\'Montserrat Medium\'),local(\'Montserrat-Medium\'),url(https://fonts.gstatic.com/s/montserrat/v13/JTURjIg1_i6t8kCHKm45_ZpC3gnD-w.ttf) format(\'truetype\')}@font-face{font-family:\'Montserrat\';font-style:normal;font-weight:700;src:local(\'Montserrat Bold\'),local(\'Montserrat-Bold\'),url(https://fonts.gstatic.com/s/montserrat/v13/JTURjIg1_i6t8kCHKm45_dJE3gnD-w.ttf) format(\'truetype\')}body.partPayWidgetDialogVisible{overflow:hidden}.partPayCalculatorWidgetDialogHeadingLogo{padding:10px}#partPayCalculatorWidget1{margin:0;padding:2px;width:380px;min-height:80px;background-color:#fff;color:#002751;cursor:pointer;text-transform:none;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;display:flex;align-items:center}.partPayCalculatorWidgetDialogHeadingLogo img{background-color:#c8a6fa;padding:10px;border-radius:100px}#partPayCalculatorWidget1 #freetext{font-weight:700;color:#002751}#partPayCalculatorWidget1 #partPayCalculatorWidgetLogo{height:30px;float:right;background-color:transparent;border-radius:20px;margin-left:20px}#partPayCalculatorWidget1 #partPayCalculatorWidgetText{font-size:.85rem}#partPayCalculatorWidget1 #partPayCalculatorWidgetText .partPayCalculatorWidgetTextFromCopy>span{font-weight:700}#partPayCalculatorWidget1 #partPayCalculatorWidgetText #partPayCalculatorWidgetLearn{text-decoration:underline;font-size:12px;font-style:normal;color:#0086ef}#partPayCalculatorWidget1 #partPayCalculatorWidgetText #partPayCalculatorWidgetSlogen{font-size:12px;font-style:normal}#partPayCalculatorWidgetDialog{box-sizing:border-box;z-index:999999;font-family:\'Arial\',\'Helvetica\';font-size:14px;display:none;color:#002751;position:fixed;bottom:0;left:0;right:0;top:0}#partPayCalculatorWidgetDialog *,#partPayCalculatorWidgetDialog :after,#partPayCalculatorWidgetDialog :before{box-sizing:inherit}.partPayCalculatorWidgetDialogOuter{background-color:rgba(0,0,0,.2);height:100%;left:0;position:absolute;text-align:center;top:0;vertical-align:middle;width:100%;z-index:999999;overflow-x:hidden;overflow-y:auto}.partPayCalculatorWidgetDialogInner{background-color:#fff;border:1px solid rgba(0,0,0,.2);-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5);max-width:900px;margin:30px auto;position:relative;font-family:Montserrat,sans-serif;-webkit-border-radius:30px;-moz-border-radius:30px;border-radius:30px}.partPayCalculatorWidgetDialogInner #partPayCalculatorWidgetDialogClose{position:absolute;margin-right:8px;margin-top:8px;cursor:pointer;max-height:28px;max-width:28px;right:0;top:0}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading{padding:50px 50px 24px;display:flex}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading .partPayCalculatorWidgetDialogHeadingLogo img{display:inline-block}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading .partPayCalculatorWidgetDialogHeadingTitle{font-size:32px;text-align:left;flex:1;margin-left:2rem;font-style:italic;color:#002751}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorksTitle{padding:20px 50px 0;font-size:28px;text-align:left}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorksDesc{padding:10px 50px 0;font-size:17px;text-align:left}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorks{display:flex;justify-content:space-between;padding:30px 50px 0}@media (max-width:320px){#partPayCalculatorWidget1{width:300px!important}#partPayCalculatorWidgetText{font-size:.8rem!important}}@media (max-width:768px){#partPayCalculatorWidget1{max-height:54px!important;min-height:40px!important;display:flex;justify-content:space-between;width:320px}#partPayCalculatorWidgetLogo{width:130px!important;height:30px!important;padding-bottom:0!important;float:left!important;top:0!important;margin-top:8px;margin-bottom:15px;border-radius:100px}#partPayCalculatorWidgetText{font-size:.85rem;clear:both;line-height:1.4}.partPayCalculatorWidgetDialogHeadingLogo{padding:0}.partPayCalculatorWidgetDialogHeadingTitle{margin-top:40px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorks{flex-direction:column}}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorks .partPayCalculatorWidgetDialogHowItWorksBody{flex:1;display:block;padding-top:20px}.nuumberingarea{margin:0 0 10px;padding:0;float:left;width:100%;text-align:center}.nuumberingarea strong{margin:0;padding:15px 0;width:100px;float:none;display:inline-block;border:none;border-radius:100%;font-size:50px;font-weight:700;color:#002751;background-color:#c8a6fa}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorks .partPayCalculatorWidgetDialogHowItWorksBody div img{max-width:120px;max-height:120px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHowItWorks .partPayCalculatorWidgetDialogHowItWorksBody p{display:block;font-size:15px;padding:5px 15px;color:#002751}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter{margin-top:20px;border-top:2px solid #002751;padding-bottom:25px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterTitle{width:100%;font-size:15px;font-weight:500;padding:10px 0 0 15px;text-align:left}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterBody{display:block;padding-top:20px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterBody>ul{padding:0;width:100%}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterBody>ul>li{display:inline-block;padding:0 34px 0 30px;margin-left:3px;margin-bottom:13px;text-align:left;list-style:none;background-repeat:no-repeat;background-image:url(https://widgets.payflex.co.za/assets/tick.png);background-position:left center;background-size:25px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterLinks{padding-top:10px;font-size:15px;font-style:italic;color:#002751}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterLinks a{text-decoration:underline;color:#002751}@media only screen and (max-width:915px){.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading{display:block}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading .partPayCalculatorWidgetDialogHeadingLogo{padding-top:0;width:100%}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading .partPayCalculatorWidgetDialogHeadingLogo img{max-width:100%}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogHeading .partPayCalculatorWidgetDialogHeadingTitle{margin-left:0;font-size:24px}}@media only screen and (max-width:710px){.partPayCalculatorWidgetDialogInner{max-width:350px}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter{display:block;width:100%}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterBody>ul{width:100%}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterBody>ul>li{display:block}.partPayCalculatorWidgetDialogInner .partPayCalculatorWidgetDialogFooter .partPayCalculatorWidgetDialogFooterLinks{padding-top:10px;font-size:10px}}';
    
        var $widget = $(html);
        $script.after($widget);
        $widget.prepend('<style type="text/css">' + css + '</style>')
    
        $widget.on('click', function(ev) {
            ev.preventDefault();
    
            var $body = $('body');
            var $dialog = $('#partPayCalculatorWidgetDialog').show();
            $body.addClass("partPayWidgetDialogVisible");
    
            var $button = $dialog
                .find("#partPayCalculatorWidgetDialogClose")
                .on('click', function(e) {
                    e.preventDefault();
                    $dialog.hide();
                    $body.removeClass("partPayWidgetDialogVisible");
    
                    // Put back on the widget.
                    $('#partPayCalculatorWidgetDialog').append($dialog);
                });
    
            // Move to the body element.
            $body.append($dialog);
            $body.animate({ scrollTop: 0 }, 'fast');
        });
        
        // Disable calculator if disabled state set.
        var disabled = + getParam($script.attr('src'), 'disabled');
    
        // Set the min and max range - defined by customer - not looked up
        var rangeMin = + getParam($script.attr('src'), 'min'),
            rangeMax = + getParam($script.attr('src'), 'max');
    	
        if(!(rangeMin && rangeMax) || rangeMin < 10 || rangeMax < 25 || rangeMax > 2000001 ) {
            rangeMin = 50;
            rangeMax = 20000;
        } else if( rangeMax < rangeMin ) {
            var x = rangeMax;
            rangeMax = rangeMin;
            rangeMin = x;
        }
        var amount = parseAmount(getParam($script.attr('src'), 'amount'));
        var installmentAmount = 'R' + getInstallmentAmount(amount);
        console.log(amount+'= amount');
        console.log(rangeMin+' = rangeMin');
        console.log(rangeMax+' = rangeMax');
        var html = '';
        if(amount > 10000){
            // if heavy basket
            html = '';
            $('.paypercentage').html('');
            $('#heavybasketnote').html('* Higher first payment may apply on large purchases');
            $('.heavyBasketText').html("Payflex lets you get what you need now, but pay for it over four interest-free instalments. "+
            "You pay a larger amount upfront with the remainder spread across three payments over the following six weeks.");
            installmentAmount = '';
            html = 'of <span id="installmentValue">' + installmentAmount + '</span>';
        }
        else if (disabled == 1) {
                html = 'of 25%';
        } else if(amount < rangeMin) {
            html = 'of 25% on orders over <br> <span id="installmentValue">R' + rangeMin+'</span>';
        } else if (amount > rangeMax) {
            html = 'of 25% on orders  <span id="installmentValue">R' + rangeMin + ' - R' + rangeMax +'</span>';
        }
        else {
            html = 'of <span id="installmentValue">' + installmentAmount + '</span>';
        }

        if(getParam($script.attr('src'), 'integration') =='multipleshopify') { 
            html = '';
        }
        console.log('html is here  '+ getParam($script.attr('src'), 'integration')   +html);
        $('.partPayCalculatorWidgetTextFromCopy').html(html);
        updateWidgetPrice();
    	}
    } 
    
    function parseAmount(value) {
        if(!value) {
            return 0;
        }
        value = value.replace('R', '');
        var amount = parseFloat(value).toFixed(2);
        
        if(isNaN(amount) || amount < 0) {
            return 0;
        }
        return amount;
    }
    
    function getInstallmentAmount(value) {

        value = + value;
        if(isNaN(value) || value < 0 ) {
            return 0;
        }
        var result = Math.floor(value * 100 / 4) / 100;
        return endsWithZeroCents(result) ? result.toFixed(0) : result.toFixed(2);
    }
    
    function endsWithZeroCents(value) {
        var fixed = value.toFixed(2);
        var endsWith = fixed.lastIndexOf(".00") != -1;
        return endsWith;
    }
    
    function getParam(url, name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
        return results && results.length > 1 ? results[1] : '';
    }
    var variants;
    function updateWidgetPrice(){   
        
        var url = window.location.search === "" || window.location.href.indexOf("?") === -1 ? window.location.href : window.location.href.split("?")[0];
        $.getJSON(url+'.json', function(data){
            let variantId = 0;
            variants = data.product.variants;
            // variantId = window.location.search.split("=")[1];
            const urlParams = new URLSearchParams(window.location.search);
            variantId = urlParams.get('variant');
            console.log(!variantId);
            if(window.location.search==='' || !variantId){
                variantId = data.product.variants[0].id;
            }

            var currentVariant = variants.filter(function (obj) { return obj.id == variantId});
            if(currentVariant[0].price > 10000){
                $('#installmentValue').html('');
            }else{
                $('#installmentValue').html('R'+getInstallmentAmount(currentVariant[0].price));
            }
         });
        
    }
    
    function eventadded(){
        
        var selection = document.querySelectorAll('select') !== null;
        var selection2 = document.querySelectorAll("input[type='radio") !== null;
        var selection3 = document.querySelectorAll(".product-option-item[data-option-type='button']") !== null;
        var selection4 = document.getElementsByTagName("a") !== null;
        var selection5 = document.getElementsByClassName("gf_swatch") !== null;

        var selection6 = document.getElementsByClassName("swatch-element") !== null;
        var selection7 = document.getElementsByClassName("Popover__Value") !== null;
        var selection8 = document.getElementsByClassName("options-selection__option-swatch") !== null;
        if(selection){
            document.querySelectorAll("select").forEach(box => {
                box.addEventListener("change", () => updateWidgetPrice())
            })
        }
        if(selection2){
            document.querySelectorAll("input[type='radio'").forEach(box => {
                box.addEventListener("change", () => updateWidgetPrice())
            })
        }
        if(selection3){ 
            document.querySelectorAll(".product-option-item[data-option-type='button']").forEach(box => 
                box.addEventListener("click", () => updateWidgetPrice())
            )
        }
        if(selection5){
            document.querySelectorAll(".gf_swatch").forEach(box => 
                box.addEventListener("click", () => updateWidgetPrice())
            )
        }

        if(selection6){
            document.querySelectorAll(".swatch-element").forEach(box => 
                box.addEventListener("click", () => updateWidgetPrice())
            )
        }
        if(selection7){
            document.querySelectorAll(".Popover__Value").forEach(box =>{
                box.addEventListener("click", () => {updateWidgetPrice()})
            })
        }
        if(selection8){
            document.querySelectorAll(".options-selection__option-swatch").forEach(box => 
                box.addEventListener("click", () => updateWidgetPrice())
            )
        }
        // for mobile
        document.addEventListener('touchstart', function(e){  
            var anchor = e.target.closest('a');     
            if(anchor !== null) {
                updateWidgetPrice();
            }
        });
        document.addEventListener('click', function(e){  
            var anchor = e.target.closest('a');     
            if(anchor !== null) {
                updateWidgetPrice();
            }
        });
    }
    function loadScript(url, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        if (script.readyState)
        {
            // IE.
            script.onreadystatechange = function() {
                if (script.readyState == 'loaded' || script.readyState == 'complete')
                {
                    script.onreadystatechange = null;
                    eventadded();
                    callback();
                }
            };
        } else {
            // Not IE.
            script.onload = function() {
                eventadded();
                callback();
            };
        }
    
        script.src = url;
        setTimeout(function(){ document.getElementsByTagName('head')[0].appendChild(script) }, 2000);    
    }
    
    	loadScript('https://partpayassets.blob.core.windows.net/widgets/ppQuery-3.2.1.js', function() {
		$ = ppQuery;
		var $script = $("script[src*='partpay-widget-']");
	    	
		//var type = getParam($script.attr('src'), 'type') || 'calculator';
		var type = 'calculator';
		var fn = eval(type);
		fn($script);
		$script.remove();
    	});
    
    })();