/**
 *---------------------------------------------------------------------------------------
 * @package       VP Smart Template
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */
// Select Picker's Default Settings
!(function($) {
	$(document).ready(function() {
		$.fn.selectpicker.defaults = {
			noneSelectedText: Joomla.JText._("TPL_VP_SMART_SELECTPICKER_NOTHING_SELECTED"),
			noneResultsText: Joomla.JText._("TPL_VP_SMART_SELECTPICKER_NO_RESULT"),
			countSelectedText: function(numSelected, numTotal) {
				return (numSelected == 1) ? Joomla.JText._("TPL_VP_SMART_SELECTPICKER_ITEM_SELECTED") : Joomla.JText._("TPL_VP_SMART_SELECTPICKER_N_ITEMS_SELECTED");
			},
			maxOptionsText: function(numAll, numGroup) {
				var arr = [];

				arr[0] = (numAll == 1) ? Joomla.JText._("TPL_VP_SMART_SELECTPICKER_ITEM_LIMIT_REACHED") : Joomla.JText._("TPL_VP_SMART_SELECTPICKER_N_ITEMS_LIMIT_REACHED");
				arr[1] = (numGroup == 1) ? Joomla.JText._("TPL_VP_SMART_SELECTPICKER_GROUP_ITEM_LIMIT_REACHED") : Joomla.JText._("TPL_VP_SMART_SELECTPICKER_GROUP_N_ITEMS_LIMIT_REACHED");

				return arr;
			},
			selectAllText: Joomla.JText._("TPL_VP_SMART_SELECTPICKER_SELECT_ALL"),
			deselectAllText: Joomla.JText._("TPL_VP_SMART_SELECTPICKER_DESELECT_ALL"),
			multipleSeparator: Joomla.JText._("TPL_VP_SMART_SELECTPICKER_SEPARATOR")
		};
	});
}(jQuery));

// Override Chosen by Select Picker
if (typeof Virtuemart != 'undefined' && Virtuemart.updateChosenDropdownLayout == 'undefined') {
	Virtuemart.updateChosenDropdownLayout = function() {
		var $ = jQuery.noConflict();
		$('select.vm-chzn-select').each(function() {
			if ($(this).hasClass('selectpicker-active')) {
				$(this).selectpicker('refresh');
			} else {
				$(this).selectpicker();
			}
			$(this).on('liszt:updated', function() {
				$(this).selectpicker('refresh');
			});
		});
	}
}

function quickviewNavigate(url) {
	if (url) {
		url += (url.match(/\?/) ? '&' : '?') + 'tmpl=component&quickview=1&Itemid=' + VPF._('ITEMID');
		jQuery('.vm-product-quickview-frame').attr('src', url);
		jQuery('.quick-view-cont').append('<div class="iframe-loading" />');
	}
	return false;
};

function doClick(selector, button) {
	var product_id = jQuery(button).data('productid');
	jQuery(selector + '[data-productid="' + product_id + '"]').trigger('click');
};

// General Template Scripts
!(function($) {
	VPF.setIFrameHeight = function(iframe) {
		if ($(iframe).hasClass('vm-product-quickview-frame')) {
			$('.quick-view-cont').height(iframe.contentWindow.document.body.offsetHeight + 20);
			$('.quick-view-cont').find('.iframe-loading').animate({
				opacity: 0
			}, 200, 'linear', function() {
				$(this).remove();
			});
			$(window).resize(function() {
				if (iframe.contentWindow)
					$('.quick-view-cont').height(iframe.contentWindow.document.body.offsetHeight + 20);
			});
		}
		if ($(iframe).hasClass('modal-iframe')) {
			$('.modal-iframe-wrap').height(iframe.contentWindow.document.body.offsetHeight + 20);
			$('.modal-iframe-wrap').find('.iframe-loading').animate({
				opacity: 0
			}, 200, 'linear', function() {
				$(this).remove();
			});
			$(window).resize(function() {
				if (iframe.contentWindow)
					$('.modal-iframe-wrap').height(iframe.contentWindow.document.body.offsetHeight + 20);
			});
		}
	};

	VPF.showTemplateModalLogin = function(msg, loginReturn) {
		if (!VPF.modalLogin) {
			VPF.modalLogin = $('#vpf-modal-login-box');
		}
		if (!VPF.modalLogin.length) {
			return false;
		}
		if (!loginReturn) {
			loginReturn = $('input[name="return"]:hidden', VPF.modalLogin).data('value');
		}
		$('input[name="return"]:hidden', VPF.modalLogin).val(loginReturn);
		if (VPF.modalLogin.attr('aria-hidden') == 'false') {
			VPF.modalLogin.modal('hide');
		}
		if (msg) {
			$('.alert', VPF.modalLogin).text(msg).removeClass('hide');
		} else {
			$('.alert', VPF.modalLogin).text('').addClass('hide');
		}
		VPF.modalLogin.modal('show');
	};

	VPF.showVPFActivity = function() {
		if (!$('#show-activity').length) {
			$('body').append('<div id="show-activity" class="fade"></div>');
		}
		$('#show-activity').addClass('in');
	};

	VPF.stopVPFActivity = function() {
		$('#show-activity').remove();
	};

	/* Update token dynamically to avoid issues created by page cache */
	VPF.updateToken = function() {
		if (VPF._('UPDATE_TOKEN', 0)) {
			$.ajax({
				type: 'GET',
				url: VPF._('AJAXURI'),
				data: {
					'vpfmethod': 'getToken',
					'Itemid': VPF._('ITEMID')
				},
				dataType: 'json',
				cache: false,
				success: function(e) {
					if (!e.token) {
						return false;
					}
					VPF.updateOption('TOKEN', e.token);
					$('div[data-token="dynamic"]').find('input[value="1"]:hidden').attr('name', e.token);
				},
				error: function(jqXHR, textStatus, errorThrown) {
					console.log(jqXHR);
					console.log(textStatus);
					console.log(errorThrown);
				}
			});
		} else {
			if ($('div[data-token="dynamic"]').length) {
				var token = $('div[data-token="dynamic"]').find('input[value="1"]:hidden').attr('name');
				if (token) {
					VPF.updateOption('TOKEN', token);
				}
			}
		}
	};

	$(document).ready(function() {
		
		$(".navbar.navbar-offcanvas").clone().appendTo($("#footer-toolbar"));
		$("#footer-toolbar").addClass('ready');
		
		$(document).on('vpcf.update breadcrumbUpdate', function(e, html) {
			if(html) {
				var $breadCrumb = $(html).find('.breadcrumbs-cont .breadcrumbs-inner');
				if($breadCrumb.length) {
					$('.breadcrumbs-cont .breadcrumbs-inner').html($breadCrumb.html());
				}
			}
		});

		$(document).off('template.basic.initialize');
		$(document).on('template.basic.initialize', function() {

			VPF.updateToken();

			$('.hasTooltip').tooltip({
				'html': true,
				'container': 'body',
				'placement': $(this).data('placement'),
				'delay': {
					'show': 300,
					'hide': 0
				}
			});

			// On scroll animation
			function scrollAnimation() {
				$('[data-scrollanimate]').each(function(i) {
					var that = this;
					/* Check the location of each desired element and animate when element is within viewport */
					var bottom_of_object = $(that).offset().top;
					var bottom_of_window = $(window).scrollTop() + $(window).height();
					/* If the object is completely visible in the window, fade it in */
					if (bottom_of_window > bottom_of_object) {
						var animation = $(that).data('scrollanimate');
						if (animation) {
							setTimeout(function() {
								$(that).addClass(animation);
								$(that).removeAttr('data-scrollanimate');
							}, 50);
						}
					}
				});
			}
			$('[data-scrollanimate]').addClass('reveal-later');
			scrollAnimation();
			$(window).scroll(function() {
				scrollAnimation();
			});
			
			$('form[data-searchform]').on('submit', function(e) {
				if($('input.search-query', this).length && !$('input.search-query', this).val()) {
					e.preventDefault();
					return false;
				}
			});

			// Hover animation
			$('[data-hoveranimate]').hover(function() {
				var animation = $(this).data('hoveranimate');
				if (!animation) {
					return;
				}
				$(this).toggleClass(animation);
			});
			
			$('button#helpsite-refresh').wrap('<div class="input-group-btn" />');
			$('#jform_params_helpsite').addClass('form-control');
			
			// Header search
			$('.show-header-search').off('click').on('click', function(e) {
				e.preventDefault();
				$('.header-search').fadeIn(200);
				if($(window).width() < 992) {
					$('html, body').animate({
						scrollTop: 0
					}, 500);
				}
				$('.header-search input[type="search"]').focus();
				return false;
			});
			
			$('.close-header-search').off('click').on('click', function(e) {
				e.preventDefault();
				$('.header-search input[type="search"]').trigger('hide.suggesstions');
				$('.header-search').fadeOut(200);
				return false;
			});
			
			// Left module positions collapse in VM Category View
			if(!$('#main .category-view .product-item').length) {
				$('#left-aside .aside-inner').removeClass('modpos-collapse');
			}
			$('.btn-modpos-collapse').off('click').on('click', function(e) {
				e.preventDefault();
				var $target = $('#left-aside .modpos-collapse'),
						that = this;
				$target.toggleClass('show');
				$(that).toggleClass('active');

				var $list = $('.category-view .browse-view'),
				    offset = $list .data('offset') ? $list.data('offset') : 10;
						
				$('html,body').stop().animate({
					scrollTop: $('#left-aside').offset().top - offset
				}, 500);

				return false;
			});
			
			// Sidebar menu style
			$('.sidebar-menu:not(.vpf-collapsible-menu) li').each(function() {
				if ($(this).find('li.active').length) {
					$(this).removeClass('active');
				}
			});

			// Turn radios into btn-group
			$('.radio.btn-group label').addClass('btn');
			$(".btn-group label:not(.active)").click(function() {
				var label = $(this);
				var input = $('#' + label.attr('for'));
				if (!input.prop('checked')) {
					label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
					if (input.val() == '') {
						label.addClass('active btn-primary');
					} else if (input.val() == 0) {
						label.addClass('active btn-danger');
					} else {
						label.addClass('active btn-success');
					}
					input.prop('checked', true);
				}
			});
			$(".btn-group input[checked=checked]").each(function() {
				if ($(this).val() == '') {
					$("label[for=" + $(this).attr('id') + "]").addClass('active btn-primary');
				} else if ($(this).val() == 0) {
					$("label[for=" + $(this).attr('id') + "]").addClass('active btn-danger');
				} else {
					$("label[for=" + $(this).attr('id') + "]").addClass('active btn-success');
				}
			});

			$('.btn-round').each(function() {
				$(this).parent().css('display', 'inline-block');
				$(this).outerHeight($(this).outerWidth());
				$(this).parent().css('display', '');
			});

			$('input.addtocart-button-disabled').attr('type', 'button').attr('disabled', true);
			if ($('select.vm-chzn-select').length) {
				$('select.vm-chzn-select').css('width', '');
				if (typeof Virtuemart != 'undefined' && typeof Virtuemart.updateChosenDropdownLayout != 'undefined') {
					Virtuemart.updateChosenDropdownLayout();
				}
			}

			// Scroll to top
			$(window).scroll(function() {
				var scroll = $(window).scrollTop();
				if (scroll >= 122) {
					$('#header .navigation').addClass('sticky');
				} else {
					$('#header .navigation').removeClass('sticky');
				}
				if ($(this).scrollTop()) {
					$('[data-scroll="top"]').addClass('active');
					$('[data-scroll="bottom"]').addClass('inactive');
				} else {
					$('[data-scroll="top"]').removeClass('active');
					$('[data-scroll="bottom"]').removeClass('inactive');
				}
			});
			$(document).off('click touchstart', '[data-scroll="top"]').on('click', '[data-scroll="top"]', function(e) {
				e.preventDefault();
				$('html, body').animate({
					scrollTop: 0
				}, 500);
				return false;
			});
			$(document).off('click touchstart', '[data-scroll="bottom"]').on('click', '[data-scroll="bottom"]', function(e) {
				e.preventDefault();
				$('html, body').animate({
					scrollTop: $(document).height() - $(window).height()
				}, 500);
				return false;
			});

			// IFrame Modal
			var iFrameURL,
				modalTitle,
				$iframeWrap,
				$loader,
				$iframe,
				$closeButton;

			$('*[data-iframe="modal"]').off('click');
			$('*[data-iframe="modal"]').on('click', function(e) {
				e.preventDefault();
				var $that = $(this);
				iFrameURL = $(this).data('url');
				modalTitle = $(this).data('modaltitle');
				if (!iFrameURL) {
					return false;
				}
				$iframeWrap = $('<div class="modal-iframe-wrap" />');
				$loader = $('<div class="iframe-loading" />');
				$iframe = $('<iframe class="modal-iframe" height="100%" width="100%" border="0"/>').attr('src', iFrameURL);
				$closeButton = $('<button type="button" class="btn btn-modal-close"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>');
				var dialog = new BootstrapDialog({
					title: '<h4 class="modal-title">' + modalTitle + '</h4>',
					type: BootstrapDialog.TYPE_DEFAULT,
					message: function(dialogRef) {
						$closeButton.on('click', {
							dialogRef: dialogRef
						}, function(event) {
							event.data.dialogRef.close();
						});
						if (!modalTitle) {
							$iframeWrap.append($closeButton);
						}
						$iframeWrap.append($iframe);
						$iframeWrap.append($loader);
						$iframe.load(function() {
							VPF.setIFrameHeight(this);
						});
						return $iframeWrap;
					},
					closable: true,
					cssClass: 'modal-iframe-outer'
				});
				dialog.realize();
				if (!modalTitle) {
					dialog.getModalHeader().remove();
				}
				dialog.getModalFooter().remove();
				dialog.getModalDialog().css('background-color', '#FFF');
				dialog.open();

				return false;
			});

			// Quick View
			var quickProductID,
				quickCategoryID,
				params,
				$quickview,
				$loader,
				$iframe,
				$closeButton;

			$('.vpf-quickview-btn').off('click');
			$('.vpf-quickview-btn').on('click tap', function(e) {
				e.preventDefault();
				var $that = $(this);
				quickProductID = $(this).data('productid');
				quickCategoryID = $(this).data('catid');
				if (!quickProductID || !quickCategoryID) {
					return false;
				}
				params = {
					'option': 'com_virtuemart',
					'view': 'productdetails',
					'virtuemart_product_id': quickProductID,
					'virtuemart_category_id': quickCategoryID,
					'tmpl': 'component',
					'quickview': 1,
					'Itemid': VPF._('ITEMID')
				};

				$quickview = $('<div class="quick-view-cont" />');
				$loader = $('<div class="iframe-loading" />');
				$iframe = $('<iframe class="vm-product-quickview-frame" height="100%" width="100%" border="0"/>').attr('src', VPF._('URI') + '?' + $.param(params));
				$closeButton = $('<button type="button" class="btn btn-modal-close"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>');

				var dialog = new BootstrapDialog({
					message: function(dialogRef) {
						$closeButton.on('click', {
							dialogRef: dialogRef
						}, function(event) {
							event.data.dialogRef.close();
						});
						$quickview.append($closeButton);
						$quickview.append($iframe);
						$quickview.append($loader);
						$iframe.load(function() {
							VPF.setIFrameHeight(this);
						})
						return $quickview;
					},
					closable: true,
					cssClass: 'product-quickview',
				});
				dialog.realize();
				dialog.getModalHeader().remove();
				dialog.getModalFooter().remove();
				// dialog.getModalDialog().css('z-index', '145');
				dialog.open();
			});

			// Display on hover with animation
			if ($('*[ data-onhover]').length) {
				var $parentCont;

				$('*[data-onhover]').each(function() {
					var $that = $(this);
					$parentCont = $that.parents($that.data('onhover'));
					$parentCont.hoverIntent({
						interval: 40,
						sensitivity: 10,
						over: function() {
							$that.show();
							if ($that.data('animate')) {
								$that.addClass($that.data('animate'));
							}
						},
						timeout: 100,
						out: function() {
							$that.hide();
							if ($that.data('animate')) {
								$that.removeClass($that.data('animate'));
							}
						}
					});
				})
			}

			// Comparison Page style
			if ($('.product-comparison-page').length) {
				var $comparePage = $('.product-comparison-page');
				$('.product:first > div', $comparePage).each(function() {
					if ($(this).attr('class') && $(this).attr('class') != 'product-image') {
						$('.product > div.' + $(this).attr('class'), $comparePage).equalHeight({
							wait: false,
							responsive: true
						});
					}
				})
			}

			if ($('#vm-vendor-image-area').length) {
				$('input#searchMedia').css({
					'height': ''
				});
				$('.reset-value.fg-button').addClass('btn btn-default').css({
					'height': ''
				})
			}
			$('fieldset.add-shipto-set ul a').wrap('<span/>');
			$('fieldset.add-shipto-set > a').addClass('btn btn-default');
			$('input:checkbox, input:radio').removeClass('inputbox');


			$('.vp-cookie-consent-inner').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
				if ($(this).data('vpcc-anim')) $(this).removeClass($(this).data('vpcc-anim')).data('vpcc-anim', false);
			}).each(function() {
				if ($(this).data('vpcc-anim')) $(this).removeClass('reveal-later').addClass($(this).data('vpcc-anim'));
			});

			$('[data-vpcc-btn="dismiss"]').off('click').on('click', function(e) {
				e.preventDefault();
				var container = $(this).closest('.vp-cookie-consent'),
					inner = $('.vp-cookie-consent-inner', container);

				if (inner.data('vpcc-closeanim')) {
					inner.addClass(inner.data('vpcc-closeanim'));
					setTimeout(function() {
						$(container).remove();
					}, 1500);
				} else {
					setTimeout(function() {
						$(container).remove();
					}, 200);
				}

				var token = VPF._('TOKEN'),
					data = {};
				data['vpfmethod'] = 'setCookieConsent';
				data[token] = 1;

				$.ajax({
					dataType: 'JSON',
					type: 'POST',
					cache: false,
					url: VPF._('AJAXURI'),
					data: data,
					success: function(d) {
						// Success. Nothing to do.
					},
					error: function(a, b, c) {
						console.log(a);
						console.log(b);
						console.log(c);
					}
				});
				return false;
			});
		});

		$(document).trigger('template.basic.initialize');
	});

	$(window).load(function() {
		$('#editor-xtd-buttons, .toggle-editor').css({
			'padding-top': 10,
			'padding-bottom': 20
		});
		$('#editor-xtd-buttons .btn, .toggle-editor .btn').each(function() {
			if (this.className.indexOf('btn-') < 0) {
				$(this).addClass('btn-default');
			}
		});
		if ($.fn.chosen) {
			$('select.chzn-done').each(function() {
				if (!$(this).parents('.article-edit-page').length) {
					$(this).css('display', '').removeClass('chzn-done');
					$(this).siblings('[id*=_chzn]').remove();
				}

			});
		}
		if ($('.input-group .search-button-left-cont').length) {
			if ($('.input-group .search-button-left-cont ~ div.bootstrap-select').length) {
				var buttonWidth = $('.input-group .search-button-left-cont').width();
				var listWidth = $('.input-group .search-button-left-cont ~ div.bootstrap-select').width();
				console.log(listWidth);
				if (listWidth) {
					$('.input-group .search-button-left-cont').css('left', listWidth);
				}
			}
		}
		// Comparison Page Image Container Height
		if ($('.product-comparison-page').length) {
			$('.product-comparison-page .product-image').equalHeight({
				wait: false,
				responsive: true
			});
			$('.product-comparison-page .product-addtocart').equalHeight({
				wait: false,
				responsive: true
			});
		}

		// For Quick View iFrame we need to re-initialize Compare and Wishlist after Window Load
		$(document).trigger('initVPFCompare');
		$(document).trigger('initVPFWishlist');
	})
})(jQuery);

// Top Switch and Dropmod
! function($) {
	$(function() {
		if ($('.topbar-switch').length) {

			$('.topbar-switch').each(function() {
				var $that = $(this);
				$('.topbar-switch-list', this).css('min-width', $(this).outerWidth());
				$('.topbar-switch-list .select-me', this).click(function(e) {
					e.preventDefault();
					$that.find('input.topbar-switch-id').val($(this).data('id'));
					$that.find('form').submit();
				});
			});

			var config = {
				over: function() {
					$(this).addClass('over');
					$('.topbar-switch-list', this).animate({
						opacity: 1,
						height: 'toggle'
					}, 100, 'easeInOutCubic');
				},
				timeout: 0, // number = milliseconds delay before onMouseOut
				out: function() {
					var that = this;
					$('.topbar-switch-list', this).animate({
						opacity: 0,
						height: 'toggle'
					}, 100, function() {
						$(that).removeClass('over');
					});
				}
			};
			$('.topbar-switch').hoverIntent(config);
			$('.isMobile .topbar-switch').on('click tap', function() {
				if ($(this).hasClass('over')) {
					$(this).trigger('mouseout');
				} else {
					$(this).trigger('mouseover');
				}
			});
		}

		if ($('.vp-dropmod-container').length) {

			var alignment = 'right';

			var config = {
				over: function() {
					$('.vp-dropmod-container').not(this).removeClass('over');
					if ($(this).parents('[data-align="check"]').length) {
						alignment = $(this).parents('[data-align="check"]').css('text-align');
					}
					if (alignment == 'center') {
						$(this).css('position', 'static').parents('[data-align="check"]').css('position', 'relative');
					} else {
						$(this).css('position', '').parents('[data-align="check"]').css('position', '');
					}
					if (alignment) {
						$('.vp-dropmod-inner', this).removeClass('drop-center').removeClass('drop-left').removeClass('drop-right').addClass('drop-' + alignment);
					}

					var $parent = $(this).parents('.navbar-offcanvas');
					if ($parent.length && $parent.find('.navbar-toggle').is(':visible')) {
						$('.vp-dropmod-pointer', this).css('left', this.offsetLeft + 19);
					} else {
						$('.vp-dropmod-pointer', this).css('left', '');
					}
					$(this).addClass('over');
					//$('.vp-dropmod-inner', this).addClass('bounceIn aminated')
				},
				timeout: 200, // number = milliseconds delay before onMouseOut
				sensitivity: 100,
				out: function() {
					$(this).removeClass('over');
					//$('.vp-dropmod-inner', this).removeClass('bounceIn aminated')
				}
			};

			$(document).off('dropmodUpdated');
			$(document).on('dropmodUpdated', function() {
				$('.vp-dropmod-container').each(function() {
					if($(this).hasClass('over')) {
						config.over.call(this);
					}
					$('.vp-dropmod-inner', this).css('min-width', $(this).width());
					if (!$('.vp-dropmod-pointer', this).length) {
						$(this).append('<div class="vp-dropmod-pointer"/>');
					}
				});

				$('.vp-dropmod-container').hoverIntent(config);
				$(document).on('touchstart click', '.vp-dropmod-anchor > a', function(e) {
					if (!$(this).closest('#footer-toolbar').length) {
						e.preventDefault();
						return false;
					}
				});
			});

			$(document).trigger('dropmodUpdated');
			
			$(document).on('init.vmessentials', function() {
				$(document).trigger('dropmodUpdated');
			});
		}
	})
}(jQuery);

// VirtueMart Product Comparison
! function($) {
	$(function() {
		var addToComparePool = {};

		$(document).off('initVPFCompare');
		$(document).on('initVPFCompare', function() {

			if ($('.vpf-addtocompare-btn, .vpf-removefromcompare-btn').length) {

				$('.vpf-addtocompare-btn').off('click');
				$('.vpf-addtocompare-btn').on('click', function(e) {
					e.preventDefault();
					if ($(this).parents('.quickview-product').length) {
						parent.doClick('.vpf-addtocompare-btn', this);
						return false;
					}
					var $that = $(this);
					if (addToComparePool.hasOwnProperty('add') && addToComparePool['add'].readystate != 4) {
						addToComparePool['add'].abort();
					}
					addToComparePool['add'] = $.ajax({
						beforeSend: function() {
							VPF.showVPFActivity();
						},
						dataType: 'json',
						type: 'GET',
						cache: false,
						url: VPF._('AJAXURI'),
						data: {
							'vpfmethod': 'addToCompare',
							'product_id': $that.data('productid'),
							'product_name': encodeURIComponent($that.data('productname')),
							'Itemid': VPF._('ITEMID')
						},
						success: function(data, textStatus, jqXHR) {
							VPF.stopVPFActivity();
							if (data.msg) {
								if (data.error) {
									BootstrapDialog.alert({
										title: Joomla.JText._("ERROR"),
										message: data.msg,
										type: BootstrapDialog.TYPE_DANGER,
										buttonLabel: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE")
									});
								} else {
									BootstrapDialog.show({
										title: Joomla.JText._("PLG_SYSTEM_VPFRAMEWORK_ITEM_ADDED"),
										message: data.msg,
										type: BootstrapDialog.TYPE_INFO,
										cssClass: 'modal-center',
										buttons: [{
											label: Joomla.JText._("PLG_SYSTEM_VPFRAMEWORK_COMPARE"),
											cssClass: (data.url ? 'btn-base' : 'hide'),
											action: function(dialog) {
												var $button = this;
												$button.disable();
												VPF.showVPFActivity();
												//$button.spin();
												if (data.url) {
													window.location = data.url;
												}
												//dialog.setClosable(false);
											}
										}, {
											label: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE"),
											action: function(dialog) {
												dialog.close();
											}
										}]
									});
								}
								$(document).trigger('vpfcompareUpdated', [data.html]);
							}
						},
						error: function(jqXHR, textStatus, errorThrown) {
							VPF.stopVPFActivity();
							console.log(jqXHR);
							console.log(textStatus);
							console.log(errorThrown);
						}

					});

					return false;
				});

				$('.vpf-removefromcompare-btn').off('click');
				$('.vpf-removefromcompare-btn').on('click', function(e) {
					e.preventDefault();
					var $that = $(this);
					if (addToComparePool.hasOwnProperty('remove') && addToComparePool['remove'].readystate != 4) {
						addToComparePool['remove'].abort();
					}
					addToComparePool['remove'] = $.ajax({
						dataType: 'json',
						type: 'GET',
						cache: false,
						url: VPF._('AJAXURI'),
						data: {
							'vpfmethod': 'removeFromCompare',
							'product_id': $that.data('productid'),
							'product_name': encodeURIComponent($that.data('productname')),
							'ajax': '1',
							'Itemid': VPF._('ITEMID')
						},
						beforeSend: function() {
							$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').removeClass('hide');
						},
						success: function(data, textStatus, jqXHR) {
							if (data.msg) {
								if (data.error) {
									BootstrapDialog.alert({
										title: Joomla.JText._("ERROR"),
										message: data.msg,
										type: BootstrapDialog.TYPE_DANGER,
										buttonLabel: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE")
									});
								}
								$(document).trigger('vpfcompareUpdated', [data.html]);
								if (!$that.data('ajax') && data.url) {
									window.location.href = data.url;
								}
							}
						},
						error: function(jqXHR, textStatus, errorThrown) {
							$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').addClass('hide');
							console.log(textStatus);
							console.log(errorThrown);
						}

					});

					return false;
				});

			}

		});

		$(document).trigger('initVPFCompare');

		$(document).off('vpfcompareUpdated');
		$(document).on('vpfcompareUpdated', function(event) {
			if (addToComparePool.hasOwnProperty('update') && addToComparePool['update'].readystate != 4) {
				addToComparePool['update'].abort();
			}
			if (!VPF._('VP_COMPARE_MODULE_CLASS')) {
				var oClass = window.vp_compare_module_class || 'vp-compare';
				VPF.updateOption('VP_COMPARE_MODULE_CLASS', oClass);
			}

			addToComparePool['update'] = $.ajax({
				dataType: 'json',
				type: 'GET',
				cache: false,
				url: VPF._('URI'),
				data: {
					'option': 'com_ajax',
					'module': 'vp_compare',
					'method': 'get',
					'format': 'json',
					'Itemid': VPF._('ITEMID')
				},
				success: function(data, textStatus, jqXHR) {
					if (!data.html) {
						return;
					}
					if ($.type(data.html) == 'string') {
						data.html = $.parseHTML(data.html);
					}

					var html = $(data.html).find('.' + VPF._('VP_COMPARE_MODULE_CLASS') + ' .vp-dropmod-container').html();

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

					$('.' + VPF._('VP_COMPARE_MODULE_CLASS') + ' .vp-dropmod-container').html(html);

					$(document).trigger('dropmodUpdated');
					$(document).trigger('initVPFCompare');
				},
				error: function(jqXHR, textStatus, errorThrown) {
					console.log(jqXHR);
					console.log(textStatus);
					console.log(errorThrown);
				}
			});
		});
	})
}(jQuery);

// VirtueMart WishList
! function($) {
	$(function() {

		var addToWishlistPool = {};

		$(document).off('initVPFWishlist');
		$(document).on('initVPFWishlist', function() {

			if ($('.vpf-addtowishlist-btn, .vpf-removefromwishlist-btn').length) {

				$('.vpf-addtowishlist-btn').off('click');
				$('.vpf-addtowishlist-btn').on('click', function(e) {
					e.preventDefault();
					if ($(this).parents('.quickview-product').length) {
						parent.doClick('.vpf-addtowishlist-btn', this);
						return false;
					}
					var $that = $(this);
					if (addToWishlistPool.hasOwnProperty('add') && addToWishlistPool['add'].readystate != 4) {
						addToWishlistPool['add'].abort();
					}

					addToWishlistPool['add'] = $.ajax({
						beforeSend: function() {
							VPF.showVPFActivity();
						},
						dataType: 'json',
						type: 'GET',
						cache: false,
						url: VPF._('AJAXURI') + '&' + VPF._('TOKEN') + '=1',
						data: {
							'vpfmethod': 'addToWishlist',
							'product_id': $that.data('productid'),
							'product_name': encodeURIComponent($that.data('productname')),
							'Itemid': VPF._('ITEMID')
						},
						success: function(data, textStatus, jqXHR) {
							VPF.stopVPFActivity();
							if (data.msg) {
								if (data.error) {
									if (data.error == 2) {
										VPF.showTemplateModalLogin(data.msg);
									} else {
										BootstrapDialog.alert({
											title: Joomla.JText._("ERROR"),
											message: data.msg,
											type: BootstrapDialog.TYPE_DANGER,
											buttonLabel: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE")
										});
									}
								} else {
									BootstrapDialog.show({
										title: Joomla.JText._("PLG_SYSTEM_VPFRAMEWORK_ITEM_ADDED"),
										message: data.msg,
										type: BootstrapDialog.TYPE_INFO,
										cssClass: 'modal-center',
										buttons: [{
											label: Joomla.JText._("PLG_SYSTEM_VPFRAMEWORK_WISHLIST_SHOW"),
											cssClass: (data.url ? 'btn-base' : 'hide'),
											action: function(dialog) {
												var $button = this;
												$button.disable();
												VPF.showVPFActivity();
												//$button.spin();
												if (data.url) {
													window.location = data.url;
												}
												//dialog.setClosable(false);
											}
										}, {
											label: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE"),
											action: function(dialog) {
												dialog.close();
											}
										}]
									});
								}
							}
							$(document).trigger('vpfwishlistUpdated', [data.html]);
						},
						error: function(jqXHR, textStatus, errorThrown) {
							VPF.stopVPFActivity();
							console.log(textStatus);
							console.log(errorThrown);
						}
					});

					return false;
				});

				$('.vpf-removefromwishlist-btn').off('click');
				$('.vpf-removefromwishlist-btn').on('click', function(e) {
					e.preventDefault();
					var $that = $(this);
					if (addToWishlistPool.hasOwnProperty('remove') && addToWishlistPool['remove'].readystate != 4) {
						addToWishlistPool['remove'].abort();
					}
					addToWishlistPool['remove'] = $.ajax({
						dataType: 'json',
						type: 'GET',
						cache: false,
						url: VPF._('AJAXURI') + '&' + VPF._('TOKEN') + '=1',
						data: {
							'vpfmethod': 'removeFromWishlist',
							'product_id': $that.data('productid'),
							'product_name': encodeURIComponent($that.data('productname')),
							'ajax': '1',
							'Itemid': VPF._('ITEMID')
						},
						beforeSend: function() {
							$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').removeClass('hide');
						},
						success: function(data, textStatus, jqXHR) {
							if (data.msg) {
								if (data.error) {
									BootstrapDialog.alert({
										title: Joomla.JText._("ERROR"),
										message: data.msg,
										type: BootstrapDialog.TYPE_DANGER,
										buttonLabel: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE")
									});
									if (data.error == 2) {
										window.location.href = data.url;
									}
								}
								$(document).trigger('vpfwishlistUpdated', [data.html]);
								if (!$that.data('ajax') && data.url) {
									window.location.href = data.url;
								}
							}
						},
						error: function(jqXHR, textStatus, errorThrown) {
							$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').addClass('hide');
							console.log(textStatus);
							console.log(errorThrown);
						}

					});

					return false;
				});
			}

		});

		$(document).trigger('initVPFWishlist');

		$(document).off('vpfwishlistUpdated');
		$(document).on('vpfwishlistUpdated', function(event) {
			if (addToWishlistPool.hasOwnProperty('update') && addToWishlistPool['update'].readystate != 4) {
				addToWishlistPool['update'].abort();
			}
			if (!VPF._('VP_WISHLIST_MODULE_CLASS')) {
				var oClass = window.vp_wishlist_module_class || 'vp-wishlist';
				VPF.updateOption('VP_WISHLIST_MODULE_CLASS', oClass);
			}
			addToWishlistPool['update'] = $.ajax({
				dataType: 'json',
				type: 'GET',
				cache: false,
				url: VPF._('URI'),
				data: {
					'option': 'com_ajax',
					'module': 'vp_wishlist',
					'method': 'get',
					'format': 'json',
					'Itemid': VPF._('ITEMID')
				},
				success: function(data, textStatus, jqXHR) {
					if (!data.html) {
						return;
					}
					if ($.type(data.html) == 'string') {
						data.html = $.parseHTML(data.html);
					}
					var html = $(data.html).find('.' + VPF._('VP_WISHLIST_MODULE_CLASS') + ' .vp-dropmod-container').html();
					if (!html) {
						html = data.html;
					}
					$('.' + VPF._('VP_WISHLIST_MODULE_CLASS') + ' .vp-dropmod-container').html(html);

					$(document).trigger('dropmodUpdated');
					$(document).trigger('initVPFWishlist');
				},
				error: function(jqXHR, textStatus, errorThrown) {
					console.log(jqXHR);
					console.log(textStatus);
					console.log(errorThrown);
				}
			});
		});
	});
}(jQuery);

// VP Mini Cart Module Actions
;
(function($) {
	var addToCartModPool = {};

	$(document).ready(function() {

		$(document).off('initMiniCartModule');
		$(document).on('initMiniCartModule', function() {

			$('.vpf-removefromcart-btn').off('click');
			$('.vpf-removefromcart-btn').on('click', function(e) {
				e.preventDefault();
				var $that = $(this);
				if (addToCartModPool.hasOwnProperty('remove') && addToCartModPool['remove'].readystate != 4) {
					addToCartModPool['remove'].abort();
				}
				addToCartModPool['remove'] = $.ajax({
					dataType: 'json',
					type: 'GET',
					cache: false,
					url: VPF._('AJAXURI'),
					data: {
						'vpfmethod': 'removeFromCart',
						'cart_virtuemart_product_id': $that.data('productkey'),
						'product_name': encodeURIComponent($that.data('productname')),
						'ajax': 1,
						'Itemid': VPF._('ITEMID')
					},
					beforeSend: function() {
						$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').removeClass('hide');
					},
					success: function(data, textStatus, jqXHR) {
						if (data.msg) {
							if (data.error) {
								BootstrapDialog.alert({
									title: Joomla.JText._("ERROR"),
									message: data.msg,
									type: BootstrapDialog.TYPE_DANGER,
									buttonLabel: Joomla.JText._("JLIB_HTML_BEHAVIOR_CLOSE")
								});
							}
							$(document).trigger('updateVirtueMartCartModule');
							if (!$that.data('ajax') && data.url) {
								window.location.href = data.url;
							}
						}
					},
					error: function(jqXHR, textStatus, errorThrown) {
						$that.parents('.vp-dropmod-inner').find('.vp-dropmod-loader').addClass('hide');
						console.log(textStatus);
						console.log(errorThrown);
					}
				});
				return false;
			});

		});

		$(document).trigger('initMiniCartModule');

		$(document).off('updateVirtueMartCartModule');
		$(document).on('updateVirtueMartCartModule', function(event) {
			if (addToCartModPool.hasOwnProperty('update') && addToCartModPool['update'].readystate != 4) {
				addToCartModPool['update'].abort();
			}
			addToCartModPool['update'] = $.ajax({
				dataType: 'json',
				type: 'GET',
				cache: false,
				url: VPF._('URI'),
				data: {
					'option': 'com_ajax',
					'module': 'vp_mini_cart',
					'method': 'get',
					'format': 'json',
					'Itemid': VPF._('ITEMID')
				},
				success: function(data, textStatus, jqXHR) {
					if (!data.html) {
						return;
					}
					data.html = data.html.replace(/\uFEFF/g, '');
					if ($.type(data.html) == 'string') {
						data.html = $.parseHTML(data.html);
					}
					//data.html = data.html.replace(/\uFEFF/g, '');
					if (!VPF._('VP_MINICART_MODULE_CLASS')) {
						var oClass = window.vp_minicart_module_class || 'vp-minicart';
						VPF.updateOption('VP_MINICART_MODULE_CLASS', oClass);
					}
					var html = $(data.html).find('.' + VPF._('VP_MINICART_MODULE_CLASS') + ' .vp-dropmod-container').html();
					if (!html) {
						html = data.html;
					}
					$('.' + VPF._('VP_MINICART_MODULE_CLASS') + ' .vp-dropmod-container').html(html);
					$(document).trigger('initMiniCartModule');
					$(document).trigger('dropmodUpdated');
				},
				error: function(jqXHR, textStatus, errorThrown) {
					console.log(jqXHR);
					console.log(textStatus);
					console.log(errorThrown);
				}
			});
		});
	});
})(jQuery);

// VirtueMart Product Listing
! function($) {
	$(function() {

		$(document).off('vm.productlist.loaded');
		$(document).on('vm.productlist.loaded', function(event, target) {
			var $product_list = target ? $('.product-listing', target) : $('.product-listing');

			$product_list.each(function() {

				if ($(this).data('vpjs-ready')) {
					return;
				}

				var lazyLoadEnabled = $(this).hasClass('lazyload-enabled');
				var $listing = $(this);
				var $product = $('.product-item', $listing);
				var $productCont = $('.product-inner', $product);
				var resizeTimer;
				
				Virtuemart.product($('form.product', this));
				
				// If lazyload enabled
				if (lazyLoadEnabled && $('img.load-lazily', this).length) {
					if ($.fn.lazyload) {
						$('img.load-lazily', this).lazyload({
							skip_invisible: false,
							effect: 'fadeIn',
							threshold: 300,
							appear: function(elements_left, settings) {
								if (!$(this).hasClass('loaded')) {
									$(this).addClass('appeared');
									$(this).closest('.product-image-cont').addClass('lazy-image-loading').removeClass('lazy-image-loaded');
								} else {
									$(document).trigger('vm.resize.products', [$listing]);
								}
							},
							load: function(elements_left, settings) {
								$(this).removeData().removeAttr("data-" + settings.data_attribute).removeAttr('style');
								$(this).removeClass('appeared').addClass('loaded');
								$(this).closest('.product-image-cont').removeClass('lazy-image-loading').addClass('lazy-image-loaded');
								$(document).trigger('vm.resize.products', [$listing]);
							}
						});
						$(window).load(function() {
							$('html,body').trigger('scroll');
						});
					} else {
						alert('jQuery.lazyload plugin is required but not found.');
					}
				} else if (!lazyLoadEnabled) {
					$(this).waitForImages(function() {
						$(document).trigger('vm.resize.products', [$listing]);
					});
				}

				$(window).resize(function() {
					if (resizeTimer) {
						clearTimeout(resizeTimer)
					}
					resizeTimer = setTimeout(function() {
						$(document).trigger('vm.resize.products', [$listing, 10]);
					}, 200);
				});

				// Product Mouse Over Effect
				$product.hoverIntent({
					interval: 40,
					sensitivity: 10,
					timeout: 100,
					over: function() {
						var $inner = $(this).find('.product-inner');
						var orgHeight = $inner.outerHeight();
						var marginBottom = $inner.pxVal('margin-bottom');
						$inner.addClass('open').css('height', '');
						$(this).addClass('over');
						var newHeight = $inner.outerHeight();
						if (newHeight) {
							//$inner.outerHeight(newHeight).css('margin-bottom', ((newHeight - orgHeight) - marginBottom) * -1);
						}
						$('.display-on-mouseover', this).each(function() {
							if ($(this).data('animate')) {
								$(this).addClass($(this).data('animate'));
							}
						});
					},
					out: function() {
						var $inner = $(this).find('.product-inner');
						$('.display-on-mouseover', this).each(function() {
							if ($(this).data('animate')) {
								$(this).removeClass($(this).data('animate'));
							}
						});
						$inner.css({
							'margin-bottom': '',
							'height': ''
						});
						$(this).removeClass('over');
						$inner.removeClass('open');
						if (!$(this).hasClass('over') && $(this).find('.btn-showvariants').length) {
							$(this).find('.btn-showvariants').removeClass('hide');
							$(this).find('.addtocart-button, .addtocart-button-disabled, .product-cart-variants').addClass('hide');
						}
					}
				});

				// Fix VirtueMart input/button missing type attribute
				$('input', this).each(function() {
					if (!$(this).attr('type')) {
						$(this).attr('type', 'button');
					}
				});

				// Show Varients
				var $addtocartForm,
					$productInner,
					orgHeight,
					marginBottom,
					newHeight;

				$('.btn-showvariants', this).off('click');
				$('.btn-showvariants', this).on('click', function(e) {
					e.preventDefault();
					$addtocartForm = $(this).parents('form');
					$productInner = $(this).parents('.product-inner');
					orgHeight = $productInner.height();
					$('.product-cart-variants', $addtocartForm).css('opacity', 0).removeClass('hide');
					$(this).addClass('hide').siblings('.addtocart-button, .addtocart-button-disabled').removeClass('hide');
					marginBottom = $productInner.pxVal('margin-bottom');
					$productInner.css('height', '');
					newHeight = $productInner.height();
					if (newHeight > orgHeight) {
						$productInner.height(newHeight).css('margin-bottom', ((newHeight - orgHeight) - marginBottom) * -1);
					}

					$('.product-cart-variants', $addtocartForm).animate({
						'opacity': 1
					}, 200);

					return false;
				});
				
				$('.btn-hover-addtocart', this).off('click');
				$('.btn-hover-addtocart', this).on('click', function(e) {
					e.preventDefault();
					var form = $(this).closest('.product-item').find('form.js-recalculate');
					if($('a.btn-notify', form).length) {
						window.location.href = $('a.btn-notify', form).attr('href');
					} else if($('a.btn-options', form).length) {
						window.location.href = $('a.btn-options', form).attr('href');
					} else {
						$('input.btn-addtocart', form).trigger('click');
					}
					return false;
				});

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

		$(document).trigger('vm.productlist.loaded');

		var mutationCall = null;

		$(document).off('vm.category.page.loaded').on('vm.category.page.loaded', function() {
			$('.category-view').each(function() {
				if (!$('.product-listing', this).data('vpjs-ready')) {
					$(document).trigger('template.basic.initialize');
					$(document).trigger('vm.productlist.loaded', [this]);
					$('.selectpicker', this).selectpicker();
					$(document).trigger('vm.product.loaded');
					$(document).trigger('vpf.rating.updated');
					$(document).trigger('initVPFCompare');
					$(document).trigger('initVPFWishlist');
					$(document).trigger('scroll');
				}
				// Bind the new category view container
				$(this).on('DOMNodeInserted DOMNodeRemoved', function(e) {
					if (mutationCall) clearTimeout(mutationCall);
					if (e.type && e.type == 'DOMNodeRemoved') {
						mutationCall = setTimeout(function() {
							$(document).trigger('vm.category.page.loaded');
						}, 100);
					}
				});
			})
		});

		$(document).trigger('vm.category.page.loaded');
	});
}(jQuery);

// Resize product listing container
! function($) {
	$(function() {

		$(document).off('vm.resize.products');
		$(document).on('vm.resize.products', function(event, $listings, timeOut) {
			var $product, $productCont, timer, equalHeightEnabled;
			timeOut = timeOut ? timeOut : 200;
			$listings.each(function() {
				equalHeightEnabled = $(this).hasClass('equal-height');
				if (!equalHeightEnabled) {
					return false;
				}
				$product = $('.product-item', this);
				$productCont = $('.product-inner', $product);
				var resizeTimer;
				if (resizeTimer) {
					clearTimeout(resizeTimer)
				}
				resizeTimer = setTimeout(function() {
					$('.product-name-cont', $productCont).equalHeight({
						wait: false,
						responsive: false
					});
					$('.product-rating-cont:not(.display-on-mouseover)', $productCont).equalHeight({
						wait: false,
						responsive: false
					});
					$('.product-price-cont:not(.display-on-mouseover)', $productCont).equalHeight({
						wait: false,
						responsive: false
					});
					$('.product-addtocart-cont:not(.display-on-mouseover)', $productCont).equalHeight({
						wait: false,
						responsive: false
					});
					$('.product-image-cont', $productCont).equalHeight({
						wait: false,
						responsive: false
					});
					if (timer) {
						clearTimeout(timer)
					}
					timer = setTimeout(function() {
						var maxHeight = 0;
						var ownHeight, exclude;
						$productCont.css('min-height', '');
						$productCont.each(function() {
							ownHeight = $(this).height();
							exclude = 0;
							$(this).find('.display-on-mouseover:visible').each(function() {
								exclude += $(this).outerHeight();
							});
							ownHeight = (ownHeight - exclude);
							if (ownHeight > maxHeight) {
								maxHeight = ownHeight;
							}
						})
						$productCont.css('min-height', maxHeight);
					}, 100);
				}, timeOut);
			});
		});
		$(document).trigger('vm.resize.products', [$('.product-listing')]);
	});
}(jQuery);

// VirtueMart Other Listings
! function($) {
	$(function() {

		$(document).off('vm.otherlists.loaded');
		$(document).on('vm.otherlists.loaded', function() {

			$('.category-list').each(function() {
				$(this).waitForImages(function() {
					var $categoryCont = $('.category-item-inner', this);
					$('.category-image-cont', $categoryCont).equalHeight({
						wait: false,
						responsive: true
					});
					$categoryCont.equalHeight({
						wait: false,
						responsive: true
					});
				});
			});

			$('.manufacturer-list').each(function() {
				$(this).waitForImages(function() {
					var $manufacturerCont = $('.manufacturer-inner', this);
					$('.manufactuer-image-cont', $manufacturerCont).equalHeight({
						wait: false,
						responsive: true
					});
					$manufacturerCont.equalHeight({
						wait: false,
						responsive: true
					});
				});
			});

			// VirtueMart Vendor View
			$('.vendor-default-view .vendor-storename-cont').equalHeight({
				wait: false,
				responsive: true
			});
			$('.vendor-default-view .vendor-name-cont').equalHeight({
				wait: false,
				responsive: true
			});
			$('.vendor-default-view .vendor-inner').equalHeight({
				wait: false,
				responsive: true
			});

		});

		$(document).trigger('vm.otherlists.loaded');
		$(window).resize(function() {
			$('.category-item-inner').css('min-height', '');
			$(document).trigger('vm.otherlists.loaded');
		});
	});
}(jQuery);

// VirtueMart Product
! function($) {

	$(function() {

		$(document).off('vm.product.loaded');
		$(document).on('vm.product.loaded', function() {

			// For button style cart attributes
			if ($('.vpf-radio-button').length) {
				var fieldName;
				$('.vpf-radio-button input:radio').siblings('.btn-fieldvalue').removeClass('active');
				$('.vpf-radio-button input:radio:checked, .vpf-radio-button input:radio[selected="selected"]').siblings('.btn-fieldvalue').addClass('active');

				$('.vpf-radio-button input[type="radio"]').off('click').on('click', function() {
					fieldName = $(this).attr('name');
					$('.vpf-radio-button input[name="' + fieldName + '"]:radio:not(:checked)').siblings('.btn-fieldvalue').removeClass('active');
					$('.vpf-radio-button input[name="' + fieldName + '"]:radio:checked').siblings('.btn-fieldvalue').addClass('active');
				});
			}

			// For Dropdown List style cart attributes
			if ($('.vm-field-selectpicker').length) {

				$('.vm-field-selectpicker').each(function() {
					if ($(this).hasClass('dropup')) {
						$(this).selectpicker({
							style: function(e) {
								var $select = $('select#' + $(this).data('id'));
								$(this).parent().removeClasses('cvselection no-vm-bind vm-field-');
								if ($select.length) {
									var optionClass = $select.children('option[value="' + $select.val() + '"]:last').attr('class');
									if (optionClass) {
										$(this).attr('data-option-class', optionClass);
										return 'btn-default ' + optionClass;
									}
								}
								return 'btn-default';
							},
							dropupAuto: false
						});
					} else {
						$(this).selectpicker({
							style: function(e) {
								var $select = $('select#' + $(this).data('id'));
								$(this).parent().removeClasses('cvselection no-vm-bind vm-field-');
								if ($select.length) {
									var optionClass = $select.children('option[value="' + $select.val() + '"]:last').attr('class');
									if (optionClass) {
										return 'btn-default ' + optionClass;
									}
								}
								return 'btn-default';
							},
							dropupAuto: true
						});
					}
				});

				$('.vm-field-selectpicker').change(function() {
					var $btn = $('button[data-id="' + $(this).attr('id') + '"]');
					$btn.removeClassPrefix('vpf-colorfield-');
					var optionClass = $(this).children('option[value="' + $(this).val() + '"]:last').attr('class');
					if (optionClass) {
						$btn.addClass(optionClass);
					}
				});
			}
			/* To format Related Category Display */
			$('.product-related-category > a').contents().filter(function() {
				return this.nodeType == 3;
			}).wrap('<h4 class="category-name hover-invert"></h4>').end();
			$('.product-related-category > a').removeAttr('target');

			$('.show-product-reviews').off('click');
			$('.show-product-reviews').on('click', function(e) {
				e.preventDefault();
				$('.product-tabpanel a[href="#tab-reviews"]').click();
				$('html,body').animate({
					scrollTop: $('.product-tabpanel a[href="#tab-reviews"]').offset().top - 100
				}, 500);
				return false;
			});
		});

		$('body').on('updateVirtueMartProductDetail', function(event) {
			$(document).trigger('template.basic.initialize');
			$(document).trigger('vm.product.loaded');
			$(document).trigger('vpf.rating.updated');
			$(document).trigger('initVPFCompare');
			$(document).trigger('initVPFWishlist');
			if ($.fn.CloudZoom) {
				$('.vpf-zoom, .vpf-zoom-gallery').CloudZoom();
			}
			if ($.fn.simpleGallery) {
				$('.vpf-simplegallery-item').simpleGallery();
			}
			if (typeof addthis != 'undefined' && typeof addthis.layers != 'undefined' && typeof addthis.layers.refresh != 'undefined') {
				addthis.layers.refresh();
			}
		});
		$(document).trigger('vm.product.loaded');
	});

}(jQuery);

// VM Cart Page Styles
! function($) {

	$(function() {

		$(document).off('vm.cartpage.loaded');
		$(document).on('vm.cartpage.loaded', function() {

			var $STsameAsBT = $('#STsameAsBTjs');
			var $shipToContents = $('#cart-shipto-edit-link, #cart-shipto-address');

			if ($STsameAsBT.length && $shipToContents.length) {
				$STsameAsBT.change(function() {
					if ($(this).is(':checked')) {
						$shipToContents.addClass('hide');
					} else {
						$shipToContents.removeClass('hide');
					}
					$('.cart-addresses-cont .cart-address-content').equalHeight({
						wait: false,
						responsive: true
					});
				})
			}

			$('.cart-addresses-cont .cart-address-content').equalHeight({
				wait: false,
				responsive: true
			});

			$('.cart-order-done .vm-button-correct').addClass('btn btn-base');
		});

		$(document).trigger('vm.cartpage.loaded');
	});

}(jQuery);

// Modal Login and Logout
! function($) {

	$(function() {
		if (!VPF.modalLogin) {
			VPF.modalLogin = $('#vpf-modal-login-box');
		}
		if (!VPF.modalLogout) {
			VPF.modalLogout = $('#vpf-modal-logout-box');
		}
		if (!VPF.modalLogin.length && !VPF.modalLogout.length) {
			return false;
		}

		$(document).off('vpf.init.modallogin');
		$(document).on('vpf.init.modallogin', function() {
			var $logOutForm = $('form#vpf-modal-logout-form');
			var $loginLink = $('[data-modallogin="1"]');
			if ($logOutForm.length) {
				var logoutText = $('input[name="logout_text"]:hidden', $logOutForm).val();
				$loginLink.each(function() {
					if ($('.image-title', this).length) {
						$('.image-title', this).text(logoutText);
					} else {
						$(this).text(logoutText);
					}
				});
				$loginLink.off('click');
				$loginLink.on('click', function(e) {
					e.preventDefault();
					var logoutReturn = $(this).data('logoutreturn');
					$('input[name="return"]:hidden', $logOutForm).val(logoutReturn);
					$logOutForm[0].submit();
					return false;
				});
			} else {
				$loginLink.off('click');
				$loginLink.on('click', function(e) {
					e.preventDefault();
					var loginReturn = $(this).data('loginreturn');
					VPF.showTemplateModalLogin(null, loginReturn);
					return false;
				});
			}
		});

		$(document).trigger('vpf.init.modallogin');
	});

}(jQuery);