Before After
var actionDirection = ''; var actionDirection = '';
   
var autoTimeout; var autoTimeout;
var quiz; var quiz;
var resumePage = ''; var resumePage = '';
var resumeURL = ''; var resumeURL = '';
var resumeReq = ''; var resumeReq = '';
   
var productDetails = []; var productDetails = [];
   
var tempStorageName = 'quiz'; var tempStorageName = 'quiz';
   
var customerStorage = 'customer'; var customerStorage = 'customer';
   
var pageHandle = ''; var pageHandle = '';
   
var useragent = navigator.userAgent; var useragent = navigator.userAgent;
   
function deviceOS() { function deviceOS() {
   if(useragent.match(/Android/i)) {    if(useragent.match(/Android/i)) {
       return 'android';        return 'android';
   } else if(useragent.match(/iPhone/i)) {    } else if(useragent.match(/iPhone/i)) {
       return 'iphone';        return 'iphone';
   } else if(useragent.match(/iPod/i)) {    } else if(useragent.match(/iPod/i)) {
       return 'ipod';        return 'ipod';
   } else if(useragent.match(/iPad/i)) {    } else if(useragent.match(/iPad/i)) {
       return 'ipad';        return 'ipad';
   } else if(useragent.match(/Windows Phone/i)) {    } else if(useragent.match(/Windows Phone/i)) {
       return 'windows phone';        return 'windows phone';
   } else {    } else {
       return 'no-device';        return 'no-device';
   }    }
} }
   
function setRightInputKeyboard() { function setRightInputKeyboard() {
   var input = document.getElementsByTagName('input');    var input = document.getElementsByTagName('input');
   if(deviceOS() === 'iphone' || deviceOS() === 'ipod' || deviceOS() === 'ipad') {    if(deviceOS() === 'iphone' || deviceOS() === 'ipod' || deviceOS() === 'ipad') {
       console.log('deviceOS: ', deviceOS());        console.log('deviceOS: ', deviceOS());
       for(var i in input){        for(var i in input){
           if(input[i].type === 'number'){            if(input[i].type === 'number'){
               input[i].type = 'tel';                input[i].type = 'tel';
               console.log(input[i], 'Changed to tel');                console.log(input[i], 'Changed to tel');
           }            }
       }        }
   } else if(deviceOS() === 'android') {    } else if(deviceOS() === 'android') {
       if(useragent.match(/Android 4.1.2/i)) {        if(useragent.match(/Android 4.1.2/i)) {
           for(var i in input){            for(var i in input){
               if(input[i].type === 'number'){                if(input[i].type === 'number'){
                   input[i].type = 'tel';                    input[i].type = 'tel';
                   console.log(input[i], 'Changed to number');                    console.log(input[i], 'Changed to number');
               }                }
           }            }
       }        }
   }    }
} }
   
$(document).ready(function () { $(document).ready(function () {
   
   $('.quiz-wrapper').on('keyup','.question__responses input', function(e){    $('.quiz-wrapper').on('keyup','.question__responses input', function(e){
   
       var inputType = $(this).attr('type');        var inputType = $(this).attr('type');
   
       if( inputType == 'text' || inputType == 'number' || inputType == 'tel'){        if( inputType == 'text' || inputType == 'number' || inputType == 'tel'){
   
           var minLength = $(this).attr('minlength');            var minLength = $(this).attr('minlength');
           char = $(this).val().trim();            char = $(this).val().trim();
           removeLeadingZeros = char.replace(/^0+\s/g, '');            removeLeadingZeros = char.replace(/^0+\s/g, '');
           charLength = removeLeadingZeros.length;            charLength = removeLeadingZeros.length;
           $parent = $(this).closest('.question__responses');            $parent = $(this).closest('.question__responses');
           var inputName = $(this).attr('name');            var inputName = $(this).attr('name');
   
           if((inputName.trim().toLowerCase()) !== 'age'){            if((inputName.trim().toLowerCase()) !== 'age'){
   
               if(charLength < minLength){                if(charLength < minLength){
                   $parent.removeClass('valid');                    $parent.removeClass('valid');
               }else{                }else{
                   $parent.addClass('valid');                    $parent.addClass('valid');
               }                }
           }            }
   
           // Age validation on keyup event.            // Age validation on keyup event.
           if((inputName.trim().toLowerCase()) == 'age'){            if((inputName.trim().toLowerCase()) == 'age'){
   
   
               removeLeadingZeros = removeLeadingZeros.replace(/\D/g,'');                removeLeadingZeros = removeLeadingZeros.replace(/\D/g,'');
   
               // alert(removeLeadingZeros);                // alert(removeLeadingZeros);
               $(this).attr('value',removeLeadingZeros);                $(this).attr('value',removeLeadingZeros);
   
               // alert(removeLeadingZeros);                // alert(removeLeadingZeros);
               char = $(this).val().trim();                char = $(this).val().trim();
   
               if(char >= 18 && char <= 99) {                if(char >= 18 && char <= 99) {
                   $parent.addClass('valid');                    $parent.addClass('valid');
               }else{                }else{
                   $parent.removeClass('valid');                    $parent.removeClass('valid');
               }                }
   
               var regex = /^\d+$/;                var regex = /^\d+$/;
               if( !regex.test(char) ) {                if( !regex.test(char) ) {
                   $parent.removeClass('valid');                    $parent.removeClass('valid');
               }else{                }else{
                   if($("#age-error").size() >= 0 ) {                    if($("#age-error").size() >= 0 ) {
                       $("#age-error").remove();                        $("#age-error").remove();
                   }                    }
               }                }
   
           }            }
   
           if((inputName.trim().toLowerCase()) == 'name'){            if((inputName.trim().toLowerCase()) == 'name'){
   
               if(char.length > 30 || char.length < 2){                if(char.length > 30 || char.length < 2){
                   $parent.removeClass('valid');                    $parent.removeClass('valid');
               }                }
   
           }            }
   
           // Zip validation on keyup.            // Zip validation on keyup.
           if(inputName.trim().toLowerCase() == 'environmentzipcode')            if(inputName.trim().toLowerCase() == 'environmentzipcode')
           {            {
               removeLeadingZeros = removeLeadingZeros.replace(/\D/g,'');                removeLeadingZeros = removeLeadingZeros.replace(/\D/g,'');
   
               // alert(removeLeadingZeros);                // alert(removeLeadingZeros);
               $(this).attr('value',removeLeadingZeros);                $(this).attr('value',removeLeadingZeros);
   
               // alert(removeLeadingZeros);                // alert(removeLeadingZeros);
               char = $(this).val().trim();                char = $(this).val().trim();
   
               var form = $(".validateForm");                var form = $(".validateForm");
               var zipValidate = ValidateZip(char);                var zipValidate = ValidateZip(char);
   
               if(zipValidate == true){                if(zipValidate == true){
                   $parent.addClass('valid');                    $parent.addClass('valid');
                   $('#Zip-error').hide();                    $('#Zip-error').hide();
               } else{                } else{
                   $parent.removeClass('valid');                    $parent.removeClass('valid');
               }                }
   
           }            }
       }        }
   
   });    });
   
   $('.quiz-wrapper').on('keyup','.question__responses input[type="email"]', function(){    $('.quiz-wrapper').on('keyup','.question__responses input[type="email"]', function(){
       var value = $(this).val();        var value = $(this).val();
       var validResult = ValidateEmail(value);        var validResult = ValidateEmail(value);
       $parent = $(this).closest('.question__responses');        $parent = $(this).closest('.question__responses');
   
       if(validResult == true)        if(validResult == true)
       {        {
           $parent.addClass('valid');            $parent.addClass('valid');
           $('#Email-error').hide();            $('#Email-error').hide();
       }        }
       else        else
       {        {
           $parent.removeClass('valid');            $parent.removeClass('valid');
           $('#Email-error').show();            $('#Email-error').show();
       }        }
   
   });    });
   
   $('.quiz-wrapper').on('submit', '.validateForm', function () {    $('.quiz-wrapper').on('submit', '.validateForm', function () {
       return false;        return false;
   });    });
   
   $('.quiz-wrapper').on('click', '.quizReset', function () {    $('.quiz-wrapper').on('click', '.quizReset', function () {
       window.localStorage.removeItem('quiz');        window.localStorage.removeItem('quiz');
       window.location.href = $(this).attr('href');        window.location.href = $(this).attr('href');
       return false        return false
   
   });    });
   
   $('.quiz-wrapper').keypress(function(event) {    $('.quiz-wrapper').keypress(function(event) {
       setTimeout(function () {        setTimeout(function () {
           if(pageHandle == 'food-eating-diet'){            if(pageHandle == 'food-eating-diet'){
               //$('#dialog-form').find('.btn-other-submit').trigger('click');                //$('#dialog-form').find('.btn-other-submit').trigger('click');
           } else {            } else {
               if (event.keyCode == 13 || event.which == 13) {                if (event.keyCode == 13 || event.which == 13) {
                   event.preventDefault();                    event.preventDefault();
                   $('.quiz-wrapper').find('[data-action]:visible').trigger('click');                    $('.quiz-wrapper').find('[data-action]:visible').trigger('click');
               }                }
           }            }
   
         },250);          },250);
   });    });
   
   // trigger all data action submit    // trigger all data action submit
   $('.quiz-wrapper').on('click', '[data-action]', function (event) {    $('.quiz-wrapper').on('click', '[data-action]', function (event) {
       //console.log('4');        //console.log('4');
       event.preventDefault();        event.preventDefault();
       //if the event triggered from logic elements        //if the event triggered from logic elements
       var isLogicTrigger = $(this).data('logic');        var isLogicTrigger = $(this).data('logic');
   
       $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected');        $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected');
   
       // get next question url        // get next question url
       var loadUrl = triggerSubmit($(this),event,isLogicTrigger);        var loadUrl = triggerSubmit($(this),event,isLogicTrigger);
   
       //if trigger is from logic elements apply logic        //if trigger is from logic elements apply logic
       if(loadUrl == undefined && !isLogicTrigger) {        if(loadUrl == undefined && !isLogicTrigger) {
           applyLogic();            applyLogic();
       }        }
   
       //load next question        //load next question
       if(loadUrl) {        if(loadUrl) {
           loadQuiz(actionDirection, loadUrl, true);            loadQuiz(actionDirection, loadUrl, true);
       }        }
   });    });
   
   var applyLogic = function() {    var applyLogic = function() {
       if($('.quizLogic').size() > 0) {        if($('.quizLogic').size() > 0) {
           if($('.skipSubmitField').size() > 0){            if($('.skipSubmitField').size() > 0){
               renderLocalStorage();                renderLocalStorage();
               skipSubmitField(null);                skipSubmitField(null);
           } else {            } else {
               renderLocalStorage();                renderLocalStorage();
               logicalAutoAdvance();                logicalAutoAdvance();
           }            }
       }        }
   }    }
   
   function logicalAutoAdvance() {    function logicalAutoAdvance() {
       var logicDiv = $('.quizLogic');        var logicDiv = $('.quizLogic');
   
       if ($(logicDiv).find('[data-logic]').size() > 1) {        if ($(logicDiv).find('[data-logic]').size() > 1) {
               $('div[storage-field]:visible > [data-logic]').trigger('click');                $('div[storage-field]:visible > [data-logic]').trigger('click');
       } else {        } else {
           $(logicDiv).find('div:visible [data-logic]').trigger('click');            $(logicDiv).find('div:visible [data-logic]').trigger('click');
       }        }
   }    }
   
   // for open vegan modal    // for open vegan modal
   $('.quiz-wrapper').on('click', '.exit-quiz-diet', function (event) {    $('.quiz-wrapper').on('click', '.exit-quiz-diet', function (event) {
       if(pageHandle == 'food-eating-diet'){        if(pageHandle == 'food-eating-diet'){
           event.preventDefault();            event.preventDefault();
           //console.log($(this).find('input').val(),'--------------');            //console.log($(this).find('input').val(),'--------------');
           openVeganModal($(this));            openVeganModal($(this));
       }        }
   });    });
   
   // for open surgery modal    // for open surgery modal
   $('.quiz-wrapper').on('click', '.exit-quiz', function (event) {    $('.quiz-wrapper').on('click', '.exit-quiz', function (event) {
       if(pageHandle == 'basic-profile-surgery'){        if(pageHandle == 'basic-profile-surgery'){
           event.preventDefault();            event.preventDefault();
           openSurgeryModal($(this));            openSurgeryModal($(this));
       }        }
   });    });
   
   // open other diet modal    // open other diet modal
   $('.quiz-wrapper').on('click', '.other-diet-open', function (event) {    $('.quiz-wrapper').on('click', '.other-diet-open', function (event) {
       if(pageHandle == 'food-eating-diet'){        if(pageHandle == 'food-eating-diet'){
           event.preventDefault();            event.preventDefault();
           openDietModal();            openDietModal();
       }        }
   });    });
   
   // conditional show hide    // conditional show hide
   $('.quiz-wrapper').on('change', '.conditional input[type="radio"]', function () {    $('.quiz-wrapper').on('change', '.conditional input[type="radio"]', function () {
       var xName = $(this).attr('name');        var xName = $(this).attr('name');
       var xVal = $('.conditional input[type="radio"]:checked').val();        var xVal = $('.conditional input[type="radio"]:checked').val();
   
       $('[conditional-name][conditional-value]').hide();        $('[conditional-name][conditional-value]').hide();
       $('[conditional-name="' + xName + '"][conditional-value="' + xVal + '"]').show();        $('[conditional-name="' + xName + '"][conditional-value="' + xVal + '"]').show();
       if ($('.conditional input[type="radio"][submit-trigger="true"]:checked')) {        if ($('.conditional input[type="radio"][submit-trigger="true"]:checked')) {
           var submitVal = $('.conditional input[type="radio"][submit-trigger="true"]:checked').attr('submit-value');            var submitVal = $('.conditional input[type="radio"][submit-trigger="true"]:checked').attr('submit-value');
   
           if (submitVal != undefined) {            if (submitVal != undefined) {
               $('[conditional-name="' + xName + '"] input[value="' + submitVal + '"]').prop('checked', true);                $('[conditional-name="' + xName + '"] input[value="' + submitVal + '"]').prop('checked', true);
               $('[data-submit="true"]').trigger('click');                $('[data-submit="true"]').trigger('click');
           } else {            } else {
               $('[conditional-name="' + xName + '"][conditional-value="' + xVal + '"] input').prop('checked', false);                $('[conditional-name="' + xName + '"][conditional-value="' + xVal + '"] input').prop('checked', false);
           }            }
       }        }
   });    });
   
   // auto submit radio on change    // auto submit radio on change
   
   $('.quiz-wrapper').on('change', 'input[data-storage][type="radio"]', function () {    $('.quiz-wrapper').on('change', 'input[data-storage][type="radio"]', function () {
       //console.log("auto submit radio on change");        //console.log("auto submit radio on change");
       if($('.quizLogic').size() <= 0){        if($('.quizLogic').size() <= 0){
           $('.quiz__content-box, .quiz__content-box--pill').removeClass('selected');            $('.quiz__content-box, .quiz__content-box--pill').removeClass('selected');
           if ($('button[data-submit="true"]').size() > 1) {            if ($('button[data-submit="true"]').size() > 1) {
               $('[storage-field]:visible > button[data-submit="true"]').trigger('click');                $('[storage-field]:visible > button[data-submit="true"]').trigger('click');
               $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected'); //add class selected for q:diabetes-blood-sugar                $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected'); //add class selected for q:diabetes-blood-sugar
           } else {            } else {
               $(this).closest('.quizSectionInner').find('button[data-submit="true"]').trigger('click');                $(this).closest('.quizSectionInner').find('button[data-submit="true"]').trigger('click');
               $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected');                $(this).closest('.quiz__content-box, .quiz__content-box--pill').addClass('selected');
           }            }
       }        }
   
   });    });
   
   $('.quiz-wrapper').on('change', '.multiselect-component.checkbox input[data-storage]', function () {    $('.quiz-wrapper').on('change', '.multiselect-component.checkbox input[data-storage]', function () {
       var xMin = parseInt($(this).closest('.multiselect-component').attr('select-min'));        var xMin = parseInt($(this).closest('.multiselect-component').attr('select-min'));
       var xMax = parseInt($(this).closest('.multiselect-component').attr('select-max')) + 1;        var xMax = parseInt($(this).closest('.multiselect-component').attr('select-max')) + 1;
       var len = $(".multiselect-component.checkbox input:checked").length;        var len = $(".multiselect-component.checkbox input:checked").length;
   
       if (len >= xMin) {        if (len >= xMin) {
           if (len >= xMax) {            if (len >= xMax) {
               $('.selectIndicator').text('Max number of items selected');                $('.selectIndicator').text('Max number of items selected');
               $('.selectIndicator').show();                $('.selectIndicator').show();
           } else {            } else {
               $('.selectIndicator').text('If your selections look good, please proceed.')                $('.selectIndicator').text('If your selections look good, please proceed.')
               $('.selectIndicator').hide();                $('.selectIndicator').hide();
           }            }
           $('.multiselect-component.checkbox [data-submit="true"]').removeAttr('disabled');            $('.multiselect-component.checkbox [data-submit="true"]').removeAttr('disabled');
           $('.multiselect-component.checkbox [data-submit="true"]').show();            $('.multiselect-component.checkbox [data-submit="true"]').show();
       } else {        } else {
           var remainder = xMin - len;            var remainder = xMin - len;
           $('.selectIndicator').text('Please select ' + remainder + ' more').show();            $('.selectIndicator').text('Please select ' + remainder + ' more').show();
           $('.multiselect-component.checkbox [data-submit="true"]').attr('disabled', 'disabled');            $('.multiselect-component.checkbox [data-submit="true"]').attr('disabled', 'disabled');
           $('.multiselect-component.checkbox [data-submit="true"]').hide();            $('.multiselect-component.checkbox [data-submit="true"]').hide();
       }        }
       $(this).closest('.quiz__content-box, .quiz__content-box--pill').toggleClass('selected');        $(this).closest('.quiz__content-box, .quiz__content-box--pill').toggleClass('selected');
   
       if (len >= xMax) {        if (len >= xMax) {
           $(this).prop('checked', false);            $(this).prop('checked', false);
           $(this).closest('.quiz__content-box, .quiz__content-box--pill').removeClass('selected');            $(this).closest('.quiz__content-box, .quiz__content-box--pill').removeClass('selected');
       }        }
       // do not select NONE on with other questions        // do not select NONE on with other questions
       callOptionChanges($(this))        callOptionChanges($(this))
   });    });
   
   
   // Scroll to bottom    // Scroll to bottom
   $('.quiz-wrapper').on('change', '.multiselect-component.checkbox input[data-storage]', function (e) {    $('.quiz-wrapper').on('change', '.multiselect-component.checkbox input[data-storage]', function (e) {
   
       if($(window).width() < 1200 ){        if($(window).width() < 1200 ){
           if(pageHandle == "dr-directed-deficiencies" || pageHandle == "specific-interests"            if(pageHandle == "dr-directed-deficiencies" || pageHandle == "specific-interests"
           || pageHandle == "food-eating-habits-allergy" || pageHandle == "hobbies"){            || pageHandle == "food-eating-habits-allergy" || pageHandle == "hobbies"){
   
               var selLen = $(".multiselect-component.checkbox input:checked").length;                var selLen = $(".multiselect-component.checkbox input:checked").length;
               var selectMin = $(".multiselect-component").attr('select-min');                var selectMin = $(".multiselect-component").attr('select-min');
   
               if(selLen == selectMin){                if(selLen == selectMin){
   
                   var tempHeight = $('.btn-cta--light').offset().top;                    var tempHeight = $('.btn-cta--light').offset().top;
                   $('.quizSectionWrap').animate({                    $('.quizSectionWrap').animate({
                       scrollTop:  tempHeight+150                        scrollTop:  tempHeight+150
                   },'slow');                    },'slow');
   
               }                }
   
           }            }
       }        }
   });    });
   
   
   $('.quiz-wrapper').on('click', '.button_survey_back', function () {    $('.quiz-wrapper').on('click', '.button_survey_back', function () {
       window.history.go(-1);        window.history.go(-1);
   });    });
   
   
   var winSearch = window.location.search;    var winSearch = window.location.search;
   if($('.hero__btn').size() > 0) {    if($('.hero__btn').size() > 0) {
   
       $('.hero__btn').each(function(i, obj) {        $('.hero__btn').each(function(i, obj) {
           var buttonText = $(obj).text().trim().toLowerCase().split(' ').join('-');            var buttonText = $(obj).text().trim().toLowerCase().split(' ').join('-');
           if( buttonText.trim() == "get-started") {            if( buttonText.trim() == "get-started") {
               if (JSON.parse(localStorage.getItem(tempStorageName)) !== null) {                if (JSON.parse(localStorage.getItem(tempStorageName)) !== null) {
                   quiz = JSON.parse(localStorage.getItem(tempStorageName));                    quiz = JSON.parse(localStorage.getItem(tempStorageName));
   
                   // check for an incomplete existing quiz                    // check for an incomplete existing quiz
                   var quizExist = false;                    var quizExist = false;
                   var incompleted = false;                    var incompleted = false;
                   $.each(quiz, function (key, value) {                    $.each(quiz, function (key, value) {
                       if (value.split('||').length > 1 && value.split('||')[0] != "") {                        if (value.split('||').length > 1 && value.split('||')[0] != "") {
                           quizExist = true;                            quizExist = true;
                       } else if(value.split('||').length > 1 && value.split('||')[0] == ""){                        } else if(value.split('||').length > 1 && value.split('||')[0] == ""){
                           incompleted = true;                            incompleted = true;
                       }                        }
                   });                    });
   
                   if (quizExist && incompleted) {                    if (quizExist && incompleted) {
                       $('.hero__btn').text('Resume Quiz');                        $('.hero__btn').text('Resume Quiz');
                   }                    }
               }                }
           }            }
       });        });
   
   } else if($('.quiz-wrapper').size() > 0 && $('.quiz-calculation').size() == 0 ){    } else if($('.quiz-wrapper').size() > 0 && $('.quiz-calculation').size() == 0 ){
   
       if (JSON.parse(localStorage.getItem(tempStorageName)) === null) {        if (JSON.parse(localStorage.getItem(tempStorageName)) === null) {
   
           $('body').addClass('quizLoaded');            $('body').addClass('quizLoaded');
   
           var uID = uniqueID();            var uID = uniqueID();
           var quizData = "{{ settings.quiz_data | strip | strip_newlines }}";            var quizData = "{{ settings.quiz_data | strip | strip_newlines }}";
           {% assign quizDatas = settings.quiz_data | split: "," %}            {% assign quizDatas = settings.quiz_data | split: "," %}
           quiz = {            quiz = {
               "uniqueID": uID,                "uniqueID": uID,
               {% for quizData in quizDatas %}                {% for quizData in quizDatas %}
               "{{ quizData | split: ':' | first | strip | strip_newlines }}": "||{{ quizData | split: ':' | last | strip_newlines }}"{% if forloop.last == true %}{% else %},{% endif %}                "{{ quizData | split: ':' | first | strip | strip_newlines }}": "||{{ quizData | split: ':' | last | strip_newlines }}"{% if forloop.last == true %}{% else %},{% endif %}
               {% endfor %}                {% endfor %}
           };            };
           setCustomerJSONNode();            setCustomerJSONNode();
           localStorage.setItem(tempStorageName, JSON.stringify(quiz));            localStorage.setItem(tempStorageName, JSON.stringify(quiz));
           autoAdvance();            autoAdvance();
       } else {        } else {
           quiz = JSON.parse(localStorage.getItem(tempStorageName));            quiz = JSON.parse(localStorage.getItem(tempStorageName));
   
           var xKey = 'uniqueID';            var xKey = 'uniqueID';
           var getUID = JSON.parse(localStorage.getItem(tempStorageName))[xKey];            var getUID = JSON.parse(localStorage.getItem(tempStorageName))[xKey];
   
           // check for last blank entry in localstorage            // check for last blank entry in localstorage
           $.each(quiz, function (key, value) {            $.each(quiz, function (key, value) {
               if (value.split('||')[0] != '') {                if (value.split('||')[0] != '') {
   
               } else {                } else {
                   resumePage = value.split('||')[1];                    resumePage = value.split('||')[1];
                   resumeURL = '?page=' + resumePage;                    resumeURL = '?page=' + resumePage;
                   resumeReq = '/pages/' + resumePage;                    resumeReq = '/pages/' + resumePage;
                   return false;                    return false;
               }                }
           });            });
           //alert(resumePage);            //alert(resumePage);
           if (resumePage === undefined || resumePage === "close") {            if (resumePage === undefined || resumePage === "close") {
               //initial visit do nothing                //initial visit do nothing
               if (winSearch != '') {                if (winSearch != '') {
                   var xUrl = '/pages/' + param('page');                    var xUrl = '/pages/' + param('page');
                   var xPID = param('page');                    var xPID = param('page');
                   $('body').addClass('quizLoading');                    $('body').addClass('quizLoading');
                   $('.quizSection').html('');                    $('.quizSection').html('');
                   $('.quizSection').load(xUrl + ' .quizSectionInner', function () {                    $('.quizSection').load(xUrl + ' .quizSectionInner', function () {
                       $(this).attr('data-pid', xPID);                        $(this).attr('data-pid', xPID);
                       $('body').removeClass('quizLoading');                        $('body').removeClass('quizLoading');
                       renderLocalStorage();                        renderLocalStorage();
                       autoAdvance();                        autoAdvance();
                   });                    });
               } else {                } else {
                   autoAdvance();                    autoAdvance();
               }                }
           } else {            } else {
               var resumeAction = true;                var resumeAction = true;
               var txt;                var txt;
               if(resumePage === "name" || resumePage == "") {                if(resumePage === "name" || resumePage == "") {
                   resumeAction = false;                    resumeAction = false;
                   //console.log('-------Start action 1');                    //console.log('-------Start action 1');
                   startAction(resumeAction, resumePage);                    startAction(resumeAction, resumePage);
   
               } else {                } else {
                   var msg = 'Would You Like To Resume The Quiz Where You Left Off?';                    var msg = 'Would You Like To Resume The Quiz Where You Left Off?';
                   openModal(msg, resumeAction, resumePage);                    openModal(msg, resumeAction, resumePage);
               }                }
   
           }            }
       }        }
   }    }
   
}); });
   
window.onpopstate = function (event, state) { window.onpopstate = function (event, state) {
   //console.log('9');    //console.log('9');
   //console.log(event);    //console.log(event);
   if (event.state === undefined || event.state === null) {    if (event.state === undefined || event.state === null) {
       loadQuiz('left', window.location.pathname.replace('/pages/', ''), false);        loadQuiz('left', window.location.pathname.replace('/pages/', ''), false);
   }    }
   var popEvent = JSON.stringify(event.state);    var popEvent = JSON.stringify(event.state);
   var eventURL = event.state.page.split('?page=')[1];    var eventURL = event.state.page.split('?page=')[1];
   
   var loadUrl = '/pages/' + eventURL;    var loadUrl = '/pages/' + eventURL;
   //console.log('popstate:'+eventURL);    //console.log('popstate:'+eventURL);
   loadQuiz('left', loadUrl, false);    loadQuiz('left', loadUrl, false);
}; };
   
function triggerSubmit(ele,e,logicTrigger){ function triggerSubmit(ele,e,logicTrigger){
   //console.log('10');    //console.log('10');
   var formValid = true;    var formValid = true;
   var inputName = '';    var inputName = '';
   
   ele.attr('disabled', 'disabled');    ele.attr('disabled', 'disabled');
   
   if ($(".validateForm").size() > 0) {    if ($(".validateForm").size() > 0) {
       var form = $(".validateForm");        var form = $(".validateForm");
       if($(form).find('input[type="email"]').size() > 0) {        if($(form).find('input[type="email"]').size() > 0) {
           var value = $(form).find('input[type="email"]').val();            var value = $(form).find('input[type="email"]').val();
           var validResult = ValidateEmail(value);            var validResult = ValidateEmail(value);
           formValid = validResult;            formValid = validResult;
   
           if(!formValid) {            if(!formValid) {
               if($("#Email-error").size() <= 0 ) {                if($("#Email-error").size() <= 0 ) {
                   $(form).find('input[type="email"]').after(                    $(form).find('input[type="email"]').after(
                       '<label id="Email-error" class="error" for="Email">Please enter a valid email address</label>'                        '<label id="Email-error" class="error" for="Email">Please enter a valid email address</label>'
                   );                    );
               }                }
           }            }
       }        }
       else {        else {
           // inputName  = $(form).find('input[type="text"]').attr('name');            // inputName  = $(form).find('input[type="text"]').attr('name');
           inputName  = $(form).find('input').attr('name');            inputName  = $(form).find('input').attr('name');
   
           // var value = $(form).find('input[type="text"]').val();            // var value = $(form).find('input[type="text"]').val();
           var value = $(form).find('input').val();            var value = $(form).find('input').val();
   
   
           // Zip code validation on submit            // Zip code validation on submit
           if(inputName == 'EnvironmentZipCode'){            if(inputName == 'EnvironmentZipCode'){
   
               var validResult = ValidateZip(value);                var validResult = ValidateZip(value);
   
               //console.log('Result = ' + validResult);                //console.log('Result = ' + validResult);
               formValid = validResult;                formValid = validResult;
   
               if(!formValid) {                if(!formValid) {
                   if($("#Zip-error").size() <= 0 ) {                    if($("#Zip-error").size() <= 0 ) {
                       $(form).find('input[name="EnvironmentZipCode"]').after(                        $(form).find('input[name="EnvironmentZipCode"]').after(
                           '<label id="Zip-error" class="error" for="Zip">Please enter a valid ZIP code</label>'                            '<label id="Zip-error" class="error" for="Zip">Please enter a valid ZIP code</label>'
                       );                        );
                   }                    }
                   else{                    else{
                       $('#Zip-error').show();                        $('#Zip-error').show();
                   }                    }
               }                }
               else{                else{
                   formValid = validateCustomForm(form);                    formValid = validateCustomForm(form);
               }                }
           }            }
           else{            else{
               formValid = validateCustomForm(form);                formValid = validateCustomForm(form);
           }            }
   
   
       }        }
   
   
       if($('.error').size() > 0)        if($('.error').size() > 0)
       {        {
           ele.removeAttr('disabled');            ele.removeAttr('disabled');
       }        }
   }    }
   
   
   if (formValid == true) {    if (formValid == true) {
       var xAction = ele.data('action');        var xAction = ele.data('action');
       var pId = pageHandle;        var pId = pageHandle;
       var xURL = '?page=' + xAction;        var xURL = '?page=' + xAction;
       if (xAction != '') {        if (xAction != '') {
           var loadUrl = '/pages/' + xAction;            var loadUrl = '/pages/' + xAction;
       }        }
       var submit = ele.data('submit');        var submit = ele.data('submit');
       actionDirection = ele.data('direction');        actionDirection = ele.data('direction');
       var stateObj = {        var stateObj = {
           page: xURL,            page: xURL,
       };        };
   
   
       if (submit == true) {        if (submit == true) {
   
           var postParam = {'page': pId};            var postParam = {'page': pId};
   
           var xName = '';            var xName = '';
   
           quiz = JSON.parse(localStorage.getItem(tempStorageName));            quiz = JSON.parse(localStorage.getItem(tempStorageName));
   
           customerNode = JSON.parse(localStorage.getItem(customerStorage));            customerNode = JSON.parse(localStorage.getItem(customerStorage));
   
           postParam['sessionID'] = quiz['uniqueID'];            postParam['sessionID'] = quiz['uniqueID'];
   
           // for identifying the food eating diet (other) input type            // for identifying the food eating diet (other) input type
           var xType = ele.closest('.quizSectionInner').find('input[data-storage]').attr('type');            var xType = ele.closest('.quizSectionInner').find('input[data-storage]').attr('type');
           if(pageHandle == 'food-eating-diet' && ele.data('value') == 'other'){            if(pageHandle == 'food-eating-diet' && ele.data('value') == 'other'){
               xType = ele.closest('#dialog-form').find('input[data-storage]').attr('type');                xType = ele.closest('#dialog-form').find('input[data-storage]').attr('type');
           }            }
   
           var questionTitle = $('.question__title').text();            var questionTitle = $('.question__title').text();
   
           var questionID = $('.question__title').data('qnid');            var questionID = $('.question__title').data('qnid');
           var questionNo = $('.question__title').data('qnno');            var questionNo = $('.question__title').data('qnno');
   
           postParam['question'] = questionTitle;            postParam['question'] = questionTitle;
           postParam['questionID'] = questionID;            postParam['questionID'] = questionID;
           postParam['questionNo'] = questionNo;            postParam['questionNo'] = questionNo;
   
   
           postParam['responses'] = new Array();            postParam['responses'] = new Array();
           postParam['responseIDs'] = new Array();            postParam['responseIDs'] = new Array();
           postParam['responseKeys'] = new Array();            postParam['responseKeys'] = new Array();
   
   
           if (xType == 'text' || xType == 'number' || xType == 'tel') {            if (xType == 'text' || xType == 'number' || xType == 'tel') {
   
               var xVal = '';                var xVal = '';
   
               if(pageHandle == 'food-eating-diet'){                if(pageHandle == 'food-eating-diet'){
                   ele.closest('#dialog-form').find('input').each(function () {                    ele.closest('#dialog-form').find('input').each(function () {
                       xName = $(this).attr('name');                        xName = $(this).attr('name');
                       xVal = $(this).val();                        xVal = $(this).val();
                       quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;                        quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;
   
                       postParam['responses'].push(xVal);                        postParam['responses'].push(xVal);
   
                   });                    });
   
               }else{                }else{
                   ele.closest('.quizSectionInner').find('input').each(function () {                    ele.closest('.quizSectionInner').find('input').each(function () {
                       xName = $(this).attr('name');                        xName = $(this).attr('name');
                       xVal = $(this).val();                        xVal = $(this).val();
                       quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;                        quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;
   
                       postParam['responses'].push(xVal);                        postParam['responses'].push(xVal);
   
                   });                    });
               }                }
   
               //setting customerInfo                //setting customerInfo
               if(pageHandle == "name"){                if(pageHandle == "name"){
                   customerNode['Name'] = xVal;                    customerNode['Name'] = xVal;
                   localStorage.setItem(customerStorage, JSON.stringify(customerNode));                    localStorage.setItem(customerStorage, JSON.stringify(customerNode));
               }                }
   
           } else if (xType == 'email') {            } else if (xType == 'email') {
               ele.closest('.quizSectionInner').find('input').each(function () {                ele.closest('.quizSectionInner').find('input').each(function () {
                   xName = $(this).attr('name');                    xName = $(this).attr('name');
                   var xVal = $(this).val();                    var xVal = $(this).val();
                   quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;                    quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xVal;
   
                   postParam['responses'].push(xVal);                    postParam['responses'].push(xVal);
   
                   //setting customerInfo                    //setting customerInfo
                   customerNode['Email'] = xVal;                    customerNode['Email'] = xVal;
                   localStorage.setItem(customerStorage, JSON.stringify(customerNode));                    localStorage.setItem(customerStorage, JSON.stringify(customerNode));
   
               });                });
           } else if (xType == 'radio') {            } else if (xType == 'radio') {
   
               var xCheck = ele.closest('.quizSectionInner').find('input[data-storage]:checked');                var xCheck = ele.closest('.quizSectionInner').find('input[data-storage]:checked');
               if(pageHandle == "food-eating-diet") {                if(pageHandle == "food-eating-diet") {
                   var xCheck = ele;                    var xCheck = ele;
               }                }
   
               xName = xCheck.attr('name');                xName = xCheck.attr('name');
   
               var xVal = xCheck.val();                var xVal = xCheck.val();
               var xID = xCheck.data('respid');                var xID = xCheck.data('respid');
               var xIndexVal = xCheck.data('numval');                var xIndexVal = xCheck.data('numval');
   
               quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xIndexVal;                quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xIndexVal;
   
               postParam['responses'].push(xVal);                postParam['responses'].push(xVal);
               postParam['responseIDs'].push(xID);                postParam['responseIDs'].push(xID);
               postParam['responseKeys'].push(xIndexVal);                postParam['responseKeys'].push(xIndexVal);
   
           } else if (xType == 'checkbox') {            } else if (xType == 'checkbox') {
               var xVal = '';                var xVal = '';
               var xIndexVal = '';                var xIndexVal = '';
   
               var tempVal;                var tempVal;
               var tempIndexVal;                var tempIndexVal;
               var tempID;                var tempID;
   
               xName = $('.quizSectionInner input[data-storage]:checked').attr('name');                xName = $('.quizSectionInner input[data-storage]:checked').attr('name');
               $('.quizSectionInner input:checked').each(function (index) {                $('.quizSectionInner input:checked').each(function (index) {
   
                   tempVal = $(this).val();                    tempVal = $(this).val();
                   tempID = $(this).data('respid');                    tempID = $(this).data('respid');
                   tempIndexVal = $(this).data('numval');                    tempIndexVal = $(this).data('numval');
   
                   if(pageHandle == 'hw-attitude'){                    if(pageHandle == 'hw-attitude'){
                       var postRank = $(this).closest('div').find('span').text();                        var postRank = $(this).closest('div').find('span').text();
                       if(postRank !== '' && postRank !== undefined){                        if(postRank !== '' && postRank !== undefined){
                           postParam['responses'][postRank - 1] = tempVal;                            postParam['responses'][postRank - 1] = tempVal;
                           postParam['responseIDs'][postRank - 1] = tempID;                            postParam['responseIDs'][postRank - 1] = tempID;
                           postParam['responseKeys'][postRank - 1] = tempIndexVal;                            postParam['responseKeys'][postRank - 1] = tempIndexVal;
                       }                        }
                   }else{                    }else{
                       postParam['responses'].push(tempVal);                        postParam['responses'].push(tempVal);
                       postParam['responseIDs'].push(tempID);                        postParam['responseIDs'].push(tempID);
                       postParam['responseKeys'].push(tempIndexVal);                        postParam['responseKeys'].push(tempIndexVal);
                   }                    }
   
                   if(pageHandle !== 'hw-attitude'){                    if(pageHandle !== 'hw-attitude'){
                       if (index == 0) {                        if (index == 0) {
                           xVal += $(this).val();                            xVal += $(this).val();
                           xIndexVal += $(this).data('numval');                            xIndexVal += $(this).data('numval');
                       } else {                        } else {
                           xVal += '|' + $(this).val();                            xVal += '|' + $(this).val();
                           xIndexVal += '|' + $(this).data('numval');                            xIndexVal += '|' + $(this).data('numval');
                       }                        }
                   }                    }
               });                });
               // console.log(postParam.responseIDs,'postParam.responseIDs');                // console.log(postParam.responseIDs,'postParam.responseIDs');
               if(pageHandle == 'hw-attitude'){                if(pageHandle == 'hw-attitude'){
                   $.each(postParam.responseIDs, function (key, value) {                    $.each(postParam.responseIDs, function (key, value) {
                       if (key == 0) {                        if (key == 0) {
                           xIndexVal += value;                            xIndexVal += value;
                       } else {                        } else {
                           xIndexVal += '|' + value;                            xIndexVal += '|' + value;
                       }                        }
                   });                    });
   
                   $.each(postParam.responses, function (key, value) {                    $.each(postParam.responses, function (key, value) {
                       if (key == 0) {                        if (key == 0) {
                           xVal += value;                            xVal += value;
                       } else {                        } else {
                           xVal += '|' + value;                            xVal += '|' + value;
                       }                        }
                   });                    });
               }                }
   
               quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xIndexVal;                quiz[xName] = xVal + '||' + pId + '||' + questionTitle + '=' + xIndexVal;
           }            }
   
           $('[storage-field]:visible  input[type="hidden"]').each(function () {            $('[storage-field]:visible  input[type="hidden"]').each(function () {
               var yQuestionTitle = $(this).data('question');                var yQuestionTitle = $(this).data('question');
   
               var yName = $(this).attr('name');                var yName = $(this).attr('name');
               var yVal = $(this).val();                var yVal = $(this).val();
               var ypId = $(this).attr('action');                var ypId = $(this).attr('action');
               var yIndexVal = 0;                var yIndexVal = 0;
               if (yVal == 'NA') {                if (yVal == 'NA') {
                   yIndexVal = 0;                    yIndexVal = 0;
               }                }
   
               if (yVal == '') {                if (yVal == '') {
                   yIndexVal = 0;                    yIndexVal = 0;
               }                }
   
               // console.log(yVal);                // console.log(yVal);
               quiz[yName] = yVal + '||' + ypId + '||' + yQuestionTitle + '=' + yIndexVal;                quiz[yName] = yVal + '||' + ypId + '||' + yQuestionTitle + '=' + yIndexVal;
           });            });
   
           clearRemainingNodeAfterSubmit(xName);            clearRemainingNodeAfterSubmit(xName);
   
           localStorage.setItem(tempStorageName, JSON.stringify(quiz));            localStorage.setItem(tempStorageName, JSON.stringify(quiz));
   
           if (logicTrigger == undefined && postParam) {            if (logicTrigger == undefined && postParam) {
               var method = 'POST';                var method = 'POST';
               var path   = 'storeQuizResponse';                var path   = 'storeQuizResponse';
               console.log(postParam);                console.log(postParam);
               triggerAPI(path, postParam, method)                triggerAPI(path, postParam, method)
           }            }
   
           localStorage.setItem(tempStorageName, JSON.stringify(quiz));            localStorage.setItem(tempStorageName, JSON.stringify(quiz));
   
       }        }
   
       if(loadUrl) {        if(loadUrl) {
           history.pushState(stateObj, '', xURL);            history.pushState(stateObj, '', xURL);
       }        }
   
       return loadUrl;        return loadUrl;
   }else{    }else{
       return false;        return false;
   
   }    }
} }
   
   
// for checking the age and zipcode on keypress in custom page // for checking the age and zipcode on keypress in custom page
function preventNonNumericalInput(e) { function preventNonNumericalInput(e) {
   e = e || window.event;    e = e || window.event;
   var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;    var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
   var charStr = String.fromCharCode(charCode);    var charStr = String.fromCharCode(charCode);
   
   if (!charStr.match(/^[0-9]+$/))    if (!charStr.match(/^[0-9]+$/))
     e.preventDefault();      e.preventDefault();
} }
   
   
function setCustomDefaultValues(handle){ function setCustomDefaultValues(handle){
   
   if(handle == 'name'){    if(handle == 'name'){
       if(cDetails.firstName !== undefined && cDetails.firstName.length > 2){        if(cDetails.firstName !== undefined && cDetails.firstName.length > 2){
               $('.input-textbox').val(cDetails.firstName);                $('.input-textbox').val(cDetails.firstName);
               $('.input-textbox').closest('div').addClass('valid');                $('.input-textbox').closest('div').addClass('valid');
       }        }
   }    }
   if(handle == 'email' && cDetails.email !== undefined){    if(handle == 'email' && cDetails.email !== undefined){
   
       value = cDetails.email;        value = cDetails.email;
       if(value.length > 0 ){        if(value.length > 0 ){
   
           var validResult = ValidateEmail(value);            var validResult = ValidateEmail(value);
           $('.input-textbox').val(cDetails.email);            $('.input-textbox').val(cDetails.email);
   
           if(validResult == true)            if(validResult == true)
           {            {
               $('.input-textbox').closest('div').addClass('valid');                $('.input-textbox').closest('div').addClass('valid');
               $('#Email-error').hide();                $('#Email-error').hide();
           }            }
           else            else
           {            {
               $('.input-textbox').closest('div').removeClass('valid');                $('.input-textbox').closest('div').removeClass('valid');
               $('#Email-error').show();                $('#Email-error').show();
           }            }
   
   
       }        }
   }    }
} }
   
   
function validateCustomForm(form){ function validateCustomForm(form){
   form.validate({    form.validate({
       rules: {        rules: {
           Name:{            Name:{
               maxlength : 30,                maxlength : 30,
               required: true,                required: true,
           },            },
           Age:{            Age:{
              required:true,               required:true,
              validAge : true               validAge : true
           },            },
           FoodEatingDiet:{            FoodEatingDiet:{
               required: true,                required: true,
               minlength : 3                minlength : 3
           }            }
         },          },
         messages: {          messages: {
           Name: {            Name: {
              maxlength: "Please enter your name (not more than 30 characters)"               maxlength: "Please enter your name (not more than 30 characters)"
           },            },
           Age:{            Age:{
               validAge: "Please enter a valid age (18-99)"                validAge: "Please enter a valid age (18-99)"
           },            },
           FoodEatingDiet:{            FoodEatingDiet:{
               required: "Please enter your diet.",                required: "Please enter your diet.",
               minlength: "Please enter your diet."                minlength: "Please enter your diet."
           }            }
   
         }          }
   });    });
   
   $.validator.addMethod("validAge", function(value, element, min) {    $.validator.addMethod("validAge", function(value, element, min) {
       var value = $('.input-textbox').val();        var value = $('.input-textbox').val();
       var regex = /^\d+$/;        var regex = /^\d+$/;
       return regex.test(value);        return regex.test(value);
   
   }, "Not valid age");    }, "Not valid age");
   
   return formValid = form.valid();    return formValid = form.valid();
   
   
} }
   
   
function param(name) { function param(name) {
   return (location.search.split(name + '=')[1] || '').split('&')[0];    return (location.search.split(name + '=')[1] || '').split('&')[0];
} }
   
   
function quizLoaded() { function quizLoaded() {
   //console.log('11');    //console.log('11');
   $('body').addClass('quizLoaded');    $('body').addClass('quizLoaded');
   $('.multiselect-component.checkbox [data-submit="true"]').attr('disabled', 'disabled');    $('.multiselect-component.checkbox [data-submit="true"]').attr('disabled', 'disabled');
   
   $('.multiselect-component').not('.conditional').find('input[type="radio"]').each(function (index) {    $('.multiselect-component').not('.conditional').find('input[type="radio"]').each(function (index) {
       var xIndex = index + 1;        var xIndex = index + 1;
       $(this).attr('data-numval', xIndex);        $(this).attr('data-numval', xIndex);
   });    });
   
   $('.multiselect-component').not('.conditional').find('input[type="checkbox"]').each(function (index) {    $('.multiselect-component').not('.conditional').find('input[type="checkbox"]').each(function (index) {
       var xIndex = index + 1;        var xIndex = index + 1;
       $(this).attr('data-numval', xIndex);        $(this).attr('data-numval', xIndex);
   });    });
   
   $('.multiselect-component.checkbox input').prop('checked', false);    $('.multiselect-component.checkbox input').prop('checked', false);
   
   $(".randomize").html($(".randomize .rand").sort(function () {    $(".randomize").html($(".randomize .rand").sort(function () {
       return Math.random() - 0.5;        return Math.random() - 0.5;
   }));    }));
   
   /*$(".randomize1").html($(".randomize1 .quiz__content-box").sort(function () {    /*$(".randomize1").html($(".randomize1 .quiz__content-box").sort(function () {
       return Math.random() - 0.5;        return Math.random() - 0.5;
   }));*/    }));*/
   var othersEle = '';    var othersEle = '';
   
   $(".randomize1").html($(".randomize1 .rand").sort(function (elements) {    $(".randomize1").html($(".randomize1 .rand").sort(function (elements) {
       $(elements ).each(function( index ) {        $(elements ).each(function( index ) {
           var eText = $( this ).text().trim();            var eText = $( this ).text().trim();
           if(eText == 'Other'){            if(eText == 'Other'){
               othersEle = $(this);                othersEle = $(this);
           }            }
       });        });
   
       return Math.random() - 0.5;        return Math.random() - 0.5;
   }));    }));
   $('.randomize1 .rand:last').after(othersEle);    $('.randomize1 .rand:last').after(othersEle);
   
   
   
   $(".randomize").css('opacity', 1);    $(".randomize").css('opacity', 1);
   $(".randomize1").css('opacity', 1);    $(".randomize1").css('opacity', 1);
   
   // quiz end action    // quiz end action
   if ($('.endBtn').size() > 0) {    if ($('.endBtn').size() > 0) {
       var eTimeout = $('.endBtn').data('delay');        var eTimeout = $('.endBtn').data('delay');
       setTimeout(function () {        setTimeout(function () {
           //alert("Post Quiz check console for data");            //alert("Post Quiz check console for data");
           quizPost();            quizPost();
       }, eTimeout);        }, eTimeout);
   }    }
} }
   
   
function autoAdvance() { function autoAdvance() {
   //console.log('12');    //console.log('12');
   if ($('[data-advance]').size() > 0) {    if ($('[data-advance]').size() > 0) {
       if ($('[data-advance]').size() > 1) {        if ($('[data-advance]').size() > 1) {
           var autoAdvance = parseInt($('div[storage-field]:visible [data-advance]').data('advance'));            var autoAdvance = parseInt($('div[storage-field]:visible [data-advance]').data('advance'));
           clearTimeout(autoTimeout);            clearTimeout(autoTimeout);
           autoTimeout = setTimeout(function () {            autoTimeout = setTimeout(function () {
               clearTimeout(autoTimeout);                clearTimeout(autoTimeout);
   
               $('div[storage-field]:visible > [data-advance]').trigger('click');                $('div[storage-field]:visible > [data-advance]').trigger('click');
   
           }, autoAdvance);            }, autoAdvance);
       } else {        } else {
           var autoAdvance = parseInt($('[data-advance]').data('advance'));            var autoAdvance = parseInt($('[data-advance]').data('advance'));
           clearTimeout(autoTimeout);            clearTimeout(autoTimeout);
           autoTimeout = setTimeout(function () {            autoTimeout = setTimeout(function () {
               clearTimeout(autoTimeout);                clearTimeout(autoTimeout);
               $('div:visible [data-advance]').trigger('click');                $('div:visible [data-advance]').trigger('click');
           }, autoAdvance);            }, autoAdvance);
       }        }
   }    }
} }
   
   
function renderLocalStorage() { function renderLocalStorage() {
   //console.log('13');    
   $('[storage-value]').hide();    $('[storage-value]').hide();
   
     var aboveSixtyFemale = '';  
     var aboveSixtyNonBinary = '';  
   
   $('[storage-field]').each(function () {    $('[storage-field]').each(function () {
   
       var sThis = $(this);        var sThis = $(this);
   
       var xv = $(this).is('[storage-value]');        var xv = $(this).is('[storage-value]');
   
       var hasValue;        var hasValue;
       if (xv == true) {        if (xv == true) {
           hasValue = $(this).attr('storage-value');            hasValue = $(this).attr('storage-value');
       }        }
   
         if(hasValue == 'Age-60-above-Female'){  
             aboveSixtyFemale = $(this);  
         }          
   
         if(hasValue == 'Age-60-above-NonBinary'){  
             aboveSixtyNonBinary = $(this);  
         }    
   
       var xKey = $(this).attr('storage-field');        var xKey = $(this).attr('storage-field');
       var xValue = JSON.parse(localStorage.getItem(tempStorageName))[xKey];         var jsonNode = JSON.parse(localStorage.getItem(tempStorageName)); 
         var xValue = jsonNode[xKey];  
   
       var xValue2 = xValue.split('||')[0];        var xValue2 = xValue.split('||')[0];
   
       if (xv == false) {        if (xv == false) {
           // render storage value            // render storage value
           $(this).html(xValue2);            $(this).html(xValue2);
       } else {        } else {
           // show hide block based on storage            // show hide block based on storage
           var showValueArr = sThis.attr('storage-value').split('|');            var showValueArr = sThis.attr('storage-value').split('|');
           var xValueArray = xValue2.split('|');            var xValueArray = xValue2.split('|');
           //console.log('xValue2:'+xValue2);    
           //loop selected value            //loop selected value
           //console.log('xKey:'+xKey+'|||showValueArr:'+showValueArr);    
           if (xValue2 != '') {            if (xValue2 != '') {
               $.each(xValueArray, function (key, value) {                $.each(xValueArray, function (key, value) {
                   var selectedValue = value;                    var selectedValue = value;
                   //console.log(key + ": " + value);    
                   // loop show attr                    // loop show attr
                   $.each(showValueArr, function (k, v) {                    $.each(showValueArr, function (k, v) {
                       //console.log('KEY:' + k + '||VALUE:' + v);    
                       //console.log('xKey:' + xKey + '||VALUE:' + v);    
                       var inAttr = v.indexOf(selectedValue);                        var inAttr = v.indexOf(selectedValue);
                       if (inAttr >= 0) {                         console.log('inAttr'+inAttr); 
                           sThis.show();                         if (inAttr == 0) { 
                             if(pageHandle == 'specific-interests')  
                             {  
                                 var xAgeValue  = jsonNode['Age'].split('||')[0];  
                                 xAgeValue = parseInt(xAgeValue);  
                                 var xGenderValue  = jsonNode['Gender'].split('||')[0];                                  
   
                                 if(xGenderValue == 'Female' && xAgeValue > 60){  
                                     console.log(xAgeValue,'aboveSixtyFemale ------------');  
                                     aboveSixtyFemale.show();  
                                 } else if (xGenderValue == 'Non-Binary' && xAgeValue > 60){  
                                     console.log(xAgeValue,'aboveSixtyNonBinary ------------');  
                                       
                                     aboveSixtyNonBinary.show();  
                                 } else {                                    
                                     sThis.show();  
                                 }  
                             }  
                             else if(pageHandle == 'nutritional-support'){  
                                 var xAgeValue  = jsonNode['Age'].split('||')[0];  
                                 var xGenderValue  = jsonNode['Gender'].split('||')[0];      
                                 if (xGenderValue == 'Non-Binary' && xAgeValue >= 60){  
                                     aboveSixtyNonBinary.show();  
                                 } else {  
                                     sThis.show();  
                                 }  
                             }  
                             else{  
                                 sThis.show();  
                             }  
                       }                        }
                   });                    });
               });                });
           }            }
       }        }
   });    });
} }
   
function skipSubmitField(isLoad) { function skipSubmitField(isLoad) {
   //console.log('34');    //console.log('34');
   var xAction = ''    var xAction = ''
   $('.skipSubmitField').each(function () {    $('.skipSubmitField').each(function () {
       var sThis = $(this);        var sThis = $(this);
       var skipValArray = sThis.find('[data-skip="true"]').text().split('|');        var skipValArray = sThis.find('[data-skip="true"]').text().split('|');
   
       $.each(skipValArray, function (key, value) {        $.each(skipValArray, function (key, value) {
           //alert(value);            //alert(value);
           sThis.find('input[data-value="' + value + '"]').val('');            sThis.find('input[data-value="' + value + '"]').val('');
       });        });
       xAction = sThis.find('input[value=""]').first().attr('action');        xAction = sThis.find('input[value=""]').first().attr('action');
   
       if(sThis.find('[data-action]').size() > 0) {        if(sThis.find('[data-action]').size() > 0) {
           sThis.find('[data-action]').attr('data-action', xAction);            sThis.find('[data-action]').attr('data-action', xAction);
           var priority = sThis.find('[data-skip="true"]').attr('prioritize');            var priority = sThis.find('[data-skip="true"]').attr('prioritize');
           var priorityAction = sThis.find('input[data-value="' + priority + '"][value=""]').attr('action');            var priorityAction = sThis.find('input[data-value="' + priority + '"][value=""]').attr('action');
           if (priorityAction != '') {            if (priorityAction != '') {
               sThis.find('[data-action]').attr('data-action', priorityAction)                sThis.find('[data-action]').attr('data-action', priorityAction)
           }            }
       }        }
   
       if(isLoad !== null) {        if(isLoad !== null) {
           $('.skipSubmitField  input[type="hidden"]').each(function () {            $('.skipSubmitField  input[type="hidden"]').each(function () {
               var yName = $(this).attr('name');                var yName = $(this).attr('name');
               var yVal = $(this).val();                var yVal = $(this).val();
               var ypId = $(this).attr('action');                var ypId = $(this).attr('action');
               var yQuestionTitle = $(this).data('question');                var yQuestionTitle = $(this).data('question');
               var yIndexVal = 0;                var yIndexVal = 0;
               if (yVal == 'NA') {                if (yVal == 'NA') {
                   yIndexVal = 0;                    yIndexVal = 0;
               }                }
               if (yVal == '') {                if (yVal == '') {
                   yIndexVal = 0;                    yIndexVal = 0;
               }                }
   
               quiz[yName] = yVal + '||' + ypId + '||' + yQuestionTitle + '=' + yIndexVal;                quiz[yName] = yVal + '||' + ypId + '||' + yQuestionTitle + '=' + yIndexVal;
               localStorage.setItem(tempStorageName, JSON.stringify(quiz));                localStorage.setItem(tempStorageName, JSON.stringify(quiz));
           });            });
       }        }
   
       if(sThis.find('[data-action]').size() > 0 && isLoad == null) {        if(sThis.find('[data-action]').size() > 0 && isLoad == null) {
           sThis.find('[data-action]').trigger('click');            sThis.find('[data-action]').trigger('click');
       }        }
   });    });
   
   // auto add last blank    // auto add last blank
   $.each(quiz, function (key, value) {    $.each(quiz, function (key, value) {
       if (value.split('||')[0] != '') {        if (value.split('||')[0] != '') {
   
       } else {        } else {
           resumePage = value.split('||')[1];            resumePage = value.split('||')[1];
           //alert(resumePage);            //alert(resumePage);
           if(resumePage == xAction){            if(resumePage == xAction){
               return true;                return true;
           }            }
   
           $('.goToLastBlank').attr('data-action', resumePage);            $('.goToLastBlank').attr('data-action', resumePage);
   
           if(isLoad == null) {            if(isLoad == null) {
               $('.goToLastBlank').trigger('click');                $('.goToLastBlank').trigger('click');
           }            }
   
           return false;            return false;
       }        }
   });    });
} }
   
   
function loadQuiz(dir, url, push) { function loadQuiz(dir, url, push) {
   //console.log('15');    //console.log('15');
   $('.quizSectionWrap .quizSection').addClass('oldContent');    $('.quizSectionWrap .quizSection').addClass('oldContent');
   var pID = url.replace('/pages/', '');    var pID = url.replace('/pages/', '');
   
   pageHandle = pID;    pageHandle = pID;
   
   if (dir == 'right') {    if (dir == 'right') {
       $('.quizSectionWrap').append('<div class="quizSection newContent" data-position="right" data-pid="' + pID + '"></div>');        $('.quizSectionWrap').append('<div class="quizSection newContent" data-position="right" data-pid="' + pID + '"></div>');
   } else if (dir == 'left') {    } else if (dir == 'left') {
       $('.quizSectionWrap').prepend('<div class="quizSection newContent" data-position="left" data-pid="' + pID + '"></div>');        $('.quizSectionWrap').prepend('<div class="quizSection newContent" data-position="left" data-pid="' + pID + '"></div>');
   }    }
   
   // load    // load
   $('body').addClass('quizLoading');    $('body').addClass('quizLoading');
   $('body').removeClass('loaded');    $('body').removeClass('loaded');
   $('body').addClass('loading');    $('body').addClass('loading');
   $('.newContent').load(url + ' .quizSectionInner', function () {    $('.newContent').load(url + ' .quizSectionInner', function () {
       $('body').removeClass('quizLoading');        $('body').removeClass('quizLoading');
       $('.quizSectionWrap').attr('data-move', dir);        $('.quizSectionWrap').attr('data-move', dir);
       renderLocalStorage();        renderLocalStorage();
       setTimeout(function () {        setTimeout(function () {
           $('body').removeClass('loading');            $('body').removeClass('loading');
           $('body').addClass('loaded');            $('body').addClass('loaded');
           $('.quizSectionWrap').attr('data-move', '');            $('.quizSectionWrap').attr('data-move', '');
           $('.quizSectionWrap .quizSection.oldContent').remove();            $('.quizSectionWrap .quizSection.oldContent').remove();
           $('.quizSectionWrap .quizSection.newContent').removeClass('.newContent').attr('data-position', 'center');            $('.quizSectionWrap .quizSection.newContent').removeClass('.newContent').attr('data-position', 'center');
           $('.button_survey_back').show();            $('.button_survey_back').show();
           autoAdvance();            autoAdvance();
           quizLoaded();            quizLoaded();
           skipSubmitField(true);            skipSubmitField(true);
           getProgress();            getProgress();
   
           var ua = window.navigator.userAgent;            var ua = window.navigator.userAgent;
           var msie = ua.indexOf("MSIE ");            var msie = ua.indexOf("MSIE ");
   
           if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
           {            {
               //console.log('IE browser!');                //console.log('IE browser!');
           }            }
           else  // If another browser, return 0            else  // If another browser, return 0
           {            {
               // set autofocus                // set autofocus
               $(".input-textbox").first().trigger('focus');                $(".input-textbox").first().trigger('focus');
           }            }
                         
           // set number keybord for mobile devices            // set number keybord for mobile devices
           if(pageHandle == 'basic-profile-age' || pageHandle == 'environment-zipcode'){            if(pageHandle == 'basic-profile-age' || pageHandle == 'environment-zipcode'){
               setRightInputKeyboard();                setRightInputKeyboard();
           }            }
   
           // set default values in email and name field.            // set default values in email and name field.
           if(pageHandle == 'name' || pageHandle == 'email'){            if(pageHandle == 'name' || pageHandle == 'email'){
               setCustomDefaultValues(pageHandle);                setCustomDefaultValues(pageHandle);
           }            }
           if(pageHandle == 'name-response'){            if(pageHandle == 'name-response'){
               displayUserName();                displayUserName();
           }            }
   
       }, 310);        }, 310);
   });    });
} }
   
   
function getUrlParameter(sParam) { function getUrlParameter(sParam) {
   //console.log('16');    //console.log('16');
   var sPageURL = window.location.search.substring(1),    var sPageURL = window.location.search.substring(1),
       sURLVariables = sPageURL.split('&'),        sURLVariables = sPageURL.split('&'),
       sParameterName,        sParameterName,
       i;        i;
   
   for (i = 0; i < sURLVariables.length; i++) {    for (i = 0; i < sURLVariables.length; i++) {
       sParameterName = sURLVariables[i].split('=');        sParameterName = sURLVariables[i].split('=');
   
       if (sParameterName[0] === sParam) {        if (sParameterName[0] === sParam) {
           return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
       }        }
   }    }
}; };
   
   
function getProgress() { function getProgress() {
   //console.log('17');    //console.log('17');
   var totalProgress = 0;    var totalProgress = 0;
   var progressBar = 0;    var progressBar = 0;
   var quizVal = JSON.parse(localStorage.getItem(tempStorageName));    var quizVal = JSON.parse(localStorage.getItem(tempStorageName));
   var currentStep = getUrlParameter('page');    var currentStep = getUrlParameter('page');
   var foundJSON = false;    var foundJSON = false;
   
   if(quizVal !== undefined) {    if(quizVal !== undefined) {
       foundJSON = true;        foundJSON = true;
   }    }
   
   $.each(quizVal, function (key, value) {    $.each(quizVal, function (key, value) {
       var questionAnswer = value.split('||')[0];        var questionAnswer = value.split('||')[0];
       var questionPage = value.split('||')[1];        var questionPage = value.split('||')[1];
       totalProgress += 1;        totalProgress += 1;
   });    });
   totalProgress += 1;    totalProgress += 1;
   //console.log(totalProgress + 1);    //console.log(totalProgress + 1);
   
   var questionNum  = $('body').find('[data-qnno]').data('qnno');    var questionNum  = $('body').find('[data-qnno]').data('qnno');
   
   progressBar = (parseInt(questionNum) / totalProgress) * 100;    progressBar = (parseInt(questionNum) / totalProgress) * 100;
   if (currentStep == 'close') {    if (currentStep == 'close') {
       progressBar = 100;        progressBar = 100;
   }    }
   if (currentStep === undefined) {    if (currentStep === undefined) {
       progressBar = 0;        progressBar = 0;
   }    }
   
   
   $('.progressBar .bar').css('width', progressBar + '%');    $('.progressBar .bar').css('width', progressBar + '%');
   if (foundJSON == false) {    if (foundJSON == false) {
       $('.progressBar').hide();        $('.progressBar').hide();
   } else {    } else {
       $('.progressBar').show();        $('.progressBar').show();
   }    }
   
   if (progressBar == 0 ){    if (progressBar == 0 ){
     $('.progressBar').hide();      $('.progressBar').hide();
   }    }
   
   
   
   if(questionNum == undefined) {    if(questionNum == undefined) {
       var message = '';        var message = '';
   } else {    } else {
       var message = questionNum + ' of 49';        var message = questionNum + ' of 49';
   }    }
   $('#quiz-no-status').text(message);    $('#quiz-no-status').text(message);
   
   // Color Background and Sun element    // Color Background and Sun element
   var bg_opacity = (parseInt(questionNum) * 4)/100.00;    var bg_opacity = (parseInt(questionNum) * 4)/100.00;
   if(bg_opacity > 0) {    if(bg_opacity > 0) {
       $('#quiz-bg-2').css('opacity',bg_opacity);        $('#quiz-bg-2').css('opacity',bg_opacity);
   }    }
   if(bg_opacity >= 1) {    if(bg_opacity >= 1) {
       var bg_opacity_2 = ((parseInt(questionNum)*4)-100.00)/100.00;        var bg_opacity_2 = ((parseInt(questionNum)*4)-100.00)/100.00;
       $('#quiz-bg-3').css('opacity', bg_opacity_2);        $('#quiz-bg-3').css('opacity', bg_opacity_2);
   }    }
   
   //console.log("progressBar: "+progressBar);    //console.log("progressBar: "+progressBar);
   if(progressBar > 6) {    if(progressBar > 6) {
       var left_pos = 104-progressBar,        var left_pos = 104-progressBar,
           bottom_pos = progressBar-1;            bottom_pos = progressBar-1;
       if(progressBar > 55) {        if(progressBar > 55) {
           var bottom_pos = 99 - progressBar,            var bottom_pos = 99 - progressBar,
               left_pos = bottom_pos-1;                left_pos = bottom_pos-1;
       }        }
       //console.log({bottom_pos},{left_pos});        //console.log({bottom_pos},{left_pos});
       if(bottom_pos >= 0 ) {        if(bottom_pos >= 0 ) {
           $(".sun-wrapper").css('bottom', bottom_pos + '%');            $(".sun-wrapper").css('bottom', bottom_pos + '%');
           $(".sun-wrapper").css('left', left_pos + '%');            $(".sun-wrapper").css('left', left_pos + '%');
       }        }
   }    }
   
} }
   
function displayUserName(){ function displayUserName(){
   if($('#user-display-name').size()>0){    if($('#user-display-name').size()>0){
       var quizVal = JSON.parse(localStorage.getItem(tempStorageName));        var quizVal = JSON.parse(localStorage.getItem(tempStorageName));
       var userName = quizVal['Name'].split('||')[0];        var userName = quizVal['Name'].split('||')[0];
       $('#user-display-name').text(userName);        $('#user-display-name').text(userName);
   }    }
} }
   
   
function uniqueID() { function uniqueID() {
   function chr4() {    function chr4() {
       return Math.random().toString(16).slice(-4);        return Math.random().toString(16).slice(-4);
   }    }
   
   return chr4() + chr4() +    return chr4() + chr4() +
       '-' + chr4() +        '-' + chr4() +
       '-' + chr4() +        '-' + chr4() +
       '-' + chr4() +        '-' + chr4() +
       '-' + chr4() + chr4() + chr4();        '-' + chr4() + chr4() + chr4();
} }
   
   
function quizPost() { function quizPost() {
   //console.log('18');    //console.log('18');
   var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));    var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));
   var questionIndex = 0;    var questionIndex = 0;
   var sessionEntry = '';    var sessionEntry = '';
   var surveyAnswers = {"SurveyAnswers": {"SessionId": "Session1", "Questions": []}};    var surveyAnswers = {"SurveyAnswers": {"SessionId": "Session1", "Questions": []}};
   
   $.each(quizStorage, function (key, value) {    $.each(quizStorage, function (key, value) {
       if (key != 'uniqueID') {        if (key != 'uniqueID') {
           questionIndex += 1;            questionIndex += 1;
           var questionNo = questionIndex;            var questionNo = questionIndex;
           var questionTitle = value.split('||')[2].split('=')[0];            var questionTitle = value.split('||')[2].split('=')[0];
           var questionAnswer = value.split('||')[2].split('=')[1];            var questionAnswer = value.split('||')[2].split('=')[1];
           var questionAnswerArr = questionAnswer.split('|');            var questionAnswerArr = questionAnswer.split('|');
           //console.log(questionNo+':'+questionTitle+'='+questionAnswer);            //console.log(questionNo+':'+questionTitle+'='+questionAnswer);
           var ansArr = [];            var ansArr = [];
           $.each(questionAnswerArr, function (k, v) {            $.each(questionAnswerArr, function (k, v) {
               ansArr.push(v);                ansArr.push(v);
           });            });
   
           surveyAnswers.SurveyAnswers.Questions.push({            surveyAnswers.SurveyAnswers.Questions.push({
               "QuestionNo": questionNo,                "QuestionNo": questionNo,
               "QuestionText": questionTitle,                "QuestionText": questionTitle,
               "AnswerText": ansArr                "AnswerText": ansArr
           });            });
   
       } else {        } else {
           if (key == 'uniqueID') {            if (key == 'uniqueID') {
               surveyAnswers.SurveyAnswers.SessionId = value;                surveyAnswers.SurveyAnswers.SessionId = value;
           }            }
       }        }
   });    });
   
   var surveyAnswerString = JSON.stringify(surveyAnswers);    var surveyAnswerString = JSON.stringify(surveyAnswers);
   
} }
   
   
function escapeDoubleQuotes(str) { function escapeDoubleQuotes(str) {
   return str.replace(/\\([\s\S])|(")/g, "\\$1$2"); // thanks @slevithan!    return str.replace(/\\([\s\S])|(")/g, "\\$1$2"); // thanks @slevithan!
} }
   
/* /*
$(function() { $(function() {
   
   
 $('#gtmtest').on('click', function(event) {  $('#gtmtest').on('click', function(event) {
         
   let products = [{    let products = [{
     VariantId: '17751228842055',      VariantId: '17751228842055',
     Quantity: 2      Quantity: 2
         
   },    },
   {    {
     VariantId: '17751228776519',      VariantId: '17751228776519',
     Quantity: 1      Quantity: 1
   },    },
   {    {
     VariantId: '30081196589127',      VariantId: '30081196589127',
     Quantity: 5      Quantity: 5
   }];    }];
         
   gtmTestaddItemsToCart(products);    gtmTestaddItemsToCart(products);
         
 });  });
   
}); });
   
*/ */
function gtmTestaddItemsToCart(product){ function gtmTestaddItemsToCart(product){
   
   Shopify.queue = [];    Shopify.queue = [];
   GTM_products = [];    GTM_products = [];
     
   // for clear the cart    // for clear the cart
   $.ajax({    $.ajax({
     type: "POST",      type: "POST",
     url: '/cart/clear.js',      url: '/cart/clear.js',
     success: function(){      success: function(){
       console.log('I cleared the cart!');        console.log('I cleared the cart!');
     },      },
     dataType: 'json'      dataType: 'json'
   });    });
   
   // Creating the queue for adding the items to cart.    // Creating the queue for adding the items to cart.
   let products_length = product.length;    let products_length = product.length;
     
   for(var i = 0 ; i< products_length ; i++){    for(var i = 0 ; i< products_length ; i++){
       Shopify.queue.push({        Shopify.queue.push({
           variantId: product[i].VariantId,            variantId: product[i].VariantId,
           quantity: product[i].Quantity,            quantity: product[i].Quantity,
           properties: {            properties: {
               // "ReasonsForProduct": product[i].ReasonsForProduct,                // "ReasonsForProduct": product[i].ReasonsForProduct,
               "ReasonsForProduct": "Because you're interested in Diabetes Support",                "ReasonsForProduct": "Because you're interested in Diabetes Support",
               "recommendedQty": 5                "recommendedQty": 5
           },            },
       });        });
   }    }
   
   Shopify.moveAlong = function() {    Shopify.moveAlong = function() {
       // If we still have requests in the queue, let's process the next one.        // If we still have requests in the queue, let's process the next one.
       if (Shopify.queue.length) {        if (Shopify.queue.length) {
         var request = Shopify.queue.shift();          var request = Shopify.queue.shift();
       //   var data = 'id='+ request.variantId + '&quantity='+request.quantity        //   var data = 'id='+ request.variantId + '&quantity='+request.quantity
         var data = {"id":request.variantId,"quantity":request.quantity,"properties":request.properties}          var data = {"id":request.variantId,"quantity":request.quantity,"properties":request.properties}
         $.ajax({          $.ajax({
               type: 'POST',                type: 'POST',
               url: '/cart/add.js',                url: '/cart/add.js',
               dataType: 'json',                dataType: 'json',
               data: data,                data: data,
               success: function(res) {                success: function(res) {
                GTM_products.push(res);                 GTM_products.push(res);
                Shopify.moveAlong();                 Shopify.moveAlong();
               },                },
               error: function(){                error: function(){
                   // if it's not last one Move Along else update the cart number with the current quantity                    // if it's not last one Move Along else update the cart number with the current quantity
                   if (Shopify.queue.length){                    if (Shopify.queue.length){
                       Shopify.moveAlong()                        Shopify.moveAlong()
                   }                    }
               }                }
         });          });
       }        }
       // If the queue is empty, moving to cart        // If the queue is empty, moving to cart
       else {        else {
                     
           if(pageHandle !== undefined && pageHandle == 'close') {            if(pageHandle !== undefined && pageHandle == 'close') {
               window.localStorage.removeItem(tempStorageName);                window.localStorage.removeItem(tempStorageName);
           }            }
   
           //GTM Add to cart from Quiz listing            //GTM Add to cart from Quiz listing
           //Build GTM Products            //Build GTM Products
           let allProducts = GTM_products.map(function(product, index) {            let allProducts = GTM_products.map(function(product, index) {
                   return {                    return {
                       name: product.title.replace("<sub>", '').replace('</sub>', ''),                        name: product.title.replace("<sub>", '').replace('</sub>', ''),
                       id: product.sku,                        id: product.sku,
                       price: product.price / 100,                        price: product.price / 100,
                       brand: product.vendor,                        brand: product.vendor,
                       position: index,                        position: index,
                       category: product.product_type                        category: product.product_type
                   };                    };
               });                });
   
           window.dataLayer.push({            window.dataLayer.push({
                   event: "addToCart",                    event: "addToCart",
                   ecommerce: {                    ecommerce: {
                       actionField: {list: "Quiz"},                        actionField: {list: "Quiz"},
                       add: {                        add: {
                        products: allProducts                         products: allProducts
                       }                        }
                   }                    }
           });            });
                     
         //facebook addToCart          //facebook addToCart
         //fbq('track', 'AddToCart');          //fbq('track', 'AddToCart');
         //fbq('track', 'CompleteRegistration');          //fbq('track', 'CompleteRegistration');
               
   
          // document.location.href = '/cart';           // document.location.href = '/cart';
       }        }
   };    };
   Shopify.moveAlong();    Shopify.moveAlong();
   
} }
   
function addItemsToCart(product){ function addItemsToCart(product){
   
   Shopify.queue = [];    Shopify.queue = [];
   GTM_products = [];    GTM_products = [];
   
   // for clear the cart    // for clear the cart
   $.ajax({    $.ajax({
     type: "POST",      type: "POST",
     url: '/cart/clear.js',      url: '/cart/clear.js',
     success: function(){      success: function(){
       console.log('I cleared the cart!');        console.log('I cleared the cart!');
     },      },
     dataType: 'json'      dataType: 'json'
   });    });
   
   // Creating the queue for adding the items to cart.    // Creating the queue for adding the items to cart.
   let products_length = product.length;    let products_length = product.length;
     
   for(var i = 0 ; i< products_length ; i++){    for(var i = 0 ; i< products_length ; i++){
       Shopify.queue.push({        Shopify.queue.push({
           variantId: product[i].VariantId,            variantId: product[i].VariantId,
           quantity: product[i].Quantity,            quantity: product[i].Quantity,
           properties: {            properties: {
               "ReasonsForProduct": decodeEntities(product[i].ReasonsForProduct.join('||')),                "ReasonsForProduct": decodeEntities(product[i].ReasonsForProduct.join('||')),
               "recommendedQty": product[i].Quantity                "recommendedQty": product[i].Quantity
           },            },
       });        });
   }    }
   
   Shopify.moveAlong = function() {    Shopify.moveAlong = function() {
       // If we still have requests in the queue, let's process the next one.        // If we still have requests in the queue, let's process the next one.
       if (Shopify.queue.length) {        if (Shopify.queue.length) {
         var request = Shopify.queue.shift();          var request = Shopify.queue.shift();
       //   var data = 'id='+ request.variantId + '&quantity='+request.quantity        //   var data = 'id='+ request.variantId + '&quantity='+request.quantity
         var data = {"id":request.variantId,"quantity":request.quantity,"properties":request.properties}          var data = {"id":request.variantId,"quantity":request.quantity,"properties":request.properties}
         $.ajax({          $.ajax({
               type: 'POST',                type: 'POST',
               url: '/cart/add.js',                url: '/cart/add.js',
               dataType: 'json',                dataType: 'json',
               data: data,                data: data,
               success: function(res) {                success: function(res) {
                GTM_products.push(res);                 GTM_products.push(res);
                Shopify.moveAlong();                 Shopify.moveAlong();
               },                },
               error: function(){                error: function(){
                   // if it's not last one Move Along else update the cart number with the current quantity                    // if it's not last one Move Along else update the cart number with the current quantity
                   if (Shopify.queue.length){                    if (Shopify.queue.length){
                       Shopify.moveAlong()                        Shopify.moveAlong()
                   }                    }
               }                }
         });          });
       }        }
       // If the queue is empty, moving to cart        // If the queue is empty, moving to cart
       else {        else {
           if(pageHandle !== undefined && pageHandle == 'close'){            if(pageHandle !== undefined && pageHandle == 'close'){
               window.localStorage.removeItem(tempStorageName);                window.localStorage.removeItem(tempStorageName);
           }            }
   
           //GTM Add to cart from Quiz listing            //GTM Add to cart from Quiz listing
           //Build GTM Products            //Build GTM Products
           let allProducts = GTM_products.map(function(product, index) {            let allProducts = GTM_products.map(function(product, index) {
                   return {                    return {
                       name: product.title.replace("<sub>", '').replace('</sub>', ''),                        name: product.title.replace("<sub>", '').replace('</sub>', ''),
                       id: product.sku,                        id: product.sku,
                       price: product.price / 100,                        price: product.price / 100,
                       brand: product.vendor,                        brand: product.vendor,
                       position: index,                        position: index,
                       category: product.product_type                        category: product.product_type
                   };                    };
               });                });
         
           //P80 12/24/2019 - Facebook Events            //P80 12/24/2019 - Facebook Events
           //fbq('track', 'AddToCart');            //fbq('track', 'AddToCart');
           fbq('track', 'CompleteRegistration');            fbq('track', 'CompleteRegistration');
                     
           /*window.dataLayer.push({            /*window.dataLayer.push({
             event: "addToCart",              event: "addToCart",
              ecommerce: {               ecommerce: {
               actionField: {list: "Quiz"},                actionField: {list: "Quiz"},
                add: {                 add: {
                 products: allProducts                  products: allProducts
               }                }
             }              }
           });*/            });*/
                     
                 
         document.location.href = '/cart';          document.location.href = '/cart';
                     
                     
       }        }
   };    };
   Shopify.moveAlong();    Shopify.moveAlong();
   
} }
   
function openDeleteErrorModal(message) { function openDeleteErrorModal(message) {
   $('<div></div>').appendTo('body').html('<div><h6>' + message + '?</h6></div>')    $('<div></div>').appendTo('body').html('<div><h6>' + message + '?</h6></div>')
   .dialog({    .dialog({
       modal: true,        modal: true,
       title: '',        title: '',
       zIndex: 10000,        zIndex: 10000,
       autoOpen: true,        autoOpen: true,
       width: 'auto',        width: 'auto',
       resizable: false,        resizable: false,
        buttons: {         buttons: {
       "Close": function() {        "Close": function() {
   
         resumeAction =  true;          resumeAction =  true;
         startAction(resumeAction, resumePage);          startAction(resumeAction, resumePage);
         $(this).remove();          $(this).remove();
   
       }        }
     },      },
       close: function(event, ui) {        close: function(event, ui) {
       $(this).remove();        $(this).remove();
       }        }
   });    });
} }
   
function decodeEntities(encodedString) { function decodeEntities(encodedString) {
   
   var textArea = document.createElement('textarea');    var textArea = document.createElement('textarea');
     
   textArea.innerHTML = encodedString;    textArea.innerHTML = encodedString;
   return textArea.value;    return textArea.value;
     
 }  }
   
   
   
// function for popup resume modal // function for popup resume modal
function openModal(message,resumeAction, resumePage) { function openModal(message,resumeAction, resumePage) {
   $('<div></div>').appendTo('body')    $('<div></div>').appendTo('body')
   .html('<div><h4>' + message + '</h4></div>')    .html('<div><h4>' + message + '</h4></div>')
   .dialog({    .dialog({
       modal: true,        modal: true,
       title: '',        title: '',
       zIndex: 10000,        zIndex: 10000,
       autoOpen: true,        autoOpen: true,
       width: 'auto',        width: 'auto',
       resizable: false,        resizable: false,
       buttons: {        buttons: {
       "CONTINUE": function() {        "CONTINUE": function() {
   
           resumeAction =  true;            resumeAction =  true;
           startAction(resumeAction, resumePage);            startAction(resumeAction, resumePage);
           $(this).remove();            $(this).remove();
   
       },        },
       "START OVER": function() {        "START OVER": function() {
   
           resumeAction  = false;            resumeAction  = false;
           startAction(resumeAction, resumePage);            startAction(resumeAction, resumePage);
           $(this).remove();            $(this).remove();
   
       }        }
       },        },
       close: function(ele, ui) {        close: function(ele, ui) {
       resumeAction =  true;        resumeAction =  true;
       startAction(resumeAction, resumePage);        startAction(resumeAction, resumePage);
       $(this).remove();        $(this).remove();
       }        }
   });    });
   
} }
   
// function for popup surgery modal // function for popup surgery modal
function openSurgeryModal(ele) { function openSurgeryModal(ele) {
   
   message = "Good luck! Please check back after your surgery when you have doctor's clearance to change your nutritional program. Do you want us to remind you to check in afterwards?";    message = "Good luck! Please check back after your surgery when you have doctor's clearance to change your nutritional program. Do you want us to remind you to check in afterwards?";
   var buttonMessage1 = "Yes, Remind Me";    var buttonMessage1 = "Yes, Remind Me";
   var buttonMessage2 = "No Thanks, I'll Remember";    var buttonMessage2 = "No Thanks, I'll Remember";
   
   var resID = ele.find('input').data('respid');    var resID = ele.find('input').data('respid');
   var qnID = $('.question__title').data('qnid');    var qnID = $('.question__title').data('qnid');
   var qnNo = $('.question__title').data('qnno');    var qnNo = $('.question__title').data('qnno');
   
   var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));    var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));
   
   var email = quizStorage.Email.split('||')[0];    var email = quizStorage.Email.split('||')[0];
   var tag = 'exit-surgery';    var tag = 'exit-surgery';
   var uniqId = quizStorage.uniqueID;    var uniqId = quizStorage.uniqueID;
   
   var data = {    var data = {
       email:email,        email:email,
       tag:tag,        tag:tag,
       sessionID:uniqId,        sessionID:uniqId,
       responseID:resID,        responseID:resID,
       questionID:qnID,        questionID:qnID,
       questionNo:qnNo        questionNo:qnNo
   };    };
   //console.log(data);    //console.log(data);
   
   
   $('<div class="basic-profile-surgery--dialog-content"></div>').appendTo('body')    $('<div class="basic-profile-surgery--dialog-content"></div>').appendTo('body')
       .html('<div><h6>' + message + '</h6></div>')        .html('<div><h6>' + message + '</h6></div>')
       .dialog({        .dialog({
           modal: true,            modal: true,
           title: '',            title: '',
           zIndex: 10000,            zIndex: 10000,
           autoOpen: true,            autoOpen: true,
           width: 'auto',            width: 'auto',
           resizable: false,            resizable: false,
           buttons: {            buttons: {
               "Yes, Remind Me": function() {                "Yes, Remind Me": function() {
   
                   exitSurveyUpdate(data);                    exitSurveyUpdate(data);
   
                   $(this).remove();                    $(this).remove();
                   // window.localStorage.removeItem('quiz');                    // window.localStorage.removeItem('quiz');
                   // window.location.href = window.location.origin;                    // window.location.href = window.location.origin;
   
               },                },
               "No Thanks, I'll Remember": function() {                "No Thanks, I'll Remember": function() {
   
                   exitSurveyUpdate(data);                    exitSurveyUpdate(data);
   
                   $(this).remove();                    $(this).remove();
                   // window.localStorage.removeItem('quiz');                    // window.localStorage.removeItem('quiz');
                   // window.location.href = window.location.origin;                    // window.location.href = window.location.origin;
               }                }
           },            },
           close: function(event, ui) {            close: function(event, ui) {
               $(this).remove();                $(this).remove();
           }            }
       });        });
   
} }
// function for popup Vegan modal // function for popup Vegan modal
function openVeganModal(ele) { function openVeganModal(ele) {
   
   var inputValue = ele.find('input').val();    var inputValue = ele.find('input').val();
   var resID = ele.find('input').data('respid');    var resID = ele.find('input').data('respid');
   var qnID = $('.question__title').data('qnid');    var qnID = $('.question__title').data('qnid');
   
   if(inputValue.toLowerCase() == 'vegan'){    if(inputValue.toLowerCase() == 'vegan'){
       message = "Are you open to non-vegan products? If not, we'll email you when we have products that meet your needs. Until then, B12 is a great addition to a vegan diet.";        message = "Are you open to non-vegan products? If not, we'll email you when we have products that meet your needs. Until then, B12 is a great addition to a vegan diet.";
   }else{    }else{
       message = "Are you open to non-vegetarian products? If not, we'll email you when we have products that meet your needs. Until then, B12 is a great addition to a vegetarian diet.";        message = "Are you open to non-vegetarian products? If not, we'll email you when we have products that meet your needs. Until then, B12 is a great addition to a vegetarian diet.";
   }    }
   
   var buttonMessage1 = "Yes, I'm Open";    var buttonMessage1 = "Yes, I'm Open";
   var buttonMessage2 = 'No, Exit Survey';    var buttonMessage2 = 'No, Exit Survey';
   
   var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));    var quizStorage = JSON.parse(localStorage.getItem(tempStorageName));
   var email = quizStorage.Email.split('||')[0];    var email = quizStorage.Email.split('||')[0];
   
   var tag = '';    var tag = '';
   if(inputValue.toLowerCase() == 'vegan'){    if(inputValue.toLowerCase() == 'vegan'){
       tag = "exit-veganDiet";        tag = "exit-veganDiet";
   }else if(inputValue.toLowerCase() == 'vegetarian'){    }else if(inputValue.toLowerCase() == 'vegetarian'){
       tag = "exit-vegetarianDiet";        tag = "exit-vegetarianDiet";
   }    }
   
   var uniqId = quizStorage.uniqueID;    var uniqId = quizStorage.uniqueID;
   var data = {    var data = {
       email:email,        email:email,
       tag:tag,        tag:tag,
       sessionID:uniqId,        sessionID:uniqId,
       responseID:resID,        responseID:resID,
       questionID:qnID        questionID:qnID
   };    };
   //console.log(data);    //console.log(data);
   
   
   dialog = $('<div></div>').appendTo('body')    dialog = $('<div></div>').appendTo('body')
       .html('<div><h6>' + message + '</h6></div>')        .html('<div><h6>' + message + '</h6></div>')
       .dialog({        .dialog({
           modal: true,            modal: true,
           title: '',            title: '',
           zIndex: 10000,            zIndex: 10000,
           autoOpen: false,            autoOpen: false,
           width: 'auto',            width: 'auto',
           resizable: false,            resizable: false,
           buttons: {            buttons: {
               "Yes, I'm Open": function() {                "Yes, I'm Open": function() {
                   dialog.dialog( "close" );                    dialog.dialog( "close" );
                   ele.find('[data-action]').trigger('click');                    ele.find('[data-action]').trigger('click');
   
               },                },
               "No, Exit Survey": function() {                "No, Exit Survey": function() {
   
                   exitSurveyUpdate(data);                    exitSurveyUpdate(data);
                   // window.localStorage.removeItem(tempStorageName);                    // window.localStorage.removeItem(tempStorageName);
                   // window.location.href = window.location.origin;                    // window.location.href = window.location.origin;
               }                }
           },            },
           close: function(event, ui) {            close: function(event, ui) {
               $(this).remove();                $(this).remove();
           }            }
       });        });
   
       dialog.dialog( "open" );        dialog.dialog( "open" );
   
} }
   
function openDietModal(){ function openDietModal(){
   
   $('#dialog-form').show();    $('#dialog-form').show();
   
} }
   
// function for redirection according to resume quiz or startover quiz. // function for redirection according to resume quiz or startover quiz.
function startAction(resumeAction, resumePage){ function startAction(resumeAction, resumePage){
   //console.log('19');    //console.log('19');
   if (resumeAction == true) {    if (resumeAction == true) {
       if (resumePage == '') {        if (resumePage == '') {
           // if no blank entries go to last page            // if no blank entries go to last page
           resumePage = 'close';            resumePage = 'close';
           resumeURL = '?page=' + resumePage;            resumeURL = '?page=' + resumePage;
           resumeReq = '/pages/' + resumePage;            resumeReq = '/pages/' + resumePage;
       }        }
       var resumeObj = {        var resumeObj = {
           page: resumeURL,            page: resumeURL,
       };        };
   
       history.pushState(resumeObj, '', resumeURL);        history.pushState(resumeObj, '', resumeURL);
       loadQuiz('left', resumeReq, true);        loadQuiz('left', resumeReq, true);
   } else {    } else {
       $('body').addClass('quizLoaded');        $('body').addClass('quizLoaded');
       var uID = uniqueID();        var uID = uniqueID();
       var quizData = "{{ settings.quiz_data | strip | strip_newlines }}";        var quizData = "{{ settings.quiz_data | strip | strip_newlines }}";
       {% assign quizDatas = settings.quiz_data | split: "," %}        {% assign quizDatas = settings.quiz_data | split: "," %}
       quiz = {        quiz = {
           "uniqueID": uID,            "uniqueID": uID,
           {% for quizData in quizDatas %}            {% for quizData in quizDatas %}
           "{{ quizData | split: ':' | first | strip | strip_newlines }}": "||{{ quizData | split: ':' | last | strip_newlines }}"{% if forloop.last == true %}{% else %},{% endif %}            "{{ quizData | split: ':' | first | strip | strip_newlines }}": "||{{ quizData | split: ':' | last | strip_newlines }}"{% if forloop.last == true %}{% else %},{% endif %}
           {% endfor %}            {% endfor %}
       };        };
       setCustomerJSONNode();        setCustomerJSONNode();
       localStorage.setItem(tempStorageName, JSON.stringify(quiz));        localStorage.setItem(tempStorageName, JSON.stringify(quiz));
       autoAdvance();        autoAdvance();
   }    }
} }
   
function setCustomerJSONNode(){ function setCustomerJSONNode(){
   customer = {    customer = {
       "Email": "",        "Email": "",
       "Name" : ""        "Name" : ""
   }    }
   localStorage.setItem(customerStorage, JSON.stringify(customer));    localStorage.setItem(customerStorage, JSON.stringify(customer));
} }
   
function ValidateEmail(inputText){ function ValidateEmail(inputText){
   
   // var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,16})+$/;    // var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,16})+$/;
   var mailformat = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;    var mailformat = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if(inputText.match(mailformat))    if(inputText.match(mailformat))
   {    {
       return true;        return true;
   }    }
   else    else
   {    {
       return false;        return false;
   }    }
} }
   
function ValidateZip(inputText){ function ValidateZip(inputText){
   
   var zipformat = /(^\d{5}$)|(^\d{5}-\d{4}$)/;    var zipformat = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
   
   if(inputText.match(zipformat))    if(inputText.match(zipformat))
   {    {
       return true;        return true;
   }    }
   else    else
   {    {
       return false;        return false;
   }    }
} }
   
function clearRemainingNodeAfterSubmit(page){ function clearRemainingNodeAfterSubmit(page){
   
   //console.log('20');    //console.log('20');
   var flag = false;    var flag = false;
   
   $.each(quiz, function (key, value) {    $.each(quiz, function (key, value) {
   
       if(page === key){        if(page === key){
           flag = true;            flag = true;
           return;            return;
       }        }
   
       if(flag){        if(flag){
           var node = value.split('||');            var node = value.split('||');
           if (node[0].trim().length > 0 && node[0].trim() !== 'NA' && node[0].trim() !== 'uniqueID') {            if (node[0].trim().length > 0 && node[0].trim() !== 'NA' && node[0].trim() !== 'uniqueID') {
               quiz[key] = '||'+node[1];                quiz[key] = '||'+node[1];
           }            }
       }        }
   
   
   });    });
   
} }
   
// do not select NONE on with other questions (Q10, Q23) // do not select NONE on with other questions (Q10, Q23)
function callOptionChanges(ele){ function callOptionChanges(ele){
   //console.log('21');    //console.log('21');
   var input = ele.attr('data-value');    var input = ele.attr('data-value');
   var inputField = '';    var inputField = '';
   if(input == 'none'){    if(input == 'none'){
       var inputField = $(this);        var inputField = $(this);
       $('.quiz__content-box').each(function (i, obj) {        $('.quiz__content-box').each(function (i, obj) {
           $(obj).removeClass('selected');            $(obj).removeClass('selected');
       });        });
       $('.quizSectionInner input:checked').each(function (index, obj) {        $('.quizSectionInner input:checked').each(function (index, obj) {
   
           if($(obj).attr('data-value') == 'none'){            if($(obj).attr('data-value') == 'none'){
   
               if($(obj).is(':checked')){                if($(obj).is(':checked')){
                   // $(obj).closest('div').parent().addClass('selected');                    // $(obj).closest('div').parent().addClass('selected');
               } else{                } else{
                   $(obj).prop('checked', true);                    $(obj).prop('checked', true);
               }                }
               $('.quiz-wrapper').find('[data-action]').trigger('click');                $('.quiz-wrapper').find('[data-action]').trigger('click');
   
           }else{            }else{
               $(obj).prop('checked', false);                $(obj).prop('checked', false);
           }            }
   
       });        });
   
   }else{    }else{
   
       var checkEle = $('.quiz-wrapper').find('.none-specific-select');        var checkEle = $('.quiz-wrapper').find('.none-specific-select');
       if(checkEle.hasClass('selected')){        if(checkEle.hasClass('selected')){
           $(checkEle).find('input').prop('checked', false);            $(checkEle).find('input').prop('checked', false);
           $(checkEle).removeClass('selected');            $(checkEle).removeClass('selected');
       }        }
   }    }
} }
   
   
/*-------Q listing------- */ /*-------Q listing------- */
   
    var quizCount = 0;     var quizCount = 0;
    var clickElement = '';     var clickElement = '';
    var customer = '';     var customer = '';
    var token ='';     var token ='';
   
   
    function triggerAPI(path, params, method){     function triggerAPI(path, params, method){
         // Live test middleware          // Live test middleware
         var url = "//amber.pharmavite.net/quiz/quiz/"+path;          var url = "//amber.pharmavite.net/quiz/quiz/"+path;
   
         //p80 dev.          //p80 dev.
         //var url = "https://nurish.p80w.com/staging/nurish-quiz/public/quiz/"+path;          //var url = "https://nurish.p80w.com/staging/nurish-quiz/public/quiz/"+path;
   
         var productList = [];          var productList = [];
   
         dataParam = JSON.stringify(params);          dataParam = JSON.stringify(params);
   
         $.ajax({          $.ajax({
             url: url,              url: url,
             contentType: "application/json",              contentType: "application/json",
             method: method,              method: method,
             data : dataParam,              data : dataParam,
             success: function (data) {              success: function (data) {
               console.log(data);                console.log(data);
               //Scrub PII                //Scrub PII
               var gtm_response = params.responses;                var gtm_response = params.responses;
                                 
               if(params.page == 'email') {                if(params.page == 'email') {
                                     
                  window.dataLayer.push({                   window.dataLayer.push({
                   event: 'captureLead'                    event: 'captureLead'
                 });                  });
                                     
                 gtm_response = '';                  gtm_response = '';
                                     
               }                }
                                 
               if(params.page == 'environment-zipcode') {                if(params.page == 'environment-zipcode') {
                                     
                 gtm_response = '';                  gtm_response = '';
                                     
               }                }
               // end PII scrub                // end PII scrub
                                 
                //GTM Integration                 //GTM Integration
                window.dataLayer.push({                 window.dataLayer.push({
                  event: 'quizSubmit',                   event: 'quizSubmit',
                  question: params.question,                   question: params.question,
                  page: params.page,                   page: params.page,
                  responses: gtm_response,                   responses: gtm_response,
                  questionID: params.questionID,                   questionID: params.questionID,
                  questionNo: params.questionNo,                   questionNo: params.questionNo,
                  responseIDs: params.responseIDs,                   responseIDs: params.responseIDs,
                  responseKeys: params.responseKeys,                   responseKeys: params.responseKeys,
                  sessionID: params.sessionID                   sessionID: params.sessionID
                 });                  });
   
                                 
                 if(path == 'getQuizzes' && data){                  if(path == 'getQuizzes' && data){
                   setQuizzes(data, params.page);                    setQuizzes(data, params.page);
                 }                  }
                 if(path == 'deleteQuiz' && data.body.deleted == true){                  if(path == 'deleteQuiz' && data.body.deleted == true){
                   showDeletedResponse(data)                    showDeletedResponse(data)
                 }                  }
                 if(path == 'getRecommendation' && data.body.recommendation){                  if(path == 'getRecommendation' && data.body.recommendation){
                   setRecommendations(data);                    setRecommendations(data);
                 }/*else{                  }/*else{
                     $('.question__results-text').text('No recommended items found...');                      $('.question__results-text').text('No recommended items found...');
                 }*/                  }*/
                 if(path == 'storeQuizResponse' && data.body.Recommendation != undefined){                  if(path == 'storeQuizResponse' && data.body.Recommendation != undefined){
   
                   var recommendaionResp = data.body.Recommendation;                    var recommendaionResp = data.body.Recommendation;
                   if(recommendaionResp && recommendaionResp.length > 0){                    if(recommendaionResp && recommendaionResp.length > 0){
                       productList = recommendaionResp;                        productList = recommendaionResp;
                       addItemsToCart(productList);                        addItemsToCart(productList);
                   }                    }
                 }                  }
                 if(path == 'exitQuizTag'){                  if(path == 'exitQuizTag'){
                   window.localStorage.removeItem(tempStorageName);                    window.localStorage.removeItem(tempStorageName);
                   window.location.href = window.location.origin;                    window.location.href = window.location.origin;
                 }                  }
             }, error: function (xhr, status, error) {              }, error: function (xhr, status, error) {
                 console.log(error);                  console.log(error);
                 throw new Error('error : Unable to complete Ajax Request ', error);                  throw new Error('error : Unable to complete Ajax Request ', error);
                 return false;                  return false;
             }              }
         });          });
    }     }
   
    function exitSurveyUpdate(data){     function exitSurveyUpdate(data){
       var method = 'POST';        var method = 'POST';
       var path   = 'exitQuizTag';        var path   = 'exitQuizTag';
       var params = data;        var params = data;
       triggerAPI(path, params,method);        triggerAPI(path, params,method);
    }     }
   
    function getCustomerQuiz( page, email, tok){     function getCustomerQuiz( page, email, tok){
         customer = email;          customer = email;
         token = tok;          token = tok;
         if(customer.length > 0){          if(customer.length > 0){
           // var records  = 6;            // var records  = 6;
           $('#customer-login').hide();            $('#customer-login').hide();
           var method = 'POST';            var method = 'POST';
           var path   = 'getQuizzes';            var path   = 'getQuizzes';
           var params = {email:customer,page:page,token:token}            var params = {email:customer,page:page,token:token}
           triggerAPI(path, params,method);            triggerAPI(path, params,method);
   
         }else{          }else{
           $('#cart-loader').hide();            $('#cart-loader').hide();
         }          }
   
    }     }
   
   
    function deleteQuiz(quizID, element){     function deleteQuiz(quizID, element){
   
     var method = 'DELETE';      var method = 'DELETE';
     var path   = 'deleteQuiz';      var path   = 'deleteQuiz';
     var params = {"email":customer,"quizId" : quizID,"token":token};      var params = {"email":customer,"quizId" : quizID,"token":token};
     var response = triggerAPI(path, params,method);      var response = triggerAPI(path, params,method);
   
    }     }
   
    function showDeletedResponse(response){     function showDeletedResponse(response){
       if(response)        if(response)
       {        {
         clickElement.closest('.quiz-inner').remove();          clickElement.closest('.quiz-inner').remove();
       }        }
       else        else
       {        {
         var msg = response.body.error;          var msg = response.body.error;
         openDeleteErrorModal(msg);          openDeleteErrorModal(msg);
       }        }
    }     }
   
   
    function setQuizzes(quizData, page){     function setQuizzes(quizData, page){
   
      var quizHtml = '';       var quizHtml = '';
   
      if(quizData.body.quizzes && quizData.body.quizzes.length > 0){       if(quizData.body.quizzes && quizData.body.quizzes.length > 0){
   
        var quizzes = quizData.body.quizzes;         var quizzes = quizData.body.quizzes;
   
        var hasNext = quizData.body.hasNext;         var hasNext = quizData.body.hasNext;
        var pageNumber = quizData.body.pageNumber;         var pageNumber = quizData.body.pageNumber;
   
        $.each(quizzes, function (key, value) {         $.each(quizzes, function (key, value) {
         var end_date = value.endDate;          var end_date = value.endDate;
         var dateOnly = end_date.split(' ');          var dateOnly = end_date.split(' ');
         var newdate = new Date(dateOnly[0]);          var newdate = new Date(dateOnly[0]);
           var dd = newdate.getDate();            var dd = newdate.getDate();
           var mm = newdate.getMonth() + 1;            var mm = newdate.getMonth() + 1;
           var y = newdate.getFullYear().toString().substr(-2);            var y = newdate.getFullYear().toString().substr(-2);
           end_date = mm + '/' + dd + '/' + y;            end_date = mm + '/' + dd + '/' + y;
         quizCount = quizCount+1;          quizCount = quizCount+1;
         if ( quizData.body.quizzes.length == 1 ) {          if ( quizData.body.quizzes.length == 1 ) {
           quizHtml += '<div class="grid__item medium-up--two-quarters medium-up--push-one-quarter"><div class="quiz-inner">';            quizHtml += '<div class="grid__item medium-up--two-quarters medium-up--push-one-quarter"><div class="quiz-inner">';
         } else {          } else {
           quizHtml += '<div class="grid__item medium-up--one-half"><div class="quiz-inner">';            quizHtml += '<div class="grid__item medium-up--one-half"><div class="quiz-inner">';
         }          }
   
         quizHtml += '<div class="box-wrap">';          quizHtml += '<div class="box-wrap">';
   
         quizHtml += '<h3> Quiz '+ end_date +' <span quiz-id="'+value.quizID+'"><img src="{{ 'icon-trash.svg' | file_url }}" title="Delete Quiz" quiz-id="'+value.quizID+'" class="quiz-delete" alt="icon delete"></span></h3>';          quizHtml += '<h3> Quiz '+ end_date +' <span quiz-id="'+value.quizID+'"><img src="{{ 'icon-trash.svg' | file_url }}" title="Delete Quiz" quiz-id="'+value.quizID+'" class="quiz-delete" alt="icon delete"></span></h3>';
   
         quizHtml += '<div class="retake-outer hide clearfix">';          quizHtml += '<div class="retake-outer hide clearfix">';
   
         for(var i=0; i < value.interests.length; i++) {          for(var i=0; i < value.interests.length; i++) {
           var interest_value = value.interests[i];            var interest_value = value.interests[i];
           var icon_handle = interest_value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, '').replace(/^-/, '');            var icon_handle = interest_value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-$/, '').replace(/^-/, '');
           var icon_url = "https://cdn.shopify.com/s/files/1/0068/2586/9383/files/icon-"+icon_handle+".png"            var icon_url = "https://cdn.shopify.com/s/files/1/0068/2586/9383/files/icon-"+icon_handle+".png"
           quizHtml += '<div class="retake-inner">';            quizHtml += '<div class="retake-inner">';
           quizHtml += '<input type="hidden" name="retake" quiz-id="'+value.quizID+'" value="'+interest_value+'"></label>';            quizHtml += '<input type="hidden" name="retake" quiz-id="'+value.quizID+'" value="'+interest_value+'"></label>';
           quizHtml += '<div class="quiz__content-box--image"><img src="'+icon_url+'" alt="icon '+icon_handle+'"></div>';            quizHtml += '<div class="quiz__content-box--image"><img src="'+icon_url+'" alt="icon '+icon_handle+'"></div>';
           quizHtml += '<div class="quiz__content-box--description"><span>'+interest_value+'</span></div>';            quizHtml += '<div class="quiz__content-box--description"><span>'+interest_value+'</span></div>';
           quizHtml += '</div>';            quizHtml += '</div>';
         }          }
   
         quizHtml += '</div>';          quizHtml += '</div>';
   
         /*          /*
         quizHtml += '<div class="quiz__content-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s</div>';          quizHtml += '<div class="quiz__content-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s</div>';
         */          */
   
         quizHtml += '<h6><a class="recommended-products" quiz-id="'+value.sessionID+'" href="/pages/recommendations?id='+value.sessionID+'">VIEW RECOMMENDED PRODUCTS <svg width="23" height="7" viewBox="0 0 23 7" fill="none" class="arrow"><path d="M1 3H0.5V4H1V3ZM22.1351 3.5L17.1351 0.613249V6.38675L22.1351 3.5ZM1 4H17.6351V3H1V4Z" fill="#30AC71"/></svg></a></h6>';          quizHtml += '<h6><a class="recommended-products" quiz-id="'+value.sessionID+'" href="/pages/recommendations?id='+value.sessionID+'">VIEW RECOMMENDED PRODUCTS <svg width="23" height="7" viewBox="0 0 23 7" fill="none" class="arrow"><path d="M1 3H0.5V4H1V3ZM22.1351 3.5L17.1351 0.613249V6.38675L22.1351 3.5ZM1 4H17.6351V3H1V4Z" fill="#30AC71"/></svg></a></h6>';
   
         quizHtml += '</div>';          quizHtml += '</div>';
   
         quizHtml += '</div></div>';          quizHtml += '</div></div>';
   
        });         });
   
   
        $('#cart-loader').hide();         $('#cart-loader').hide();
      }else{       }else{
       $('#cart-loader').hide();        $('#cart-loader').hide();
       quizHtml+='<div class="grid__item"><div class="box-wrap"><hr class="hr--invisible"><div class="empty-content text-center"><h2 class="h3 cart-header__sub-title text-center title">You Haven’t Taken Any Quizzes</h2><p> <a href="/pages/quiz-landing" class="btn"> Take Quiz </a> </p><p><a href="/collections/our-products" class="cart__continue-btn btn--link">Browse Products</a></p></div><hr class="hr--invisible"></div></div><hr class="hr--invisible" />'        quizHtml+='<div class="grid__item"><div class="box-wrap"><hr class="hr--invisible"><div class="empty-content text-center"><h2 class="h3 cart-header__sub-title text-center title">You Haven’t Taken Any Quizzes</h2><p> <a href="/pages/quiz-landing" class="btn"> Take Quiz </a> </p><p><a href="/collections/our-products" class="cart__continue-btn btn--link">Browse Products</a></p></div><hr class="hr--invisible"></div></div><hr class="hr--invisible" />'
      }       }
   
      //quizHtml += '<div class="clear"></div>';       //quizHtml += '<div class="clear"></div>';
   if(quizData.body.quizzes && quizData.body.quizzes.length > 0){    if(quizData.body.quizzes && quizData.body.quizzes.length > 0){
      var startQuiz = '';       var startQuiz = '';
      startQuiz += '<div class="startQuizButton"><hr class="hr--invisible hr--medium"><div class="quiz-action text-center">';       startQuiz += '<div class="startQuizButton"><hr class="hr--invisible hr--medium"><div class="quiz-action text-center">';
      startQuiz += '<a href="/pages/quiz-landing" class="btn btn-retake">Start Quiz Over</a><hr class="hr--invisible hr--small">';       startQuiz += '<a href="/pages/quiz-landing" class="btn btn-retake">Start Quiz Over</a><hr class="hr--invisible hr--small">';
      if(hasNext || hasNext == 'true'){       if(hasNext || hasNext == 'true'){
           page = parseInt(page);            page = parseInt(page);
           $('#show_more_main'+page).remove();            $('#show_more_main'+page).remove();
           page = page+1;            page = page+1;
   
           startQuiz += '<div class="show_more_main" id="show_more_main'+page+'">';            startQuiz += '<div class="show_more_main" id="show_more_main'+page+'">';
           startQuiz += '<a href="javascript:void(0)" class="btn show_more" page="'+page+'" title="Load more quizzes">See More</a>';            startQuiz += '<a href="javascript:void(0)" class="btn show_more" page="'+page+'" title="Load more quizzes">See More</a>';
           startQuiz += '<span class="loading" style="display: none;"><span class="loading_txt">Loading...</span></span>';            startQuiz += '<span class="loading" style="display: none;"><span class="loading_txt">Loading...</span></span>';
           startQuiz += '</div>';            startQuiz += '</div>';
      }       }
      startQuiz += '</div>';       startQuiz += '</div>';
      startQuiz += '</div></div>';       startQuiz += '</div></div>';
   }    }
   
      $('.loading').hide();       $('.loading').hide();
   
      $('#load-quizzes').append(quizHtml);       $('#load-quizzes').append(quizHtml);
      $('.startQuizButton').remove();       $('.startQuizButton').remove();
      $(startQuiz).insertAfter( $( "#load-quizzes" ) );       $(startQuiz).insertAfter( $( "#load-quizzes" ) );
   
    }     }
   
   function setRecommendations(dataResponse){    function setRecommendations(dataResponse){
   
     setTimeout(function(){      setTimeout(function(){
       jQuery.post('/cart/clear.js', { });        jQuery.post('/cart/clear.js', { });
     },100)      },100)
   
     if(dataResponse && dataResponse.body.recommendation.length > 0){      if(dataResponse && dataResponse.body.recommendation.length > 0){
         var recommendation = dataResponse.body.recommendation          var recommendation = dataResponse.body.recommendation
         recommendation = JSON.parse(recommendation);          recommendation = JSON.parse(recommendation);
         addItemsToCart(recommendation);          addItemsToCart(recommendation);
   
     }      }
   
   }    }
   
   function getRecommendedItems(id, cDetails){    function getRecommendedItems(id, cDetails){
   
     var method = 'POST';      var method = 'POST';
     var path   = 'getRecommendation';      var path   = 'getRecommendation';
     var params = {"sessionID" : id,"token":cDetails.token,"email":cDetails.customer}      var params = {"sessionID" : id,"token":cDetails.token,"email":cDetails.customer}
     triggerAPI(path, params,method);      triggerAPI(path, params,method);
   
   }    }
   
   
   var getUrlParameter = function getUrlParameter(sParam) {    var getUrlParameter = function getUrlParameter(sParam) {
       var sPageURL = window.location.search.substring(1),        var sPageURL = window.location.search.substring(1),
           sURLVariables = sPageURL.split('&'),            sURLVariables = sPageURL.split('&'),
           sParameterName,            sParameterName,
           i;            i;
   
       for (i = 0; i < sURLVariables.length; i++) {        for (i = 0; i < sURLVariables.length; i++) {
           sParameterName = sURLVariables[i].split('=');            sParameterName = sURLVariables[i].split('=');
   
           if (sParameterName[0] === sParam) {            if (sParameterName[0] === sParam) {
               return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
           }            }
       }        }
   };    };