/* Mobile Menu */
let mtoggle = document.querySelector('#mobile-toggle');
let mnav = document.querySelector('.m-nav');

mtoggle.addEventListener('click', () => {
  console.log('test');
  mtoggle.classList.toggle('active');
  mnav.classList.toggle('active');
})

/* Slick Carousel */
$(document).ready(function(){
	$('.carousel').each(function() {
		var _this = $(this);
		$(this).slick({
			slide: '.carousel-item',
			arrows: true,
			dots: true,
			fade: true,
			prevArrow: $(_this).find(".slide-prev"),
      		nextArrow: $(_this).find(".slide-next"),
			appendDots: $(_this).find(".slide-dots"),
			adaptiveHeight: true
	  	});
    });
	/* Slick Carousel */
	$('.auto-carousel').each(function() {
		var _this = $(this);
		$(this).slick({
			slide: '.carousel-item',
			speed: 800,
			autoplay: true,
  			autoplaySpeed: 10000,
			arrows: true,
			dots: true,
			fade: true,
			prevArrow: $(_this).find(".slide-prev"),
      		nextArrow: $(_this).find(".slide-next"),
			appendDots: $(_this).find(".slide-dots"),
			adaptiveHeight: true
	  	});
    });
	$("form").on("submit",function(e){
		var isOK = true,
			_form = $(this);
		_form.find(".error").removeClass("error");
		_form.find("label.freeform-required").each(function(){
			var _field = $(this).next();
			if (_field.val() == "") {
				_field.addClass("error");
				isOK = false;
			}
		});
		if (!isOK){e.preventDefault();}
		return isOK;
	});
	
	$('.blog-cats').slick({
		arrows: true,
		dots: false,
		fade: false,
		slidesToShow: 4,
        slidesToScroll: 1,
		variableWidth: true,
		infinite: true,
		prevArrow: '<button type="button" class="slick-prev"><svg xmlns="http://www.w3.org/2000/svg" width="21" height="37" viewBox="0 0 21 37" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M19.8373 3.98241C20.5197 3.29997 20.5197 2.19353 19.8373 1.51109C19.1549 0.828659 18.0484 0.828659 17.366 1.51109L1.51161 17.3655C1.16928 17.7078 0.998671 18.1568 0.999792 18.6055C0.998671 19.0542 1.16928 19.5032 1.51161 19.8456L17.366 35.6999C18.0484 36.3824 19.1549 36.3824 19.8373 35.6999C20.5197 35.0175 20.5197 33.9111 19.8373 33.2286L5.21419 18.6055L19.8373 3.98241Z" fill="#171E49"/><path d="M19.8373 1.51109L19.4254 1.92298L19.8373 1.51109ZM19.8373 3.98241L20.2492 4.39429L20.2492 4.39429L19.8373 3.98241ZM17.366 1.51109L16.9541 1.09921L17.366 1.51109ZM1.51161 17.3655L1.9235 17.7773L1.9235 17.7773L1.51161 17.3655ZM0.999792 18.6055L1.58229 18.607L1.58229 18.6041L0.999792 18.6055ZM1.51161 19.8456L1.9235 19.4337L1.9235 19.4337L1.51161 19.8456ZM17.366 35.6999L16.9541 36.1118H16.9541L17.366 35.6999ZM19.8373 35.6999L20.2492 36.1118H20.2492L19.8373 35.6999ZM19.8373 33.2286L19.4254 33.6405H19.4254L19.8373 33.2286ZM5.21419 18.6055L4.8023 18.1936L4.39042 18.6055L4.8023 19.0174L5.21419 18.6055ZM19.4254 1.92298C19.8804 2.37794 19.8804 3.11557 19.4254 3.57052L20.2492 4.39429C21.1591 3.48438 21.1591 2.00912 20.2492 1.09921L19.4254 1.92298ZM17.7779 1.92298C18.2328 1.46802 18.9705 1.46802 19.4254 1.92298L20.2492 1.09921C19.3393 0.189295 17.864 0.189295 16.9541 1.09921L17.7779 1.92298ZM1.9235 17.7773L17.7779 1.92298L16.9541 1.09921L1.09973 16.9536L1.9235 17.7773ZM1.58229 18.6041C1.58154 18.304 1.69517 18.0057 1.9235 17.7773L1.09973 16.9536C0.643383 17.4099 0.415806 18.0096 0.417299 18.607L1.58229 18.6041ZM0.417299 18.6041C0.415806 19.2014 0.643383 19.8011 1.09973 20.2575L1.9235 19.4337C1.69517 19.2054 1.58154 18.907 1.58229 18.607L0.417299 18.6041ZM1.09973 20.2575L16.9541 36.1118L17.7779 35.2881L1.9235 19.4337L1.09973 20.2575ZM16.9541 36.1118C17.864 37.0217 19.3393 37.0217 20.2492 36.1118L19.4254 35.2881C18.9705 35.743 18.2328 35.743 17.7779 35.2881L16.9541 36.1118ZM20.2492 36.1118C21.1591 35.2019 21.1591 33.7267 20.2492 32.8167L19.4254 33.6405C19.8804 34.0955 19.8804 34.8331 19.4254 35.2881L20.2492 36.1118ZM20.2492 32.8167L5.62607 18.1936L4.8023 19.0174L19.4254 33.6405L20.2492 32.8167ZM19.4254 3.57052L4.8023 18.1936L5.62607 19.0174L20.2492 4.39429L19.4254 3.57052Z" fill="#171E49"/></svg></button>',
		nextArrow: '<button type="button" class="slick-next"><svg xmlns="http://www.w3.org/2000/svg" width="21" height="37" viewBox="0 0 21 37" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.51427 33.2285C0.831833 33.911 0.831833 35.0174 1.51427 35.6998C2.1967 36.3823 3.30315 36.3823 3.98558 35.6998L19.8399 19.8455C20.1822 19.5032 20.3528 19.0543 20.3518 18.6057C20.353 18.1569 20.1823 17.7078 19.84 17.3654L3.98558 1.511C3.30315 0.828567 2.1967 0.828567 1.51427 1.511C0.831833 2.19344 0.831833 3.29988 1.51427 3.98232L16.1374 18.6054L1.51427 33.2285Z" fill="#171E49"/><path d="M1.51427 35.6998L1.92615 35.288L1.51427 35.6998ZM1.51427 33.2285L1.10238 32.8166H1.10238L1.51427 33.2285ZM3.98558 35.6998L4.39747 36.1117L3.98558 35.6998ZM19.8399 19.8455L19.4281 19.4336L19.4281 19.4336L19.8399 19.8455ZM20.3518 18.6057L19.7693 18.6041L19.7693 18.607L20.3518 18.6057ZM19.84 17.3654L19.4281 17.7773L19.84 17.3654ZM3.98558 1.511L4.39747 1.09912L4.39747 1.09912L3.98558 1.511ZM1.51427 1.511L1.10238 1.09912H1.10238L1.51427 1.511ZM1.51427 3.98232L1.92615 3.57043L1.92615 3.57043L1.51427 3.98232ZM16.1374 18.6054L16.5493 19.0173L16.9611 18.6054L16.5493 18.1935L16.1374 18.6054ZM1.92615 35.288C1.4712 34.833 1.4712 34.0954 1.92615 33.6404L1.10238 32.8166C0.192469 33.7266 0.192469 35.2018 1.10238 36.1117L1.92615 35.288ZM3.5737 35.288C3.11874 35.7429 2.38111 35.7429 1.92615 35.288L1.10238 36.1117C2.01229 37.0216 3.48755 37.0216 4.39747 36.1117L3.5737 35.288ZM19.4281 19.4336L3.5737 35.288L4.39747 36.1117L20.2518 20.2574L19.4281 19.4336ZM19.7693 18.607C19.77 18.907 19.6564 19.2053 19.4281 19.4336L20.2518 20.2574C20.7081 19.8011 20.9357 19.2015 20.9343 18.6043L19.7693 18.607ZM20.9343 18.6072C20.9358 18.0098 20.7083 17.4099 20.2518 16.9535L19.4281 17.7773C19.6564 18.0056 19.7701 18.304 19.7693 18.6041L20.9343 18.6072ZM20.2518 16.9535L4.39747 1.09912L3.5737 1.92289L19.4281 17.7773L20.2518 16.9535ZM4.39747 1.09912C3.48755 0.189205 2.01229 0.189205 1.10238 1.09912L1.92615 1.92289C2.38111 1.46793 3.11874 1.46793 3.5737 1.92289L4.39747 1.09912ZM1.10238 1.09912C0.192469 2.00903 0.192469 3.48429 1.10238 4.3942L1.92615 3.57043C1.4712 3.11547 1.4712 2.37784 1.92615 1.92289L1.10238 1.09912ZM1.10238 4.3942L15.7255 19.0173L16.5493 18.1935L1.92615 3.57043L1.10238 4.3942ZM1.92615 33.6404L16.5493 19.0173L15.7255 18.1935L1.10238 32.8166L1.92615 33.6404Z" fill="#171E49"/></svg></button>',
		responsive: [
		  {
			breakpoint: 980,
			settings: {
			  slidesToShow: 4,
			  slidesToScroll: 1,
			  centerPadding: '0px',
			}
		  },
		  {
			breakpoint: 680,
			settings: {
			  slidesToShow: 3,
			  slidesToScroll: 1,
			  centerPadding: '0px',
			}
		  },
		  {
			breakpoint: 480,
			settings: {
			variableWidth: false,
			  slidesToShow: 2,
			  slidesToScroll: 1,
			  centerPadding: '0px',
			}
		  }
		]
	});
    $("ul[role=tablist] li button").on("click",function(e){
    	e.preventDefault();
        var parent_ul = $(this).closest("ul"),
        	parent_content = $(parent_ul.data("tabsToggle"));
        parent_ul.find("button").removeClass("active");
        parent_content.find("[role='tabpanel']").addClass("hidden");
        $(this).addClass("active");
        $($(this).data("tabsTarget")).removeClass("hidden");
    });
});

/* Field Required */
if ( $(".field-required").length ) {
  $('.field-required').each(function() {
    $(this).attr('required', '')
  })
}
if ( $("#scroll-indicator").length ) {
  jQuery(function($) {
	var PageH = $(document).height();
	var WindowH = $(window).height();
	var NewPageH = PageH-WindowH;
	$(window).scroll(function() {
	   var Scrolled = $(window).scrollTop();
	   var NewWidth = Scrolled/NewPageH*100;
	   $('#scroll-indicator span').css('width',NewWidth+'%');
	 });
  });
}
$(document).ready(function(){
	//set the click listener on pagination
    paginationClickHandler();
	featClickHandler();
    
    $(".showShareButtons").on("click",function(event){event.preventDefault();});
    
    $('.share-link').on("click",function(event){
    	event.preventDefault();
        
        copyToClipboard(window.location.href);
        $(this).css("position","relative");
        var _tooltip = $("<span></span>");
        _tooltip
        	.attr("id","copyToClipboardSuccess")
            .text("URL copied to clipboard");
        $(this).append(_tooltip);
        setTimeout("$('#copyToClipboardSuccess').css('opacity',1)",5);
        setTimeout("$('#copyToClipboardSuccess').css('opacity',0)",2500);
        setTimeout("$('#copyToClipboardSuccess').remove()",3000);
    });
});

function copyToClipboard(text) {
	var dummy = document.createElement('input');

	dummy.style.position="fixed";
    dummy.style.top="-200px";
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);
}

function paginationClickHandler() {
	$(".pagination a").click(function(e){
    	e.preventDefault();

        //link to the next set of articles
        var href = $(this).attr("href");

        //get new articles and pagination
        $.get(href, {}, function(data){
        	//remove existing pagination
            $(".pagination").remove();

            //add new articles and pagination links
            $("#articles").append(data);

            //disable pagination click listener
            $('.pagination a').off('click');

            //set new click listener with new pagination links
            paginationClickHandler();
			//featClickHandler();
         });
    });
}
$(document).on("click", "a.scrollto",function(e) {
	e.preventDefault();
    let itemOffset = $($(this).attr("href")).offset().top;
  	let TopHeaderHeight = $("header").outerHeight();
  	let scrolltodis = itemOffset - TopHeaderHeight - 0;
    $("html, body").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
      $('html, body').stop();
    });
    $('html,body').animate({ scrollTop: scrolltodis }, 900, "linear", function(){
      $("html, body").unbind("scroll mousedown mouseup DOMMouseScroll mousewheel keyup");
    });
});
$(document).find("a.scrollto").each(function(){
	let target = $($(this).attr("href"));
    if (target.length > 0) {$(this).removeClass("!hidden");}
});
$(document).on("click", "a.tab-heading, a.feat-cat", function(e){
  e.preventDefault();
  let itemOffset = $('#recent-posts').offset().top;
  let TopHeaderHeight = $("header").outerHeight();
  let scrolltodis = itemOffset - TopHeaderHeight - 0;
  $("html, body").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
    $('html, body').stop();
  });
  $('html,body').animate({ scrollTop: scrolltodis }, 900, "linear", function(){
    $("html, body").unbind("scroll mousedown mouseup DOMMouseScroll mousewheel keyup");
  });
  $("a.tab-heading").each(function() {$(this).removeClass("active");});
  let catH = $(this).data("tabheading");
  $('a.tab-heading[data-tabheading='+ catH +']').addClass("active");
  //link to the next set of articles
  var href = $(this).attr("href");

  //get new articles and pagination
  $.get(href, {}, function(data){
    //remove existing pagination
    $(".pagination").remove();

    //add new articles and pagination links
    $("#articles").html(data);

    //disable pagination click listener
    $('.pagination a').off('click');

    //set new click listener with new pagination links
    paginationClickHandler();
  });
});
function featClickHandler() {
  $("a.feat-cat, a.post-filter").click(function(e){
    e.preventDefault();
	let itemOffset = $('#recent-posts').offset().top;
	let TopHeaderHeight = $("header").outerHeight();
	let scrolltodis = itemOffset - TopHeaderHeight - 0;
	$("a.tab-heading").each(function() {$(this).removeClass("active");});
	let catH = $(this).data("tabheading");
	$('a.tab-heading[data-tabheading='+ catH +']').addClass("active");
    //link to the next set of articles
    var href = $(this).attr("href");

    //get new articles and pagination
    $.get(href, {}, function(data){
      //remove existing pagination
      $(".pagination").remove();

      //add new articles and pagination links
      $("#articles").html(data);

      //disable pagination click listener
      $('.pagination a').off('click');

      //set new click listener with new pagination links
      paginationClickHandler();
    });		
  });
}
let getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};
let blogCat = getUrlParameter('cat');
if(blogCat != '' || blogCat == undefined) {
   $("a.tab-heading").each(function() {$(this).removeClass("active");});
   $('a.tab-heading[data-tabheading='+ blogCat +']').addClass('active');
   
   let href = $('a.tab-heading[data-tabheading='+ blogCat +']').attr("href");
   //get new articles and pagination
   $.get(href, {}, function(data){
   	//remove existing pagination
    $(".pagination").remove();

	//add new articles and pagination links
    $("#articles").html(data);

    //disable pagination click listener
    $('.pagination a').off('click');

    //set new click listener with new pagination links
    paginationClickHandler();
  });
  let itemOffset = $('#recent-posts').offset().top;
  let TopHeaderHeight = $("header").outerHeight();
  let scrolltodis = itemOffset - TopHeaderHeight - 0;
  $("html, body").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
	$('html, body').stop();
  });
  $('html,body').animate({ scrollTop: scrolltodis }, 900, "linear", function(){
    $("html, body").unbind("scroll mousedown DOMMouseScroll mousewheel keyup");
  });
}
$(document).on('click', '', function() {$('.thankyou-pop-wrap').removeClass('active');})
$('.profile #cform').submit(function(e) {
     e.preventDefault;
     var $theForm = $(this);
	 var chngPW = $('#showChangePW').val();
     let pwCheck = 0;
     console.log($('#showChangePW').is(":checked"));
     if($('#showChangePW').is(":checked") == true) {
        $('input[type=password]').each(function() {
        	var checkPWFields = $(this).filter(function () {
                return $.trim($(this).val()).length == 0
            }).length == 0;
            if(!checkPWFields) {
            	$(this).css('border-color', '#ff0000');
            } else {
                $(this).css('border-color', '');
                pwCheck += 1;
            }
            
        });
     	// submit form
       if(pwCheck == 3) {
       	  $.ajax({
             type: $theForm.attr('method'),
             url: $theForm.attr('action'),
             data: $theForm.serialize(),
             success: function(data) {
                 // Success Message
                 let msg = 'Profile updated successfully.';
                 $('#result').html(msg).show(800);
                 setTimeout(function() {$("#result").hide(800)}, 5000);
                 var mRole = $('#roleDd').val();
                 var mID = $('#memberID').val();

                 $.ajax({ url: '/profile-update.php?mid='+ mID +'&mrole=' + mRole });


                 $('#current_password').val('');
                 $('#password').val('');
                 $('#password_confirm').val('');
             },
             error: function(xhr, status, error) {
               $('#result').html("There was an error... please check your fields and try again.").show(800);
               setTimeout(function() {$("#result").hide(800)}, 5000);
             }
         });        
       }
     } else {
       $.ajax({
           type: $theForm.attr('method'),
           url: $theForm.attr('action'),
           data: $theForm.serialize(),
           success: function(data) {
             // Call the other function to update Role
             var mRole = $('#roleDd').val();
             var mID = $('#memberID').val();

             $.ajax({ url: '/profile-update.php?mid='+ mID +'&mrole=' + mRole });


             $('#current_password').val('');
             $('#password').val('');
             $('#password_confirm').val('');

             // Success Message
             let msg = 'Profile updated successfully.';
             $('#result').html(msg).show(800);
             setTimeout(function() {$("#result").hide(800)}, 5000);
           },
           error: function(xhr, status, error) {
             console.log(xhr);
             console.log(status);
             console.log(error);
             $('#result').html("There was an error... Please check your fields and try again.").show(800);
             setTimeout(function() {$("#result").hide(800)}, 5000);
           }
       });
     }
     // Prevent submitting form
     return false;
});
$('.complete-profile #cform').submit(function(e) {
     e.preventDefault;
     var $theForm = $(this);
     let pwCheck = 0;
     $('input[type=password]').each(function() {
        	var checkPWFields = $(this).filter(function () {
                return $.trim($(this).val()).length == 0
            }).length == 0;
            if(!checkPWFields) {
            	$(this).css('border-color', '#ff0000');
            } else {
                $(this).css('border-color', '');
                pwCheck += 1;
            }
            
     });
     	// submit form
     if(pwCheck == 2) {
       	  $.ajax({
             type: $theForm.attr('method'),
             url: $theForm.attr('action'),
             data: $theForm.serialize(),
             success: function(data) {
                 // Success Message
                 let msg = 'Profile updated successfully.<br/><br/>Loading Customer Portal. Please wait...';
                 $('#result').html(msg).show(800);
                 $theForm.hide();
                 var mRole = $('#roleDd').val();
                 var mID = $('#memberID').val();
				 $.ajax({ 
                 	url: '/welcome-email.php?mid='+ mID, 
                    success:function(){console.log('success')}
                 });
                 $.ajax({ url: '/profile-update.php?mid='+ mID +'&mrole=' + mRole, success:function(){setTimeout('document.location.href="/customer-portal";',5000);} });
             },
             error: function(xhr, status, error) {
               $('#result').html("There was an error... please check your fields and try again.").show(800);
               setTimeout(function() {$("#result").hide(800)}, 5000);
             }
         });        
     }
     // Prevent submitting form
     return false;
});
$('.profile #reg_specialty, #reg_specialty').on('change', function() {
console.log('change: ' + this.value);
  $('#m_field_id_7').val(this.value);
});
$('.profile #showChangePW').on('change', function() {
	console.log('change: ' + this.value);
    if($('#showChangePW').is(":checked")) {$('#changePW-wrap').addClass('active');} else {$('#changePW-wrap').removeClass('active');}
});
$('#register_member_form').submit(function(e) {
	var $theForm = $(this);
    $('.login-form').addClass('processing');
	$.ajax({
      type: $theForm.attr('method'),
      url: $theForm.attr('action'),
      data: $theForm.serialize(),
      success: function(data) {
        console.log('success');
        var mRole = $('#roleDd').val();
        var cUrl = location.href;
        var lastCharcUrl = cUrl.substr(-1);
        if(lastCharcUrl === "/") {
        	window.location.href = cUrl + 'thank-you?r=' + mRole;
        } else {
        	window.location.href = cUrl + '/thank-you?r=' + mRole;
        }
        
      },
      error: function(xhr, status, error) {
        $('.login-form').removeClass('processing');
        let parser = new DOMParser();
        var ErrorHTML = parser.parseFromString(xhr.responseText, 'text/html');
        var ErrorMsg = ErrorHTML.querySelector(".panel-body");
        var ErrString = xhr.responseText;
        var EmailExist = "This field must contain a unique email address.";
        if(ErrString.includes(EmailExist)){
            console.log("Email Exist");
            // Show login redirect
            $(".login-form").html('<div class="text-center"><img src="/assets/images/hyperfine-gradient-logo.png" alt="Hyperfine" class="max-w-[230px] mx-auto mb-4"><h3 class="text-4xl font-bold leading-tight tracking-wide mt-4 text-center">Customer Resources</h3><div class="text-2xl leading-tight mt-4 text-center mb-2">Email already exists. <br/>Please proceed to login page.</div><a href="/login" class="inline-block text-white bg-[#161e49] py-3 px-6 mt-2 mb-10 rounded-2xl">Login</a></div>')
        } else {
          //console.log(ErrorMsg);
          $('#results').html(ErrorMsg).show(800);
            setTimeout(function() {$("#results").hide(800)}, 7000);
          }
        }
    }); 

    // Prevent submitting form
    return false;
});



const _specialtiesBtn = document.querySelector('.viewSpecialties');
const _specialtiesList = document.querySelector('.specialtiesList');

if (_specialtiesBtn) {
_specialtiesBtn.addEventListener('click', (e, i) => {
	e.preventDefault();
	if(_specialtiesList.classList.contains("hidden")){
    	_specialtiesList.classList.remove("hidden");
    	_specialtiesList.style.display= "flex";
    } else {
    	_specialtiesList.classList.add("hidden");
    	_specialtiesList.style.display= "";
    }
});
}

const _specialtiesBtnM = document.querySelector(".viewSpecialtiesM");
const _specialtiesListM = document.querySelector(".specialtiesListM");

if(_specialtiesBtnM) {
_specialtiesBtnM.addEventListener("click", (e, i) => {
	e.preventDefault();
	if(_specialtiesListM.classList.contains("hidden")){
    	_specialtiesListM.classList.remove("hidden");
    	_specialtiesListM.style.display= "flex";
    } else {
    	_specialtiesListM.classList.add("hidden");
    	_specialtiesListM.style.display= "";
    }
});
}