/**
 * --------------------------------------------------------------------------------------------
 * VP Custom Filter Module - Joomla! 3 Module for VirtueMart 3.0
 * --------------------------------------------------------------------------------------------
 * @package    VP Custom Filter Module
 * @author     Abhishek Das
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2. http://www.gnu.org/licenses/gpl-2.0.html
 * @link       http://www.virtueplanet.com
 * --------------------------------------------------------------------------------------------
*/
var VPCF = window.VPCF || {};

String.prototype.str_replace = function(find, replace) {
	var replaceString = this;
	for (var i = 0; i < find.length; i++) {
		replaceString = replaceString.replace(find[i], replace[i]);
	}
	return replaceString;
};

!(function($, doc, win, VPCF) {

	VPCF.ajaxPool = {};
	VPCF.listContSelector = '.category-view';
	VPCF.listSelector = '.category-view .browse-view';
	VPCF.moduleContSelector = '.vpcf-filter-module-container';
	VPCF.moduleSelector = 'div.vpcf-filter-module';
	VPCF.onLoadForm = null;
	VPCF.onLoadUrl = null;

	VPCF.number_format = function(number, decimals, decPoint, thousandsSep) {
		number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
		var n = !isFinite(+number) ? 0 : +number
		var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
		var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
		var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
		var s = ''

		var toFixedFix = function(n, prec) {
			var k = Math.pow(10, prec)
			return '' + (Math.round(n * k) / k)
				.toFixed(prec)
		}

		// @todo: for IE parseFloat(0.55).toFixed(0) = 0;
		s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
		if (s[0].length > 3) {
			s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
		}
		if ((s[1] || '').length < prec) {
			s[1] = s[1] || ''
			s[1] += new Array(prec - s[1].length + 1).join('0')
		}

		return s.join(dec)
	};

	VPCF.currency_format = function(number, decimals, decPoint, thousandsSep, symbol, style) {
		number = VPCF.number_format(number, decimals, decPoint, thousandsSep);
		if (style && $.type(style) === 'string') {
			return style.str_replace(['{number}', '{symbol}'], [number, symbol]);
		}
		return number;
	};

	VPCF.ajaxify = function(urlString, dataObject, skipBrowserState) {
		if (VPCF.ajaxPool.hasOwnProperty('ajaxify') && VPCF.ajaxPool['ajaxify'].readystate != 4) {
			VPCF.ajaxPool['ajaxify'].abort();
		}

		dataObject = dataObject ? dataObject : {};

		VPCF.ajaxPool['ajaxify'] = $.ajax({
			type: 'GET',
			dataType: 'HTML',
			url: urlString,
			data: dataObject,
			headers: {
				'Ajax-Request': 'active'
			},
			beforeSend: function() {
				$(VPCF.listContSelector + ',' + VPCF.moduleContSelector).addClass('product-filter-loading');
			},
			success: function(html) {
				$(VPCF.listContSelector + ',' + VPCF.moduleContSelector).removeClass('product-filter-loading');
				var newList = $(html).find(VPCF.listSelector),
					newModule = $(html).find(VPCF.moduleSelector),
					title = $(html).filter('title').text();
				if (newList.length && newModule.length) {
					$('.hasTooltip').tooltip('hide');
					$(VPCF.listSelector).html(newList.html());
					$(VPCF.moduleSelector).html(newModule.html());
					if (title) {
						document.title = title;
					}
					if (!skipBrowserState) {
						VPCF.updateBrowserState(this.url, html);
					}
					$(doc).trigger('vpcf.update', [html]);
					$(doc).trigger('vm.category.page.loaded');
					var offset = $(VPCF.listSelector).data('offset') ? $(VPCF.listSelector).data('offset') : 10,
						$body = $('html,body'),
						$list = $(VPCF.listSelector);
					$body.stop().animate({
						scrollTop: $list.offset().top - offset
					}, 500);
				} else {
					win.location.href = this.url;
				}
			},
			error: function(e, t, n) {
				$(VPCF.listContSelector + ',' + VPCF.moduleContSelector).removeClass('product-filter-loading');
				if (t != 'abort' && n != 'abort') {
					console.warn('Ajax error is generated executing ctask ' + ctask + '.');
					if (t == 'parsererror' && e.responseText) {
						console.log(e.responseText);
					}
					console.log(e);
					console.log(t);
					console.log(n);
				}
			}
		});
	};

	VPCF.browserStateUpdated = false;

	VPCF.updateBrowserState = function(url, html) {
		if (typeof window.onpopstate == 'undefined') return;

		try {
			win.history.pushState({
				'html': html,
				'url': url,
				'vpfc': true
			}, "", url);
			VPCF.browserStateUpdated = true;
		} catch (error) {
			win.location.href = url;
		}
	};

	VPCF.onpopstate = function(event) {
		if (VPCF.browserStateUpdated && event.state && typeof event.state.html != 'undefined' && event.state.html && typeof event.state.url != 'undefined' && event.state.url && typeof event.state.vpfc != 'undefined' && event.state.vpfc) {
			VPCF.ajaxify(event.state.url, false, true);
		} else if (VPCF.onLoadForm && VPCF.onLoadUrl && VPCF.onLoadUrl == win.location.href) {
			$(VPCF.moduleSelector).html(VPCF.onLoadForm);
			$(doc).trigger('vpfc.init');
			$(VPCF.moduleSelector).find('input[data-vpfcnone="true"][type="hidden"]').removeAttr('disabled');
			$(VPCF.moduleSelector).find('form.form-vpcf').trigger('submit');
		}
	};

	$(doc).off('vpfc.init').on('vpfc.init', function() {
		$('[data-vpfc-slider="true"]').each(function() {
			if (!$(this).data('vpfc-ready')) {
				var that = this,
					fieldset = $(that).closest('fieldset'),
					form = fieldset.closest('form'),
					amount = $('.vpfv-price-amount', fieldset),
					min_input = $('input[data-minprice="input"]', fieldset),
					max_input = $('input[data-maxprice="input"]', fieldset),
					min_price = $(that).data('minprice') ? $(that).data('minprice') : 0,
					max_price = $(that).data('maxprice') ? $(that).data('maxprice') : 0,
					currentmin = $(that).data('currentmin') ? $(that).data('currentmin') : min_price,
					currentmax = $(that).data('currentmax') ? $(that).data('currentmax') : max_price,
					decimals = $(that).data('decimals') ? $(that).data('decimals') : 0,
					decPoint = $(that).data('decimalpoint') ? $(that).data('decimalpoint') : '',
					thousandsSep = $(that).data('thousands') ? $(that).data('thousands') : '',
					symbol = $(that).data('symbol'),
					style = $(that).data('style');

				$(this).slider({
					range: true,
					min: min_price,
					max: max_price,
					values: [currentmin, currentmax],
					slide: function(event, ui) {
						var price_from = VPCF.currency_format(ui.values[0], decimals, decPoint, thousandsSep, symbol, style);
						var price_to = VPCF.currency_format(ui.values[1], decimals, decPoint, thousandsSep, symbol, style);
						$('.from', amount).text(price_from);
						$('.to', amount).text(price_to);
					},
					change: function(event, ui) {
						var minVal = (ui.values[0] == min_price && ui.values[0] != currentmin) ? 0 : ui.values[0],
							maxVal = (ui.values[1] == min_price && ui.values[1] != currentmax) ? 0 : ui.values[1];

						$(min_input).val(minVal);
						$(max_input).val(maxVal);

						if (minVal != currentmin || maxVal != currentmax) {
							$(min_input).removeAttr('disabled');
							$(max_input).removeAttr('disabled');
							$(form).submit();
						} else {
							$(min_input).attr('disabled', true);
							$(max_input).attr('disabled', true);
						}
					}
				});

				var price_from = VPCF.currency_format($(that).slider('values', 0), decimals, decPoint, thousandsSep, symbol, style);
				var price_to = VPCF.currency_format($(that).slider('values', 1), decimals, decPoint, thousandsSep, symbol, style);

				$('.from', amount).text(price_from);
				$('.to', amount).text(price_to);

				$(this).data('vpfc-ready', true);
			}
		});

		$('form.form-vpcf').each(function() {
			var form = this;

			if (!$(form).data('vpfc-ready')) {
				$('input[type="checkbox"], input[type="radio"]', form).off('change').on('change', function() {
					var $noneField = $(this).closest('fieldset').find('input[data-vpfcnone="true"][type="hidden"]'),
						name = $(this).attr('name'),
						type = $(this).attr('type');
					if ($(this).is(':checked') || (name && ($(this).closest('fieldset').find('input[type="checkbox"][name="' + name + '"]:checked').length || $(this).closest('fieldset').find('input[type="radio"][name="' + name + '"]:checked').length))) {
						if (type == 'radio') {
							$(this).closest('fieldset').find('.btn-fieldvalue').removeClass('active');
						}
						$(this).siblings('.btn-fieldvalue').addClass('active');
						$noneField.attr('disabled', true);
					} else {
						$(this).siblings('.btn-fieldvalue').removeClass('active');
						$noneField.removeAttr('disabled');
					}
					$(form).submit();
				});

				if ($(form).data('vpcfajax') && VPCF.listSelector && VPCF.moduleSelector) {

					$(form).on('submit autosubmit', function(e) {
						if ($(VPCF.listSelector).length && $(VPCF.moduleSelector).length) {
							e.preventDefault();
							var skipBrowserState = (typeof e.type != 'undefined') && (e.type == 'autosubmit') ? true : false;
							VPCF.ajaxify($(this).attr('action'), $(this).serialize(), skipBrowserState);
							return false;
						}
					});

					$(form).find('a[data-vpcfurl=true]').on('click', function(e) {
						if ($(VPCF.listSelector).length && $(VPCF.moduleSelector).length) {
							e.preventDefault();

							if ($(this).hasClass('btn-fieldvalue')) {
								if ($(this).hasClass('active')) {
									if ($(this).closest('.vpcf-checkbox-buttons').length) {
										$(this).removeClass('active');
									}
									if ($(this).closest('fieldset.vpcf-radio-buttons').length) {
										return false;
									}
								} else {
									$(this).closest('.vpcf-radio-buttons').find('.btn-fieldvalue').not(this).removeClass('active');
									$(this).addClass('active');
								}
							}

							if ($(this).closest('fieldset.vpcf-radios').length && $(this).closest('label').find('input[type="radio"]').is(':checked')) {
								return false;
							}

							VPCF.ajaxify($(this).attr('href'));
							return false;
						}
					});
				}

				$('input.vpcf-quicksearch', form).off('keyup').on('keyup', function() {
					var text = $(this).val().toLowerCase(),
						options = $(this).siblings('.vpcf-options');
					$('label, li', options).each(function() {
						var $option = $('.vpcf-option-name', this);
						if ($option.length) {
							var name = $option.text().toLowerCase();
							if (!name || name.indexOf(text) !== -1) {
								$(this).removeClass('hide');
							} else {
								$(this).addClass('hide');
							}
						}
					});
				});

				// For button style cart attributes
				if ($('.vpcf-checkbox-buttons', form).length) {
					var buttons = $('.vpcf-checkbox-buttons', form);
					$('input[type="checkbox"]', buttons).siblings('.btn-fieldvalue').removeClass('active');
					$('input[type="checkbox"]:checked', buttons).siblings('.btn-fieldvalue').addClass('active');
				}

				if ($('.vpcf-radio-buttons', form).length) {
					var buttons = $('.vpcf-radio-buttons', form);
					$('input[type="radio"]', buttons).siblings('.btn-fieldvalue').removeClass('active');
					$('input[type="radio"]:checked', buttons).siblings('.btn-fieldvalue').addClass('active');
				}

				/*
				// Use nanoScroller
				$('.vpcf-options', form).each(function() {
					var max_height = $(this).css('max-height');
					if(max_height && max_height != 'none') {
						$(this).addClass('nano').wrapInner('<div class="nano-content"></div>').nanoScroller();
					}
				}); */

				$(form).data('vpfc-ready', true);
			}
		});

		$(VPCF.listContSelector + ',' + VPCF.moduleContSelector).each(function() {
			if (!$('.vpcf-filter-loader', this).length) {
				$(this).append('<div class="vpcf-filter-loader"></div>');
				$(this).append('<div class="vpcf-filter-loader-wheel"></div>');
			}
		});
	});

	$(function() {
		$(doc).trigger('vpfc.init');

		$(doc).ajaxStop(function() {
			$(doc).trigger('vpfc.init');
		});

		VPCF.onLoadForm = $(VPCF.moduleSelector).html();
		VPCF.onLoadUrl = win.location.href;

		if ($('form.form-vpcf').data('vpcfajax') && VPCF.listSelector && VPCF.moduleSelector) {
			win.onpopstate = VPCF.onpopstate;
		}
	});

})(jQuery, document, window, VPCF);