// source --> https://najlacnejsiemeradla.sk/wp-content/plugins/bonsai-woo-vat-validator/view/js/main.js?ver=1778490853 
/**
 * v20250506
 */
jQuery(document).ready(function($) {





	// ADD notice element for company data fetching feedback (hoisted so toggle can update it)
	var companyDataDefaultText = bbvat_ajax_object.fetcher_description_cz;
	var companyDataNotice = $('<span class="bbvat-notice"></span>').text(companyDataDefaultText);
	$('#billing_company_data_fetcher').after(companyDataNotice);

	// SHOW/HIDE company data fetcher field based on the "Fakturovať na firmu" checkbox and billing country
	// (mirrors the logic in bonsai-woo-superfaktura checkout.js, but runs even when that module is disabled)
	function bbvat_toggle_company_data_fetcher_field() {
		var country = $('#billing_country').val();
		if ( $('#wi_as_company').is(':checked') && country === 'CZ' ) {
			$('#billing_company_data_fetcher_field').fadeIn();
		} else {
			$('#billing_company_data_fetcher_field').fadeOut();
		}
	}
	bbvat_toggle_company_data_fetcher_field(); // on page load
	$('#wi_as_company, #billing_country').change( bbvat_toggle_company_data_fetcher_field );




	// ADD span to hold our VAT verification notices
	var verificationNotice = $('<span id="bbvat-verification-notice" class="bbvat-notice"></span>').hide();
	$('#billing_company_wi_vat').after(verificationNotice);

	// ON fields CHANGE
	// CHECK VAT validity
    $('#wi_as_company, #billing_country, #billing_company, #billing_company_wi_vat').change(function() {

		// GET all validation variables
		var customerBillingCountry = $('#billing_country').val();
		var iscustomerBillingCountryNotSK = customerBillingCountry !== 'SK'; // boolean
		var isCompanyPurchase = $('#wi_as_company').is(':checked'); // boolean
		var companyName = $('#billing_company').val();
		var isCompanyNameProvided = companyName !== ''; // boolean
		var companyVatNumber = $('#billing_company_wi_vat').val();
		var isCompanyVatNumberProvided = companyVatNumber !== '' && companyVatNumber.length > 2; // boolean
		var isCompanyVatExempt = $('#billing_company_is_vat_exempt').val() === '1'; // boolean

		// PREFIX Czech company VAT number with 'CZ', if it's missing
		if ( customerBillingCountry === 'CZ' && isCompanyVatNumberProvided ) {
			// Check if the VAT number already starts with 'CZ'
			if ( companyVatNumber.substring(0, 2).toUpperCase() !== 'CZ' ) {
				companyVatNumber = 'CZ' + companyVatNumber;
				$('#billing_company_wi_vat').val(companyVatNumber);
			}
		}

		// ADMIN debug log
		var debugMessage = `Je fakturačná krajina iná než SK: ${iscustomerBillingCountryNotSK ? 'Áno' : 'Nie'}
Je firemná objednávka: ${isCompanyPurchase ? 'Áno' : 'Nie'}
Je zadaný názov firmy: ${isCompanyNameProvided ? 'Áno' : 'Nie'}
Je zadané IČ DPH: ${isCompanyVatNumberProvided ? 'Áno' : 'Nie'}
Spĺňa firma podmienky na odpočet DPH: ${isCompanyVatExempt ? 'Áno' : 'Nie'}`;

		console.log(debugMessage);

		// CHECK current conditions (values from the form)

		var readdVat = false;
		var callAjax = false;
		var notice = '';

		// IF billing country SK
		if( !iscustomerBillingCountryNotSK ) {
			notice = 'Slovenské objednávky nepodliehajú odpočtu DPH.';
			readdVat = true;
		}
		// IS NOT company purchase
		else if( !isCompanyPurchase ) {
			notice = 'Nefiremné objednávky nepodliehajú odpočtu DPH.';
			readdVat = true;
		}
		// IS company NOT provided
		else if( !isCompanyNameProvided ) {
			notice = 'Nezadali ste názov firmy.';
			readdVat = true;
		}
		// IF VAT number NOT provided
		else if( !isCompanyVatNumberProvided ) {
			notice = 'Nezadali ste vaše číslo IČ DPH.';
			readdVat = true;
		}
		// ALL is good, call AJAX to validate VAT number and store the result
		else {
			notice = 'Všetky podmienky sú splnené, preto cez AJAX overíme platnosť IČ DPH.';
			callAjax = true;
		}

		// DEBUG
		if( notice !== '' ) {
			console.log(notice);
		}

		// IF company is set as VAT exempt, but NOT all conditions are true anymore
		// CALL AJAX to change the variable, so the recalculation adds the VAT back
		// THEN RETURN
		if( isCompanyVatExempt && readdVat ) {
			$.ajax({
				url: bbvat_ajax_object.ajax_url,
				type: 'POST',
				data: {
					action: 'bbvat_remove_vat_exempt_in_session',
					nonce: bbvat_ajax_object.nonce,
				},
				success: function(response) {

					// console.log(response.data.message);
					console.log('Podmienky pre odpočet DPH už neplatia. Spúšťam update_checkout, aby sa VAT pripočítalo...');

					// SET the field value
					$('#billing_company_is_vat_exempt').val(0);

					// Temporarily disable required fields so that the update is not blocked
					jQuery('#billing_company_wi_vat').prop('required', false);

					// Trigger checkout update (class-wc-ajax.php > update_order_review())
					jQuery(document.body).trigger('update_checkout');

					// Re-enable required fields
					jQuery('#billing_company_wi_vat').prop('required', true);

				},
				error: function(xhr, status, error) {
					// console.log('Action bbvat_remove_vat_exempt_in_session failed: ' + error);
				}
			}); // ajax
			return;
		}

		// ALL conditions are right
		// CALL AJAX to validate VAT number
		if( callAjax ) {

			// ADD loading to the input field
			verificationNotice.addClass('is-loading').removeClass('has-error').text(bbvat_ajax_object.verifying_text).fadeIn();

			$.ajax({
				url: bbvat_ajax_object.ajax_url,
				type: 'POST',
				data: {
					action: 'bbvat_validate_vat_and_update_form',
					nonce: bbvat_ajax_object.nonce,
					vat_number: companyVatNumber,
					company_name: companyName
				},
				success: function(response) {

					var isNumberValid = ( response.data.valid === 'yes' ) ? 1 : 0;
					var validationMessage = response.data.message;
					
					// console.log(response.data);
					console.log(validationMessage);

					// SET the field value (either 1 or 0)
					$('#billing_company_is_vat_exempt').val(isNumberValid);

					// IF VAT number valid
					if(isNumberValid === 1) {

						// Remove loading message
						verificationNotice.removeClass('is-loading has-error').fadeOut();

						// Trigger checkout update (class-wc-ajax.php > update_order_review())
						console.log('EU VAT je správne. Spúšťam update_checkout, aby sa VAT odpočítalo...');
						jQuery(document.body).trigger('update_checkout');
					}
					// IF VAT number NOT valid, OR there was an error
					else {

						// SET error message
						verificationNotice.removeClass('is-loading').addClass('has-error').text(validationMessage);

						// Trigger checkout update (class-wc-ajax.php > update_order_review())
						console.log('EU VAT nie je správne, alebo nastala chyba. Spúšťam update_checkout, aby sa VAT pripočítalo...');
						jQuery(document.body).trigger('update_checkout');
					}

				},
				error: function(xhr, status, error) {
					// console.log('Action bbvat_validate_vat_and_update_form failed: ' + error);
				}
			}); // ajax
		}

    }); // ON field change





	// ON fields CHANGE
	// FETCH company data
    $('#billing_company_data_fetcher').change(function() {

		// GET all validation variables
		var billing_company_data_fetcher_field = $('#billing_company_data_fetcher').val();

		// DO NOT call API if field is empty
		if ( billing_company_data_fetcher_field === '' ) {
			companyDataNotice.removeClass('is-loading has-error').text( companyDataDefaultText );
			return;
		}

		// SHOW loading state
		companyDataNotice.addClass('is-loading').removeClass('has-error').text( bbvat_ajax_object.verifying_text );

		// ADMIN debug log
		console.log( 'Zadané IČO alebo názov spoločnosti: ' + billing_company_data_fetcher_field );

		// STRIP legal form from name and update field so user sees what is sent
		var legalFormPattern = /[\s,]+(?:s\.?\s*r\.?\s*o\.?|spol\.\s+s\s+r\.?\s*o\.?|a\.?\s*s\.?|v\.?\s*o\.?\s*s\.?|k\.?\s*s\.?|s\.?\s*c\.?|o\.?\s*z\.?|n\.?\s*o\.?|n\.?\s*f\.?|š\.?\s*p\.?|p\.?\s*o\.?|SZČO|družstvo|nadácia|nadačný\s+fond|z\.?\s*s\.?|o\.?\s*p\.?\s*s\.?)\s*$/i;
		var stripped = billing_company_data_fetcher_field.replace( legalFormPattern, '' ).trim();
		if ( stripped !== billing_company_data_fetcher_field ) {
			$('#billing_company_data_fetcher').val( stripped );
			billing_company_data_fetcher_field = stripped;
		}

		// CALL AJAX to fetch company data
		$.ajax({
			url: bbvat_ajax_object.ajax_url,
			type: 'POST',
			data: {
				action: 'bbvat_fetch_company_data_and_update_form',
				nonce: bbvat_ajax_object.nonce,
				ico_or_company_name: billing_company_data_fetcher_field,
				billing_country: $('#billing_country').val(),
			},
			success: function(response) {

				if ( !response.success ) {
					companyDataNotice.removeClass('is-loading').addClass('has-error').text(response.data);
					return;
				}

				var company = response.data;

				console.log(company);

				// SET company name
				if( company.name ) {
					$('#billing_company').val(company.name);
				}

				// SET ICO
				if( company.ico ) {
					$('#billing_company_wi_id').val(company.ico);
				}

				// SET DIC
				if( company.dic ) {
					$('#billing_company_wi_tax').val(company.dic);
				}

				// SET VAT ID
				// AND trigger change so Czech companies will have their EU VAT checked to remove VAT from the order
				if( company.vat_id ) {
					$('#billing_company_wi_vat').val(company.vat_id).trigger('change');
				}

				// SET payer type (We do not use this field anymore)
				// if( company.vat_payer_type ) {
				// 	if( company.vat_payer_type == '§4' ) {
				// 		$('#billing_company_is_vat_payer').val('yes');
				// 	} else {
				// 		$('#billing_company_is_vat_payer').val('no');
				// 	}
				// }

				// SET company address
				if( company.street && company.city && company.postal_code && company.country ) {
					$('#billing_address_1').val(company.street + ' ' + company.building_number);
					$('#billing_postcode').val(company.postal_code);
					$('#billing_city').val(company.city);
				}

				// SET company country
				if( company.country ) {
					var country_code = 'SK'; // Default to SK
					if( company.country === 'Česká republika' ) { // TOOD: How is Czechia returned?
						country_code = 'CZ';
					}
					$('#billing_country').val(country_code);
				}

				// CLEAR the fetcher field so it does not confuse customers
				$('#billing_company_data_fetcher').val('');

				// RESTORE default description text
				companyDataNotice.removeClass('is-loading has-error').text(companyDataDefaultText);

				// Trigger checkout update — but only if VAT validation was NOT triggered.
				// If vat_id was set above, update_checkout will fire after VIES validation completes.
				if ( !company.vat_id ) {
					console.log('Aktualizovali sme firemné údaje. Spúšťam update_checkout, aby sa prípadne prepočítalo poštovné...');
					jQuery(document.body).trigger('update_checkout');
				}

			},
			error: function(_xhr, _status, error) {
				console.log('Action bbvat_fetch_company_data_and_update_form failed: ' + error);
				companyDataNotice.removeClass('is-loading').addClass('has-error').text('Nepodarilo sa získať údaje o spoločnosti. Skúste to znovu.');
			}
		}); // ajax

    }); // ON field change





}); // jQuery;
// source --> https://najlacnejsiemeradla.sk/wp-content/plugins/woocommerce/assets/js/jquery-blockui/jquery.blockUI.min.js?ver=2.7.0-wc.10.9.4 
/*!
 * jQuery blockUI plugin
 * Version 2.70.0-2014.11.23
 * Requires jQuery v1.7 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2013 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */
!function(){"use strict";function e(e){e.fn._fadeIn=e.fn.fadeIn;var t=e.noop||function(){},o=/MSIE/.test(navigator.userAgent),n=/MSIE 6.0/.test(navigator.userAgent)&&!/MSIE 8.0/.test(navigator.userAgent),i=(document.documentMode,"function"==typeof document.createElement("div").style.setExpression&&document.createElement("div").style.setExpression);e.blockUI=function(e){d(window,e)},e.unblockUI=function(e){a(window,e)},e.growlUI=function(t,o,n,i){var s=e('<div class="growlUI"></div>');t&&s.append("<h1>"+t+"</h1>"),o&&s.append("<h2>"+o+"</h2>"),n===undefined&&(n=3e3);var l=function(t){t=t||{},e.blockUI({message:s,fadeIn:"undefined"!=typeof t.fadeIn?t.fadeIn:700,fadeOut:"undefined"!=typeof t.fadeOut?t.fadeOut:1e3,timeout:"undefined"!=typeof t.timeout?t.timeout:n,centerY:!1,showOverlay:!1,onUnblock:i,css:e.blockUI.defaults.growlCSS})};l();s.css("opacity");s.on("mouseover",function(){l({fadeIn:0,timeout:3e4});var t=e(".blockMsg");t.stop(),t.fadeTo(300,1)}).on("mouseout",function(){e(".blockMsg").fadeOut(1e3)})},e.fn.block=function(t){if(this[0]===window)return e.blockUI(t),this;var o=e.extend({},e.blockUI.defaults,t||{});return this.each(function(){var t=e(this);o.ignoreIfBlocked&&t.data("blockUI.isBlocked")||t.unblock({fadeOut:0})}),this.each(function(){"static"==e.css(this,"position")&&(this.style.position="relative",e(this).data("blockUI.static",!0)),this.style.zoom=1,d(this,t)})},e.fn.unblock=function(t){return this[0]===window?(e.unblockUI(t),this):this.each(function(){a(this,t)})},e.blockUI.version=2.7,e.blockUI.defaults={message:"<h1>Please wait...</h1>",title:null,draggable:!0,theme:!1,css:{padding:0,margin:0,width:"30%",top:"40%",left:"35%",textAlign:"center",color:"#000",border:"3px solid #aaa",backgroundColor:"#fff",cursor:"wait"},themedCSS:{width:"30%",top:"40%",left:"35%"},overlayCSS:{backgroundColor:"#000",opacity:.6,cursor:"wait"},cursorReset:"default",growlCSS:{width:"350px",top:"10px",left:"",right:"10px",border:"none",padding:"5px",opacity:.6,cursor:"default",color:"#fff",backgroundColor:"#000","-webkit-border-radius":"10px","-moz-border-radius":"10px","border-radius":"10px"},iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank",forceIframe:!1,baseZ:1e3,centerX:!0,centerY:!0,allowBodyStretch:!0,bindEvents:!0,constrainTabKey:!0,fadeIn:200,fadeOut:400,timeout:0,showOverlay:!0,focusInput:!0,focusableElements:":input:enabled:visible",onBlock:null,onUnblock:null,onOverlayClick:null,quirksmodeOffsetHack:4,blockMsgClass:"blockMsg",ignoreIfBlocked:!1};var s=null,l=[];function d(d,c){var u,b,h=d==window,k=c&&c.message!==undefined?c.message:undefined;if(!(c=e.extend({},e.blockUI.defaults,c||{})).ignoreIfBlocked||!e(d).data("blockUI.isBlocked")){if(c.overlayCSS=e.extend({},e.blockUI.defaults.overlayCSS,c.overlayCSS||{}),u=e.extend({},e.blockUI.defaults.css,c.css||{}),c.onOverlayClick&&(c.overlayCSS.cursor="pointer"),b=e.extend({},e.blockUI.defaults.themedCSS,c.themedCSS||{}),k=k===undefined?c.message:k,h&&s&&a(window,{fadeOut:0}),k&&"string"!=typeof k&&(k.parentNode||k.jquery)){var y=k.jquery?k[0]:k,m={};e(d).data("blockUI.history",m),m.el=y,m.parent=y.parentNode,m.display=y.style.display,m.position=y.style.position,m.parent&&m.parent.removeChild(y)}e(d).data("blockUI.onUnblock",c.onUnblock);var g,v,I,w,U=c.baseZ;g=o||c.forceIframe?e('<iframe class="blockUI" style="z-index:'+U+++';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+c.iframeSrc+'"></iframe>'):e('<div class="blockUI" style="display:none"></div>'),v=c.theme?e('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+U+++';display:none"></div>'):e('<div class="blockUI blockOverlay" style="z-index:'+U+++';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'),c.theme&&h?(w='<div class="blockUI '+c.blockMsgClass+' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(U+10)+';display:none;position:fixed">',c.title&&(w+='<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(c.title||"&nbsp;")+"</div>"),w+='<div class="ui-widget-content ui-dialog-content"></div>',w+="</div>"):c.theme?(w='<div class="blockUI '+c.blockMsgClass+' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(U+10)+';display:none;position:absolute">',c.title&&(w+='<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(c.title||"&nbsp;")+"</div>"),w+='<div class="ui-widget-content ui-dialog-content"></div>',w+="</div>"):w=h?'<div class="blockUI '+c.blockMsgClass+' blockPage" style="z-index:'+(U+10)+';display:none;position:fixed"></div>':'<div class="blockUI '+c.blockMsgClass+' blockElement" style="z-index:'+(U+10)+';display:none;position:absolute"></div>',I=e(w),k&&(c.theme?(I.css(b),I.addClass("ui-widget-content")):I.css(u)),c.theme||v.css(c.overlayCSS),v.css("position",h?"fixed":"absolute"),(o||c.forceIframe)&&g.css("opacity",0);var x=[g,v,I],C=e(h?"body":d);e.each(x,function(){this.appendTo(C)}),c.theme&&c.draggable&&e.fn.draggable&&I.draggable({handle:".ui-dialog-titlebar",cancel:"li"});var S=i&&(!e.support.boxModel||e("object,embed",h?null:d).length>0);if(n||S){if(h&&c.allowBodyStretch&&e.support.boxModel&&e("html,body").css("height","100%"),(n||!e.support.boxModel)&&!h)var E=p(d,"borderTopWidth"),O=p(d,"borderLeftWidth"),T=E?"(0 - "+E+")":0,M=O?"(0 - "+O+")":0;e.each(x,function(e,t){var o=t[0].style;if(o.position="absolute",e<2)h?o.setExpression("height","Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:"+c.quirksmodeOffsetHack+') + "px"'):o.setExpression("height",'this.parentNode.offsetHeight + "px"'),h?o.setExpression("width",'jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):o.setExpression("width",'this.parentNode.offsetWidth + "px"'),M&&o.setExpression("left",M),T&&o.setExpression("top",T);else if(c.centerY)h&&o.setExpression("top",'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'),o.marginTop=0;else if(!c.centerY&&h){var n="((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "+(c.css&&c.css.top?parseInt(c.css.top,10):0)+') + "px"';o.setExpression("top",n)}})}if(k&&(c.theme?I.find(".ui-widget-content").append(k):I.append(k),(k.jquery||k.nodeType)&&e(k).show()),(o||c.forceIframe)&&c.showOverlay&&g.show(),c.fadeIn){var B=c.onBlock?c.onBlock:t,j=c.showOverlay&&!k?B:t,H=k?B:t;c.showOverlay&&v._fadeIn(c.fadeIn,j),k&&I._fadeIn(c.fadeIn,H)}else c.showOverlay&&v.show(),k&&I.show(),c.onBlock&&c.onBlock.bind(I)();if(r(1,d,c),h?(s=I[0],l=e(c.focusableElements,s),c.focusInput&&setTimeout(f,20)):function(e,t,o){var n=e.parentNode,i=e.style,s=(n.offsetWidth-e.offsetWidth)/2-p(n,"borderLeftWidth"),l=(n.offsetHeight-e.offsetHeight)/2-p(n,"borderTopWidth");t&&(i.left=s>0?s+"px":"0");o&&(i.top=l>0?l+"px":"0")}(I[0],c.centerX,c.centerY),c.timeout){var z=setTimeout(function(){h?e.unblockUI(c):e(d).unblock(c)},c.timeout);e(d).data("blockUI.timeout",z)}}}function a(t,o){var n,i,d=t==window,a=e(t),u=a.data("blockUI.history"),f=a.data("blockUI.timeout");f&&(clearTimeout(f),a.removeData("blockUI.timeout")),o=e.extend({},e.blockUI.defaults,o||{}),r(0,t,o),null===o.onUnblock&&(o.onUnblock=a.data("blockUI.onUnblock"),a.removeData("blockUI.onUnblock")),i=d?e(document.body).children().filter(".blockUI").add("body > .blockUI"):a.find(">.blockUI"),o.cursorReset&&(i.length>1&&(i[1].style.cursor=o.cursorReset),i.length>2&&(i[2].style.cursor=o.cursorReset)),d&&(s=l=null),o.fadeOut?(n=i.length,i.stop().fadeOut(o.fadeOut,function(){0==--n&&c(i,u,o,t)})):c(i,u,o,t)}function c(t,o,n,i){var s=e(i);if(!s.data("blockUI.isBlocked")){t.each(function(e,t){this.parentNode&&this.parentNode.removeChild(this)}),o&&o.el&&(o.el.style.display=o.display,o.el.style.position=o.position,o.el.style.cursor="default",o.parent&&o.parent.appendChild(o.el),s.removeData("blockUI.history")),s.data("blockUI.static")&&s.css("position","static"),"function"==typeof n.onUnblock&&n.onUnblock(i,n);var l=e(document.body),d=l.width(),a=l[0].style.width;l.width(d-1).width(d),l[0].style.width=a}}function r(t,o,n){var i=o==window,l=e(o);if((t||(!i||s)&&(i||l.data("blockUI.isBlocked")))&&(l.data("blockUI.isBlocked",t),i&&n.bindEvents&&(!t||n.showOverlay))){var d="mousedown mouseup keydown keypress keyup touchstart touchend touchmove";t?e(document).on(d,n,u):e(document).off(d,u)}}function u(t){if("keydown"===t.type&&t.keyCode&&9==t.keyCode&&s&&t.data.constrainTabKey){var o=l,n=!t.shiftKey&&t.target===o[o.length-1],i=t.shiftKey&&t.target===o[0];if(n||i)return setTimeout(function(){f(i)},10),!1}var d=t.data,a=e(t.target);return a.hasClass("blockOverlay")&&d.onOverlayClick&&d.onOverlayClick(t),a.parents("div."+d.blockMsgClass).length>0||0===a.parents().children().filter("div.blockUI").length}function f(e){if(l){var t=l[!0===e?l.length-1:0];t&&t.trigger("focus")}}function p(t,o){return parseInt(e.css(t,o),10)||0}}"function"==typeof define&&define.amd&&define.amd.jQuery?define(["jquery"],e):e(jQuery)}();