(function($){
	'use strict';
	 
	jQuery(document).ready(function(){

		var tooltip = false;
		var timer2, timer3;
	 	var timePeriod = cartbounty_ec.hours; //Time period in hours
	 	var early_capture_form = '';
	 	var custom_button_selectors = cartbounty_co.custom_button_selectors;

	 	if((timePeriod == 0)){ //In case test mode is on, we clear information that we previously had displayed Early capture
	 		localStorage.removeItem('cartbounty_pro_ec_last_time');
	 	}

	 	function pauseAddToCartButtons(){ //Pausing Add to cart buttons
			var button = jQuery(this);
			var contact_saved = localStorage.getItem('cartbounty_pro_contact_saved');
			var custom_email = localStorage.getItem('cartbounty_pro_custom_email');
			var custom_phone = localStorage.getItem('cartbounty_pro_custom_phone');

			if(!button.hasClass('product_type_variable') && !button.hasClass('disabled') && (!contact_saved || timePeriod == 0) && !custom_email && !custom_phone ){ //Unless the button has these classes and Early capture data has not already been saved and we have not saved email via custom field before - we stop them from working and go ahead with Early capture procedure

				if( early_capture_form != '' ){ //Making sure to go further only in case Early capture form has loaded
					insertEarlyCaptureForm(button);
				}
				
				return false;
			}
		}

		function insertEarlyCaptureForm(button){ //Adding Early capture form
			var currentTime = new Date().getTime();
			var last_time_displayed = localStorage.getItem('cartbounty_pro_ec_last_time');
			var form = jQuery('#cartbounty-pro-early-capture-form');
			var button_triggered = button.hasClass('cartbounty-pro-ec-on');

			if(!button_triggered){ //If current button does not have Early capture popup visisble - destroy any other open pupups
				destroyEarlyCapturePopup();
				//This is required so we can click the button using native Javascript click
				removeTarget();
				button.addClass('cartbounty-pro-button-target'); //Add target class to current button that is clicked
			}
			
			if(cartbounty_ec.mandatory_input || last_time_displayed == null || (last_time_displayed == null && timePeriod == 0) ){ //If contact details are mandatory or time period has passed or test mode is enabled
				if(!button_triggered){ //In case Early capture is not visible on current button - display it
					button.addClass('cartbounty-pro-ec-on');
					displayEarlyCapture(currentTime, button);
				}else{ //In case Early capture already visible on current button
					if(!cartbounty_ec.mandatory_input){ //If mandatory input is disabled
						removeEarlyCaptureForm();
						resumeAddToCartButton(button);
						if(currentTime - last_time_displayed > timePeriod * 60 * 60 * 1000){ // If the time has expired, clear the cookie
							localStorage.removeItem('cartbounty_pro_ec_last_time');
						}
					}
				}

			}else{//Do not insert form in case the customer has already declined to provide input in Early capture and resume Add to cart buttons
				removeEarlyCaptureForm();
				resumeAddToCartButton(button);
				if(currentTime - last_time_displayed > timePeriod * 60 * 60 * 1000){ // If the time has expired, clear the cookie
					localStorage.removeItem('cartbounty_pro_ec_last_time');
				}
			}
		}

		function loadEarlyCaptureForm(){//Loading Early capture form data
			var data = {
				action: 							"insert_early_capture",
				cartbounty_pro_show_early_capture: 	true
			}

			jQuery.post(cartbounty_co.ajaxurl, data,
			function(response){ //Response consists of Early capture HTML template
				early_capture_form = response; //Save HTML response in a global variable
			})
			.fail(function(response) { //In case Ajax request was unable to fire
				if(response.status == '404'){
					console.log('Ajax request unable to fire due to missing access to native WordPress file: ' + cartbounty_co.ajaxurl + '. Please check with your server administrator that mod_security is disabled and nothing else has been setup to restrict access to this file.');
					resumeAddToCartButton(button); //Resuming button since we do not want to cause issues adding items to the cart
				}
			});
		}

		function displayEarlyCapture(currentTime, button){ //Displays Early capture form
			if(cartbounty_ec.style == 2){ //Not using Tooltipster in case Early capture should be displayed as a popup
				jQuery('body').append(early_capture_form); //Adding Early capture form to the footer

			}else{ //Using Tooltipster
				tooltip = button.tooltipster({
					'trigger': 				'custom',
					'contentAsHTML': 		true,
					'interactive': 			true,
					'content': 				early_capture_form,
					'onlyOne': 				true,
					'arrow': 				false,
					'side': 				'bottom',
					'distance': 			15,
					'zIndex': 				8000,
					'debug': 				false,
					'theme': 				'cartbounty-pro'
				});
				tooltip.tooltipster('show'); //Opening up Tooltipster popup
			}

			jQuery("#cartbounty-pro-early-capture-submit").on('click', {button: button }, getEarlyCaptureInput);
			jQuery('#cartbounty-pro-early-capture-email, #cartbounty-pro-early-capture-phone').on('keyup keypress change', {button: button }, getEarlyCaptureInput );
			jQuery('#cartbounty-pro-early-capture-close, #cartbounty-pro-early-capture-form-backdrop').on('click', {button: button }, closeEarlyCaptureForm );

			localStorage.setItem('cartbounty_pro_ec_last_time', currentTime);

			if ( typeof CartBountyProPhoneInput != "undefined") { //Initialize easy international phone input in case it is enabled
				CartBountyProPhoneInput.start();
			}
		}

		function getEarlyCaptureInput(e){ //Retrieving input when user enters any data in the email or phone fields
			var fields = jQuery("#cartbounty-pro-early-capture-email, #cartbounty-pro-early-capture-phone");
			let email = jQuery('#cartbounty-pro-early-capture-email').val() || '';
			let phone = jQuery('#cartbounty-pro-early-capture-phone').val() || '';
			var form_closing_time = 3500; //Default time after Early capture will automatically close
			var button = e.data.button;
			var submit_button_clicked = false;

			if(jQuery(this).attr('id') == 'cartbounty-pro-early-capture-submit'){ //In case the button is pressed, change the waiting time so that form would close immediately after Save button pressed
				form_closing_time = 0;
				submit_button_clicked = true;
			}
			
			if(email.length > 0 || phone.length > 0){
				clearTimeout(timer2);
				clearTimeout(timer3);
				var emailValidation = cartbounty_co.email_validation; //Regex validation
				var phoneValidation = cartbounty_co.phone_validation; //Regex validation

				//Adding loading class to the input field during input and then removing it once the user stops typing
				fields.closest('form').addClass("cartbounty-pro-loading");
				timer2 = setTimeout(function(){
					fields.closest('form').removeClass("cartbounty-pro-loading");
				}, 1000);

				if( email.match(emailValidation) || phone.match(phoneValidation) ){

					if(email != ''){ //If Email is not empty
						localStorage.setItem('cartbounty_pro_email', email); //Saving user's input in browser memory
					
					}else if(phone != ''){ //If Phone is not empty
						localStorage.setItem('cartbounty_pro_phone', phone); //Saving user's input in browser memory
					}

					fields.parent().addClass("cartbounty-pro-input-valid");
					fields.parent().removeClass("cartbounty-pro-input-error");

					timer3 = setTimeout(function(){
						removeEarlyCaptureForm();
						resumeAddToCartButton(button);
					}, form_closing_time);

				}else{
					//console.log('Not a valid email or phone address');
					removeFields();
					fields.parent().removeClass("cartbounty-pro-input-valid");
					
					if(submit_button_clicked){
						fields.parent().addClass("cartbounty-pro-input-error");
					}
				}
			}
		}

		function closeEarlyCaptureForm(e){ //Closing Early capture popup in case the close button pressed
			removeEarlyCaptureForm();
			if(!cartbounty_ec.mandatory_input){ //If mandatory input is disabled, resume buttons
				resumeAddToCartButton(e.data.button);
			}
		}

		function removeEarlyCaptureForm(){ //Removing Early capture popup
			var form = jQuery('#cartbounty-pro-early-capture-form');
			if(form.length > 0){ //If Early capture HTML exists on page
				form.addClass('cartbounty-pro-fade-out');
				setTimeout(function(){
					if(jQuery('#cartbounty-pro-early-capture-close')){ //In case Early capture close button pressed - Destroy tooltip so we would be able to display the tooltip again next time when clicking on the same button
						destroyEarlyCapturePopup();
					}
				}, 200);
			}
		}

		function resumeAddToCartButton(button){ //Resuming click on initial Add to Cart button that was pressed
			setTimeout(function(){
				jQuery(custom_button_selectors).off( "click", pauseAddToCartButtons );
				jQuery(document).off('click', pauseAddToCartButtons);
				jQuery(custom_button_selectors).off( "click", insertEarlyCaptureForm );
				destroyEarlyCapturePopup();

				//Using native Javascript to trigger button since jQuery button.trigger('click') function was not able to trigger click in case Ajax was disabled on All products page
				var buttons = document.getElementsByClassName('cartbounty-pro-button-target');
				for (var i=0;i<buttons.length; i++) {
				    buttons[i].click();
				}
				removeTarget();
			}, 210);
		}

		function passInputToCartBounty(){ //Function passes user's input to backend for abandoned cart update
			var email = localStorage.getItem('cartbounty_pro_email');
			var phone = localStorage.getItem('cartbounty_pro_phone');
			var consent = cartbounty_co.consent_field;
			var language = cartbounty_co.language;

			if( email == null && phone == null ){ //If data is missing, not sending anything
				return;
			}

			var fields = {
				email: 			email,
				phone: 			phone,
			};

			if( consent ){
				fields[consent] = 1;
			}

			var gtranslate_language = get_gtranslate_language();

			if( gtranslate_language ){
				language = gtranslate_language;
			}

			var data = {
				action:			"cartbounty_pro_save",
				nonce:			cartbounty_co.nonce,
				source:			"cartbounty_pro_early_capture",
				customer:		fields,
				language: 		language
			}

			if(!cartbounty_co.is_user_logged_in && cartbounty_co.recaptcha_enabled){ //If the user is not logged in and reCAPTCHA has been enabled
				grecaptcha.ready(function() { //If reCAPTCHA is loaded and ready
					grecaptcha.execute(cartbounty_co.recaptcha_site_key, {action: 'cartbounty_pro_abandoned_cart_tool'}).then(function(token) {
						data['cartbounty_pro_recaptcha_token'] = token; //Adding additional token element to the object
						jQuery.post(cartbounty_co.ajaxurl, data, handleResponse);
					});
				});

			}else{ //If the user is logged in or if the reCAPTCHA is disabled, not sending data to reCAPTCHA
				jQuery.post(cartbounty_co.ajaxurl, data, handleResponse);
			}
		}

		//Callback function taking care of cart update, coupon display and removal content that is no longer required
		function handleResponse(response){

			if(response.success){ //If successfully saved data

				if(response.data.coupon_html != ''){ //If coupon code generated - display popup informing about it
					jQuery('body').append(response.data.coupon_html);
					jQuery('#cartbounty-pro-tool-coupon-message').html(response.data.message);
					jQuery('#cartbounty-pro-tool-coupon').addClass('cartbounty-pro-fade-in-down');
					jQuery('#cartbounty-pro-tool-close-coupon-message').on('click', closeCouponMessage);
					setTimeout(closeCouponMessage, 10000);
				}

				//Updating cart with a coupon that we have added
				jQuery(document.body).trigger('update_checkout');
				jQuery(document.body).trigger('wc_fragment_refresh');

				localStorage.setItem('cartbounty_pro_contact_saved', true); //Setting a browser variable that the data has been passed. Necessary in cases when backend is not quick enough to identify that abandoned cart has been already saved
				//Removing data from local storage since we have saved it and no longer require it
				removeFields();
				removeExitIntentForm();
			}

			if(timePeriod == 0){ //If testing is enabled, remove this from storage so we would see the form again after page refresh
				localStorage.removeItem('cartbounty_pro_ec_last_time');
			}
		}

		//Function closes message about successful coupon application
		function closeCouponMessage(){
			jQuery('#cartbounty-pro-tool-coupon').removeClass('cartbounty-pro-fade-in-down');
			jQuery('#cartbounty-pro-tool-coupon').addClass('cartbounty-pro-fade-out-up');
		}

		function removeExitIntentForm(){ //Removing Exit Intent popup
			if(jQuery('#cartbounty-pro-exit-intent-form').length > 0){ //If Exit intent HTML exists on page
				jQuery('#cartbounty-pro-exit-intent-form').remove();
				jQuery('#cartbounty-pro-exit-intent-form-backdrop').remove();
			}
		}

		function destroyEarlyCapturePopup(){
			jQuery(custom_button_selectors).removeClass('cartbounty-pro-ec-on');
			if(cartbounty_ec.style == 2){ //Not using Tooltipster in case Early capture should be displayed as a popup
				jQuery('#cartbounty-pro-early-capture-form').remove();
				jQuery('#cartbounty-pro-early-capture-form-backdrop').remove();
			}else{ //In case Tooltipster is used - destroy instance of tooltipster
				if(tooltip){
					tooltip.tooltipster('destroy');
					tooltip = false;
				}
			}
		}

		function removeTarget(){
			jQuery(custom_button_selectors).removeClass('cartbounty-pro-button-target'); //Removing click target class from all buttons that have it
		}

		function removeFields(){ //Removing localstorage saved user input values
			localStorage.removeItem('cartbounty_pro_email');
			localStorage.removeItem('cartbounty_pro_phone');
		}

		function autofillCheckoutField(){
			if(jQuery("#billing_email").length > 0 || jQuery("#billing_phone").length > 0){ //If at least one of these two fields exist on page
				var email = localStorage.getItem('cartbounty_pro_email');
				var phone = localStorage.getItem('cartbounty_pro_phone');

				if( email != null ){ //If data is missing, not filling the field
					jQuery("#billing_email").val(email);
				}
				if( phone != null ){ //If data is missing, not filling the field
					jQuery("#billing_phone").val(phone);
				}
			}
		}

		//Retrieve GTranslate selected language
		function get_gtranslate_language(){
			//Retrieve GTranslate selected language in case using the free GTranslate version
			var cookie = document.cookie.match(/(?:^|;\s*)googtrans=([^;]*)/);
			
			if (cookie && cookie[1]){
				var parts = cookie[1].split('/');
				
				if (parts.length === 3 && parts[2]){
					return parts[2]; // Example: '/en/es' → 'es'
				}
			}

			//Retrieve GTranslate selected language in case using the paid GTranslate version
			return document.documentElement.getAttribute('lang') || '';
		}

		passInputToCartBounty(); //Used in case a page is reloaded and Ajax was not able to pass the data
		autofillCheckoutField(); //Used in case a page is redirected to Checkout immediately after Add to cart button to fill the Email or Phone field
		loadEarlyCaptureForm(); //Loading Early capture form as soon as the document loads

		jQuery(custom_button_selectors).on("click", pauseAddToCartButtons ); //Disabling Add to Cart button actions by default
		jQuery(document).on('click', custom_button_selectors, pauseAddToCartButtons); ////Disabling Add to Cart button in case Ajax loads product Quick view
		jQuery(document).on('added_to_cart', passInputToCartBounty ); //Sending data over for saving in case WooCommerce "added_to_cart" event fires after product added to cart
	});

})(jQuery);