;(function($, window, document, undefined) {
	$(document).ready(function() {
		var $win = $(window);
		var $quickPopPopups = $('.qp-js-popup');

		qpBtnHoversPopup();
		qpHidePopupOnClick();
		qpPopupFormSubmit();

		$win.on('load', function() {
			if ( $('body').is('.qp-browser-ie') ) {
				$( '.js-image-fit' ).each(function(i, container) {
					var $container  = $(container);
					var $image      = $container.find('img');
					var imageSource = $image.attr('src') || $image.data('src');

					$container.css('background-image', 'url(' + imageSource + ')');
					$image.addClass('screen-reader-text');
				});
			}
		});

		$win.on('load', function() {
			var $popupsOnLoad = $('.qp-js-popup-delay');

			qpTriggerPopup($popupsOnLoad);
		});

		var $mailchimpForms = $('.qp-mailchimp-form');

		$mailchimpForms.each(function(index, elem) {
			var $elem = $(elem);
			var interval;

			$elem.on('submit', function() {
				var $form = $(this);
				var $ajaxContainer = $form.closest('.qp-popup__body');
				var formData = $form.serializeArray();

				clearInterval(interval);

				interval = setInterval(function() {
					var $errorFields = $form.find('input.mce_inline_error, select.mce_inline_error, textarea.mce_inline_error');
					var $successResponse = $form.find('#mce-success-response');

					if ($errorFields.length < 1 && $successResponse.css('display') !== 'none') {
						clearInterval(interval);
						
						$ajaxContainer.addClass('is-loading').append('<i class="qp-ico-loading"></i>');

						$.ajax({
							type: 'POST',
							action: 'qp_ajax_form_submission_mailchimp',
							data: {
								action: 'qp_ajax_form_submission_mailchimp',
								form_data: formData
							},
							url: qp_options.ajax_url,
							success: function(result) {
								$ajaxContainer.removeClass('is-loading').find('.qp-ico-loading').remove();
								$ajaxContainer.closest('.qp-popup').addClass('is-submitted');
							},
							error: function(jqXHR, textStatus, errorThrown) {
								alert('An unexpected error occurred, please try reloading the page.');
							}
						});

						return;
					}

				}, 100);

				setTimeout(function() {
					var $errorFields = $form.find('input.mce_inline_error, select.mce_inline_error, textarea.mce_inline_error');
				}, 100);

				setTimeout(function() {
					if (interval) {
						clearInterval(interval);
					}
				}, 10000);
			});
		});

		$(document).on('click', '[class*="qp-js-trigger-popup-"]', function(event) {
			event.preventDefault();
			var classes = this.classList;
			var popupID = 'null';

			classes.forEach(function(elem, index) {
				if (elem.indexOf('qp-js-trigger-popup-') === -1) {
					return;
				}

				popupID = elem.replace('qp-js-trigger-popup-', '');
			});

			if (popupID === 'null') {
				return;
			}

			qpTriggerPopup($('#qp-popup-' + popupID));
		});

		$(document).on('mouseleave', function() {
			$('.qp-js-popup-on-exit').each(function(index, elem) {
				const $popup = $(elem);
				var cookieName = 'hide-popup-' + $popup.data('id');
				var snoozePopup = $popup.data('snooze');
				var snoozeDays = $popup.data('snooze-days');

				if ( snoozePopup === true && qpGetCookie(cookieName)) {
					return;
				}

				qpTriggerPopup($popup);

				var expirationDays = parseInt(snoozeDays);

				if (snoozePopup === true) {
					qpSetCookie(cookieName, true, expirationDays);
				}
			});
		});

		function qpSetCookie(cookieName, cookieValue, expirationDays) {
			const date = new Date();
			date.setTime(date.getTime() + (expirationDays * 24 * 60 * 60 * 1000));
			const expires = "expires="+ date.toUTCString();
			document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
		}

		function qpGetCookie(cname) {
			var name = cname + "=";
			var decodedCookie = decodeURIComponent(document.cookie);
			var ca = decodedCookie.split(';');
			for(var i = 0; i <ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ') {
					c = c.substring(1);
				}
				if (c.indexOf(name) == 0) {
					return c.substring(name.length, c.length);
				}
			}
			return "";
		}

		function qpTriggerPopup($popup) {
			$popup.each(function(index, elem) {
				var $elem = $(elem);
				var delay = $elem.data('delay');
				var regexPattern = /^\d+$/;


				if (! regexPattern.test(delay)) {
					delay = 0;
				}

				delay = parseInt(delay);
				delay *= 1000;

				setTimeout(function() {
					$elem.addClass('is-visible');
				}, delay);
			});
		}

		function qpHidePopup($popup) {
			var cookieName = 'hide-popup-' + $popup.data('id');
			var expirationDays = parseInt( $popup.data('snooze-days') );
			var snoozePopup = $popup.data('snooze');

			if (! $('body').is('.wp-admin')) {
				if (snoozePopup === true) {
					qpSetCookie(cookieName, true, expirationDays);
				}
			}

			$popup.removeClass('is-visible');

			var $previewContainer = $('.qp-preview-container');

			if ($previewContainer.length) {
				setTimeout(function() {
					$previewContainer.remove();
				}, 400);
			}
		}

		function qpHidePopupOnClick() {
			$('.qp-js-hide-popup').on('click', function(event) {
				event.preventDefault();
				var $popup = $(this).closest('.qp-js-popup');
				
				qpHidePopup($popup);
			});

			$(document).on('click', '.js-qp-preview-close', function(event) {
				event.preventDefault();
				var $popup = $(this).closest('.qp-preview-container').find('.qp-js-popup');
				
				qpHidePopup($popup);
			});

			$(document).on('click', function(event) {
				event.stopPropagation();

				var $eventTarget = $(event.target);

				if (! $eventTarget.is('.qp-popup .qp-popup__inner')) {
					return;
				}


				qpHidePopup($eventTarget.closest('.qp-popup'));
			});
		}

		function qpBtnHoversPopup() {
			$('.qp-js-btn-hover').each(function(index, elem) {
				var $elem = $(elem);
				var color = $elem.data('hoverColor');

				$elem.hover(
					function() {
						$elem.css({
							'background-color' : 'transparent',
							'color' : color,
						});
					},

					function() {
						$elem.css({
							'background-color' : color,
							'color' : '#fff',
						});
					}
				)
			})
		}

		function qpRegexTestEmail(email) {
			const regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

			return regex.test(email);
		}

		function qpRegexTestPhone(phone) {
			const regex = /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;

			return regex.test(phone);
		}

		function qpValidateFormFields($field) {
			var fieldValue = $field.val();
			var validationResult = true;


			if ($field.is('[type="checkbox"]')) {
				fieldValue = $field[0].checked;

				if (! $field.is('[required]')) {
					validationResult = true;

					return validationResult;
				}

				if ($field.is('[required]') && ! fieldValue) {
					validationResult = false;

					return validationResult;
				}

				if ($field.is('[required]') && fieldValue) {
					validationResult = true;

					return validationResult;
				}
			}

			if ($field.is('[required]') && ! fieldValue.length) {
				validationResult = false;

				return validationResult;
			}

			if (! $field.is('[required]') && ! fieldValue.length) {
				validationResult = true;

				return validationResult;
			}

			if (fieldValue.length && $field.is('.qp-email-field')) {
				validationResult = qpRegexTestEmail(fieldValue);
			}

			if (fieldValue.length && $field.is('.qp-phone-field')) {
				validationResult = qpRegexTestPhone(fieldValue);
			}

			return validationResult;
		}

		function qpPopupFormSubmit() {
			$('.qp-popup form.qp-form').on('submit', function(event) {
				event.preventDefault();

				var $this = $(this);
				var validationResult = true;

				var id = $this.closest('.qp-popup').attr('data-id');
				var emailValue = $this.find('#qp-popup-form-email-field').val();
				var nameValue = $this.find('#qp-popup-form-name-field').val();
				var phoneValue = $this.find('#qp-popup-form-phone-field').val();

				var $fields = $this.find('.qp-field');

				$fields.each(function(index, elem) {
					var $elem = $(elem);

					if (! qpValidateFormFields($elem)) {
						$elem.addClass('qp-error');

						validationResult = false;

						return;
					}

					$elem.removeClass('qp-error');
				});

				if (! validationResult) {
					event.preventDefault();

					return;
				}

		        // ajax the results!
				$.ajax({
					type: 'POST',
		        	data: {
		        		action  : 'qp_ajax_form_submission',
		        		'id'    : id,
		        		'email' : emailValue,
		        		'name'  : nameValue,
		        		'phone' : phoneValue
		        	},
		            url: qp_options.ajax_url,
		            success: function(result) {
						$this.closest('.qp-popup').addClass('is-submitted');
		            },
		            error: function(jqXHR, textStatus, errorThrown) {
		            	alert('An unexpected error occurred, please try reloading the page.');
		            }
		        });
			});
		}
	});
})(jQuery, window, document);
