var jwsThemeModule;
(function($) {
	"use strict";
	jwsThemeModule = (function() {
		return { 
		    jws_script: jws_script, 
			init: function() {
				this.login_form();
				this.header_sticky();
				this.jwsCompare();
				this.jwsWishlist();
				this.car_single_tabs();
				this.search_product();
				this.jws_theme_countdown();
				this.post_gallery();
				this.post_related();
				this.menu_mobile();
				this.menu_offset();
				this.scrollTop();
				this.menu_list();
                this.mobile_default();
			},

			menu_list: function() {
				$(document).on("click", 'body[data-elementor-device-mode="mobile"] .jws-menu-list.toggle-mobile h3', function() {
					$(this).next('ul').slideToggle();
				});
			},
			post_related: function() {
				$('.post_related_slider').not('.slick-initialized').slick({
					dots: false,
					arrows: true,
					swipeToSlide: true,
					prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
					nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
				});
			},
			jws_theme_countdown: function() {
				var $tb_countdown_js = $('.idealautoduct-sale-time');
				if($tb_countdown_js.length > 0) {
					$tb_countdown_js.each(function() {
						var $this = $(this);
						var $countdown_time = $this.data('countdown');
						var $current_time = new Date().getTime();
						var $dateEnd = new Date($countdown_time * 1000);
						if($countdown_time > $current_time) {
							$this.remove();
							return;
						}
						// Update the count down every 1 second
						setInterval(function() {
							// Get today's date and time
							var $current_time = new Date().getTime();
							// Find the distance between now and the count down date
							var distance = $dateEnd - $current_time;
							// Time calculations for days, hours, minutes and seconds
							var days = Math.floor(distance / (1000 * 60 * 60 * 24));
							var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
							var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
							var seconds = Math.floor((distance % (1000 * 60)) / 1000);
							if(days < 1) {
								$this.html('<div class="jws-box-countdown"><span class="wrapper"><span>0</span> <p>' + $this.data('d') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>0</span> <p>' + $this.data('h') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>0</span> <p>' + $this.data('m') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>0</span> <p>' + $this.data('s') + '</p></span></div>');
								return false;
							}
							$this.html('<div class="jws-box-countdown"><span class="wrapper"><span>' + days + '</span> <p>' + $this.data('d') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>' + hours + '</span> <p>' + $this.data('h') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>' + minutes + '</span> <p>' + $this.data('m') + '</p></span></div><span>:</span>' + '<div class="jws-box-countdown"><span class="wrapper"><span>' + seconds + '</span> <p>' + $this.data('s') + '</p></span></div>');
						}, 1000);
					});
				}
			},
			/* Car form for autocomplete input fields*/
			search_product: function() {
				if(typeof($.fn.devbridgeAutocomplete) == 'undefined') return;
				$('form.jws-ajax-search').eq(0).each(function() {
					var $this = $(this),
						thumbnail = parseInt($this.data('thumbnail')),
						$results = $this.parent().find('.jws-search-results'),
						url = jwsThemeModule.jws_script.ajax_url + '?action=jws_ajax_search_product',
						price = parseInt($this.data('price'));
					$results.on('click', '.view-all-results', function() {
						$this.submit();
					});
					$this.find('[type="text"]').devbridgeAutocomplete({
						serviceUrl: url,
						appendTo: $results,
						onSelect: function(suggestion) {
							if(suggestion.permalink.length > 0) window.location.href = suggestion.permalink;
						},
						onSearchStart: function() {
							$this.addClass('search-loading');
						},
						beforeRender: function(container) {
							if(container[0].childElementCount > 2) $(container).append('<div class="view-all-results"><span>View All post</span></div>');
						},
						onSearchComplete: function() {
							$this.removeClass('search-loading');
						},
						formatResult: function(suggestion, currentValue) {
							if(currentValue == '&') currentValue = "&#038;";
							var returnValue = '';
							if(thumbnail && suggestion.thumbnail) {
								returnValue += ' <div class="suggestion-thumb">' + suggestion.thumbnail + '</div>';
							}
							returnValue += '<div class="suggestion_content"><h4 class="suggestion-title result-title">' + suggestion.value + '</h4>';
							if(suggestion.no_found) returnValue = '<div class="suggestion-title no-found-msg">' + suggestion.value + '</div>';
							if(price && suggestion.price) {
								returnValue += ' <div class="suggestion-price price">' + suggestion.price + '</div></div>';
							}
							return returnValue;
						}
					});
					$('.jws-search-results').click(function(e) {
						e.stopPropagation();
					});
				});
			},
			car_single_tabs: function() {
				$(document).on('click', '.form-filter-product-cars span[data-tabs]', function() {
					var tabs_main = $(this).parents('.form-filter-product-cars');
					tabs_main.find('span[data-tabs]').removeClass('active');
					tabs_main.find('.tabcontent').hide();
					var tab = $(this).data('tabs');
					$(this).addClass('active');
					$('#' + tab).show();
				});
			},
			jwsCompare: function() {
				var cookiesName = 'jws_compare_list';
             
				if(jwsThemeModule.jws_script.is_multisite) {
				}
				var $body = $("body"),
					$widget = $('.jws-compare-info-widget'),
					compareCookie = Cookies.get(cookiesName);
				if($widget.length > 0) {
					try {
						var ids = JSON.parse(compareCookie);
						$widget.find('.compare-count').text(ids.length);
					} catch(e) {
						console.log('cant parse cookies json');
					}
				}
				// Add to compare action
				$body.on('click', 'a.jws-compare-btn, a.jws-comparesg-btn', function(e) {
					var $this = $(this),
						id = $this.data('id');
					if($this.hasClass('added')) return true;
					e.preventDefault();
					$this.addClass('loading');
					$.ajax({
						url: jwsThemeModule.jws_script.ajax_url,
						data: {
							action: 'jws_add_to_compare',
							id: id
						},
						dataType: 'json',
						method: 'GET',
						success: function(response) {
							if(response.table) {
								updateCompare(response);
							} else {
								console.log('something wrong loading compare data ', response);
							}
						},
						error: function() {
							console.log('We cant add to compare. Something wrong with AJAX response. Probably some PHP conflict.');
						},
						complete: function() {
							$this.removeClass('loading').addClass('added');
						},
					});
				});
				// Remove from compare action
				$body.on('click', '.jws-compare-remove', function(e) {
					var $table = $('.jws-compare-table');
					e.preventDefault();
					var $this = $(this),
						id = $this.data('id');
					$table.addClass('loading');
					$this.addClass('loading');
					$.ajax({
						url: jwsThemeModule.jws_script.ajax_url,
						data: {
							action: 'jws_remove_from_compare',
							id: id
						},
						dataType: 'json',
						method: 'GET',
						success: function(response) {
							if(response.table) {
								updateCompare(response);
							} else {
								console.log('something wrong loading compare data ', response);
							}
						},
						error: function() {
							console.log('We cant remove product compare. Something wrong with AJAX response. Probably some PHP conflict.');
						},
						complete: function() {
							$table.removeClass('loading');
							$this.addClass('loading');
						},
					});
				});
				// Elements update after ajax
				function updateCompare(data) {
					if($widget.length > 0) {
						$widget.find('.compare-count').text(data.count);
					}
					if($('.jws-compare-table').length > 0) {
						$('.jws-compare-table').replaceWith(data.table);
					}
				}
			},
			/**
			 *-------------------------------------------------------------------------------------------------------------------------------------------
			 * jws wishlist functions
			 *-------------------------------------------------------------------------------------------------------------------------------------------
			 */
			jwsWishlist: function() {
				var cookiesName = 'jws_wishlist_list';
				if(jwsThemeModule.jws_script.is_multisite) {
					//cookiesName += '_' + jwsThemeModule.jws_script.current_blog_id;
				}
				var $body = $("body"),
					$widget = $('.jws-wishlist-info-widget'),
					wishlistCookie = Cookies.get(cookiesName);
				if($widget.length > 0) {
					try {
						var ids = JSON.parse(wishlistCookie);
						$widget.find('.wishlist-count').text(ids.length);
					} catch(e) {
						console.log('cant parse cookies json');
					}
				}
				// Add to wishlist action
				$body.on('click', 'a.jws-wishlist-btn , a.jws-wishlistsg-btn', function(e) {
					var $this = $(this),
						id = $this.data('id');
					if($this.hasClass('added')) return true;
					e.preventDefault();
					$this.addClass('loading');
					$.ajax({
						url: jwsThemeModule.jws_script.ajax_url,
						data: {
							action: 'jws_add_to_wishlist',
							id: id
						},
						dataType: 'json',
						method: 'GET',
						success: function(response) {
							if(response.table) {
								updateWishlist(response);
							} else {
								console.log('something wrong loading wishlist data ', response);
							}
						},
						error: function() {
							console.log('We cant add to wishlist. Something wrong with AJAX response. Probably some PHP conflict.');
						},
						complete: function() {
							$this.removeClass('loading').addClass('added');
						},
					});
				});
				// Remove from wishlist action
				$body.on('click', '.jws-wishlist-remove', function(e) {
					var $table = $('.jws-wishlist-table');
					e.preventDefault();
					var $this = $(this),
						id = $this.data('id');
					$table.addClass('loading');
					$this.addClass('loading');
					$.ajax({
						url: jwsThemeModule.jws_script.ajax_url,
						data: {
							action: 'jws_remove_from_wishlist',
							id: id
						},
						dataType: 'json',
						method: 'GET',
						success: function(response) {
							if(response.table) {
								updateWishlist(response);
							} else {
								console.log('something wrong loading wishlist data ', response);
							}
						},
						error: function() {
							console.log('We cant remove product wishlist. Something wrong with AJAX response. Probably some PHP conflict.');
						},
						complete: function() {
							$table.removeClass('loading');
							$this.addClass('loading');
						},
					});
				});
				// Elements update after ajax
				function updateWishlist(data) {
					if($widget.length > 0) {
						$widget.find('.wishlist-count').text(data.count);
					}
					if($('.jws-wishlist-table').length > 0) {
						$('.jws-wishlist-table').replaceWith(data.table);
					}
				}
			},
			header_sticky: function() {
				if($('.cafe-row-sticky')[0]) {
					$(window).on('load', function() {
						$('.cafe-row-sticky').each(function() {
							var $this = $(this);
							var $sidebar = $('.jws_sticky_move');
							var $parent = $(this).parent();
							var current_width = 0;
							$(window).resize(function() {
								if(current_width != $(window).width()) {
									current_width = $(window).width();
									$parent.height('');
									if(current_width > 1024.98 && $this.hasClass('desktop-sticky')) {
										$parent.height($this.outerHeight());
									} else if(current_width < 1024.98 && current_width > 768.98 && $this.hasClass('tablet-sticky')) {
										$parent.height($this.outerHeight());
									} else if(current_width < 768.98 && $this.hasClass('mobile-sticky')) {
										$parent.height($this.outerHeight());
									} else {
										$this.removeClass('is-sticky');
										$this.find('.elementor-widget-clever-site-logo').removeClass('header-is-sticky');
									}
								}
							}).resize();
							var HeaderTop = $parent.offset().top - $('body').offset().top;
							var old_top_position = 0;
							$(window).on('scroll', function() {
								var top = $(window).scrollTop();
								if($this.hasClass('cafe-scroll-up-sticky')) {
									top = top - $parent.outerHeight();
									if(old_top_position > top && top > $parent.outerHeight() * 3) {
										$this.not('.active-sticky').addClass('active-sticky');
										$this.removeClass('no-active-sticky');
										$sidebar.removeClass('no-active-sticky');
									} else {
										$this.removeClass('active-sticky');
										if($this.hasClass('is-sticky')) {
											$this.addClass('no-active-sticky');
											$sidebar.addClass('no-active-sticky');
										}
									}
									old_top_position = top;
								}
								if(current_width > 1024.98 && $this.hasClass('desktop-sticky')) {
									if(HeaderTop < top) {
										$this.not('.is-sticky').addClass('is-sticky');
										$this.find('.elementor-widget-clever-site-logo:not(.header-is-sticky)').addClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').removeClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideUp();
									} else {
										$this.removeClass('is-sticky');
										$this.removeClass('no-active-sticky');
										$sidebar.removeClass('no-active-sticky');
										$this.find('.elementor-widget-clever-site-logo').removeClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').addClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideDown();
									}
								} else if(current_width < 1024.98 && current_width > 768.98 && $this.hasClass('tablet-sticky')) {
									if(HeaderTop < top) {
										$this.not('.is-sticky').addClass('is-sticky');
										$this.find('.elementor-widget-clever-site-logo').addClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').removeClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideUp();
									} else {
										$this.removeClass('is-sticky');
										$this.removeClass('no-active-sticky');
										$sidebar.removeClass('no-active-sticky');
										$this.find('.elementor-widget-clever-site-logo').removeClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').addClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideDown();
									}
								} else if(current_width < 768.98 && $this.hasClass('mobile-sticky')) {
									if(HeaderTop < top) {
										$this.not('.is-sticky').addClass('is-sticky');
										$this.find('.elementor-widget-clever-site-logo:not(.header-is-sticky)').addClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').removeClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideUp();
									} else {
										$this.removeClass('is-sticky');
										$this.removeClass('no-active-sticky');
										$sidebar.removeClass('no-active-sticky');
										$this.find('.elementor-widget-clever-site-logo.header-is-sticky').removeClass('header-is-sticky');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').addClass('toggle-active');
										$('.cafe-wrap-menu .toggle .arrow.on-scroll').parents('.cafe-wrap-menu').find('.wrap-menu-inner').slideDown();
									}
								}
							});
						});
					});
				}
			},
			post_share: function() {
				$('.post-share .social_label').on('click', function() {
					var parents = $(this).parents('.post-share');
					parents.toggleClass('opened');
					if(parents.hasClass('opened')) {
						parents.find("a").delay(100).each(function(i) {
							$(this).delay(100 * i).queue(function() {
								$(this).addClass("show");
								$(this).dequeue();
							});
						});
					} else {
						parents.find("a").removeClass('show');
					}
				});
			},
			/* ## Theme popup */
			mobile_default: function() {
				$('body').on('click', '.jws-tiger-mobile,.overlay', function() {
					$(this).parents('.elemetor-menu-mobile').toggleClass('active');
				});
			},
			/* ## Theme popup */
			handlePopup: function(data) {
				$(data).each(function() {
					// Activate popup
					$(this).addClass('visible');
					$(this).find('.btn-loading-disabled').addClass('btn-loading');
				});
			},
			scrollTop: function() {
				//Check to see if the window is top if not then display button
				$(window).scroll(function() {
					if($(this).scrollTop() > 100) {
						$('.backToTop').addClass('totop-show');
					} else {
						$('.backToTop').removeClass('totop-show');
					}
				});
				//Click event to scroll to top
				$('.backToTop').on("click", function() {
					$('html, body').animate({
						scrollTop: 0
					}, 100);
					return false;
				});
			},
			/**
			 *-------------------------------------------------------------------------------------------------------------------------------------------
			 * video popup
			 *-------------------------------------------------------------------------------------------------------------------------------------------
			 */
			video_popup: function() {
				$('.video_format').eq(0).each(function() {
					$('.video_format').magnificPopup({
						delegate: 'a',
						type: 'image',
						removalDelay: 500, //delay removal by X to allow out-animation
						callbacks: {
							beforeOpen: function() {
								this.st.mainClass = 'mfp-zoom-in';
							},
							elementParse: function(item) {
								item.type = 'iframe',
									item.iframe = {
										patterns: {
											youtube: {
												index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).
												id: 'v=', // String that splits URL in a two parts, second part should be %id%
												// Or null - full URL will be returned
												// Or a function that should return %id%, for example:
												// id: function(url) { return 'parsed id'; } 
												src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe. 
											},
											vimeo: {
												index: 'vimeo.com/',
												id: '/',
												src: '//player.vimeo.com/video/%id%?autoplay=1'
											}
										}
									};
							}
						},
					});
				});
			},
			/**
			 *-------------------------------------------------------------------------------------------------------------------------------------------
			 * post fomart
			 *--------o-----------------------------------------------------------------------------------------------------------------------------------
			 */
			post_gallery: function() {
				$('.post-image-slider').not('.slick-initialized').slick({
					dots: false,
					arrows: true,
					prevArrow: '<span class="jws-carousel-btn prev-item"><i class="jws-icon-arrow_carrot-left"></i></span>',
					nextArrow: '<span class="jws-carousel-btn next-item "><i class="jws-icon-arrow_carrot-right"></i></span>',
				});
			},
			menu_offset: function() {
				var setOffset = function(li) {
					var $dropdown = li;
					var dropdownWidth = $dropdown.outerWidth();
					var dropdownOffset = $dropdown.offset();
					var toRight;
					var viewportWidth;
					var dropdownOffsetRight;
					viewportWidth = $(document).width();
					if(!dropdownWidth || !dropdownOffset) {
						return;
					}
					if($dropdown.hasClass('mega_menu')) {
						dropdownOffsetRight = viewportWidth - dropdownOffset.left - dropdownWidth;
						var extraSpace = 15;
						var dropdownOffsetLeft;
						if($('body').hasClass('rtl')) {
							dropdownOffsetLeft = dropdownOffsetRight;
							if(dropdownOffsetLeft + dropdownWidth >= viewportWidth) {
								toRight = dropdownOffsetLeft + dropdownWidth - viewportWidth;
								$dropdown.css({
									right: -toRight - extraSpace
								});
							}
						} else {
							dropdownOffsetLeft = dropdownOffset.left;
							if(dropdownOffsetLeft + dropdownWidth >= viewportWidth) {
								toRight = dropdownOffsetLeft + dropdownWidth - viewportWidth;
								$dropdown.css({
									left: -toRight - extraSpace
								});
							}
						}
					}
				};
				$('.elementor_jws_menu_layout_menu_horizontal .jws_main_menu_inner .nav > li').each(function() {
					var $menu = $(this);
					$menu.on('mouseenter mousemove', function() {
						if($menu.hasClass('wd-offsets-calculated')) {
							return;
						}
						$menu.find(' > .sub-menu-dropdown').each(function() {
							setOffset($(this));
						});
						$menu.addClass('wd-offsets-calculated');
					});
					setTimeout(function() {
						$(window).on('resize', function() {
							$menu.removeClass('wd-offsets-calculated');
							$menu.find(' > .sub-menu-dropdown').attr('style', '');
						});
					}, 2000);
				});
			},
			menu_mobile: function() {
				var dropDownCat = $(".elementor_jws_menu_layout_menu_vertical .menu-item-has-children ,.elementor_jws_menu_layout_menu_vertical .menu_has_shortcode"),
					elementIcon = '<button class="btn-sub-menu jws-icon-arrow_carrot-down"></button>';
				$(elementIcon).insertAfter(dropDownCat.find('> a'));
				if(dropDownCat.hasClass("active")) {
					dropDownCat.addClass("active");
				}
				$(document).on("click", ".btn-sub-menu", function(e) {
					e.preventDefault();
					if($(this).parent().hasClass("active")) {
						$(this).parent().removeClass("active").find("> ul").slideUp(320);
						$(this).parent().removeClass("active").find(".sub-menu-dropdown").slideUp(320);
					} else {
						$(this).parent().addClass("active").find("> ul").slideDown(320);
						$(this).parent().addClass("active").find(".sub-menu-dropdown").slideDown(320);
					}
				});
			},
			login_form: function() {
				$('.jws-login-form').each(function() {
					var $this = $(this);
					$(this).find('form[name=loginpopopform]').on('submit', function(event) {
						event.preventDefault();
						var valid = true,
							email_valid = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
						$(this).find('input.required').each(function() {
							// Check empty value
							if(!$(this).val()) {
								$(this).addClass('invalid');
								valid = false;
							}
							// Uncheck
							if($(this).is(':checkbox') && !$(this).is(':checked')) {
								$(this).addClass('invalid');
								valid = false;
							}
							// Check email format
							if('email' === $(this).attr('type')) {
								if(!email_valid.test($(this).val())) {
									$(this).addClass('invalid');
									valid = false;
								}
							}
						});
						$(this).find('input.required').on('focus', function() {
							$(this).removeClass('invalid');
						});
						if(!valid) {
							return valid;
						}
						var form = $(this),
							$elem = $this.find('.jws-login-container'),
							wp_submit = $elem.find('input[type=submit]').val();
						$elem.addClass('loading');
						$elem.find('.jws-login .popup-message').slideUp();
						$elem.find('.message').slideDown().remove();
						var data = {
							action: 'jws_login_ajax',
							data: form.serialize() + '&wp-submit=' + wp_submit,
						};
						$.post(jwsThemeModule.jws_script.ajax_url, data, function(response) {
							if(typeof grecaptcha !== "undefined"  && typeof goole_captcha_api_obj !== "undefined") {
								grecaptcha.reset(0);
							}
							if(response.data.code == '1') {
								if($('.jws_add_car_form').length) {
									$('.jws-login-form').remove();
									$('#jws-submit-car').click();
								} else {
									if(response.data.redirect) {
										if(window.location.href == response.data.redirect) {
											location.reload();
										} else {
											window.location.href = response.data.redirect;
										}
									} else {
										location.reload();
									}
								}
							} else {
								var $captchaIframe = $('#jws-login-form .gglcptch iframe');
								if($captchaIframe.length > 0) {
									$captchaIframe.attr('src', $captchaIframe.attr('src')); // reload iframe
								}
							}
							$elem.find('.jws-login .popup-message').html(response.data.message).slideDown();
							$elem.removeClass('loading');
						});
						return false;
					});
					$(this).find('form[name=registerformpopup]').on('submit', function(e) {
						e.preventDefault();
						var valid = true,
							email_valid = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
						$(this).find('input.required').each(function() {
							// Check empty value
							if(!$(this).val()) {
								$(this).addClass('invalid');
								valid = false;
							}
							// Uncheck
							if($(this).is(':checkbox') && !$(this).is(':checked')) {
								$(this).addClass('invalid');
								valid = false;
							}
							// Check email format
							if('email' === $(this).attr('type')) {
								if(!email_valid.test($(this).val())) {
									$(this).addClass('invalid');
									valid = false;
								}
							}
						});
						$(this).find('input.required').on('focus', function() {
							$(this).removeClass('invalid');
						});
						if(!valid) {
							return valid;
						}
						var $form = $(this),
							data = {
								action: 'jws_register_ajax',
								data: $form.serialize() + '&wp-submit=' + $form.find('input[type=submit]').val(),
								register_security: $form.find('#register_security').
								val(),
							},
							$elem = $('#jws-login-form .jws-login-container');
						$elem.addClass('loading');
						$elem.find('.jws-register .popup-message').slideUp();
						$elem.find('.message').slideDown().remove();
						$.ajax({
							type: 'POST',
							url: jwsThemeModule.jws_script.ajax_url,
							data: data,
							success: function(response) {
								$elem.removeClass('loading');
								if(typeof grecaptcha !== "undefined" && typeof goole_captcha_api_obj !== "undefined") {
									grecaptcha.reset(1);
								}
								if(response.data.code == '1') {
									if($('.jws_add_car_form').length) {
										$('.jws-login-form').remove();
										$('#jws-submit-car').click();
									} else {
										if(response.data.redirect) {
											if(window.location.href == response.data.redirect) {
												location.reload();
											} else {
												window.location.href = response.data.redirect;
											}
										} else {
											location.reload();
										}
									}
								} else {
									var $captchaIframe = $('#jws-login-form .gglcptch iframe');
									if($captchaIframe.length > 0) {
										$captchaIframe.attr('src', $captchaIframe.attr('src')); // reload iframe
									}
								}
								$elem.find('.jws-register .popup-message').html(response.data.message).slideDown();
							},
						});
					});
					/* Check Strong Passwoed */
					$(this).find('.jws-register input[name="password"]').keyup(function() {
						checkpassword($(this).val());
					});

					function checkpassword(password) {
						var strength = 0,
							meter = $('.meter'),
							meter_text = $('.text-meter'),
							password_hint = $('.jws-password-hint');
						if(password.match(/[a-z]+/)) {
							strength += 1;
						}
						if(password.match(/[A-Z]+/) && password.length >= 8) {
							strength += 1;
						}
						if(password.match(/[0-9]+/) && password.length >= 12) {
							strength += 1;
						}
						if(password.match(/[$@#&!]+/) && password.length >= 14) {
							strength += 1;
						}
						if(password.length > 0) {
							meter.show();
							password_hint.show();
						} else {
							meter.hide();
							password_hint.hide();
						}
						switch(strength) {
							case 0:
								meter_text.html("");
								meter.attr("meter", "0");
								break;
							case 1:
								meter_text.html(jwsThemeModule.jws_script.metera);
								meter.attr("meter", "1");
								break;
							case 2:
								meter_text.html(jwsThemeModule.jws_script.meterb);
								meter.attr("meter", "2");
								break;
							case 3:
								meter_text.html(jwsThemeModule.jws_script.meterc);
								meter.attr("meter", "3");
								password_hint.hide();
								break;
							case 4:
								meter_text.html(jwsThemeModule.jws_script.meterd);
								meter.attr("meter", "4");
								password_hint.hide();
								break;
						}
					}
					$(this).find('.change-form.login').on('click', function(e) {
						e.preventDefault();
						$this.find('.jws-login').addClass('active');
						$this.find('.jws-register').removeClass('active');
					});
					$(this).find('.change-form.register').on('click', function(e) {
						e.preventDefault();
						$this.find('.jws-register').addClass('active');
						$this.find('.jws-login').removeClass('active');
					});
					$(".toggle-password2").click(function() {
						$(this).toggleClass("fa-eye fa-eye-slash");
						$(this).parents('.active').find('input[type="password"]').addClass('change-type');
						if($(this).parents('.active').find('.change-type').attr("type") == "password") {
							$(this).parents('.active').find('.change-type').attr("type", "text");
						} else {
							$(this).parents('.active').find('.change-type').attr("type", "password");
						}
					});
				});
                var recaptcha7;
                var recaptcha8;
    			$(window).on('load', function(){
    				if(document.getElementById("recaptcha7") && typeof goole_captcha_api_obj !== "undefined") {
    					recaptcha7 = grecaptcha.render('recaptcha7', {
    						'sitekey': goole_captcha_api_obj.google_captcha_site_key, //Replace this with your Site key
    						'theme': 'light'
    					});
    				}
    				if(document.getElementById("recaptcha8") && typeof goole_captcha_api_obj !== "undefined") {
    					recaptcha8 = grecaptcha.render('recaptcha8', {
    						'sitekey': goole_captcha_api_obj.google_captcha_site_key, //Replace this with your Site key
    						'theme': 'light'
    					});
    				}
    			});
			},
			menu_nav: function() {
				var mainMenu = $('.elementor_jws_menu_layout_menu_horizontal').find('.nav'),
					lis = mainMenu.find(' > li.menu-item-design-mega_menu');
				mainMenu.on('hover', ' > li.menu-item-design-mega_menu', function() {
					setOffset($(this));
				});
				var setOffset = function(li) {
					var dropdown = li.find(' > .sub-menu-dropdown');
					dropdown.attr('style', '');
					var dropdownWidth = dropdown.outerWidth(),
						dropdownOffset = dropdown.offset(),
						screenWidth = $(window).width(),
						viewportWidth = screenWidth,
						extraSpace = 10;
					if(!dropdownWidth || !dropdownOffset) return;
					if(dropdownOffset.left + dropdownWidth >= viewportWidth && li.hasClass('menu-item-design-mega_menu')) {
						// If right point is not in the viewport
						var toRight = dropdownOffset.left + dropdownWidth - viewportWidth;
						dropdown.css({
							left: -toRight - extraSpace
						});
					}
				};
				lis.each(function() {
					setOffset($(this));
					$(this).addClass('with-offsets');
				});
				//mega menu  
				var mega_item = mainMenu.find(' > li.menu-item-design-mega_menu_full_width');
				if(mega_item.length > 0) {
					$('.jws_header').addClass('has-mega-full');
				}
				if($('.elementor_jws_menu_layout_menu_horizontal').hasClass('elementor-jws-menu-change-background-yes')) {
					mega_item.mouseenter(function() {
						$('.jws_header.has-mega-full').addClass('mega-has-hover');
					});
					mega_item.mouseleave(function() {
						$('.jws_header.has-mega-full').removeClass('mega-has-hover');
					});
				}
			},
			mobile_pcbuilder: function() {
				$('.nav-mobile a').magnificPopup({
					type: 'inline',
					mainClass: '',
					midClick: true,
					removalDelay: 500, //delay removal by X to allow out-animation
					callbacks: {
						beforeOpen: function() {
							this.st.mainClass = 'pc_bulder_popup woo_product_builder sidebar-mobile-wap';
						},
						afterClose: function() {
							$('.woocommerce-product-builder-sidebar,.woopb-steps').removeClass('mfp-hide');
						}
					},
				});
			},
		};
	}());
	$(document).ready(function() {
		jwsThemeModule.init();
		$(document).on("scroll", onScroll);
		$('.jws-icon-icon_info_alt').tooltip({
			track: true
		});
		$(".ba-main").mouseout(function() {
			$(this).css('transition', '0.3s all');
		});
        setTimeout(function(){
             var tag_new = $("template").last().attr("id");
             $("#" + tag_new).css("display", "none");
             $("#" + tag_new).next().next().css("display", "none");
        }, 100);
	});

	function onScroll() {
		var scrollPos = $(document).scrollTop();
		$('.custom_nav .nav li.menu_scroll a').each(function() {
			var currLink = $(this);
			var refElement = $(currLink.attr("href"));
			if(refElement.length > 0) {
				if(refElement.position().top <= scrollPos + 100 && refElement.position().top + refElement.height() > scrollPos + 100) {
					$('.custom_nav .nav ul li.menu_scroll a').parent().removeClass("current-menu-item");
					currLink.parent().addClass("current-menu-item");
				} else {
					currLink.parent().removeClass("current-menu-item");
				}
			}
		});
	}
	$.fn.isInViewport = function() {
		let elementTop = $(this).offset().top;
		let elementBottom = elementTop + $(this).outerHeight();
		let viewportTop = $(window).scrollTop();
		let viewportBottom = viewportTop + $(window).height();
		return elementBottom > viewportTop && elementTop < viewportBottom;
	};
	$(window).resize(function() {
		jwsThemeModule.menu_offset();
	});
	$(window).scroll(function() {
		var scrollDistance = $(window).scrollTop();
		// Assign active class to nav links while scolling
		$('.elementor-menu-anchor').each(function(i) {
			if($(this).position().top <= scrollDistance) {
				$('.menu-item-type-custom a.active').removeClass('active');
				$('.menu-item-type-custom a').eq(i).addClass('active');
			}
		});
	}).scroll();
	$.fn.gallery_popup = function(option) {
		if(typeof($.fn.magnificPopup) == 'undefined') return;
		option.find('a.jws-popup-global').magnificPopup({
			type: 'image',
			gallery: {
				enabled: true
			},
			removalDelay: 500, //delay removal by X to allow out-animation
			mainClass: 'gallery-global mfp-zoom-in mfp-img-mobile',
			callbacks: {
				open: function() {
					//overwrite default prev + next function. Add timeout for css3 crossfade animation
					$.magnificPopup.instance.next = function() {
						var self = this;
						self.wrap.removeClass('mfp-image-loaded');
						setTimeout(function() {
							$.magnificPopup.proto.next.call(self);
						}, 120);
					};
					$.magnificPopup.instance.prev = function() {
						var self = this;
						self.wrap.removeClass('mfp-image-loaded');
						setTimeout(function() {
							$.magnificPopup.proto.prev.call(self);
						}, 120);
					};
				},
				imageLoadComplete: function() {
					var self = this;
					setTimeout(function() {
						self.wrap.addClass('mfp-image-loaded');
					}, 16);
				},
			},
		});
	};

	function get_cfb_ajax_parameter_with_cfb_type($this) {
		var parameters_arr = {};
		var selectedattr = [];
		var selobj = {};
		var formdata = "";
		var tid = '';
		var form = $($this).parents('form');
		form.find('.product-filter-select').each(function() {
			tid = $(this).attr('data-id');
			var sel_val = $(this).val();
			if(tid) {
				selectedattr.push(tid);
				if(sel_val != "") {
					formdata += "&" + tid + "=" + sel_val;
					selobj[tid] = sel_val;
				}
			}
		});
		parameters_arr.selected_attr = selectedattr;
		parameters_arr.sel_obj = selobj;
		parameters_arr.form_data = formdata;
		parameters_arr.tid = tid;
		parameters_arr.form_parent = form;
		return parameters_arr;
	}

	function do_cfb_ajax_call(form_data, form_parent, selected_attr, sel_obj) {
		$.ajax({
			url: jwsThemeModule.jws_script.ajax_url,
			type: 'post',
			dataType: 'json',
			data: 'action=product_cars_filter_query' + form_data + '&cfb=yes&selected_attr=' + selected_attr,
			beforeSend: function() {
				form_parent.addClass('form-loader');
				$('.product-filter-select').prop('disabled', true);
				$('.product-submit-btn').prop('disabled', true);
			},
			success: function(response) {
				if(response.status == "success") {
					if(typeof response.all_filters == "object") {
					  
						$.each(response.all_filters, function(key, value) {
							var tax_label = $('.box_' + key).data('tax');
						
							var new_options = "<option value=''>--" + tax_label + "--</option>";
							if(typeof value == "object") {
						
								$.each(value, function(value_key, value_value) {
								    
									$.each(value_value, function(new_value_key, new_value_value) {
										var selected_val = '';
										$.each(sel_obj, function(sel_obj_key , sel_obj_value) {
								
											if(sel_obj_value == new_value_key) {
												selected_val = "selected='selected'";
											}
										});
										new_options += "<option value='" + new_value_key + "' " + selected_val + ">" + new_value_value + "</option>";
									});
								});
							}
							form_parent.find('#filter_' + key).html(new_options);
						});
					}
					form_parent.removeClass('form-loader');
					$('.product-filter-select').prop('disabled', false);
					$('.product-submit-btn').prop('disabled', false);
				}
			},
			error: function() {
				alert('Something went wrong!');
				form_parent.removeClass('form-loader');
			}
		});
	}

	function GetURLParameter(sParam) {
		var sPageURL = window.location.search.substring(1);
		var sURLVariables = sPageURL.split('&');
		for(var i = 0; i < sURLVariables.length; i++) {
			var sParameterName = sURLVariables[i].split('=');
			if(sParameterName[0] == sParam) {
				return sParameterName[1];
			}
		}
	}
	$(document).ready(function() {
		$(document.body).on('click', '.panel-selector-open', function() {
			$('.panel-wrapper').toggleClass('in');
		});
		$('.colorSelector').each(function() {
			var type = $(this);
			type.ColorPicker({
				color: '#0000ff',
				onShow: function(colpkr) {
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function(colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function(hsb, hex) {
					var button_type = type.data('type');
		
					if(button_type == 'main') {
						$("body").css({
							'--main': '#' + hex + '',
							'--e-global-color-primary': '#' + hex + ' !important',
						});
					}
					if(button_type == 'button') {
						$("body").css("--btn-bgcolor", "#" + hex + "");
					}
					if(button_type == 'custom1') {
						$("body").css("" + type.data('var') + "", "#" + hex + "");
					}
					if(button_type == 'custom2') {
						$("body").css("--custom2", "#" + hex + "");
					}
					if(button_type == 'button_hover') {
						$("body").css("--btn-bgcolor2", "#" + hex + "");
					}
					if(button_type == 'light') {
						$("body").css({
							'--light': '#' + hex + '',
							'--e-global-color-accent': '#' + hex + '',
						});
					}
					if(button_type == 'heading') {
						$("body").css({
							'--heading': '#' + hex + '',
							'--e-global-color-secondary': '#' + hex + '',
						});
					}
					if(button_type == 'body') {
						$("body").css({
							'--body': '#' + hex + '',
							'--e-global-color-text': '#' + hex + '',
						});
					}
					type.css("background-color", "#" + hex + "");
				}
			});
		});
		$('select:not([name="rating"]):not(.wpcf7-form-control)').select2({
			dropdownAutoWidth: true
		});
		$('.widget-filter-checkbox,.widget-jws-filter-rating').each(function() {
			var tid = $(this).find('.sort-product-checkbox').attr('data-name');
			var value = [];
			var sel_val = '';
			$(this).find('[data-name="' + tid + '"].active').each(function(i) {
				sel_val = $(this).attr('data-value');
				value[i] = sel_val;
			});
			$('.file_attachments_' + tid + '').val(value);
		});
		$(document).on('change', '.product-filter-select', function() {
			var tid = $(this).attr('data-id'),
				slug = $(this).val();
			$('.value_' + tid + '').val(slug);
			var cfb_ajax_paramete = get_cfb_ajax_parameter_with_cfb_type(this);
			do_cfb_ajax_call(cfb_ajax_paramete.form_data, cfb_ajax_paramete.form_parent, cfb_ajax_paramete.selected_attr, cfb_ajax_paramete.sel_obj, cfb_ajax_paramete, cfb_ajax_paramete.uid);
		});

		function add_vehicle_garage() {
			$(document.body).on('click', '.add-vehicle-garage', function() {
				$('.search-my-vehicles').addClass('opened');
			});
			$(document.body).on('click', '.close-form-add-garage', function() {
				$('.search-my-vehicles').removeClass('opened');
			});
			$(document.body).on('click', '.my-garage-toggle', function() {
				$('.my-garage-list').toggleClass('active');
			});
			$(document).on("click", function(e) {
				if($(e.target).is(".my-garage-wrap,.my-garage-wrap *,.remove-garage") === false) {
					$('.my-garage-list').removeClass('active');
				}
			});
			$(document.body).on('click', '.remove-garage', function() {
				var $this = $(this);
				var dataAction = 'remove';
				var garaname = $(this).data('id');
				$this.parents('.my-garage-list').addClass('loading');
				$this.parents('li').remove();
				$.ajax({
					url: jwsThemeModule.jws_script.ajax_url,
					type: "POST",
					dataType: 'json',
					data: '&gara_id=' + garaname + '&post_action=' + dataAction + '&action=jws_ajax_add_to_garage',
					context: this,
					success: function(data) {
						if(typeof data.response != 'undefined') {
							$('.vehicles-added').html(data.garage_html);
							$('.my-garage-list').removeClass('loading');
						}
					},
					error: function(data) {
						console.log(data);
					},
				});
			});
			$(document.body).on('submit', '.jws-my-garage', function(e) {
				e.preventDefault();
				var garaname = "";
				var garaurl = "";
				var tid = "";
				var $this = $(this);
				var $i = 1;
				$('.garage-notes-wap').slideUp();
				$(this).find('.product-filter-select').each(function() {
					tid = $(this).attr('data-url');
					var sel_val = $(this).val();
					if(tid) {
						if(sel_val != "") {
							garaurl += " " + tid + "=" + sel_val;
							garaname += sel_val + "-";
							$i += 1;
						} else {
							return false;
						}
					}
				});
				console.log(garaname);
				//if($('body').hasClass('user-not-logged-in') && $i == 4) {
				var dataAction = 'add';
				$.ajax({
					url: jwsThemeModule.jws_script.ajax_url,
					type: "POST",
					dataType: 'json',
					data: '&gara_id=' + garaname + '&gara_url=' + garaurl + '&post_action=' + dataAction + '&action=jws_ajax_add_to_garage',
					context: this,
					beforeSend: function() {
						$this.find('.product-submit-btn').addClass('loading');
					},
					success: function(data) {
						console.log(data);
						$('.garage-notes-wap').html(data.response).slideDown();
						if(data.status == 'success') {
							$('.search-my-vehicles').removeClass('opened');
							$('.garage-notes-wap').slideUp();
							$('.vehicles-added').html(data.garage_html);
						}
					},
					complete: function() {
						$this.find('.product-submit-btn').removeClass('loading');
					},
					error: function(data) {
						console.log(data);
					},
				});
			});
		}
		add_vehicle_garage();

		function jws_car_account() {
			$('.car-account-action > a').on("click", function() {
				$(this).parents('.car-account-action').toggleClass('active');
			});
		}
		jws_car_account();

        
	});
	$(window).on("load", function() {
		var tech = GetURLParameter('search-location');
		var make = GetURLParameter('filter_make');
		if(tech != undefined) {
			$('#wpsl-search-input').val(tech.replace(/[_\W]+/g, ""));
			$('#wpsl-search-btn').click();
		}
		if(make != undefined) {
			$('.box_pa_make').change();
		}
		var blog_layout = GetURLParameter('blog_layout');
		if(blog_layout != undefined) {
			var url = window.location.href;
			if(url.includes('?')) {
				var menu_items_links = $(".sub-menu li a");
				menu_items_links.each(function() {
					if($(this).is('[href*="?blog_layout"]')) {
						$(this).parent().removeClass('current-menu-item');
						var current_index = $(this).parent().index(),
							parent_element = $(this).closest('ul');
						parent_element.find('li').not(':eq(' + current_index + ')').removeClass('current-menu-item');
						$(this).parent().addClass('current-menu-item');
					}
				});
			}
		}
	});
})(jQuery);