$ = jQuery;
let le_pakett_selected = false;
let le_extra_fields_required = false;
let le_extra_fields_filled = false;
let le_subscribtion_desc = '';
let le_subscribtion_name = '';
let le_subscribtion_id;
let pcpp_is_acting = false;

function nb(){
	
}

const paber_pakett = [367334, 215434, 208405, 368104, 264839, 367335, 208422, 367340, 208428, 389829, 389830, 400899, 400898];
const earve_pakett = [
	400899, 400898, 400893, // DEV tooted
	389830, 389829, 389827, // LIVE tooted
];

const pc_bought_cat = 462;

if(typeof pcud_vars !== 'undefined' 
	&& typeof pcud_vars.user_data !== 'undefined'
	&& typeof pcud_vars.user_data.categories !== 'undefined'
	&& pcud_vars.user_data.categories[0] == pc_bought_cat
	&& typeof sessionStorage.getItem('redirectAfterBuy') !== 'undefined'
){
	if(sessionStorage.getItem('redirectAfterBuy')){
		let redirect_url = sessionStorage.getItem('redirectAfterBuy');
		sessionStorage.removeItem('redirectAfterBuy');
		window.location.href = redirect_url;			
	}
}

function checkLisaFields() {
    let inputs = $('#le_shop_fields input.le_user_input_required');
    let allFilled = true;

	inputs.each(function() {
		if($(this).val() === ''){
			if($(this).attr('name') != 'pcpp_plan_dur_ext' && $(this).attr('name') != 'pcpp_real_renew_stamp'){
				allFilled = false;
				return false;			
			}
		}else{
			$('#le_shop_overview .le_overview_'+$(this).attr('name')).text($(this).val());
			$('#le_shop_overview .le_overview_'+$(this).attr('name')).parent().show();
			$('input[name="le_'+$(this).attr('name')+'"]').val($(this).val());
		}
	});
	
	let not_required_inputs = $('#le_shop_fields input:not(.le_user_input_required)');
	not_required_inputs.each(function() {
		$('#le_shop_overview .le_overview_'+$(this).attr('name')).text('');
		$('#le_shop_overview .le_overview_'+$(this).attr('name')).parent().hide();
		$('input[name="le_'+$(this).attr('name')+'"]').val('');
	});	

    le_extra_fields_filled = allFilled;
}

function assign_le_plan(){
	le_extra_fields_required = false;
	le_pakett_selected = true;
	$('input[name="package_id"]').val(le_subscribtion_id);
	let plan_name = $(this).find('.pcpp_plan_name').text();
	$('.chosenPackage').text(le_subscribtion_name);
	$('.packageDesc').html(le_subscribtion_desc);
	$('#le_shop_user .pcpp_plan_block').removeClass('pcpp_chosen');
	$(this).addClass('pcpp_chosen');
	$('.le_shop_user_fields_rows').hide();
	$('#le_shop_fields input').val('');
	$('#le_shop_fields input').removeClass('le_user_input_required');
	if(paber_pakett.includes(le_subscribtion_id) || earve_pakett.includes(le_subscribtion_id)){
		le_extra_fields_required = true;
		let le_fields = 0;
		if(paber_pakett.includes(le_subscribtion_id)){	
			$('#le_shop_user_paber_fields input').addClass('le_user_input_required');				
			$('#le_shop_user_paber_fields').show();
			$('#le_shop_fields .le_shop_titles').text('Paberlehe puhul vajame teilt mõningaid andmeid veel:');
			le_fields++;
		}
		if(earve_pakett.includes(le_subscribtion_id)){
			$('#le_shop_fields .le_shop_titles').text('E-arve tellimuse jätkamiseks vajame teilt veel mõningaid andmeid:');
			$('#le_shop_user_earve_fields input').addClass('le_user_input_required');
			$('#le_shop_user_earve_fields').show();
			le_fields++;
		}
		if(le_fields == 2){
			$('#le_shop_fields .le_shop_titles').text('Paberlehe e-arvega tellimuse jätkamiseks vajame teilt mõningaid andmeid veel:');
		}
		$('#shopStepsNavigation #showLeExtraFieldTab').css('display', 'table-cell');
		$('.le_extra_fields_summary').show();
		$('input[name="le_extra_fields"]').val(1);
	}
	let scroll_to_element;
	if(!le_extra_fields_required){
		$('#shopStepsNavigation #showLeExtraFieldTab').hide();
		$('.le_extra_fields_summary').hide();
		$('input[name="le_extra_fields"]').val(0);
		$('#overviewLeTab').trigger('click');
		scroll_to_element = '#le_shop_overview';
	}else{
		$('#showLeExtraFieldTab').trigger('click');
		scroll_to_element = '#le_shop_fields';
	}
	let targetElement = document.querySelector('.td-main-content-wrap');
	let targetOffset = targetElement.offsetTop-100;
	let scrollOptions = {
	top: targetOffset,
		behavior: 'smooth'
	};
	window.scrollTo(scrollOptions);	

	$('#le_shop_overview input[name="pcpp_key"]').val($('#le_shop_package input[name="pcpp_key"]').val());
	$('#le_shop_overview input[name="pcpp_plan"]').val(le_subscribtion_id);
}


$(document).ready( function (){
	$('textarea[name="tmcp_textarea_1"]').attr('spellcheck', 'off');
	$('textarea[name="tmcp_textarea_1"]').attr('autocapitalize', 'off');
	$('textarea[name="tmcp_textarea_1"]').attr('autocorrect', 'off');
	$('textarea[name="tmcp_textarea_1"]').attr('autocomplete', 'off');
/*
	const textArea = document.querySelector('textarea[name="tmcp_textarea_1"]');
	
	textArea.addEventListener('paste', (event) => {
		event.preventDefault(); // Prevent default paste action
		//alert('Paste is disabled!');
	});	

	function enforce33CharsPerLine() {
		// Get the raw text from the textarea
		let text = textArea.value;

		// Remove any existing line breaks
		text = text.replace(/\r?\n|\r/g, '');

		// Strict chunk size of 33 characters
		const chunkSize = 33;
		const lines = [];

		// Iterate over the text in increments of `chunkSize`
		for (let i = 0; i < text.length; i += chunkSize) {
		let line = text.substring(i, i + chunkSize);

		// If you need to ensure every line is exactly 33 characters (padding with spaces):
		// line = line.padEnd(chunkSize, ' ');

		lines.push(line);
		}

		// Join all chunks with a newline
		textArea.value = lines.join('\n');
		$(textArea).change();
	}

	// Reformat when the textarea loses focus (onblur)
	textArea.addEventListener('change', enforce33CharsPerLine);	
	*/
	
	if($('.woocommerce-error').length > 0){
		$.each( $('.woocommerce-error'), function( key, value ) {
			el_text = $(value).text();
			if(el_text == '\n\t\t\t\n\t'){
				$(value).remove();
			}
		});		
	}
	if(typeof tm_epo_js !== 'undefined' && typeof tm_epo_js.currency_format_symbol !== 'undefined'){
		tm_epo_js.currency_format_symbol = '';
	}
	
	$('.tm-element-ul-textarea textarea').after('<div class="tm_ad_counter">Tähemärke sisestatud: <span class="tm_ad_count">0</span></div>');
	
	$('.tm-element-ul-textarea textarea').on('keydown keyup change', function(event) {
		$(this).next('.tm_ad_counter').find('.tm_ad_count').text($(this).val().length);
	});
	
    $('.le_order_article a').click(function(e) {
        var currentURL = window.location.href;
        sessionStorage.setItem('redirectAfterBuy', currentURL);
    });
	
	// GALERII REDIRECT STUFF
    var slider = $('#new-royalslider-1');

    // Listen for slide change event
    slider.on('rsAfterSlideChange', function(event) {
        var currentSlideIndex = event.currentTarget.rsCurrentSlideId;
        // Check if the current slide is the fourth slide (index 3)
        if (currentSlideIndex === 2) {
            // Add onclick attribute to the fourth slide
            var fourthSlide = $('#new-royalslider-1 .rsSlide:eq(3)');
            fourthSlide.attr('onclick', 'yourFunction();');
        }
    });	
	
	
	$('img[src="https://online.le.ee/wp-content/uploads/2024/03/image_article.png"]').css('cursor', 'pointer');
	$('img[src="https://online.le.ee/wp-content/uploads/2024/03/image_article.png"]').attr('onclick', 'redirect_to_order();');
	$('img[src="https://online.le.ee/wp-content/uploads/2024/03/image_article.png"]').attr('title', 'Vajuta siia, et suunata teid tellimise lehele!');
	// GALERII REDIRECT END
	
	var textarea_ad = $('#product-208269 textarea[name="tmcp_textarea_1"]');

	$('#product-208269 textarea[name="tmcp_textarea_1"]').on('keydown', function(event) {
		var el = document.querySelector('#product-208269 textarea[name="tmcp_textarea_1"]');
		let line = '';
		if (el instanceof HTMLTextAreaElement) {
			// Get the current line of text
			line = el.value.slice(
				el.value.lastIndexOf('\n', el.selectionStart - 1) + 1,
				((end = el.value.indexOf('\n', el.selectionStart)) => end > -1 ? end : undefined)()
			);
		}
		if (line.length > 33) {
			if (event.key !== "Backspace" && event.key !== "Delete") {
				event.preventDefault();
				var text = el.value;
				// Insert a newline character at the current cursor position
				var startPos = el.selectionStart;
				var endPos = el.selectionEnd;
				var newText = text.substring(0, startPos) + '\n' + text.substring(endPos, text.length);
				// Set the new text in the textarea
				el.value = newText;
				// Adjust the cursor position
				el.selectionStart = el.selectionEnd = startPos + 1;
			}
		}
	});
/*
	$('#product-208269 textarea[name="tmcp_textarea_1"]').bind("input", function() {
		var previousValue = $(this).data('old_value') || '',
			newValue = $(this).val();

		if((newValue.length - previousValue.length) > 1) {
			$(this).val(previousValue);
		}

		$(this).data('old_value', $(this).val());
	});		
*/
	$('#product-208269 textarea[name="tmcp_textarea_1"]').on('paste', function(event) {
		event.preventDefault();
	});
	
	$('#le_shop_package .pvtcont_form').submit(function(event) {
		event.preventDefault();
	});
	
	$('#le_shop_package .pcpp_change_plan_btn').click(function(event) {
		event.preventDefault();
	});
	
	$('.le_konto_btn').click( function(){
		$('.le_konto_btn').removeClass('le_konto_btn_selected');
		$(this).addClass('le_konto_btn_selected');
		$('.le_konto_page').hide();
		let el_id = $(this).attr('id');
		switch(el_id){
			case 'le_konto_btn_view':
				$('#le_konto_view').show();
			break;
			case 'le_konto_btn_pw':
				$('#le_konto_pw').show();
			break;
			case 'le_konto_btn_edit':
				$('#le_konto_edit').show();
			break;
		}
	});
	
	$('#le_shop_user .pcpp_plan_block').click( function(e){
		le_subscribtion_id = parseInt($(this).attr('data-plan-id'));
		le_subscribtion_desc = $(this).find('.pcpp_plan_descr').html();	
		le_subscribtion_name = $(this).find('.pcpp_plan_name').text();				
		$('#le_shop_user .pcpp_plan_block').removeClass('pcpp_chosen');
		$(this).addClass('pcpp_chosen');
		assign_le_plan();
	});	
	
	$('.showTab').click( function(e){
		checkLisaFields();
		let target_tab = '#'+$(this).attr('data-target');
		if((le_pakett_selected == false && target_tab == '#le_shop_fields') || (le_extra_fields_required == true && le_extra_fields_filled == false && target_tab == '#le_shop_overview')){
			if(target_tab == '#le_shop_overview'){
				$('#le_shop_notice .le_reg_form_error').text('Palun kõik väljad täita tellimuse lõpuni viimiseks!');
				$('#le_shop_notice .le_reg_form_error').show();
				setTimeout(function(){$('#le_shop_notice .le_reg_form_error').fadeOut();}, 5000);
			}
			return false;
		}
		if(le_pakett_selected == false && target_tab == '#le_shop_overview'){
			return false;
		}
		$('.showTab').removeClass('current');
		$(this).addClass('current');

		$('.le_shop_page').hide();
		$(target_tab).show();
	}); 
	
    $('.pcpp_user_actual_plan_check').click( function(e){
		if(!$('input[type="checkbox"][name="pcpp_plan_dur_ext"]').prop('checked')){
			le_subscribtion_id = $('input[type="checkbox"][name="pcpp_plan_dur_ext"]').val();
			le_subscribtion_name = $('div.pcpp_user_actual_plan[data-plan-id="'+le_subscribtion_id+'"]').find('strong').text()+' + pikendamine';	
			le_subscribtion_desc = '';				
			$('#le_shop_overview input[name="pcpp_plan_dur_ext"]').val(le_subscribtion_id);
			$('#le_shop_overview input[name="pcpp_plan"]').val(le_subscribtion_id);
			$('#le_shop_overview input[name="pcpp_key"]').val($('#le_shop_package input[name="pcpp_key"]').val());
			$('div.pcpp_user_actual_plan[data-plan-id="'+le_subscribtion_id+'"]').find('strong').text();
			// pcpp_dur_ext
			$('.chosenPackage').text(le_subscribtion_name);
			$('#le_shop_overview input[name="pcpp_real_renew_stamp"]').val($('input[name="pc_real_duration_stamp"]').val());
			le_pakett_selected = true;			
			$('#le_shop_user .pcpp_plan_block').removeClass('pcpp_chosen');
			assign_le_plan();			
		}else{
			$('#le_shop_overview input[name="pcpp_plan_dur_ext"]').val('');
			$('#le_shop_overview input[name="pcpp_plan"]').val('');
			$('#le_shop_overview input[name="pcpp_real_renew_stamp"]').val('');
			$('#shopStepsNavigation #showLeExtraFieldTab').hide();
			$('.le_extra_fields_summary').hide();
			$('input[name="le_extra_fields"]').val(0);			
			$('.chosenPackage').text('');
			le_pakett_selected = false;
		}
	});
	
    $(document).on('click', '#le_order_submit_btn', function() {
        if(pcpp_is_acting) {
            return false;
        }
		
		$(this).attr('disabled', true);
		$(this).css('cursor', 'not-allowed');
		
        const $form = $(this).parents('form'),
              $btn  = $(this);

        // be sure at least one option is selected
        let sel_plan = $('#le_shop_overview input[name="pcpp_plan"]').val();
        if(!sel_plan || sel_plan == '') {
            $form.find('.pcpp_form_message').html('<span class="pc_error_mess">' + pcpp_vars.no_sel_opt + '</span>');
			enable_le_submit();
            return false;    
        }
        
        // duration extension?
        let dur_ext; 
        $form.find('.pcpp_plan_dur_ext_block li:not(.pcpp_user_actual_plan_check) input').each(function() {
            if(this.checked) {
                dur_ext = parseInt($(this).val(), 10);
				enable_le_submit();
                return false;
            }
        });
        
        
        // ajax call
        $btn.addClass('pc_spinner_btn');
        $form.find('.pcpp_form_message').empty();

        pcpp_is_acting = true;
        
        let data = {
            type            : 'pcpp_renew_order', 
            pcpp_uid        : $form.find('input[name=pcpp_uid]').val(),
            pcpp_sel_plan   : sel_plan,
            pcpp_dur_ext    : dur_ext,
            pcpp_coupon     : ($form.find('.pcpp_hidden_coupon_field').length) ? $form.find('.pcpp_hidden_coupon_field').val() : '',
            pcpp_key        : $form.find('input[name=pcpp_key]').val(),
            le_extra_fields : $form.find('input[name=le_extra_fields]').val(),
            le_kandeaadress : $form.find('input[name=le_kandeaadress]').val(),
            le_saajanimi    : $form.find('input[name=le_saajanimi]').val(),
            le_kandealgus   : $form.find('input[name=le_kandealgus]').val(),
            le_pank         : $form.find('input[name=le_pank]').val(),
            le_pangakonto   : $form.find('input[name=le_pangakonto]').val(),
            le_renew_stamp  : $form.find('input[name=pcpp_real_renew_stamp]').val(),
        };

        $.ajax({
            type    : "POST",
            url     : window.location.href,
            dataType: "json",
            data    : data,

            success: function(response){
                if(response.status == 'success') {
                    $form.find('.pcpp_form_message').html('<span class="pc_success_mess">'+ response.mess +'</span>');
                    
                    setTimeout(function() {
                        if(response.url == 'refresh') {
                            window.location.reload();        
                        }
                        else if(response.url != 'none') {
                            window.location.href = response.url;        
                        }
                    }, 1300);  
                } 
                else {
                    $form.find('.pcpp_form_message').html('<span class="pc_error_mess">'+ response.error +'</span>');
					enable_le_submit();
                }
            }
        })
        .fail(function(e) {
            if(e.status) {
                console.error('pcpp renew order error', e);
                $form.find('.pcpp_form_message').html('<span class="pc_error_mess">'+ pc_vars.ajax_failed_mess +'</span>');
				enable_le_submit();
            }
        })
        .always(function() {
            $btn.removeClass('pc_spinner_btn');
            pcpp_is_acting = false;    
        });
    });	
});

function enable_le_submit(){
	$('#le_order_submit_btn').attr('disabled', false);
	$('#le_order_submit_btn').css('cursor', 'pointer');	
}