jQuery( document ).ready( function( $ ) {
	// if url contains 'oded-search' string
	if( $( '.search-results-grid' ).length > 0 ) {
		let el = $( '.search-results-grid' );
		var searchTerm = window.location.href.split( 's=' )[ 1 ];
		let elElementorGrid = el.find( '.elementor-loop-container.elementor-grid' );
		let data = {
			action: 'te_ajax_search_for_grid',
			security: el.attr( 'data-security' ),
			data: {
				searchTerm: searchTerm,
			},
		}
		
		elElementorGrid.html( '<div class="te-loading"><i class="fas fa-spinner fa-spin"></i></div>' );
		el.addClass( 'active' );
		
		$.post( ajaxObj.ajaxUrl, data, function( response ) {
			if( response.success ) {
				el.find( '.elementor-loop-container.elementor-grid' ).html( response.data.html );
				$( '.search-results-grid .elementor-pagination' ).html( response.data.pagination ).addClass( 'active' );
				$( '.search-results-grid' ).attr( 'data-posts_in', response.data.postsIn );
				
				$( 'html, body' ).animate(
					{
						scrollTop: el.offset().top - 100,
					},
				);
				
				if( 'undefined' !== typeof response.data.productCats ) {
					let productCats = Object.values( response.data.productCats );
					
					$( '.te-product-cat-filters input[type="checkbox"]' ).each( function() {
						let _el = $( this );
						let elVal = parseInt( _el.val() );
						
						if( -1 === $.inArray( elVal, productCats ) ) {
							_el.parent().addClass( 'hide' );
						}
					} );
				}
			}
		} );
		
		$( document ).on( 'click', '.search-results-grid a.page-numbers', function( e ) {
			e.preventDefault();
			
			let el = $( this );
			let elText = el.text().replace( /\D/g, '' );
			let elHtml = el.html();
			let elParentGrid = el.closest( '.search-results-grid' );
			
			el.html( elHtml + ' <i class="fas fa-spinner fa-spin"></i>' );
			
			let terms = [];
			
			$( '.te-product-cat-filters input[type="checkbox"]:checked' ).each( function() {
				terms.push( $( this ).val() );
			} );
			
			if( 0 === terms.length ) {
				terms = [7178, 466, 38353, 7426, 8049, 7427, 38112, 467, 465, 5455];
			}
			
			let data = {
				action: 'te_ajax_search_for_grid',
				security: elParentGrid.attr( 'data-security' ),
				data: {
					searchTerm: searchTerm,
					page: elText,
					taxQuery: {
						taxonomy: 'product_cat',
						field: 'term_id',
						terms: terms,
						operator: 'IN',
					},
				},
			}
			
			if( $( '#te-instock-filter' ).is( ':checked' ) ) {
				data.data.metaQuery = [
					{
						key: '_stock',
						value: '0',
						compare: '>',
					},
					{
						key: '_stock_status',
						value: 'instock',
						compare: '=',
					},
				];
			}
			
			if( $( '#te-outofstock-filter' ).is( ':checked' ) ) {
				data.data.metaQuery = [
					{
						key: '_stock',
						value: '0',
						compare: '=',
					},
					{
						key: '_stock_status',
						value: 'outofstock',
						compare: '=',
					},
				];
			}
			
			$.post( ajaxObj.ajaxUrl, data, function( response ) {
				el.html( elHtml );
				console.log( response );
				if( response.success ) {
					elParentGrid.find( '.elementor-loop-container.elementor-grid' ).html( response.data.html );
					$( '.search-results-grid .elementor-pagination' ).html( response.data.pagination );
					//$( '.search-results-grid' ).attr( 'data-posts_in', response.data.postsIn );
					
					$( 'html, body' ).animate(
						{
							scrollTop: el.offset().top - 100,
						},
					);
				}
			} );
		} );
	}
	
	/*$( document ).on( 'click', '.te-filter-btn input[type="checkbox"]', function( e ) {
		e.preventDefault();
		
		return false;
	} );*/
	
	$( document ).on( 'change', '.te-filter-btn input', function( e ) {
		//e.preventDefault();
		
		let el = $( this );
		let elSpan = el.siblings( 'span.label' );
		let elSpanText = elSpan.text();
		let elLabel = el.closest( 'label' );
		let elParent = el.closest( '.filter-wrapper' );
		let postsIn = $( '.search-results-grid' ).attr( 'data-posts_in' );
		
		/*if( elInput.is( ':checked' ) ) {
			elInput.prop( 'checked', false );
		}
		else {
			elInput.prop( 'checked', true );
		}*/
		
		let data = {
			action: 'te_ajax_search_for_grid',
			security: elParent.attr( 'data-security' ),
			data: {
				postsIn: postsIn,
				searchTerm: searchTerm,
				page: '' !== $( '.page-numbers.current' ).text() ? $( '.page-numbers.current' ).text() : 1,
			},
		}
		
		if( $( '#te-instock-filter' ).is( ':checked' ) ) {
			data.data.page = 1;
			data.data.metaQuery = [
				{
					key: '_stock',
					value: '0',
					compare: '>',
				},
				{
					key: '_stock_status',
					value: 'instock',
					compare: '=',
				},
			];
		}
		
		if( $( '#te-outofstock-filter' ).is( ':checked' ) ) {
			data.data.page = 1;
			data.data.metaQuery = [
				{
					key: '_stock',
					value: '0',
					compare: '=',
				},
				{
					key: '_stock_status',
					value: 'outofstock',
					compare: '=',
				},
			];
		}
		
		/*if( 'te-instock-filter' === elInput.attr( 'id' ) ) {
			data.data.metaQuery = {
				key: '_stock',
				value: '0',
				compare: '>',
			}
			
			$( '#te-outofstock-filter' ).prop( 'checked', false );
			
			if( !elInput.is( ':checked' ) ) {
				delete data.data.metaQuery;
				delete data.data.postsIn;
			}
		}
		
		if( 'te-outofstock-filter' === elInput.attr( 'id' ) ) {
			data.data.metaQuery = {
				key: '_stock',
				value: '0',
				compare: '=',
			}
			
			$( '#te-instock-filter' ).prop( 'checked', false );
			
			if( !elInput.is( ':checked' ) ) {
				delete data.data.metaQuery;
				delete data.data.postsIn;
			}
		}*/
		
		//if( 'product-cat-filter' === elInput.attr( 'name' ) ) {
		let terms = [];
		
		$( '.te-product-cat-filters input[type="checkbox"]:checked' ).each( function() {
			terms.push( $( this ).val() );
		} );
		
		if( 0 === terms.length ) {
			terms = [7178, 466, 38353, 7426, 8049, 7427, 38112, 467, 465, 5455];
		}
		
		data.data.taxQuery = {
			taxonomy: 'product_cat',
			field: 'term_id',
			terms: terms,
			operator: 'IN',
		}
		
		/*data.data.metaQuery = {
			key: 'post_id',
			value: postsIn,
			compare: 'IN',
		}*/
		
		
		//}
		
		elSpan.html( elSpanText + ' <i class="fas fa-spinner fa-spin"></i>' );
		
		$.post( ajaxObj.ajaxUrl, data, function( response ) {
			elSpan.html( elSpanText );
			
			if( response.success ) {
				$( '.search-results-grid .elementor-loop-container.elementor-grid' ).html( response.data.html );
				$( '.search-results-grid .elementor-pagination' ).html( response.data.pagination );
				
				$( 'html, body' ).animate(
					{
						scrollTop: $( '.search-results-grid' ).offset().top - 100,
					},
				);
				
				/*if( 'product-cat-filter' === elInput.attr( 'name' ) && 'undefined' !== typeof response.data.productCats ) {
					let productCats = Object.values( response.data.productCats );
					
					$( '.te-product-cat-filters input[type="checkbox"]' ).parent().addClass( 'hide' );
					
					$( '.te-product-cat-filters input[type="checkbox"]' ).each( function() {
						let _el = $( this );
						let elVal = parseInt( _el.val() );
						
						if( -1 === $.inArray( elVal, productCats ) ) {
							_el.parent().removeClass( 'hide' );
						}
					} );
				}*/
			}
		} );
	} );
	
	$( document ).on( 'click touchstart', '.search-form-toggle', function() {
		
		let el = $( this );
		let elI = el.find( 'i' );
		
		elI.toggleClass( 'fa-search fa-times' );
		$( '.header-search-form-wrapper' ).toggleClass( 'active' );
		/*
		if( el.hasClass( 'fa-search' ) ) {
			elI.removeClass( 'fa-search' );
			elI.addClass( 'fa-close' );
			
			$( '.header-search-form-wrapper' ).addClass( 'active' );
		}
		else {
			elI.removeClass( 'fa-close' );
			elI.addClass( 'fa-search' );
			
			$( '.header-search-form-wrapper' ).removeClass( 'active' );
		}*/
	} );
	
	$( window ).on( 'elementor/frontend/init', function() {
		$( document ).on( 'elementor/popup/show', ( event, id ) => {
			if( 97094 == id ) {
				if( $( 'body' ).hasClass( 'single-product' ) ) {
					let currentHref = $( '#whatsapp_dynamic_link_products a' ).attr( 'href' ).split( '/' );
					let newHref = 'https://wa.me/' + currentHref[ currentHref.length - 1 ] + '?text=' + encodeURI( 'שלום, אני מעוניינ/ת בפרטים נוספים על המוצר ' + $( '.product_title' ).text() + '\n' + window.location.href );
					
					$( '#whatsapp_dynamic_link_products a' ).attr( 'href', newHref );
				}
			}
		} );
	} );
	
	// get url param filter_kids_voz
	let urlParams = new URLSearchParams( window.location.search );
	let filterKidsVoz = urlParams.get( 'filter_kids_voz' );
	// if defined and not empty paste code
	if( filterKidsVoz ) {
		$( 'article.elementor-post .elementor-post__excerpt' ).addClass( 'trim-excerpt-4' );
	}
	
	//break url into parts
	let urlParts = window.location.href.split( '/' );
	
	// if last part contains only numbers
	if( $( 'body' ).hasClass( 'page-id-50707' ) && urlParts[ urlParts.length - 2 ].match( /^[0-9]+$/ ) ) {
		// scroll to #catalog
		setTimeout(
			function() {
				$( 'html, body' ).animate(
					{
						scrollTop: $( '#catalog' ).offset().top - 20,
					},
					1000,
				);
			},
			1000,
		);
	}
	
	
	/*
	 * Third Ear Search form
	 */
	function ThirdEarSearchForm() {
		this.el = $( '.te-search-form' );
		this.elSearchInput = $( '.te-search-field' );
		this.delayTimer = null;
		this.queryDelay = 500;
		this.page = 1;
	}
	
	ThirdEarSearchForm.prototype.init = function() {
		this.initEvents();
	};
	
	ThirdEarSearchForm.prototype.getInstance = function() {
		return this;
	}
	
	ThirdEarSearchForm.prototype.initEvents = function() {
		this.el.on( 'submit', this.formSubmit );
		
		//this.elSearchInput.on( 'blur', this.searchKeyup );
		this.elSearchInput.on( 'input', this.searchKeyup );
		$( document ).on( 'click', this.eventClick );
	}
	
	ThirdEarSearchForm.prototype.eventClick = function( e ) {
		let instance = ThirdEarSearchForm.getInstance();
		let elResults = instance.el.children( '.results' );
		
		if( 'search' === $( e.target ).attr( 'type' ) && elResults.children().length > 0 ) {
			elResults.addClass( 'show' );
		}
		
		if( !$( e.target ).closest( '.te-search-form' ).length ) {
			elResults.removeClass( 'show' );
		}
	}
	
	ThirdEarSearchForm.prototype.formSubmit = function( e ) {
		e.preventDefault();
	}
	
	ThirdEarSearchForm.prototype.searchKeyup = function( e ) {
		e.preventDefault();
		
		/*if( !( ( e.keyCode >= 48 && e.keyCode <= 57 ) || ( e.keyCode >= 65 && e.keyCode <= 90 ) || ( e.keyCode >= 97 && e.keyCode <= 122 ) || ( 8 === e.keyCode ) ) ) {
			return;
		}*/
		
		let el = $( e.target );
		
		if( '' === el.val() ) {
			return;
		}
		
		let instance = ThirdEarSearchForm.getInstance();
		
		if( instance.queryDelay > 0 ) {
			clearTimeout( instance.delayTimer );
			
			instance.delayTimer = setTimeout(
				function() {
					ThirdEarSearchForm.query( e );
				},
				instance.queryDelay,
			);
		}
		else {
			ThirdEarSearchForm.query();
		}
	}
	
	ThirdEarSearchForm.prototype.query = function( e ) {
		let elSearchInput = $( e.target );
		let elSearchInputVal = elSearchInput.val();
		
		if( 0 === elSearchInput.length ) {
			return;
		}
		
		if( 'מוזיקה ישראלית' === elSearchInputVal ) {
			window.location.href = 'https://third-ear.com/product-tag/israeli-music/';
			
			return;
		}
		
		elSearchInput.addClass( 'loading' );
		
		$.ajax( {
			method: 'post',
			url: ajaxObj.ajaxUrl,
			data: {
				action: 'te_ajax_search',
				nonce: this.el.find( '[name="te_ajax_search_nonce"]' ).val(),
				data: {
					searchQuery: elSearchInputVal,
					page: this.page,
				},
			},
			success: function( response ) {
				ThirdEarSearchForm.querySuccess( response, e );
			},
			error: function( jqXHR, textStatus, errorThrown ) {
				ThirdEarSearchForm.queryError( jqXHR, textStatus, errorThrown, e );
				
				alert( textStatus );
			},
		} );
		
		this.queryDelay = 1000;
	}
	
	ThirdEarSearchForm.prototype.querySuccess = function( response, e ) {
		let elSearchInput = $( e.target );
		
		elSearchInput.removeClass( 'loading' );
		
		if( response.success ) {
			if( response.data.length > 0 ) {
				this.el.find( '.results' ).addClass( 'has-results show' ).html( response.data );
			}
			else {
				this.el.find( '.results' ).removeClass( 'has-results' );
			}
		}
		else {
			alert( response.message );
		}
	}
	
	ThirdEarSearchForm.prototype.queryError = function( jqXHR, textStatus, errorThrown, e ) {
		$( e.target ).removeClass( 'loading' );
	}
	
	var ThirdEarSearchForm = new ThirdEarSearchForm();
	
	ThirdEarSearchForm.init();
	
	$( '#voz-search-form-toggle' ).on( 'click', function( e ) {
		e.preventDefault();
		
		$( '#voz-search-form-wrapper' ).slideToggle( 200 );
	} );
	
	$( '.voz-search-form select[name="actors"]' ).select2( { placeholder: 'שחקן/נית בסרט', width: '100%' } );
	$( '.voz-search-form select[name="country"]' ).select2( { placeholder: 'ארץ הפקה', width: '100%' } );
	$( '.voz-search-form select[name="subtitles_language"]' ).select2( { placeholder: 'שפת תרגום', width: '100%' } );
	$( '.voz-search-form select[name="audio_language"]' ).select2( { placeholder: 'שפת המקור', width: '100%' } );
	$( '.voz-search-form select[name="categories"]' ).select2( { placeholder: 'קטגוריות', width: '100%' } );
	$( '.voz-search-form select[name="keywords"]' ).select2( { placeholder: 'מילות מפתח', width: '100%' } );
	
	$( '#actor1,#actor2' ).on( 'keyup', function( e ) {
		if( /[\u0590-\u05FF]/.test( e.target.value ) ) {
			e.target.value = e.target.value.replace( /[\u0590-\u05FF]/g, '' );
		}
	} );
	
	$( '.voz-search-form' ).on( 'submit', function( e ) {
		e.preventDefault();
		
		let elForm = $( this );
		let elQ = elForm.find( 'input[name="q"]' );
		let elActorOne = elForm.find( 'input[name="actor1"]' );
		let elActorTwo = elForm.find( 'input[name="actor2"]' );
		let elCountry = elForm.find( 'select[name="country"]' );
		let elYearStart = elForm.find( 'input[name="year_start"]' );
		let elYearEnd = elForm.find( 'input[name="year_end"]' );
		let elSubtitlesLanguage = elForm.find( 'select[name="subtitles_language"]' );
		let elAudioLanguage = elForm.find( 'select[name="audio_language"]' );
		let elCategories = elForm.find( 'select[name="categories"]' );
		let elKeywords = elForm.find( 'input[name="keywords"]' );
		let queryString = '?';
		
		if( '' !== elQ.val() ) {
			queryString += 'q=' + elQ.val();
		}
		
		if( '' !== elActorOne.val() ) {
			queryString += '&actor1=' + elActorOne.val();
		}
		
		if( '' !== elActorTwo.val() ) {
			queryString += '&actor2=' + elActorTwo.val();
		}
		
		if( '' !== elCountry.val() && 'undefined' !== typeof elCountry.val() ) {
			queryString += '&country=' + elCountry.val();
		}
		
		if( '' !== elYearStart.val() ) {
			queryString += '&year_start=' + elYearStart.val();
		}
		
		if( '' !== elYearEnd.val() ) {
			queryString += '&year_end=' + elYearEnd.val();
		}
		
		if( '' !== elSubtitlesLanguage.val() && 'undefined' !== typeof elSubtitlesLanguage.val() ) {
			queryString += '&subtitles=' + elSubtitlesLanguage.val();
		}
		
		if( '' !== elAudioLanguage.val() && 'undefined' !== typeof elAudioLanguage.val() ) {
			queryString += '&audio=' + elAudioLanguage.val();
		}
		
		if( '' !== elCategories.val() && 'undefined' !== typeof elCategories.val() ) {
			queryString += '&categories=' + elCategories.val();
		}
		
		if( '' !== elKeywords.val() ) {
			queryString += '&keywords=' + elKeywords.val();
		}
		
		window.location.href = elForm.attr( 'action' ) + queryString;
	} );
	
	$( 'a.page-numbers' ).on( 'click', function( e ) {
		let url = new URL( window.location.href );
		
		history.pushState( null, null, url );
	} );
} );