// source --> https://www.silviakelly.it/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart-variation.js?ver=1.6 
/*global wc_add_to_cart_variation_params */
( function ( $, window, document, undefined ) {
	/**
	 * VariationForm class which handles variation forms and attributes.
	 */
	var VariationForm = function ( $form ) {
		var self = this;

		self.$form = $form;
		self.$attributeFields = $form.find( '.variations select' );
		self.$singleVariation = $form.find( '.single_variation' );
		self.$singleVariationWrap = $form.find( '.single_variation_wrap' );
		self.$resetVariations = $form.find( '.reset_variations' );
		self.$resetAlert = $form.find( '.reset_variations_alert' );
		self.$product = $form.closest( '.product' );
		self.variationData = $form.data( 'product_variations' );
		self.useAjax = false === self.variationData;
		self.xhr = false;
		self.loading = true;

		// Initial state.
		self.$singleVariationWrap.show();
		self.$form.off( '.wc-variation-form' );

		// Methods.
		self.getChosenAttributes = self.getChosenAttributes.bind( self );
		self.findMatchingVariations = self.findMatchingVariations.bind( self );
		self.isMatch = self.isMatch.bind( self );
		self.toggleResetLink = self.toggleResetLink.bind( self );
		self.showNoMatchingVariationsMsg =
			self.showNoMatchingVariationsMsg.bind( self );

		// Events.
		$form.on(
			'click.wc-variation-form',
			'.reset_variations',
			{ variationForm: self },
			self.onReset
		);
		$form.on(
			'reload_product_variations',
			{ variationForm: self },
			self.onReload
		);
		$form.on( 'hide_variation', { variationForm: self }, self.onHide );
		$form.on( 'show_variation', { variationForm: self }, self.onShow );
		$form.on(
			'click',
			'.single_add_to_cart_button',
			{ variationForm: self },
			self.onAddToCart
		);
		$form.on(
			'reset_data',
			{ variationForm: self },
			self.onResetDisplayedVariation
		);
		$form.on(
			'reset_focus',
			{ variationForm: self },
			self.onResetVariationFocus
		);
		$form.on(
			'announce_reset',
			{ variationForm: self },
			self.onAnnounceReset
		);
		$form.on(
			'clear_reset_announcement',
			{ variationForm: self },
			self.onClearResetAnnouncement
		);
		$form.on( 'reset_image', { variationForm: self }, self.onResetImage );
		$form.on(
			'change.wc-variation-form',
			'.variations select',
			{ variationForm: self },
			self.onChange
		);
		$form.on(
			'found_variation.wc-variation-form',
			{ variationForm: self },
			self.onFoundVariation
		);
		$form.on(
			'check_variations.wc-variation-form',
			{ variationForm: self },
			self.onFindVariation
		);
		$form.on(
			'update_variation_values.wc-variation-form',
			{ variationForm: self },
			self.onUpdateAttributes
		);
		$form.on(
			'keydown.wc-variation-form',
			'.reset_variations',
			{ variationForm: self },
			self.onResetKeyDown
		);

		// Init after gallery.
		setTimeout( function () {
			$form.trigger( 'check_variations' );
			$form.trigger( 'wc_variation_form', self );
			self.loading = false;
		}, 100 );
	};

	/**
	 * Reset all fields.
	 */
	VariationForm.prototype.onReset = function ( event ) {
		event.preventDefault();
		event.data.variationForm.$attributeFields.val( '' ).trigger( 'change' );
		event.data.variationForm.$form.trigger( 'announce_reset' );
		event.data.variationForm.$form.trigger( 'reset_data' );
		event.data.variationForm.$form.trigger( 'reset_focus' );
	};

	/**
	 * Reload variation data from the DOM.
	 */
	VariationForm.prototype.onReload = function ( event ) {
		var form = event.data.variationForm;
		form.variationData = form.$form.data( 'product_variations' );
		form.useAjax = false === form.variationData;
		form.$form.trigger( 'check_variations' );
	};

	/**
	 * When a variation is hidden.
	 */
	VariationForm.prototype.onHide = function ( event ) {
		event.preventDefault();
		event.data.variationForm.$form
			.find( '.single_add_to_cart_button' )
			.removeClass( 'wc-variation-is-unavailable' )
			.addClass( 'disabled wc-variation-selection-needed' );
		event.data.variationForm.$form
			.find( '.woocommerce-variation-add-to-cart' )
			.removeClass( 'woocommerce-variation-add-to-cart-enabled' )
			.addClass( 'woocommerce-variation-add-to-cart-disabled' );
	};

	/**
	 * When a variation is shown.
	 */
	VariationForm.prototype.onShow = function (
		event,
		variation,
		purchasable
	) {
		event.preventDefault();
		if ( purchasable ) {
			event.data.variationForm.$form
				.find( '.single_add_to_cart_button' )
				.removeClass(
					'disabled wc-variation-selection-needed wc-variation-is-unavailable'
				);
			event.data.variationForm.$form
				.find( '.woocommerce-variation-add-to-cart' )
				.removeClass( 'woocommerce-variation-add-to-cart-disabled' )
				.addClass( 'woocommerce-variation-add-to-cart-enabled' );
		} else {
			event.data.variationForm.$form
				.find( '.single_add_to_cart_button' )
				.removeClass( 'wc-variation-selection-needed' )
				.addClass( 'disabled wc-variation-is-unavailable' );
			event.data.variationForm.$form
				.find( '.woocommerce-variation-add-to-cart' )
				.removeClass( 'woocommerce-variation-add-to-cart-enabled' )
				.addClass( 'woocommerce-variation-add-to-cart-disabled' );
		}

		// If present, the media element library needs initialized on the variation description.
		if ( wp.mediaelement ) {
			event.data.variationForm.$form
				.find( '.wp-audio-shortcode, .wp-video-shortcode' )
				.not( '.mejs-container' )
				.filter( function () {
					return ! $( this ).parent().hasClass( 'mejs-mediaelement' );
				} )
				.mediaelementplayer( wp.mediaelement.settings );
		}
	};

	/**
	 * When the cart button is pressed.
	 */
	VariationForm.prototype.onAddToCart = function ( event ) {
		if ( $( this ).is( '.disabled' ) ) {
			event.preventDefault();

			if ( $( this ).is( '.wc-variation-is-unavailable' ) ) {
				window.alert(
					wc_add_to_cart_variation_params.i18n_unavailable_text
				);
			} else if ( $( this ).is( '.wc-variation-selection-needed' ) ) {
				window.alert(
					wc_add_to_cart_variation_params.i18n_make_a_selection_text
				);
			}
		}
	};

	/**
	 * When displayed variation data is reset.
	 */
	VariationForm.prototype.onResetDisplayedVariation = function ( event ) {
		var form = event.data.variationForm;
		form.$product.find( '.product_meta' ).find( '.sku' ).wc_reset_content();
		form.$product
			.find(
				'.product_weight, .woocommerce-product-attributes-item--weight .woocommerce-product-attributes-item__value'
			)
			.wc_reset_content();
		form.$product
			.find(
				'.product_dimensions, .woocommerce-product-attributes-item--dimensions .woocommerce-product-attributes-item__value'
			)
			.wc_reset_content();
		form.$form.trigger( 'reset_image' );
		form.$singleVariation.slideUp( 200 ).trigger( 'hide_variation' );
	};

	/**
	 * Announce reset to screen readers.
	 */
	VariationForm.prototype.onAnnounceReset = function ( event ) {
		event.data.variationForm.$resetAlert.text(
			wc_add_to_cart_variation_params.i18n_reset_alert_text
		);
	};

	/**
	 * Focus variation reset
	 */
	VariationForm.prototype.onResetVariationFocus = function ( event ) {
		event.data.variationForm.$attributeFields[ 0 ].focus();
	};

	/** Clear reset announcement */
	VariationForm.prototype.onClearResetAnnouncement = function ( event ) {
		event.data.variationForm.$resetAlert.text( '' );
	};

	/**
	 * When the product image is reset.
	 */
	VariationForm.prototype.onResetImage = function ( event ) {
		event.data.variationForm.$form.wc_variations_image_update( false );
	};

	/**
	 * Looks for matching variations for current selected attributes.
	 */
	VariationForm.prototype.onFindVariation = function (
		event,
		chosenAttributes
	) {
		var form = event.data.variationForm,
			attributes =
				'undefined' !== typeof chosenAttributes
					? chosenAttributes
					: form.getChosenAttributes(),
			currentAttributes = attributes.data;

		if ( attributes.count && attributes.count === attributes.chosenCount ) {
			if ( form.useAjax ) {
				if ( form.xhr ) {
					form.xhr.abort();
				}
				form.$form.block( {
					message: null,
					overlayCSS: { background: '#fff', opacity: 0.6 },
				} );
				currentAttributes.product_id = parseInt(
					form.$form.data( 'product_id' ),
					10
				);
				currentAttributes.custom_data =
					form.$form.data( 'custom_data' );
				form.xhr = $.ajax( {
					url: wc_add_to_cart_variation_params.wc_ajax_url
						.toString()
						.replace( '%%endpoint%%', 'get_variation' ),
					type: 'POST',
					data: currentAttributes,
					success: function ( variation ) {
						if ( variation ) {
							form.$form.trigger( 'found_variation', [
								variation,
							] );
						} else {
							form.$form.trigger( 'reset_data' );
							attributes.chosenCount = 0;

							if ( ! form.loading ) {
								form.showNoMatchingVariationsMsg();
							}
						}
					},
					complete: function () {
						form.$form.unblock();
					},
				} );
			} else {
				form.$form.trigger( 'update_variation_values' );

				var matching_variations = form.findMatchingVariations(
						form.variationData,
						currentAttributes
					),
					variation = matching_variations.shift();

				if ( variation ) {
					form.$form.trigger( 'found_variation', [ variation ] );
				} else {
					form.$form.trigger( 'reset_data' );
					attributes.chosenCount = 0;

					if ( ! form.loading ) {
						form.showNoMatchingVariationsMsg();
					}
				}
			}
		} else {
			form.$form.trigger( 'update_variation_values' );
			form.$form.trigger( 'reset_data' );
		}

		// Show reset link.
		form.toggleResetLink( attributes.chosenCount > 0 );
	};

	/**
	 * Triggered when a variation has been found which matches all attributes.
	 */
	VariationForm.prototype.onFoundVariation = function ( event, variation ) {
		var form = event.data.variationForm,
			$sku = form.$product.find( '.product_meta' ).find( '.sku' ),
			$weight = form.$product.find(
				'.product_weight, .woocommerce-product-attributes-item--weight .woocommerce-product-attributes-item__value'
			),
			$dimensions = form.$product.find(
				'.product_dimensions, .woocommerce-product-attributes-item--dimensions .woocommerce-product-attributes-item__value'
			),
			$qty_input = form.$singleVariationWrap.find(
				'.quantity input.qty[name="quantity"]'
			),
			$qty = $qty_input.closest( '.quantity' ),
			purchasable = true,
			variation_id = '',
			template = false,
			$template_html = '';

		if ( variation.sku ) {
			$sku.wc_set_content( variation.sku );
		} else {
			$sku.wc_reset_content();
		}

		if ( variation.weight ) {
			$weight.wc_set_content( variation.weight_html );
		} else {
			$weight.wc_reset_content();
		}

		if ( variation.dimensions ) {
			// Decode HTML entities.
			$dimensions.wc_set_content(
				$.parseHTML( variation.dimensions_html )[ 0 ].data
			);
		} else {
			$dimensions.wc_reset_content();
		}

		form.$form.wc_variations_image_update( variation );

		if ( ! variation.variation_is_visible ) {
			template = wp_template( 'unavailable-variation-template' );
		} else {
			template = wp_template( 'variation-template' );
			variation_id = variation.variation_id;
		}

		$template_html = template( {
			variation: variation,
		} );
		$template_html = $template_html.replace( '/*<![CDATA[*/', '' );
		$template_html = $template_html.replace( '/*]]>*/', '' );

		form.$form
			.find( 'input[name="variation_id"], input.variation_id' )
			.val( variation.variation_id )
			.trigger( 'change' );

		// Hide or show qty input
		if ( variation.is_sold_individually === 'yes' ) {
			$qty_input
				.val( '1' )
				.attr( 'min', '1' )
				.attr( 'max', '' )
				.trigger( 'change' );
			$qty.hide();
		} else {
			var qty_val = parseFloat( $qty_input.val() );

			if ( isNaN( qty_val ) ) {
				qty_val = variation.min_qty;
			} else {
				qty_val =
					qty_val > parseFloat( variation.max_qty )
						? variation.max_qty
						: qty_val;
				qty_val =
					qty_val < parseFloat( variation.min_qty )
						? variation.min_qty
						: qty_val;
			}

			$qty_input
				.attr( 'min', variation.min_qty )
				.attr( 'max', variation.max_qty )
				.val( qty_val )
				.trigger( 'change' );
			$qty.show();
		}

		// Enable or disable the add to cart button
		if (
			! variation.is_purchasable ||
			! variation.is_in_stock ||
			! variation.variation_is_visible
		) {
			purchasable = false;
		}

		// Add a delay before updating the live region to ensure screen readers pick up the content changes.
		setTimeout( function () {
			form.$singleVariation.html( $template_html );

			// Reveal
			if ( form.$singleVariation.text().trim() ) {
				form.$singleVariation
					.slideDown( 200 )
					.trigger( 'show_variation', [ variation, purchasable ] );
			} else {
				form.$singleVariation
					.show()
					.trigger( 'show_variation', [ variation, purchasable ] );
			}
		}, 300 );
	};

	/**
	 * Triggered when an attribute field changes.
	 */
	VariationForm.prototype.onChange = function ( event ) {
		var form = event.data.variationForm;

		form.$form
			.find( 'input[name="variation_id"], input.variation_id' )
			.val( '' )
			.trigger( 'change' );
		form.$form.trigger( 'clear_reset_announcement' );
		form.$form.find( '.wc-no-matching-variations' ).parent().remove();

		if ( form.useAjax ) {
			form.$form.trigger( 'check_variations' );
		} else {
			form.$form.trigger( 'woocommerce_variation_select_change' );
			form.$form.trigger( 'check_variations' );
		}

		// Custom event for when variation selection has been changed
		form.$form.trigger( 'woocommerce_variation_has_changed' );
	};

	/**
	 * Escape quotes in a string.
	 * @param {string} string
	 * @return {string}
	 */
	VariationForm.prototype.addSlashes = function ( string ) {
		string = string.replace( /'/g, "\\'" );
		string = string.replace( /"/g, '\\"' );
		return string;
	};

	/**
	 * Updates attributes in the DOM to show valid values.
	 */
	VariationForm.prototype.onUpdateAttributes = function ( event ) {
		var form = event.data.variationForm,
			attributes = form.getChosenAttributes(),
			currentAttributes = attributes.data;

		if ( form.useAjax ) {
			return;
		}

		// Loop through selects and disable/enable options based on selections.
		form.$attributeFields.each( function ( index, el ) {
			var current_attr_select = $( el ),
				current_attr_name =
					current_attr_select.data( 'attribute_name' ) ||
					current_attr_select.attr( 'name' ),
				show_option_none = $( el ).data( 'show_option_none' ),
				option_gt_filter = ':gt(0)',
				attached_options_count = 0,
				new_attr_select = $( '<select/>' ),
				selected_attr_val = current_attr_select.val() || '',
				selected_attr_val_valid = true;

			// Reference options set at first.
			if ( ! current_attr_select.data( 'attribute_html' ) ) {
				var refSelect = current_attr_select.clone();

				refSelect
					.find( 'option' )
					.removeAttr( 'attached' )
					.prop( 'disabled', false )
					.prop( 'selected', false );

				// Legacy data attribute.
				current_attr_select.data(
					'attribute_options',
					refSelect.find( 'option' + option_gt_filter ).get()
				);
				current_attr_select.data( 'attribute_html', refSelect.html() );
			}

			new_attr_select.html(
				current_attr_select.data( 'attribute_html' )
			);

			// The attribute of this select field should not be taken into account when calculating its matching variations:
			// The constraints of this attribute are shaped by the values of the other attributes.
			var checkAttributes = $.extend( true, {}, currentAttributes );

			checkAttributes[ current_attr_name ] = '';

			var variations = form.findMatchingVariations(
				form.variationData,
				checkAttributes
			);

			// Loop through variations.
			for ( var num in variations ) {
				if ( typeof variations[ num ] !== 'undefined' ) {
					var variationAttributes = variations[ num ].attributes;

					for ( var attr_name in variationAttributes ) {
						if ( variationAttributes.hasOwnProperty( attr_name ) ) {
							var attr_val = variationAttributes[ attr_name ],
								variation_active = '';

							if ( attr_name === current_attr_name ) {
								if ( variations[ num ].variation_is_active ) {
									variation_active = 'enabled';
								}

								if ( attr_val ) {
									// Decode entities.
									attr_val = $( '<div/>' )
										.html( attr_val )
										.text();

									// Attach to matching options by value. This is done to compare
									// TEXT values rather than any HTML entities.
									var $option_elements =
										new_attr_select.find( 'option' );
									if ( $option_elements.length ) {
										for (
											var i = 0,
												len = $option_elements.length;
											i < len;
											i++
										) {
											var $option_element = $(
													$option_elements[ i ]
												),
												option_value =
													$option_element.val();

											if ( attr_val === option_value ) {
												$option_element.addClass(
													'attached ' +
														variation_active
												);
												break;
											}
										}
									}
								} else {
									// Attach all apart from placeholder.
									new_attr_select
										.find( 'option:gt(0)' )
										.addClass(
											'attached ' + variation_active
										);
								}
							}
						}
					}
				}
			}

			// Count available options.
			attached_options_count =
				new_attr_select.find( 'option.attached' ).length;

			// Check if current selection is in attached options.
			if ( selected_attr_val ) {
				selected_attr_val_valid = false;

				if ( 0 !== attached_options_count ) {
					new_attr_select
						.find( 'option.attached.enabled' )
						.each( function () {
							var option_value = $( this ).val();

							if ( selected_attr_val === option_value ) {
								selected_attr_val_valid = true;
								return false; // break.
							}
						} );
				}
			}

			// Detach the placeholder if:
			// - Valid options exist.
			// - The current selection is non-empty.
			// - The current selection is valid.
			// - Placeholders are not set to be permanently visible.
			if (
				attached_options_count > 0 &&
				selected_attr_val &&
				selected_attr_val_valid &&
				'no' === show_option_none
			) {
				new_attr_select.find( 'option:first' ).remove();
				option_gt_filter = '';
			}

			// Detach unattached.
			new_attr_select
				.find( 'option' + option_gt_filter + ':not(.attached)' )
				.remove();

			// Finally, copy to DOM and set value.
			current_attr_select.html( new_attr_select.html() );
			current_attr_select
				.find( 'option' + option_gt_filter + ':not(.enabled)' )
				.prop( 'disabled', true );

			// Choose selected value.
			if ( selected_attr_val ) {
				// If the previously selected value is no longer available, fall back to the placeholder (it's going to be there).
				if ( selected_attr_val_valid ) {
					current_attr_select.val( selected_attr_val );
				} else {
					current_attr_select.val( '' ).trigger( 'change' );
				}
			} else {
				current_attr_select.val( '' ); // No change event to prevent infinite loop.
			}
		} );

		// Custom event for when variations have been updated.
		form.$form.trigger( 'woocommerce_update_variation_values' );
	};

	/**
	 * Get chosen attributes from form.
	 * @return array
	 */
	VariationForm.prototype.getChosenAttributes = function () {
		var data = {};
		var count = 0;
		var chosen = 0;

		this.$attributeFields.each( function () {
			var attribute_name =
				$( this ).data( 'attribute_name' ) || $( this ).attr( 'name' );
			var value = $( this ).val() || '';

			if ( value.length > 0 ) {
				chosen++;
			}

			count++;
			data[ attribute_name ] = value;
		} );

		return {
			count: count,
			chosenCount: chosen,
			data: data,
		};
	};

	/**
	 * Find matching variations for attributes.
	 */
	VariationForm.prototype.findMatchingVariations = function (
		variations,
		attributes
	) {
		var matching = [];
		for ( var i = 0; i < variations.length; i++ ) {
			var variation = variations[ i ];

			if ( this.isMatch( variation.attributes, attributes ) ) {
				matching.push( variation );
			}
		}
		return matching;
	};

	/**
	 * See if attributes match.
	 * @return {Boolean}
	 */
	VariationForm.prototype.isMatch = function (
		variation_attributes,
		attributes
	) {
		var match = true;
		for ( var attr_name in variation_attributes ) {
			if ( variation_attributes.hasOwnProperty( attr_name ) ) {
				var val1 = variation_attributes[ attr_name ];
				var val2 = attributes[ attr_name ];
				if (
					val1 !== undefined &&
					val2 !== undefined &&
					val1.length !== 0 &&
					val2.length !== 0 &&
					val1 !== val2
				) {
					match = false;
				}
			}
		}
		return match;
	};

	/**
	 * Show or hide the reset link.
	 */
	VariationForm.prototype.toggleResetLink = function ( on ) {
		if ( on ) {
			if ( this.$resetVariations.css( 'visibility' ) === 'hidden' ) {
				this.$resetVariations
					.css( 'visibility', 'visible' )
					.hide()
					.fadeIn();
			}
		} else {
			this.$resetVariations.css( 'visibility', 'hidden' );
		}
	};

	/**
	 * Show no matching variation message.
	 */
	VariationForm.prototype.showNoMatchingVariationsMsg = function () {
		this.$form
			.find( '.single_variation' )
			.after(
				'<div role="alert">' +
					'<p class="wc-no-matching-variations woocommerce-info">' +
					wc_add_to_cart_variation_params.i18n_no_matching_variations_text +
					'</p>' +
					'</div>'
			)
			.next( 'div' )
			.find( '.wc-no-matching-variations' )
			.slideDown( 200 );
	};

	/**
	 * Handle reset key down event for accessibility.
	 * @param {KeyboardEvent} event - The keyboard event object
	 */
	VariationForm.prototype.onResetKeyDown = function ( event ) {
		if ( event.code === 'Enter' || event.code === 'Space' ) {
			event.preventDefault();
			event.data.variationForm.onReset( event );
		}
	};

	/**
	 * Function to call wc_variation_form on jquery selector.
	 */
	$.fn.wc_variation_form = function () {
		new VariationForm( this );
		return this;
	};

	/**
	 * Stores the default text for an element so it can be reset later
	 */
	$.fn.wc_set_content = function ( content ) {
		if ( undefined === this.attr( 'data-o_content' ) ) {
			this.attr( 'data-o_content', this.text() );
		}
		this.text( content );
	};

	/**
	 * Stores the default text for an element so it can be reset later
	 */
	$.fn.wc_reset_content = function () {
		if ( undefined !== this.attr( 'data-o_content' ) ) {
			this.text( this.attr( 'data-o_content' ) );
		}
	};

	/**
	 * Stores a default attribute for an element so it can be reset later
	 */
	$.fn.wc_set_variation_attr = function ( attr, value ) {
		if ( undefined === this.attr( 'data-o_' + attr ) ) {
			this.attr(
				'data-o_' + attr,
				! this.attr( attr ) ? '' : this.attr( attr )
			);
		}
		if ( false === value ) {
			this.removeAttr( attr );
		} else {
			this.attr( attr, value );
		}
	};

	/**
	 * Reset a default attribute for an element so it can be reset later
	 */
	$.fn.wc_reset_variation_attr = function ( attr ) {
		if ( undefined !== this.attr( 'data-o_' + attr ) ) {
			this.attr( attr, this.attr( 'data-o_' + attr ) );
		}
	};

	/**
	 * Reset the slide position if the variation has a different image than the current one
	 */
	$.fn.wc_maybe_trigger_slide_position_reset = function ( variation ) {
		var $form = $( this ),
			$product = $form.closest( '.product' ),
			$product_gallery = $product.find( '.images' ),
			reset_slide_position = false,
			new_image_id =
				variation && variation.image_id ? variation.image_id : '';

		if ( $form.attr( 'current-image' ) !== new_image_id ) {
			reset_slide_position = true;
		}

		$form.attr( 'current-image', new_image_id );

		if ( reset_slide_position ) {
			$product_gallery.trigger(
				'woocommerce_gallery_reset_slide_position'
			);
		}
	};

	/**
	 * Sets product images for the chosen variation
	 */
	$.fn.wc_variations_image_update = function ( variation ) {
		var $form = this,
			$product = $form.closest( '.product' ),
			$product_gallery = $product.find( '.images' ),
			$gallery_nav = $product.find( '.flex-control-nav' ),
			$gallery_img = $gallery_nav.find( 'li:eq(0) img' ),
			$product_img_wrap = $product_gallery
				.find(
					'.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder'
				)
				.eq( 0 ),
			$product_img = $product_img_wrap.find( '.wp-post-image' ),
			$product_link = $product_img_wrap.find( 'a' ).eq( 0 );

		if (
			variation &&
			variation.image &&
			variation.image.src &&
			variation.image.src.length > 1
		) {
			// See if the gallery has an image with the same original src as the image we want to switch to.
			var galleryHasImage =
				$gallery_nav.find(
					'li img[data-o_src="' +
						variation.image.gallery_thumbnail_src +
						'"]'
				).length > 0;

			// If the gallery has the image, reset the images. We'll scroll to the correct one.
			if ( galleryHasImage ) {
				$form.wc_variations_image_reset();
			}

			// See if gallery has a matching image we can slide to.
			var slideToImage = $gallery_nav.find(
				'li img[src="' + variation.image.gallery_thumbnail_src + '"]'
			);

			if ( slideToImage.length > 0 ) {
				slideToImage.trigger( 'flexslider-click' );
				$form.attr( 'current-image', variation.image_id );
				window.setTimeout( function () {
					$( window ).trigger( 'resize' );
					$product_gallery.trigger( 'woocommerce_gallery_init_zoom' );
				}, 20 );
				return;
			}

			$product_img.wc_set_variation_attr( 'src', variation.image.src );
			$product_img.wc_set_variation_attr(
				'height',
				variation.image.src_h
			);
			$product_img.wc_set_variation_attr(
				'width',
				variation.image.src_w
			);
			$product_img.wc_set_variation_attr(
				'srcset',
				variation.image.srcset
			);
			$product_img.wc_set_variation_attr(
				'sizes',
				variation.image.sizes
			);
			$product_img.wc_set_variation_attr(
				'title',
				variation.image.title
			);
			$product_img.wc_set_variation_attr(
				'data-caption',
				variation.image.caption
			);
			$product_img.wc_set_variation_attr( 'alt', variation.image.alt );
			$product_img.wc_set_variation_attr(
				'data-src',
				variation.image.full_src
			);
			$product_img.wc_set_variation_attr(
				'data-large_image',
				variation.image.full_src
			);
			$product_img.wc_set_variation_attr(
				'data-large_image_width',
				variation.image.full_src_w
			);
			$product_img.wc_set_variation_attr(
				'data-large_image_height',
				variation.image.full_src_h
			);
			$product_img_wrap.wc_set_variation_attr(
				'data-thumb',
				variation.image.src
			);
			$gallery_img.wc_set_variation_attr(
				'src',
				variation.image.gallery_thumbnail_src
			);
			$product_link.wc_set_variation_attr(
				'href',
				variation.image.full_src
			);
		} else {
			$form.wc_variations_image_reset();
		}

		window.setTimeout( function () {
			$( window ).trigger( 'resize' );
			$form.wc_maybe_trigger_slide_position_reset( variation );
			$product_gallery.trigger( 'woocommerce_gallery_init_zoom' );
		}, 20 );
	};

	/**
	 * Reset main image to defaults.
	 */
	$.fn.wc_variations_image_reset = function () {
		var $form = this,
			$product = $form.closest( '.product' ),
			$product_gallery = $product.find( '.images' ),
			$gallery_nav = $product.find( '.flex-control-nav' ),
			$gallery_img = $gallery_nav.find( 'li:eq(0) img' ),
			$product_img_wrap = $product_gallery
				.find(
					'.woocommerce-product-gallery__image, .woocommerce-product-gallery__image--placeholder'
				)
				.eq( 0 ),
			$product_img = $product_img_wrap.find( '.wp-post-image' ),
			$product_link = $product_img_wrap.find( 'a' ).eq( 0 );

		$product_img.wc_reset_variation_attr( 'src' );
		$product_img.wc_reset_variation_attr( 'width' );
		$product_img.wc_reset_variation_attr( 'height' );
		$product_img.wc_reset_variation_attr( 'srcset' );
		$product_img.wc_reset_variation_attr( 'sizes' );
		$product_img.wc_reset_variation_attr( 'title' );
		$product_img.wc_reset_variation_attr( 'data-caption' );
		$product_img.wc_reset_variation_attr( 'alt' );
		$product_img.wc_reset_variation_attr( 'data-src' );
		$product_img.wc_reset_variation_attr( 'data-large_image' );
		$product_img.wc_reset_variation_attr( 'data-large_image_width' );
		$product_img.wc_reset_variation_attr( 'data-large_image_height' );
		$product_img_wrap.wc_reset_variation_attr( 'data-thumb' );
		$gallery_img.wc_reset_variation_attr( 'src' );
		$product_link.wc_reset_variation_attr( 'href' );
	};

	$( function () {
		if ( typeof wc_add_to_cart_variation_params !== 'undefined' ) {
			$( '.variations_form' ).each( function () {
				$( this ).wc_variation_form();
			} );
		}
	} );

	/**
	 * Matches inline variation objects to chosen attributes
	 * @deprecated 2.6.9
	 * @type {Object}
	 */
	var wc_variation_form_matcher = {
		find_matching_variations: function ( product_variations, settings ) {
			var matching = [];
			for ( var i = 0; i < product_variations.length; i++ ) {
				var variation = product_variations[ i ];

				if (
					wc_variation_form_matcher.variations_match(
						variation.attributes,
						settings
					)
				) {
					matching.push( variation );
				}
			}
			return matching;
		},
		variations_match: function ( attrs1, attrs2 ) {
			var match = true;
			for ( var attr_name in attrs1 ) {
				if ( attrs1.hasOwnProperty( attr_name ) ) {
					var val1 = attrs1[ attr_name ];
					var val2 = attrs2[ attr_name ];
					if (
						val1 !== undefined &&
						val2 !== undefined &&
						val1.length !== 0 &&
						val2.length !== 0 &&
						val1 !== val2
					) {
						match = false;
					}
				}
			}
			return match;
		},
	};

	/**
	 * Avoids using wp.template where possible in order to be CSP compliant.
	 * wp.template uses internally eval().
	 * @param {string} templateId
	 * @return {Function}
	 */
	var wp_template = function ( templateId ) {
		var html = document.getElementById( 'tmpl-' + templateId ).textContent;
		var hard = false;
		// any <# #> interpolate (evaluate).
		hard = hard || /<#\s?data\./.test( html );
		// any data that is NOT data.variation.
		hard = hard || /{{{?\s?data\.(?!variation\.).+}}}?/.test( html );
		// any data access deeper than 1 level e.g.
		// data.variation.object.item
		// data.variation.object['item']
		// data.variation.array[0]
		hard = hard || /{{{?\s?data\.variation\.[\w-]*[^\s}]/.test( html );
		if ( hard ) {
			return wp.template( templateId );
		}
		return function template( data ) {
			var variation = data.variation || {};
			return html.replace(
				/({{{?)\s?data\.variation\.([\w-]*)\s?(}}}?)/g,
				function ( _, open, key, close ) {
					// Error in the format, ignore.
					if ( open.length !== close.length ) {
						return '';
					}
					var replacement = variation[ key ] || '';
					// {{{ }}} => interpolate (unescaped).
					// {{  }}  => interpolate (escaped).
					// https://codex.wordpress.org/Javascript_Reference/wp.template
					if ( open.length === 2 ) {
						return window.escape( replacement );
					}
					return replacement;
				}
			);
		};
	};
} )( jQuery, window, document );
// source --> https://www.silviakelly.it/wp-content/plugins/woo-product-grid-list-design/js/isotope.js?ver=1.0.8 
/*!
 * Isotope PACKAGED v3.0.2
 *
 * Licensed GPLv3 for open source use
 * or Isotope Commercial License for commercial use
 *
 * http://isotope.metafizzy.co
 * Copyright 2016 Metafizzy
 */

!function(t, e){"function" == typeof define && define.amd?define("jquery-bridget/jquery-bridget", ["jquery"], function(i){return e(t, i)}):"object" == typeof module && module.exports?module.exports = e(t, require("jquery")):t.jQueryBridget = e(t, t.jQuery)}(window, function(t, e){"use strict"; function i(i, s, a){function u(t, e, n){var o, s = "$()." + i + '("' + e + '")'; return t.each(function(t, u){var h = a.data(u, i); if (!h)return void r(i + " not initialized. Cannot call methods, i.e. " + s); var d = h[e]; if (!d || "_" == e.charAt(0))return void r(s + " is not a valid method"); var l = d.apply(h, n); o = void 0 === o?l:o}), void 0 !== o?o:t}function h(t, e){t.each(function(t, n){var o = a.data(n, i); o?(o.option(e), o._init()):(o = new s(n, e), a.data(n, i, o))})}a = a || e || t.jQuery, a && (s.prototype.option || (s.prototype.option = function(t){a.isPlainObject(t) && (this.options = a.extend(!0, this.options, t))}), a.fn[i] = function(t){if ("string" == typeof t){var e = o.call(arguments, 1); return u(this, t, e)}return h(this, t), this}, n(a))}function n(t){!t || t && t.bridget || (t.bridget = i)}var o = Array.prototype.slice, s = t.console, r = "undefined" == typeof s?function(){}:function(t){s.error(t)}; return n(e || t.jQuery), i}), function(t, e){"function" == typeof define && define.amd?define("ev-emitter/ev-emitter", e):"object" == typeof module && module.exports?module.exports = e():t.EvEmitter = e()}("undefined" != typeof window?window:this, function(){function t(){}var e = t.prototype; return e.on = function(t, e){if (t && e){var i = this._events = this._events || {}, n = i[t] = i[t] || []; return n.indexOf(e) == - 1 && n.push(e), this}}, e.once = function(t, e){if (t && e){this.on(t, e); var i = this._onceEvents = this._onceEvents || {}, n = i[t] = i[t] || {}; return n[e] = !0, this}}, e.off = function(t, e){var i = this._events && this._events[t]; if (i && i.length){var n = i.indexOf(e); return n != - 1 && i.splice(n, 1), this}}, e.emitEvent = function(t, e){var i = this._events && this._events[t]; if (i && i.length){var n = 0, o = i[n]; e = e || []; for (var s = this._onceEvents && this._onceEvents[t]; o; ){var r = s && s[o]; r && (this.off(t, o), delete s[o]), o.apply(this, e), n += r?0:1, o = i[n]}return this}}, t}), function(t, e){"use strict"; "function" == typeof define && define.amd?define("get-size/get-size", [], function(){return e()}):"object" == typeof module && module.exports?module.exports = e():t.getSize = e()}(window, function(){"use strict"; function t(t){var e = parseFloat(t), i = t.indexOf("%") == - 1 && !isNaN(e); return i && e}function e(){}function i(){for (var t = {width:0, height:0, innerWidth:0, innerHeight:0, outerWidth:0, outerHeight:0}, e = 0; e < h; e++){var i = u[e]; t[i] = 0}return t}function n(t){var e = getComputedStyle(t); return e || a("Style returned " + e + ". Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1"), e}function o(){if (!d){d = !0; var e = document.createElement("div"); e.style.width = "200px", e.style.padding = "1px 2px 3px 4px", e.style.borderStyle = "solid", e.style.borderWidth = "1px 2px 3px 4px", e.style.boxSizing = "border-box"; var i = document.body || document.documentElement; i.appendChild(e); var o = n(e); s.isBoxSizeOuter = r = 200 == t(o.width), i.removeChild(e)}}function s(e){if (o(), "string" == typeof e && (e = document.querySelector(e)), e && "object" == typeof e && e.nodeType){var s = n(e); if ("none" == s.display)return i(); var a = {}; a.width = e.offsetWidth, a.height = e.offsetHeight; for (var d = a.isBorderBox = "border-box" == s.boxSizing, l = 0; l < h; l++){var f = u[l], c = s[f], m = parseFloat(c); a[f] = isNaN(m)?0:m}var p = a.paddingLeft + a.paddingRight, y = a.paddingTop + a.paddingBottom, g = a.marginLeft + a.marginRight, v = a.marginTop + a.marginBottom, _ = a.borderLeftWidth + a.borderRightWidth, I = a.borderTopWidth + a.borderBottomWidth, z = d && r, x = t(s.width); x !== !1 && (a.width = x + (z?0:p + _)); var S = t(s.height); return S !== !1 && (a.height = S + (z?0:y + I)), a.innerWidth = a.width - (p + _), a.innerHeight = a.height - (y + I), a.outerWidth = a.width + g, a.outerHeight = a.height + v, a}}var r, a = "undefined" == typeof console?e:function(t){console.error(t)}, u = ["paddingLeft", "paddingRight", "paddingTop", "paddingBottom", "marginLeft", "marginRight", "marginTop", "marginBottom", "borderLeftWidth", "borderRightWidth", "borderTopWidth", "borderBottomWidth"], h = u.length, d = !1; return s}), function(t, e){"use strict"; "function" == typeof define && define.amd?define("desandro-matches-selector/matches-selector", e):"object" == typeof module && module.exports?module.exports = e():t.matchesSelector = e()}(window, function(){"use strict"; var t = function(){var t = Element.prototype; if (t.matches)return"matches"; if (t.matchesSelector)return"matchesSelector"; for (var e = ["webkit", "moz", "ms", "o"], i = 0; i < e.length; i++){var n = e[i], o = n + "MatchesSelector"; if (t[o])return o}}(); return function(e, i){return e[t](i)}}), function(t, e){"function" == typeof define && define.amd?define("fizzy-ui-utils/utils", ["desandro-matches-selector/matches-selector"], function(i){return e(t, i)}):"object" == typeof module && module.exports?module.exports = e(t, require("desandro-matches-selector")):t.fizzyUIUtils = e(t, t.matchesSelector)}(window, function(t, e){var i = {}; i.extend = function(t, e){for (var i in e)t[i] = e[i]; return t}, i.modulo = function(t, e){return(t % e + e) % e}, i.makeArray = function(t){var e = []; if (Array.isArray(t))e = t; else if (t && "number" == typeof t.length)for (var i = 0; i < t.length; i++)e.push(t[i]); else e.push(t); return e}, i.removeFrom = function(t, e){var i = t.indexOf(e); i != - 1 && t.splice(i, 1)}, i.getParent = function(t, i){for (; t != document.body; )if (t = t.parentNode, e(t, i))return t}, i.getQueryElement = function(t){return"string" == typeof t?document.querySelector(t):t}, i.handleEvent = function(t){var e = "on" + t.type; this[e] && this[e](t)}, i.filterFindElements = function(t, n){t = i.makeArray(t); var o = []; return t.forEach(function(t){if (t instanceof HTMLElement){if (!n)return void o.push(t); e(t, n) && o.push(t); for (var i = t.querySelectorAll(n), s = 0; s < i.length; s++)o.push(i[s])}}), o}, i.debounceMethod = function(t, e, i){var n = t.prototype[e], o = e + "Timeout"; t.prototype[e] = function(){var t = this[o]; t && clearTimeout(t); var e = arguments, s = this; this[o] = setTimeout(function(){n.apply(s, e), delete s[o]}, i || 100)}}, i.docReady = function(t){var e = document.readyState; "complete" == e || "interactive" == e?setTimeout(t):document.addEventListener("DOMContentLoaded", t)}, i.toDashed = function(t){return t.replace(/(.)([A-Z])/g, function(t, e, i){return e + "-" + i}).toLowerCase()}; var n = t.console; return i.htmlInit = function(e, o){i.docReady(function(){var s = i.toDashed(o), r = "data-" + s, a = document.querySelectorAll("[" + r + "]"), u = document.querySelectorAll(".js-" + s), h = i.makeArray(a).concat(i.makeArray(u)), d = r + "-options", l = t.jQuery; h.forEach(function(t){var i, s = t.getAttribute(r) || t.getAttribute(d); try{i = s && JSON.parse(s)} catch (a){return void(n && n.error("Error parsing " + r + " on " + t.className + ": " + a))}var u = new e(t, i); l && l.data(t, o, u)})})}, i}), function(t, e){"function" == typeof define && define.amd?define("outlayer/item", ["ev-emitter/ev-emitter", "get-size/get-size"], e):"object" == typeof module && module.exports?module.exports = e(require("ev-emitter"), require("get-size")):(t.Outlayer = {}, t.Outlayer.Item = e(t.EvEmitter, t.getSize))}(window, function(t, e){"use strict"; function i(t){for (var e in t)return!1; return e = null, !0}function n(t, e){t && (this.element = t, this.layout = e, this.position = {x:0, y:0}, this._create())}function o(t){return t.replace(/([A-Z])/g, function(t){return"-" + t.toLowerCase()})}var s = document.documentElement.style, r = "string" == typeof s.transition?"transition":"WebkitTransition", a = "string" == typeof s.transform?"transform":"WebkitTransform", u = {WebkitTransition:"webkitTransitionEnd", transition:"transitionend"}[r], h = {transform:a, transition:r, transitionDuration:r + "Duration", transitionProperty:r + "Property", transitionDelay:r + "Delay"}, d = n.prototype = Object.create(t.prototype); d.constructor = n, d._create = function(){this._transn = {ingProperties:{}, clean:{}, onEnd:{}}, this.css({position:"absolute"})}, d.handleEvent = function(t){var e = "on" + t.type; this[e] && this[e](t)}, d.getSize = function(){this.size = e(this.element)}, d.css = function(t){var e = this.element.style; for (var i in t){var n = h[i] || i; e[n] = t[i]}}, d.getPosition = function(){var t = getComputedStyle(this.element), e = this.layout._getOption("originLeft"), i = this.layout._getOption("originTop"), n = t[e?"left":"right"], o = t[i?"top":"bottom"], s = this.layout.size, r = n.indexOf("%") != - 1?parseFloat(n) / 100 * s.width:parseInt(n, 10), a = o.indexOf("%") != - 1?parseFloat(o) / 100 * s.height:parseInt(o, 10); r = isNaN(r)?0:r, a = isNaN(a)?0:a, r -= e?s.paddingLeft:s.paddingRight, a -= i?s.paddingTop:s.paddingBottom, this.position.x = r, this.position.y = a}, d.layoutPosition = function(){var t = this.layout.size, e = {}, i = this.layout._getOption("originLeft"), n = this.layout._getOption("originTop"), o = i?"paddingLeft":"paddingRight", s = i?"left":"right", r = i?"right":"left", a = this.position.x + t[o]; e[s] = this.getXValue(a), e[r] = ""; var u = n?"paddingTop":"paddingBottom", h = n?"top":"bottom", d = n?"bottom":"top", l = this.position.y + t[u]; e[h] = this.getYValue(l), e[d] = "", this.css(e), this.emitEvent("layout", [this])}, d.getXValue = function(t){var e = this.layout._getOption("horizontal"); return this.layout.options.percentPosition && !e?t / this.layout.size.width * 100 + "%":t + "px"}, d.getYValue = function(t){var e = this.layout._getOption("horizontal"); return this.layout.options.percentPosition && e?t / this.layout.size.height * 100 + "%":t + "px"}, d._transitionTo = function(t, e){this.getPosition(); var i = this.position.x, n = this.position.y, o = parseInt(t, 10), s = parseInt(e, 10), r = o === this.position.x && s === this.position.y; if (this.setPosition(t, e), r && !this.isTransitioning)return void this.layoutPosition(); var a = t - i, u = e - n, h = {}; h.transform = this.getTranslate(a, u), this.transition({to:h, onTransitionEnd:{transform:this.layoutPosition}, isCleaning:!0})}, d.getTranslate = function(t, e){var i = this.layout._getOption("originLeft"), n = this.layout._getOption("originTop"); return t = i?t: - t, e = n?e: - e, "translate3d(" + t + "px, " + e + "px, 0)"}, d.goTo = function(t, e){this.setPosition(t, e), this.layoutPosition()}, d.moveTo = d._transitionTo, d.setPosition = function(t, e){this.position.x = parseInt(t, 10), this.position.y = parseInt(e, 10)}, d._nonTransition = function(t){this.css(t.to), t.isCleaning && this._removeStyles(t.to); for (var e in t.onTransitionEnd)t.onTransitionEnd[e].call(this)}, d.transition = function(t){if (!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(t); var e = this._transn; for (var i in t.onTransitionEnd)e.onEnd[i] = t.onTransitionEnd[i]; for (i in t.to)e.ingProperties[i] = !0, t.isCleaning && (e.clean[i] = !0); if (t.from){this.css(t.from); var n = this.element.offsetHeight; n = null}this.enableTransition(t.to), this.css(t.to), this.isTransitioning = !0}; var l = "opacity," + o(a); d.enableTransition = function(){if (!this.isTransitioning){var t = this.layout.options.transitionDuration; t = "number" == typeof t?t + "ms":t, this.css({transitionProperty:l, transitionDuration:t, transitionDelay:this.staggerDelay || 0}), this.element.addEventListener(u, this, !1)}}, d.onwebkitTransitionEnd = function(t){this.ontransitionend(t)}, d.onotransitionend = function(t){this.ontransitionend(t)}; var f = {"-webkit-transform":"transform"}; d.ontransitionend = function(t){if (t.target === this.element){var e = this._transn, n = f[t.propertyName] || t.propertyName; if (delete e.ingProperties[n], i(e.ingProperties) && this.disableTransition(), n in e.clean && (this.element.style[t.propertyName] = "", delete e.clean[n]), n in e.onEnd){var o = e.onEnd[n]; o.call(this), delete e.onEnd[n]}this.emitEvent("transitionEnd", [this])}}, d.disableTransition = function(){this.removeTransitionStyles(), this.element.removeEventListener(u, this, !1), this.isTransitioning = !1}, d._removeStyles = function(t){var e = {}; for (var i in t)e[i] = ""; this.css(e)}; var c = {transitionProperty:"", transitionDuration:"", transitionDelay:""}; return d.removeTransitionStyles = function(){this.css(c)}, d.stagger = function(t){t = isNaN(t)?0:t, this.staggerDelay = t + "ms"}, d.removeElem = function(){this.element.parentNode.removeChild(this.element), this.css({display:""}), this.emitEvent("remove", [this])}, d.remove = function(){return r && parseFloat(this.layout.options.transitionDuration)?(this.once("transitionEnd", function(){this.removeElem()}), void this.hide()):void this.removeElem()}, d.reveal = function(){delete this.isHidden, this.css({display:""}); var t = this.layout.options, e = {}, i = this.getHideRevealTransitionEndProperty("visibleStyle"); e[i] = this.onRevealTransitionEnd, this.transition({from:t.hiddenStyle, to:t.visibleStyle, isCleaning:!0, onTransitionEnd:e})}, d.onRevealTransitionEnd = function(){this.isHidden || this.emitEvent("reveal")}, d.getHideRevealTransitionEndProperty = function(t){var e = this.layout.options[t]; if (e.opacity)return"opacity"; for (var i in e)return i}, d.hide = function(){this.isHidden = !0, this.css({display:""}); var t = this.layout.options, e = {}, i = this.getHideRevealTransitionEndProperty("hiddenStyle"); e[i] = this.onHideTransitionEnd, this.transition({from:t.visibleStyle, to:t.hiddenStyle, isCleaning:!0, onTransitionEnd:e})}, d.onHideTransitionEnd = function(){this.isHidden && (this.css({display:"none"}), this.emitEvent("hide"))}, d.destroy = function(){this.css({position:"", left:"", right:"", top:"", bottom:"", transition:"", transform:""})}, n}), function(t, e){"use strict"; "function" == typeof define && define.amd?define("outlayer/outlayer", ["ev-emitter/ev-emitter", "get-size/get-size", "fizzy-ui-utils/utils", "./item"], function(i, n, o, s){return e(t, i, n, o, s)}):"object" == typeof module && module.exports?module.exports = e(t, require("ev-emitter"), require("get-size"), require("fizzy-ui-utils"), require("./item")):t.Outlayer = e(t, t.EvEmitter, t.getSize, t.fizzyUIUtils, t.Outlayer.Item)}(window, function(t, e, i, n, o){"use strict"; function s(t, e){var i = n.getQueryElement(t); if (!i)return void(u && u.error("Bad element for " + this.constructor.namespace + ": " + (i || t))); this.element = i, h && (this.$element = h(this.element)), this.options = n.extend({}, this.constructor.defaults), this.option(e); var o = ++l; this.element.outlayerGUID = o, f[o] = this, this._create(); var s = this._getOption("initLayout"); s && this.layout()}function r(t){function e(){t.apply(this, arguments)}return e.prototype = Object.create(t.prototype), e.prototype.constructor = e, e}function a(t){if ("number" == typeof t)return t; var e = t.match(/(^\d*\.?\d*)(\w*)/), i = e && e[1], n = e && e[2]; if (!i.length)return 0; i = parseFloat(i); var o = m[n] || 1; return i * o}var u = t.console, h = t.jQuery, d = function(){}, l = 0, f = {}; s.namespace = "outlayer", s.Item = o, s.defaults = {containerStyle:{position:"relative"}, initLayout:!0, originLeft:!0, originTop:!0, resize:!0, resizeContainer:!0, transitionDuration:"0.4s", hiddenStyle:{opacity:0, transform:"scale(0.001)"}, visibleStyle:{opacity:1, transform:"scale(1)"}}; var c = s.prototype; n.extend(c, e.prototype), c.option = function(t){n.extend(this.options, t)}, c._getOption = function(t){var e = this.constructor.compatOptions[t]; return e && void 0 !== this.options[e]?this.options[e]:this.options[t]}, s.compatOptions = {initLayout:"isInitLayout", horizontal:"isHorizontal", layoutInstant:"isLayoutInstant", originLeft:"isOriginLeft", originTop:"isOriginTop", resize:"isResizeBound", resizeContainer:"isResizingContainer"}, c._create = function(){this.reloadItems(), this.stamps = [], this.stamp(this.options.stamp), n.extend(this.element.style, this.options.containerStyle); var t = this._getOption("resize"); t && this.bindResize()}, c.reloadItems = function(){this.items = this._itemize(this.element.children)}, c._itemize = function(t){for (var e = this._filterFindItemElements(t), i = this.constructor.Item, n = [], o = 0; o < e.length; o++){var s = e[o], r = new i(s, this); n.push(r)}return n}, c._filterFindItemElements = function(t){return n.filterFindElements(t, this.options.itemSelector)}, c.getItemElements = function(){return this.items.map(function(t){return t.element})}, c.layout = function(){this._resetLayout(), this._manageStamps(); var t = this._getOption("layoutInstant"), e = void 0 !== t?t:!this._isLayoutInited; this.layoutItems(this.items, e), this._isLayoutInited = !0}, c._init = c.layout, c._resetLayout = function(){this.getSize()}, c.getSize = function(){this.size = i(this.element)}, c._getMeasurement = function(t, e){var n, o = this.options[t]; o?("string" == typeof o?n = this.element.querySelector(o):o instanceof HTMLElement && (n = o), this[t] = n?i(n)[e]:o):this[t] = 0}, c.layoutItems = function(t, e){t = this._getItemsForLayout(t), this._layoutItems(t, e), this._postLayout()}, c._getItemsForLayout = function(t){return t.filter(function(t){return!t.isIgnored})}, c._layoutItems = function(t, e){if (this._emitCompleteOnItems("layout", t), t && t.length){var i = []; t.forEach(function(t){var n = this._getItemLayoutPosition(t); n.item = t, n.isInstant = e || t.isLayoutInstant, i.push(n)}, this), this._processLayoutQueue(i)}}, c._getItemLayoutPosition = function(){return{x:0, y:0}}, c._processLayoutQueue = function(t){this.updateStagger(), t.forEach(function(t, e){this._positionItem(t.item, t.x, t.y, t.isInstant, e)}, this)}, c.updateStagger = function(){var t = this.options.stagger; return null === t || void 0 === t?void(this.stagger = 0):(this.stagger = a(t), this.stagger)}, c._positionItem = function(t, e, i, n, o){n?t.goTo(e, i):(t.stagger(o * this.stagger), t.moveTo(e, i))}, c._postLayout = function(){this.resizeContainer()}, c.resizeContainer = function(){var t = this._getOption("resizeContainer"); if (t){var e = this._getContainerSize(); e && (this._setContainerMeasure(e.width, !0), this._setContainerMeasure(e.height, !1))}}, c._getContainerSize = d, c._setContainerMeasure = function(t, e){if (void 0 !== t){var i = this.size; i.isBorderBox && (t += e?i.paddingLeft + i.paddingRight + i.borderLeftWidth + i.borderRightWidth:i.paddingBottom + i.paddingTop + i.borderTopWidth + i.borderBottomWidth), t = Math.max(t, 0), this.element.style[e?"width":"height"] = t + "px"}}, c._emitCompleteOnItems = function(t, e){function i(){o.dispatchEvent(t + "Complete", null, [e])}function n(){r++, r == s && i()}var o = this, s = e.length; if (!e || !s)return void i(); var r = 0; e.forEach(function(e){e.once(t, n)})}, c.dispatchEvent = function(t, e, i){var n = e?[e].concat(i):i; if (this.emitEvent(t, n), h)if (this.$element = this.$element || h(this.element), e){var o = h.Event(e); o.type = t, this.$element.trigger(o, i)} else this.$element.trigger(t, i)}, c.ignore = function(t){var e = this.getItem(t); e && (e.isIgnored = !0)}, c.unignore = function(t){var e = this.getItem(t); e && delete e.isIgnored}, c.stamp = function(t){t = this._find(t), t && (this.stamps = this.stamps.concat(t), t.forEach(this.ignore, this))}, c.unstamp = function(t){t = this._find(t), t && t.forEach(function(t){n.removeFrom(this.stamps, t), this.unignore(t)}, this)}, c._find = function(t){if (t)return"string" == typeof t && (t = this.element.querySelectorAll(t)), t = n.makeArray(t)}, c._manageStamps = function(){this.stamps && this.stamps.length && (this._getBoundingRect(), this.stamps.forEach(this._manageStamp, this))}, c._getBoundingRect = function(){var t = this.element.getBoundingClientRect(), e = this.size; this._boundingRect = {left:t.left + e.paddingLeft + e.borderLeftWidth, top:t.top + e.paddingTop + e.borderTopWidth, right:t.right - (e.paddingRight + e.borderRightWidth), bottom:t.bottom - (e.paddingBottom + e.borderBottomWidth)}}, c._manageStamp = d, c._getElementOffset = function(t){var e = t.getBoundingClientRect(), n = this._boundingRect, o = i(t), s = {left:e.left - n.left - o.marginLeft, top:e.top - n.top - o.marginTop, right:n.right - e.right - o.marginRight, bottom:n.bottom - e.bottom - o.marginBottom}; return s}, c.handleEvent = n.handleEvent, c.bindResize = function(){t.addEventListener("resize", this), this.isResizeBound = !0}, c.unbindResize = function(){t.removeEventListener("resize", this), this.isResizeBound = !1}, c.onresize = function(){this.resize()}, n.debounceMethod(s, "onresize", 100), c.resize = function(){this.isResizeBound && this.needsResizeLayout() && this.layout()}, c.needsResizeLayout = function(){var t = i(this.element), e = this.size && t; return e && t.innerWidth !== this.size.innerWidth}, c.addItems = function(t){var e = this._itemize(t); return e.length && (this.items = this.items.concat(e)), e}, c.appended = function(t){var e = this.addItems(t); e.length && (this.layoutItems(e, !0), this.reveal(e))}, c.prepended = function(t){var e = this._itemize(t); if (e.length){var i = this.items.slice(0); this.items = e.concat(i), this._resetLayout(), this._manageStamps(), this.layoutItems(e, !0), this.reveal(e), this.layoutItems(i)}}, c.reveal = function(t){if (this._emitCompleteOnItems("reveal", t), t && t.length){var e = this.updateStagger(); t.forEach(function(t, i){t.stagger(i * e), t.reveal()})}}, c.hide = function(t){if (this._emitCompleteOnItems("hide", t), t && t.length){var e = this.updateStagger(); t.forEach(function(t, i){t.stagger(i * e), t.hide()})}}, c.revealItemElements = function(t){var e = this.getItems(t); this.reveal(e)}, c.hideItemElements = function(t){var e = this.getItems(t); this.hide(e)}, c.getItem = function(t){for (var e = 0; e < this.items.length; e++){var i = this.items[e]; if (i.element == t)return i}}, c.getItems = function(t){t = n.makeArray(t); var e = []; return t.forEach(function(t){var i = this.getItem(t); i && e.push(i)}, this), e}, c.remove = function(t){var e = this.getItems(t); this._emitCompleteOnItems("remove", e), e && e.length && e.forEach(function(t){t.remove(), n.removeFrom(this.items, t)}, this)}, c.destroy = function(){var t = this.element.style; t.height = "", t.position = "", t.width = "", this.items.forEach(function(t){t.destroy()}), this.unbindResize(); var e = this.element.outlayerGUID; delete f[e], delete this.element.outlayerGUID, h && h.removeData(this.element, this.constructor.namespace)}, s.data = function(t){t = n.getQueryElement(t); var e = t && t.outlayerGUID; return e && f[e]}, s.create = function(t, e){var i = r(s); return i.defaults = n.extend({}, s.defaults), n.extend(i.defaults, e), i.compatOptions = n.extend({}, s.compatOptions), i.namespace = t, i.data = s.data, i.Item = r(o), n.htmlInit(i, t), h && h.bridget && h.bridget(t, i), i}; var m = {ms:1, s:1e3}; return s.Item = o, s}), function(t, e){"function" == typeof define && define.amd?define("isotope/js/item", ["outlayer/outlayer"], e):"object" == typeof module && module.exports?module.exports = e(require("outlayer")):(t.Isotope = t.Isotope || {}, t.Isotope.Item = e(t.Outlayer))}(window, function(t){"use strict"; function e(){t.Item.apply(this, arguments)}var i = e.prototype = Object.create(t.Item.prototype), n = i._create; i._create = function(){this.id = this.layout.itemGUID++, n.call(this), this.sortData = {}}, i.updateSortData = function(){if (!this.isIgnored){this.sortData.id = this.id, this.sortData["original-order"] = this.id, this.sortData.random = Math.random(); var t = this.layout.options.getSortData, e = this.layout._sorters; for (var i in t){var n = e[i]; this.sortData[i] = n(this.element, this)}}}; var o = i.destroy; return i.destroy = function(){o.apply(this, arguments), this.css({display:""})}, e}), function(t, e){"function" == typeof define && define.amd?define("isotope/js/layout-mode", ["get-size/get-size", "outlayer/outlayer"], e):"object" == typeof module && module.exports?module.exports = e(require("get-size"), require("outlayer")):(t.Isotope = t.Isotope || {}, t.Isotope.LayoutMode = e(t.getSize, t.Outlayer))}(window, function(t, e){"use strict"; function i(t){this.isotope = t, t && (this.options = t.options[this.namespace], this.element = t.element, this.items = t.filteredItems, this.size = t.size)}var n = i.prototype, o = ["_resetLayout", "_getItemLayoutPosition", "_manageStamp", "_getContainerSize", "_getElementOffset", "needsResizeLayout", "_getOption"]; return o.forEach(function(t){n[t] = function(){return e.prototype[t].apply(this.isotope, arguments)}}), n.needsVerticalResizeLayout = function(){var e = t(this.isotope.element), i = this.isotope.size && e; return i && e.innerHeight != this.isotope.size.innerHeight}, n._getMeasurement = function(){this.isotope._getMeasurement.apply(this, arguments)}, n.getColumnWidth = function(){this.getSegmentSize("column", "Width")}, n.getRowHeight = function(){this.getSegmentSize("row", "Height")}, n.getSegmentSize = function(t, e){var i = t + e, n = "outer" + e; if (this._getMeasurement(i, n), !this[i]){var o = this.getFirstItemSize(); this[i] = o && o[n] || this.isotope.size["inner" + e]}}, n.getFirstItemSize = function(){var e = this.isotope.filteredItems[0]; return e && e.element && t(e.element)}, n.layout = function(){this.isotope.layout.apply(this.isotope, arguments)}, n.getSize = function(){this.isotope.getSize(), this.size = this.isotope.size}, i.modes = {}, i.create = function(t, e){function o(){i.apply(this, arguments)}return o.prototype = Object.create(n), o.prototype.constructor = o, e && (o.options = e), o.prototype.namespace = t, i.modes[t] = o, o}, i}), function(t, e){"function" == typeof define && define.amd?define("masonry/masonry", ["outlayer/outlayer", "get-size/get-size"], e):"object" == typeof module && module.exports?module.exports = e(require("outlayer"), require("get-size")):t.Masonry = e(t.Outlayer, t.getSize)}(window, function(t, e){var i = t.create("masonry"); return i.compatOptions.fitWidth = "isFitWidth", i.prototype._resetLayout = function(){this.getSize(), this._getMeasurement("columnWidth", "outerWidth"), this._getMeasurement("gutter", "outerWidth"), this.measureColumns(), this.colYs = []; for (var t = 0; t < this.cols; t++)this.colYs.push(0); this.maxY = 0}, i.prototype.measureColumns = function(){if (this.getContainerWidth(), !this.columnWidth){var t = this.items[0], i = t && t.element; this.columnWidth = i && e(i).outerWidth || this.containerWidth}var n = this.columnWidth += this.gutter, o = this.containerWidth + this.gutter, s = o / n, r = n - o % n, a = r && r < 1?"round":"floor"; s = Math[a](s), this.cols = Math.max(s, 1)}, i.prototype.getContainerWidth = function(){var t = this._getOption("fitWidth"), i = t?this.element.parentNode:this.element, n = e(i); this.containerWidth = n && n.innerWidth}, i.prototype._getItemLayoutPosition = function(t){t.getSize(); var e = t.size.outerWidth % this.columnWidth, i = e && e < 1?"round":"ceil", n = Math[i](t.size.outerWidth / this.columnWidth); n = Math.min(n, this.cols); for (var o = this._getColGroup(n), s = Math.min.apply(Math, o), r = o.indexOf(s), a = {x:this.columnWidth * r, y:s}, u = s + t.size.outerHeight, h = this.cols + 1 - o.length, d = 0; d < h; d++)this.colYs[r + d] = u; return a}, i.prototype._getColGroup = function(t){if (t < 2)return this.colYs; for (var e = [], i = this.cols + 1 - t, n = 0; n < i; n++){var o = this.colYs.slice(n, n + t); e[n] = Math.max.apply(Math, o)}return e}, i.prototype._manageStamp = function(t){var i = e(t), n = this._getElementOffset(t), o = this._getOption("originLeft"), s = o?n.left:n.right, r = s + i.outerWidth, a = Math.floor(s / this.columnWidth); a = Math.max(0, a); var u = Math.floor(r / this.columnWidth); u -= r % this.columnWidth?0:1, u = Math.min(this.cols - 1, u); for (var h = this._getOption("originTop"), d = (h?n.top:n.bottom) + i.outerHeight, l = a; l <= u; l++)this.colYs[l] = Math.max(d, this.colYs[l])}, i.prototype._getContainerSize = function(){this.maxY = Math.max.apply(Math, this.colYs); var t = {height:this.maxY}; return this._getOption("fitWidth") && (t.width = this._getContainerFitWidth()), t}, i.prototype._getContainerFitWidth = function(){for (var t = 0, e = this.cols; --e && 0 === this.colYs[e]; )t++; return(this.cols - t) * this.columnWidth - this.gutter}, i.prototype.needsResizeLayout = function(){var t = this.containerWidth; return this.getContainerWidth(), t != this.containerWidth}, i}), function(t, e){"function" == typeof define && define.amd?define("isotope/js/layout-modes/masonry", ["../layout-mode", "masonry/masonry"], e):"object" == typeof module && module.exports?module.exports = e(require("../layout-mode"), require("masonry-layout")):e(t.Isotope.LayoutMode, t.Masonry)}(window, function(t, e){"use strict"; var i = t.create("masonry"), n = i.prototype, o = {_getElementOffset:!0, layout:!0, _getMeasurement:!0}; for (var s in e.prototype)o[s] || (n[s] = e.prototype[s]); var r = n.measureColumns; n.measureColumns = function(){this.items = this.isotope.filteredItems, r.call(this)}; var a = n._getOption; return n._getOption = function(t){return"fitWidth" == t?void 0 !== this.options.isFitWidth?this.options.isFitWidth:this.options.fitWidth:a.apply(this.isotope, arguments)}, i}), function(t, e){"function" == typeof define && define.amd?define("isotope/js/layout-modes/fit-rows", ["../layout-mode"], e):"object" == typeof exports?module.exports = e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window, function(t){"use strict"; var e = t.create("fitRows"), i = e.prototype; return i._resetLayout = function(){this.x = 0, this.y = 0, this.maxY = 0, this._getMeasurement("gutter", "outerWidth")}, i._getItemLayoutPosition = function(t){t.getSize(); var e = t.size.outerWidth + this.gutter, i = this.isotope.size.innerWidth + this.gutter; 0 !== this.x && e + this.x > i && (this.x = 0, this.y = this.maxY); var n = {x:this.x, y:this.y}; return this.maxY = Math.max(this.maxY, this.y + t.size.outerHeight), this.x += e, n}, i._getContainerSize = function(){return{height:this.maxY}}, e}), function(t, e){"function" == typeof define && define.amd?define("isotope/js/layout-modes/vertical", ["../layout-mode"], e):"object" == typeof module && module.exports?module.exports = e(require("../layout-mode")):e(t.Isotope.LayoutMode)}(window, function(t){"use strict"; var e = t.create("vertical", {horizontalAlignment:0}), i = e.prototype; return i._resetLayout = function(){this.y = 0}, i._getItemLayoutPosition = function(t){t.getSize(); var e = (this.isotope.size.innerWidth - t.size.outerWidth) * this.options.horizontalAlignment, i = this.y; return this.y += t.size.outerHeight, {x:e, y:i}}, i._getContainerSize = function(){return{height:this.y}}, e}), function(t, e){"function" == typeof define && define.amd?define(["outlayer/outlayer", "get-size/get-size", "desandro-matches-selector/matches-selector", "fizzy-ui-utils/utils", "isotope/js/item", "isotope/js/layout-mode", "isotope/js/layout-modes/masonry", "isotope/js/layout-modes/fit-rows", "isotope/js/layout-modes/vertical"], function(i, n, o, s, r, a){return e(t, i, n, o, s, r, a)}):"object" == typeof module && module.exports?module.exports = e(t, require("outlayer"), require("get-size"), require("desandro-matches-selector"), require("fizzy-ui-utils"), require("isotope/js/item"), require("isotope/js/layout-mode"), require("isotope/js/layout-modes/masonry"), require("isotope/js/layout-modes/fit-rows"), require("isotope/js/layout-modes/vertical")):t.Isotope = e(t, t.Outlayer, t.getSize, t.matchesSelector, t.fizzyUIUtils, t.Isotope.Item, t.Isotope.LayoutMode)}(window, function(t, e, i, n, o, s, r){function a(t, e){return function(i, n){for (var o = 0; o < t.length; o++){var s = t[o], r = i.sortData[s], a = n.sortData[s]; if (r > a || r < a){var u = void 0 !== e[s]?e[s]:e, h = u?1: - 1; return(r > a?1: - 1) * h}}return 0}}var u = t.jQuery, h = String.prototype.trim?function(t){return t.trim()}:function(t){return t.replace(/^\s+|\s+$/g, "")}, d = e.create("isotope", {layoutMode:"masonry", isJQueryFiltering:!0, sortAscending:!0}); d.Item = s, d.LayoutMode = r; var l = d.prototype; l._create = function(){this.itemGUID = 0, this._sorters = {}, this._getSorters(), e.prototype._create.call(this), this.modes = {}, this.filteredItems = this.items, this.sortHistory = ["original-order"]; for (var t in r.modes)this._initLayoutMode(t)}, l.reloadItems = function(){this.itemGUID = 0, e.prototype.reloadItems.call(this)}, l._itemize = function(){for (var t = e.prototype._itemize.apply(this, arguments), i = 0; i < t.length; i++){var n = t[i]; n.id = this.itemGUID++}return this._updateItemsSortData(t), t}, l._initLayoutMode = function(t){var e = r.modes[t], i = this.options[t] || {}; this.options[t] = e.options?o.extend(e.options, i):i, this.modes[t] = new e(this)}, l.layout = function(){return!this._isLayoutInited && this._getOption("initLayout")?void this.arrange():void this._layout()}, l._layout = function(){var t = this._getIsInstant(); this._resetLayout(), this._manageStamps(), this.layoutItems(this.filteredItems, t), this._isLayoutInited = !0}, l.arrange = function(t){this.option(t), this._getIsInstant(); var e = this._filter(this.items); this.filteredItems = e.matches, this._bindArrangeComplete(), this._isInstant?this._noTransition(this._hideReveal, [e]):this._hideReveal(e), this._sort(), this._layout()}, l._init = l.arrange, l._hideReveal = function(t){this.reveal(t.needReveal), this.hide(t.needHide)}, l._getIsInstant = function(){var t = this._getOption("layoutInstant"), e = void 0 !== t?t:!this._isLayoutInited; return this._isInstant = e, e}, l._bindArrangeComplete = function(){function t(){e && i && n && o.dispatchEvent("arrangeComplete", null, [o.filteredItems])}var e, i, n, o = this; this.once("layoutComplete", function(){e = !0, t()}), this.once("hideComplete", function(){i = !0, t()}), this.once("revealComplete", function(){n = !0, t()})}, l._filter = function(t){var e = this.options.filter; e = e || "*"; for (var i = [], n = [], o = [], s = this._getFilterTest(e), r = 0; r < t.length; r++){var a = t[r]; if (!a.isIgnored){var u = s(a); u && i.push(a), u && a.isHidden?n.push(a):u || a.isHidden || o.push(a)}}return{matches:i, needReveal:n, needHide:o}}, l._getFilterTest = function(t){return u && this.options.isJQueryFiltering?function(e){return u(e.element).is(t)}:"function" == typeof t?function(e){return t(e.element)}:function(e){return n(e.element, t)}}, l.updateSortData = function(t){var e; t?(t = o.makeArray(t), e = this.getItems(t)):e = this.items, this._getSorters(), this._updateItemsSortData(e)}, l._getSorters = function(){var t = this.options.getSortData; for (var e in t){var i = t[e]; this._sorters[e] = f(i)}}, l._updateItemsSortData = function(t){for (var e = t && t.length, i = 0; e && i < e; i++){var n = t[i]; n.updateSortData()}}; var f = function(){function t(t){if ("string" != typeof t)return t; var i = h(t).split(" "), n = i[0], o = n.match(/^\[(.+)\]$/), s = o && o[1], r = e(s, n), a = d.sortDataParsers[i[1]];
        return t = a?function(t){return t && a(r(t))}:function(t){return t && r(t)}}function e(t, e){return t?function(e){return e.getAttribute(t)}:function(t){var i = t.querySelector(e); return i && i.textContent}}return t}(); d.sortDataParsers = {parseInt:function(t){return parseInt(t, 10)}, parseFloat:function(t){return parseFloat(t)}}, l._sort = function(){var t = this.options.sortBy; if (t){var e = [].concat.apply(t, this.sortHistory), i = a(e, this.options.sortAscending); this.filteredItems.sort(i), t != this.sortHistory[0] && this.sortHistory.unshift(t)}}, l._mode = function(){var t = this.options.layoutMode, e = this.modes[t]; if (!e)throw new Error("No layout mode: " + t); return e.options = this.options[t], e}, l._resetLayout = function(){e.prototype._resetLayout.call(this), this._mode()._resetLayout()}, l._getItemLayoutPosition = function(t){return this._mode()._getItemLayoutPosition(t)}, l._manageStamp = function(t){this._mode()._manageStamp(t)}, l._getContainerSize = function(){return this._mode()._getContainerSize()}, l.needsResizeLayout = function(){return this._mode().needsResizeLayout()}, l.appended = function(t){var e = this.addItems(t); if (e.length){var i = this._filterRevealAdded(e); this.filteredItems = this.filteredItems.concat(i)}}, l.prepended = function(t){var e = this._itemize(t); if (e.length){this._resetLayout(), this._manageStamps(); var i = this._filterRevealAdded(e); this.layoutItems(this.filteredItems), this.filteredItems = i.concat(this.filteredItems), this.items = e.concat(this.items)}}, l._filterRevealAdded = function(t){var e = this._filter(t); return this.hide(e.needHide), this.reveal(e.matches), this.layoutItems(e.matches, !0), e.matches}, l.insert = function(t){var e = this.addItems(t); if (e.length){var i, n, o = e.length; for (i = 0; i < o; i++)n = e[i], this.element.appendChild(n.element); var s = this._filter(e).matches; for (i = 0; i < o; i++)e[i].isLayoutInstant = !0; for (this.arrange(), i = 0; i < o; i++)delete e[i].isLayoutInstant; this.reveal(s)}}; var c = l.remove; return l.remove = function(t){t = o.makeArray(t); var e = this.getItems(t); c.call(this, t); for (var i = e && e.length, n = 0; i && n < i; n++){var s = e[n]; o.removeFrom(this.filteredItems, s)}}, l.shuffle = function(){for (var t = 0; t < this.items.length; t++){var e = this.items[t]; e.sortData.random = Math.random()}this.options.sortBy = "random", this._sort(), this._layout()}, l._noTransition = function(t, e){var i = this.options.transitionDuration; this.options.transitionDuration = 0; var n = t.apply(this, e); return this.options.transitionDuration = i, n}, l.getFilteredItemElements = function(){return this.filteredItems.map(function(t){return t.element})}, d});
// source --> https://www.silviakelly.it/wp-content/plugins/woo-product-grid-list-design/js/jquery.bxslider.js?ver=1.0.8 
/**
 * BxSlider v4.1.2 - Fully loaded, responsive content slider
 * http://bxslider.com
 *
 * Copyright 2014, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com
 * Written while drinking Belgian ales and listening to jazz
 *
 * Released under the MIT license - http://opensource.org/licenses/MIT
 */

;
(function($) {

    var defaults = {

        // GENERAL
        mode: 'horizontal',
        slideSelector: '',
        infiniteLoop: true,
        hideControlOnEnd: false,
        speed: 500,
        easing: null,
        slideMargin: 0,
        startSlide: 0,
        randomStart: false,
        captions: false,
        ticker: false,
        tickerHover: false,
        adaptiveHeight: false,
        adaptiveHeightSpeed: 500,
        video: false,
        useCSS: true,
        preloadImages: 'visible',
        responsive: true,
        slideZIndex: 50,
        wrapperClass: 'bx-wrapper',

        // TOUCH
        touchEnabled: true,
        swipeThreshold: 50,
        oneToOneTouch: true,
        preventDefaultSwipeX: true,
        preventDefaultSwipeY: false,

        // ACCESSIBILITY
        ariaLive: true,
        ariaHidden: true,

        // KEYBOARD
        keyboardEnabled: false,

        // PAGER
        pager: true,
        pagerType: 'full',
        pagerShortSeparator: ' / ',
        pagerSelector: null,
        buildPager: null,
        pagerCustom: null,

        // CONTROLS
        controls: true,
        nextText: 'Next',
        prevText: 'Prev',
        nextSelector: null,
        prevSelector: null,
        autoControls: false,
        startText: 'Start',
        stopText: 'Stop',
        autoControlsCombine: false,
        autoControlsSelector: null,

        // AUTO
        auto: false,
        pause: 4000,
        autoStart: true,
        autoDirection: 'next',
        stopAutoOnClick: true,
        autoHover: false,
        autoDelay: 0,
        autoSlideForOnePage: false,

        // CAROUSEL
        minSlides: 1,
        maxSlides: 1,
        moveSlides: 0,
        slideWidth: 0,
        shrinkItems: false,

        // CALLBACKS
        onSliderLoad: function() {
            return true;
        },
        onSlideBefore: function() {
            return true;
        },
        onSlideAfter: function() {
            return true;
        },
        onSlideNext: function() {
            return true;
        },
        onSlidePrev: function() {
            return true;
        },
        onSliderResize: function() {
            return true;
        }
    };

    $.fn.bxSlider = function(options) {

        if (this.length === 0) {
            return this;
        }

        // support multiple elements
        if (this.length > 1) {
            this.each(function() {
                $(this).bxSlider(options);
            });
            return this;
        }

        // create a namespace to be used throughout the plugin
        var slider = {},
                // set a reference to our slider element
                el = this,
                // get the original window dimens (thanks a lot IE)
                windowWidth = $(window).width(),
                windowHeight = $(window).height();

        // Return if slider is already initialized
        if ($(el).data('bxSlider')) {
            return;
        }

        /**
         * ===================================================================================
         * = PRIVATE FUNCTIONS
         * ===================================================================================
         */

        /**
         * Initializes namespace settings to be used throughout plugin
         */
        var init = function() {
            // Return if slider is already initialized
            if ($(el).data('bxSlider')) {
                return;
            }
            // merge user-supplied options with the defaults
            slider.settings = $.extend({}, defaults, options);
            // parse slideWidth setting
            slider.settings.slideWidth = parseInt(slider.settings.slideWidth);
            // store the original children
            slider.children = el.children(slider.settings.slideSelector);
            // check if actual number of slides is less than minSlides / maxSlides
            if (slider.children.length < slider.settings.minSlides) {
                slider.settings.minSlides = slider.children.length;
            }
            if (slider.children.length < slider.settings.maxSlides) {
                slider.settings.maxSlides = slider.children.length;
            }
            // if random start, set the startSlide setting to random number
            if (slider.settings.randomStart) {
                slider.settings.startSlide = Math.floor(Math.random() * slider.children.length);
            }
            // store active slide information
            slider.active = {index: slider.settings.startSlide};
            // store if the slider is in carousel mode (displaying / moving multiple slides)
            slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1 ? true : false;
            // if carousel, force preloadImages = 'all'
            if (slider.carousel) {
                slider.settings.preloadImages = 'all';
            }
            // calculate the min / max width thresholds based on min / max number of slides
            // used to setup and update carousel slides dimensions
            slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin);
            slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
            // store the current state of the slider (if currently animating, working is true)
            slider.working = false;
            // initialize the controls object
            slider.controls = {};
            // initialize an auto interval
            slider.interval = null;
            // determine which property to use for transitions
            slider.animProp = slider.settings.mode === 'vertical' ? 'top' : 'left';
            // determine if hardware acceleration can be used
            slider.usingCSS = slider.settings.useCSS && slider.settings.mode !== 'fade' && (function() {
                // create our test div element
                var div = document.createElement('div'),
                        // css transition properties
                        props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
                // test for each property
                for (var i = 0; i < props.length; i++) {
                    if (div.style[props[i]] !== undefined) {
                        slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase();
                        slider.animProp = '-' + slider.cssPrefix + '-transform';
                        return true;
                    }
                }
                return false;
            }());
            // if vertical mode always make maxSlides and minSlides equal
            if (slider.settings.mode === 'vertical') {
                slider.settings.maxSlides = slider.settings.minSlides;
            }
            // save original style data
            el.data('origStyle', el.attr('style'));
            el.children(slider.settings.slideSelector).each(function() {
                $(this).data('origStyle', $(this).attr('style'));
            });

            // perform all DOM / CSS modifications
            setup();
        };

        /**
         * Performs all DOM and CSS modifications
         */
        var setup = function() {
            var preloadSelector = slider.children.eq(slider.settings.startSlide); // set the default preload selector (visible)

            // wrap el in a wrapper
            el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="bx-viewport"></div></div>');
            // store a namespace reference to .bx-viewport
            slider.viewport = el.parent();

            // add aria-live if the setting is enabled and ticker mode is disabled
            if (slider.settings.ariaLive && !slider.settings.ticker) {
                slider.viewport.attr('aria-live', 'polite');
            }
            // add a loading div to display while images are loading
            slider.loader = $('<div class="bx-loading" />');
            slider.viewport.prepend(slider.loader);
            // set el to a massive width, to hold any needed slides
            // also strip any margin and padding from el
            el.css({
                width: slider.settings.mode === 'horizontal' ? (slider.children.length * 1000 + 215) + '%' : 'auto',
                position: 'relative'
            });
            // if using CSS, add the easing property
            if (slider.usingCSS && slider.settings.easing) {
                el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing);
                // if not using CSS and no easing value was supplied, use the default JS animation easing (swing)
            } else if (!slider.settings.easing) {
                slider.settings.easing = 'swing';
            }
            // make modifications to the viewport (.bx-viewport)
            slider.viewport.css({
                width: '100%',
                overflow: 'hidden',
                position: 'relative'
            });
            slider.viewport.parent().css({
                maxWidth: getViewportMaxWidth()
            });
            // make modification to the wrapper (.bx-wrapper)
            if (!slider.settings.pager && !slider.settings.controls) {
                slider.viewport.parent().css({
                    margin: '0 auto 0px'
                });
            }
            // apply css to all slider children
            slider.children.css({
                float: slider.settings.mode === 'horizontal' ? 'left' : 'none',
                listStyle: 'none',
                position: 'relative'
            });
            // apply the calculated width after the float is applied to prevent scrollbar interference
            slider.children.css('width', getSlideWidth());
            // if slideMargin is supplied, add the css
            if (slider.settings.mode === 'horizontal' && slider.settings.slideMargin > 0) {
                slider.children.css('marginRight', slider.settings.slideMargin);
            }
            if (slider.settings.mode === 'vertical' && slider.settings.slideMargin > 0) {
                slider.children.css('marginBottom', slider.settings.slideMargin);
            }
            // if "fade" mode, add positioning and z-index CSS
            if (slider.settings.mode === 'fade') {
                slider.children.css({
                    position: 'absolute',
                    zIndex: 0,
                    display: 'none'
                });
                // prepare the z-index on the showing element
                slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'});
            }
            // create an element to contain all slider controls (pager, start / stop, etc)
            slider.controls.el = $('<div class="bx-controls" />');
            // if captions are requested, add them
            if (slider.settings.captions) {
                appendCaptions();
            }
            // check if startSlide is last slide
            slider.active.last = slider.settings.startSlide === getPagerQty() - 1;
            // if video is true, set up the fitVids plugin
            if (slider.settings.video) {
                el.fitVids();
            }
            if (slider.settings.preloadImages === 'all' || slider.settings.ticker) {
                preloadSelector = slider.children;
            }
            // only check for control addition if not in "ticker" mode
            if (!slider.settings.ticker) {
                // if controls are requested, add them
                if (slider.settings.controls) {
                    appendControls();
                }
                // if auto is true, and auto controls are requested, add them
                if (slider.settings.auto && slider.settings.autoControls) {
                    appendControlsAuto();
                }
                // if pager is requested, add it
                if (slider.settings.pager) {
                    appendPager();
                }
                // if any control option is requested, add the controls wrapper
                if (slider.settings.controls || slider.settings.autoControls || slider.settings.pager) {
                    slider.viewport.after(slider.controls.el);
                }
                // if ticker mode, do not allow a pager
            } else {
                slider.settings.pager = false;
            }
            loadElements(preloadSelector, start);
        };

        var loadElements = function(selector, callback) {
            var total = selector.find('img:not([src=""]), iframe').length,
                    count = 0;
            if (total === 0) {
                callback();
                return;
            }
            selector.find('img:not([src=""]), iframe').each(function() {
                $(this).one('load error', function() {
                    if (++count === total) {
                        callback();
                    }
                }).each(function() {
                    if (this.complete) {
                        $(this).load();
                    }
                });
            });
        };

        /**
         * Start the slider
         */
        var start = function() {
            // if infinite loop, prepare additional slides
            if (slider.settings.infiniteLoop && slider.settings.mode !== 'fade' && !slider.settings.ticker) {
                var slice = slider.settings.mode === 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides,
                        sliceAppend = slider.children.slice(0, slice).clone(true).addClass('bx-clone'),
                        slicePrepend = slider.children.slice(-slice).clone(true).addClass('bx-clone');
                if (slider.settings.ariaHidden) {
                    sliceAppend.attr('aria-hidden', true);
                    slicePrepend.attr('aria-hidden', true);
                }
                el.append(sliceAppend).prepend(slicePrepend);
            }
            // remove the loading DOM element
            slider.loader.remove();
            // set the left / top position of "el"
            setSlidePosition();
            // if "vertical" mode, always use adaptiveHeight to prevent odd behavior
            if (slider.settings.mode === 'vertical') {
                slider.settings.adaptiveHeight = true;
            }
            // set the viewport height
            slider.viewport.height(getViewportHeight());
            // make sure everything is positioned just right (same as a window resize)
            el.redrawSlider();
            // onSliderLoad callback
            slider.settings.onSliderLoad.call(el, slider.active.index);
            // slider has been fully initialized
            slider.initialized = true;
            // bind the resize call to the window
            if (slider.settings.responsive) {
                $(window).bind('resize', resizeWindow);
            }
            // if auto is true and has more than 1 page, start the show
            if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) {
                initAuto();
            }
            // if ticker is true, start the ticker
            if (slider.settings.ticker) {
                initTicker();
            }
            // if pager is requested, make the appropriate pager link active
            if (slider.settings.pager) {
                updatePagerActive(slider.settings.startSlide);
            }
            // check for any updates to the controls (like hideControlOnEnd updates)
            if (slider.settings.controls) {
                updateDirectionControls();
            }
            // if touchEnabled is true, setup the touch events
            if (slider.settings.touchEnabled && !slider.settings.ticker) {
                initTouch();
            }
            // if keyboardEnabled is true, setup the keyboard events
            if (slider.settings.keyboardEnabled && !slider.settings.ticker) {
                $(document).keydown(keyPress);
            }
        };

        /**
         * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value
         */
        var getViewportHeight = function() {
            var height = 0;
            // first determine which children (slides) should be used in our height calculation
            var children = $();
            // if mode is not "vertical" and adaptiveHeight is false, include all children
            if (slider.settings.mode !== 'vertical' && !slider.settings.adaptiveHeight) {
                children = slider.children;
            } else {
                // if not carousel, return the single active child
                if (!slider.carousel) {
                    children = slider.children.eq(slider.active.index);
                    // if carousel, return a slice of children
                } else {
                    // get the individual slide index
                    var currentIndex = slider.settings.moveSlides === 1 ? slider.active.index : slider.active.index * getMoveBy();
                    // add the current slide to the children
                    children = slider.children.eq(currentIndex);
                    // cycle through the remaining "showing" slides
                    for (i = 1; i <= slider.settings.maxSlides - 1; i++) {
                        // if looped back to the start
                        if (currentIndex + i >= slider.children.length) {
                            children = children.add(slider.children.eq(i - 1));
                        } else {
                            children = children.add(slider.children.eq(currentIndex + i));
                        }
                    }
                }
            }
            // if "vertical" mode, calculate the sum of the heights of the children
            if (slider.settings.mode === 'vertical') {
                children.each(function(index) {
                    height += $(this).outerHeight();
                });
                // add user-supplied margins
                if (slider.settings.slideMargin > 0) {
                    height += slider.settings.slideMargin * (slider.settings.minSlides - 1);
                }
                // if not "vertical" mode, calculate the max height of the children
            } else {
                height = Math.max.apply(Math, children.map(function() {
                    return $(this).outerHeight(false);
                }).get());
            }

            if (slider.viewport.css('box-sizing') === 'border-box') {
                height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) +
                        parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width'));
            } else if (slider.viewport.css('box-sizing') === 'padding-box') {
                height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom'));
            }

            return height;
        };

        /**
         * Returns the calculated width to be used for the outer wrapper / viewport
         */
        var getViewportMaxWidth = function() {
            var width = '100%';
            if (slider.settings.slideWidth > 0) {
                if (slider.settings.mode === 'horizontal') {
                    width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
                } else {
                    width = slider.settings.slideWidth;
                }
            }
            return width;
        };

        /**
         * Returns the calculated width to be applied to each slide
         */
        var getSlideWidth = function() {
            var newElWidth = slider.settings.slideWidth, // start with any user-supplied slide width
                    wrapWidth = slider.viewport.width();    // get the current viewport width
            // if slide width was not supplied, or is larger than the viewport use the viewport width
            if (slider.settings.slideWidth === 0 ||
                    (slider.settings.slideWidth > wrapWidth && !slider.carousel) ||
                    slider.settings.mode === 'vertical') {
                newElWidth = wrapWidth;
                // if carousel, use the thresholds to determine the width
            } else if (slider.settings.maxSlides > 1 && slider.settings.mode === 'horizontal') {
                if (wrapWidth > slider.maxThreshold) {
                    return newElWidth;
                } else if (wrapWidth < slider.minThreshold) {
                    newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides;
                } else if (slider.settings.shrinkItems) {
                    newElWidth = Math.floor((wrapWidth + slider.settings.slideMargin) / (Math.ceil((wrapWidth + slider.settings.slideMargin) / (newElWidth + slider.settings.slideMargin))) - slider.settings.slideMargin);
                }
            }
            return newElWidth;
        };

        /**
         * Returns the number of slides currently visible in the viewport (includes partially visible slides)
         */
        var getNumberSlidesShowing = function() {
            var slidesShowing = 1,
                    childWidth = null;
            if (slider.settings.mode === 'horizontal' && slider.settings.slideWidth > 0) {
                // if viewport is smaller than minThreshold, return minSlides
                if (slider.viewport.width() < slider.minThreshold) {
                    slidesShowing = slider.settings.minSlides;
                    // if viewport is larger than maxThreshold, return maxSlides
                } else if (slider.viewport.width() > slider.maxThreshold) {
                    slidesShowing = slider.settings.maxSlides;
                    // if viewport is between min / max thresholds, divide viewport width by first child width
                } else {
                    childWidth = slider.children.first().width() + slider.settings.slideMargin;
                    slidesShowing = Math.floor((slider.viewport.width() +
                            slider.settings.slideMargin) / childWidth);
                }
                // if "vertical" mode, slides showing will always be minSlides
            } else if (slider.settings.mode === 'vertical') {
                slidesShowing = slider.settings.minSlides;
            }
            return slidesShowing;
        };

        /**
         * Returns the number of pages (one full viewport of slides is one "page")
         */
        var getPagerQty = function() {
            var pagerQty = 0,
                    breakPoint = 0,
                    counter = 0;
            // if moveSlides is specified by the user
            if (slider.settings.moveSlides > 0) {
                if (slider.settings.infiniteLoop) {
                    pagerQty = Math.ceil(slider.children.length / getMoveBy());
                } else {
                    // when breakpoint goes above children length, counter is the number of pages
                    while (breakPoint < slider.children.length) {
                        ++pagerQty;
                        breakPoint = counter + getNumberSlidesShowing();
                        counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing();
                    }
                }
                // if moveSlides is 0 (auto) divide children length by sides showing, then round up
            } else {
                pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing());
            }
            return pagerQty;
        };

        /**
         * Returns the number of individual slides by which to shift the slider
         */
        var getMoveBy = function() {
            // if moveSlides was set by the user and moveSlides is less than number of slides showing
            if (slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()) {
                return slider.settings.moveSlides;
            }
            // if moveSlides is 0 (auto)
            return getNumberSlidesShowing();
        };

        /**
         * Sets the slider's (el) left or top position
         */
        var setSlidePosition = function() {
            var position, lastChild, lastShowingIndex;
            // if last slide, not infinite loop, and number of children is larger than specified maxSlides
            if (slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop) {
                if (slider.settings.mode === 'horizontal') {
                    // get the last child's position
                    lastChild = slider.children.last();
                    position = lastChild.position();
                    // set the left position
                    setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0);
                } else if (slider.settings.mode === 'vertical') {
                    // get the last showing index's position
                    lastShowingIndex = slider.children.length - slider.settings.minSlides;
                    position = slider.children.eq(lastShowingIndex).position();
                    // set the top position
                    setPositionProperty(-position.top, 'reset', 0);
                }
                // if not last slide
            } else {
                // get the position of the first showing slide
                position = slider.children.eq(slider.active.index * getMoveBy()).position();
                // check for last slide
                if (slider.active.index === getPagerQty() - 1) {
                    slider.active.last = true;
                }
                // set the respective position
                if (position !== undefined) {
                    if (slider.settings.mode === 'horizontal') {
                        setPositionProperty(-position.left, 'reset', 0);
                    } else if (slider.settings.mode === 'vertical') {
                        setPositionProperty(-position.top, 'reset', 0);
                    }
                }
            }
        };

        /**
         * Sets the el's animating property position (which in turn will sometimes animate el).
         * If using CSS, sets the transform property. If not using CSS, sets the top / left property.
         *
         * @param value (int)
         *  - the animating property's value
         *
         * @param type (string) 'slide', 'reset', 'ticker'
         *  - the type of instance for which the function is being
         *
         * @param duration (int)
         *  - the amount of time (in ms) the transition should occupy
         *
         * @param params (array) optional
         *  - an optional parameter containing any variables that need to be passed in
         */
        var setPositionProperty = function(value, type, duration, params) {
            var animateObj, propValue;
            // use CSS transform
            if (slider.usingCSS) {
                // determine the translate3d value
                propValue = slider.settings.mode === 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)';
                // add the CSS transition-duration
                el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's');
                if (type === 'slide') {
                    // set the property value
                    el.css(slider.animProp, propValue);
                    if (duration !== 0) {
                        // bind a callback method - executes when CSS transition completes
                        el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
                            //make sure it's the correct one
                            if (!$(e.target).is(el)) {
                                return;
                            }
                            // unbind the callback
                            el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
                            updateAfterSlideTransition();
                        });
                    } else { //duration = 0
                        updateAfterSlideTransition();
                    }
                } else if (type === 'reset') {
                    el.css(slider.animProp, propValue);
                } else if (type === 'ticker') {
                    // make the transition use 'linear'
                    el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear');
                    el.css(slider.animProp, propValue);
                    if (duration !== 0) {
                        el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
                            //make sure it's the correct one
                            if (!$(e.target).is(el)) {
                                return;
                            }
                            // unbind the callback
                            el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
                            // reset the position
                            setPositionProperty(params.resetValue, 'reset', 0);
                            // start the loop again
                            tickerLoop();
                        });
                    } else { //duration = 0
                        setPositionProperty(params.resetValue, 'reset', 0);
                        tickerLoop();
                    }
                }
                // use JS animate
            } else {
                animateObj = {};
                animateObj[slider.animProp] = value;
                if (type === 'slide') {
                    el.animate(animateObj, duration, slider.settings.easing, function() {
                        updateAfterSlideTransition();
                    });
                } else if (type === 'reset') {
                    el.css(slider.animProp, value);
                } else if (type === 'ticker') {
                    el.animate(animateObj, duration, 'linear', function() {
                        setPositionProperty(params.resetValue, 'reset', 0);
                        // run the recursive loop after animation
                        tickerLoop();
                    });
                }
            }
        };

        /**
         * Populates the pager with proper amount of pages
         */
        var populatePager = function() {
            var pagerHtml = '',
                    linkContent = '',
                    pagerQty = getPagerQty();
            // loop through each pager item
            for (var i = 0; i < pagerQty; i++) {
                linkContent = '';
                // if a buildPager function is supplied, use it to get pager link value, else use index + 1
                if (slider.settings.buildPager && $.isFunction(slider.settings.buildPager) || slider.settings.pagerCustom) {
                    linkContent = slider.settings.buildPager(i);
                    slider.pagerEl.addClass('bx-custom-pager');
                } else {
                    linkContent = i + 1;
                    slider.pagerEl.addClass('bx-default-pager');
                }
                // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1;
                // add the markup to the string
                pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>';
            }
            // populate the pager element with pager links
            slider.pagerEl.html(pagerHtml);
        };

        /**
         * Appends the pager to the controls element
         */
        var appendPager = function() {
            if (!slider.settings.pagerCustom) {
                // create the pager DOM element
                slider.pagerEl = $('<div class="bx-pager" />');
                // if a pager selector was supplied, populate it with the pager
                if (slider.settings.pagerSelector) {
                    $(slider.settings.pagerSelector).html(slider.pagerEl);
                    // if no pager selector was supplied, add it after the wrapper
                } else {
                    slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl);
                }
                // populate the pager
                populatePager();
            } else {
                slider.pagerEl = $(slider.settings.pagerCustom);
            }
            // assign the pager click binding
            slider.pagerEl.on('click touchend', 'a', clickPagerBind);
        };

        /**
         * Appends prev / next controls to the controls element
         */
        var appendControls = function() {
            slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>');
            slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>');
            // bind click actions to the controls
            slider.controls.next.bind('click touchend', clickNextBind);
            slider.controls.prev.bind('click touchend', clickPrevBind);
            // if nextSelector was supplied, populate it
            if (slider.settings.nextSelector) {
                $(slider.settings.nextSelector).append(slider.controls.next);
            }
            // if prevSelector was supplied, populate it
            if (slider.settings.prevSelector) {
                $(slider.settings.prevSelector).append(slider.controls.prev);
            }
            // if no custom selectors were supplied
            if (!slider.settings.nextSelector && !slider.settings.prevSelector) {
                // add the controls to the DOM
                slider.controls.directionEl = $('<div class="bx-controls-direction" />');
                // add the control elements to the directionEl
                slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next);
                // slider.viewport.append(slider.controls.directionEl);
                slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl);
            }
        };

        /**
         * Appends start / stop auto controls to the controls element
         */
        var appendControlsAuto = function() {
            slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>');
            slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>');
            // add the controls to the DOM
            slider.controls.autoEl = $('<div class="bx-controls-auto" />');
            // bind click actions to the controls
            slider.controls.autoEl.on('click', '.bx-start', clickStartBind);
            slider.controls.autoEl.on('click', '.bx-stop', clickStopBind);
            // if autoControlsCombine, insert only the "start" control
            if (slider.settings.autoControlsCombine) {
                slider.controls.autoEl.append(slider.controls.start);
                // if autoControlsCombine is false, insert both controls
            } else {
                slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop);
            }
            // if auto controls selector was supplied, populate it with the controls
            if (slider.settings.autoControlsSelector) {
                $(slider.settings.autoControlsSelector).html(slider.controls.autoEl);
                // if auto controls selector was not supplied, add it after the wrapper
            } else {
                slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl);
            }
            // update the auto controls
            updateAutoControls(slider.settings.autoStart ? 'stop' : 'start');
        };

        /**
         * Appends image captions to the DOM
         */
        var appendCaptions = function() {
            // cycle through each child
            slider.children.each(function(index) {
                // get the image title attribute
                var title = $(this).find('img:first').attr('title');
                // append the caption
                if (title !== undefined && ('' + title).length) {
                    $(this).append('<div class="bx-caption"><span>' + title + '</span></div>');
                }
            });
        };

        /**
         * Click next binding
         *
         * @param e (event)
         *  - DOM event object
         */
        var clickNextBind = function(e) {
            e.preventDefault();
            if (slider.controls.el.hasClass('disabled')) {
                return;
            }
            // if auto show is running, stop it
            if (slider.settings.auto && slider.settings.stopAutoOnClick) {
                el.stopAuto();
            }
            el.goToNextSlide();
        };

        /**
         * Click prev binding
         *
         * @param e (event)
         *  - DOM event object
         */
        var clickPrevBind = function(e) {
            e.preventDefault();
            if (slider.controls.el.hasClass('disabled')) {
                return;
            }
            // if auto show is running, stop it
            if (slider.settings.auto && slider.settings.stopAutoOnClick) {
                el.stopAuto();
            }
            el.goToPrevSlide();
        };

        /**
         * Click start binding
         *
         * @param e (event)
         *  - DOM event object
         */
        var clickStartBind = function(e) {
            el.startAuto();
            e.preventDefault();
        };

        /**
         * Click stop binding
         *
         * @param e (event)
         *  - DOM event object
         */
        var clickStopBind = function(e) {
            el.stopAuto();
            e.preventDefault();
        };

        /**
         * Click pager binding
         *
         * @param e (event)
         *  - DOM event object
         */
        var clickPagerBind = function(e) {
            var pagerLink, pagerIndex;
            e.preventDefault();
            if (slider.controls.el.hasClass('disabled')) {
                return;
            }
            // if auto show is running, stop it
            if (slider.settings.auto && slider.settings.stopAutoOnClick) {
                el.stopAuto();
            }
            pagerLink = $(e.currentTarget);
            if (pagerLink.attr('data-slide-index') !== undefined) {
                pagerIndex = parseInt(pagerLink.attr('data-slide-index'));
                // if clicked pager link is not active, continue with the goToSlide call
                if (pagerIndex !== slider.active.index) {
                    el.goToSlide(pagerIndex);
                }
            }
        };

        /**
         * Updates the pager links with an active class
         *
         * @param slideIndex (int)
         *  - index of slide to make active
         */
        var updatePagerActive = function(slideIndex) {
            // if "short" pager type
            var len = slider.children.length; // nb of children
            if (slider.settings.pagerType === 'short') {
                if (slider.settings.maxSlides > 1) {
                    len = Math.ceil(slider.children.length / slider.settings.maxSlides);
                }
                slider.pagerEl.html((slideIndex + 1) + slider.settings.pagerShortSeparator + len);
                return;
            }
            // remove all pager active classes
            slider.pagerEl.find('a').removeClass('active');
            // apply the active class for all pagers
            slider.pagerEl.each(function(i, el) {
                $(el).find('a').eq(slideIndex).addClass('active');
            });
        };

        /**
         * Performs needed actions after a slide transition
         */
        var updateAfterSlideTransition = function() {
            // if infinite loop is true
            if (slider.settings.infiniteLoop) {
                var position = '';
                // first slide
                if (slider.active.index === 0) {
                    // set the new position
                    position = slider.children.eq(0).position();
                    // carousel, last slide
                } else if (slider.active.index === getPagerQty() - 1 && slider.carousel) {
                    position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position();
                    // last slide
                } else if (slider.active.index === slider.children.length - 1) {
                    position = slider.children.eq(slider.children.length - 1).position();
                }
                if (position) {
                    if (slider.settings.mode === 'horizontal') {
                        setPositionProperty(-position.left, 'reset', 0);
                    } else if (slider.settings.mode === 'vertical') {
                        setPositionProperty(-position.top, 'reset', 0);
                    }
                }
            }
            // declare that the transition is complete
            slider.working = false;
            // onSlideAfter callback
            slider.settings.onSlideAfter.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
        };

        /**
         * Updates the auto controls state (either active, or combined switch)
         *
         * @param state (string) "start", "stop"
         *  - the new state of the auto show
         */
        var updateAutoControls = function(state) {
            // if autoControlsCombine is true, replace the current control with the new state
            if (slider.settings.autoControlsCombine) {
                slider.controls.autoEl.html(slider.controls[state]);
                // if autoControlsCombine is false, apply the "active" class to the appropriate control
            } else {
                slider.controls.autoEl.find('a').removeClass('active');
                slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active');
            }
        };

        /**
         * Updates the direction controls (checks if either should be hidden)
         */
        var updateDirectionControls = function() {
            if (getPagerQty() === 1) {
                slider.controls.prev.addClass('disabled');
                slider.controls.next.addClass('disabled');
            } else if (!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd) {
                // if first slide
                if (slider.active.index === 0) {
                    slider.controls.prev.addClass('disabled');
                    slider.controls.next.removeClass('disabled');
                    // if last slide
                } else if (slider.active.index === getPagerQty() - 1) {
                    slider.controls.next.addClass('disabled');
                    slider.controls.prev.removeClass('disabled');
                    // if any slide in the middle
                } else {
                    slider.controls.prev.removeClass('disabled');
                    slider.controls.next.removeClass('disabled');
                }
            }
        };

        /**
         * Initializes the auto process
         */
        var initAuto = function() {
            // if autoDelay was supplied, launch the auto show using a setTimeout() call
            if (slider.settings.autoDelay > 0) {
                var timeout = setTimeout(el.startAuto, slider.settings.autoDelay);
                // if autoDelay was not supplied, start the auto show normally
            } else {
                el.startAuto();

                //add focus and blur events to ensure its running if timeout gets paused
                $(window).focus(function() {
                    el.startAuto();
                }).blur(function() {
                    el.stopAuto();
                });
            }
            // if autoHover is requested
            if (slider.settings.autoHover) {
                // on el hover
                el.hover(function() {
                    // if the auto show is currently playing (has an active interval)
                    if (slider.interval) {
                        // stop the auto show and pass true argument which will prevent control update
                        el.stopAuto(true);
                        // create a new autoPaused value which will be used by the relative "mouseout" event
                        slider.autoPaused = true;
                    }
                }, function() {
                    // if the autoPaused value was created be the prior "mouseover" event
                    if (slider.autoPaused) {
                        // start the auto show and pass true argument which will prevent control update
                        el.startAuto(true);
                        // reset the autoPaused value
                        slider.autoPaused = null;
                    }
                });
            }
        };

        /**
         * Initializes the ticker process
         */
        var initTicker = function() {
            var startPosition = 0,
                    position, transform, value, idx, ratio, property, newSpeed, totalDimens;
            // if autoDirection is "next", append a clone of the entire slider
            if (slider.settings.autoDirection === 'next') {
                el.append(slider.children.clone().addClass('bx-clone'));
                // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position
            } else {
                el.prepend(slider.children.clone().addClass('bx-clone'));
                position = slider.children.first().position();
                startPosition = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
            }
            setPositionProperty(startPosition, 'reset', 0);
            // do not allow controls in ticker mode
            slider.settings.pager = false;
            slider.settings.controls = false;
            slider.settings.autoControls = false;
            // if autoHover is requested
            if (slider.settings.tickerHover) {
                if (slider.usingCSS) {
                    idx = slider.settings.mode === 'horizontal' ? 4 : 5;
                    slider.viewport.hover(function() {
                        transform = el.css('-' + slider.cssPrefix + '-transform');
                        value = parseFloat(transform.split(',')[idx]);
                        setPositionProperty(value, 'reset', 0);
                    }, function() {
                        totalDimens = 0;
                        slider.children.each(function(index) {
                            totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
                        });
                        // calculate the speed ratio (used to determine the new speed to finish the paused animation)
                        ratio = slider.settings.speed / totalDimens;
                        // determine which property to use
                        property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
                        // calculate the new speed
                        newSpeed = ratio * (totalDimens - (Math.abs(parseInt(value))));
                        tickerLoop(newSpeed);
                    });
                } else {
                    // on el hover
                    slider.viewport.hover(function() {
                        el.stop();
                    }, function() {
                        // calculate the total width of children (used to calculate the speed ratio)
                        totalDimens = 0;
                        slider.children.each(function(index) {
                            totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
                        });
                        // calculate the speed ratio (used to determine the new speed to finish the paused animation)
                        ratio = slider.settings.speed / totalDimens;
                        // determine which property to use
                        property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
                        // calculate the new speed
                        newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property)))));
                        tickerLoop(newSpeed);
                    });
                }
            }
            // start the ticker loop
            tickerLoop();
        };

        /**
         * Runs a continuous loop, news ticker-style
         */
        var tickerLoop = function(resumeSpeed) {
            var speed = resumeSpeed ? resumeSpeed : slider.settings.speed,
                    position = {left: 0, top: 0},
                    reset = {left: 0, top: 0},
                    animateProperty, resetValue, params;

            // if "next" animate left position to last child, then reset left to 0
            if (slider.settings.autoDirection === 'next') {
                position = el.find('.bx-clone').first().position();
                // if "prev" animate left position to 0, then reset left to first non-clone child
            } else {
                reset = slider.children.first().position();
            }
            animateProperty = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
            resetValue = slider.settings.mode === 'horizontal' ? -reset.left : -reset.top;
            params = {resetValue: resetValue};
            setPositionProperty(animateProperty, 'ticker', speed, params);
        };

        /**
         * Check if el is on screen
         */
        var isOnScreen = function(el) {
            var win = $(window),
                    viewport = {
                        top: win.scrollTop(),
                        left: win.scrollLeft()
                    },
                    bounds = el.offset();

            viewport.right = viewport.left + win.width();
            viewport.bottom = viewport.top + win.height();
            bounds.right = bounds.left + el.outerWidth();
            bounds.bottom = bounds.top + el.outerHeight();

            return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
        };

        /**
         * Initializes keyboard events
         */
        var keyPress = function(e) {
            var activeElementTag = document.activeElement.tagName.toLowerCase(),
                    tagFilters = 'input|textarea',
                    p = new RegExp(activeElementTag, ['i']),
                    result = p.exec(tagFilters);

            if (result == null && isOnScreen(el)) {
                if (e.keyCode === 39) {
                    clickNextBind(e);
                    return false;
                } else if (e.keyCode === 37) {
                    clickPrevBind(e);
                    return false;
                }
            }
        };

        /**
         * Initializes touch events
         */
        var initTouch = function() {
            // initialize object to contain all touch values
            slider.touch = {
                start: {x: 0, y: 0},
                end: {x: 0, y: 0}
            };
            slider.viewport.bind('touchstart MSPointerDown pointerdown', onTouchStart);

            //for browsers that have implemented pointer events and fire a click after
            //every pointerup regardless of whether pointerup is on same screen location as pointerdown or not
            slider.viewport.on('click', '.bxslider a', function(e) {
                if (slider.viewport.hasClass('click-disabled')) {
                    e.preventDefault();
                    slider.viewport.removeClass('click-disabled');
                }
            });
        };

        /**
         * Event handler for "touchstart"
         *
         * @param e (event)
         *  - DOM event object
         */
        var onTouchStart = function(e) {
            //disable slider controls while user is interacting with slides to avoid slider freeze that happens on touch devices when a slide swipe happens immediately after interacting with slider controls
            slider.controls.el.addClass('disabled');

            if (slider.working) {
                e.preventDefault();
                slider.controls.el.removeClass('disabled');
            } else {
                // record the original position when touch starts
                slider.touch.originalPos = el.position();
                var orig = e.originalEvent,
                        touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig];
                // record the starting touch x, y coordinates
                slider.touch.start.x = touchPoints[0].pageX;
                slider.touch.start.y = touchPoints[0].pageY;

                if (slider.viewport.get(0).setPointerCapture) {
                    slider.pointerId = orig.pointerId;
                    slider.viewport.get(0).setPointerCapture(slider.pointerId);
                }
                // bind a "touchmove" event to the viewport
                slider.viewport.bind('touchmove MSPointerMove pointermove', onTouchMove);
                // bind a "touchend" event to the viewport
                slider.viewport.bind('touchend MSPointerUp pointerup', onTouchEnd);
                slider.viewport.bind('MSPointerCancel pointercancel', onPointerCancel);
            }
        };

        /**
         * Cancel Pointer for Windows Phone
         *
         * @param e (event)
         *  - DOM event object
         */
        var onPointerCancel = function(e) {
            /* onPointerCancel handler is needed to deal with situations when a touchend
             doesn't fire after a touchstart (this happens on windows phones only) */
            setPositionProperty(slider.touch.originalPos.left, 'reset', 0);

            //remove handlers
            slider.controls.el.removeClass('disabled');
            slider.viewport.unbind('MSPointerCancel pointercancel', onPointerCancel);
            slider.viewport.unbind('touchmove MSPointerMove pointermove', onTouchMove);
            slider.viewport.unbind('touchend MSPointerUp pointerup', onTouchEnd);
            if (slider.viewport.get(0).releasePointerCapture) {
                slider.viewport.get(0).releasePointerCapture(slider.pointerId);
            }
        };

        /**
         * Event handler for "touchmove"
         *
         * @param e (event)
         *  - DOM event object
         */
        var onTouchMove = function(e) {
            var orig = e.originalEvent,
                    touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
                    // if scrolling on y axis, do not prevent default
                    xMovement = Math.abs(touchPoints[0].pageX - slider.touch.start.x),
                    yMovement = Math.abs(touchPoints[0].pageY - slider.touch.start.y),
                    value = 0,
                    change = 0;

            // x axis swipe
            if ((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX) {
                e.preventDefault();
                // y axis swipe
            } else if ((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY) {
                e.preventDefault();
            }
            if (slider.settings.mode !== 'fade' && slider.settings.oneToOneTouch) {
                // if horizontal, drag along x axis
                if (slider.settings.mode === 'horizontal') {
                    change = touchPoints[0].pageX - slider.touch.start.x;
                    value = slider.touch.originalPos.left + change;
                    // if vertical, drag along y axis
                } else {
                    change = touchPoints[0].pageY - slider.touch.start.y;
                    value = slider.touch.originalPos.top + change;
                }
                setPositionProperty(value, 'reset', 0);
            }
        };

        /**
         * Event handler for "touchend"
         *
         * @param e (event)
         *  - DOM event object
         */
        var onTouchEnd = function(e) {
            slider.viewport.unbind('touchmove MSPointerMove pointermove', onTouchMove);
            //enable slider controls as soon as user stops interacing with slides
            slider.controls.el.removeClass('disabled');
            var orig = e.originalEvent,
                    touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
                    value = 0,
                    distance = 0;
            // record end x, y positions
            slider.touch.end.x = touchPoints[0].pageX;
            slider.touch.end.y = touchPoints[0].pageY;
            // if fade mode, check if absolute x distance clears the threshold
            if (slider.settings.mode === 'fade') {
                distance = Math.abs(slider.touch.start.x - slider.touch.end.x);
                if (distance >= slider.settings.swipeThreshold) {
                    if (slider.touch.start.x > slider.touch.end.x) {
                        el.goToNextSlide();
                    } else {
                        el.goToPrevSlide();
                    }
                    el.stopAuto();
                }
                // not fade mode
            } else {
                // calculate distance and el's animate property
                if (slider.settings.mode === 'horizontal') {
                    distance = slider.touch.end.x - slider.touch.start.x;
                    value = slider.touch.originalPos.left;
                } else {
                    distance = slider.touch.end.y - slider.touch.start.y;
                    value = slider.touch.originalPos.top;
                }
                // if not infinite loop and first / last slide, do not attempt a slide transition
                if (!slider.settings.infiniteLoop && ((slider.active.index === 0 && distance > 0) || (slider.active.last && distance < 0))) {
                    setPositionProperty(value, 'reset', 200);
                } else {
                    // check if distance clears threshold
                    if (Math.abs(distance) >= slider.settings.swipeThreshold) {
                        if (distance < 0) {
                            el.goToNextSlide();
                        } else {
                            el.goToPrevSlide();
                        }
                        el.stopAuto();
                    } else {
                        // el.animate(property, 200);
                        setPositionProperty(value, 'reset', 200);
                    }
                }
            }
            slider.viewport.unbind('touchend MSPointerUp pointerup', onTouchEnd);
            if (slider.viewport.get(0).releasePointerCapture) {
                slider.viewport.get(0).releasePointerCapture(slider.pointerId);
            }
        };

        /**
         * Window resize event callback
         */
        var resizeWindow = function(e) {
            // don't do anything if slider isn't initialized.
            if (!slider.initialized) {
                return;
            }
            // Delay if slider working.
            if (slider.working) {
                window.setTimeout(resizeWindow, 10);
            } else {
                // get the new window dimens (again, thank you IE)
                var windowWidthNew = $(window).width(),
                        windowHeightNew = $(window).height();
                // make sure that it is a true window resize
                // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements
                // are resized. Can you just die already?*
                if (windowWidth !== windowWidthNew || windowHeight !== windowHeightNew) {
                    // set the new window dimens
                    windowWidth = windowWidthNew;
                    windowHeight = windowHeightNew;
                    // update all dynamic elements
                    el.redrawSlider();
                    // Call user resize handler
                    slider.settings.onSliderResize.call(el, slider.active.index);
                }
            }
        };

        /**
         * Adds an aria-hidden=true attribute to each element
         *
         * @param startVisibleIndex (int)
         *  - the first visible element's index
         */
        var applyAriaHiddenAttributes = function(startVisibleIndex) {
            var numberOfSlidesShowing = getNumberSlidesShowing();
            // only apply attributes if the setting is enabled and not in ticker mode
            if (slider.settings.ariaHidden && !slider.settings.ticker) {
                // add aria-hidden=true to all elements
                slider.children.attr('aria-hidden', 'true');
                // get the visible elements and change to aria-hidden=false
                slider.children.slice(startVisibleIndex, startVisibleIndex + numberOfSlidesShowing).attr('aria-hidden', 'false');
            }
        };

        /**
         * Returns index according to present page range
         *
         * @param slideOndex (int)
         *  - the desired slide index
         */
        var setSlideIndex = function(slideIndex) {
            if (slideIndex < 0) {
                if (slider.settings.infiniteLoop) {
                    return getPagerQty() - 1;
                } else {
                    //we don't go to undefined slides
                    return slider.active.index;
                }
                // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop)
            } else if (slideIndex >= getPagerQty()) {
                if (slider.settings.infiniteLoop) {
                    return 0;
                } else {
                    //we don't move to undefined pages
                    return slider.active.index;
                }
                // set active index to requested slide
            } else {
                return slideIndex;
            }
        };

        /**
         * ===================================================================================
         * = PUBLIC FUNCTIONS
         * ===================================================================================
         */

        /**
         * Performs slide transition to the specified slide
         *
         * @param slideIndex (int)
         *  - the destination slide's index (zero-based)
         *
         * @param direction (string)
         *  - INTERNAL USE ONLY - the direction of travel ("prev" / "next")
         */
        el.goToSlide = function(slideIndex, direction) {
            // onSlideBefore, onSlideNext, onSlidePrev callbacks
            // Allow transition canceling based on returned value
            var performTransition = true,
                    moveBy = 0,
                    position = {left: 0, top: 0},
                    lastChild = null,
                    lastShowingIndex, eq, value, requestEl;
            // store the old index
            slider.oldIndex = slider.active.index;
            //set new index
            slider.active.index = setSlideIndex(slideIndex);

            // if plugin is currently in motion, ignore request
            if (slider.working || slider.active.index === slider.oldIndex) {
                return;
            }
            // declare that plugin is in motion
            slider.working = true;

            performTransition = slider.settings.onSlideBefore.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);

            // If transitions canceled, reset and return
            if (typeof (performTransition) !== 'undefined' && !performTransition) {
                slider.active.index = slider.oldIndex; // restore old index
                slider.working = false; // is not in motion
                return;
            }

            if (direction === 'next') {
                // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
                if (!slider.settings.onSlideNext.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
                    performTransition = false;
                }
            } else if (direction === 'prev') {
                // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
                if (!slider.settings.onSlidePrev.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
                    performTransition = false;
                }
            }

            // check if last slide
            slider.active.last = slider.active.index >= getPagerQty() - 1;
            // update the pager with active class
            if (slider.settings.pager || slider.settings.pagerCustom) {
                updatePagerActive(slider.active.index);
            }
            // // check for direction control update
            if (slider.settings.controls) {
                updateDirectionControls();
            }
            // if slider is set to mode: "fade"
            if (slider.settings.mode === 'fade') {
                // if adaptiveHeight is true and next height is different from current height, animate to the new height
                if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
                    slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
                }
                // fade out the visible child and reset its z-index value
                slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0});
                // fade in the newly requested slide
                slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex + 1).fadeIn(slider.settings.speed, function() {
                    $(this).css('zIndex', slider.settings.slideZIndex);
                    updateAfterSlideTransition();
                });
                // slider mode is not "fade"
            } else {
                // if adaptiveHeight is true and next height is different from current height, animate to the new height
                if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
                    slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
                }
                // if carousel and not infinite loop
                if (!slider.settings.infiniteLoop && slider.carousel && slider.active.last) {
                    if (slider.settings.mode === 'horizontal') {
                        // get the last child position
                        lastChild = slider.children.eq(slider.children.length - 1);
                        position = lastChild.position();
                        // calculate the position of the last slide
                        moveBy = slider.viewport.width() - lastChild.outerWidth();
                    } else {
                        // get last showing index position
                        lastShowingIndex = slider.children.length - slider.settings.minSlides;
                        position = slider.children.eq(lastShowingIndex).position();
                    }
                    // horizontal carousel, going previous while on first slide (infiniteLoop mode)
                } else if (slider.carousel && slider.active.last && direction === 'prev') {
                    // get the last child position
                    eq = slider.settings.moveSlides === 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides);
                    lastChild = el.children('.bx-clone').eq(eq);
                    position = lastChild.position();
                    // if infinite loop and "Next" is clicked on the last slide
                } else if (direction === 'next' && slider.active.index === 0) {
                    // get the last clone position
                    position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position();
                    slider.active.last = false;
                    // normal non-zero requests
                } else if (slideIndex >= 0) {
                    //parseInt is applied to allow floats for slides/page
                    requestEl = slideIndex * parseInt(getMoveBy());
                    position = slider.children.eq(requestEl).position();
                }

                /* If the position doesn't exist
                 * (e.g. if you destroy the slider on a next click),
                 * it doesn't throw an error.
                 */
                if (typeof (position) !== 'undefined') {
                    value = slider.settings.mode === 'horizontal' ? -(position.left - moveBy) : -position.top;
                    // plugin values to be animated
                    setPositionProperty(value, 'slide', slider.settings.speed);
                } else {
                    slider.working = false;
                }
            }
            if (slider.settings.ariaHidden) {
                applyAriaHiddenAttributes(slider.active.index * getMoveBy());
            }
        };

        /**
         * Transitions to the next slide in the show
         */
        el.goToNextSlide = function() {
            // if infiniteLoop is false and last page is showing, disregard call
            if (!slider.settings.infiniteLoop && slider.active.last) {
                return;
            }
            var pagerIndex = parseInt(slider.active.index) + 1;
            el.goToSlide(pagerIndex, 'next');
        };

        /**
         * Transitions to the prev slide in the show
         */
        el.goToPrevSlide = function() {
            // if infiniteLoop is false and last page is showing, disregard call
            if (!slider.settings.infiniteLoop && slider.active.index === 0) {
                return;
            }
            var pagerIndex = parseInt(slider.active.index) - 1;
            el.goToSlide(pagerIndex, 'prev');
        };

        /**
         * Starts the auto show
         *
         * @param preventControlUpdate (boolean)
         *  - if true, auto controls state will not be updated
         */
        el.startAuto = function(preventControlUpdate) {
            // if an interval already exists, disregard call
            if (slider.interval) {
                return;
            }
            // create an interval
            slider.interval = setInterval(function() {
                if (slider.settings.autoDirection === 'next') {
                    el.goToNextSlide();
                } else {
                    el.goToPrevSlide();
                }
            }, slider.settings.pause);
            // if auto controls are displayed and preventControlUpdate is not true
            if (slider.settings.autoControls && preventControlUpdate !== true) {
                updateAutoControls('stop');
            }
        };

        /**
         * Stops the auto show
         *
         * @param preventControlUpdate (boolean)
         *  - if true, auto controls state will not be updated
         */
        el.stopAuto = function(preventControlUpdate) {
            // if no interval exists, disregard call
            if (!slider.interval) {
                return;
            }
            // clear the interval
            clearInterval(slider.interval);
            slider.interval = null;
            // if auto controls are displayed and preventControlUpdate is not true
            if (slider.settings.autoControls && preventControlUpdate !== true) {
                updateAutoControls('start');
            }
        };

        /**
         * Returns current slide index (zero-based)
         */
        el.getCurrentSlide = function() {
            return slider.active.index;
        };

        /**
         * Returns current slide element
         */
        el.getCurrentSlideElement = function() {
            return slider.children.eq(slider.active.index);
        };

        /**
         * Returns a slide element
         * @param index (int)
         *  - The index (zero-based) of the element you want returned.
         */
        el.getSlideElement = function(index) {
            return slider.children.eq(index);
        };

        /**
         * Returns number of slides in show
         */
        el.getSlideCount = function() {
            return slider.children.length;
        };

        /**
         * Return slider.working variable
         */
        el.isWorking = function() {
            return slider.working;
        };

        /**
         * Update all dynamic slider elements
         */
        el.redrawSlider = function() {
            // resize all children in ratio to new screen size
            slider.children.add(el.find('.bx-clone')).outerWidth(getSlideWidth());
            // adjust the height
            slider.viewport.css('height', getViewportHeight());
            // update the slide position
            if (!slider.settings.ticker) {
                setSlidePosition();
            }
            // if active.last was true before the screen resize, we want
            // to keep it last no matter what screen size we end on
            if (slider.active.last) {
                slider.active.index = getPagerQty() - 1;
            }
            // if the active index (page) no longer exists due to the resize, simply set the index as last
            if (slider.active.index >= getPagerQty()) {
                slider.active.last = true;
            }
            // if a pager is being displayed and a custom pager is not being used, update it
            if (slider.settings.pager && !slider.settings.pagerCustom) {
                populatePager();
                updatePagerActive(slider.active.index);
            }
            if (slider.settings.ariaHidden) {
                applyAriaHiddenAttributes(slider.active.index * getMoveBy());
            }
        };

        /**
         * Destroy the current instance of the slider (revert everything back to original state)
         */
        el.destroySlider = function() {
            // don't do anything if slider has already been destroyed
            if (!slider.initialized) {
                return;
            }
            slider.initialized = false;
            $('.bx-clone', this).remove();
            slider.children.each(function() {
                if ($(this).data('origStyle') !== undefined) {
                    $(this).attr('style', $(this).data('origStyle'));
                } else {
                    $(this).removeAttr('style');
                }
            });
            if ($(this).data('origStyle') !== undefined) {
                this.attr('style', $(this).data('origStyle'));
            } else {
                $(this).removeAttr('style');
            }
            $(this).unwrap().unwrap();
            if (slider.controls.el) {
                slider.controls.el.remove();
            }
            if (slider.controls.next) {
                slider.controls.next.remove();
            }
            if (slider.controls.prev) {
                slider.controls.prev.remove();
            }
            if (slider.pagerEl && slider.settings.controls && !slider.settings.pagerCustom) {
                slider.pagerEl.remove();
            }
            $('.bx-caption', this).remove();
            if (slider.controls.autoEl) {
                slider.controls.autoEl.remove();
            }
            clearInterval(slider.interval);
            if (slider.settings.responsive) {
                $(window).unbind('resize', resizeWindow);
            }
            if (slider.settings.keyboardEnabled) {
                $(document).unbind('keydown', keyPress);
            }
            //remove self reference in data
            $(this).removeData('bxSlider');
        };

        /**
         * Reload the slider (revert all DOM changes, and re-initialize)
         */
        el.reloadSlider = function(settings) {
            if (settings !== undefined) {
                options = settings;
            }
            el.destroySlider();
            init();
            //store reference to self in order to access public functions later
            $(el).data('bxSlider', this);
        };

        init();

        $(el).data('bxSlider', this);

        // returns the current jQuery object
        return this;
    };


    var bxSlider = jQuery.fn.bxSlider;
    var $window = $(window);

    jQuery.fn.bxSlider = function() {

        var slider = bxSlider.apply(this, arguments);

        if (!this.length || !arguments[0].mouseDrag) {
            return slider;
        }

        var posX;
        var $viewport = this.parents('.bx-viewport');

        $viewport
                .on('dragstart', dragHandler)
                .on('mousedown', mouseDownHandler);

        function dragHandler(e) {
            e.preventDefault();
        }

        function mouseDownHandler(e) {

            posX = e.pageX;

            $window.on('mousemove.bxSlider', mouseMoveHandler);
        }

        function mouseMoveHandler(e) {

            if (posX < e.pageX) {
                slider.goToPrevSlide();
            } else {
                slider.goToNextSlide();
            }

            $window.off('mousemove.bxSlider');
        }

        return slider;
    };

})(jQuery);
// source --> https://www.silviakelly.it/wp-content/plugins/woo-product-grid-list-design/js/imagesloaded.min.js?ver=1.0.8 
/*!
 * imagesLoaded PACKAGED v4.1.1
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

!function(t, e){"function" == typeof define && define.amd?define("ev-emitter/ev-emitter", e):"object" == typeof module && module.exports?module.exports = e():t.EvEmitter = e()}("undefined" != typeof window?window:this, function(){function t(){}var e = t.prototype; return e.on = function(t, e){if (t && e){var i = this._events = this._events || {}, n = i[t] = i[t] || []; return - 1 == n.indexOf(e) && n.push(e), this}}, e.once = function(t, e){if (t && e){this.on(t, e); var i = this._onceEvents = this._onceEvents || {}, n = i[t] = i[t] || {}; return n[e] = !0, this}}, e.off = function(t, e){var i = this._events && this._events[t]; if (i && i.length){var n = i.indexOf(e); return - 1 != n && i.splice(n, 1), this}}, e.emitEvent = function(t, e){var i = this._events && this._events[t]; if (i && i.length){var n = 0, o = i[n]; e = e || []; for (var r = this._onceEvents && this._onceEvents[t]; o; ){var s = r && r[o]; s && (this.off(t, o), delete r[o]), o.apply(this, e), n += s?0:1, o = i[n]}return this}}, t}), function(t, e){"use strict"; "function" == typeof define && define.amd?define(["ev-emitter/ev-emitter"], function(i){return e(t, i)}):"object" == typeof module && module.exports?module.exports = e(t, require("ev-emitter")):t.imagesLoaded = e(t, t.EvEmitter)}(window, function(t, e){function i(t, e){for (var i in e)t[i] = e[i]; return t}function n(t){var e = []; if (Array.isArray(t))e = t;  else if ("number" == typeof t.length)for (var i = 0; i < t.length; i++)e.push(t[i]);  else e.push(t); return e}function o(t, e, r){return this instanceof o?("string" == typeof t && (t = document.querySelectorAll(t)), this.elements = n(t), this.options = i({}, this.options), "function" == typeof e?r = e:i(this.options, e), r && this.on("always", r), this.getImages(), h && (this.jqDeferred = new h.Deferred), void setTimeout(function(){this.check()}.bind(this))):new o(t, e, r)}function r(t){this.img = t}function s(t, e){this.url = t, this.element = e, this.img = new Image}var h = t.jQuery, a = t.console; o.prototype = Object.create(e.prototype), o.prototype.options = {}, o.prototype.getImages = function(){this.images = [], this.elements.forEach(this.addElementImages, this)}, o.prototype.addElementImages = function(t){"IMG" == t.nodeName && this.addImage(t), this.options.background === !0 && this.addElementBackgroundImages(t); var e = t.nodeType; if (e && d[e]){for (var i = t.querySelectorAll("img"), n = 0; n < i.length; n++){var o = i[n]; this.addImage(o)}if ("string" == typeof this.options.background){var r = t.querySelectorAll(this.options.background); for (n = 0; n < r.length; n++){var s = r[n]; this.addElementBackgroundImages(s)}}}}; var d = {1:!0, 9:!0, 11:!0}; return o.prototype.addElementBackgroundImages = function(t){var e = getComputedStyle(t); if (e)for (var i = /url\((['"])?(.*?)\1\)/gi, n = i.exec(e.backgroundImage); null !== n; ){var o = n && n[2]; o && this.addBackground(o, t), n = i.exec(e.backgroundImage)}}, o.prototype.addImage = function(t){var e = new r(t); this.images.push(e)}, o.prototype.addBackground = function(t, e){var i = new s(t, e); this.images.push(i)}, o.prototype.check = function(){function t(t, i, n){setTimeout(function(){e.progress(t, i, n)})}var e = this; return this.progressedCount = 0, this.hasAnyBroken = !1, this.images.length?void this.images.forEach(function(e){e.once("progress", t), e.check()}):void this.complete()}, o.prototype.progress = function(t, e, i){this.progressedCount++, this.hasAnyBroken = this.hasAnyBroken || !t.isLoaded, this.emitEvent("progress", [this, t, e]), this.jqDeferred && this.jqDeferred.notify && this.jqDeferred.notify(this, t), this.progressedCount == this.images.length && this.complete(), this.options.debug && a && a.log("progress: " + i, t, e)}, o.prototype.complete = function(){var t = this.hasAnyBroken?"fail":"done"; if (this.isComplete = !0, this.emitEvent(t, [this]), this.emitEvent("always", [this]), this.jqDeferred){var e = this.hasAnyBroken?"reject":"resolve"; this.jqDeferred[e](this)}}, r.prototype = Object.create(e.prototype), r.prototype.check = function(){var t = this.getIsImageComplete(); return t?void this.confirm(0 !== this.img.naturalWidth, "naturalWidth"):(this.proxyImage = new Image, this.proxyImage.addEventListener("load", this), this.proxyImage.addEventListener("error", this), this.img.addEventListener("load", this), this.img.addEventListener("error", this), void(this.proxyImage.src = this.img.src))}, r.prototype.getIsImageComplete = function(){return this.img.complete && void 0 !== this.img.naturalWidth}, r.prototype.confirm = function(t, e){this.isLoaded = t, this.emitEvent("progress", [this, this.img, e])}, r.prototype.handleEvent = function(t){var e = "on" + t.type; this[e] && this[e](t)}, r.prototype.onload = function(){this.confirm(!0, "onload"), this.unbindEvents()}, r.prototype.onerror = function(){this.confirm(!1, "onerror"), this.unbindEvents()}, r.prototype.unbindEvents = function(){this.proxyImage.removeEventListener("load", this), this.proxyImage.removeEventListener("error", this), this.img.removeEventListener("load", this), this.img.removeEventListener("error", this)}, s.prototype = Object.create(r.prototype), s.prototype.check = function(){this.img.addEventListener("load", this), this.img.addEventListener("error", this), this.img.src = this.url; var t = this.getIsImageComplete(); t && (this.confirm(0 !== this.img.naturalWidth, "naturalWidth"), this.unbindEvents())}, s.prototype.unbindEvents = function(){this.img.removeEventListener("load", this), this.img.removeEventListener("error", this)}, s.prototype.confirm = function(t, e){this.isLoaded = t, this.emitEvent("progress", [this, this.element, e])}, o.makeJQueryPlugin = function(e){e = e || t.jQuery, e && (h = e, h.fn.imagesLoaded = function(t, e){var i = new o(this, t, e); return i.jqDeferred.promise(h(this))})}, o.makeJQueryPlugin(), o});
// source --> https://www.silviakelly.it/wp-content/plugins/woo-product-grid-list-design/js/jquery.mCustomScrollbar.concat.min.js?ver=1.0.8 
/* == jquery mousewheel plugin == Version: 3.1.11, License: MIT License (MIT) */
!function(a){"function" == typeof define && define.amd?define(["jquery"], a):"object" == typeof exports?module.exports = a:a(jQuery)}(function(a){function b(b){var g = b || window.event, h = i.call(arguments, 1), j = 0, l = 0, m = 0, n = 0, o = 0, p = 0; if (b = a.event.fix(g), b.type = "mousewheel", "detail"in g && (m = - 1 * g.detail), "wheelDelta"in g && (m = g.wheelDelta), "wheelDeltaY"in g && (m = g.wheelDeltaY), "wheelDeltaX"in g && (l = - 1 * g.wheelDeltaX), "axis"in g && g.axis === g.HORIZONTAL_AXIS && (l = - 1 * m, m = 0), j = 0 === m?l:m, "deltaY"in g && (m = - 1 * g.deltaY, j = m), "deltaX"in g && (l = g.deltaX, 0 === m && (j = - 1 * l)), 0 !== m || 0 !== l){if (1 === g.deltaMode){var q = a.data(this, "mousewheel-line-height"); j *= q, m *= q, l *= q} else if (2 === g.deltaMode){var r = a.data(this, "mousewheel-page-height"); j *= r, m *= r, l *= r}if (n = Math.max(Math.abs(m), Math.abs(l)), (!f || f > n) && (f = n, d(g, n) && (f /= 40)), d(g, n) && (j /= 40, l /= 40, m /= 40), j = Math[j >= 1?"floor":"ceil"](j / f), l = Math[l >= 1?"floor":"ceil"](l / f), m = Math[m >= 1?"floor":"ceil"](m / f), k.settings.normalizeOffset && this.getBoundingClientRect){var s = this.getBoundingClientRect(); o = b.clientX - s.left, p = b.clientY - s.top}return b.deltaX = l, b.deltaY = m, b.deltaFactor = f, b.offsetX = o, b.offsetY = p, b.deltaMode = 0, h.unshift(b, j, l, m), e && clearTimeout(e), e = setTimeout(c, 200), (a.event.dispatch || a.event.handle).apply(this, h)}}function c(){f = null}function d(a, b){return k.settings.adjustOldDeltas && "mousewheel" === a.type && b % 120 === 0}var e, f, g = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], h = "onwheel"in document || document.documentMode >= 9?["wheel"]:["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], i = Array.prototype.slice; if (a.event.fixHooks)for (var j = g.length; j; )a.event.fixHooks[g[--j]] = a.event.mouseHooks; var k = a.event.special.mousewheel = {version:"3.1.11", setup:function(){if (this.addEventListener)for (var c = h.length; c; )this.addEventListener(h[--c], b, !1);  else this.onmousewheel = b; a.data(this, "mousewheel-line-height", k.getLineHeight(this)), a.data(this, "mousewheel-page-height", k.getPageHeight(this))}, teardown:function(){if (this.removeEventListener)for (var c = h.length; c; )this.removeEventListener(h[--c], b, !1);  else this.onmousewheel = null; a.removeData(this, "mousewheel-line-height"), a.removeData(this, "mousewheel-page-height")}, getLineHeight:function(b){var c = a(b)["offsetParent"in a.fn?"offsetParent":"parent"](); return c.length || (c = a("body")), parseInt(c.css("fontSize"), 10)}, getPageHeight:function(b){return a(b).height()}, settings:{adjustOldDeltas:!0, normalizeOffset:!0}}; a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel", a):this.trigger("mousewheel")}, unmousewheel:function(a){return this.unbind("mousewheel", a)}})});
        /* == malihu jquery custom scrollbar plugin == Version: 3.0.0, License: MIT License (MIT) */
                (function(h, l, m, d){var e = "mCustomScrollbar", a = "mCS", k = ".mCustomScrollbar", f = {setWidth:false, setHeight:false, setTop:0, setLeft:0, axis:"y", scrollbarPosition:"inside", scrollInertia:950, autoDraggerLength:true, autoHideScrollbar:false, autoExpandScrollbar:false, alwaysShowScrollbar:0, snapAmount:null, snapOffset:0, mouseWheel:{enable:true, scrollAmount:"auto", axis:"y", preventDefault:false, deltaFactor:"auto", normalizeDelta:false, invert:false}, scrollButtons:{enable:false, scrollType:"stepless", scrollAmount:"auto"}, keyboard:{enable:true, scrollType:"stepless", scrollAmount:"auto"}, contentTouchScroll:25, advanced:{autoExpandHorizontalScroll:false, autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']", updateOnContentResize:true, updateOnImageLoad:true, updateOnSelectorChange:false}, theme:"light", callbacks:{onScrollStart:false, onScroll:false, onTotalScroll:false, onTotalScrollBack:false, whileScrolling:false, onTotalScrollOffset:0, onTotalScrollBackOffset:0, alwaysTriggerOffsets:true}, live:false}, j = 0, o = {}, c = function(p){if (o[p]){clearTimeout(o[p]); g._delete.call(null, o[p])}}, i = (l.attachEvent && !l.addEventListener)?1:0, n = false, b = {init:function(q){var q = h.extend(true, {}, f, q), p = g._selector.call(this); var s = this.selector || k; if (q.live){var r = h(s); if (q.live === "off"){c(s); return}o[s] = setTimeout(function(){r.mCustomScrollbar(q); if (q.live === "once" && r.length){c(s)}}, 500)} else{c(s)}q.setWidth = (q.set_width)?q.set_width:q.setWidth; q.setHeight = (q.set_height)?q.set_height:q.setHeight; q.axis = (q.horizontalScroll)?"x":g._findAxis.call(null, q.axis); q.scrollInertia = q.scrollInertia < 17?17:q.scrollInertia; if (typeof q.mouseWheel !== "object" && q.mouseWheel == true){q.mouseWheel = {enable:true, scrollAmount:"auto", axis:"y", preventDefault:false, deltaFactor:"auto", normalizeDelta:false, invert:false}}q.mouseWheel.scrollAmount = !q.mouseWheelPixels?q.mouseWheel.scrollAmount:q.mouseWheelPixels; q.mouseWheel.normalizeDelta = !q.advanced.normalizeMouseWheelDelta?q.mouseWheel.normalizeDelta:q.advanced.normalizeMouseWheelDelta; q.scrollButtons.scrollType = g._findScrollButtonsType.call(null, q.scrollButtons.scrollType); g._theme.call(null, q); return h(p).each(function(){var u = h(this); if (!u.data(a)){u.data(a, {idx:++j, opt:q, scrollRatio:{y:null, x:null}, overflowed:null, bindEvents:false, tweenRunning:false, sequential:{}, langDir:u.css("direction"), cbOffsets:null, trigger:null}); var w = u.data(a).opt, v = u.data("mcs-axis"), t = u.data("mcs-scrollbar-position"), x = u.data("mcs-theme"); if (v){w.axis = v}if (t){w.scrollbarPosition = t}if (x){w.theme = x; g._theme.call(null, w)}g._pluginMarkup.call(this); b.update.call(null, u)}})}, update:function(q){var p = q || g._selector.call(this); return h(p).each(function(){var t = h(this); if (t.data(a)){var v = t.data(a), u = v.opt, r = h("#mCSB_" + v.idx + "_container"), s = [h("#mCSB_" + v.idx + "_dragger_vertical"), h("#mCSB_" + v.idx + "_dragger_horizontal")]; if (v.tweenRunning){g._stop.call(null, t)}if (t.hasClass("mCS_disabled")){t.removeClass("mCS_disabled")}if (t.hasClass("mCS_destroyed")){t.removeClass("mCS_destroyed")}g._maxHeight.call(this); g._expandContentHorizontally.call(this); if (u.axis !== "y" && !u.advanced.autoExpandHorizontalScroll){r.css("width", g._contentWidth(r.children()))}v.overflowed = g._overflowed.call(this); g._scrollbarVisibility.call(this); if (u.autoDraggerLength){g._setDraggerLength.call(this)}g._scrollRatio.call(this); g._bindEvents.call(this); var w = [Math.abs(r[0].offsetTop), Math.abs(r[0].offsetLeft)]; if (u.axis !== "x"){if (!v.overflowed[0]){g._resetContentPosition.call(this); if (u.axis === "y"){g._unbindEvents.call(this)} else{if (u.axis === "yx" && v.overflowed[1]){g._scrollTo.call(this, t, w[1].toString(), {dir:"x", dur:0, overwrite:"none"})}}} else{if (s[0].height() > s[0].parent().height()){g._resetContentPosition.call(this)} else{g._scrollTo.call(this, t, w[0].toString(), {dir:"y", dur:0, overwrite:"none"})}}}if (u.axis !== "y"){if (!v.overflowed[1]){g._resetContentPosition.call(this); if (u.axis === "x"){g._unbindEvents.call(this)} else{if (u.axis === "yx" && v.overflowed[0]){g._scrollTo.call(this, t, w[0].toString(), {dir:"y", dur:0, overwrite:"none"})}}} else{if (s[1].width() > s[1].parent().width()){g._resetContentPosition.call(this)} else{g._scrollTo.call(this, t, w[1].toString(), {dir:"x", dur:0, overwrite:"none"})}}}g._autoUpdate.call(this)}})}, scrollTo:function(r, q){if (typeof r == "undefined" || r == null){return}var p = g._selector.call(this); return h(p).each(function(){var u = h(this); if (u.data(a)){var x = u.data(a), w = x.opt, v = {trigger:"external", scrollInertia:w.scrollInertia, scrollEasing:"mcsEaseInOut", moveDragger:false, callbacks:true, onStart:true, onUpdate:true, onComplete:true}, s = h.extend(true, {}, v, q), y = g._arr.call(this, r), t = s.scrollInertia < 17?17:s.scrollInertia; y[0] = g._to.call(this, y[0], "y"); y[1] = g._to.call(this, y[1], "x"); if (s.moveDragger){y[0] *= x.scrollRatio.y; y[1] *= x.scrollRatio.x}s.dur = t; setTimeout(function(){if (y[0] !== null && typeof y[0] !== "undefined" && w.axis !== "x" && x.overflowed[0]){s.dir = "y"; s.overwrite = "all"; g._scrollTo.call(this, u, y[0].toString(), s)}if (y[1] !== null && typeof y[1] !== "undefined" && w.axis !== "y" && x.overflowed[1]){s.dir = "x"; s.overwrite = "none"; g._scrollTo.call(this, u, y[1].toString(), s)}}, 60)}})}, stop:function(){var p = g._selector.call(this); return h(p).each(function(){var q = h(this); if (q.data(a)){g._stop.call(null, q)}})}, disable:function(q){var p = g._selector.call(this); return h(p).each(function(){var r = h(this); if (r.data(a)){var t = r.data(a), s = t.opt; g._autoUpdate.call(this, "remove"); g._unbindEvents.call(this); if (q){g._resetContentPosition.call(this)}g._scrollbarVisibility.call(this, true); r.addClass("mCS_disabled")}})}, destroy:function(){var p = g._selector.call(this); return h(p).each(function(){var s = h(this); if (s.data(a)){var u = s.data(a), t = u.opt, q = h("#mCSB_" + u.idx), r = h("#mCSB_" + u.idx + "_container"), v = h(".mCSB_" + u.idx + "_scrollbar"); if (t.live){c(p)}g._autoUpdate.call(this, "remove"); g._unbindEvents.call(this); g._resetContentPosition.call(this); s.removeData(a); g._delete.call(null, this.mcs); v.remove(); q.replaceWith(r.contents()); s.removeClass(e + " _" + a + "_" + u.idx + " mCS-autoHide mCS-dir-rtl mCS_no_scrollbar mCS_disabled").addClass("mCS_destroyed")}})}}, g = {_selector:function(){return(typeof h(this.selector) !== "object" || h(this.selector).length < 1)?k:this.selector}, _theme:function(s){var r = ["rounded", "rounded-dark", "rounded-dots", "rounded-dots-dark"], q = ["rounded-dots", "rounded-dots-dark", "3d", "3d-dark", "3d-thick", "3d-thick-dark", "inset", "inset-dark", "inset-2", "inset-2-dark", "inset-3", "inset-3-dark"], p = ["minimal", "minimal-dark"], u = ["minimal", "minimal-dark"], t = ["minimal", "minimal-dark"]; s.autoDraggerLength = h.inArray(s.theme, r) > - 1?false:s.autoDraggerLength; s.autoExpandScrollbar = h.inArray(s.theme, q) > - 1?false:s.autoExpandScrollbar; s.scrollButtons.enable = h.inArray(s.theme, p) > - 1?false:s.scrollButtons.enable; s.autoHideScrollbar = h.inArray(s.theme, u) > - 1?true:s.autoHideScrollbar; s.scrollbarPosition = h.inArray(s.theme, t) > - 1?"outside":s.scrollbarPosition}, _findAxis:function(p){return(p === "yx" || p === "xy" || p === "auto")?"yx":(p === "x" || p === "horizontal")?"x":"y"}, _findScrollButtonsType:function(p){return(p === "stepped" || p === "pixels" || p === "step" || p === "click")?"stepped":"stepless"}, _pluginMarkup:function(){var y = h(this), x = y.data(a), r = x.opt, t = r.autoExpandScrollbar?" mCSB_scrollTools_onDrag_expand":"", B = ["<div id='mCSB_" + x.idx + "_scrollbar_vertical' class='mCSB_scrollTools mCSB_" + x.idx + "_scrollbar mCS-" + r.theme + " mCSB_scrollTools_vertical" + t + "'><div class='mCSB_draggerContainer'><div id='mCSB_" + x.idx + "_dragger_vertical' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>", "<div id='mCSB_" + x.idx + "_scrollbar_horizontal' class='mCSB_scrollTools mCSB_" + x.idx + "_scrollbar mCS-" + r.theme + " mCSB_scrollTools_horizontal" + t + "'><div class='mCSB_draggerContainer'><div id='mCSB_" + x.idx + "_dragger_horizontal' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"], u = r.axis === "yx"?"mCSB_vertical_horizontal":r.axis === "x"?"mCSB_horizontal":"mCSB_vertical", w = r.axis === "yx"?B[0] + B[1]:r.axis === "x"?B[1]:B[0], v = r.axis === "yx"?"<div id='mCSB_" + x.idx + "_container_wrapper' class='mCSB_container_wrapper' />":"", s = r.autoHideScrollbar?" mCS-autoHide":"", p = (r.axis !== "x" && x.langDir === "rtl")?" mCS-dir-rtl":""; if (r.setWidth){y.css("width", r.setWidth)}if (r.setHeight){y.css("height", r.setHeight)}r.setLeft = (r.axis !== "y" && x.langDir === "rtl")?"989999px":r.setLeft; y.addClass(e + " _" + a + "_" + x.idx + s + p).wrapInner("<div id='mCSB_" + x.idx + "' class='mCustomScrollBox mCS-" + r.theme + " " + u + "'><div id='mCSB_" + x.idx + "_container' class='mCSB_container' style='position:relative; top:" + r.setTop + "; left:" + r.setLeft + ";' dir=" + x.langDir + " /></div>"); var q = h("#mCSB_" + x.idx), z = h("#mCSB_" + x.idx + "_container"); if (r.axis !== "y" && !r.advanced.autoExpandHorizontalScroll){z.css("width", g._contentWidth(z.children()))}if (r.scrollbarPosition === "outside"){if (y.css("position") === "static"){y.css("position", "relative")}y.css("overflow", "visible"); q.addClass("mCSB_outside").after(w)} else{q.addClass("mCSB_inside").append(w); z.wrap(v)}g._scrollButtons.call(this); var A = [h("#mCSB_" + x.idx + "_dragger_vertical"), h("#mCSB_" + x.idx + "_dragger_horizontal")]; A[0].css("min-height", A[0].height()); A[1].css("min-width", A[1].width())}, _contentWidth:function(p){return Math.max.apply(Math, p.map(function(){return h(this).outerWidth(true)}).get())}, _expandContentHorizontally:function(){var q = h(this), s = q.data(a), r = s.opt, p = h("#mCSB_" + s.idx + "_container"); if (r.advanced.autoExpandHorizontalScroll && r.axis !== "y"){p.css({position:"absolute", width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:(Math.ceil(p[0].getBoundingClientRect().right + 0.4) - Math.floor(p[0].getBoundingClientRect().left)), position:"relative"}).unwrap()}}, _scrollButtons:function(){var s = h(this), u = s.data(a), t = u.opt, q = h(".mCSB_" + u.idx + "_scrollbar:first"), r = ["<a href='#' class='mCSB_buttonUp' oncontextmenu='return false;' />", "<a href='#' class='mCSB_buttonDown' oncontextmenu='return false;' />", "<a href='#' class='mCSB_buttonLeft' oncontextmenu='return false;' />", "<a href='#' class='mCSB_buttonRight' oncontextmenu='return false;' />"], p = [(t.axis === "x"?r[2]:r[0]), (t.axis === "x"?r[3]:r[1]), r[2], r[3]]; if (t.scrollButtons.enable){q.prepend(p[0]).append(p[1]).next(".mCSB_scrollTools").prepend(p[2]).append(p[3])}}, _maxHeight:function(){var t = h(this), w = t.data(a), v = w.opt, r = h("#mCSB_" + w.idx), q = t.css("max-height"), s = q.indexOf("%") !== - 1, p = t.css("box-sizing"); if (q !== "none"){var u = s?t.parent().height() * parseInt(q) / 100:parseInt(q); if (p === "border-box"){u -= ((t.innerHeight() - t.height()) + (t.outerHeight() - t.innerHeight()))}r.css("max-height", Math.round(u))}}, _setDraggerLength:function(){var u = h(this), s = u.data(a), p = h("#mCSB_" + s.idx), v = h("#mCSB_" + s.idx + "_container"), y = [h("#mCSB_" + s.idx + "_dragger_vertical"), h("#mCSB_" + s.idx + "_dragger_horizontal")], t = [p.height() / v.outerHeight(false), p.width() / v.outerWidth(false)], q = [parseInt(y[0].css("min-height")), Math.round(t[0] * y[0].parent().height()), parseInt(y[1].css("min-width")), Math.round(t[1] * y[1].parent().width())], r = i && (q[1] < q[0])?q[0]:q[1], x = i && (q[3] < q[2])?q[2]:q[3]; y[0].css({height:r, "max-height":(y[0].parent().height() - 10)}).find(".mCSB_dragger_bar").css({"line-height":q[0] + "px"}); y[1].css({width:x, "max-width":(y[1].parent().width() - 10)})}, _scrollRatio:function(){var t = h(this), v = t.data(a), q = h("#mCSB_" + v.idx), r = h("#mCSB_" + v.idx + "_container"), s = [h("#mCSB_" + v.idx + "_dragger_vertical"), h("#mCSB_" + v.idx + "_dragger_horizontal")], u = [r.outerHeight(false) - q.height(), r.outerWidth(false) - q.width()], p = [u[0] / (s[0].parent().height() - s[0].height()), u[1] / (s[1].parent().width() - s[1].width())]; v.scrollRatio = {y:p[0], x:p[1]}}, _onDragClasses:function(r, t, q){var s = q?"mCSB_dragger_onDrag_expanded":"", p = ["mCSB_dragger_onDrag", "mCSB_scrollTools_onDrag"], u = r.closest(".mCSB_scrollTools"); if (t === "active"){r.toggleClass(p[0] + " " + s); u.toggleClass(p[1]); r[0]._draggable = r[0]._draggable?0:1} else{if (!r[0]._draggable){if (t === "hide"){r.removeClass(p[0]); u.removeClass(p[1])} else{r.addClass(p[0]); u.addClass(p[1])}}}}, _overflowed:function(){var t = h(this), u = t.data(a), q = h("#mCSB_" + u.idx), s = h("#mCSB_" + u.idx + "_container"), r = u.overflowed == null?s.height():s.outerHeight(false), p = u.overflowed == null?s.width():s.outerWidth(false); return[r > q.height(), p > q.width()]}, _resetContentPosition:function(){var t = h(this), v = t.data(a), u = v.opt, q = h("#mCSB_" + v.idx), r = h("#mCSB_" + v.idx + "_container"), s = [h("#mCSB_" + v.idx + "_dragger_vertical"), h("#mCSB_" + v.idx + "_dragger_horizontal")]; g._stop(t); if ((u.axis !== "x" && !v.overflowed[0]) || (u.axis === "y" && v.overflowed[0])){s[0].add(r).css("top", 0)}if ((u.axis !== "y" && !v.overflowed[1]) || (u.axis === "x" && v.overflowed[1])){var p = dx = 0; if (v.langDir === "rtl"){p = q.width() - r.outerWidth(false); dx = Math.abs(p / v.scrollRatio.x)}r.css("left", p); s[1].css("left", dx)}}, _bindEvents:function(){var r = h(this), t = r.data(a), s = t.opt; if (!t.bindEvents){g._draggable.call(this); if (s.contentTouchScroll){g._contentDraggable.call(this)}if (s.mouseWheel.enable){function q(){p = setTimeout(function(){if (!h.event.special.mousewheel){q()} else{clearTimeout(p); g._mousewheel.call(r[0])}}, 1000)}var p; q()}g._draggerRail.call(this); g._wrapperScroll.call(this); if (s.advanced.autoScrollOnFocus){g._focus.call(this)}if (s.scrollButtons.enable){g._buttons.call(this)}if (s.keyboard.enable){g._keyboard.call(this)}t.bindEvents = true}}, _unbindEvents:function(){var s = h(this), t = s.data(a), p = a + "_" + t.idx, u = ".mCSB_" + t.idx + "_scrollbar", r = h("#mCSB_" + t.idx + ",#mCSB_" + t.idx + "_container,#mCSB_" + t.idx + "_container_wrapper," + u + " .mCSB_draggerContainer,#mCSB_" + t.idx + "_dragger_vertical,#mCSB_" + t.idx + "_dragger_horizontal," + u + ">a"), q = h("#mCSB_" + t.idx + "_container"); if (t.bindEvents){h(m).unbind("." + p); r.each(function(){h(this).unbind("." + p)}); clearTimeout(s[0]._focusTimeout); g._delete.call(null, s[0]._focusTimeout); clearTimeout(t.sequential.step); g._delete.call(null, t.sequential.step); clearTimeout(q[0].onCompleteTimeout); g._delete.call(null, q[0].onCompleteTimeout); t.bindEvents = false}}, _scrollbarVisibility:function(q){var t = h(this), v = t.data(a), u = v.opt, p = h("#mCSB_" + v.idx + "_container_wrapper"), r = p.length?p:h("#mCSB_" + v.idx + "_container"), w = [h("#mCSB_" + v.idx + "_scrollbar_vertical"), h("#mCSB_" + v.idx + "_scrollbar_horizontal")], s = [w[0].find(".mCSB_dragger"), w[1].find(".mCSB_dragger")]; if (u.axis !== "x"){if (v.overflowed[0] && !q){w[0].add(s[0]).add(w[0].children("a")).css("display", "block"); r.removeClass("mCS_no_scrollbar_y mCS_y_hidden")} else{if (u.alwaysShowScrollbar){if (u.alwaysShowScrollbar !== 2){s[0].add(w[0].children("a")).css("display", "none")}r.removeClass("mCS_y_hidden")} else{w[0].css("display", "none"); r.addClass("mCS_y_hidden")}r.addClass("mCS_no_scrollbar_y")}}if (u.axis !== "y"){if (v.overflowed[1] && !q){w[1].add(s[1]).add(w[1].children("a")).css("display", "block"); r.removeClass("mCS_no_scrollbar_x mCS_x_hidden")} else{if (u.alwaysShowScrollbar){if (u.alwaysShowScrollbar !== 2){s[1].add(w[1].children("a")).css("display", "none")}r.removeClass("mCS_x_hidden")} else{w[1].css("display", "none"); r.addClass("mCS_x_hidden")}r.addClass("mCS_no_scrollbar_x")}}if (!v.overflowed[0] && !v.overflowed[1]){t.addClass("mCS_no_scrollbar")} else{t.removeClass("mCS_no_scrollbar")}}, _coordinates:function(q){var p = q.type; switch (p){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return[q.originalEvent.pageY, q.originalEvent.pageX]; break; case"touchstart":case"touchmove":case"touchend":var r = q.originalEvent.touches[0] || q.originalEvent.changedTouches[0]; return[r.pageY, r.pageX]; break; default:return[q.pageY, q.pageX]}}, _draggable:function(){var u = h(this), s = u.data(a), p = s.opt, r = a + "_" + s.idx, t = ["mCSB_" + s.idx + "_dragger_vertical", "mCSB_" + s.idx + "_dragger_horizontal"], v = h("#mCSB_" + s.idx + "_container"), w = h("#" + t[0] + ",#" + t[1]), A, y, z; w.bind("mousedown." + r + " touchstart." + r + " pointerdown." + r + " MSPointerDown." + r, function(E){E.stopImmediatePropagation(); E.preventDefault(); if (!g._mouseBtnLeft(E)){return}n = true; if (i){m.onselectstart = function(){return false}}x(false); g._stop(u); A = h(this); var F = A.offset(), G = g._coordinates(E)[0] - F.top, B = g._coordinates(E)[1] - F.left, D = A.height() + F.top, C = A.width() + F.left; if (G < D && G > 0 && B < C && B > 0){y = G; z = B}g._onDragClasses(A, "active", p.autoExpandScrollbar)}).bind("touchmove." + r, function(C){C.stopImmediatePropagation(); C.preventDefault(); var D = A.offset(), E = g._coordinates(C)[0] - D.top, B = g._coordinates(C)[1] - D.left; q(y, z, E, B)}); h(m).bind("mousemove." + r + " pointermove." + r + " MSPointerMove." + r, function(C){if (A){var D = A.offset(), E = g._coordinates(C)[0] - D.top, B = g._coordinates(C)[1] - D.left; if (y === E){return}q(y, z, E, B)}}).add(w).bind("mouseup." + r + " touchend." + r + " pointerup." + r + " MSPointerUp." + r, function(B){if (A){g._onDragClasses(A, "active", p.autoExpandScrollbar); A = null}n = false; if (i){m.onselectstart = null}x(true)}); function x(B){var C = v.find("iframe"); if (!C.length){return}var D = !B?"none":"auto"; C.css("pointer-events", D)}function q(D, E, G, B){v[0].idleTimer = p.scrollInertia < 233?250:0; if (A.attr("id") === t[1]){var C = "x", F = ((A[0].offsetLeft - E) + B) * s.scrollRatio.x} else{var C = "y", F = ((A[0].offsetTop - D) + G) * s.scrollRatio.y}g._scrollTo(u, F.toString(), {dir:C, drag:true})}}, _contentDraggable:function(){var y = h(this), K = y.data(a), I = K.opt, F = a + "_" + K.idx, v = h("#mCSB_" + K.idx), z = h("#mCSB_" + K.idx + "_container"), w = [h("#mCSB_" + K.idx + "_dragger_vertical"), h("#mCSB_" + K.idx + "_dragger_horizontal")], E, G, L, M, C = [], D = [], H, A, u, t, J, x, r = 0, q, s = I.axis === "yx"?"none":"all"; z.bind("touchstart." + F + " pointerdown." + F + " MSPointerDown." + F, function(N){if (!g._pointerTouch(N) || n){return}var O = z.offset(); E = g._coordinates(N)[0] - O.top; G = g._coordinates(N)[1] - O.left}).bind("touchmove." + F + " pointermove." + F + " MSPointerMove." + F, function(Q){if (!g._pointerTouch(Q) || n){return}Q.stopImmediatePropagation(); A = g._getTime(); var P = v.offset(), S = g._coordinates(Q)[0] - P.top, U = g._coordinates(Q)[1] - P.left, R = "mcsLinearOut"; C.push(S); D.push(U); if (K.overflowed[0]){var O = w[0].parent().height() - w[0].height(), T = ((E - S) > 0 && (S - E) > - (O * K.scrollRatio.y))}if (K.overflowed[1]){var N = w[1].parent().width() - w[1].width(), V = ((G - U) > 0 && (U - G) > - (N * K.scrollRatio.x))}if (T || V){Q.preventDefault()}x = I.axis === "yx"?[(E - S), (G - U)]:I.axis === "x"?[null, (G - U)]:[(E - S), null]; z[0].idleTimer = 250; if (K.overflowed[0]){B(x[0], r, R, "y", "all", true)}if (K.overflowed[1]){B(x[1], r, R, "x", s, true)}}); v.bind("touchstart." + F + " pointerdown." + F + " MSPointerDown." + F, function(N){if (!g._pointerTouch(N) || n){return}N.stopImmediatePropagation(); g._stop(y); H = g._getTime(); var O = v.offset(); L = g._coordinates(N)[0] - O.top; M = g._coordinates(N)[1] - O.left; C = []; D = []}).bind("touchend." + F + " pointerup." + F + " MSPointerUp." + F, function(P){if (!g._pointerTouch(P) || n){return}P.stopImmediatePropagation(); u = g._getTime(); var N = v.offset(), T = g._coordinates(P)[0] - N.top, V = g._coordinates(P)[1] - N.left; if ((u - A) > 30){return}J = 1000 / (u - H); var Q = "mcsEaseOut", R = J < 2.5, W = R?[C[C.length - 2], D[D.length - 2]]:[0, 0]; t = R?[(T - W[0]), (V - W[1])]:[T - L, V - M]; var O = [Math.abs(t[0]), Math.abs(t[1])]; J = R?[Math.abs(t[0] / 4), Math.abs(t[1] / 4)]:[J, J]; var U = [Math.abs(z[0].offsetTop) - (t[0] * p((O[0] / J[0]), J[0])), Math.abs(z[0].offsetLeft) - (t[1] * p((O[1] / J[1]), J[1]))]; x = I.axis === "yx"?[U[0], U[1]]:I.axis === "x"?[null, U[1]]:[U[0], null]; q = [(O[0] * 4) + I.scrollInertia, (O[1] * 4) + I.scrollInertia]; var S = parseInt(I.contentTouchScroll) || 0; x[0] = O[0] > S?x[0]:0; x[1] = O[1] > S?x[1]:0; if (K.overflowed[0]){B(x[0], q[0], Q, "y", s, false)}if (K.overflowed[1]){B(x[1], q[1], Q, "x", s, false)}}); function p(P, N){var O = [N * 1.5, N * 2, N / 1.5, N / 2]; if (P > 90){return N > 4?O[0]:O[3]} else{if (P > 60){return N > 3?O[3]:O[2]} else{if (P > 30){return N > 8?O[1]:N > 6?O[0]:N > 4?N:O[2]} else{return N > 8?N:O[3]}}}}function B(P, R, S, O, N, Q){if (!P){return}g._scrollTo(y, P.toString(), {dur:R, scrollEasing:S, dir:O, overwrite:N, drag:Q})}}, _mousewheel:function(){var s = h(this), u = s.data(a), t = u.opt, q = a + "_" + u.idx, p = h("#mCSB_" + u.idx), r = [h("#mCSB_" + u.idx + "_dragger_vertical"), h("#mCSB_" + u.idx + "_dragger_horizontal")]; p.bind("mousewheel." + q, function(z, D){g._stop(s); var B = t.mouseWheel.deltaFactor !== "auto"?parseInt(t.mouseWheel.deltaFactor):(i && z.deltaFactor < 100)?100:z.deltaFactor < 40?40:z.deltaFactor || 100; if (t.axis === "x" || t.mouseWheel.axis === "x"){var w = "x", C = [Math.round(B * u.scrollRatio.x), parseInt(t.mouseWheel.scrollAmount)], y = t.mouseWheel.scrollAmount !== "auto"?C[1]:C[0] >= p.width()?p.width() * 0.9:C[0], E = Math.abs(h("#mCSB_" + u.idx + "_container")[0].offsetLeft), A = r[1][0].offsetLeft, x = r[1].parent().width() - r[1].width(), v = z.deltaX || z.deltaY || D} else{var w = "y", C = [Math.round(B * u.scrollRatio.y), parseInt(t.mouseWheel.scrollAmount)], y = t.mouseWheel.scrollAmount !== "auto"?C[1]:C[0] >= p.height()?p.height() * 0.9:C[0], E = Math.abs(h("#mCSB_" + u.idx + "_container")[0].offsetTop), A = r[0][0].offsetTop, x = r[0].parent().height() - r[0].height(), v = z.deltaY || D}if ((w === "y" && !u.overflowed[0]) || (w === "x" && !u.overflowed[1])){return}if (t.mouseWheel.invert){v = - v}if (t.mouseWheel.normalizeDelta){v = v < 0? - 1:1}if ((v > 0 && A !== 0) || (v < 0 && A !== x) || t.mouseWheel.preventDefault){z.stopImmediatePropagation(); z.preventDefault()}g._scrollTo(s, (E - (v * y)).toString(), {dir:w})})}, _draggerRail:function(){var s = h(this), t = s.data(a), q = a + "_" + t.idx, r = h("#mCSB_" + t.idx + "_container"), u = r.parent(), p = h(".mCSB_" + t.idx + "_scrollbar .mCSB_draggerContainer"); p.bind("touchstart." + q + " pointerdown." + q + " MSPointerDown." + q, function(v){n = true}).bind("touchend." + q + " pointerup." + q + " MSPointerUp." + q, function(v){n = false}).bind("click." + q, function(z){if (h(z.target).hasClass("mCSB_draggerContainer") || h(z.target).hasClass("mCSB_draggerRail")){g._stop(s); var w = h(this), y = w.find(".mCSB_dragger"); if (w.parent(".mCSB_scrollTools_horizontal").length > 0){if (!t.overflowed[1]){return}var v = "x", x = z.pageX > y.offset().left? - 1:1, A = Math.abs(r[0].offsetLeft) - (x * (u.width() * 0.9))} else{if (!t.overflowed[0]){return}var v = "y", x = z.pageY > y.offset().top? - 1:1, A = Math.abs(r[0].offsetTop) - (x * (u.height() * 0.9))}g._scrollTo(s, A.toString(), {dir:v, scrollEasing:"mcsEaseInOut"})}})}, _focus:function(){var r = h(this), t = r.data(a), s = t.opt, p = a + "_" + t.idx, q = h("#mCSB_" + t.idx + "_container"), u = q.parent(); q.bind("focusin." + p, function(x){var w = h(m.activeElement), y = q.find(".mCustomScrollBox").length, v = 0; if (!w.is(s.advanced.autoScrollOnFocus)){return}g._stop(r); clearTimeout(r[0]._focusTimeout); r[0]._focusTimer = y?(v + 17) * y:0; r[0]._focusTimeout = setTimeout(function(){var C = [w.offset().top - q.offset().top, w.offset().left - q.offset().left], B = [q[0].offsetTop, q[0].offsetLeft], z = [(B[0] + C[0] >= 0 && B[0] + C[0] < u.height() - w.outerHeight(false)), (B[1] + C[1] >= 0 && B[0] + C[1] < u.width() - w.outerWidth(false))], A = (s.axis === "yx" && !z[0] && !z[1])?"none":"all"; if (s.axis !== "x" && !z[0]){g._scrollTo(r, C[0].toString(), {dir:"y", scrollEasing:"mcsEaseInOut", overwrite:A, dur:v})}if (s.axis !== "y" && !z[1]){g._scrollTo(r, C[1].toString(), {dir:"x", scrollEasing:"mcsEaseInOut", overwrite:A, dur:v})}}, r[0]._focusTimer)})}, _wrapperScroll:function(){var q = h(this), r = q.data(a), p = a + "_" + r.idx, s = h("#mCSB_" + r.idx + "_container").parent(); s.bind("scroll." + p, function(t){s.scrollTop(0).scrollLeft(0)})}, _buttons:function(){var u = h(this), w = u.data(a), v = w.opt, p = w.sequential, r = a + "_" + w.idx, t = h("#mCSB_" + w.idx + "_container"), s = ".mCSB_" + w.idx + "_scrollbar", q = h(s + ">a"); q.bind("mousedown." + r + " touchstart." + r + " pointerdown." + r + " MSPointerDown." + r + " mouseup." + r + " touchend." + r + " pointerup." + r + " MSPointerUp." + r + " mouseout." + r + " pointerout." + r + " MSPointerOut." + r + " click." + r, function(z){z.preventDefault(); if (!g._mouseBtnLeft(z)){return}var y = h(this).attr("class"); p.type = v.scrollButtons.scrollType; switch (z.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if (p.type === "stepped"){return}n = true; w.tweenRunning = false; x("on", y); break; case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if (p.type === "stepped"){return}n = false; if (p.dir){x("off", y)}break; case"click":if (p.type !== "stepped" || w.tweenRunning){return}x("on", y); break}function x(A, B){p.scrollAmount = v.snapAmount || v.scrollButtons.scrollAmount; g._sequentialScroll.call(this, u, A, B)}})}, _keyboard:function(){var u = h(this), t = u.data(a), q = t.opt, x = t.sequential, s = a + "_" + t.idx, r = h("#mCSB_" + t.idx), w = h("#mCSB_" + t.idx + "_container"), p = w.parent(), v = "input,textarea,select,datalist,keygen,[contenteditable='true']"; r.attr("tabindex", "0").bind("blur." + s + " keydown." + s + " keyup." + s, function(D){switch (D.type){case"blur":if (t.tweenRunning && x.dir){y("off", null)}break; case"keydown":case"keyup":var A = D.keyCode?D.keyCode:D.which, B = "on"; if ((q.axis !== "x" && (A === 38 || A === 40)) || (q.axis !== "y" && (A === 37 || A === 39))){if (((A === 38 || A === 40) && !t.overflowed[0]) || ((A === 37 || A === 39) && !t.overflowed[1])){return}if (D.type === "keyup"){B = "off"}if (!h(m.activeElement).is(v)){D.preventDefault(); D.stopImmediatePropagation(); y(B, A)}} else{if (A === 33 || A === 34){if (t.overflowed[0] || t.overflowed[1]){D.preventDefault(); D.stopImmediatePropagation()}if (D.type === "keyup"){g._stop(u); var C = A === 34? - 1:1; if (q.axis === "x" || (q.axis === "yx" && t.overflowed[1] && !t.overflowed[0])){var z = "x", E = Math.abs(w[0].offsetLeft) - (C * (p.width() * 0.9))} else{var z = "y", E = Math.abs(w[0].offsetTop) - (C * (p.height() * 0.9))}g._scrollTo(u, E.toString(), {dir:z, scrollEasing:"mcsEaseInOut"})}} else{if (A === 35 || A === 36){if (!h(m.activeElement).is(v)){if (t.overflowed[0] || t.overflowed[1]){D.preventDefault(); D.stopImmediatePropagation()}if (D.type === "keyup"){if (q.axis === "x" || (q.axis === "yx" && t.overflowed[1] && !t.overflowed[0])){var z = "x", E = A === 35?Math.abs(p.width() - w.outerWidth(false)):0} else{var z = "y", E = A === 35?Math.abs(p.height() - w.outerHeight(false)):0}g._scrollTo(u, E.toString(), {dir:z, scrollEasing:"mcsEaseInOut"})}}}}}break}function y(F, G){x.type = q.keyboard.scrollType; x.scrollAmount = q.snapAmount || q.keyboard.scrollAmount; if (x.type === "stepped" && t.tweenRunning){return}g._sequentialScroll.call(this, u, F, G)}})}, _sequentialScroll:function(r, u, s){var w = r.data(a), q = w.opt, y = w.sequential, x = h("#mCSB_" + w.idx + "_container"), p = y.type === "stepped"?true:false; switch (u){case"on":y.dir = [(s === "mCSB_buttonRight" || s === "mCSB_buttonLeft" || s === 39 || s === 37?"x":"y"), (s === "mCSB_buttonUp" || s === "mCSB_buttonLeft" || s === 38 || s === 37? - 1:1)]; g._stop(r); if (g._isNumeric(s) && y.type === "stepped"){return}t(p); break; case"off":v(); if (p || (w.tweenRunning && y.dir)){t(true)}break}function t(z){var F = y.type !== "stepped", J = !z?1000 / 60:F?q.scrollInertia / 1.5:q.scrollInertia, B = !z?2.5:F?7.5:40, I = [Math.abs(x[0].offsetTop), Math.abs(x[0].offsetLeft)], E = [w.scrollRatio.y > 10?10:w.scrollRatio.y, w.scrollRatio.x > 10?10:w.scrollRatio.x], C = y.dir[0] === "x"?I[1] + (y.dir[1] * (E[1] * B)):I[0] + (y.dir[1] * (E[0] * B)), H = y.dir[0] === "x"?I[1] + (y.dir[1] * parseInt(y.scrollAmount)):I[0] + (y.dir[1] * parseInt(y.scrollAmount)), G = y.scrollAmount !== "auto"?H:C, D = !z?"mcsLinear":F?"mcsLinearOut":"mcsEaseInOut", A = !z?false:true; if (z && J < 17){G = y.dir[0] === "x"?I[1]:I[0]}g._scrollTo(r, G.toString(), {dir:y.dir[0], scrollEasing:D, dur:J, onComplete:A}); if (z){y.dir = false; return}clearTimeout(y.step); y.step = setTimeout(function(){t()}, J)}function v(){clearTimeout(y.step); g._stop(r)}}, _arr:function(r){var q = h(this).data(a).opt, p = []; if (typeof r === "function"){r = r()}if (!(r instanceof Array)){p[0] = r.y?r.y:r.x || q.axis === "x"?null:r; p[1] = r.x?r.x:r.y || q.axis === "y"?null:r} else{p = r.length > 1?[r[0], r[1]]:q.axis === "x"?[null, r[0]]:[r[0], null]}if (typeof p[0] === "function"){p[0] = p[0]()}if (typeof p[1] === "function"){p[1] = p[1]()}return p}, _to:function(v, w){if (v == null || typeof v == "undefined"){return}var C = h(this), B = C.data(a), u = B.opt, D = h("#mCSB_" + B.idx + "_container"), r = D.parent(), F = typeof v; if (!w){w = u.axis === "x"?"x":"y"}var q = w === "x"?D.outerWidth(false):D.outerHeight(false), x = w === "x"?D.offset().left:D.offset().top, E = w === "x"?D[0].offsetLeft:D[0].offsetTop, z = w === "x"?"left":"top"; switch (F){case"function":return v(); break; case"object":if (v.nodeType){var A = w === "x"?h(v).offset().left:h(v).offset().top} else{if (v.jquery){if (!v.length){return}var A = w === "x"?v.offset().left:v.offset().top}}return A - x; break; case"string":case"number":if (g._isNumeric.call(null, v)){return Math.abs(v)} else{if (v.indexOf("%") !== - 1){return Math.abs(q * parseInt(v) / 100)} else{if (v.indexOf("-=") !== - 1){return Math.abs(E - parseInt(v.split("-=")[1]))} else{if (v.indexOf("+=") !== - 1){var s = (E + parseInt(v.split("+=")[1])); return s >= 0?0:Math.abs(s)} else{if (v.indexOf("px") !== - 1 && g._isNumeric.call(null, v.split("px")[0])){return Math.abs(v.split("px")[0])} else{if (v === "top" || v === "left"){return 0} else{if (v === "bottom"){return Math.abs(r.height() - D.outerHeight(false))} else{if (v === "right"){return Math.abs(r.width() - D.outerWidth(false))} else{if (v === "first" || v === "last"){var y = D.find(":" + v), A = w === "x"?h(y).offset().left:h(y).offset().top; return A - x} else{if (h(v).length){var A = w === "x"?h(v).offset().left:h(v).offset().top; return A - x} else{D.css(z, v); b.update.call(null, C[0]); return}}}}}}}}}}break}}, _autoUpdate:function(q){var t = h(this), F = t.data(a), z = F.opt, v = h("#mCSB_" + F.idx + "_container"); if (q){clearTimeout(v[0].autoUpdate); g._delete.call(null, v[0].autoUpdate); return}var s = v.parent(), p = [h("#mCSB_" + F.idx + "_scrollbar_vertical"), h("#mCSB_" + F.idx + "_scrollbar_horizontal")], D = function(){return[p[0].is(":visible")?p[0].outerHeight(true):0, p[1].is(":visible")?p[1].outerWidth(true):0]}, E = y(), x, u = [v.outerHeight(false), v.outerWidth(false), s.height(), s.width(), D()[0], D()[1]], H, B = G(), w; C(); function C(){clearTimeout(v[0].autoUpdate); v[0].autoUpdate = setTimeout(function(){if (z.advanced.updateOnSelectorChange){x = y(); if (x !== E){r(); E = x; return}}if (z.advanced.updateOnContentResize){H = [v.outerHeight(false), v.outerWidth(false), s.height(), s.width(), D()[0], D()[1]]; if (H[0] !== u[0] || H[1] !== u[1] || H[2] !== u[2] || H[3] !== u[3] || H[4] !== u[4] || H[5] !== u[5]){r(); u = H}}if (z.advanced.updateOnImageLoad){w = G(); if (w !== B){v.find("img").each(function(){A(this.src)}); B = w}}if (z.advanced.updateOnSelectorChange || z.advanced.updateOnContentResize || z.advanced.updateOnImageLoad){C()}}, 60)}function G(){var I = 0; if (z.advanced.updateOnImageLoad){I = v.find("img").length}return I}function A(L){var I = new Image(); function K(M, N){return function(){return N.apply(M, arguments)}}function J(){this.onload = null; r()}I.onload = K(I, J); I.src = L}function y(){if (z.advanced.updateOnSelectorChange === true){z.advanced.updateOnSelectorChange = "*"}var I = 0, J = v.find(z.advanced.updateOnSelectorChange); if (z.advanced.updateOnSelectorChange && J.length > 0){J.each(function(){I += h(this).height() + h(this).width()})}return I}function r(){clearTimeout(v[0].autoUpdate); b.update.call(null, t[0])}}, _snapAmount:function(r, p, q){return(Math.round(r / p) * p - q)}, _stop:function(p){var r = p.data(a), q = h("#mCSB_" + r.idx + "_container,#mCSB_" + r.idx + "_container_wrapper,#mCSB_" + r.idx + "_dragger_vertical,#mCSB_" + r.idx + "_dragger_horizontal"); q.each(function(){g._stopTween.call(this)})}, _scrollTo:function(q, s, u){var I = q.data(a), E = I.opt, D = {trigger:"internal", dir:"y", scrollEasing:"mcsEaseOut", drag:false, dur:E.scrollInertia, overwrite:"all", callbacks:true, onStart:true, onUpdate:true, onComplete:true}, u = h.extend(D, u), G = [u.dur, (u.drag?0:u.dur)], v = h("#mCSB_" + I.idx), B = h("#mCSB_" + I.idx + "_container"), K = E.callbacks.onTotalScrollOffset?g._arr.call(q, E.callbacks.onTotalScrollOffset):[0, 0], p = E.callbacks.onTotalScrollBackOffset?g._arr.call(q, E.callbacks.onTotalScrollBackOffset):[0, 0]; I.trigger = u.trigger; if (E.snapAmount){s = g._snapAmount(s, E.snapAmount, E.snapOffset)}switch (u.dir){case"x":var x = h("#mCSB_" + I.idx + "_dragger_horizontal"), z = "left", C = B[0].offsetLeft, H = [v.width() - B.outerWidth(false), x.parent().width() - x.width()], r = [s, (s / I.scrollRatio.x)], L = K[1], J = p[1], A = L > 0?L / I.scrollRatio.x:0, w = J > 0?J / I.scrollRatio.x:0; break; case"y":var x = h("#mCSB_" + I.idx + "_dragger_vertical"), z = "top", C = B[0].offsetTop, H = [v.height() - B.outerHeight(false), x.parent().height() - x.height()], r = [s, (s / I.scrollRatio.y)], L = K[0], J = p[0], A = L > 0?L / I.scrollRatio.y:0, w = J > 0?J / I.scrollRatio.y:0; break}if (r[1] < 0){r = [0, 0]} else{if (r[1] >= H[1]){r = [H[0], H[1]]} else{r[0] = - r[0]}}clearTimeout(B[0].onCompleteTimeout); if (!I.tweenRunning && ((C === 0 && r[0] >= 0) || (C === H[0] && r[0] <= H[0]))){return}g._tweenTo.call(null, x[0], z, Math.round(r[1]), G[1], u.scrollEasing); g._tweenTo.call(null, B[0], z, Math.round(r[0]), G[0], u.scrollEasing, u.overwrite, {onStart:function(){if (u.callbacks && u.onStart && !I.tweenRunning){if (t("onScrollStart")){F(); E.callbacks.onScrollStart.call(q[0])}I.tweenRunning = true; g._onDragClasses(x); I.cbOffsets = y()}}, onUpdate:function(){if (u.callbacks && u.onUpdate){if (t("whileScrolling")){F(); E.callbacks.whileScrolling.call(q[0])}}}, onComplete:function(){if (u.callbacks && u.onComplete){if (E.axis === "yx"){clearTimeout(B[0].onCompleteTimeout)}var M = B[0].idleTimer || 0; B[0].onCompleteTimeout = setTimeout(function(){if (t("onScroll")){F(); E.callbacks.onScroll.call(q[0])}if (t("onTotalScroll") && r[1] >= H[1] - A && I.cbOffsets[0]){F(); E.callbacks.onTotalScroll.call(q[0])}if (t("onTotalScrollBack") && r[1] <= w && I.cbOffsets[1]){F(); E.callbacks.onTotalScrollBack.call(q[0])}I.tweenRunning = false; B[0].idleTimer = 0; g._onDragClasses(x, "hide")}, M)}}}); function t(M){return I && E.callbacks[M] && typeof E.callbacks[M] === "function"}function y(){return[E.callbacks.alwaysTriggerOffsets || C >= H[0] + L, E.callbacks.alwaysTriggerOffsets || C <= - J]}function F(){var O = [B[0].offsetTop, B[0].offsetLeft], P = [x[0].offsetTop, x[0].offsetLeft], M = [B.outerHeight(false), B.outerWidth(false)], N = [v.height(), v.width()]; q[0].mcs = {content:B, top:O[0], left:O[1], draggerTop:P[0], draggerLeft:P[1], topPct:Math.round((100 * Math.abs(O[0])) / (Math.abs(M[0]) - N[0])), leftPct:Math.round((100 * Math.abs(O[1])) / (Math.abs(M[1]) - N[1])), direction:u.dir}}}, _tweenTo:function(r, u, s, q, A, t, J){var J = J || {}, G = J.onStart || function(){}, B = J.onUpdate || function(){}, H = J.onComplete || function(){}, z = g._getTime(), x, v = 0, D = r.offsetTop, E = r.style; if (u === "left"){D = r.offsetLeft}var y = s - D; r._mcsstop = 0; if (t !== "none"){C()}p(); function I(){if (r._mcsstop){return}if (!v){G.call()}v = g._getTime() - z; F(); if (v >= r._mcstime){r._mcstime = (v > r._mcstime)?v + x - (v - r._mcstime):v + x - 1; if (r._mcstime < v + 1){r._mcstime = v + 1}}if (r._mcstime < q){r._mcsid = _request(I)} else{H.call()}}function F(){if (q > 0){r._mcscurrVal = w(r._mcstime, D, y, q, A); E[u] = Math.round(r._mcscurrVal) + "px"} else{E[u] = s + "px"}B.call()}function p(){x = 1000 / 60; r._mcstime = v + x; _request = (!l.requestAnimationFrame)?function(K){F(); return setTimeout(K, 0.01)}:l.requestAnimationFrame; r._mcsid = _request(I)}function C(){if (r._mcsid == null){return}if (!l.requestAnimationFrame){clearTimeout(r._mcsid)} else{l.cancelAnimationFrame(r._mcsid)}r._mcsid = null}function w(M, L, Q, P, N){switch (N){case"linear":case"mcsLinear":return Q * M / P + L; break; case"mcsLinearOut":M /= P; M--; return Q * Math.sqrt(1 - M * M) + L; break; case"easeInOutSmooth":M /= P / 2; if (M < 1){return Q / 2 * M * M + L}M--; return - Q / 2 * (M * (M - 2) - 1) + L; break; case"easeInOutStrong":M /= P / 2; if (M < 1){return Q / 2 * Math.pow(2, 10 * (M - 1)) + L}M--; return Q / 2 * ( - Math.pow(2, - 10 * M) + 2) + L; break; case"easeInOut":case"mcsEaseInOut":M /= P / 2; if (M < 1){return Q / 2 * M * M * M + L}M -= 2; return Q / 2 * (M * M * M + 2) + L; break; case"easeOutSmooth":M /= P; M--; return - Q * (M * M * M * M - 1) + L; break; case"easeOutStrong":return Q * ( - Math.pow(2, - 10 * M / P) + 1) + L; break; case"easeOut":case"mcsEaseOut":default:var O = (M /= P) * M, K = O * M; return L + Q * (0.499999999999997 * K * O + - 2.5 * O * O + 5.5 * K + - 6.5 * O + 4 * M)}}}, _getTime:function(){if (l.performance && l.performance.now){return l.performance.now()} else{if (l.performance && l.performance.webkitNow){return l.performance.webkitNow()} else{if (Date.now){return Date.now()} else{return new Date().getTime()}}}}, _stopTween:function(){var p = this; if (p._mcsid == null){return}if (!l.requestAnimationFrame){clearTimeout(p._mcsid)} else{l.cancelAnimationFrame(p._mcsid)}p._mcsid = null; p._mcsstop = 1}, _delete:function(r){try{delete r} catch (q){r = null}}, _mouseBtnLeft:function(p){return !(p.which && p.which !== 1)}, _pointerTouch:function(q){var p = q.originalEvent.pointerType; return !(p && p !== "touch" && p !== 2)}, _isNumeric:function(p){return !isNaN(parseFloat(p)) && isFinite(p)}}; h.fn[e] = function(p){if (b[p]){return b[p].apply(this, Array.prototype.slice.call(arguments, 1))} else{if (typeof p === "object" || !p){return b.init.apply(this, arguments)} else{h.error("Method " + p + " does not exist")}}}; h[e] = function(p){if (b[p]){return b[p].apply(this, Array.prototype.slice.call(arguments, 1))} else{if (typeof p === "object" || !p){return b.init.apply(this, arguments)} else{h.error("Method " + p + " does not exist")}}}; h[e].defaults = f; l[e] = true; h(l).load(function(){h(k)[e]()})})(jQuery, window, document);