/* JS Document */

/******************************

[Table of Contents]

1. Vars and Inits
2. Set Header
3. Init Hero Slider
4. Init SVG
5. Initialize Hamburger
6. Initialize Testimonials Slider
7. Initialize Parallax


******************************/

$(document).ready(function()
{
	"use strict";

	/* 

	1. Vars and Inits

	*/

	var hamb = $('.hamburger');
	var header = $('.header');
	var hambActive = false;
	var menuActive = false;
	var ctrl = new ScrollMagic.Controller();

	setHeader();

	$(window).on('resize', function()
	{
		setHeader();
	});

	$(document).on('scroll', function()
	{
		setHeader();
	});

	// Set current year in footer
	$('#year').text(new Date().getFullYear());

	initHeroSlider();
	initSvg();
	initHamburger();
	initTestimonialsSlider();
	initPartnersCarousel();
	initAccreditationCarousel();
	initParallax();
	initSETATabs();

	/* 

	2. Set Header

	*/

	function setHeader()
	{
		if(window.innerWidth < 992)
		{
			if($(window).scrollTop() > 100)
			{
				header.addClass('scrolled');
			}
			else
			{
				header.removeClass('scrolled');
			}
		}
		else
		{
			if($(window).scrollTop() > 100)
			{
				header.addClass('scrolled');
			}
			else
			{
				header.removeClass('scrolled');
			}
		}
		if(window.innerWidth > 991 && menuActive)
		{
			closeMenu();
		}
	}

	/* 

	3. Init Hero Slider

	*/

	function initHeroSlider()
	{
		if($('.hero_slider').length)
		{
			var owl = $('.hero_slider');

			owl.owlCarousel(
			{
				items:1,
				loop:true,
				smartSpeed:800,
				autoplay:true,
				nav:false,
				dots:false
			});

			// add animate.css class(es) to the elements to be animated
			function setAnimation ( _elem, _InOut )
			{
				// Store all animationend event name in a string.
				// cf animate.css documentation
				var animationEndEvent = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';

				_elem.each ( function ()
				{
					var $elem = $(this);
					var $animationType = 'animated ' + $elem.data( 'animation-' + _InOut );

					$elem.addClass($animationType).one(animationEndEvent, function ()
					{
						$elem.removeClass($animationType); // remove animate.css Class at the end of the animations
					});
				});
			}

			// Fired before current slide change
			owl.on('change.owl.carousel', function(event)
			{
				var $currentItem = $('.owl-item', owl).eq(event.item.index);
				var $elemsToanim = $currentItem.find("[data-animation-out]");
				setAnimation ($elemsToanim, 'out');
			});

			// Fired after current slide has been changed
			owl.on('changed.owl.carousel', function(event)
			{
				var $currentItem = $('.owl-item', owl).eq(event.item.index);
				var $elemsToanim = $currentItem.find("[data-animation-in]");
				setAnimation ($elemsToanim, 'in');
			})

			// Handle Custom Navigation
			if($('.hero_slider_left').length)
			{
				var owlPrev = $('.hero_slider_left');
				owlPrev.on('click', function()
				{
					owl.trigger('prev.owl.carousel');
				});
			}

			if($('.hero_slider_right').length)
			{
				var owlNext = $('.hero_slider_right');
				owlNext.on('click', function()
				{
					owl.trigger('next.owl.carousel');
				});
			}
		}	
	}

	/* 

	4. Init SVG

	*/

	function initSvg()
	{
		jQuery('img.svg').each(function()
		{
			var $img = jQuery(this);
			var imgID = $img.attr('id');
			var imgClass = $img.attr('class');
			var imgURL = $img.attr('src');

			jQuery.get(imgURL, function(data)
			{
				// Get the SVG tag, ignore the rest
				var $svg = jQuery(data).find('svg');

				// Add replaced image's ID to the new SVG
				if(typeof imgID !== 'undefined') {
				$svg = $svg.attr('id', imgID);
				}
				// Add replaced image's classes to the new SVG
				if(typeof imgClass !== 'undefined') {
				$svg = $svg.attr('class', imgClass+' replaced-svg');
				}

				// Remove any invalid XML tags as per http://validator.w3.org
				$svg = $svg.removeAttr('xmlns:a');

				// Replace image with new SVG
				$img.replaceWith($svg);
			}, 'xml');
		});
	}

	/* 

	5. Initialize Hamburger

	*/

	function initHamburger()
	{
		if($('.hamburger_container').length)
		{
			var hamb = $('.hamburger_container');

			hamb.on('click', function(event)
			{
				event.stopPropagation();

				if(!menuActive)
				{
					openMenu();
					
					$(document).one('click', function cls(e)
					{
						if($(e.target).hasClass('menu_mm'))
						{
							$(document).one('click', cls);
						}
						else
						{
							closeMenu();
						}
					});
				}
				else
				{
					$('.menu_container').removeClass('active');
					menuActive = false;
				}
			});
		}
	}

	function openMenu()
	{
		var fs = $('.menu_container');
		fs.addClass('active');
		hambActive = true;
		menuActive = true;
	}

	function closeMenu()
	{
		var fs = $('.menu_container');
		fs.removeClass('active');
		hambActive = false;
		menuActive = false;
	}

	/* 

	6. Initialize Testimonials Slider

	*/

	function initAccreditationCarousel()
	{
		if($('.accreditation_carousel').length)
		{
			$('.accreditation_carousel').owlCarousel(
			{
				loop: true,
				margin: 16,
				nav: false,
				dots: false,
				autoplay: true,
				autoplayTimeout: 2800,
				autoplayHoverPause: true,
				smartSpeed: 800,
				responsive:
				{
					0:    { items: 2 },
					480:  { items: 3 },
					768:  { items: 4 },
					992:  { items: 5 },
					1200: { items: 6 }
				}
			});
		}
	}

	function initPartnersCarousel()
	{
		if($('.partners_carousel').length)
		{
			$('.partners_carousel').owlCarousel(
			{
				loop: true,
				margin: 30,
				nav: false,
				dots: false,
				autoplay: true,
				autoplayTimeout: 2500,
				autoplayHoverPause: true,
				smartSpeed: 800,
				responsive:
				{
					0:    { items: 2 },
					480:  { items: 3 },
					768:  { items: 4 },
					992:  { items: 5 },
					1200: { items: 6 }
				}
			});
		}
	}

	function initTestimonialsSlider()
	{
		if($('.testimonials_slider').length)
		{
			var owl1 = $('.testimonials_slider');

			owl1.owlCarousel(
			{
				items:1,
				loop:true,
				nav:false,
				autoplay:true,
				autoplayTimeout:5000,
				smartSpeed:1000
			});
		}
	}

	/* 

	7. Initialize Parallax

	*/

	function initParallax()
	{
		// Add parallax effect to home slider
		if($('.slider_prlx').length)
		{
			var homeBcg = $('.slider_prlx');

			var homeBcgScene = new ScrollMagic.Scene({
		        triggerElement: homeBcg,
		        triggerHook: 1,
		        duration: "100%"
		    })
		    .setTween(TweenMax.to(homeBcg, 1, {y: '15%', ease:Power0.easeNone}))
		    .addTo(ctrl);
		}

		// Add parallax effect to every element with class prlx
		// Add class prlx_parent to the parent of the element
		if($('.prlx_parent').length && $('.prlx').length)
		{
			var elements = $('.prlx_parent');

			elements.each(function()
			{
				var ele = this;
				var bcg = $(ele).find('.prlx');

				var slideParallaxScene = new ScrollMagic.Scene({
			        triggerElement: ele,
			        triggerHook: 1,
			        duration: "200%"
			    })
			    .setTween(TweenMax.from(bcg, 1, {y: '-30%', ease:Power0.easeNone}))
			    .addTo(ctrl);
			});
		}
	}

	/* 

	8. Initialize SETA Tabs

	*/

	function initSETATabs()
	{
		if($('.tab_button').length)
		{
			var tabButtons = $('.tab_button');

			tabButtons.on('click', function(event)
			{
				event.preventDefault();

				var tabId = $(this).data('tab');
				var tabContent = $('#' + tabId);

				// Remove active class from all buttons and contents
				tabButtons.removeClass('active');
				$('.tab_content').removeClass('active');

				// Add active class to clicked button and corresponding content
				$(this).addClass('active');
				tabContent.addClass('active');
			});

			// Set first tab as active by default
			tabButtons.first().addClass('active');
			$('.tab_content').first().addClass('active');
		}
	}

	/* 

	8. Initialize Application Form

	*/

	// Store qualifications data for each tab
	var qualificationsData = {
		'service-seta': [
			'66249 - New Venture Creation, Level 4',
			'61595 - Business Administration Services, Level 4',
			'80646 - Beauty and Nail Technology, Level 4',
			'59097 - Real Estate, Level 4',
			'49648 - New Venture Creation (SMME), Level 2',
			'36233 - Specialist Hygiene and Cleaning Services, Level 2',
			'67465 - Business Administration Services, Level 3',
			'20175 - Hygiene and Cleaning Supervision, Level 3',
			'48887 - Hiring Services and Support, Level 3',
			'58395 - Project Management, Level 5',
			'57937 - Hygiene and Cleaning, Level 1',
			'118709 - Occupational Certificate: Commercial Cleaner, Level 01',
			'101869 - Occupational Certificate: Project Manager, level 5'
		],
		'lgseta': [
			'50081 - Leadership Development, Level 4',
			'50309 - Environmental Practice, Level 4',
			'49554 - Public Finance Management and Administration, Level 5',
			'57823 - Ward Committee Governance, Level 2',
			'49752 - Environmental Practice, Level 3',
			'58578 - Local Government Councilor Practices, Level 3',
			'36436 - Local Economic Development, Level 4',
			'60529 - Municipal Governance, Level 5',
			'50205 - Municipal Integrated Development Planning, Level 5',
			'66789 - Environmental Management, Level 5',
			'48965 - Municipal Financial Management, Level 6',
			'433449 - Occupational Certificate- Environment Science Technician',
			'118775 - Occupational Certificate- Municipal Finance Manager, Level 8',
			'99700 - Occupational Certificate- Valuer (Municipal Property Assessor), Level 5'
		],
		'cathsseta': [
			'HSP/AssChf/2/0022 - Assistant Chef, Level 2',
			'NATSITEGD/2/0040 - Nature Site Guide, Level 2',
			'EVM/EVSUPASSOP/4/0002 - Event Support Assistant: Operations, Level 4'
		],
		'agriseta': [
			'49668 - Horticulture, Level 1',
			'48972 - Plant Production, Level 1',
			'66589 - Horticulture, Level 2',
			'66649 - Landscaping, Level 3',
			'49582 - Poultry Production, Level 3',
			'48979 - Animal Production, Level 4'
		],
		'mictseta': [
			'80306 - Electronics, Level 4',
			'78964 - Information Technology: Technical Support, Level 4',
			'61591 - Information Technology: End user Computing, Level 3',
			'48573 - Information Technology: Systems Support, Level 5'
		],
		'etdpseta': [
			'115753 - Conduct outcomes-based assessment, NQF Level 5',
			'115759 - Conduct moderation of outcomes-based assessments, NQF Level 6',
			'117871 - Facilitate learning using a variety of given methodologies, NQF Level 5'
		],
		'qcto': [
			'101869 - Occupational Certificate: Project Manager, NQF Level 5',
			'118709 - Occupational Certificate: Commercial Cleaner, Level 1',
			'118714 - Occupational Certificate: Real Estate Agent, Level 4',
			'433449 - Occupational Certificate: Environment Science Technician',
			'118775 - Occupational Certificate: Municipal Finance Manager, Level 8',
			'99700 - Occupational Certificate: Valuer (Municipal Property Assessor), Level 5',
			'SP-191206 - Occupational Skills Programme: Assistant Baker (Fermented Dough Products), NQF Level 02',
			'SP-211003 - Community Counsellor, NQF Level 05',
			'SP-211006 - Community Development Facilitator (Drug and Alcohol Abuse Awareness), NQF Level 05',
			'SP-200901 - Work Place Preparedness and Risk Control Assistant-Communicable & Other Occupational Diseases, NQF Level 03',
			'SP-210401 - Occupational Skills Programme: New Venture Creation, NQF Level 02',
			'SP-210409 - Conflict Management, NQF Level 05',
			'SP-191214 - Seamstress, NQF Level 03'
		]
	};

	var currentTab = null;
	var recaptchaVerified = false;

	// Initialize EmailJS
	emailjs.init('2FajlDACOKAP-1bCW');

	// Handle Apply button clicks
	$(document).on('click', '.apply_button', function(e) {
		e.preventDefault();
		var tabContent = $(this).closest('.tab_content');
		currentTab = tabContent.attr('id');
		
		// Populate certificate dropdown
		var certificatesSelect = $('#certificates');
		certificatesSelect.empty();
		
		if (qualificationsData[currentTab]) {
			qualificationsData[currentTab].forEach(function(cert) {
				certificatesSelect.append('<option value="' + cert + '">' + cert + '</option>');
			});
		}
		
		// Clear form
		$('#applicationForm')[0].reset();
		recaptchaVerified = false;
		
		// Show modal
		$('#applicationModal').modal('show');
	});

	// reCAPTCHA callback
	function onRecaptchaSuccess(token) {
		recaptchaVerified = true;
		$('#captchaError').hide();
	}

	// Make function global
	window.onRecaptchaSuccess = onRecaptchaSuccess;

	// Handle form submission
	$('#applicationForm').on('submit', function(e) {
		e.preventDefault();

		// Validate reCAPTCHA
		if (!recaptchaVerified) {
			$('#captchaError').show();
			return false;
		}

		// Check if user has already submitted
		var userEmail = $('#emailAddress').val();
		var submittedEmails = JSON.parse(localStorage.getItem('submittedEmails')) || [];
		
		if (submittedEmails.indexOf(userEmail) !== -1) {
			$('#formMessage').removeClass('alert-success').addClass('alert-danger');
			$('#formMessage').html('<strong>Error:</strong> This email has already submitted an application. Only one submission per user is allowed.').show();
			return false;
		}

		// Get form data
		var formData = {
			studentName: $('#studentName').val(),
			surname: $('#studentSurname').val(),
			contactNumber: $('#contactNumber').val(),
			email: userEmail,
			certificates: $('#certificates').val().join(', '),
			seta: currentTab.replace('-', ' ').toUpperCase(),
			submissionDate: new Date().toLocaleString()
		};

		// Send email using EmailJS
		emailjs.send('service_r6d4k9g', 'template_a5o1gzt', {
			to_email: 'admin@rasinkhu.co.za',
			from_name: formData.studentName + ' ' + formData.surname,
			from_email: formData.email,
			student_name: formData.studentName,
			surname: formData.surname,
			contact_number: formData.contactNumber,
			email: formData.email,
			certificates: formData.certificates,
			seta: formData.seta,
			submission_date: formData.submissionDate
		}).then(function(response) {
			// Mark email as submitted
			submittedEmails.push(userEmail);
			localStorage.setItem('submittedEmails', JSON.stringify(submittedEmails));

			// Show success message
			$('#formMessage').removeClass('alert-danger').addClass('alert-success');
			$('#formMessage').html('<strong>Success!</strong> Your application has been submitted successfully. We will contact you shortly.').show();
			
			// Clear form
			$('#applicationForm')[0].reset();
			recaptchaVerified = false;
			
			// Close modal after 3 seconds
			setTimeout(function() {
				$('#applicationModal').modal('hide');
				$('#formMessage').hide();
			}, 3000);
		}).catch(function(error) {
			$('#formMessage').removeClass('alert-success').addClass('alert-danger');
			$('#formMessage').html('<strong>Error:</strong> Failed to submit application. Please try again later.').show();
			console.error('Email sending failed:', error);
		});
	});
});