jQuery( function( $ ) {
	
	var $el = $( '.variations_form');

	var pm_load = {
		/**
		 * Init jQuery.BlockUI
		 */
		block: function() {
			$el.block({
				message: null,
				overlayCSS: {
					background: '#fff',
					opacity: 0.6
				}
			});
		},

		/**
		 * Remove jQuery.BlockUI
		 */
		unblock: function() {
			$el.unblock();
		}
	}
	var pm_frontend = {

		/**
		 * Initialize variations actions
		 */
		init: function() {
        	$(document).on('click', '.pure-table .price', this.selected_price);
        	$(document).on('change', 'table.un-variations tr:visible select', this.change_attr);
			this.autoload_pm();
     

            Tippy('.tippy', {
                animation: 'scale',
                duration: 200,
                arrow: true,
                position: 'bottom'
            });
			
			/* Replace default display price of woocommerce ver 3.4 */
			// if( $('body').hasClass('has-price-matrix') ) {
				// $('.woocommerce-variation.single_variation').remove();
				// $('.table-responsive').after('<div class="woocommerce-variation single_variation" style="display: none"></div>');
			// }
			

		},
		
		autoload_pm: function() {
			//pm_load.block();
			if( $('#single-product_variations').length ) {
				var $product_variations = $('#single-product_variations').attr('data-product_variations');
				var $product_attr = $('#single-product_variations').attr('data-attr');
				var $product_count = $('#single-product_variations').attr('data-count');
				$.ajax({
					url: nbt_solutions.ajax_url,
					data: {
						action:     'pm_autoload',
						security:   $('[name="security"]').val(),
						product_id: $('[name="add-to-cart"]').val(),
						un_attr: $.parseJSON($product_variations),
						attr: $.parseJSON($product_attr),
						count: $product_count,
						suffix: $('.un-variations').attr('data-suffix')
					},
					type: 'POST',
					success: function( response ) {
						pm_load.unblock();
						$('body').append(response);
					},
					error:function(){
						//alert('There was an error when processing data, please try again !');
					}
				});
			}
		},
		
		change_attr: function(){
			var $this = $(this).val();
			pm_load.block();
			var $total = $( 'table.un-variations tr:visible select' ).length;

			var optionVal = {};
			var pmid = '';
			var count = 0;
			$( 'table.un-variations tr:visible select' ).each(function( index ) {
				if($(this).val()){
					var $id = $(this).closest('select').attr('id');
					var $val = $(this).val();
					optionVal[$id] = $val;
					pmid += $id + $val;
					count += 1;
				}
			});

			if($this && $total == count){
				if( $('#wppm-' + md5(pmid)).length ) {
					var $autoload_pm = $('#wppm-' + md5(pmid)).html();
					setTimeout(function(){
						pm_load.unblock();
						$('.load-table-pm').html($autoload_pm);
						Tippy('.tippy', {
							animation: 'scale',
							duration: 200,
							arrow: true,
							position: 'bottom'
						});
					}, 500);
					console.log('Có');
				}else {
					console.log('Không');
					$.ajax({
						url: nbt_solutions.ajax_url,
						data: {
							action:     'pm_load_matrix',
							security:   $('[name="security"]').val(),
							product_id: $('[name="add-to-cart"]').val(),
							attr: optionVal
						},
						type: 'POST',
						datatype: 'json',
						success: function( response ) {
							var rs = JSON.parse(response);
							
							if(rs.complete != undefined){
								$('.price_attr').remove();
								$('.table-responsive, [name="price_attr"], [name="security"]').remove();
								$('.load-table-pm').html(rs.return);

								Tippy('.tippy', {
									animation: 'scale',
									duration: 200,
									arrow: true,
									position: 'bottom'
								});
							}
							pm_load.unblock();

						},
						error:function(){
							alert('There was an error when processing data, please try again !');
						}
					});
				}
			}else{
				$('.table-responsive').remove();
				pm_load.unblock();
			}


		},
		selected_price: function(){
			var price = $(this).html();
			var total_length = $( "form.variations_form select" ).length;
			
			//$('.wc-price-matrix-amount').show().html(price);
			if( $('.pure-table td.price').not($(this)).hasClass('selected') ){
				$('.pure-table td.price.selected').removeAttr('style');
			}

			$('.pure-table .price').removeClass('selected');
			$(this).addClass('selected');
			
			var $attr = $(this).attr('data-attr');
			$.each(JSON.parse($attr), function (key, pm) {
				$('#' + pm.name).val(pm.value);
				$('#nbtcs-' + pm.name + ' .swatch').removeClass('selected');
				$('#nbtcs-' + pm.name + ' [data-value="' + pm.value + '"]').addClass('selected');
			});
			
			
			var stuff = [];
			$( "form.variations_form select" ).each(function( index ) {
				if( $(this).is('[data-attribute_name]') ) {
					$(this).addClass('pm-select');
					if( $(this).val() ) {
						stuff.push( $(this).val() );
					}
				}
			});
			
			$('form.variations_form select.pm-select').trigger('change');

			if( nbt_solutions.is_scroll ) {
				$('html,body').animate({
					scrollTop: $("form.variations_form").find('[type="submit"]').offset().top - 150},
		        'slow');
			}
		    
		}
	}

	if($( ".pure-table" ).length > 0){
		pm_frontend.init();
	}
	
});