%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /proc/self/root/var/softaculous/sitepad/editor/site-data/plugins/kkart-pro/js/
Upload File :
Create Path :
Current File : //proc/self/root/var/softaculous/sitepad/editor/site-data/plugins/kkart-pro/js/frontend.js

/*
KKART
http://kkart.com/
(c) Kkart Team
*/

// Lets start
jQuery(document).ready(function(){

	// Setup any sliders
	jQuery('.pagelayer-kkart_img_gallery').each(function(){
		kkart_pl_product_slider(jQuery(this));
	});
	
	jQuery('.kkart-product-quantity').each(function(){
		kkart_pl_product_quantity(jQuery(this));
	});
	
	jQuery('.kkart-item-remove-link').each(function(){
		kkart_pl_cart_item_remove(jQuery(this));
	});
	
	jQuery('.kkart-items-update').each(function(){
		kkart_pl_cart_update_quantity(jQuery(this));
	});
	
	jQuery('.pagelayer-kkart_archive_thumb').each(function(){
		var jEle = jQuery(this);
		
		if(jEle.find('.kkart-thumbnail-gallery').length > 0){
			kkart_thumbnail_img_slider(jEle);
		}
    
	});
  
	jQuery('input[name^="shipping_method"]').on('change', function(){
		kkart_shipping_form(jQuery(this));
	});
	
	jQuery('.pagelayer-kkart_checkout_form').each(function(){
		var jEle = jQuery(this);
		
		jEle.find('.kkart-checkout-tab').each(function(){
			kkart_checkout_tabs(jQuery(this));
		});
	});
	
	jQuery('.kkart-address-holder').each(function(){
		kkart_billing_form_handler(jQuery(this));
	});
	
	jQuery('.pagelayer-kkart_myaccount_tabs').each(function(){
		kkart_myaccount_tabs(jQuery(this));
	});
	
	jQuery('.kkart-myaccount-address-holder').each(function(){
		kkart_billing_address_reload(jQuery(this));
	});
	
	jQuery('.kkart-myaccount-order-holder').each(function(){
		kkart_order_details_handler(jQuery(this));
	});
	
	jQuery('.pagelayer-kkart_archive_crt_btn').each(function(){
		kkart_archive_crt_btn_holder(jQuery(this));
	});
	
	jQuery('.kkart-login-form-holder').each(function(){
		kkart_login_form_handler(jQuery(this));
	});
	
	jQuery('.kkart-form-coupon-toggle').each( function() {
		kkart_coupon_toggle( jQuery(this) );
	});
	
	jQuery('.pagelayer-kkart_menu_cart').each(function(){
		kkart_menu_cart(jQuery(this));
	});
	
	jQuery('.pagelayer-kkart_products').each(function(){
		kkart_products_handler(jQuery(this));
	});
  
	jQuery('.kkart-cart-item-price').each(function(){
		kkart_cart_shipping_handling(jQuery(this));
	});
	
});

function kkart_cart_shipping_handling(jEle){
	
	// TODO: load this on open modal
	
	var cartModal =jEle.find('.kkart-cart-modal');
	var addressHolder = cartModal.find('.kkart-address-holder');
	var addressesHolder =  addressHolder.find('.kkart-addresses-holder');

	jEle.on('click', '.kkart-address-selection',function(){
    
		if(addressHolder.attr('address-loaded') != '1'){
			kkart_billing_address_reload(jEle);
		}
		
		addressHolder.attr('address-loaded', 1);
		
		cartModal.parent().addClass('kkart-show');
		addressesHolder.css('display', '');
	})

	cartModal.on('click', '.kkart-address-form-adder', function(e){
		cartModal.find('.kkart-address-holder').removeClass('kkart-address-done');
		addressesHolder.hide();
	});
	
	cartModal.on('click','.kkart-close-address', function(){
		cartModal.parent().removeClass('kkart-show');
		addressHolder.addClass('kkart-address-done');

	})
	jEle.on('click', '.kkart-address-form-headding',function(){
		
    if(addressHolder.attr('address-loaded') != '1'){
			kkart_billing_address_reload(jEle);
		}
    
		addressHolder.removeClass('kkart-address-done');
		cartModal.parent().addClass('kkart-show');
		addressesHolder.hide();
	})
}

// products handler
function kkart_products_handler(jEle){
	
	var ul = jEle.find('.pagelayer-products-container');
   
   if (!ul.hasClass('pagelayer-owl-holder')) {
        return;
    }

    // Build the options
    var options = pagelayer_fetch_dataAttrs(ul, 'data-slides-');
	
    pagelayer_owl_init(jEle, ul, options);
}

function kkart_pl_product_slider(jEle){
	
	var gallerycontainer = jEle.find('.kkart-product-gallery-container');
	var galleryHolder = jEle.find('.kkart-image-gallery-holder');
	var ul = jEle.find('.kkart-product-gallery-ul');
	var thumbnails = jEle.find('.kkart-product-gallery-ul li');
	
	var thumbLength = thumbnails.length;
	var colcnt = ul.attr('data-slides-count');
	
	var  sliderThumbnailAction = function(){
		
		var hoverSlider = jEle.find('.kkart-product-gallery-ul').attr('data-slides-hover');
		var sliderAction = "click";
  
		if(hoverSlider){
			sliderAction = "hover";
		}
		
		for (var i=0; i < thumbLength; i++){
			
			jQuery(thumbnails[i]).unbind(sliderAction);
			jQuery(thumbnails[i]).on(sliderAction, function(){
				
				var activeimage = thumbnails.find('.kkart-product-active');
				activeimage.removeClass('kkart-product-active');
				sliderImageChange(this);
			});
		}
	}
	
	
	var sliderPrevAction = function(){
		//on click  prev button show Image
		var prevButton = jEle.find('.primary-slider-controls .primary-image-prev');
		prevButton.unbind('click');
		prevButton.on('click' , function(){
			
			var activeimage = thumbnails.find('.kkart-product-active');
			jQuery(activeimage).removeClass('kkart-product-active');
			var activeli = jQuery(activeimage).parentsUntil("ul")[1];
			
			if(jQuery(activeli).prev().length != 0){
				var prevli = jQuery(activeli).prev();
				sliderImageChange(prevli);
			}else{
				var lastli = jQuery(activeli).siblings("li:last");
				sliderImageChange(lastli);
			}
			
		});
	}
	
	var sliderNextAction = function(){
		//on click next button show Image
		var nextButton = jEle.find('.primary-slider-controls .primary-image-next');
		nextButton.unbind('click');
		nextButton.on('click' , function(){
			
			var activeimage = thumbnails.find('.kkart-product-active');
			jQuery(activeimage).removeClass('kkart-product-active');
			var activeli = jQuery(activeimage).parentsUntil("ul")[1];
			
  			if(jQuery(activeli).next().length != 0){
				var nextli = jQuery(activeli).next();
				sliderImageChange(nextli);			
			}else{
				var firstli = jQuery(activeli).siblings("li:first");
				sliderImageChange(firstli);
			}
			
		});
	}
	
	var sliderImageChange = function(elementli){
		
		var clickimg = jQuery(elementli).find('.kkart-product-gimage ').addClass('kkart-product-active');
		var imgsrc = jQuery(elementli).find('a').attr('data-href');
		var changeimg = jEle.find('.kkart-primary-image-container img');
  
		changeimg.fadeOut('fast', function(){
			jQuery(changeimg).fadeIn('fast');
			jQuery(changeimg).attr('src', imgsrc);
		});
	}
	
	var sliderHorizontal = function(){
		
		if(colcnt < thumbLength){
			
			var thumbWidth = jQuery(thumbnails[0]).outerWidth(true);
			var holderWidth = galleryHolder.outerWidth(true);
			var totalWidth = thumbWidth * thumbLength;
			var ulWidth = thumbWidth * colcnt;
			
			var nc = 0;
			var pc = 0;
			var click = thumbLength - colcnt;
			ul.width(totalWidth);
			
			if(holderWidth >= ulWidth){
				gallerycontainer.width(ulWidth);
			}else{
				gallerycontainer.width(holderWidth);
			}
		
			gallerycontainer.append('<div class="gallery-slider-controls"><button type="button" class="gallery-image-prev"><i class="fas fa-chevron-left"></i></button><button type="button" class="gallery-image-next"><i class="fas fa-chevron-right"></i></button></div>');
		
			var nextButton = jEle.find('.gallery-slider-controls .gallery-image-next');
			nextButton.unbind('click');
			nextButton.on('click' , function(){
				if(nc < click){
					nc++;
					pc++;
					ul.animate({marginLeft: '-'+(jQuery(thumbnails[0]).outerWidth(true)*nc)});
				}
			});
    
			var prevButton = jEle.find('.gallery-slider-controls .gallery-image-prev');
			prevButton.unbind('click');
			prevButton.on('click' , function(){
				if(pc > 0){
					nc--;
					pc--;
					ul.animate({marginLeft: '-'+(jQuery(thumbnails[0]).outerWidth(true)*nc)});
				}
			});
		}
	}
	
	var sliderVertical = function(){

		if(colcnt < thumbLength){
			
			var thumbHeight = jQuery(thumbnails[0]).outerHeight(true);
			var holderHeight = galleryHolder.outerHeight(true);
			var totalHeight = thumbHeight * thumbLength;
			var ulHeight = thumbHeight * colcnt;
			var nc = 0;
			var pc = 0;
			var click = thumbLength - colcnt;
			ul.height(totalHeight);
			if(holderHeight >= ulHeight){
				gallerycontainer.height(ulHeight);
			}else{
				gallerycontainer.height(holderHeight);
			}
		
			gallerycontainer.append('<div class="gallery-slider-controls"><button type="button" class="gallery-image-prev"><i class="fas fa-chevron-up"></i></button><button type="button" class="gallery-image-next"><i class="fas fa-chevron-down"></i></button></div>');
		
			var nextButton = jEle.find('.gallery-slider-controls .gallery-image-next');
			nextButton.unbind('click');
			nextButton.on('click' , function(){
				if(nc < click){
					nc++;
					pc++;
					ul.animate({marginTop: '-'+(jQuery(thumbnails[0]).outerHeight(true)*nc)});
				}
			});
    
			var prevButton = jEle.find('.gallery-slider-controls .gallery-image-prev');
			prevButton.unbind('click');
			prevButton.on('click' , function(){
				if(pc > 0){
					nc--;
					pc--;
					ul.animate({marginTop: '-'+(jQuery(thumbnails[0]).outerHeight(true)*nc)});
				}
			});
		}
	}
	
	var zoomImage = function(jELe){
		var defaultParas = {
			layerW: 100, // Mask Width
			layerH: 100, // Mask Height
			layerOpacity: 0.2, // Mask Transperency
			layerBgc: '#000', // Mask Background Color
			showPanelW: 500, // Wide Display Area
			showPanelH: 500, // Display magnified area high
			marginL: 50, // The distance from the zoomed area to the right of the thumbnail
			marginT: 10 // The distance between the enlarged area and the upper side of the thumbnail
		};
		var self = jEle.find('.kkart-primary-image-container');
		var selfOffset = self.offset();
		var imageW = self.width();
		var imageH = self.height();
		var boxHeight = boxWidth = self.parent().outerWidth(true);
		var wTimes = 3;
		var hTimes = 3;
	
		var layer = jQuery('<div>').css({
			display: 'none',
			position: 'absolute',
			left: '0',
			top: '0',
			backgroundColor: defaultParas.layerBgc,
			width: defaultParas.layerW,
			height: defaultParas.layerH,
			opacity: defaultParas.layerOpacity,
			border: '1px solid #ccc',
			cursor: 'crosshair'
		});
	
		self.append(layer);
	
		var img = jQuery('<img>').attr('src', jQuery('.kkart-product-pimage')).css({
			position: 'relative',
			left: '0',
			top: '0',
			zIndex: '999',
			width: imageW * wTimes,
			height: imageH * hTimes,maxWidth: 'initial',
			maxHeight: 'initial',
		}).attr('id', 'big-img');
	
		var showPanel = jQuery('<div>').css({
			display: 'none',
			position: 'absolute',
			overflow: 'hidden',
			left: boxWidth + defaultParas.marginL,
			top: defaultParas.marginT,
			width: defaultParas.showPanelW,
			height: defaultParas.showPanelH,
		}).append(img);
	
		self.after(showPanel);
	
		self.on('mousemove', function(e) {
		
			var width_limit = layer.width() / 2;
			var max_X = imageW - width_limit;
			var max_Y = imageH - width_limit;
			var current_X = e.pageX - selfOffset.left;
			var current_Y = e.pageY - selfOffset.top;
			var move_X = current_X - width_limit;
			var move_Y = current_Y - width_limit;
  
			if(current_X <= width_limit) {
				move_X = 0;
			}
			if (current_X >= max_X) {
				move_X = max_X - width_limit;
			}
			if (current_Y <= width_limit) {
				move_Y = 0;
			}
			if (current_Y >= max_Y) {
				move_Y = max_Y - width_limit;
			}

			layer.css({
				left: move_X,
				top: move_Y
			});

			img.attr('src', jQuery('.kkart-product-pimage').attr('src')).css({
				left: -move_X * wTimes,
				top: -move_Y * hTimes
			});
		}).on('mouseenter', function() {
			layer.show();
			showPanel.show();
		}).on('mouseleave', function() {
			layer.hide();
			showPanel.hide();
		});
	}
	
	sliderThumbnailAction();
	sliderPrevAction();
	sliderNextAction();
	
	
	if(galleryHolder.hasClass('kkart-gallery-position-top') || galleryHolder.hasClass('kkart-gallery-position-bottom')){
		sliderHorizontal();
	}else{
		sliderVertical();
	}
	
	var pImg = jQuery(jEle.find('.kkart-primary-image-container'));
	if(!pagelayer_empty(pImg.attr('data-zoom')) && !pImg.find('.kkart-product-pimage').hasClass('kkart-upload-gallery-handler')){
		zoomImage(jEle);
	}
}

function kkart_pl_product_quantity(jEle){
	
	var minus = jEle.find(".kkart-minus");
	var plus = jEle.find(".kkart-plus");
	var quantity = jEle.find(".kkart-quantity-input");
	
	minus.click(function(){
		var qval = quantity.val();
		
		// TODO change 1 to min val of input
		if(qval > 1){
			quantity.val(--qval);
		}
    
	});
	
	plus.click(function(){
		var qval = quantity.val();
		var max = parseInt(quantity.attr('max'));
		
		if(!max || qval < max){
			quantity.val(++qval);
		}
    
	});
}

function kkart_thumbnail_img_slider(jEle){	
	
	var Interval = setInterval(function(){
		var closestOwl = jEle.closest('.pagelayer-owl-holder');

		if (closestOwl.length > 0 && closestOwl.children('.pagelayer-owl-stage-outer').length < 1) {
			return;
		}

		clearInterval(Interval);
		
		var parentWidth = jEle.parent().width();
		jEle.width(parentWidth);
		
		var ul = jEle.find('.kkart-thumbnail-gallery');
		
		var options = pagelayer_fetch_dataAttrs(ul, 'data-slides-');
		
		pagelayer_owl_init(jEle, ul, options);
	}, 500);
	
	jEle.on('click', '.pagelayer-owl-nav, .pagelayer-owl-dots', function(e){
		e.preventDefault();
	});

}

function kkart_price_update(data){
	
	jQuery('.kkart-cart-item-price-holder').each(function(){
  
		var cpEle = jQuery(this),
		pricetype = cpEle.find('.kkart-cart-item-price').data('pricetype'),
		priceHtml = cpEle.find('.kkart-cart-item-price'),
		pricetypeArr = [ 'sub_total', 'grand_total', 'all_items_total', 'tax', 'delivery_charges', 'discount' ];
		
		if( pricetypeArr.indexOf( pricetype ) > -1  && data[pricetype] ) {
			priceHtml.empty();
			priceHtml.html( data[pricetype] );
		}
    
	});
}

//handles removal of item from the cart
function kkart_pl_cart_item_remove(jEle){
	
	jQuery(".kkart-item-remove-link").click(function(e){
		e.preventDefault();
		
		var cart_item_key = jQuery(this).data('cart-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_remove_from_cart',
			data:{
				cart_item_key:cart_item_key,
				kkart_nonce: kkart_ajax_nonce
			},
			success: function (data){
				
				jQuery('[data-cart-key="'+cart_item_key+'"]').closest('.pagelayer-inner_row').animate({
						height: "toggle",
						opacity:"0"
					},
					{
						duration: 2000,
						complete: function(){
							jQuery('[data-cart-key="'+cart_item_key+'"]').closest('.pagelayer-inner_row').remove();
						}
					}
				);
        
				kkart_price_update(data);
				kkart_update_cart_data();
			}
		});
	});
}

//Cart update button
function kkart_pl_cart_update_quantity(jEle){

	jEle.on('click', function(e){
  
		e.preventDefault();
		var quantity = jEle.parent('.pagelayer-kkart_cart_update').siblings('.pagelayer-kkart_cart_item_quantity').find('input').val();
		var cart_item_key = jEle.data('cart-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_cart_update_quantity',
			data: {
				quantity : quantity,
				kkart_nonce: kkart_ajax_nonce,
				cart_item_key: cart_item_key
			},
			success: function(data){
				kkart_update_cart_data();
				kkart_price_update(data);
				jEle.parent('.pagelayer-kkart_cart_update').siblings('.pagelayer-kkart_cart_price').find('[data-pricetype="product_sub_total"]').html(data.product_subtotal);
				
			}
		});
	});
}

// Update mini cart and quentity
function kkart_update_cart_data(){
    
	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl+'action=kkart_get_cart_data',
		data:{
			kkart_nonce: kkart_ajax_nonce
		},
		success: function(response){
		    
			if(pagelayer_empty(response.data)){
				return;
			}
			
			// Update cart quantity 
			if(response.data.quantity != undefined){
				var cartIcon = jQuery('body').find('.pagelayer-cart-button-icon');
				if(cartIcon.length > 0){
					cartIcon.attr('data-counter', response.data.quantity);
				}    
			}

			// Update mini cart
			if ( response.data.fragments != undefined ) {
				var miniCartForm = jQuery('body').find('.kkart-cart-form');
				if(miniCartForm.length > 0){
					miniCartForm.find('.product_list_widget,.kkart-mini-cart__total,.kkart-mini-cart__buttons,.kkart-mini-cart__empty-message').remove();
					miniCartForm.find('.pagelayer-menu-cart-close').after(response.data.fragments);
				}
			}

			// Update cart button price
			if ( response.data.price != undefined ) {
				var cartBtnTxt = jQuery('body').find('.pagelayer-cart-button-text');
				if(cartBtnTxt.length > 0){
					cartBtnTxt.html(response.data.price);
				}
			}

		},
		error: function(){
			console.log('error while retriving cart information');
		}
	});
}

// Checkout handler
function kkart_checkout_tabs(jEle){
	
	var present_tab = jEle.find('.kkart-checkout-tab-holder');
	var button = jEle.find('button.checkout-tabs-proceed');
	var checkoutHolder = jEle.closest('.kkart-checkout-holder');
	var tab_type = jEle.data('checkout-tab');
	var nextEle = jEle.next();

	
	/* doneisTrue is used bcoz .data() wasnt able to assign value to the attribute, so vanilla js was used and it was outputting a 
	string, rather than a boolean value so the doneisTrue variable is used to convert that string to boolean */
	var doneisTrue = '';
	
	button.on('click', function(e){
		e.preventDefault();
		
		// Disable Currebt button
		button.prop('disabled', true);
		
		var post_data = {};
		
		if(tab_type == 'shipping' || tab_type == 'payment'){
			if(checkoutHolder.find('[name="ship_to_billing_address"]').is(":checked")){
				post_data = {
					ship_to_billing_address: 1,
				}
			}
		}
					
		if(checkoutHolder.find('[name="payment_method"]').val() && tab_type == 'payment'){
			varData = Object.assign(post_data, {
				'kkart-process-checkout-nonce': kkart_checkout_nonce,
				'payment_method': checkoutHolder.find('[name="payment_method"]:checked').val(),
			});	
		}
		
		var varData = {
			kkart_nonce: kkart_ajax_nonce,
			tab_type: tab_type,
		};
			
		varData = Object.assign(post_data, varData);
			
		jQuery.ajax({
			type: 'post',
			url: kkart_ajaxurl+'action=kkart_checkout_tabs_procceed',
			data: varData,
			success: function(data){
				
				if(typeof data != 'object'){
					data = jQuery.parseJSON(data);
				}
				
				if(data['error']){
					alert(data['error']);
					return;
				}
				
				if(data['logged_out']){
					alert(data['logged_out']);
					return;
				}
				
				if(tab_type == 'payment' && 'result' in data){
					if( data['result'] == 'success') {
						window.location.href = data['redirect'];
						
					} else if('messages' in data){
						var selected_method = present_tab.find('input[name="payment_method"]:checked').closest('.kkart-payment-method');
					
						if( selected_method.find('.kkart-error').length ) {
							selected_method.find('.kkart-error').remove();
						}
			  
						selected_method.append( data['messages'] );
					}
					
				}
		
				//if(present_tab.has('.kkart-payment-method').length > 0 && present_tab.has('.kkart-payment-method .radioActive').length == 0){
				//	present_tab.find('.kkart-payments-method-holder').prepend('<div class="payment_method_error" style="background-color:red; color:white;padding:5px 5px;">Select a Payment Method to Proceed</div>');
				//	error_count += 1;
				//	}
				
				if(nextEle.length > 0 ){ //&& doneisTrue
				
					if( nextEle.data('checkout-tab') == 'cart' ){
						kkart_reload_cart_tab( jEle );
						kkart_shipping_form( jQuery(this) );
					}		
        
					present_tab[0]['dataset']['done'] = true;
					jEle.removeClass('kkart-checkout-active-tab');
					jEle.find('button.checkout_edit_button').css('display', 'inline-block');
					jEle.find('i').css('display', 'inline-block');
				
					//doneisTrue conversion is done here
					//doneisTrue = (present_tab[0]['dataset']['done'] == 'true');
					
					present_tab[0]['dataset']['touched'] = false;
					nextEle.find('.kkart-checkout-tab-holder')[0]['dataset']['touched'] = true;
					nextEle.addClass('kkart-checkout-active-tab');
					location.hash = nextEle.data('checkout-tab');
					
					var billingAddre = nextEle;
					
					if(billingAddre.length > 0){
						kkart_billing_address_reload(billingAddre);
					}
					
				}
				
			},
			complete: function(){
				// Enable Currebt button
				button.prop('disabled', false);
			}
		});
		
	});	
	
	var add_data_to_header = function(data){
		var header_text = jEle.find('.kkart-checkout-tab-header .kkart-checkout-tab-header-text');
		
		if(header_text.length > 0){
			header_text.text(data.display_name+'&nbsp;&nbsp;'+data.user_email);
			return;
		}
	
		jEle.find('.kkart-checkout-tab-header').append('<span class="kkart-checkout-tab-header-text">'+data.display_name+'&nbsp;&nbsp;'+data.user_email+'</span>');
	}
	
	if(jEle.prev().length == 0 && !present_tab.data('done')){
		
		jEle.addClass('kkart-checkout-active-tab');
		present_tab[0]['dataset']['touched'] = true;
		
		jQuery.ajax({
			url: kkart_ajaxurl+'action=kkart_user_auth',
			data: {
				kkart_nonce: kkart_ajax_nonce
			},
			success: function(data){
				
				if(!data.isLoggedIn){
					return;
				}
				
				button.click();
				add_data_to_header(data);
			}
		});
	}else{
		// Remove class
		jEle.removeClass('kkart-checkout-active-tab');
	}
	
	var edit_button = jEle.find('button.checkout_edit_button');
	edit_button.on('click',function(e){
		
		e.preventDefault();
		var billingAddre = present_tab;
					
		if(billingAddre.length > 0){
			kkart_billing_address_reload(billingAddre);
		}
		
		jEle.addClass('kkart-checkout-active-tab');
		present_tab[0]['dataset']['touched']= true;
		
		// Hide All edit buttons from all next tabs
		edit_button.hide();
		jEle.nextAll().find('button.checkout_edit_button').hide();
		
		jEle.nextAll().find('.kkart-checkout-tab-holder').each(function(){
		
			jEle.nextAll().removeClass('kkart-checkout-active-tab');
			jEle.nextAll().find('i').hide();
			jEle.nextAll().find('.kkart-checkout-tab-holder')[0]['dataset']['touched'] = false;
			
		});
	});
	
	
	var $payment_method = jEle.find('.kkart-payment-method');
	
	$payment_method.on('change',function(){
		
		jQuery(present_tab).find('.kkart-payments-method-holder .payment_method_error').fadeOut("slow",function(){
			jQuery(this).remove();
		});
		
		var $payment_method_desc = jQuery(this).find('.kkart-payment-method-desc');
		
		if(jQuery(this).prop("checked",true)){
			
			if($payment_method.siblings().has('.radioActive').length > 0){
				
				$payment_method.siblings().each(function(){
					
					jQuery(this).find('.radioActive').slideUp("slow",function(){
						jQuery(this).hide().removeClass('radioActive');
					});
					
					$payment_method_desc.slideDown("slow",function(){
						jQuery(this).show();
						jQuery(this).addClass('radioActive');
					});
					
				});	
				
			}else{
				
				$payment_method_desc.slideDown("slow",function(){
					jQuery(this).show();
					jQuery(this).addClass('radioActive');
				});
				
			}
			
		}
	
	});
	
	// Add signup button
	jEle.find('.kkart-checkout-login-holder .signup').on('click', function(e){
		e.preventDefault();
		jEle.find('.kkart-checkout-login-holder').hide();
		jEle.find('.kkart-checkout-register-holder').show();
	});
	
	jEle.find('.kkart-login-form-show').click(function(e){
		e.preventDefault();
		jEle.find('.kkart-checkout-login-holder').show();
		jEle.find('.kkart-checkout-register-holder').hide();
	});
}

function kkart_reload_cart_tab( jEle ) {
	
	var cartTab = jEle,
	nextEle = jEle.next(),
	tab_type = cartTab.data('checkout-tab');
	
	if( tab_type == 'shipping' ){
		cartTab = nextEle;
	}
	
	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl+'action=kkart_reload_cart_tab',
		data: {
			kkart_nonce: kkart_ajax_nonce
		},
		success: function(res) {
			cartTab.find('.kkart-checkout-tab-holder :first-child').remove();
			cartTab.find('.kkart-checkout-tab-holder :first-child').before(res);
			
			jQuery('input[name^="shipping_method"]').off().on('change', function(){
				kkart_shipping_form( jQuery(this) );
			});
		}	
	});
	
}

//handles validation of form
function kkart_validateForm(jEle, error_count){
	
	var nameReg = /^[A-Za-z ]+$/;
	var numberReg = /^(\+\d{1,3}[- ]?)?\d{10}$/;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var urlReg = 'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)';
	
	if(jEle.val() == '' ){
		
		error_count +=1;
		
		if(jEle.next('span.form-error').length > 0){
			jEle.next('span.form-error').remove();
			jEle.removeClass('empty-field');
		}
		
		jEle.after('<span class="form-error" style="color:red;display:block">Enter Some Value in this Field</span>');
		jEle.addClass('empty-field');	
		return error_count;
	}
		
	if(jEle.next('span.form-error').length > 0){
		jEle.next('span.form-error').remove();
		jEle.removeClass('empty-field');
	}
	
	if(jEle.attr('type') == 'country' || jEle.attr('type') == 'state' || jEle.attr('name').includes('name')){
	
		if(!nameReg.test(jEle.val())){
			error_count += 1;
			if(jEle.next('span.form-error').length > 0){
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
      
			jEle.after('<span class="form-error" style="color:red;display:block">Enter a Valid Value</span>');
			jEle.addClass('empty-field');

			
		}else{
			if(jEle.next('span.form-error').length > 0){
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
		}
	}
	
	if(jEle.attr('type') == 'email'){
		if(!emailReg.test(jEle.val())){
			error_count += 1;
			if(jEle.next('span.form-error').length > 0){
			
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');

			}
			
			jEle.after('<span class="form-error" style="color:red;display:block">Enter a Valid Email</span>');
			jEle.addClass('empty-field');

			
		}else{
			if(jEle.next('span.form-error').length > 0){
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
		}
	}
	
	if(jEle.attr('type') == 'number'){
		if(!numberReg.test(jEle.val())){
			error_count +=1;
			if(jEle.next('span.form-error').length > 0){
			
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
			
			jEle.after('<span class="form-error" style="color:red;display:block">Enter a Valid Number</span>');
			jEle.addClass('empty-field');
			
		}else{
			if(jEle.next('span.form-error').length > 0){
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
		}
	}
	
	if(jEle.attr('type') == 'url'){
		if(!urlReg.test(jEle.val())){
			error_count +=1;
			if(jEle.next('span.form-error').length > 0){
			
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
			}
			
			jEle.after('<span class="form-error" style="color:red;display:block">Enter a Valid URL</span>');
			jEle.addClass('empty-field');
			
		}else{
			if(jEle.next('span.form-error').length > 0){
				jEle.next('span.form-error').remove();
				jEle.removeClass('empty-field');
		
			}
		}
		
	}
	
	return error_count;
}

// Save Checkout address
function kkart_save_checkout_address(jEle, e){
  e.preventDefault();
	
	jEle = jQuery(jEle);
	
	var addressHolder = jEle.closest('.kkart-address-holder');
	var holder = jEle.closest('.kkart-address-form-container');
	var data = holder.find('select, textarea, input').serialize();
	var error_count = 0;
	var postalInput = holder.find('#billing_postcode');
	
	// validate the Filelds
	holder.find('input, select').each(function(e){
		if(jQuery(this).closest('.validate-required').length > 0){
			error_count = kkart_validateForm(jQuery(this), error_count);
		}
	});
	
	if(error_count > 0){
		return;
	}
	
	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl+'action=kkart_save_billing_address&kkart_nonce='+kkart_ajax_nonce,
		data:data,
		success: function (data){
			data = jQuery.parseJSON(data);
			
			//to handle postal code error
			if(data['postal_error']){
				
				if(postalInput.next('span.form-error').length > 0){
					postalInput.next('span.form-error').remove();
					postalInput.removeClass('empty-field');
				}
				
				postalInput.after('<span class="form-error" style="color:red;display:block">Enter a Valid Postal Code</span>');
				postalInput.addClass('empty-field');
				return;
			}
			
			if(data['error']){
				return;
			}
			
			addressHolder.addClass('kkart-address-done');

			kkart_billing_add_address(addressHolder, data['address_data']);
			
			// To remove the address_id value so that new form can be open 
			jEle.siblings('[name="address_id"]').removeAttr('value');
		}
	});
}

// Edit checkout address
function kkart_billing_address_reload(jEle){
	
	var addressHolder = jEle.find('.kkart-address-holder');
	var addressesHolder =  addressHolder.find('.kkart-addresses-holder');
	
	if(addressHolder.length < 1){
		return;
	}
	
	var is_shipping = false;
	
	if(addressHolder.attr('data-form-type') == 'shipping' || addressHolder.attr('data-form-type') == 'shipping_cart'){
		is_shipping = true;
	}

	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl+'action=kkart_get_address_details',
		data:{
			kkart_nonce: kkart_ajax_nonce,
			is_shipping: is_shipping,
		},
		success: function (data){
			data = jQuery.parseJSON(data);
			
			addressHolder.unbind('change');
			addressHolder.on('change', '.country_to_state', function( e ) {
				kkart_update_state(jQuery(this), data);
			});
      
			if(data['error']){
				return;
			}
						
			addressesHolder.empty();
			
			for(var key in data['address_data']){
				data['address_data'][key]['address_id'] = key;
				kkart_billing_add_address(addressHolder, data['address_data'][key]);
				
			}
			
			addressHolder.find('.kkart-active-address-details').removeClass('kkart-active-address-details');
			addressHolder.find('[data-address-key="'+data['active_addr_id']+'"]').addClass('kkart-active-address-details');
      
		}
	});
}

// Add checkout address
function kkart_billing_add_address(jEle, data){
	
	var addressesHolder =  jEle.find('.kkart-addresses-holder');
	var addr_content =  '';//addressesHolder.attr('data-formate');
	var hereText =  addressesHolder.attr('data-here-text') || 'Use This';
	var editText =  addressesHolder.attr('data-edit-text') || 'Edit';
	var deleteText =  addressesHolder.attr('data-delete-text') || 'Delete';
	
  // Default show grid view
  addressesHolder.css('display', '');
  
	if(!addr_content){
		addr_content = '$billing_first_name $billing_last_name <br/>$billing_email <br/>$billing_address_1 <br/>$billing_address_2';
	}
	
	for(var field in data){
		addr_content = addr_content.replace('$'+field, data[field]);
	}

	var detailEle = addressesHolder.find('.kkart-address-details[data-address-key="'+ data['address_id'] +'"]');

	if(detailEle.length > 0){
		detailEle.find('.kkart-billing-detail').html(addr_content);
	}else{
		addressesHolder.append('<div class="kkart-address-details" data-address-key="'+ data['address_id'] +'">'+
			'<div class="kkart-billing-detail">'+addr_content+'</div>'+
			'<button class="kkart-billing-here" >'+hereText+'</button>'+
			'<button class="kkart-billing-edit">'+editText+'</button>'+
			'<button class="kkart-billing-delete">'+deleteText+'</button>'+
		'</div>');
	}
}

// Edit checkout address
function kkart_billing_form_handler(jEle){
	
	var is_shipping = false;
	var is_cart = false;
  
	if(jEle.attr('data-form-type') == 'shipping'){
		is_shipping = true;
	}
  
	if(jEle.attr('data-form-type') == 'shipping_cart'){
		is_cart = true;
		is_shipping = true;
	}
	
	// Set billing address
	jEle.on('click', '.kkart-billing-here', function(e){
		
		var curEle = jQuery(this);
		var addressDiv = curEle.closest('.kkart-address-details');
		var addressID = addressDiv.data('address-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_set_billing_address',
			data:{
				kkart_nonce: kkart_ajax_nonce,
				address_id: addressID,
				is_shipping: is_shipping,
			},
			success: function (data){
				data = jQuery.parseJSON(data);
				
				if(data['error']){
					return;
				}
        
				if(is_cart){
					location.reload(true);
				}else{
					curEle.closest('.kkart-addresses-holder').find('.kkart-address-details').removeClass('kkart-active-address-details');
					curEle.closest('.kkart-address-details').addClass('kkart-active-address-details');
					
					var proceed_button = jEle.parents('.kkart-checkout-tab').find('.checkout-tabs-proceed');
					proceed_button.click();
				}
				
			}
		});
		
	});
	
	// Edit address
	jEle.on('click', '.kkart-billing-edit', function(e){
		
		var curEle = jQuery(this);
		var addressDiv = curEle.closest('.kkart-address-details');
		var addressID = addressDiv.data('address-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_get_address_details',
			data:{
				kkart_nonce: kkart_ajax_nonce,
				address_id: addressID,
			},
			success: function (data){
				data = jQuery.parseJSON(data);
				
				if(data['error']){
					return;
				}
				
				var form_container = jEle.find('.kkart-address-form-container');
				
				// To identify which address is being edited
				jQuery( form_container ).data( 'addr-id', addressID );
				
				// Add address ID
				data['address_data']['address_id'] = addressID;
				
				for(var key in data['address_data']){
					var field = form_container.find('[name="'+key+'"]');

					if(field.length < 1){
						continue;
					}
					
					var value = data['address_data'][key];
										
					// Set value
					field.val(value);
					
					var tagName = field.prop("tagName");
					
					if(tagName == 'SELECT'){
						// TODO fix for state chenge
						field.trigger('change');
					}
					
					// TODO for checkbox
					
					// Show form
					curEle.closest('.kkart-address-holder').removeClass('kkart-address-done');
					
					// Hide address list on edit address
					if(is_cart){
						curEle.closest('.kkart-addresses-holder').hide();
					}
				}
			}
		});
		
	});
	
	// Delete address
	jEle.on('click', '.kkart-billing-delete', function(e){
		
		var curEle = jQuery(this);
		var addressDiv = curEle.closest('.kkart-address-details');
		var addressID = addressDiv.data('address-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_delete_address',
			data:{
				kkart_nonce: kkart_ajax_nonce,
				address_id: addressID,
			},
			success: function (data){
				data = jQuery.parseJSON(data);
				
				if(data['error']){
					return;
				}
				
				addressDiv.remove();
        
				// To reload when the addressDiv is empty
				if(jEle.find('.kkart-address-details').length < 1){
					jQuery('.kkart-cart-modal-wrapper').removeClass('kkart-show');
					location.reload(true);
				}
			}
		});
		
	});
	
	// Show address form
	jEle.on('click', '.kkart-address-form-headding', function(e){
		var curEle = jQuery(this);
		
		curEle.closest('.kkart-address-holder').removeClass('kkart-address-done');
	});
	
	// Save address form
	jEle.on('click', '.kkart-save-address-form', function(e){
		kkart_save_checkout_address(this, e);
	});
	
	// Cancel address form
	jEle.on('click', '.kkart-cancel-address-form', function(e){
		var curEle = jQuery(this);
		var addressHolderDiv = jQuery('.kkart-cart-modal').find('.kkart-addresses-holder');
		
		//TODO reset form
		curEle.closest('.kkart-address-holder').addClass('kkart-address-done');
		
		// Close modal if addresses empty
		if(addressHolderDiv.children().length < 1){
			addressHolderDiv.closest('.kkart-cart-modal-wrapper').removeClass('kkart-show');
		}else{
			addressHolderDiv.css('display', '');
		}
    
	});
	
	// Shipping address checkbox handler
	if(is_shipping){
		//set initial state.
		var shipEle = jEle.find('input[name="ship_to_billing_address"]');
		
		var shipEleToggle = function(){
			if(!shipEle.is(':checked')){
				jEle.find('.kkart-addresses-container').show();
			}else{
				jEle.find('.kkart-addresses-container').hide();
			}
		}
		
		//shipEleToggle();
		
		// Checkbox on change
		shipEle.on('change', function(){
			shipEleToggle();
		});
	}
}


function kkart_myaccount_tabs(jEle){
	
	var holder = jEle.find('.kkart-myaccount-tabholder');
	var tabs = holder.find('.kkart-tablinks');
	var hash = location.hash;
	
	tabs.on('click', function(e){

		var tEle = jQuery(this);
		var id = tEle.data('target');
		
		//Tab Content active
		jEle.find('.kkart-tab-content-holder').removeClass('kkart-active-tabcontent');
		jEle.find('.kkart-tab-content-holder[data-tabholder="'+id+'"]').addClass('kkart-active-tabcontent');
		
		holder.find('.kkart-tablinks').removeClass('kkart-active-tab');
		tEle.addClass('kkart-active-tab');
	});
	
	
	if(!pagelayer_empty(hash)){
		var id = hash.substring(1);
		var tab = holder.find('.kkart-tablinks[data-target="'+id+'"]');
    if(tab.length > 0){
      tab.click();
      return;
    }
	}
  
	tabs.first().click();
}

function kkart_order_details_handler(jEle){
	
	// View Order Details
	jEle.on('click', '.kkart-order-view', function(e){
		
		var curEle = jQuery(this);
		var orderID = curEle.data('order-key');
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_account_order_details',
			data:{
				kkart_nonce: kkart_ajax_nonce,
				order_id: orderID,
			},
			success: function (result){
				//console.log(result);
				jEle.find('.kkart-myaccount-orderdetails').append(result);
			}
		});
		
		jEle.find('.kkart-myaccount-orders').css({'display':'none'});
		jEle.find('.kkart-myaccount-orderdetails').css({'display':'block'});
	});
	
	jEle.on('click', '.kkart-close-orderdetails', function(e){
		jEle.find('.kkart-myaccount-orderdetails').empty();
		jEle.find('.kkart-myaccount-orderdetails').css({'display':'none'});
		jEle.find('.kkart-myaccount-orders').css({'display':'table'});
	});
}

function kkart_archive_crt_btn_holder(jEle){
	
	var addtocartHandler = function(jELe){
		
		jELe.on('click', '.kkart-archive-crt-btn, .kkart-plus, .kkart-minus, .kkart-close', function(e){
			
      if(pagelayer_empty(pagelayer_is_live)){
				
				if(jQuery(this).hasClass('kkart-minus')){
					removefromCart(jQuery(this), e);
				}else if(jQuery(this).hasClass('kkart-close')){
					deletefromCart(jQuery(this), e);
				}else if(jQuery(this).hasClass('kkart-archive-crt-btn') || jQuery(this).hasClass('kkart-plus')){
					addtoCart(jQuery(this), e);
				}
        
			}else{
				updateButton(this);
			}
      
		});
		
		jELe.on('change', '.kkart-quantity-input', function(e){
			
			e.preventDefault();
			var thisparent = jQuery(this).parents('.kkart-quantity-holder');
			var data_cart_key = jQuery(thisparent).attr('data-cart-key');
			var quantity = jQuery(this).val();
			
			setquantity(data_cart_key, quantity);
			
			if(quantity == 0){
				hidequantityHolder(jQuery(this));
			}
      
		});
	}
	
	var fetchCart = function(jELe){
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_get_cart_items',
			data:{
				kkart_nonce: kkart_ajax_nonce
			},
			success: function(result){
				
				var cartbutton = jQuery(jELe).find('.kkart-archive-crt-btn');
				var product_id = jQuery(cartbutton).attr('data-product_id');
				
				if(typeof (result['data']) == 'object'){
					
					var fetchcartdata = {};
					
					jQuery.each(result['data'], function(index, val){
						
						if(val['product_id'] == product_id){
							fetchcartdata = result['data'][index];
						}
            
					});

					var quantityHolder = jQuery(jELe).find('.kkart-quantity-holder');
					
					if(quantityHolder.length > 0){
						
						var kkartquantity = jQuery(quantityHolder).find('.kkart-quantity-input');
						jQuery(kkartquantity).val(fetchcartdata.quantity);
						jQuery(quantityHolder).attr('data-cart-key',fetchcartdata.key);
						
					}
          
				}
			},
			error: function(){
				console.log('there is some issue while fetching cart data!');
				
			}
		});
	}
	
	var addtoCart = function(thisbutton, e){
		
		
		if(thisbutton.is('.ajax_add_to_cart') || thisbutton.hasClass('kkart-plus')){
			
			var thisbtn = thisbutton;
			
			if(thisbutton.hasClass('kkart-plus')){
				thisparent = thisbutton.parents('.kkart-quantity-holder');
				thisbtn = jQuery(thisparent);
			}
			
			if (!thisbtn.attr( 'data-product_id')){
				return true;
			}
			
			e.preventDefault();
			var data = {};
			
			jQuery.each(thisbtn[0].dataset, function( key, value ) {
				
				if(key != 'data-cart-key'){
					data[ key ] = value;
				}
			
			});
			
			jQuery.ajax({
				type: 'POST',
				url: kkart_add_to_cart_params.kkart_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
				data: data,
				dataType: 'json',
				success: function( response ) {
					
					if ( ! response ) {
						return;
					}

					if ( response.error && response.product_url ) {
						window.location = response.product_url;
						return;
					}

					//Redirect to cart option
					if ( kkart_add_to_cart_params.cart_redirect_after_add === 'yes' ) {
						window.location = kkart_add_to_cart_params.cart_url;
						return;
					}

					//Trigger event so themes can refresh other areas.
					// View cart text.
					if ( !pagelayer_empty(response.fragments) ) {
						kkart_update_cart_data();
						updateButton(thisbutton);
					}
          
				},
				error: function(){
					console.log('error while adding product');
				}
			});
		}
	}
	
	
	var removefromCart = function(thisbutton, e){
		
		thisparent = thisbutton.parents('.kkart-quantity-holder');
	
		if (!thisparent.attr('data-cart-key')) {
			return true;
		}
		
		e.preventDefault();
			
		quantityinput = jQuery(thisparent).find('.kkart-quantity-input');
		var data_cart_key = jQuery(thisparent).attr( 'data-cart-key' );
		var quantity = jQuery(quantityinput).val();
			
		if(quantity > 0){	
			var quantity = --quantity;
			setquantity(data_cart_key, quantity);
			updateButton(thisbutton);
		}
		
	}
	
	var setquantity = function(data_cart_key, qty){
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_set_cart_quantity',
			data:{
				cart_item_key: data_cart_key,
				quantity: qty,
				kkart_nonce: kkart_ajax_nonce
			},
			success: function(data){
				if(!pagelayer_empty(data.success)){
					kkart_update_cart_data();
					return true;
				}
			},
			error: function(){
				console.log('error while removing from cart');
			}
		});
	}
	
	var deletefromCart = function(thisbutton, e){
		
		thisparent = thisbutton.parents('.kkart-quantity-holder');
		if (!thisparent.attr('data-cart-key')){
			return true;
		}
		
		e.preventDefault();
		var data_cart_key = thisparent.attr( 'data-cart-key' );
		
		jQuery.ajax({
			type: 'POST',
			url: kkart_ajaxurl+'action=kkart_remove_from_cart',
			data:{
				cart_item_key:data_cart_key,
				kkart_nonce: kkart_ajax_nonce
			},
			success: function(data){
				if(pagelayer_empty(data)){
					return;
				}else{
					kkart_update_cart_data();
					hidequantityHolder(thisbutton);
				}
			},
			error: function(){
				console.log('error while delete from cart');
			}
		});
	}
	
	var updateButton = function(thisbutton){
		
		var thisbutton = jQuery(thisbutton);
		var thisparent = thisbutton.parents('.kkart-crt-btn-holder');
		
		if ( thisbutton.hasClass( 'kkart-minus' ) ) {
			
			var inputquantity = thisparent.find('.kkart-quantity-input');
			var qval = jQuery(inputquantity).val();
			qval = --qval;
			
			if(qval > 0){
				jQuery(inputquantity).val(qval);
			}else{
				if(pagelayer_empty(pagelayer_is_live)){
					hidequantityHolder(thisbutton);
				}
			}
			
		}else if(thisbutton.hasClass('kkart-plus')){
			
			var inputquantity = thisparent.find('.kkart-quantity-input');
			var qval = jQuery(inputquantity).val();
			jQuery(inputquantity).val(++qval);
			
		}else if(thisbutton.hasClass( 'kkart-archive-crt-btn' )){
			
			if(pagelayer_empty(pagelayer_is_live)){
				
				if(!kkart_add_to_cart_params.is_cart){
					
					var data_attribute = {};
					jQuery.each( thisbutton[0].dataset, function( key, value ) {
						data_attribute[key] = value;
					});
					
					thisbutton.hide();
					
					var quantityHolder = jQuery(thisparent).find('.kkart-quantity-holder');
					if(quantityHolder.length == 0){
						thisparent.append('<div class="kkart-quantity-holder" data-quantity="'+data_attribute['quantity']+'" data-product_id="'+data_attribute['product_id']+'" data-product_sku="'+data_attribute['product_sku']+'"><div class="kkart-quantity"><i class="fas fa-minus kkart-minus"></i><input type="number" min="1" class="kkart-quantity-input" name="quantity" value=""><i class="fas fa-plus kkart-plus"></i></div><div class="kkart-quantity-close"><i class="fas fa-times kkart-close"></i></div></div>');
					}
					
					var viewbtnHolder = jQuery(thisparent).find('.kkart-view-btn-holder');
					if(viewbtnHolder.length == 0){
						
						var view_btn_text = kkart_add_to_cart_params.i18n_view_cart;
						
						if(!pagelayer_empty(jQuery(thisparent).data('view-btn-text'))){
							view_btn_text = jQuery(thisparent).data('view-btn-text');
						}
						
						thisparent.append('<div class="kkart-view-btn-holder"><a href="' + kkart_add_to_cart_params.cart_url + '" class="kkart-view-btn" title="'+view_btn_text+'">'+view_btn_text+'</a></div>' );
						
					}
					
					fetchCart(jEle);
				}
			}
		}
	}
	
	var hidequantityHolder = function(thiselement){
		
		var thisparent = thiselement.parents('.kkart-crt-btn-holder');
		var quantityHolder = jQuery(thisparent).find('.kkart-quantity-holder');
		var cartbtn = jQuery(thisparent).find('.kkart-archive-crt-btn');
		var viewbtn = jQuery(thisparent).find('.kkart-view-btn-holder')
		jQuery(quantityHolder).remove();
		jQuery(viewbtn).remove();
		jQuery(cartbtn).show();
    
	}
	
	addtocartHandler(jEle);
	var quantityHolder = jQuery(jEle).find('.kkart-quantity-holder');
	var view_btn = jQuery(jEle).find('.kkart-view-btn-holder');
	var thisbutton = jQuery(jEle).find('.kkart-archive-crt-btn');
	if(quantityHolder.length > 0 || view_btn.length > 0){
		thisbutton.hide();	
	}
}

function kkart_shipping_form(jELe){
	var shipping_methods = "",
	is_cart_tab = false,
	
	is_cart_tab = jELe.closest('.kkart-checkout-tab-holder').length ? true : false;
  
	// eslint-disable-next-line max-len
	var cart = $("#shipping_method").attr('cart');
	$( 'select.shipping_method, input[name^="shipping_method"][type="radio"]:checked, input[name^="shipping_method"][type="hidden"]' ).each( function() {
		shipping_methods = $(this).val();
	} );
  
	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl+'action=kkart_update_shipping_method',
		data:{
			shipping_method:shipping_methods,
			cart:cart,
			kkart_nonce: kkart_ajax_nonce
		},
		success: function (data){
			kkart_price_update(data);
			
			var cartTab = jELe.closest('.kkart-checkout-tab');
			
			if( is_cart_tab ) {
				kkart_reload_cart_tab( cartTab );
			}
		}
	});	
}

// Login form handler
function kkart_login_form_handler(jEle){
	
	var login = jEle.find('.kkart-login-form');
	var registration = jEle.find('.kkart-registration-form');
	
	if(registration.length < 1){
		login.find('.signup').remove();
		return;
	}
	
	login.find('.signup').click(function(e){
		e.preventDefault();
		login.hide();
		registration.show();
	});
	
	registration.find('.kkart-login-form-show').click(function(e){
		e.preventDefault();
		login.show();
		registration.hide();
	});
}
	
function kkart_coupon_toggle( jEle ) {
	
	// Show coupon
	jQuery(jEle).unbind( 'click.showcoupon');
	jQuery(jEle).on( 'click.showcoupon', 'a.showcoupon', function(e){
		e.preventDefault();
		var checkout_coupon = jQuery( '.checkout_coupon' );
		checkout_coupon.slideToggle( 400, function() {
			checkout_coupon.find( ':input:eq(0)' ).focus();
		});
		
	});
	
	jQuery( 'form.checkout_coupon' ).hide().submit( kkart_submit_coupon );
	jQuery( document.body ).on( 'click', '.kkart-remove-coupon', kkart_remove_coupon );
}

function kkart_remove_coupon(e) {
	e.preventDefault();
	
	var coupon = jQuery( this ).data( 'coupon' ),
	container = jQuery( '.kkart_cart_price_holder' );
	
	container.addClass( 'processing' ).block({
		message: null,
		overlayCSS: {
			background: '#fff',
			opacity: 0.6
		}
	});

	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl + 'action=kkart_remove_coupon',
		data: {
			security: kkart_ajax_nonce,
			coupon:   coupon
		},
		success: function( code ) {
			jQuery( '.kkart-error, .kkart-message' ).remove();
			container.removeClass( 'processing' ).unblock();
			
			if ( code ) {
				jQuery( '.kkart-form-coupon-toggle' ).after( code );
				
				setTimeout(()=>{
					jQuery( '.kkart-form-coupon-toggle' ).parent().find('.kkart-error, .kkart-message' ).remove();
				}, 4000);

				kkart_shipping_form( jQuery(this) );
				
				var tabs = jQuery('.kkart-checkout-tab');
				
				jQuery( tabs ).each(function() {
					if( 'cart' == jQuery(this).data('checkout-tab') ) {
						
						kkart_reload_cart_tab( jQuery(this) );
					}
				});
				
				// Remove coupon code from coupon field
				jQuery( 'body' ).find( 'input[name="coupon_code"]' ).val( '' );
			}
		},
		error: function ( jqXHR ) {
			console.log( jqXHR.responseText );
		},
		dataType: 'html'
	});
}

function kkart_submit_coupon() {
	var $form = jQuery( this );

	if ( $form.is( '.processing' ) ) {
		return false;
	}

	$form.addClass( 'processing' ).block({
		message: null,
		overlayCSS: {
			background: '#fff',
			opacity: 0.6
		}
	});
	
	jQuery.ajax({
		type: 'POST',
		url: kkart_ajaxurl + 'action=kkart_apply_coupon',
		data: {
			security: kkart_ajax_nonce,
			coupon_code: $form.find( 'input[name="coupon_code"]' ).val()
		},
		success: function( code ){
			jQuery( '.kkart-error, .kkart-message' ).remove();
			$form.removeClass( 'processing' ).unblock();

			if ( code ) {
				$form.before( code );

				setTimeout(()=>{
					$form.parent().find('.kkart-error, .kkart-message' ).remove();
				}, 4000);

				$form.slideUp();

				kkart_shipping_form( jQuery(this) );
				
				var tabs = jQuery('.kkart-checkout-tab');
				
				jQuery( tabs ).each(function() {
					if( 'cart' == jQuery(this).data('checkout-tab') ) {
						kkart_reload_cart_tab( jQuery(this) );
					}
				});
			}
		},
		dataType: 'html'
	});

	return false;
}

// Updates the select option of state on country change
function kkart_update_state(jEle, addrData){
	 
	addrData = addrData || {};
  
	var country = jEle.val(),
	addrHolder = jEle.closest('.kkart-address-form-container'),
	stateBox = addrHolder.find('#billing_state, #shipping_state'),
	parent = stateBox.closest('.form-row'),
	input_name = stateBox.attr('name'),
	input_classes = stateBox.attr('data-input-classes'),
	label = parent.children('label'),
	input_id  = stateBox.attr('id'),
	placeholder   = stateBox.attr( 'placeholder' ) || stateBox.attr( 'data-placeholder' ) || '',
	addressID = addrHolder.data('addr-id'),
	oldStateSel = '',
	newStateBox;

	if( !pagelayer_empty(addrData) && !pagelayer_empty(addrData['address_data'])) {
		
	if( addrData['address_data'][addressID] ) {
			oldStateSel = addrData['address_data'][addressID]['billing_state'];
		} else{
			oldStateSel = addrData['address_data']['billing_state'];
		}
		
	}
	
	jQuery.ajax({
		method : 'POST',
		url : kkart_ajaxurl+'action=kkart_get_states',
		data : {
			kkart_nonce : kkart_ajax_nonce,
			country_name : country	
		},
		success: function(res) {
		
			kkart_get_country_local(country, label);
			
			// Make input box for states
			if(typeof(res) === 'boolean' || res.length < 1){
				newStateBox = jQuery('<input type="text" />')
					.prop( 'id', input_id )
					.prop( 'name', input_name )
					.attr('data-input-classes', input_classes )
					.addClass( 'input-text  ' + input_classes );
				
				parent.show();
				stateBox.replaceWith( newStateBox );
				return;
				
			}else{
				
				// Make select box for states
				if( stateBox.is( 'input' ) ){
					newStateBox = jQuery('<select></select>')
						.prop( 'id', input_id )
						.prop( 'name', input_name )
						.data( 'placeholder', placeholder )
						.attr( 'data-input-classes', input_classes )
						.addClass( 'state_select ' + input_classes );
						
						parent.show();
						stateBox.replaceWith( newStateBox );
						stateBox = addrHolder.find( '#billing_state, #shipping_state');
				}	
				
				var state_options = '<option value>Select an option...</option>';
				
				for(var state in res){
					if(!pagelayer_empty(oldStateSel) && oldStateSel == state){
						state_options += '<option value="'+state+'" selected>'+res[state]+'</option>';
						continue;
					}
					state_options += '<option value="'+state+'">'+res[state]+'</option>';
				}
				
				stateBox.empty();
				stateBox.append(state_options);
			}
		}
	});
}

// KKart cart
function kkart_menu_cart(jEle){
	
	// On click menu cart
	jEle.find('.pagelayer-menu-cart-toggle').click(function(e){
		e.preventDefault();
		jEle.find('.pagelayer-menu-cart-container').toggle();
	});
	
	// On click menu cart close
	jEle.find('.pagelayer-menu-cart-close').click(function(){
		jEle.find('.pagelayer-menu-cart-container').hide();
	});
	
}

// Handle locale
function kkart_get_country_local(country, label){
	
	let countryObj;
	var parent = label.parent();
	
	jQuery.ajax({
		method : 'POST',
		url : kkart_ajaxurl+'action=kkart_get_country_locale',
		data : {
			kkart_nonce : kkart_ajax_nonce,
		},
		success: function(res) {
			for(let key in res){
				if(key === country){
					countryObj = res[key];
				}
			}

			label.contents().filter(function() {
                return this.nodeType === 3;
            }).replaceWith(countryObj['state']['label']);
			
			if(countryObj['state'] && 'required' in countryObj['state']){
				parent.removeClass( 'validate-required' );
				label.find('abbr').replaceWith('<span class="optional"> (Optional) </span>')
			}
			else{
				parent.addClass('validate-required' );
				label.find('span').replaceWith('<abbr class="required"> * </abbr>')
			}
		}
	});
}

Zerion Mini Shell 1.0