/**
 * dynupdate.js: Dynamic update of product content for VirtueMart
 *
 * @package     VirtueMart
 * @subpackage  Javascript Library
 * @author      Max Galt, Abhishek Das
 * @copyright   Copyright (c) 2014-2018 VirtueMart Team. All rights reserved.
 * @license     http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */

var Virtuemart = window.Virtuemart || {};

Virtuemart.dynAjaxPool = {};

! function($) {
	$(function() {

		// Add to cart and other scripts may check this variable and return while
		// the content is being updated. 
		Virtuemart.isUpdatingContent = false;

		Virtuemart.updateContent = function(url, callback) {
			if (Virtuemart.isUpdatingContent) return false;
			Virtuemart.isUpdatingContent = true;
			url += url.indexOf('&') == -1 ? '?tmpl=component&format=html&dynamic=1' : '&tmpl=component&format=html&dynamic=1';
			// Ajax pool check to avoid duplicate ajax requests
			if (Virtuemart.dynAjaxPool.hasOwnProperty('updating') && Virtuemart.dynAjaxPool['updating'].readystate != 4) {
				Virtuemart.dynAjaxPool['updating'].abort();
			}
			Virtuemart.dynAjaxPool['updating'] = $.ajax({
				beforeSend: function() {
					$('.hasTooltip').tooltip('hide');
					VPF.showVPFActivity();
				},
				url: url,
				dataType: 'html',
				success: function(data) {
					// console.log(data);
					var el = $(data).find(Virtuemart.containerSelector);
					if (!el.length) el = $(data).filter(Virtuemart.containerSelector);
					if (el.length) {
						Virtuemart.container = $(Virtuemart.container);
						var $list = Virtuemart.container.closest('.product-listing');
						
						Virtuemart.container.html(el.html());
						Virtuemart.updateCartListener();
						Virtuemart.updateDynamicUpdateListeners();
						
						if($list.length) {
							$list.data('vpjs-ready', false);
							$(document).trigger('vm.category.page.loaded');
						}
						
            var title = $(data).filter('title').text();

            if(title) {
              $('head title').text(title);
            }
            
            $(document).trigger('breadcrumbUpdate', [data]);
            
						//Virtuemart.updateCartListener();
						if (typeof Virtuemart.updateImageEventListeners != 'undefined') Virtuemart.updateImageEventListeners();
						if (typeof Virtuemart.updateChosenDropdownLayout != 'undefined') Virtuemart.updateChosenDropdownLayout();
					}
					
					Virtuemart.isUpdatingContent = false;
					
					VPF.stopVPFActivity();
					
					if (callback && typeof(callback) === "function") {
						callback();
					}
				}
			});
			Virtuemart.isUpdatingContent = false;
		};

		// GALT: this method could be renamed into more general "updateEventListeners"
		// and all other VM init scripts placed in here.
		Virtuemart.updateCartListener = function() {
			Virtuemart.product($(".product"));
			$('body').trigger('updateVirtueMartProductDetail');
		};

		Virtuemart.updL = function(event) {
			event.preventDefault();
			var url = $(this).attr('href');
			Virtuemart.setBrowserNewState(url);
			Virtuemart.updateContent(url);
		};

		Virtuemart.upd = function(event) {
			event.preventDefault();
			var that = this;
			var timeOut;
			if (timeOut) {
				clearTimeout(timeOut);
			}
			timeOut = setTimeout(function() {
				var url = $(that).attr('url');
				if (typeof url === typeof undefined || url === false) {
					url = $(that).val();
				}
				if (url != null) {

					if ($(that).closest('.quickview-product').length) {
						if(typeof parent.quickviewNavigate === 'function') {
							parent.quickviewNavigate(url);
						} else {
							window.top.location.href = url;
						}
					} else {
						Virtuemart.setBrowserNewState(url);
						Virtuemart.updateContent(url);
					}
				}
			}, 100);
		};

		Virtuemart.updForm = function(event) {
			cartform = $("#checkoutForm");
			carturl = cartform.attr('action');
			if (typeof carturl === typeof undefined || carturl === false) {
				carturl = $(this).attr('url');
				// console.log('my form no action url, try attr url ',cartform);
				if (typeof carturl === typeof undefined || carturl === false) {
					carturl = 'index.php?option=com_virtuemart&view=cart';
					// console.log('my form no action url, try attr url ', carturl);
				}
			}
			urlSuf = 'tmpl=component';
			carturlcmp = carturl;
			if (carturlcmp.indexOf(urlSuf) == -1) {
				var glue = '&';
				if (carturlcmp.indexOf('&') == -1 && carturlcmp.indexOf('?') == -1) {
					glue = '?';
				}
				carturlcmp += glue + urlSuf;
			}
			// console.log('Virtuemart.updForm url', event);
			cartform.submit(function() {
				$(this).vm2front("startVmLoading");
				VPF.showVPFActivity();
				if (Virtuemart.isUpdatingContent) return false;
				Virtuemart.isUpdatingContent = true;
				// console.log('my form submit url',carturlcmp);
				$.ajax({
					type: "POST",
					url: carturlcmp,
					dataType: "html",
					data: cartform.serialize(), // serializes the form's elements.
					success: function(datas) {
						if (typeof window._klarnaCheckout !== "undefined") {
							window._klarnaCheckout(function(api) {
								api.suspend();
							});
						}
						var el = $(datas).find(Virtuemart.containerSelector);
						if (!el.length) el = $(datas).filter(Virtuemart.containerSelector);
						if (el.length) {
							Virtuemart.container = $(Virtuemart.container);
							Virtuemart.container.html(el.html());
							//Virtuemart.updateCartListener();
							//Virtuemart.updDynFormListeners();
							//Virtuemart.updateCartListener();
							if (typeof Virtuemart.updateImageEventListeners != 'undefined') Virtuemart.updateImageEventListeners();
							if (typeof Virtuemart.updateChosenDropdownLayout != 'undefined') Virtuemart.updateChosenDropdownLayout();
						}
						Virtuemart.setBrowserNewState(carturl);
						Virtuemart.isUpdatingContent = false;
						$(this).vm2front("stopVmLoading");
						VPF.stopVPFActivity();
						$(document).trigger('vm.cartpage.loaded');
						if (typeof window._klarnaCheckout !== "undefined") {
							window._klarnaCheckout(function(api) {
								// console.log(' updateSnippet suspend');
								api.resume();
							});
						}
					},
					error: function(datas) {
						alert('Error updating cart');
						Virtuemart.isUpdatingContent = false;
						$(this).vm2front("stopVmLoading");
						VPF.stopVPFActivity();
					},
					statusCode: {
						404: function() {
							Virtuemart.isUpdatingContent = false;
							$(this).vm2front("stopVmLoading");
							VPF.stopVPFActivity();
							alert("Page not found");
						}
					}
				});
				return false;
			});
		};

		Virtuemart.updFormS = function(event) {
			Virtuemart.updForm();
			$("#checkoutForm").submit();
		}

		Virtuemart.updDynFormListeners = function() {

			$('#checkoutForm').find('*[data-dynamic-update=1]').each(function(i, el) {
				var nodeName = el.nodeName;
				el = $(el);
				switch (nodeName) {
					case 'BUTTON':
						el[0].onchange = null;
						el.off('click', Virtuemart.updForm);
						el.on('click', Virtuemart.updForm);
					default:
						el[0].onchange = null;
						el.off('click', Virtuemart.updFormS);
						el.on('click', Virtuemart.updFormS);
						break;
				}
			});
		}

		Virtuemart.updateDynamicUpdateListeners = function() {
			var elements = $('*[data-dynamic-update=1]');
			elements.each(function(i, el) {
				var nodeName = el.nodeName;
				el = $(el);
				switch (nodeName) {
					case 'A':
						el[0].onclick = null;
						el.off('click', Virtuemart.updL);
						el.on('click', Virtuemart.updL);
						break;
					default:
						el[0].onchange = null;
						el.off('change', Virtuemart.upd);
						el.on('change', Virtuemart.upd);
				}
			});
		};

		Virtuemart.everPushedHistory = false;
		Virtuemart.everFiredPopstate = false;

		Virtuemart.setBrowserNewState = function(url) {
			if (typeof window.onpopstate == "undefined" || !Virtuemart.setBrowserState)
				return;
			var stateObj = {
				url: url
			}
			Virtuemart.everPushedHistory = true;
			try {
				history.pushState(stateObj, "", url);
			} catch (err) {
				// Fallback for IE
				window.location.href = url;
				return false;
			}
		};

		Virtuemart.browserStateChangeEvent = function(event) {
			// Fix. Chrome and Safari fires onpopstate event onload.
			// Also fix browsing through history when mixed with Ajax updates and
			// full updates.
			if (!Virtuemart.everPushedHistory && event.state == null && !Virtuemart.everFiredPopstate)
				return;
			Virtuemart.everFiredPopstate = true;
			var url;
			if (event.state == null) {
				url = window.location.href;
			} else {
				url = event.state.url;
			}
			Virtuemart.updateContent(url);
		};

		window.onpopstate = Virtuemart.browserStateChangeEvent;

	});
}(jQuery);