
/*
 * JavaScript for Chessgame Shizzle Frontend.
 */


/*
Copyright 2017 - 2025  Marcel Pol  (marcel@timelord.nl)
Copyright 2025         mediaformat

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/



/*
 * Upload form.
 * Show help text if clicked.
 * This mimics slideDown(500) using CSS transition.
 *
 * @since 1.0.0
 */
document.addEventListener('DOMContentLoaded', function () {
	document.querySelectorAll('span.cs_chessgame_form_help_header').forEach(function (header) {
		header.addEventListener('click', function (e) {
			e.preventDefault();
			header.style.display = 'none';

			var parent = header.parentElement;
			var content = parent.querySelector('div.cs_chessgame_form_help_inside');

			content.style.display = 'block';
			content.style.height = '0px';
			let fullHeight = content.scrollHeight + 'px';

			setTimeout(() => {
				content.style.transition = 'height 0.5s ease';
				content.style.height = fullHeight;
			});

			return false;
		});
	});
});


/*
 * Upload form.
 * Mangle data for the honeypot.
 *
 * @since 1.0.6
 */
document.addEventListener("DOMContentLoaded", () => {
	document.querySelectorAll('form#cs_new_chessgame')?.forEach( function(form) {

		var honeypot  = chessgame_shizzle_frontend_script.honeypot;
		var honeypot2 = chessgame_shizzle_frontend_script.honeypot2;

		var honeypot_val  = parseInt( form.querySelector(`input#${honeypot}`)?.value, 10 );
		var honeypot2_val = parseInt( form.querySelector(`input#${honeypot2}`)?.value, 10 );

		if ( ! isNaN( honeypot_val ) && (typeof honeypot_val != "undefined") && (typeof honeypot2_val != "undefined") ) {
			if ( honeypot_val > 0 ) {
				form.querySelector(`input#${honeypot2}`).value = honeypot_val;
				form.querySelector(`input#${honeypot}`).value = '';
			}
		}

	});
});


/*
 * Upload form.
 * Mangle data for the form timeout.
 *
 * @since 1.0.6
 */
document.addEventListener("DOMContentLoaded", () => {
	document.querySelectorAll('form#cs_new_chessgame')?.forEach( function(form) {

		var timeout  = chessgame_shizzle_frontend_script.timeout;
		var timeout2 = chessgame_shizzle_frontend_script.timeout2;

		var timer  = parseInt( form.querySelector(`input#${timeout}`)?.value, 10 );
		var timer2 = parseInt( form.querySelector(`input#${timeout2}`)?.value, 10 );

		if ( ! isNaN( timer ) && ! isNaN( timer2 ) && (typeof timer != "undefined") && (typeof timer2 != "undefined") ) {

			var timer  = timer - 1;
			var timer2 = timer2 + 1;

			form.querySelector(`input#${timeout}`).value = timer;
			form.querySelector(`input#${timeout2}`).value = timer2;

		}

	});
});


/*
 * Upload form.
 * Select a result from a dropdown.
 *
 * @since 1.1.2
 */
document.addEventListener('DOMContentLoaded', function () {
	document.querySelectorAll('form#cs_new_chessgame select.cs_result_ajax').forEach(function (select_element) {
		select_element.addEventListener('change', function () {
			var result = select_element.options[select_element.selectedIndex].value;
			if (result !== '') {
				document.querySelector('input#cs_result').value = result;
			}
		});
	});
});


/*
 * Upload form.
 * Use a datepicker for date.
 *
 * @uses jQuery-UI.
 *
 * @since 1.1.9
 */
jQuery(document).ready(function(){

	// Only call it on normal enqueue in main page, not in iframe.
	if ( typeof jQuery.fn.datepicker === "function" ) {
		jQuery('input#cs_datetime').datepicker({ // frontend
			dateFormat: "yy.mm.dd"
		});
		jQuery('input#cs_chessgame_datetime').datepicker({ // admin
			dateFormat: "yy.mm.dd"
		});
	}

});


/*
 * Upload form.
 * Preview of single game.
 * Can be puzzle or regular game.
 *
 * @since 1.2.1
 */
document.addEventListener('DOMContentLoaded', function () {
	document.querySelectorAll('form#cs_new_chessgame input#chessgame_shizzle_preview').forEach(function ( input ) {
		input.addEventListener('click', function (event) {
			event.preventDefault();

			var nonce_field = chessgame_shizzle_frontend_script.nonce;
			var nonce_input = document.querySelector('input#' + nonce_field);
			var nonce = nonce_input ? nonce_input.value : '';

			var cs_puzzle = '';
			var puzzle_checkbox = document.querySelector('form#cs_new_chessgame input.cs_puzzle');
			if (puzzle_checkbox && puzzle_checkbox.checked) {
				cs_puzzle = 'on'; // Mimic standard $_POST value.
			}

			var pgn_textarea = document.querySelector('form#cs_new_chessgame textarea.cs_pgn');
			var cs_pgn = pgn_textarea ? pgn_textarea.value : '';

			var url = chessgame_shizzle_frontend_script.preview_url;
			var oldbrowser = chessgame_shizzle_frontend_script.oldbrowser;

			if (typeof URL !== 'function') {
				document.querySelector('form#cs_new_chessgame div.cs-preview').innerHTML = oldbrowser;
				return;
			}

			var preview_url;
			try {
				preview_url = new URL(url);
			} catch (e) {
				document.querySelector('form#cs_new_chessgame div.cs-preview').innerHTML = oldbrowser;
				return;
			}

			if (typeof preview_url.searchParams.append !== 'function') {
				document.querySelector('form#cs_new_chessgame div.cs-preview').innerHTML = oldbrowser;
				return;
			}

			preview_url.searchParams.append('cs_puzzle', cs_puzzle);
			preview_url.searchParams.append('cs_nonce', nonce);
			preview_url.searchParams.append('cs_pgn', cs_pgn);

			var iframe = '<iframe src="' + preview_url.toString() + '" class="cs-iframe cs-iframe-extended cs-iframe-preview" name="cs-iframe-preview" id="cs-iframe-preview"></iframe>';
			document.querySelector('form#cs_new_chessgame div.cs-preview').innerHTML = iframe;
		});
	});
});


/*
 * Lesson view: Event for clicking the buttons, and getting the filter form or search forms visible.
 * Uses an iframe for rendering a game.
 *
 * @since 1.1.9
 */
jQuery(document).ready(function($) {

	jQuery( "input.cs-lesson-filters-button" ).on( 'click', function() {
		var main_div = jQuery( this ).closest( 'div.cs-lesson-form-container' );
		jQuery("div.cs-lesson-search", main_div).slideUp(300);
		var display = jQuery( 'form.cs-lesson-filters' ).css( 'display' );
		if ( display == 'none' ) {
			jQuery("form.cs-lesson-filters", main_div).slideDown(300);
		} else if ( display == 'block' ) {
			jQuery("form.cs-lesson-filters", main_div).slideUp(300);
		}
		return false;
	});

	jQuery( "input.cs-lesson-search-button" ).on( 'click', function() {
		var main_div = jQuery( this ).closest( 'div.cs-lesson-form-container' );
		jQuery("form.cs-lesson-filters", main_div).slideUp(300);
		var display = jQuery( 'div.cs-lesson-search' ).css( 'display' );
		if ( display == 'none' ) {
			jQuery("div.cs-lesson-search", main_div).slideDown(300);
		} else if ( display == 'block' ) {
			jQuery("div.cs-lesson-search", main_div).slideUp(300);
		}
		return false;
	});

});


/*
 * Lesson view with extra buttons and filters.
 * Can be puzzle or regular game.
 * Uses an iframe for rendering a game.
 *
 * @since 1.1.9
 */
jQuery(document).ready(function($) {

	if ( jQuery( '.cs-chessgame-lesson' ).hasClass('cs-lesson') ) {

		/* Filter form. */
		jQuery( '.cs-lesson-buttons input.cs-next-game' ).on( 'click', function( event ) {

			jQuery( '.cs-lesson-message' ).html('');

			var form = jQuery( 'form.cs-lesson-filters' );
			var ajaxurl = jQuery( 'form.cs-lesson-filters input.cs-lesson-ajaxurl' ).val();
			var defaulterror = jQuery( 'form.cs-lesson-filters input.cs-lesson-defaulterror' ).val();

			// Use an object, arrays are only indexed by integers.
			var cs_lesson_ajax_data = {
				permalink: window.location.href,
				action: 'chessgame_shizzle_lesson_ajax'
			};

			jQuery('form.cs-lesson-filters input').each(function( index, value ) {
				var val = jQuery( this ).prop('value');
				var name = jQuery( this ).attr('name');
				var type = jQuery( this ).attr('type');
				if ( type == 'checkbox' ) {
					var checked = jQuery( this ).prop('checked');
					if ( checked == true ) {
						cs_lesson_ajax_data[name] = 'on'; // Mimick standard $_POST value.
					}
				} else if ( type == 'radio' ) {
					var checked = jQuery( this ).prop('checked');
					if ( checked == true ) {
						cs_lesson_ajax_data[name] = val;
					}
				} else {
					cs_lesson_ajax_data[name] = val;
				}
			});
			jQuery('form.cs-lesson-filters textarea').each(function( index, value ) {
				var val = jQuery( this ).val();
				var name = jQuery( this ).attr('name');
				cs_lesson_ajax_data[name] = val;
			});
			jQuery( 'form.cs-lesson-filters select' ).each(function( index, value ) {
				var val = jQuery( value ).val();
				var name = jQuery( value ).attr('name');
				cs_lesson_ajax_data[name] = val;
			});

			jQuery.post( ajaxurl, cs_lesson_ajax_data, function( response ) {

				if ( chessgame_shizzle_is_json( response ) ) {
					var returndata = JSON.parse( response );

					if ( returndata['cs_post_id'] == 0 ) {
						jQuery( '.cs-lesson-message' ).html('<p class="cs-messages notice">' + returndata['cs_message'] + '</p>');
					}
					if ( returndata['cs_post_id'] > 0 ) {
						jQuery( '.cs-single-lesson-container' ).html( returndata['cs_html'] );

						var timer  = new Number( jQuery( 'input.cs-lesson-offset' ).val() );
						var timer  = timer + 1;
						jQuery( 'input.cs-lesson-offset' ).val( timer );

					}
				} else {
					jQuery( '.cs-lesson-message' ).html('<p class="cs-messages error">' + defaulterror + '</p>');
				}
			});

			event.preventDefault();
		});
		jQuery( 'form.cs-lesson-filters input.cs-lesson-filters-apply' ).on( 'click', function( event ) {

			jQuery( 'input.cs-lesson-offset' ).val( 0 );
			jQuery( '.cs-lesson-buttons input.cs-next-game' ).trigger( 'click' );
			jQuery( "input.cs-lesson-filters-button" ).trigger( 'click' );

			event.preventDefault();
		});


		/* Post ID part of the search form. */
		jQuery( '.cs-lesson-search input.cs-lesson-show-postid' ).on( 'click', function( event ) {

			jQuery( '.cs-lesson-message' ).html('');

			var main_div     = jQuery( this ).closest( 'div.cs-lesson-form-container' );
			var form         = jQuery( 'form.cs-lesson-postid' );
			var ajaxurl      = jQuery( 'form.cs-lesson-postid input.cs-lesson-ajaxurl' ).val();
			var defaulterror = jQuery( 'form.cs-lesson-postid input.cs-lesson-defaulterror' ).val();
			var postiderror  = jQuery( 'form.cs-lesson-postid input.cs-lesson-postiderror' ).val();
			var val          = jQuery( 'input.cs-lesson-search-postid' ).prop('value');

			if ( isNaN( val ) ) {
				jQuery( '.cs-lesson-message' ).html('<p class="cs-messages error">' + postiderror + '</p>');
				event.preventDefault();
				return;
			}

			// Use an object, arrays are only indexed by integers.
			var cs_lesson_ajax_data = {
				permalink: window.location.href,
				action: 'chessgame_shizzle_lesson_ajax_postid'
			};

			jQuery('form.cs-lesson-postid input').each(function( index, value ) {
				var val = jQuery( this ).prop('value');
				var name = jQuery( this ).attr('name');
				var type = jQuery( this ).attr('type');
				cs_lesson_ajax_data[name] = val;
			});

			jQuery.post( ajaxurl, cs_lesson_ajax_data, function( response ) {

				if ( chessgame_shizzle_is_json( response ) ) {
					var returndata = JSON.parse( response );

					if ( returndata['cs_post_id'] == 0 ) {
						jQuery( '.cs-lesson-message' ).html('<p class="cs-messages notice">' + returndata['cs_message'] + '</p>');
					}
					if ( returndata['cs_post_id'] > 0 ) {
						jQuery( '.cs-single-lesson-container' ).html( returndata['cs_html'] );
						jQuery("div.cs-lesson-search", main_div).slideUp(300);
					}
				} else {
					jQuery( '.cs-lesson-message' ).html('<p class="cs-messages error">' + defaulterror + '</p>');
				}
			});

			event.preventDefault();
		});
		jQuery('.cs-lesson-search input.cs-lesson-search-postid').on('keydown', function (event) {
			if ( event.which === 13 ) { // Enter key.
				jQuery( 'input.cs-lesson-show-postid' ).trigger( 'click' );
				event.preventDefault();
			}
		});

		/* Search part of the search form. */
		jQuery( '.cs-lesson-search input.cs-lesson-search-submit' ).on( 'click', function( event ) {

			jQuery( '.cs-lesson-message' ).html('');
			jQuery( 'td.cs-chessgame-search-results' ).html( '' );

			var main_div     = jQuery( this ).closest( 'div.cs-lesson-form-container' );
			var form         = jQuery( 'form.cs-lesson-search' );
			var ajaxurl      = jQuery( 'form.cs-lesson-search input.cs-lesson-ajaxurl' ).val();
			var defaulterror = jQuery( 'form.cs-lesson-search input.cs-lesson-defaulterror' ).val();
			var searcherror  = jQuery( 'form.cs-lesson-search input.cs-lesson-searcherror' ).val();
			var val          = jQuery( 'form.cs-lesson-search input.cs-lesson-search-text' ).prop('value');

			if ( typeof val == 'undefined' || val.length == 0 ) {
				jQuery( '.cs-lesson-message' ).html('<p class="cs-messages error">' + searcherror + '</p>');
				event.preventDefault();
				return;
			}

			// Use an object, arrays are only indexed by integers.
			var cs_lesson_ajax_data = {
				permalink: window.location.href,
				action: 'chessgame_shizzle_lesson_ajax_search'
			};

			jQuery('form.cs-lesson-search input').each(function( index, value ) {
				var val = jQuery( this ).prop('value');
				var name = jQuery( this ).attr('name');
				var type = jQuery( this ).attr('type');
				cs_lesson_ajax_data[name] = val;
			});

			jQuery.post( ajaxurl, cs_lesson_ajax_data, function( response ) {

				if ( chessgame_shizzle_is_json( response ) ) {
					var returndata = JSON.parse( response );

					if ( returndata['cs_post_id'] == 0 ) {
						jQuery( '.cs-lesson-message' ).html('<p class="cs-messages notice">' + returndata['cs_message'] + '</p>');
					}
					if ( returndata['cs_post_id'] > 0 ) {

						jQuery( 'td.cs-chessgame-search-results' ).html( returndata['cs_html'] );

						jQuery( '.cs-lesson-search td.cs-chessgame-search-results tr' ).on( 'click', function( event ) {
							var postid = new Number( jQuery( this ).attr( "data-cs-postid" ) );
							jQuery( 'input.cs-lesson-search-postid' ).val( postid );
							jQuery( "input.cs-lesson-show-postid" ).trigger( 'click' );
							event.preventDefault();
						});

					}
				} else {
					jQuery( '.cs-lesson-message' ).html('<p class="cs-messages error">' + defaulterror + '</p>');
				}
			});

			event.preventDefault();
		});
		jQuery( '.cs-lesson-search input.cs-lesson-search-clear' ).on( 'click', function( event ) {
			jQuery( '.cs-chessgame-search-results' ).html('');
			event.preventDefault();
		});
		jQuery('.cs-lesson-search input.cs-lesson-search-text').on('keydown', function (event) {
			if ( event.which === 13 ) { // Enter key.
				jQuery( '.cs-lesson-search input.cs-lesson-search-submit' ).trigger( 'click' );
				event.preventDefault();
			}
		});

	}

});


/*
 * Search in simple list: Event for clicking the button, and getting the search form visible.
 *
 * @since 1.2.6
 */
jQuery(document).ready(function($) {

	jQuery( "input.cs-simple-list-search-button" ).on( 'click', function() {
		//var main_div = jQuery( this ).closest( 'div.cs-lesson-form-container' );
		//jQuery("div.cs-simple-list-search", main_div).slideUp(300);
		var display = jQuery( 'div.cs-simple-list-search' ).css( 'display' );
		if ( display == 'none' ) {
			jQuery("div.cs-simple-list-search").slideDown(300);
		} else if ( display == 'block' ) {
			jQuery("div.cs-simple-list-search").slideUp(300);
		}
		return false;
	});

});


/*
 * Search in simple list: Event for clicking the button, and getting the search form visible.
 *
 * @since 1.2.6
 */
jQuery(document).ready(function($) {

	/* Search part of the search form. */
	jQuery( '.cs-simple-list-search input.cs-simple-list-search-submit' ).on( 'click', function( event ) {

		jQuery( '.cs-simple-list-search-message' ).html('');
		jQuery( '.cs-simple-list-search-message' ).removeClass( 'error' );

		var main_div     = jQuery( this ).closest( 'div.cs-simple-list-form-container' );
		var form         = jQuery( 'form.cs-simple-list-search' );
		var ajaxurl      = jQuery( 'form.cs-simple-list-search input.cs-simple-list-search-ajaxurl' ).val();
		var defaulterror = jQuery( 'form.cs-simple-list-search input.cs-simple-list-search-defaulterror' ).val();
		var searcherror  = jQuery( 'form.cs-simple-list-search input.cs-simple-list-search-searcherror' ).val();
		var val          = jQuery( 'form.cs-simple-list-search input.cs-simple-list-search-text' ).prop('value');

		if ( typeof val == 'undefined' || val.length == 0 ) {
			jQuery( '.cs-simple-list-search-message' ).html('<p class="cs-messages error">' + searcherror + '</p>');
			jQuery( '.cs-simple-list-search-message' ).css( 'display', 'block' );
			event.preventDefault();
			return;
		}

		// Use an object, arrays are only indexed by integers.
		var cs_simple_search_ajax_data = {
			permalink: window.location.href,
			action: 'chessgame_shizzle_simple_list_search'
		};

		jQuery('form.cs-simple-list-search input').each(function( index, value ) {
			var val = jQuery( this ).prop('value');
			var name = jQuery( this ).attr('name');
			var type = jQuery( this ).attr('type');
			cs_simple_search_ajax_data[name] = val;
		});

		jQuery.post( ajaxurl, cs_simple_search_ajax_data, function( response ) {

			if ( chessgame_shizzle_is_json( response ) ) {
				var returndata = JSON.parse( response );

				if ( returndata['cs_error'] == true ) {

					jQuery( '.cs-simple-list-search-message' ).html('<p class="cs-messages notice">' + returndata['cs_message'] + '</p>');
					jQuery( '.cs-simple-list-search-message' ).addClass( 'error' );
					jQuery( '.cs-simple-list-search-message' ).css( 'display', 'block' );

				} else {

					jQuery( 'div.cs-simple-list-items' ).html( returndata['cs_html'] );
					jQuery( '.cs-simple-list-search-message' ).html('');
					jQuery( '.cs-simple-list-search-message' ).css( 'display', 'none' );

				}
			} else {

				jQuery( '.cs-simple-list-search-message' ).html('<p class="cs-messages error">' + defaulterror + '</p>');
				jQuery( '.cs-simple-list-search-message' ).addClass( 'error' );
				jQuery( '.cs-simple-list-search-message' ).css( 'display', 'block' );

			}
		});

		event.preventDefault();
	});

	jQuery('.cs-simple-list-search-text').on('keydown', function (event) {
		if ( event.which === 13 ) { // Enter key.
			jQuery( '.cs-simple-list-search-submit' ).trigger( 'click' );
			event.preventDefault();
		}
	});

});


function chessgame_shizzle_is_json( string ) {
	try {
		JSON.parse( string );
	} catch (e) {
		return false;
	}
	return true;
}
