// source --> https://www.kies-krieger.de/wp-content/plugins/karriere-portal/public/js/karriere-portal-public.js?ver=1.1.5 
var currentStep = 1;
var stepsCount = 1;
var otherConfigs = {};

(function( $ ) {
	'use strict';


	/**
	 * All of the code for your public-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * jQuery(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * jQuery( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

	jQuery( document ).ready(function() {
		jQuery("#filter-toggle").click(function(){
			jQuery("#filterForm").slideToggle(300);
			jQuery(this).toggleClass('open');
		});

		if ( jQuery(".kp-steps").length ){
			setupSteps();
		}

		checkHash();

		// load Active Jobs by default
		onActiveJobs();

		jQuery('#activeJobsButton').on('click',function(e){
			onActiveJobs();
		});

		jQuery('#archiveJobsButton').on('click', function(e){
			onNotActiveJobs();
		})

		jQuery('#submitFilter').on('click',function(e) {
			jQuery("#filter-toggle").click();
			var formArraySerializado = jQuery("#filterForm").serializeAssoc();
			onShowJobs(formArraySerializado);
		});
		
		
		jQuery('#resetFilter').on('click',function(e) {
			jQuery("#filter-toggle").click();
			var formArraySerializado = [];
			onShowJobs(formArraySerializado);
		});

		jQuery("#kp-go-top, #scrollButton").click(function(e){
			e.preventDefault();
			var href = jQuery(this).attr('href');
			var el = document.querySelector(href);
			if (el) {
				el.scrollIntoView({
					behavior: 'smooth'
				})
			}
		});

		if(jQuery(".kp-single-job").length){
			setupOtherConfigs();
			var h1Clone = jQuery('#title_of_job').clone();
			h1Clone.find('span').remove();
			var selectedPosition = h1Clone.html().trim();
			if(otherConfigs['application_position_field']) jQuery('#'+otherConfigs['application_position_field']).val(selectedPosition);

		}


	});

	$.fn.serializeAssoc = function() {
		var data = {};
		$.each(this.serializeArray(), function(key, obj) {
			var a = obj.name.match(/(.*?)\[(.*?)\]/);
			if (a !== null) {
				var subName = a[1];
				var subKey = a[2];

				if (!data[subName]) {
					data[subName] = [];
				}

				if (!subKey.length) {
					subKey = data[subName].length;
				}

				if (data[subName][subKey]) {
					if ($.isArray(data[subName][subKey])) {
						data[subName][subKey].push(obj.value);
					} else {
						data[subName][subKey] = [];
						data[subName][subKey].push(obj.value);
					}
				} else {
					data[subName][subKey] = obj.value;
				}
			} else {
				if (data[obj.name]) {
					if ($.isArray(data[obj.name])) {
						data[obj.name].push(obj.value);
					} else {
						data[obj.name] = [];
						data[obj.name].push(obj.value);
					}
				} else {
					data[obj.name] = obj.value;
				}
			}
		});
		return data;
	};

})( jQuery );

var typeOfPageJobs = 'active';

function onActiveJobs() {
    typeOfPageJobs = 'active';
    jQuery('#activeJobsButton').addClass('active');
    jQuery('#archiveJobsButton').removeClass('active');
		var params = jQuery("#filterForm").serializeAssoc();
		onShowJobs(params);
}

function onNotActiveJobs() {
    typeOfPageJobs = 'notActive';
    jQuery('#activeJobsButton').removeClass('active');
    jQuery('#archiveJobsButton').addClass('active');
		var params = jQuery("#filterForm").serializeAssoc();
		onShowJobs(params);
}

function onShowJobs(params = null) {
    jQuery('#showData').addClass('loading-data');
    jQuery.ajax({
        type: "GET",
        dataType: "html",
        url: my_script_vars.ajax_url,
        data: {
            action: "karrierePortalListingJobs",
            type: typeOfPageJobs,
            dataForm: JSON.stringify(params),
        },
        beforeSend: function() {

        },
        success: function(response) {
            var res = JSON.parse(response);
            jQuery('#showData').html(res.data.html);
            jQuery('#showData').removeClass('loading-data');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('The following error occured: ' + textStatus, errorThrown);
            jQuery('#showData').removeClass('loading-data');
        }
    });
}

function onShowMatches(params = null) {

	jQuery('.kp-steps').addClass('loading-data');
	jQuery.ajax({
			type: "GET",
			dataType: "html",
			url: my_script_vars.ajax_url,
			data: {
				action: "karrierePortalListingJobsMatch",
				dataForm: JSON.stringify(params),
			},
			beforeSend: function() {

			},
			success: function(response) {
				var res = JSON.parse(response);
				jQuery('#kpMatches').html(res.data.html);
				jQuery('.kp-steps').removeClass('loading-data');

				if (!res.data.html.length && currentStep > 1){
					showNewsletterForm();
				}
				else{
					showResultsStep();
					bindMatches();
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				console.log('The following error occured: ' + textStatus, errorThrown);
				jQuery('.kp-steps').removeClass('loading-data');
			}
	});
}

function setupOtherConfigs(){
	var strConfigs = jQuery('#kp-translations').val();
	otherConfigs = JSON.parse(strConfigs) || {};
	if (!otherConfigs['configurator_required_option']) otherConfigs['configurator_required_option'] = "Please select at least one option.";
}

function setupSteps(){
	setupOtherConfigs();

	stepsCount = jQuery(".kp-step").length - 1;

	jQuery(".kp-step").find('input').on('change', function(){
		removeWithTransition(jQuery('.kp-step-errors'))
	});

	jQuery(".kp-next-step:not(.kp-last-next)").click(function(e){
		e.preventDefault();
		nextStep();
	})

	jQuery("#kp-show-newsletter").click(function(e){
		e.preventDefault();
		showNewsletterForm();
	})


	// jQuery("#kp-apply-job-btn").click(function(e){
	// 	jQuery(".kp-step[data-step='" + (currentStep) + "']").fadeOut();
	// 	jQuery("#step7").fadeIn();
	// 	jQuery(".kp-matcher-form-apply").removeClass('kp-d-none');
	// });

}

function nextStep(){

	if (currentStep > stepsCount) return;

	if (!validateStep(currentStep)) return;

	currentStep++;

	if (currentStep > stepsCount) {

		var jobCats = [];
		jQuery('input[name="job_categories[]"]:checked').each(function(){
			var val = jQuery(this).val();
			jobCats.push(val);
		})
		var jobTypes = [];
		jQuery('input[name="job_types[]"]:checked').each(function(){
			var val = jQuery(this).val();
			jobTypes.push(val);
		})
		var jobLocations = [];
		jQuery('input[name="job_locations[]"]:checked').each(function(){
			var val = jQuery(this).val();
			jobLocations.push(val);
		})

		var formDt = {
			job_categories: jobCats,
			job_types: jobTypes,
			job_locations: jobLocations
		};

		onShowMatches(formDt);
	}
	else{
		jQuery(".kp-step[data-step='" + (currentStep-1) + "']").fadeOut(function(){
			jQuery(".kp-step[data-step='" + currentStep + "']").fadeIn();
			window.location.hash = 'step'+currentStep;
			scrollToSectionTop();
	
		});
	
		animateStepIndicator();
	}


}

function animateStepIndicator(){
	var stepLeft = ((100 / stepsCount) * currentStep);

	jQuery("#kpCurrentStep").css({
		left: stepLeft < 100 ? 'calc(' + stepLeft + '% - 35px)' : 'calc(100% - 35px)'
	})

	jQuery(".kp-steps-progress").css({
		width: stepLeft < 100 ? stepLeft + '%' : '100%'
	})
}

function validateStep(step){

	var $stepDiv = jQuery(".kp-step[data-step='" + step + "']");

	removeWithTransition($stepDiv.find('.kp-step-errors'));
	
	var hasCheckboxes = $stepDiv.find('input[type="checkbox"]').length;
	var hasChecked = $stepDiv.find('input:checked').length;
	if (hasCheckboxes && !hasChecked) {
		$stepDiv.find('.kp-step-inner').append('<div class="kp-step-errors">'+ otherConfigs['configurator_required_option'] +'</div>')
		return false;
	}

	return true;
}

function removeWithTransition($elem){
	$elem.slideUp(function(){
		$elem.remove();
	})
}

function bindMatches(){

	jQuery(".kp-match-card").click(function(){
		jQuery('.kp-matcher-buttons').slideDown();
		jQuery(".kp-match-card-selected").removeClass("kp-match-card-selected");
		jQuery(this).addClass("kp-match-card-selected");

		var jobLink = jQuery(this).attr('data-link');

		jQuery("#kp-view-job-btn").attr('href', jobLink);
		jQuery("#kp-apply-job-btn").attr('href', jobLink);

		jQuery("#kp-apply-buttons").removeClass('kp-d-none')

	});

	jQuery('#kp-apply-job-btn').click(function(e){
		e.preventDefault();
		showDirectApplyForm();
	})
}

function showNewsletterForm(){
	window.location.hash = 'step8';
	if ( !jQuery(".kp-match-card").length ){
		jQuery("#step8 .kp-step-info").show();
	}
	jQuery(".kp-step").fadeOut(function(){
		jQuery("#step8").fadeIn();
		scrollToSectionTop();
		var msg = jQuery("#kp-configurator-msg").val();
		if(otherConfigs['newsletter_appliers_message_field']) jQuery("#step8").find('#'+otherConfigs['newsletter_appliers_message_field']).val(msg);
	});
}

function showResultsStep(){
	window.location.hash = 'step6';
	jQuery(".kp-step").fadeOut(function(){
		jQuery("#step6").fadeIn();
		scrollToSectionTop();
	});
}

function showDirectApplyForm(){
	window.location.hash = 'step7';
	var selectedPosition = jQuery(".kp-match-card-selected>h5").html();
	jQuery(".kp-match-card-selected").closest('.kp-step').fadeOut(function(){
		jQuery("#step7").fadeIn();
		scrollToSectionTop();
		var msg = jQuery("#kp-configurator-msg").val();
		if(otherConfigs['application_appliers_message_field']) jQuery("#step7").find('#'+otherConfigs['application_appliers_message_field']).val(msg);
		jQuery("#kp-job-position-title").html(selectedPosition);
		if(otherConfigs['application_position_field']) jQuery("#step7").find('#'+otherConfigs['application_position_field']).val(selectedPosition);
	});
}

function checkHash(){
	var hash = window.location.hash;
	if (!hash.length) return;
	var hashStep = parseInt(hash[hash.length - 1]) ?? 1;
	if (hashStep < 7) return;
	currentStep = hashStep;

	if (jQuery(hash).length){
		jQuery(".kp-step").hide();
		jQuery(hash).fadeIn();
		scrollToSectionTop();
		animateStepIndicator();
	}
}

function scrollToSectionTop() {
	setTimeout(function () {
		const el = document.querySelector('#karriere-portal-main');
		if (el) {
			const targetScrollPosition = el.getBoundingClientRect().top + window.scrollY - 200;
			window.scrollTo({
				top: targetScrollPosition,
				behavior: 'smooth',
			});
		}
	}, 300);
};