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

	 	var timer;
	 	var timePeriod = cartbounty_ei.hours; //Time period in hours
	 	var mobileExitIntentEnabled = cartbounty_ei.mobile_exit_intent_enabled;
	 	var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
		var pageTouches = 0;
		var couponResponseData = null;
		var exitIntentWindowClosed = false;

	 	function is_mobile_device(){
			var mobile = false;
			
			if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
			|| /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
				mobile = true;
			}

			return mobile;
		}

		function showExitIntentForm(event){
			var displayed = false;
			var currentTime = new Date().getTime();
			var last_time_displayed = localStorage.getItem('cartbounty_pro_ei_last_time');
			var product_count = cartbounty_ei.product_count; //Products in the shopping cart

			if(localStorage.getItem('cartbounty_pro_product_count') !== null){
				product_count = localStorage.getItem('cartbounty_pro_product_count');
			}

			if(product_count == 0) return; //Exit if we have no products

			if(event == 'cartbounty_pro_scrolling_up' || event == 'cartbounty_pro_going_back'){ //In case if user is scrolling up or using back button

				if(last_time_displayed == null || timePeriod == 0) { //If time period has passed or Exit Intent test mode is enabled
					$('#cartbounty-pro-exit-intent-form').addClass('cartbounty-pro-visible'); //Display form
					$('#cartbounty-pro-exit-intent-form-backdrop').css('opacity', '').addClass('cartbounty-pro-visible'); //Show backdrop
					displayed = true;

					if(timePeriod != 0){ //If test mode enabled - do not set this value
						localStorage.setItem('cartbounty_pro_ei_last_time', currentTime);
					}

				}else if(currentTime - last_time_displayed > timePeriod * 60 * 60 * 1000){ // If the time has expired, clear the cookie
					localStorage.removeItem('cartbounty_pro_ei_last_time');
				}

			}else if (event.clientY <= 0 && event.target.tagName.toLowerCase() != 'select' && event.target.tagName.toLowerCase() != 'option' && event.target.tagName.toLowerCase() != 'input') { //Checking if mouse Y poosition goes beyond the top screen and that we haven't clicked on dropdown or autocomplete input field

				if(last_time_displayed == null || timePeriod == 0) { //If time period has passed or Exit Intent test mode is enabled
					$('#cartbounty-pro-exit-intent-form').addClass('cartbounty-pro-visible'); //Display form
					$('#cartbounty-pro-exit-intent-form-backdrop').css('opacity', '').addClass('cartbounty-pro-visible'); //Show backdrop
					displayed = true;

					if(timePeriod != 0){ //If test mode enabled - do not set this value
						localStorage.setItem('cartbounty_pro_ei_last_time', currentTime);
					}

				}else if(currentTime - last_time_displayed > timePeriod * 60 * 60 * 1000){ // If the time has expired, clear the cookie
					localStorage.removeItem('cartbounty_pro_ei_last_time');
				}
			}

			return displayed;
		}

	 	function getExitIntentData() { //Reading data entered in the Exit intent popup
	 		let email = jQuery('#cartbounty-pro-exit-intent-email').val() || '';
	 		let phone = jQuery('#cartbounty-pro-exit-intent-phone').val() || '';
			
			if(email.length > 0 || phone.length > 0){				
				clearTimeout(timer);
				var emailValidation = cartbounty_co.email_validation; //Regex validation
				var phoneValidation = cartbounty_co.phone_validation; //Regex validation
				var consent = cartbounty_co.consent_field;
				var language = cartbounty_co.language;
				
				if( email.match(emailValidation) || phone.match(phoneValidation) ){
					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_exit_intent",
						customer:		fields,
						language: 		language
					}

					timer = setTimeout(function(){
						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);
						}
					}, 600);
				}
			}
		}

		//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
					couponResponseData = response.data;
					
					if(exitIntentWindowClosed == true ){ //If Exit Inten window closed before coupon code could be applied - show coupon response message
						maybeShowCouponResult();
					}
				}
				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
			}

			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');
			}
		}

		//Display coupon result message if coupon provided
		function maybeShowCouponResult() {
			if(couponResponseData){
				$('body').append(couponResponseData.coupon_html);
				$('#cartbounty-pro-tool-coupon-message').html(couponResponseData.message);
				$('#cartbounty-pro-tool-coupon').addClass('cartbounty-pro-fade-in-down');
				$('#cartbounty-pro-tool-close-coupon-message')
				.off('click')
				.on('click', closeCouponMessage);

				setTimeout(closeCouponMessage, 10000); //automatically close coupon message after a set period of time

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

				//Clear data after showing
				couponResponseData = null;
			}
		}

		//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 increaseProductCount(){ //Increasing product count
			if( localStorage.getItem( 'cartbounty_pro_product_count' ) === null ){
				localStorage.setItem( 'cartbounty_pro_product_count', 1 );

			}else{
				localStorage.setItem( 'cartbounty_pro_product_count', parseInt( localStorage.getItem( 'cartbounty_pro_product_count' ) ) + 1 );
			}
		}

		function decreaseProductCount(){ //Decreasing product count
			if( localStorage.getItem( 'cartbounty_pro_product_count' ) === null ) return;
			localStorage.setItem( 'cartbounty_pro_product_count', parseInt( localStorage.getItem( 'cartbounty_pro_product_count' ) ) - 1 );
		}

		function closeExitIntentForm(){ //Close exit intent window
			exitIntentWindowClosed = true;
			$('#cartbounty-pro-exit-intent-form').addClass('cartbounty-pro-fade-out'); //Hide form
			
			setTimeout(function(){
				$('#cartbounty-pro-exit-intent-form').removeClass('cartbounty-pro-visible'); //Hide form
				$('#cartbounty-pro-exit-intent-form-backdrop').removeClass('cartbounty-pro-visible'); //Hide backdrop
				maybeShowCouponResult();
			}, 300);
		}

		//Handling Exit Intent form submit button. Making sure the page is not reloaded
		function handleFormAfterSubmit(e){
			e.preventDefault();

			//If form is invalid, let browser show validation UI
			if (!this.checkValidity()){
				this.reportValidity(); //Triggers browser validation tooltip
				return;
			}

			closeExitIntentForm();
		}

		function checkScrollDirection(){ //Checking scroll direction and speed to see if we must display Exit Intent on Mobile
			if(!mobileExitIntentEnabled || !is_mobile_device()) return; //Stop if Mobile Exit Intent disabled or this is not a mobile device
				
			if(cartbounty_pro_scrollSpeed() < -120){ //In case if the user scrolls up with a speed of 150
				showExitIntentForm('cartbounty_pro_scrolling_up');
			}
		}

		var cartbounty_pro_scrollSpeed = (function(){ //Function that checks the speed of scrolling
			
			if(!mobileExitIntentEnabled) return; //Stop if Mobile Exit Intent disabled
			
			var last_position, new_position, timer, delta, delay = 50;// in 'ms' (higher means lower fidelity )
			
			function clear() {
				last_position = null;
				delta = 0;
			}

			clear();

			return function(){
				new_position = window.scrollY;
				
				if (last_position != null){
					delta = new_position - last_position;
				}

				last_position = new_position;
				clearTimeout(timer);
				timer = setTimeout(clear, delay);

				return delta;
			};
			
		})();

		function startMobileBackButton(){

			if(!mobileExitIntentEnabled || !is_mobile_device()) return; //Stop if Mobile Exit Intent disabled or this is not a mobile device

			if(!localStorage.getItem('cartbounty_pro_popup_displayed')){

				if('cartbounty-pro-back-trigger' !== window.history.state){
					window.addEventListener( 'touchstart', handleHistory );
				}
			}

			window.onpopstate = function(t){
				var result = false;

				if(isIOS){ //In iOs devices popstate is run every time a user clicks back and previous page is loaded. This in turn creates a "onpopstate" loop which we try to break using localstorage value

					if(localStorage.getItem('cartbounty_pro_popup_displayed') && localStorage.getItem('cartbounty_pro_just_finished_loop')){
						//Do nothing in case we just went back in history
						localStorage.removeItem('cartbounty_pro_just_finished_loop');
						return;

					}else if(localStorage.getItem('cartbounty_pro_popup_displayed') && !localStorage.getItem('cartbounty_pro_just_finished_loop')){
						localStorage.setItem('cartbounty_pro_just_finished_loop', true);
						goBack();

					}else{
						result = showExitIntentForm('cartbounty_pro_going_back');

						if(result){ //If popup successfully displayed

							if(timePeriod != 0){ //If test mode enabled - do not set this value
								localStorage.setItem('cartbounty_pro_popup_displayed', true);
							}

							window.removeEventListener('touchstart', handleHistory);
						
						}else if(!localStorage.getItem('cartbounty_pro_just_finished_loop')){ //Going back in case popup was not displayed
							localStorage.setItem('cartbounty_pro_just_finished_loop', true);
							goBack();
						}
					}

				}else{ //All other mobile devices pass through this branch to be brought back in history

					if(localStorage.getItem('cartbounty_pro_popup_displayed')){
						goBack();

					}else{
						result = showExitIntentForm('cartbounty_pro_going_back');

						if( result ){ //If popup successfully displayed
							
							if(timePeriod != 0){ //If test mode enabled - do not set this value
								localStorage.setItem('cartbounty_pro_popup_displayed', true);
							}

							window.removeEventListener('touchstart', handleHistory);

						}else{ //Going back in case popup was not displayed
							goBack();
						}
					}
				}
			}
		}

		//Save current history row inisde local storage memory variable
		function handleHistory(action, state = 'cartbounty-pro-back-trigger-placebo'){

			if(localStorage.getItem('cartbounty_pro_popup_displayed') && action !== 'delete') return; //Exit If popup already displayed and we are not trying to remove item from history

			var cartbounty_pro_history_clicks = JSON.parse( localStorage.getItem( 'cartbounty_pro_history_clicks' ) || '[]' );

			if(action == 'delete'){
				cartbounty_pro_history_clicks.pop();
				localStorage.setItem('cartbounty_pro_history_clicks', JSON.stringify(cartbounty_pro_history_clicks));

			}else{

				var current_page_url = location.href;
				var touches = JSON.parse( localStorage.getItem( 'cartbounty_pro_touches' ) || '{}' );
				pageTouches++;
			
				if((touches.url !== current_page_url || touches.clicks >= pageTouches) && Object.keys(touches).length !== 0){ //In case user lands on a new page or reloads existing one and touches object has already been created - add previous page clicks to array
					cartbounty_pro_history_clicks.push(touches);
					localStorage.setItem('cartbounty_pro_history_clicks', JSON.stringify(cartbounty_pro_history_clicks));
				}

				window.history.pushState(state, document.title, current_page_url);
				localStorage.setItem('cartbounty_pro_touches', JSON.stringify({clicks: pageTouches, url: current_page_url}));
			}

		}

		function goBack(){ //Figure how many pages should be traveled back			
			var touches = JSON.parse(localStorage.getItem( 'cartbounty_pro_touches' ) || '{}');
			var cartbounty_pro_history_clicks = JSON.parse(localStorage.getItem('cartbounty_pro_history_clicks') || '[]');
			var history_length = cartbounty_pro_history_clicks.length;

			//First go back the amount of clicks user has made on current page
			if(Object.keys(touches).length !== 0 && localStorage.getItem('cartbounty_pro_touches_object_deleted')){ //If object is not empty and it has not been deleted
				localStorage.removeItem('cartbounty_pro_touches'); //Remove object since it is no longer required
				localStorage.setItem('cartbounty_pro_touches_object_deleted', true);
				var extra_clicks = 1;
				var clicks = touches.clicks - extra_clicks; //Subtracting additional value to make sure we return exactly to previous page
				window.history.go(-clicks);

			}else{ //Taking the last item from the history array and using it to go back

				if(history_length !== 0){ //If array is not empty
					var last_item = cartbounty_pro_history_clicks.pop();
					var extra_clicks = 2;
					var clicks = last_item.clicks + extra_clicks; //Subtracting additional value to make sure we return exactly to previous page
					handleHistory( 'delete' );
					window.history.go(-clicks);
				
				}else{
					window.history.back();
				}
			}
		}

		//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') || '';
		}

		startMobileBackButton();

		jQuery(document).on('mouseleave', showExitIntentForm); //Displaying Exit intent if the mouse leaves the window
		jQuery('#cartbounty-pro-exit-intent-email, #cartbounty-pro-exit-intent-phone').on('keyup keypress change', getExitIntentData ); //All action happens on or after changing the email or hpone field.
		jQuery('#cartbounty-pro-exit-intent-close, #cartbounty-pro-exit-intent-form-backdrop').on('click', closeExitIntentForm ); //Close Exit intent window
		jQuery('#cartbounty-pro-exit-intent-form form').on('submit', handleFormAfterSubmit); //Closing Exit Intent form
		jQuery(document).on('added_to_cart', increaseProductCount ); //Increasing product count if Ajax Add to Cart button pressed
		jQuery(document).on('removed_from_cart', decreaseProductCount ); //Firing the function if item is removed from cart via Ajax 
		jQuery(document).on('scroll', checkScrollDirection ); //Binding function to scroll event
	});

})(jQuery);