/**
 * @package    Essentials for VirtueMart
 * @author     Abhishek Das <info@virtueplanet.com>
 * @copyright  Copyright (C) 2012-2024 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       https://www.virtueplanet.com
 */

var vme = window.vme || {};

(function(vme, document, window) {

	if (typeof Element !== 'undefined') {
		if (!Element.prototype.matches) {
			Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
		}

		if (!Element.prototype.closest) {
			Element.prototype.closest = function(s) {
				var el = this;

				do {
					if (el.matches(s)) return el;
					el = el.parentElement || el.parentNode;
				} while (el !== null && el.nodeType === 1);

				return null;
			};
		}
	}

	vme.base = '';
	vme.itemid = 0;

	vme.initAction = function(action, selector, type) {
		document.documentElement.addEventListener('click', function(e) {
			if (e.target && (e.target.matches(selector) || e.target.closest(selector))) {
				e.preventDefault();

				var form = e.target.closest('form');
				
				if (!form) {
					return false;
				}
				
				var productIdInput = form.querySelector('input[name="virtuemart_product_id"]');

				if (!productIdInput) {
					return false;
				}

				var productId = productIdInput.value;
				var data = new FormData(form);
				var request = new XMLHttpRequest();

				request.getResponseHeader('Content-type', 'application/json');

				request.onload = function() {
					var result = JSON.parse(this.responseText);

					if (!result.error) {
						if (type == 'add') {
							vme.addedAction(action, productId);
						} else {
							vme.removedAction(action, productId);
						}
					}

					if (result.msg) {
						vme.showMessage(result.msg, result.error);
					}

					var customEvent = new CustomEvent('updated.' + action, {
						details: e
					});

					document.dispatchEvent(customEvent);

					// If jQuery is available trigger old jQuery event.
					if (typeof jQuery !== 'undefined') {
						jQuery('body').trigger('updated.' + action);
					}

					var isInIframe = (window.location != window.parent.location) ? true : false;

					if (parent && isInIframe && parent.jQuery) {
						window.parent.document.dispatchEvent(customEvent);

						if (typeof jQuery !== 'undefined') {
							window.parent.jQuery('body').trigger('updated.' + action);
						}
					}
				};

				request.onerror = function(e) {
					console.log(e);
				};

				request.open('POST', vme.base + 'index.php?option=com_vmessentials&view=' + action + '&format=json', true);

				// via Cache-Control header:
				request.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');

				// fallbacks for IE and older browsers:
				request.setRequestHeader('Expires', 'Tue, 01 Jan 1980 1:00:00 GMT');
				request.setRequestHeader('Pragma', 'no-cache');

				request.send(data);

				return false;
			}
		});
	};

	vme.updateMod = function(action) {
		var containers = [].slice.call(document.querySelectorAll('.vme-mod-' + action));

		if (containers.length) {
			[].slice.call(document.querySelectorAll('.vme-mod-' + action + ' .vme-mod-loader')).forEach(function(loader) {
				loader.classList.remove('vme-hide');
				vme.fadeIn(loader, 100);
			});

			[].slice.call(document.querySelectorAll('.vme-mod-' + action + ' .vme-mod-loader-wheel')).forEach(function(wheel) {
				wheel.classList.remove('vme-hide');
				vme.fadeIn(wheel, 100);
			});

			var request = new XMLHttpRequest();

			request.getResponseHeader('Content-type', 'application/json');

			request.onload = function() {
				var data = JSON.parse(this.responseText);

				if (!data.html) {
					return false;
				}

				if (typeof data.html == 'string') {
					var parser = new DOMParser();

					data.html = parser.parseFromString(data.html, 'text/html');
				}

				if (!data.html) {
					return false;
				}

				var modContentContainer = data.html.querySelector('.vme-mod-contents');
				var html = !modContentContainer ? null : modContentContainer.innerHTML;

				if (!html) {
					html = data.html;
				}

				[].slice.call(document.querySelectorAll('.vme-mod-' + action + ' .vme-mod-contents')).forEach(function(module) {
					module.innerHTML = html;
				});
			};

			request.onerror = function(e) {
				console.log(e);
			};

			request.open('GET', vme.base + 'index.php?option=com_ajax&module=vme_' + action + '&method=get&format=json&Itemid=' + vme.itemid + '&_' + new Date().getTime(), true);

			// via Cache-Control header:
			request.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');

			// fallbacks for IE and older browsers:
			request.setRequestHeader('Expires', 'Tue, 01 Jan 1980 1:00:00 GMT');
			request.setRequestHeader('Pragma', 'no-cache');

			request.send();
		}
	};

	vme.addedAction = function(action, product_id) {
		[].slice.call(document.querySelectorAll('form.vmessentials-' + action + '-form')).forEach(function(form) {
			[].slice.call(form.querySelectorAll('input[name="virtuemart_product_id"][value="' + product_id + '"]')).forEach(function(element) {
				form.classList.add('vme-hide');
			});
		});

		[].slice.call(document.querySelectorAll('a.vme-' + action + '-link[data-vmeid="' + product_id + '"]')).forEach(function(element) {
			if (element.classList.contains('vme-hide')) {
				element.classList.remove('vme-hide');
				vme.fadeIn(element, 100);
			}
		});

		if (window.parent && window.parent.document) {
			[].slice.call(window.parent.document.querySelectorAll('form.vmessentials-' + action + '-form')).forEach(function(form) {
				[].slice.call(form.querySelectorAll('input[name="virtuemart_product_id"][value="' + product_id + '"]')).forEach(function(element) {
					form.classList.add('vme-hide');
				});
			});

			[].slice.call(window.parent.document.querySelectorAll('a.vme-' + action + '-link[data-vmeid="' + product_id + '"]')).forEach(function(element) {
				if (element.classList.contains('vme-hide')) {
					element.classList.remove('vme-hide');
					vme.fadeIn(element, 100);
				}
			});
		}
	};

	vme.removedAction = function(action, product_id) {
		[].slice.call(document.querySelectorAll('a.vme-' + action + '-link[data-vmeid="' + product_id + '"]')).forEach(function(element) {
			element.classList.add('vme-hide');
		});

		[].slice.call(document.querySelectorAll('form.vmessentials-' + action + '-form')).forEach(function(form) {
			[].slice.call(form.querySelectorAll('input[name="virtuemart_product_id"][value="' + product_id + '"]')).forEach(function(element) {
				if (form.classList.contains('vme-hide')) {
					form.classList.remove('vme-hide');
					vme.fadeIn(form, 100);
				}
			});
		});

		if (window.parent && window.parent.document) {
			[].slice.call(window.parent.document.querySelectorAll('a.vme-' + action + '-link[data-vmeid="' + product_id + '"]')).forEach(function(element) {
				element.classList.add('vme-hide');
			});

			[].slice.call(window.parent.document.querySelectorAll('form.vmessentials-' + action + '-form')).forEach(function(form) {
				[].slice.call(form.querySelectorAll('input[name="virtuemart_product_id"][value="' + product_id + '"]')).forEach(function(element) {
					if (form.classList.contains('vme-hide')) {
						form.classList.remove('vme-hide');
						vme.fadeIn(form, 100);
					}
				});
			});
		}
	};

	vme.fadeIn = function(element, time) {
		if (!element) {
			return;
		}

		element.style.opacity = 0;
		var opacity = 0;

		var intervalID = setInterval(function() {
			if (opacity < 1) {
				opacity = opacity + 0.1;
				opacity = opacity > 1 ? 1 : opacity;
				opacity = opacity < 0 ? 0 : opacity;
				element.style.opacity = opacity
			} else {
				clearInterval(intervalID);
			}
		}, time);
	};

	vme.msgTimer = null;
	vme.msgTimerOut = null;

	vme.showMessage = function(msg, error) {
		var box = document.getElementById('vme-message-box');

		if (box) {
			box.remove();
		}

		var type = !error ? 'vme-success' : 'vme-error';

		var closeBtn = document.createElement('a');

		closeBtn.href = '#';
		closeBtn.classList.add('vme-message-close');
		closeBtn.innerHTML = '&times;';

		closeBtn.removeEventListener('click', vme.onClickHideMessage);
		closeBtn.addEventListener('click', vme.onClickHideMessage);

		var content = document.createElement('div');

		content.classList.add('vme-message-content');
		content.innerHTML = msg;

		content.append(closeBtn);

		var inner = document.createElement('div');

		inner.classList.add('vme-message');
		inner.classList.add(type);

		inner.append(content);

		box = document.createElement('div');

		box.id = 'vme-message-box';
		box.classList.add('vme-fade');
		box.style.display = 'block';

		box.append(inner);
		document.body.append(box);

		if (vme.msgTimer) clearTimeout(vme.msgTimer);
		if (vme.msgTimerOut) clearTimeout(vme.msgTimerOut);

		vme.msgTimer = setTimeout(function() {
			box.classList.add('vme-in');

			vme.msgTimerOut = setTimeout(function() {
				vme.hideMessage();
			}, 3000);
		}, 50);
	};

	vme.onClickHideMessage = function(e) {
		e.preventDefault();
		vme.hideMessage();
		return false;
	};

	vme.hideTimer = null;

	vme.hideMessage = function() {
		var box = document.getElementById('vme-message-box');

		if (box) {
			if (vme.hideTimer) clearTimeout(vme.hideTimer);

			box.classList.remove('vme-in');
			
			box.addEventListener('transitionend', vme._hideMessage);
		}
	};
	
	vme._hideMessage = function() {
		var box = document.getElementById('vme-message-box');
		
		if (box) {
			box.style.display = 'none';
		}
		
		box.removeEventListener('transitionend', vme._hideMessage);
	};

	vme.loadOptions = function(id) {
		var id = typeof id === 'undefined' ? 'vme-script-options' : id;
		var element = document.getElementById(id);

		if (element) {
			var str = element.text || element.textContent;
			var options = JSON.parse(str);

			if (options) {
				[].slice.call(Object.keys(options)).forEach(function(key) {
					vme[key] = options[key];
				});
			}
		}
	};

	document.addEventListener('init.vmessentials', function() {
		vme.initAction('compare', '[data-vmecompare]', 'add');
		vme.initAction('wishlist', '[data-vmewishlist]', 'add');
		vme.initAction('compare', '[data-vmecompareremove]', 'remove');
		vme.initAction('wishlist', '[data-vmewishlistremove]', 'remove');
	});

	document.addEventListener('updated.wishlist', function() {
		vme.updateMod('wishlist');
	});

	document.addEventListener('updated.compare', function() {
		vme.updateMod('compare');
	});
	
	document.addEventListener('keydown', function(evt) {
		evt = evt || window.event;
		var isEscape = false;

		if ('key' in evt) {
			isEscape = (evt.key === 'Escape' || evt.key === 'Esc');
		} else {
			isEscape = (evt.keyCode === 27);
		}

		var isNotCombinedKey = !(evt.ctrlKey || evt.altKey || evt.shiftKey);

		if (isEscape && isNotCombinedKey) {
			vme.hideMessage();
		}
	});

	document.addEventListener('DOMContentLoaded', function(event) {
		vme.loadOptions();

		var initEvent = new CustomEvent('init.vmessentials', {
			details: event
		});

		document.dispatchEvent(initEvent);

		[].slice.call(document.querySelectorAll('.vme-quickview .addtocart-area a')).forEach(function(link) {
			link.setAttribute('target', '_top');
		});

		document.documentElement.addEventListener('click', function(e) {
			var box = document.getElementById('vme-message-box');
			var copyfields = document.querySelectorAll('[data-vmecopyfield]');
			
			if (box && e.target && box.style.display !== 'none' && !box.querySelector('.vme-message-content').contains(e.target)) {
				vme.hideMessage();
			}
			
			[].slice.call(document.querySelectorAll('[data-vmecopyfield]')).forEach(function(copyfield) {
				if (e.target && copyfield.contains(e.target)) {
					copyfield.select();
				}
			});
			
			var popover;
			
			[].slice.call(document.querySelectorAll('[data-vmepopover]')).forEach(function(popoverBtn) {
				if (e.target && popoverBtn.contains(e.target)) {
					popoverBtn.toggleAttribute('open');
				} else if (e.target && popoverBtn.hasAttribute('open')) {
					popover = popoverBtn.closest('.vme-popover-wrapper').querySelector('.vme-popover');
					
					if (!popover.contains(e.target)) {
						popoverBtn.removeAttribute('open');
					}
				}
			});
			
			var copyField, copyTimeout;
			
			[].slice.call(document.querySelectorAll('[data-vmecopy]')).forEach(function(copyBtn) {
				if (e.target && copyBtn.contains(e.target)) {
					copyField = copyBtn.closest('.vme-input-group').querySelector('[data-vmecopyfield]');
					
					if (copyField) {
						if (!navigator.clipboard) {
							copyField.focus();
							copyField.select();
							
							if (document.execCommand('copy') && copyBtn.dataset.vmedonetext) {
								copyBtn.setAttribute('disabled', 'disabled');
								
								var copyBtnHtml = copyBtn.innerHTML;
								copyBtn.innerHTML = copyBtn.dataset.vmedonetext;
								
								if (copyTimeout) {
									clearTimeout(copyTimeout);
								}
								
								copyTimeout = setTimeout(function() {
									copyBtn.innerHTML = copyBtnHtml;
									copyBtn.removeAttribute('disabled');
								}, 1000);
							}
							
							copyField.blur();
						} else {
							navigator.clipboard.writeText(copyField.getAttribute('aria-label')).then(function() {
								copyBtn.setAttribute('disabled', 'disabled');
								
								var copyBtnHtml = copyBtn.innerHTML;
								copyBtn.innerHTML = copyBtn.dataset.vmedonetext;
								
								if (copyTimeout) {
									clearTimeout(copyTimeout);
								}
								
								copyTimeout = setTimeout(function() {
									copyBtn.innerHTML = copyBtnHtml;
									copyBtn.removeAttribute('disabled');
								}, 1000);
							}, function(error) {
								copyBtn.removeAttribute('disabled');
							  console.error('Async: Could not copy text: ', error);
							});
						}
					}
				}
			});
		});

		if (typeof jQuery !== 'undefined') {
			jQuery(document).ajaxStop(function() {
				jQuery(document).trigger('init.vmessentials');
				jQuery('#fancybox-content a').attr('target', '_top');
				jQuery('#facebox .content a').attr('target', '_top');
			});

			jQuery('body').on('updateVirtueMartCartModule', function() {
				var isInIframe = (window.location != window.parent.location) ? true : false;

				if (parent && isInIframe && parent.jQuery) {
					parent.jQuery('body').trigger('updateVirtueMartCartModule');
				}
			});
		}
	});
})(vme, document, window);