// source --> https://www.wartoobejrzec.pl/wp-content/plugins/reviews-mgmt/js/scripts.js?ver=6.9.4 
jQuery(document).ready(function($) {

// Show hide review in the front end
 
 function shwMore() {
	 
 	$(document).on('click', '.show_more_rev', function() {
		
		$(this).parent().prev().removeClass("hideRev");
		//$(this).parent().prev().toggleClass("showRev");
		
		//Add hide button and asign ScrollTo with class to get back to the class on click
		$(this).parent().append('<button type="button" class="show_less_rev">Zminimalizuj</button>');
		$(this).remove();
	});
	
 }
 
 shwMore();
 
 // Go up button
		  
function shwless() {
 
	$(document).on('click', '.show_less_rev', function() {
		 
		$(this).parent().prev().addClass("hideRev");
		$(this).parent().append('<button type="button" class="show_more_rev">Pokaż więcej</button>');
		//$(window).animate({scrollTop: $(this).offset().top -600}, 1000);
		window.scrollTo({top: $(this).offset().top -600, behavior: 'smooth'});
		$(this).remove();
		 
		});

 }
 
 shwless();
 
 // Load more reviews
 
 	function showRevs() {
		
		var revNum = 5;
		
		// Add first set of results
		
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'add_more_reviews',
					'add_more_rev': revNum
					
				},
				
				success: function(data) {

					$('#main_rev_cnt').html(data);
					cnrtLnk();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
	
	// Add more results on click

		$(document).on('click', '#add_mr_rev', function() {
			
		revNum = revNum + 5;
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'add_more_reviews',
					'add_more_rev': revNum
					
				},
				
				success: function(data) {
					
					$('#main_rev_cnt').html(data);
					$('#ctgy_revs_subpage').html(data);
					$('#show_catalog_res').html(data);
					cnrtLnk();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
			
		});
		
	}
	
	showRevs();	
	
	// Show results on click
			
	function showRewsOnClk() {
		
		$(document).on('click', '#show_revws', function() {
			
			var revNum = 5;
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'add_more_reviews',
					'add_more_rev': revNum
					
				},

				success: function(data) {
						
					$('#main_rev_cnt').html(data);
					scrlToPos();
					cnrtLnk();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
				
			});
			
		});
		
	}
	
	showRewsOnClk();
	
	// Load more movie reviews on front end on separate page
	
	// Firstly load the default amount of reviews
	let lastLoadedId = 0;
	const batchSize = 5;

	// Add a spinner element (you can place it in your HTML or dynamically)
	if ($('#loading-spinner').length === 0) {
		$('#show_more_reviews_cnt').after('<div id="loading-spinner" style="display:none; text-align:center; color:red; margin:10px;"><i class="fas fa-spinner fa-spin"></i> Wczytuję recenzje...</div>');
	}

	// Load initial batch
	function loadDefaultReviewsOnPage() {
		$('#loading-spinner').show(); // Show spinner
		$.ajax({
			url: ajxInit.ajax_url,
			method: 'post',
			data: { action: 'show_reviews_on_page_ajx' },
			success: function(data) {
				$('#show_more_reviews_cnt').html(data);
				const lastDiv = $('#show_more_reviews_cnt .rev-tmp').last();
				if (lastDiv.length) lastLoadedId = parseInt(lastDiv.data('id'));

				// Move load-more button after the last record
				$('#load-more-container').appendTo('#show_more_reviews_cnt');
			},
			complete: function() {
				$('#loading-spinner').hide(); // Hide spinner
			}
		});
	}
	loadDefaultReviewsOnPage();

	// Load more records
	$(document).on('click', '#load-more', function() {
		$('#loading-spinner').show(); // Show spinner
		$.ajax({
			url: ajxInit.ajax_url,
			method: 'post',
			data: { 
				action: 'show_more_movie_rev_ajx',
				last_id: lastLoadedId
			},
			success: function(response) {
				const data = JSON.parse(response);
				$(data.html).insertBefore('#load-more-container');

				const lastDiv = $('#show_more_reviews_cnt .rev-tmp').last();
				if (lastDiv.length) lastLoadedId = parseInt(lastDiv.data('id'));

				if (data.lastBatch) {
					$('#load-more').hide();
				}
			},
			complete: function() {
				$('#loading-spinner').hide(); // Hide spinner
			}
		});
	});

	// Back to reviews on negative search result
		
	function backToRev() {	

		$(document).on('click', '.back_to_rev', function() {
			
		var revNum = 5;
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'add_more_reviews',
					'add_more_rev': revNum
					
				},
				
				success: function(data) {

					$('#main_rev_cnt').html(data);
					$('#ctgy_revs_subpage').html(data);

				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
			
		});
		
	}
	
	backToRev();
	
	// Search Phrase
	
	function srchRev() {
	
	$(document).on('click', '#srch_rev_btn', function() {

		var passSrchPrs = $('#srch_rev').val();
		
		$.ajax ({
			
			url: ajxInit.ajax_url,
			method: 'post',
			data: {
				
				'action': 'f_srch_via_ajx',
				'pass_srch_phrs': passSrchPrs
				
			},
			
			success: function(data) {
				
				$('#main_rev_cnt').html(data);
				$('#main_rev_cnt').append("<button type='button' id='add_mr_rev' class='mt-3'>Wróć do recenzji</button>");
				scrlToPos();
				//window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
				
			},
			
			error: function(xhr) { alert(xhr.responseText); }
			
		});
		
	});
	
	}

	srchRev();

	function openSelectedRev() {
		
		$(document).on('click', '.show_selected_rev', function() {
					
			var id = $(this).attr('data-selected-rev');
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'open_slc_rev_ajx',	
					'id': id

				},
				
				success: function(data) {
									
					$('#main_rev_cnt').html(data);
					$('#ctgy_revs_subpage').html(data);
					$('#show_catalog_res').html(data);
					$('.back_to_ctgs').css("display", "block");
					scrlToPos();
					cnrtLnk();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
					

		});
		
	}
	
	openSelectedRev();
	
	// Show categories
	
	function showCtgy() {
		
		$.ajax ({
			
			url: ajxInit.ajax_url,
			method: 'post',
			data: {
				
				'action': 'show_ctgy_sdbr_ajx'
				
			},

			success: function(data) {
					
				$('#sdbr_ctgy_rev').html(data);
				
			},
			
			error: function(xhr) { alert(xhr.responseText); }
			
		});
		
	}
	
	showCtgy();
	
	// Show results for desired category on click (sidebar)
	
	function showCtgyOnClk() {
		
		$(document).on('click', '.show_ctgy', function() {
			
			var pass_ctgy = $(this).attr('data-ctgy-id');
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_ctgys_ajx',	
					'pass_ctgy': pass_ctgy
					
				},

				success: function(data) {
						
					$('#main_rev_cnt').html(data);
					scrlToPos();
					//window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
				
			});
			
		});
		
	}
	
	showCtgyOnClk();
	
	// Show categories on the subpage
	
	function showCtgySubpage() {
		
		$.ajax ({
			
			url: ajxInit.ajax_url,
			method: 'post',
			data: {
				
				'action': 'show_ctgys_subpage_ajx'
				
			},

			success: function(data) {
					
				$('#ctgy_revs_subpage').html(data);
				$('.back_to_ctgs').hide();
				
			},
			
			error: function(xhr) { alert(xhr.responseText); }
			
		});
		
	}
	
	showCtgySubpage();
	
	// Subpage! - show results for the desired category on click
	
	function showCtgyOnClkSubpage() {
		
		$(document).on('click', '.show_ctgy_subp', function() {
			
			var ctgy_subp = $(this).attr('data-ctgy-subp');
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_ctgys_subp_ajx',	
					'pass_ctgy': ctgy_subp
					
				},

				success: function(data) {
						
					$('#main_rev_cnt').html(data);
					$('#ctgy_revs_subpage').html(data);
					$('#show_catalog_res').html(data);
					$('.back_to_ctgs').hide(); // Hide "Back to reviews" button on top
					scrlToPos();

				},
				
				error: function(xhr) { alert(xhr.responseText); }
				
			});
			
		});
		
	}
	
	showCtgyOnClkSubpage();
	
	// Get back to the categories subpage on click
	
	function goToCtgys() {
		
		$(document).on('click', '.ctybtn', function(prvEvt) {
			
			event.preventDefault(prvEvt);
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_ctgys_subpage_ajx'
					
				},

				success: function(data) {
						
					$('#ctgy_revs_subpage').html(data);
					$('#main_rev_cnt').html(data);
					$('#show_catalog_res').html(data);
					$('.back_to_ctgs').hide();
					scrlToPos();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
				
			});
			
		});
		
	}
	
	goToCtgys();
	
		function backToCtgys() {
		
		$(document).on('click', '.back_to_ctgs', function() {
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_ctgys_subpage_ajx'
					
				},

				success: function(data) {
						
					$('#ctgy_revs_subpage').html(data);
					$('.back_to_ctgs').hide();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
				
			});
			
		});
		
	}
	
	backToCtgys();
	
	// Show newest reviews
	
	function showNewestRevs() {
	
		$.ajax ({
			
			url: ajxInit.ajax_url,
			method: 'post',
			data: {
				
				'action': 'show_newest_revs_ajx'
				
			},

			success: function(data) {

				$("#newest_revs").html(data); // Load results and then make a check 
				
				if ($("#newest_revs").is(":empty")) {
			
					$("#newest_revs").append("<div class='mt-3 text-warning'>Aktualnie nie znaleziono nowych recenzji!</div>"); 
					
				}
			
			},
			
			error: function(xhr) { alert(xhr.responseText); }
			
		});
		
	}
	
	showNewestRevs();
	
	// Open newest review on click
	
		function openNewestRev() {
		
		$(document).on('click', '.show_newest_rev', function() {
					
			var id_newest = $(this).attr('data-id-newest-rev');
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'open_newest_rev_ajx',	
					'id_newest': id_newest
				},
				
				success: function(data) {
					
					$('#main_rev_cnt').html(data);
					scrlToPos();
					cnrtLnk();
					//window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
  
					
				
				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
					
		});
		
	}
	
	openNewestRev();
	
	// Show catalog
 
 	function showCtgl() {
		
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_ctgl_ajx'
					
				},
				
				success: function(data) {

					$('#rev_catalog').html(data);
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
		
			});
	
	}
 
	showCtgl();
	
	// Show catalog results on click
	
	function showCtglOnClk() {
	
		$(document).on('click', '.show_rev_alph', function() {
			
		 var fchar = $(this).attr('data-fchar');
		 
			 $.ajax ({
				 
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_rev_alph_ajx',
					'fchar': fchar
					
				},
				
				success: function(data) {
					
					$('#show_catalog_res').html(data);
					window.scrollTo({top: $('#show_catalog_res').offset().top -100, behavior: 'smooth'});
					cnrtLnk();
					
				},
				
				error: function(xhr) { alert(xhr.responseText); }
				 
			 });
		
		})
	
	}
	
	showCtglOnClk();
	
	// Button for other results then alphabetical in catalog section
	
	function restResCtlg() {
		
		$(document).on('click', '.show_res_rev', function() {
			
			var fchar = $(this).attr('data-fchar');
			
			$.ajax ({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'show_res_rev_alph_ajx',
					'fchar': fchar
					
				},
				
				success: function(data) {
					
					$('#show_catalog_res').html(data);
					
				},
				
				error: function(xhr) { alert(xhr.responseText) }
				
			});
			
		});
		
	}
	
	restResCtlg();
	
	// Add exception for smaller screens
	function ajxFnsh() {
		
	$(document).ajaxComplete( function() { // Add ajaxComplete method in order to be able to add css with jquery after ajax request is completed
		
	var sizeVar = window.matchMedia("(max-width: 960px)");	
		
	function chngSize(sizeVar) {
		
		if (sizeVar.matches) { // If media query matches
		  
		  $('.rev-tmp').find('.col-4').css({'width': '100%', 'margin-bottom': '25px'});
		  $('.rev-tmp').find('.col-4').addClass('d-flex justify-content-center');
		  $('.rev-tmp').find('.col-8').css('width', '100%');
		  $('.rev-tmp').find('.col-8').children().removeAttr("style").css({'padding-left': '0px!important'});
		  $('#ctgy_revs_subpage').find('.col-3').css('width', '100%'); // Add exception for smaller screens - categories
		  $('#main_rev_cnt').find('.col-3').css('width', '100%');
		  $('#main_srch_box').css('width', '100%');
		  $('#show_catalog_res').find('.col-3').css('width', '100%');		  
		  
		}
		
		else {
			
		  $('.rev-tmp').find('.col-4').removeAttr("style");
		  $('.rev-tmp').find('.col-4').removeClass('d-flex justify-content-center');
		  $('.rev-tmp').find('.col-8').removeAttr("style");
		  $('.rev-tmp').find('.col-8').children().css({'padding-left': '25px'});
		  $('#ctgy_revs_subpage').find('.col-3').removeAttr("style");
		  $('#main_rev_cnt').find('.col-3').removeAttr("style");
		  $('#main_srch_box').removeAttr("style");
		  $('#show_catalog_res').find('.col-3').removeAttr("style");
			
		}
		  
	}
	
	chngSize(sizeVar); // Call listener function at run time
	sizeVar.addListener(chngSize); // Attach listener function
	
	});
	
	}
	
	ajxFnsh();
	
    // Find movie modal - with several options - for the sidebar plugin

    // When the user clicks on the link, open the modal
    $(document).on('click', 'a[href="open-movie-select-option"]', function(evtSrchOpt) {
        evtSrchOpt.preventDefault();
        
        var srchOpt = new bootstrap.Modal(document.getElementById('srchOpt'), {});
        srchOpt.show(); // Show the modal using Bootstrap's method
    });

    // Handle the link click inside the first modal to open the second modal // Updated 10.06.2024
    $(document).on('click', '#hlp-fnd-mov', function() {
        // First hide the current modal (srchOpt)
        var srchOptModal = bootstrap.Modal.getInstance(document.getElementById('srchOpt'));
        srchOptModal.hide();

        // Then create and show the second modal // Button - help me find a movie
        srchOptModal._element.addEventListener('hidden.bs.modal', function() {
            var fnMovModal = new bootstrap.Modal(document.getElementById('fnMovModal'), {});
            fnMovModal.show();
        }, { once: true });
    });

    // Button - find a movie in the DB
    $(document).on('click', '#fnd-mov-db', function() {
        var srchOptModal = bootstrap.Modal.getInstance(document.getElementById('srchOpt'));
        srchOptModal.hide();
        
        // Ensure backdrop is removed after the modal is completely hidden
        srchOptModal._element.addEventListener('hidden.bs.modal', function() {
            window.scrollTo({top: $('#szukajfilmu').offset().top - 100, behavior: 'smooth'});
            $('.modal-backdrop').remove(); // for hiding the background behind the modal
        }, { once: true });
    });

    // Button - find a movie according to the review
    $(document).on('click', '#chs-mov-rev', function() {
        var srchOptModal = bootstrap.Modal.getInstance(document.getElementById('srchOpt'));
        srchOptModal.hide();
        
        // Ensure backdrop is removed after the modal is completely hidden
        srchOptModal._element.addEventListener('hidden.bs.modal', function() {
            window.scrollTo({top: $('#pokazrecenzje').offset().top - 100, behavior: 'smooth'});
            $('.modal-backdrop').remove(); // for hiding the background behind the modal
        }, { once: true });
    });
	
	// Button "Help me choose a movie" - near the TMDB Search Box
    $(document).on('click', '#help-me-choose-the-movie', function(evtSrOpt) {
        evtSrOpt.preventDefault();
        
        var srchOpt = new bootstrap.Modal(document.getElementById('srchOpt'), {});
        srchOpt.show(); // Show the modal using Bootstrap's method
    });
	
	// Click event in the image "Help me find a movie"
    $(document).on('click', '#help-me-find-the-movie', function(evtFnMov) {
        evtFnMov.preventDefault();
        
        var srchOpt = new bootstrap.Modal(document.getElementById('srchOpt'), {});
        srchOpt.show(); // Show the modal using Bootstrap's method
    });
	
	// Scroll to position on click - for categories
	
	function scrlToPos() {
		
		const ctgyPosFrontPage = document.getElementById("main_rev_cnt");
		const ctgyPosRevSubp = document.getElementById("ctgy_revs_subpage");
		const ctgyPosCtgRes = document.getElementById("show_catalog_res");
		
		if (ctgyPosFrontPage) {
			
			//ctgyPosFrontPage.scrollIntoView();
			window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
			
		}
		
		if (ctgyPosRevSubp) {
			
			window.scrollTo({top: $('#ctgy_revs_subpage').offset().top -100, behavior: 'smooth'});
			
		}
		
		if (ctgyPosCtgRes) {

			window.scrollTo({top: $('#show_catalog_res').offset().top -100, behavior: 'smooth'});
			
		}
		
	}
	
	// Replace links in the review text
	
	function cnrtLnk() {
	
	$('.RevTxT').each(function(){
		
		$(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1" target="_blank" class="text-warning">Kliknij aby obejrzeć</a> ') );
		
	});
	
	}
	
	cnrtLnk();
	
	// Find movie modal
	
	$(document).on('click', '#fnMovModal', function() {
		
		$('.modal-backdrop').show();
		
	}); 
	
	$(document).on("click", "#hlp-ctgy", function() {

		$("#mdl-ctgy").show();
		$("#md-main-cnt").hide();
		$("#show-main-nav-btn").show();
 
	});
	
	$(document).on("click", "#hlp-chse", function() {

		$("#mdl-chs").show();
		$("#md-main-cnt").hide();
		$("#show-main-nav-btn").show();

	});
	
	$(document).on("click", "#hlp-md", function() {

		$("#mdl-md").show();
		$("#md-main-cnt").hide();
		$("#show-main-nav-btn").show();
 
	});
	
	// Back to main view
	
	$(document).on("click", ".hlp-back", function() {

		$("#md-main-cnt").show();
		$("#show-main-nav-btn").hide();
		$("#mdl-ctgy").hide();
		$("#mdl-chs").hide();
		$("#mdl-md").hide();
 
	});
	
	// Check all input fields
	
	$(document).on("click", ".slct-all", function() {
	
		$(".hlp-pics").find("input").prop("checked", true);
	
	});
	
	// Uncheck all input fields
	
		$(document).on("click", ".dslct-all", function() {
	
		$(".hlp-pics").find("input").prop("checked", false);
	
	});
	
	// Modal - search via category
	
	function srchCtgyMod() {
	
	$(document).on('click', '#srchctgy', function() {
		
		var animated = $('#anmtd:checked').val();
		var drama = $('#drama:checked').val();
		var fantasy = $('#fantasy:checked').val();
		var horror = $('#horror:checked').val();
		var comedy = $('#comedy:checked').val();
		var adventure = $('#adventure:checked').val();
		var romans = $('#romans:checked').val();
		var sci_fi = $('#sci-fi:checked').val();
		var sensacja = $('#action:checked').val();
		var thriller = $('#thriller:checked').val();
		var crime = $('#crime:checked').val();
		
		all_Val = new FormData();
		
		all_Val.append('animated', animated);
		all_Val.append('drama', drama);
		all_Val.append('fantasy', fantasy);
		all_Val.append('horror', horror);
		all_Val.append('comedy', comedy);
		all_Val.append('adventure', adventure);
		all_Val.append('romans', romans);
		all_Val.append('sci_fi', sci_fi);
		all_Val.append('sensacja', sensacja);
		all_Val.append('thriller', thriller);
		all_Val.append('crime', crime);
		all_Val.append('crime', crime);
		all_Val.append('action', 'srch_ctgy_md');
		
		$.ajax({
			
			url: ajxInit.ajax_url,
			method: 'post',
			contentType: false,
			processData: false,
			data: all_Val,
			
			success: function(data) {
				
				$('#main_rev_cnt').html(data);
				window.$('#fnMovModal').modal('hide'); // dont use hide() and use window:$ otherwise you get .modal is not a function
				$('.modal-backdrop').hide();
				//$("body").css("overflow", "visible");
				window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});

			    
				
			},
			
			error: function(xhr) { alert (xhr.responsText); }
			
		});
		
	});
	
	}
	
	srchCtgyMod();
	
	// Search according to the particular words
	
	function srchOnLstMod() {
	
	$(document).on('click', '#srchonlst', function() {
		
		var srchqr = $('#srchmovonlst').val();
		
		$.ajax({
			
			url: ajxInit.ajax_url,
			method: 'post',
			data: {
				
				'action': 'srch_onlst_md',
				'srchonlst': srchqr
				
			},
			
			success: function(data) {
				
				$('#main_rev_cnt').html(data);
				window.$('#fnMovModal').modal('hide');
				$('.modal-backdrop').hide();
				window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
				
			},
			
			error: {
				
				error: function(xhr) { alert(xhr.responseText) }
				
			}
			
		});
		
	});
	
	}
	
	srchOnLstMod();
	
	// Search accordding to the mood - something to raise the mood
	
	function raiseMD() {
	
		$(document).on('click', '#bttrmd', function() {
		
			$.ajax({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'fnd_Mov_rse_MD',
				
				},
				
				success: function(data) {
				
					$('#main_rev_cnt').html(data);
					window.$('#fnMovModal').modal('hide');
					$('.modal-backdrop').hide();
					window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
			
					error: function(xhr) { alert(xhr.responseText) }
				
			});
			
		});
	
	}
	
	raiseMD();
	
	// Search accordding to the mood - simply find something
	
	function fndsomeMV() {
	
		$(document).on('click', '#nutrmd', function() {
		
			$.ajax({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'fnd_Mov_ntrl_MD',
				
				},
				
				success: function(data) {
				
					$('#main_rev_cnt').html(data);
					window.$('#fnMovModal').modal('hide');
					$('.modal-backdrop').hide();
					window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
			
					error: function(xhr) { alert(xhr.responseText) }
				
			});
			
		});
	
	}
	
	fndsomeMV();
	
	// Search accordding to the mood - find interesting movie
	
	function fndsmthgGD() {
	
		$(document).on('click', '#gdmd', function() {
		
			$.ajax({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'fnd_Mov_smthg_GD',
				
				},
				
				success: function(data) {
				
					$('#main_rev_cnt').html(data);
					window.$('#fnMovModal').modal('hide');
					$('.modal-backdrop').hide();
					window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
			
					error: function(xhr) { alert(xhr.responseText) }
				
			});
			
		});
	
	}
	
	fndsmthgGD();
	
	// Search accordding to the mood - find interesting movie but not a horror
	
	function fndnohrrMV() {
	
		$(document).on('click', '#nohrr', function() {
		
			$.ajax({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {

					'action': 'fnd_Mov_nohrr_MV',
				
				},
				
				success: function(data) {
				
					$('#main_rev_cnt').html(data);
					window.$('#fnMovModal').modal('hide');
					$('.modal-backdrop').hide();
					window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
			
					error: function(xhr) { alert(xhr.responseText) }
				
			});
			
		});
	
	}
	
	fndnohrrMV();
	
	// Search from the gallery according to the slide

	function fndRevfromGlly() {
	
	document.querySelectorAll(".opnRevfrmSld").forEach(fndEl => {
		
		fndEl.addEventListener('click', function(evt) {
			
			event.preventDefault(evt);

			let fndImg = this.querySelector("img");
			let fndImgAltVal = fndImg.getAttribute("rev-id");

			$.ajax({
				
				url: ajxInit.ajax_url,
				method: 'post',
				data: {
					
					'action': 'fnd_rev_from_sld',
					'fndSld': fndImgAltVal
					
				},
				
				success: function(data) {
					
					$('#main_rev_cnt').html(data);
					window.scrollTo({top: $('#main_rev_cnt').offset().top -100, behavior: 'smooth'});
					
				},
					
					error: function(xhr) { alert(xhr.responseText) }
				
			});
		
		});
		
	});
	
	}
	
	fndRevfromGlly();
	
// Launch Trailer from the review template

// Modal window to show the trailers

// Get the modal
var mdlRevTrlCnt = document.getElementById("opnMDTrl");

// Get the <span> element that closes the modal
var clsTrailerModal = document.getElementsByClassName("cls-rev-trl-box")[0];

// When the user clicks on <span> (x)

    // Wenn die Elemente auf dieser Seite NICHT existieren – Script hier beenden
    if (!mdlRevTrlCnt || !clsTrailerModal) {
        return;
    }

    // When the user clicks on <span> (x)
    clsTrailerModal.onclick = function () {
        mdlRevTrlCnt.style.display = "none";
        $('#clsRevTrlBox').remove(); // close Trailer - Box and stop video
    };

    // When the user clicks anywhere outside of the modal, then close the modal
    $(window).on('click', function (evtClsRevTrl) {
        if (evtClsRevTrl.target === mdlRevTrlCnt) {
            mdlRevTrlCnt.style.display = "none";
            $('#clsRevTrlBox').remove(); // close Trailer - Box and stop video
        }
    });

// End

// Loader

function dsplyLoaderinModal() {
	
	$('#mdlLoader').show();

}

function hideLoaderinModal() {
	
	$('#mdlLoader').hide();
	
}

// Find movie trailer on click

$(document).on('click', '.lnchTrl', function(e) {
	
	event.preventDefault(e);
	
	$('#nthfnd').remove();
	
	// variable for searching of the PL trailer version
	let movName = $(this).attr('data-id-trl');
	let movDate = $(this).attr('data-mov-date'); // Date creation movie
	// Varieble to pass in to the model to search for ENG trailer version if PL not found
	let engMovNm = $(this).attr('data-eng-ttl');
	let mdDiv = document.getElementById('engTtlVal');
	
	mdDiv.setAttribute('data-eng-ttl', engMovNm);
	mdDiv.setAttribute('data-mov-date', movDate); 
	// Int main search API Function
	fndRevTrl(movName, movDate);
	// Open modal
	mdlRevTrlCnt.style.display = "block";

});

// Code for finding the trailer in PL - Version on click

function fndRevTrl(srchMov, movDate) {
	
	const srchAPI =`https://api.themoviedb.org/3/search/movie?api_key=aada4d2d75f6f63c63a480b0e6d3d4bd&query=${srchMov}&language=pl-PL`;
	
	fetch(srchAPI).then(response => response.json()).then(data => {
	
	if ( data.total_results == 0 ) {
		
		document.getElementById("showTrlofRev").innerHTML = `
			
			<div class="trlInfBox" style="text-align: center;">
				<h3 class="text-warning">Nie znaleziono zapowiedzi w języku polskim</h3>
				<br/>
				<button class="revEngTrailer btn-warning mb-5" style="text-align: center!important;">Pokaż zapowiedź w języku angielskim</button>
			</div>

		`;	

	}
	
	else {
		
		dspRevRes(data.results, movDate);
		$('#showTrlofRev').show();
		
	}

	})
	
	.catch((error) => {
		
		document.getElementById("errorMsg").innerHTML = error;

	}); 
	
};

function dspRevRes(data, movDate) {
	
	if (data.total_results !== "" || data.total_results !== undefined || data !== undefined) {
		
		//let defaultId = data.length > 0 ? data[0].id : null;

        data.forEach((movie, index) => {
			
            const { id, release_date } = movie;

            if (release_date.startsWith(movDate)) {
				
                // Show the result matching the year in movDate
                let movId = id;

                srchRevTrailer(movId);
				
            } else if (index === 0) {
				
                // If release_date is not found, use the id from the first position
                let movId = id; //defaultId;
               
                srchRevTrailer(movId);
				
            } 
			
        });
		
	}	
	
}

// Function to search for trailer based on the ID form TMDB API query according to title (PL Version)		

	function srchRevTrailer(id) {
		
		const lnkAPI =`https://api.themoviedb.org/3/movie/${id}/videos?api_key=aada4d2d75f6f63c63a480b0e6d3d4bd&language=pl-PL`;

		dsplyLoaderinModal();

		fetch(lnkAPI)
		
		.then(response => response.json())
		
		.then(data => { 
	
		hideLoaderinModal();

		if ( data.results !== 0 || data.results !== ""  ) {

			  revTrlQry(data.results); 
			  //$('#showTrailer').show();
			 
			} 
			
		 if ( data.results == "") {
				
				document.getElementById("showTrlofRev").innerHTML = `
					
					<div class="trlInfBox" style="text-align: center;">
						<h3 class="text-warning">Nie znaleziono zapowiedzi w języku polskim</h3>
						<br/>
						<button class="revEngTrailer btn-warning mb-5" style="text-align: center!important;">Pokaż zapowiedź w języku angielskim</button>
					</div>

				`;
				
			} 	

		})
		
		.catch((error) => {
			
			document.getElementById("errorMsg").innerHTML = error;

		}); 
		
	}  

	// Loop through results of the query

	function revTrlQry(data) {

		  data.forEach(trailer => {

			  const elTrailer = { key } = trailer;
			  
			   document.getElementById("showTrlofRev").innerHTML = `
			 
			   <div id="clsRevTrlBox">
					<div class="row">
					   <div col="4" class="mb-1">
						   <div class="cntTrlBox">
								<iframe id="dspTrailer" class="resp-ifrm" src="https://www.youtube.com/embed/${key}" title="Trailer"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          allowfullscreen></iframe>
						   </div>
					   </div>
					</div>
			   </div>
			 
				`;
			   
		  }); 
				
	}		
		
// End	
	
// Click to open trailer in the ENG Version

$(document).on('click', '.revEngTrailer', function() {
	
	let movNameEng = $("#engTtlVal").attr('data-eng-ttl');
	let movDate = $("#engTtlVal").attr('data-mov-date');
	
	if ( movNameEng == "" ) {
		
	    document.getElementById("showTrlofRev").innerHTML = `
				
			<p id="nthfnd" style="text-align: center!important;">Originalny tytuł filmu nie został podany.<br /> Znalezienie zwiastuna filmu jest nie możliwe!</p>

		`;
	
	}
	
	else {

		fndTrlEng(movNameEng, movDate);

	}

}); 

// Code for finding the trailer in PL - Version on click

function fndTrlEng(srchMov, movDate) {
	
	const srchAPI =`https://api.themoviedb.org/3/search/movie?api_key=aada4d2d75f6f63c63a480b0e6d3d4bd&query=${srchMov}&language=pl-PL`;
	
	dsplyLoaderinModal();
	
	fetch(srchAPI).then(response => response.json()).then(data => {
		
		hideLoaderinModal();
		
		if ( data.total_results == 0 ) {
			
			document.getElementById("showTrlofRev").innerHTML = `
				
				<p id="nthfnd" style="text-align: center!important;">Nie znaleziono zwiastuna filmu!</p>

				`;	

		}
		
		else {

			dspRevResEng(data.results, movDate);
			$('#showTrlofRev').show();
			
		}

	})
	
	.catch((error) => {
		
		document.getElementById("errorMsg").innerHTML = error;

	}); 
	
};

function dspRevResEng(data, movDate) {
	
    if (data !== "" || data !== undefined) {
		
        //let defaultId = data.length > 0 ? data[0].id : null;

        data.forEach((movie, index) => {
			
            const { id, release_date } = movie;

            if (release_date.startsWith(movDate)) {
				
                // Show the result matching the year in movDate
                let movId = id;

                srchRevTrlEng(movId);
				
            } else if (index === 0) {
				
                // If release_date is not found, use the id from the first position
                let movId = id; //defaultId;
               
                srchRevTrlEng(movId);
				
            } 
			
        });
		
    }
	
}

// APi query for trailer - ENG language version

function srchRevTrlEng(id) {
    
	const lnkAPIEng =`https://api.themoviedb.org/3/movie/${id}/videos?api_key=aada4d2d75f6f63c63a480b0e6d3d4bd`;

	fetch(lnkAPIEng)
	
	.then(response => response.json())
	
	.then(data => { 

		if ( data.results !== 0 ) {

		  revEngTrlQry(data.results); 
		  //$('#showTrailer').show();
		 
		} 
		
		if ( data.results == "") {
			
			document.getElementById("showTrlofRev").innerHTML = `
				
				<p id="nthfnd" style="text-align: center!important;">Nie znaleziono żadnej zapowiedzi!</p>

			`;
			
		}	

	})
	
	.catch((error) => {
		
		document.getElementById("errorMsg").innerHTML = error;

	}); 
	
}  

// Loop through results of the query

function revEngTrlQry(data) {

	  data.forEach(trailer => {
		  
		  const elTrailer = { key } = trailer;

		   document.getElementById("showTrlofRev").innerHTML = `
		 
		   <div id="clsRevTrlBox">
				<div class="row">
				   <div col="4" class="mb-1">
					   <div class="cntTrlBox">
							<iframe id="dspTrailer" class="resp-ifrm" src="https://www.youtube.com/embed/${key}" title="Trailer"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          allowfullscreen></iframe>
					   </div>
				   </div>
				</div>
		   </div>
		 
			`;
		   
	  });
		    
}

// End

// Hack for the trailers on the single page contains the single review. Adding the production year to make 
// the search more accurate

       $(document).ready(function () {
            // Function to get and set the year value
            function getAndSetYear() {
                // Find the <li> element containing the year
                var yearElement = $("ul.list-unstyled li:contains('Rok produkcji:')");

                // Extract the year value
                var yearValue = yearElement.text().replace("Rok produkcji:", "").trim();

                // Set the year value as the data-mov-date attribute for the target element
                $(".lnchTrl").attr("data-mov-date", yearValue);
            }

            // Call the function
            getAndSetYear();
        });
		
// End of hack

// For swiper library 

$(document).ready( function() { 

window.addEventListener("resize", chngSizeArtclPrev);

	function chngSizeArtclPrev() {
		
		const viewPrtWmp = window.innerWidth
		const viewPrtHmp = window.innerHeight
		
		let fndAttrEl = document.getElementById('artclPrev');
		let getAttrEl = fndAttrEl.getAttribute("slides-per-view");

		if ( viewPrtWmp < 486 ) {
			
			fndAttrEl.setAttribute("slides-per-view", "1");
			
		}
		
		else if ( viewPrtWmp >= 486 && viewPrtWmp <= 786 ) {
			
			fndAttrEl.setAttribute("slides-per-view", "2");
			
		}
		
		else if ( viewPrtWmp > 786 && viewPrtWmp < 1023 ) {
			
			fndAttrEl.setAttribute("slides-per-view", "2");
			
		}
		
		else {
			
			fndAttrEl.setAttribute("slides-per-view", "5");
			
		}
		
	}

});

// End

});