$(document).ready(function () {
    var current_fs, next_fs, previous_fs; // Fieldsets
    var opacity;
    var current = 1;
    var steps = $("fieldset").length;
    var progressStartValue = 0;
    var progressEndValue = 100;
    var totalDuration = 4500; // 4.5 seconds
    var speed = totalDuration / progressEndValue; // Calculate the interval speed

    setProgressBar(current);
    $(".next").prop("disabled", true); // Initially disable the "Next" button

    function goToNextStep() {
        if (current < steps) {
            transitionToNextStep();
        }
    }

function transitionToNextStep() {
    current_fs = $("fieldset").eq(current - 1);
    next_fs = $("fieldset").eq(current);

    // Reset styles for current and next fieldsets
    current_fs.css({ display: "none", opacity: 1 });
    next_fs.css({ display: "block", opacity: 0 });

        $('html, body').animate({
            scrollTop: next_fs.offset().top
        }, 500);

        next_fs.show();
        current_fs.animate({ opacity: 0 }, {
            step: function (now) {
                opacity = 1 - now;
                current_fs.css({ display: "none", position: "relative" });
                next_fs.css({ opacity: opacity });
            },
            duration: 500
        });

        setProgressBar(++current);
        enableNextButton();
		
        if (current === 18) {
            $(".progress").hide();
        }

        if (current === 1) {
          $(".progress").addClass("hidden-progress");
      } else {
          $(".progress").removeClass("hidden-progress");
      }
    }

    function autoAdvance() {
        if ($("fieldset").eq(current - 1).find(".auto-advance:checked").length > 0) {
            transitionToNextStep();
        }
    }
	
function autoAdvanceImg() {
    if ($("fieldset").eq(current - 1).find(".auto-advanceImg:checked").length === 3) {
        transitionToNextStep();
    }
}

function enableNextButton() {
    var currentFieldset = $("fieldset").eq(current - 1);
    var isValid = true; // Assume valid unless a check fails

    // Check if general inputs (radio or checkbox) are selected
    if (currentFieldset.find("input[type=radio], input[type=checkbox]").length > 0) {
        isValid = currentFieldset.find("input[type=radio]:checked, input[type=checkbox]:checked").length > 0;
    }

    // Additional check for .limit3 class - enable only if exactly 3 are selected
    if (currentFieldset.find(".limit3").length > 0) {
        isValid = currentFieldset.find(".limit3:checked").length === 3;
    }

    $(".next").prop("disabled", !isValid);
}


    // Event listener for all inputs to enable the Next button
    $("fieldset").on("change", "input[type=radio], input[type=checkbox]", function () {
        // Check if it's an auto-advance input
        if ($(this).hasClass("auto-advance")) {
            autoAdvance();
        } else {
            // For non-auto-advance inputs, just enable the Next button
            enableNextButton();
        }
    });

    // Event listener for auto-advance inputs
    $("fieldset").on("change", ".auto-advance", function () {
        autoAdvance();
    });
	
	$("fieldset").on("change", ".auto-advanceImg", function () {
		autoAdvanceImg();
	});


    // Event listener for other inputs, just enabling the Next button
    $("fieldset input[type=radio], fieldset input[type=checkbox]").not(".auto-advance").on("change", function () {
        enableNextButton();
    });

    $(".next").click(function () {
        transitionToNextStep();
    });

    $(".previous").click(function () {
        current_fs = $(this).parent();
        previous_fs = $(this).parent().prev();

        $('html, body').animate({
            scrollTop: previous_fs.offset().top
        }, 500);

        previous_fs.show();
        current_fs.animate({ opacity: 0 }, {
            step: function (now) {
                opacity = 1 - now;
                current_fs.css({ display: "none", position: "relative" });
                previous_fs.css({ opacity: opacity });
            },
            duration: 500
        });

        setProgressBar(--current);
        enableNextButton();
    });

    function setProgressBar(curStep) {
      if (curStep === 1) {
          $(".progress").addClass("hidden-progress");
      } else {
          $(".progress").removeClass("hidden-progress");
          var percent = parseFloat((100 / steps) * curStep).toFixed();
          $(".progress-bar").css("width", percent + "%");
      }
  }

    $("#startButton").click(function () {
        $(this).prop("disabled", true);
        let progressInterval = setInterval(function () {
            progressStartValue++;
            $(".progress-value").text(`${progressStartValue}%`);
            $(".circular-progress").css("background", `conic-gradient(#27AE60 ${progressStartValue * 3.6}deg, #ededed 0deg)`);

            if (progressStartValue >= progressEndValue) {
                clearInterval(progressInterval);
                //setTimeout(function () {
                //   hideParagraphsSequentially();
                //}, 500); // 1 second delay
				hideParagraphsSequentially();
            }
        }, speed);
    });

    function hideParagraphsSequentially() {
        let index = 0;
        let paragraphs = $(".hidden-paragraph");
        let delayFactor = 0.2; // Adjust this value to decrease or increase the delay
        let delay = (totalDuration / paragraphs.length) * delayFactor;

        function hideNextParagraph() {
          if (index < paragraphs.length) {
              paragraphs.eq(index).hide();
              index++;
              setTimeout(hideNextParagraph, delay);
          } else {
              showNextStep();
          }
      }

        hideNextParagraph();
    }

    function showNextStep() {
        transitionToNextStep();
    }

    // Handling step changes and tooltip visibility
    function handleStepChange(className, displayDivId) {
        $(`.${className}`).on('change', function () {
            // Check if any checkbox with this class is checked
            var isChecked = $(`.${className}:checked`).length > 0;

            if (isChecked) {
                $(`#${displayDivId}`).css('display', 'block');
            } else {
                $(`#${displayDivId}`).css('display', 'none');
            }
            $('.next').prop('disabled', false);
        });
    }

    handleStepChange('tooltip1', 'displayDiv1');
    handleStepChange('tooltip2', 'displayDiv2');
    handleStepChange('tooltip12', 'displayDiv12');
    handleStepChange('tooltip14', 'displayDiv14');
    handleStepChange('tooltip15', 'displayDiv15');
    // ... additional steps as needed
});

$(document).ready(function() {
    $('.limit3').on('change', function() {
        if($('.limit3:checked').length > 3) {
            this.checked = false;
            //alert('You can only select 3 options.');
        }
    });
});

var selectedGender;

$('.next').click(function() {
    selectedGender = $('input[name="step1"]:checked').val();

    // Update text based on the selected gender
    if (selectedGender === "Male") {
        $('.hung').text("How hung are you?");
    } else if (selectedGender === "Female") {
        $('.hung').text("How big do you prefer?");
    }
    if (selectedGender === "Male") {
        $('.shortage').text("We have detected a shortage of men in your area.");
    } else if (selectedGender === "Female") {
        $('.shortage').text("We have detected a shortage of users in your area.");
    }
});
