/**
 * Tool Tips
 *
 */


jQuery(document).ready(function ($) {


    (function ($) {
        "use strict";

        var $tooltips = jQuery('.tooltip'),
            $body = jQuery('body'),
            $window = jQuery(window),
            min_hover_width = 600;


        function show_tooltip($el) {
            //remove all prev classes

            if ($el.hasClass('opened')) {
                return;
            }

            $el.find('.tooltip-triangle').removeAttr('style');

            //whenever opening a new tool tip close the others
            jQuery('.tooltip.opened').each(function () {
                jQuery(this).data('tooltipLocked', false);
                hide_tooltip(jQuery(this));
            })



            var dist_left = $el.offset().left;
            var dist_right = $window.width() - ($el.offset().left + $el.width());
            $el.removeClass('left right');

            $el.addClass('opened');
            var $tooltipBubble = $el.find('.tooltip-popup-bubble');
            $tooltipBubble.removeAttr('css');




            if (min_hover_width) {

                var bubbleLeft = $tooltipBubble.offset().left;
                var bubbleRight = $tooltipBubble.offset().left + $tooltipBubble.width();

                if (bubbleLeft < 0) {
                    //bubble is off on the left
                    $el.addClass('left');

                    //recalc right
                    var offRight = $window.width() - ($tooltipBubble.offset().left + $tooltipBubble.width());

                    if (offRight < 0) {
                        $tooltipBubble.parent().css({left: offRight + 'px'});
                    }

                } else if (bubbleRight > $window.width()) {

                    //bubble if off on the right
                    $el.addClass('right');
                    bubbleLeft = $tooltipBubble.offset().left;

                    if (bubbleLeft < 0) {
                        $tooltipBubble.parent().css({right: parseInt(bubbleLeft) - 16 + 'px'});
                    }

                }
                //bubble is JUST right


            } else {

                if (dist_left < 250) {

                    $el.addClass('left');
                } else if (dist_right < 250) {
                    $el.addClass('right');
                }

            }


            $el.addClass('allowOverflow');

            //calculate the distance differnce between the  tooltip and the tip
            var hintWidth = $el.width();
            var tipWidth = $el.find('.tooltip-triangle').width();
            var tip_left = $el.find('.tooltip-triangle').offset().left;

            // get the distance diff
            var distanceDiff = Math.floor(dist_left - tip_left - ((tipWidth - hintWidth) / 2));


            $el.find('.tooltip-triangle').css({left: distanceDiff * 2 + 'px'});

            $body.on('click.outsideMenu touchstart.outsideMenu', function (e) {
                if (jQuery(e.target).closest($el).length == 0) {
                    //anytime its closed by clicking outside it should be unlocked
                    $el.data('tooltipLocked', false);
                    hide_tooltip($el);
                }
            });
        }

        function hide_tooltip($el) {

            //dont close it if it is locked
            if ($el.data('tooltipLocked')) {
                return;
            }


            //$el.find('.tooltip-popup-wrap').removeAttr('style');
            $el.removeClass('opened');
            $body.off('click.outsideMenu touchstart.outsideMenu');


            setTimeout(function () {

                if (!$el.hasClass('opened')) {
                    $el.removeClass('allowOverflow');
                    $el.find('.tooltip-triangle').removeAttr('style');
                }
            }, 500);
        }


        jQuery(document).on('focus.tooltip', '.tooltip', function (e) {
            //prevents the double event call from focus and click
            e.stopImmediatePropagation();

            show_tooltip(jQuery(this));
        });


        jQuery(document).on('mouseenter.tooltip', '.tooltip', function (e) {
            //forces tap/click on small screen sizes
            if ($window.width() <= min_hover_width) {
                return;
            }

            //prevents the double event call from focus and click
            e.stopImmediatePropagation();

            show_tooltip(jQuery(this));
        });

        jQuery(document).on('mousedown.tooltip', '.tooltip:not(.tooltip-button)', function (e) {

            // prevents the double event call from focus and click
            // using mouse down as click is mousedown + mouesup
            // does not prevent both from firing because only mousedown stops focus
            e.stopImmediatePropagation();

            var $this = jQuery(this);

            if (jQuery(e.target).closest('.tooltip-popup-bubble').length !== 0) {
                //bail if cliking inside of the popup
                return;
            } else if ($this.hasClass('opened') && $this.data('tooltipLocked') == false) {
                //tool tip is shown and it is not locked
                $this.data('tooltipLocked', true);
            } else if ($this.hasClass('opened')) {
                //tooltip is locked and open

                //unlock this
                $this.data('tooltipLocked', false);

                //turn it off
                hide_tooltip($this);

            } else {
                //lock it
                $this.data('tooltipLocked', true);
                //turn it on, duh
                show_tooltip($this);
            }


        });

        //when the mouse leaves hide it
        jQuery(document).on('mouseleave.tooltip', '.tooltip', function (e) {

            //forces tap/click on small screen sizes
            if ($window.width() <= min_hover_width) {
                return;
            }

            e.stopImmediatePropagation();
            hide_tooltip(jQuery(this));

        });

        jQuery(document).on('focusout.tooltip', '.tooltip', function (e) {
            e.stopImmediatePropagation();


            var $this = jQuery(this);
            var $currentTarget = jQuery(e.currentTarget);

            if (e.relatedTarget) {

                //this was likely a tab
                if (jQuery(e.relatedTarget).closest($this).length === 0) {
                    //if the related target is not the tooltip
                    hide_tooltip($this);
                }
            }
        });

    })(jQuery);
})


jQuery(document).ready(function ($) {
    function isBase64(str) {
        if (str === '' || str.trim() === '') {
            return false;
        }
        try {
            return btoa(atob(str)) == str;
        } catch (err) {
            return false;
        }
    }

    if ($(window).width() < 700) {
        $('.home-estimator').addClass('maybe-small')
    }

    $(window).on('resize', function () {
        if ($(this).width() < 670) {
            $('.home-estimator').addClass('maybe-small')
        } else {

        }
    });


    // set for each form
    $('.gh_calc').each(function () {

        var home_id = $(this).closest('.home-estimator').attr('data-home-id')

        if ($(this).length) {
            var conc_name = 'calcs_' + home_id
            window[conc_name] = JSON.parse($(this).attr('data-calc'))

        }
    })


    last_updated = $('#last_update').text()
    origin_website = $('#origin_website').text()
    title = $('#origin_title').text()

    // $('.gh_input').find('input').each(function () {
    //
    //     $(this).val(calcs[$(this).attr('id')])
    // })

    function pickTextColor(bgColor, lightColor = "#fff", darkColor = "#000") {
        var color = (bgColor.charAt(0) === '#') ? bgColor.substring(1, 7) : bgColor;
        var r = parseInt(color.substring(0, 2), 16); // hexToR
        var g = parseInt(color.substring(2, 4), 16); // hexToG
        var b = parseInt(color.substring(4, 6), 16); // hexToB
        return (((r * 0.299) + (g * 0.587) + (b * 0.114)) > 186) ?
            darkColor : lightColor;
    }

    $('.home-estimator h3').each(function () {
        var background = $(this).css('background')
        $(this).css('color', pickTextColor(background))
        $(this).find('span').css('color', pickTextColor(background))
    })

    $('.gh-subtotal-section *').each(function () {
        var background = $('.gh-subtotal-section').css('background')
        $(this).css('color', pickTextColor(background))
    })

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $('body').on('input', '.gh_input input', function () {

        calcs_id = $(this).closest('.home-estimator').attr('data-home-id')



        if (!$(this).val()) {
            window['calcs_' + calcs_id][$(this).attr('data-id')] = 0
            // $(this).find('input').val(0)
        } else {
            window['calcs_' + calcs_id][$(this).attr('data-id')] = $(this).val()
        }


        $(this).closest('.home-estimator').find('.gh-calc').each(function () {
            var id = $(this).attr('data-id')
            //  var formula = atob(calcs[id])
            var formula = atob($(this).attr('data-formula'))

            Object.keys(window['calcs_' + calcs_id]).forEach(key => {

                formula = formula.replace(key, window['calcs_' + calcs_id][key])

            })

            var stopwords = ['included']

            formula = formula.replace('=', '')


            if (!stopwords.includes(formula)) {
                var calculated_val = parseFloat(eval(formula))
                if (!isNaN(calculated_val)) {
                    $(this).find('input').val("$" + numberWithCommas(calculated_val.toFixed(2)))
                    window['calcs_' + calcs_id][id] = calculated_val.toFixed(2)
                }
            } else {
                var calculated_val = formula
                $(this).find('input').val(calculated_val)
                window['calcs_' + calcs_id][id] = calculated_val
            }


        })


        $('#user_input').val(JSON.stringify(window['calcs_' + calcs_id]))



    })

    $(document).ready(function () {
        $('.minus').click(function () {
            var $input = $(this).parent().find('input');
            var count = parseInt($input.val()) - 1;

            if (!count)
                count = 0

            count = count < 1 ? 0 : count;
            $input.val(count);
            $input.trigger('change').trigger('input');
            return false;
        });
        $('.plus').click(function () {
            var $input = $(this).parent().find('input');
            if (parseInt($input.val())) {
                $input.val(parseInt($input.val()) + 1);
            } else {
                $input.val(1)
            }

            $input.trigger('change').trigger('input');
            return false;
        });
    });

    $('.gh_input input').on('change keyup', function () {
        // Remove invalid characters
        var sanitized = $(this).val().replace(/[^0-9]/g, '');
        // Update value
        $(this).val(sanitized).trigger('input');

    });

    $('.estimator-form').on('keyup keypress', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            return false;
        }
    });

    function dfp() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        source = $('.home-estimator')[0]

        style = ""
        specialElementHandlers = {

            '.bypassme': function (element, renderer) {

                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };

        pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, { // y coord
                'width': margins.width, // max width of content on PDF
                'elementHandlers': specialElementHandlers
            },

            function (dispose) {
                // dispose: object with X, Y of the last line add to the PDF
                //          this allow the insertion of new lines after html
                pdf.save('plan.pdf');
            }, margins
        );
    }


    $('.sub-dpf').click(function () {
        var init = $(this).html()
        $(this).html(' <i class="fa fa-spinner fa-spin"></i>Saving')
        var element = $(this).closest('.home-estimator').clone()[0];

        last_updated = $(element).find('.last_update').text()
        origin_website = $(element).find('.origin_website').text()
        title = $(element).find('.origin_title').text()

        disclaimer = $(element).find('.sub-disclaimer .tooltip-popup-text').text()

        $(element).append('<div style=" margin: auto;  margin-top:100px;  max-width: 600px; clear: both; background: #fff !important;  " class="pdf-disclaimer"><h3>Disclaimer:</h3><p style="font-size: 10px; font-weight: 900">' + disclaimer + '</p></div>')

        $(element).css('width', '920px')
        $(element).removeClass('maybe-small')


        $(element).accordion({active: false})
        $(element).find(".ui-accordion-content").show();
        $(element).find("h3 i").remove();
        $(element).find("input").css('border', 'none')
        $(element).find("#reset_button").remove()


        $(element).css('width', '185mm').find('.subtotal-buttons').remove()
        $(element).find('.admin-save').remove()
        $(element).find('.tooltip').remove()
        $(element).find('.minus').remove()
        $(element).find('.plus').remove()
        $(element).find('.ui-accordion-header-icon').remove()

        $(element).find('textarea').each(function () {
            $(this).replaceWith($('<div style="padding:20px; " class="pdf-notes"><h2>Notes:</h2><p>' + $(this).val() + '</p></div>'));
        })

        $(element).find('.extra-notes').show()


        // var ss = $(element).find('form').clone()

        // element = ss

        //$(element  ).find('*').css('background-color', 'unset !important')

        $(element).find('.estimator-form').removeAttr('class').addClass('estimator-form')

        // $('body').append(element)

        if (!title)
            title = "Custom plan"
        var opt = {
            margin: 13,
            filename: title,
            image: {type: 'png', quality: 0.98},
            html2canvas: {scale: 1, y: 0, scrollY: 0},
            jsPDF: {format: 'A4'},
            pagebreak: {avoid: ['table', '.estimator-section', '.pdf-disclaimer', '.pdf-notes']}
        };


        html2pdf().from(element).set(opt).toPdf().get('pdf').then(function (pdf) {
            var totalPages = pdf.internal.getNumberOfPages();
            //print current pdf width & height to console

            for (var i = 1; i <= totalPages; i++) {
                pdf.setPage(i);
                pdf.setFontSize(10);
                pdf.setTextColor(150);
                //divided by 2 to go center
                pdf.text('Page ' + i + ' of ' + totalPages + '      ' + title + '   Qty. Last Update: ' + last_updated + '     ' + origin_website, 10, 10);
            }
            window.open(pdf.output('bloburl'), '_blank');
        }).save().then((val) => {
            $('.sub-dpf').html('Print PDF')
        });

    })

    $('.sub-notes').click(function () {
        $('body').find('.extra-notes').addClass('showup').slideDown();
    })


    $('.estimator-table input').trigger('input')

    // jQuery(function($) {$(function() {
    //     $(".estimator-section  tr").hide();
    //
    //
    //     $(".estimator-section ").click(function(){
    //         $(this).find("tr").each(function() {
    //             $(this).show()
    //         })
    //     }) }) })

// accordion

    $(function () {

        $(".home-estimator").accordion({
            header: "h3",
            heightStyle: "content",
            collapsible: true,
            active: true,
            speed: 'slow',
            clearStyle: true,
            icons: false


        });
        $('.home-estimator').find('h3').first().click()

        // $('.estimator-section').each(function(n, el) {
        //     $(el).accordion({
        //              header: "h3",
        //              heightStyle: "content",
        //              collapsible: true,
        //              active: true,
        //
        //
        //          });
        //
        //     $(el).find('h3').addClass('toogle-section')
        //
        //
        // })
    })

    $(".estimator-section h3").click(function () {
        $(this)
            .children("i")
            .toggleClass("fa-plus-circle fa-minus-circle");
        $(".ui-accordion-header")
            .not($(this))
            .children("i")
            .removeClass("fa-minus-circle");
        $(".ui-accordion-header")
            .not($(this))
            .children("i")
            .addClass("fa-plus-circle");
    });


    $('#reset_button').click(function () {
        setTimeout(function () {
            $('.gh_input input').trigger('input')
        }, 500)
    })

    // check if custom plan

    let new_plan = "Custom plan"
    let today = new Date();
    let month = today.getMonth() + 1; // getMonth() returns 0-based index
    let day = today.getDate();
    let year = today.getFullYear();
    let currentDate = `${month}/${day}/${year}`;

    $('.sub-price-range').each(function () {
        var ori_price = $(this).find('input').first().val()


        var ori_title = $(this).closest('.ready-to-go-plan').find('.origin_title').text()
        var ori_date = $(this).closest('.ready-to-go-plan').find('.last_update').text()

        $(this).closest('.ready-to-go-plan').attr('data-oriprice', ori_price)
        $(this).closest('.ready-to-go-plan').attr('data-orititle', ori_title)
        $(this).closest('.ready-to-go-plan').attr('data-oridate', ori_date)
    })

    $('body').on('input', '.gh_input input', function () {

        var orit = $(this).closest('.ready-to-go-plan').attr('data-orititle')
        var orip = $(this).closest('.ready-to-go-plan').attr('data-oriprice')
        var orid = $(this).closest('.ready-to-go-plan').attr('data-oridate')


        var current_price = $(this).closest('.ready-to-go-plan').find('.sub-price-range').find('input').first().val()

        if (current_price != orip) {
            $(this).closest('.ready-to-go-plan').find('.origin_title').text(new_plan)
            $(this).closest('.ready-to-go-plan').find('.last_update').text(currentDate)
        } else {
            $(this).closest('.ready-to-go-plan').find('.origin_title').text(orit)
            $(this).closest('.ready-to-go-plan').find('.last_update').text(orid)
        }


    })


}) // jQuery


