var submitted_form;
jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
jQuery.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
(function( $ ) {
  /****State option***/
  $(document).on( 'change' , '#form_country select', function(e){
    show_state();
});
function show_state(){
  var selectedCountry = $('#form_country select').children("option:selected").text();
  if(selectedCountry=="United States"){
      $('.state select').val('');
      $('.state').show();
      $('.state select').prop('required',true);
  }else{
    $('.state select').val('');
    $('.state').hide();
    $('.state select').prop('required',false);
  }
}
  /****End State option***/
  /***Search feature***/
  $('#site_search_form input[type=search]').on('focus',function(e){
        $('.nav-item.login-button').hide();
        $('.nav-item.request-demo-button').hide();
        $(this).css('transition','all .5s');
        $(this).css('width','300px');
  });
  $('#site_search_form input[type=search]').on('focusout',function(e){
    $(this).css('transition','none');
        $(this).css('width','30px');
        $('.nav-item.login-button').css('display','list-item');
        $('.nav-item.request-demo-button').css('display','list-item');
  });
  /***End Search feature***/
  /***multiselect form***/
  if( jQuery('.multi_webinar_form .multiselect').length ){
    jQuery('.multi_webinar_form .multiselect').multiselect({
          buttonWidth: '100%',
          buttonClass: 'multiselect-btn',
          nonSelectedText: 'Which webinars would you like to register? *',
          numberDisplayed: 0,
          includeSelectAllOption: true,
      });
  }
  if( jQuery('.partner_referral_form .multiselect').length ){
    jQuery('.partner_referral_form:not(.csm_referral_form) .multiselect').multiselect({
          buttonWidth: '100%',
          buttonClass: 'multiselect-btn',
          nonSelectedText: 'Which products is the prospect interested in? *',
          numberDisplayed: 0,
          includeSelectAllOption: true,
      });
  }
  /***End multiselect form**/
  /***Multistep form***/
	$('form.multistepform input').bind("keypress", function(e) {
  if (e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});
/***End multistep form**/
	/*********Omit special character on name input****/
	$('input[type="text"]').bind('input', function() {
	var c = this.selectionStart,
			r = /[^-a-z0-9 ,.:/]/gi,
			v = $(this).val();
	if(r.test(v)) {
		$(this).val(v.replace(r, ''));
		c--;
	}
	this.setSelectionRange(c, c);
});
$('textarea').bind('input', function() {
var c = this.selectionStart,
		r = /[^-a-z0-9 ,.\n()?;\\:"'/!]/gi,
		v = $(this).val();
if(r.test(v)) {
	$(this).val(v.replace(r, ''));
	c--;
}
this.setSelectionRange(c, c);
});
$('input[type="search"]').bind('input', function() {
var c = this.selectionStart,
	r = /[^-a-z0-9 ,.]/gi,
		v = $(this).val();
if(r.test(v)) {
	$(this).val(v.replace(r, ''));
	c--;
}
this.setSelectionRange(c, c);
});

	/*********End Omit special character on name input****/
	/*****New nav assibility**/
	$('.nav-menu .menu-item-has-children').on('mouseover',function(e){
			var navitemf = $('.nav-menu .menu-item-has-children:focus');
			var navitem = $('.nav-menu .menu-item-has-children');
				$('.nav-menu .menu-item-has-children').blur();
				$('.nav-menu .menu-item-has-children').focusout();
				$('.nav-menu .menu-item-has-children a').blur();
				$('.nav-menu .menu-item-has-children a').focusout();
	});
	$('.site-header .top-header .top-navigarion .main-navigation ul li ul li a').on('focus',function(e){
				$(this).parent('.menu-item  ').addClass('focused_menu');
	});
	$('.site-header .top-header .top-navigarion .main-navigation ul li ul li a').on('focusout',function(e){
				$(this).parent('.menu-item  ').removeClass('focused_menu');
	});

	$('.top-nav .sub_menu_item').on('focus',function(e){
				$(this).parents('.menu-item-has-children').addClass('isopened');
				$(this).parent('.row_menu_item  ').addClass('focused_menu');
	});
	$('.top-nav .sub_menu_item').on('focusout',function(e){
				$(this).parents('.menu-item-has-children').removeClass('isopened');
				$(this).parent('.row_menu_item  ').removeClass('focused_menu');
	});

	$('#header_nav').on("keydown", "a",
	    function(e)
	    {
	        var flag = false;
	        var smallMeni = document.getElementById('header_nav');
	        var allElements2 = smallMeni.getElementsByTagName('a'); //.link
	        if (e.keyCode == 40)
	        {
						e.preventDefault();
	            for (var i=0;i<allElements2.length;i++)
	            {

	                if(flag == true){
	                    flag = false
	                    allElements2[i].focus();
	                }
	                else
	                {
	                    if ( document.activeElement === allElements2[i] )
	                    {
	                        flag = true;
	                    }
	                }
	            }
	        }
	        if (e.keyCode == 38)
	        {
						e.preventDefault();
	            for (var i=0;i<allElements2.length;i++)
	            {
	                if ( document.activeElement === allElements2[i] )
	                {
	                    if (i>0)
	                    {
	                        allElements2[i-1].focus();
	                    }
	              	}
	            }
	        }
					if(event.keyCode == 37) { //left
						e.preventDefault();
							for (var i=0;i<allElements2.length;i++)
							{
									if ( document.activeElement === allElements2[i] )
									{
										var currenitem = document.activeElement;
										if($(currenitem).hasClass('.sub_menu_item')==false){
												var nextli = $(currenitem).parent('.menu-item').prev();
												var children = $(nextli).children('a');
												$(nextli).children('a').focus();
										}
									}
							}
					}
					if(event.keyCode == 39) { //right
						e.preventDefault();
							for (var i=0;i<allElements2.length;i++)
							{
									if ( document.activeElement === allElements2[i] )
									{
											var currenitem = document.activeElement;
											if($(currenitem).hasClass('.sub_menu_item')==false){
													var nextli = $(currenitem).parent('.menu-item').next();
													var children = $(nextli).children('a');
													$(nextli).children('a').focus();
											}
										break;
									}
							}
					}
		}
	);

	/*****End New nav assibility**/

/*******Hubspot form******/
function add_hubspot_cookie_value_on_form(){
  var hubspotutk = $.cookie('hubspotutk');
  if(hubspotutk!='' && hubspotutk!=undefined && hubspotutk!="NA" ){
    $('.hutk').val(hubspotutk);
  }
  $('.page_uri').val(window.location.href);
}
/*******End Hubspot form******/

	$(window).scroll(function() {
	  var nav = $('.navbar');
	  var top = 1;
	  if ($(window).scrollTop() >= top) {
	    nav.addClass('scrolling');
	  } else {
	    nav.removeClass('scrolling');
	  }
	});

	$('document').ready(function() {
    //Cookie popup
    $('.cky-btn-revisit-wrapper').css('display','flex');
    visitor_country();
    google_optimize_callback();
		if ( window.location.pathname == '/' ){
			homepage_initialzed();
		}
		$.cookie.defaults.secure = true;
		get_pardot_prospect();
    if($('#ondemand_webinar_form').length>0){
      ondemand_webinar_form();
    }
    if($('#gated_tour_container').length>0){
      gated_tour_submitted();
    }

		/*if ($('.form').length > 0 && $('.Country').length>0) {
				autopopulate_country_select();
		}*/
		/*if ($('.login-button').length > 0) {
				autopopulate_login_url();
		}*/
    if ($('.form').length > 0 && $('.hutk').length>0) {
        add_hubspot_cookie_value_on_form();
    }
		 fixaccessbility();
		/* $('img').load(function(e){
		 console.log($(this).attr('alt'));
		// Do your change stuff here
	});*/

	});
  /*****Optimize exp*****/
  function google_optimize_callback(){
    gtag('event', 'optimize.callback', {
      callback: (combination, experimentId, containerId) => {
           if(experimentId=='mcZPsQKWTzuUAIY85h7OEQ'){
               console.log("Optimize variant "+combination);
                optimize_variant(combination);
           }
      }
    });
  }
  function optimize_variant(optimize_variant){
    if(optimize_variant==0){
        $('.secction_banner_image').hide();
        $('.secction_banner_image').css('visibility','hidden');
        $('.secction_banner_video').show();
        $('.secction_banner_video').css('visibility','visible');
    }else{
      $('.secction_banner_video').hide();
      $('.secction_banner_video').css('visibility','hidden');
      $('.secction_banner_image').show();
      $('.secction_banner_image').css('visibility','visible');
    }
  }
  /*****End Optimize exp*****/
	if (typeof $== 'function') {
		$(function(){
					if (typeof Typed !== 'undefined') {
						var typed5_0 = new Typed('#typed5', {
							stringsElement:'#typed5',
							//strings: ['<span style="color:#1d1d1d;">Turn interest into applications<br/>with</span> Clinch'],
							typeSpeed: 100,
							backSpeed: 50,
							backDelay: 2000,
							cursorChar: '|',
							shuffle: false,
							smartBackspace: false,
							loop: true
						});
					}

				if ('URLSearchParams' in window && new URLSearchParams(window.location.search).has('editing')) {
					$('img.hidden-editor').hide()
				}

		});
		if ('URLSearchParams' in window && new URLSearchParams(window.location.search).has('editing')) {
			$('img.hidden-editor').hide()
		}
	}



	/******************Pardot Custom ID and blog subscriont list checking*********************/
		function get_pardot_prospect(){
			var checkPardotAPI = false;
      var pardot_email = $.cookie('pardot_email');
			//$.removeCookie('pardot_custom_id',{path:'/'});
			//$.removeCookie('pardot_email',{path:'/'});
			var pardot_id = $.cookie('pardot_id');
      var pardot_prospect_industry = $.cookie('pardot_prospect_industry');
			if(pardot_id=='' || pardot_id==undefined || pardot_id=="NA" || $.isNumeric(pardot_id)){
        if(pardot_email !='' && pardot_email!=undefined && pardot_email!="NA"){
          get_custom_user_id(pardot_email);
        }
			}else{
        if(pardot_prospect_industry =='' || pardot_prospect_industry==undefined || pardot_prospect_industry=="NA"){
          get_pardot_industry_by_id(pardot_id);
        }
			}
		}

    function get_pardot_industry_by_id(pardot_id){
			var myArray = pardot_id.split(/([0-9]+)/);
			if(myArray.length>1){
				var pardot_prospect_id = (myArray[1]);
				jQuery.ajax({
					type: "POST",
					url: adminurl,
					data: { action : 'get_pardot_prospect_industry', pardot_prospect_id : pardot_prospect_id },
					success: function (result){
							var pardot = JSON.parse(result);
							if(pardot.prospect_industry!="NA"){
								$.cookie('pardot_prospect_industry',pardot.prospect_industry,{path:'/'});
							}
							console.log('prospect industry is '+ pardot.prospect_industry);
					},
					error:function(jqXHR,textStatus,errorThrown){
						console.log("Error: "+textStatus);
					},
					beforeSend:function(){

					},
					complete: function () {

					}
				});
			}

		}

	//Call Pardot API to get prospect details if available
		function get_custom_user_id(pardot_email){
			jQuery.ajax({
				type: "POST",
				url: adminurl,
				data: { action : 'get_custom_user_id', pardot_email : pardot_email },
				success: function (result){
						//alert(result);
						var pardot = JSON.parse(result);
            $.removeCookie('pardot_email',{path:'/'});
						//$.cookie('pardot_custom_id',pardot.pardot_custom_id,{path:'/'}); //Update the pardot custom ID to cookie
						if(pardot.pardot_id!="NA"){
							$.cookie('pardot_id',pardot.pardot_id,{path:'/'});
						}
            if(pardot.prospect_industry!="NA"){
              $.cookie('pardot_prospect_industry',pardot.prospect_industry,{path:'/'});
            }
            console.log('prospect industry is '+ pardot.prospect_industry);
						//push_pardot_custom_id_to_ga(pardot.pardot_custom_id); //Push to GA
				},
				error:function(jqXHR,textStatus,errorThrown){
					console.log("Error: "+textStatus);
				},
				beforeSend:function(){

				},
				complete: function () {

				}
			});
		}

	//Update Pardot API count when there is a form submit, so we can get updated visitor details
		$('form').submit(function(e){
			var email = "NA";
			if($('input[type="email"]').length){
				var email_input = $('input[type="email"]')[0];
				email = $(email_input).val();
			}
				$.cookie('pardot_email',email,{path:'/'});
				get_custom_user_id(email);
		});

	/******************End Pardot Custom ID *********************/

	function fixaccessbility(){
		var bizimg = $('img[src*="https://cdn.bizible.com/m/ipv?_biz_r="]');
		$('img[src*="https://cdn.bizible.com/m/ipv?_biz_r="]').attr('alt','');
			$('img[src*="https://cdn.bizibly.com/u?_biz_u"]').attr('alt','');

	}

/***************Geo location*************/
  function visitor_country(){
    var visitor_country = $.cookie('visitor_country');
    var wilson_ipdata_api_key = '36f34478ebf706be4502b3436c73bc2763c4efd95124e6acae9bff9f';
    var pup_ipdata_api_key = 'a69ded9b11f473fe2546bb02dd4716dbe7a46c11990a62bb24a12aba';
    $.getJSON('https://api.ipdata.co/?api-key='+wilson_ipdata_api_key, function(data) {
    console.log(data);
          var c_code = data.country_code;
          var country = data.country_name;
          var latitude = data.latitude;
          var longitude = data.longitude;
          var continent = data.continent_code;
          $.cookie('visitor_country',country,{path:'/'}); //Update the pardot custom ID to cookie
          $.cookie('visitor_continent',continent,{path:'/'});
          $.cookie('visitor_c_code',c_code,{path:'/'});
          if ($('.product-login .button4').length > 0) {
      				autopopulate_login_url(c_code,country,latitude,longitude,continent);
      		}
          if ($('.form').length > 0 && $('.Country').length > 0) {
      				autopopulate_country_select(c_code,country,latitude,longitude,continent);
      		}
          checkgeo_location(c_code,country,latitude,longitude,continent);
      });
  }
  function checkgeo_location(c_code,country,latitude,longitude,continent){
    var my_continent = "EU";
      var url_path = window.location.pathname;
      if($.cookie('disable-country-redirection') != 'true' &&
      (url_path.toLowerCase().indexOf("campaign") == -1 && url_path.toLowerCase().indexOf("request-demo") == -1
      && url_path.toLowerCase().indexOf("product-login") == -1 && url_path.toLowerCase().indexOf("thank-you") == -1)
      ){
      if(continent!=my_continent || c_code=="FR"){
        url_path = url_path.substr(4);
        var redirect_link = "";
        var btn = "";
        if(c_code=="FR"){
          redirect_link = 'https://'+window.location.hostname+'/fr/'+ url_path;
          btn = "Visit our Clinch France site";
        }else{
          redirect_link = 'https://'+window.location.hostname+"/"+ url_path;
          btn = "Visit our Clinch site";
        }

        //$('#geo_location_popup_site_country').html(country);
        $('#geo_location_redirect_link').attr('href',redirect_link);
        $('#geo_location_redirect_link').html(btn);
        $('#geo_location_popup_from_country').html(country);
          setTimeout(function(){
            jQuery('.geo-location').addClass('open');
            $.cookie('disable-country-redirection','true',{path:'/'});
          },3000);
      }
    }
  }
  $(document).on( 'click' , '.geo-location #disable-siteredirection', function(e){
  	$('.geo-location').removeClass('open');
  });
  function autopopulate_login_url(c_code,country,latitude,longitude,continent){
          if(continent=="AS" || continent=="OC"){
              $('.product-login .button4').attr('href','https://rec-marketing.dc2.pageuppeople.com/password_auth/sign_in');
          }else if(continent=="EU"){
              $('.product-login .button4').attr('href','https://rec-marketing.dc3.pageuppeople.com/password_auth/sign_in');
          }else{

              $('.product-login .button4').attr('href','https://app.clinchtalent.com/password_auth/sign_in');
          }
  }
  function autopopulate_country_select(c_code,country,latitude,longitude,continent){
          var country_select = $('.Country select')[0];
          var country_val = $(".Country select option:contains("+country+")").val();
          $('.Country select option').map(function () {
               if ($(this).text() == country) return this;
            }).attr('selected', 'selected');
            show_state();
  }
/***************End Geo location*************/
	//Google Captcha Validation
$('.form input[type="submit"]').click(function(e){
			e.preventDefault();
			var form = $(this).parents('form');
			var email_field = $(form).find("input[type='email']");
			email_field[0].setCustomValidity('');
			if($(form)[0].checkValidity()){
					validateBusinessEmail(form);
			}else{
				 $(form)[0].reportValidity()
				return false;
			}
});
$(".pfah-form button").on('click', function(e) {
	e.preventDefault();
	var form = $(this).parents('form');
	var email_field = $(form).find("input[type='email']");
	email_field[0].setCustomValidity('');
	if($(form)[0].checkValidity()){
			validateBusinessEmail(form);
	}else{
		 $(form)[0].reportValidity()
		return false;
	}
});

function validateBusinessEmail(form){
		var email_field = $(form).find("input[type='email']");
		var a_email = $(email_field).val();
    var personal_email_allow = 'false';
    if($(form).hasClass("newsletter_form") || $(form).hasClass("personal_email_allow")){
       personal_email_allow = 'true';
    }
		jQuery.ajax({
			type: "POST",
			url: adminurl,
			dataType: 'text',
			data: { action : 'business_email_validation', a_email : a_email, personal_email_allow: personal_email_allow },
			success: function (result){
				if(result=='nonvalidemail'){
						email_field[0].setCustomValidity('Please use a business email address.');
						$(form)[0].reportValidity();
						return false;
				 }else{
					 submitted_form = form;
					 if($('.g-reptcha-invisible').length){
								form_google_captcha_v2_invisble(form); //v2_invisible
					 }else if($('.g-reptcha-checkbox').length){
							form_google_captcha_v2_checbox(form); //v2_checkbox
					 }else{
						 form_google_captcha_v2_invisble(form); //v2_invisible
					 }
					//	form_google_captcha(form);
				 }
			},
			error:function(){
				alert('Please submit the form again.');
				return false;
			},
			beforeSend:function(){

			},
			complete: function () {

			}
		});
}

function form_google_captcha_v2_invisble(form){
	if($('.invisible-recaptcha').length){

	}else if($('.g-recaptcha').length){
		grecaptcha.execute();
	}else{
		form.submit();
	}
}
function form_google_captcha_v2_checbox(form){
	if($('.g-recaptcha-response').length){
		var recaptcha = $(form).find(".g-recaptcha-response").val();
			if (recaptcha === "")
			{
				$(".g-recaptcha-response").focus();
				alert('Please check the captcha !');
				return false;
		 }else{
			 validate_google_captcha(recaptcha,'checkbox');
		 }
	}else{
		$(form).submit();
	}
}

/************************Fancy*************************/
if($('.fancybox').length){
		$(".fancybox").fancybox();
	}
	$(".pop-btn").on('click', function() {
		$.fancybox.open({
			src  : '.pop-content',
			type : 'inline',
		});
	});
	$(".pop-btn").on('click', function() {
		$.fancybox.open({
			src  : '.pop-content',
			type : 'inline',
		});
	});
/************************End Fancy*************************/

/************Carousel**********/
jQuery('.ebook-customer-logo-slider.owl-carousel').owlCarousel({
  loop:true,
  autoplay:true,
  autoplayTimeout: 0,
  autoplaySpeed: 8500,
  autoplayHoverPause: true,
  slideTransition: 'linear',
  items:10,
  rtl: false,
  dots: false,
  mouseDrag:true,
  touchDrag:true,
  responsive:{
    0:{
        items:3
    },
    800:{
        items:5
    },
    1000:{
        items:7
    },
    1250:{
        items:10
    }
  }
  });
jQuery('.screenshot-slider.owl-carousel').owlCarousel({
	loop:true,
	autoplay:false,
	autoplayTimeout:5500,
	items:1,
	dots: true,
	nav:true,
	singleItem : true,
	animateIn: 'fadeIn',
	//navText:['<i aria-hidden="true" class="gel-icon gel-icon-angle-left"></i>','<i aria-hidden="true" class="gel-icon gel-icon-angle-right"></i>'],
	navText:['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>']
	});
		jQuery('.customer_numbers_boxes_top_carousel .owl-carousel').owlCarousel({
			loop:true,
			autoplay:false,
			autoplayTimeout: 0,
			autoplaySpeed: 10500,
			autoplayHoverPause: true,
			slideTransition: 'linear',
			items:4,
			rtl: false,
			dots: false,
			mouseDrag:true,
			touchDrag:true,
			margin:30,
			stagePadding:10,
			responsive:{
				0:{
						items:1,
				},
				995:{
						items:2,
				},
				1400:{
						items:4,
				}
			}
			});
			jQuery('.customer_quotes-slider.owl-carousel').owlCarousel({
				loop:true,
				autoplay:false,
				autoplayTimeout:5000,
				items:3,
				dots: false,
				nav:true,
				singleItem : false,
				smartSpeed : 500,
				margin:30,
				slideBy:1,
				stagePadding:10,
				center:true,
			//navSpeed : 2000,
				//animateOut: 'slideOutRight',
				//animateIn: 'zoomIn',
				//navText:['<i aria-hidden="true" class="gel-icon gel-icon-angle-left"></i>','<i aria-hidden="true" class="gel-icon gel-icon-angle-right"></i>'],
				navText:['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>'],
				responsive:{
					0:{
						items:1,
						slideBy:1,
						dots: true,
						nav:false,
					},
					992:{
							items:3,
							slideBy:1,
							dots: false,
							nav:true,
					}
				},
			});

	var banner_carousel = jQuery('.banner-slider.owl-carousel');
	banner_carousel.owlCarousel({
		loop:true,
		autoplay:true,
		autoplayTimeout:10000,
		items:1,
		dots: true,
		nav:false,
		singleItem : true,
		smartSpeed : 2000,
		margin:30,
		slideBy:1,
		stagePadding:10,
		autoplayHoverPause:true,
	//navSpeed : 2000,
		//animateOut: 'slideOutRight',
		//animateIn: 'zoomIn',
		//navText:['<i aria-hidden="true" class="gel-icon gel-icon-angle-left"></i>','<i aria-hidden="true" class="gel-icon gel-icon-angle-right"></i>'],
		navText:['<i class="fa fa-angle-left"></i>','<i class="fa fa-angle-right"></i>'],
		responsive:{
		},
		onChange: banner_slider_changed,
		onDrag: banner_slider_changed,
		onInitialized: homepage_initialzed
	});

	banner_carousel.on('translated.owl.carousel', function(e) {
		console.log('translated');
		var index = e.item.index - 1;
    var count = e.item.count;
    if (index > count) {
        index -= count;
    }
    if (index <= 0) {
        index += count;
    }
		index = index - 1;
		$('.sub_typed_'+index).css('display', 'none');
		$('.typed_'+index).css('display', 'none');
		$('.typed_'+index+':not(.cloned_typed5)').typeWrite({
		 speed: 50,
		 repeat: false,
		 cursor: true,
		 interval: 1000,
	 });
	});


function banner_slider_changed(event){
	$('.sub_typed5').css('display', 'none');
	$('.typed5').css('display', 'none');
	$('.cloned_typed5').remove();
}
/************End Carousel**********/

/****Typing text homepage**/
function homepage_initialzed(){
	$('.sub_typed_0').css('display', 'none');
	$('.typed_0').typeWrite({
	 speed: 50,
	 repeat: false,
	 cursor: true,
	 interval: 1000,
 })
 .then((res) => {
			 $('.sub_typed_0').css('display', 'inline');
			 $('.sub_typed_0').typeWrite({
				 speed: 100,
				 repeat: false,
				 cursor: true,
				 interval: 1000,
			 })
		 });
}
/****End Typing text homepage**/

/********FAQs********/
jQuery('.tab-listing ul li').click(function(e) {
	jQuery(this).find('.tab-desc').slideToggle(300);
	jQuery(this).toggleClass('open');
	jQuery(this).siblings('.tab-listing ul li').removeClass('open');
	jQuery(this).siblings('.tab-listing ul li').find('.tab-desc').slideUp(300);

});
/**********End FAQs*******/
/***Mobile Menu***/
$(".navbar-toggler").on("click", function() {
	$('.menu-item-has-children.submenuOpened').removeClass("submenuOpened");
});
$(".submenuToggle").on("click", function() {
	if ($(window).width() < 1025) {
		$(this).toggleClass("submenuOpened");
	}
});

/**End Mobile Menu**/
if($('.spu-close-popup').length){
	$('.spu-close-popup').attr('href','javascript:;');
}
/***Scorlling indication**/
if($('.progress-container').length){
window.onscroll = function() {scrollIndicatorFunction()};
}

function scrollIndicatorFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var article_left = $('.article-left')[0];
var article_left_height = $(article_left).height();
//var height = document.documentElement.scrollHeight - document.documentElement.clientHeight - sidebar_height-posts_listing_height - action_today_height - footer_height;
var height = article_left_height-500;
var scrolled = (winScroll / height) * 100;
document.getElementById("scorllBar").style.width = scrolled + "%";
}
/***End scrolling indication**/

/*****Hash click focus***/
$('a[href*=#]:not([href=#]):not(.nav-link):not(.main_cat_toggle):not(.accordion_title)').on('click', function (event) {
			// event.preventDefault();
			 var element = $(this.hash);
			 $('html,body').animate({ scrollTop: element.offset().top-150 },'normal', 'swing');
	 });
/*****End Hash click focus***/

/*****GTM Custom Event********/
$('.a2a_kit>a').click(function(e){
	//e.preventDefault();
	var share_medium = $(this).attr('title');
	var share_url = window.location.href;
	window.dataLayer = window.dataLayer || [];
	window.dataLayer.push({
					'event': 'postShared',
					'eventCategory': share_medium,
					'eventLabel': share_url
			});
});
/*****End GTM Custom Event********/

//Footer video button play
	$(".video_button").on('click', function(e) {
		if($(this).attr('href')=="javascript:;"){
			if($("#video_cta_wistia_id").length){
				$("#video_cta_wistia_id")[0].click();
			}
		}
		/*$.fancybox.open({
			src  : '#video_signup_form',
			type : 'inline',
		});*/
	});

/*********Exit CTA********/
let exit_timer;
$(document).mouseleave(function (e) {
	if(e.clientY <= 0){
		var exit_cta = $.cookie('exit_cta');
		if(exit_cta==0 || exit_cta==undefined){
				if ($('#exit_cta_form').length > 0) {
        show_exit_cta();
		} }
	}
});
function show_exit_cta(){
	if($('.fancybox-is-open #exit_cta_form').length<1) {
		console.log('opened');
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ 'event': 'PopupOpened','eventCategory': 'Exit CTA Popup', 'eventAction': 'Exit CTA Popup opened'});
	$.fancybox.open({
		src  : '#exit_cta_form',
		type : 'inline',
		opts : {
						afterClose : function( instance, current ) {
															$.cookie('exit_cta',1,{expires: 7, path:'/'});
												}
					}
	})
}
}
$(document).on('mouseenter', function(e){
		//clearTimeout(timer);
});
$(document).on( 'click' , '#exit_cta_form a.button', function(e){
	$.cookie('exit_cta',1,{expires: 365, path:'/'});
})
/*********End Exit CTA********/

/*******Carousel Type text****/
var waypoints = $('#customer_quotes-slider').waypoint({
  handler: function(direction) {
		console.log(direction);
		if(direction=='down'){
			$('.customer_quote_cloned_typing').remove();
			$('.customer_quotes-slider .owl-item:not(.center) .customer_quote_name').css('display','inherit');
			var type_elelmet = $('.customer_quotes-slider .owl-item.center .customer_quote_name:not(.customer_quote_cloned_typing)');
			customer_quote_start_typing(type_elelmet);
		}
  },
	offset: '80%'
})

jQuery('.customer_quotes-slider.owl-carousel').on('translated.owl.carousel', function(e) {
	$('.customer_quote_cloned_typing').remove();
	$('.customer_quotes-slider .owl-item:not(.center) .customer_quote_name').css('display','inherit');
	var type_elelmet = $('.customer_quotes-slider .owl-item.center .customer_quote_name:not(.customer_quote_cloned_typing)');
	customer_quote_start_typing(type_elelmet);
});

function customer_quote_start_typing(type_elelmet){
	$(type_elelmet).quotesTypeWrite({
	 speed: 50,
	 repeat: false,
	 cursor: true,
	 interval: 50,
	 name:"customer_quote"
	});
}

/*******Carousel Type text****/
/*******Gated content****/
function ondemand_webinar_form(){
	var ondemand_submitted_form = $.cookie('ondemand_submitted_form');
	if(ondemand_submitted_form=='true'){
		$('.hidden_after_submission').hide();
		$('.pfah-done').show();
		$('.pfah-done').css('opacity',1);
	}else{
		$('.hidden_after_submission').show();
		$('.pfah-done').hide();
	}
}
function gated_tour_submitted(){
	var gated_tour_submitted = $.cookie('gated_tour_submitted');
	if(gated_tour_submitted=='true'){
		$('.hidden_after_submission').hide();
		$('.show_after_submission').show();
		$('.pfah-done').show();
		$('.pfah-done').css('opacity',1);
	}else{
		$('.hidden_after_submission').show();
		$('.show_after_submission').hide();
		$('.pfah-done').hide();
	}
}
/*******End Gated content****/
/*******LightSlider*******/
if($('.lightSlider').length){
$('.lightSlider').lightSlider({
auto:false,
adaptiveHeight:true,
enableDrag:false,
//controls:false,
prevHtml:'<p><i aria-hidden="true" class="gel-icon-3x gel-icon-angle-left"></i></p>',
nextHtml:'<p><i aria-hidden="true" class="gel-icon-3x gel-icon-angle-right"></i></p>',
gallery: true,
item: 1,
loop: false,
slideMargin: 0,
thumbItem: 6
});
}
/*******End LightSlider*******/
//Multistep form

// SmartWizard initialize
var form_submit_button = $('.partner_detail_submit');
var submit = form_submit_button[0];
$('#smartwizard').smartWizard({
	theme: 'dots',
	autoAdjustHeight: false,
	enableURLhash: false, // Enable selection of the step based on url hash
	transition: {
	 animation: 'fade', // Effect on navigation, none/fade/slide-horizontal/slide-vertical/slide-swing
	 speed: '400', // Transion animation speed
	 easing:'' // Transition animation easing. Not supported without a jQuery easing plugin
},
anchorSettings: {
		anchorClickable: false, // Enable/Disable anchor navigation
		enableAllAnchors: true, // Activates all anchors clickable all times
		markDoneStep: true, // Add done state on navigation
		markAllPreviousStepsAsDone: true, // When a step selected by url hash, all previous steps are marked done
		removeDoneStepOnNavigateBack: true, // While navigate back done step after active step will be cleared
		enableAnchorOnDoneStep: false // Enable/Disable the done steps navigation
},
toolbarSettings: {
toolbarExtraButtons: [$(submit)]
}
});
$.validator.addMethod('nofreeemail', function (value) {
	if(value==""){
		return true;
	}else{
		var first_split = value.toLowerCase().split("@")[1];
		var second_split = first_split.split(".")[0];

		var personal_email=['gmail','hotmail','msn','outlook','yahoo','icloud'];
		if(jQuery.inArray(second_split, personal_email)) {

			return true;
		}else{
			return false;
		}
	}

}, 'Please use a business email address.');

jQuery(".wpcf7-form-control.required_field").prop('required',true);
var form = $('#partner-details-form');
var email_field = $(form).find("input[type='email']");
var validator = $(form).validate({
onclick:true,
rules: {
partner_email: {
required:false,
email: true,
nofreeemail: true
}
}
});

//jQuery(".wpcf7-form").removeAttr('novalidate');
$("#smartwizard").on("leaveStep", function(e, anchorObject, currentStepIndex, nextStepIndex, stepDirection) {
if(stepDirection=="forward"){
	var form = $(this).parents('form');
	var email_field = $(form).find("input[type='email']");
	var validate_result = validator.form();
		if(!validate_result){
			return false;
		}
}


});

$("#smartwizard").on("stepContent", function(e, anchorObject, stepIndex, stepDirection) {
 if(stepIndex==4){
	 $('#partner-details-form .toolbar .partner_detail_submit').css('display','inline-block');
	 $('#partner-details-form .toolbar .sw-btn-next').hide();
 }else{
	 $('#partner-details-form .toolbar .partner_detail_submit').hide();
	 $('#partner-details-form .toolbar .sw-btn-next').css('display','inline-block');
 }
});


/*********End multistep form****/
})( jQuery );

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

function getUrlParam(parameter, defaultvalue){
    var urlparameter = defaultvalue;
    if(window.location.href.indexOf(parameter) > -1){
        urlparameter = getUrlVars()[parameter];
        }
    return urlparameter;
}

/*********Google Captcha********/

function captcha_submit_form(response){
	if(jQuery('.g-recaptcha-response').length){
		//var recaptcha = jQuery(form).find(".g-recaptcha-response").val();
			if (response === "")
			{
				alert('check Google Captcha');
		 }else{
				validate_google_captcha(response,'invisible');
		}
	}else{
			 alert('check Google Captcha');
	}
}


function validate_google_captcha(recaptcha,version){
	var form = submitted_form;
	var action;
	if(version=="checkbox"){
		action = 'captcha_validation';
	}else{
	action = 'captcha_validation_invisible';
	}
	console.log(form);
	jQuery.ajax({
		type: "POST",
		url: adminurl,
		dataType: 'json',
		data: { action : action, response : recaptcha },
		success: function (result){

			console.log(result['success']);
			var pathname = window.location.pathname;
			 if(result['success']){
				 $('.form').css('opacity','0.5');
				 if($(form).hasClass('demo_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Demo request form'});
				 }
				 if($(form).hasClass('rmkt_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'RMKT Demo request form'});
				 }
				 if($(form).hasClass('ebook_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Ebook form'});
				 }
				 if($(form).hasClass('contact_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Contact form'});
				 }
				 if($(form).hasClass('webinar_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Webinar form'});
				 }
				 if($(form).hasClass('newsletter_form')){
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Newsletter form'});
				 }
				 if($(form).attr('id')=='ondemand_webinar_form'){
					 $.cookie('ondemand_submitted_form','true',{path:pathname});
					 window.dataLayer = window.dataLayer || [];
					 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Ondemand webinar form'});
				 }
				 if($(form).hasClass('gated_tour_form')){
				 $.cookie('gated_tour_submitted','true',{path:pathname});
				 window.dataLayer = window.dataLayer || [];
				 window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Gated tour form'});
				 }
         if($(form).hasClass('audit_form')){
         window.dataLayer = window.dataLayer || [];
         window.dataLayer.push({ 'event': 'formSubmissionSuccess','eventCategory': 'formSubmissionSuccess', 'eventAction': 'Audit form'});
         }
				 $(form).submit();
			 }else{
				 alert('Please check the captcha !');
				 return false;
			 }
		},
		error:function(){
			alert('Please check the captcha !');
			return false;
		},
		beforeSend:function(){

		},
		complete: function () {

		}
	});
}
/******End Google captcha****/
///////////////////////////////////////////////////////////////////////////////////////////////
