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

// Lets start
jQuery(document).ready(function(){
	
	// Accordion handler
	kkart_accordion_toggler();
	
	// On Change product type handler
	kkart_product_data_actions();
	
	// Product gallery handler
	kkart_product_gallery_handler();
	
	// Setting page JS
	kkart_admin_tabs();
	kkart_admin_accordion();

	kkart_show_addressform();
	
});

function kkart_admin_tabs(){
	jQuery('.nav-tab-wrapper a').click(function(){

		var tEle = jQuery(this);
		
		var sel = tEle.attr('tab-class') || 'kkart-tab-panel';
		
		// Limit effect to the container element.
		var context = tEle.closest('.nav-tab-wrapper').parent().parent();
		context.find('.nav-tab-wrapper a').removeClass('nav-tab-active');
		tEle.addClass('nav-tab-active');
		context.find('.'+sel).hide();
		context.find(tEle.attr('href')).show();
		
		return false;
		
	});

	// Make setting nav-tab-active optional.
	jQuery('.nav-tab-wrapper.kkart-wrapper').each(function(){
				
		var jEle = jQuery(this);
		var hash = location.hash.slice(1);
		
		if(hash){
			var active_tab_ele = jEle.find('[href="#'+hash+'"]');
			if (active_tab_ele.length > 0){
				active_tab_ele.click();
			}
		}else{
			var first = jEle.find('a').first();
			first.click();
		}
		
	});
}

function kkart_admin_accordion(){
	
	jQuery('.kkart-acc-wrapper .kkart-acc-tab').click(function(){

		var tEle = jQuery(this);
		
		if(tEle.hasClass('nav-tab-active')){
			tEle.toggleClass('nav-tab-active').next('.kkart-acc-panel').toggle();
		}else{
			// Limit effect to the container element.
			var context = tEle.closest('.kkart-acc-wrapper ');
			context.find('.kkart-acc-tab').removeClass('nav-tab-active');
			context.find('.kkart-acc-panel').hide();
			tEle.addClass('nav-tab-active');
			tEle.next('.kkart-acc-panel').show();
		}
	});
	
	// Make setting nav-tab-active optional.
	jQuery('.kkart-acc-wrapper').each(function(){
				
		var jEle = jQuery(this);
		
		var active_acc_ele = jEle.find('nav-tab-active');
		if (active_acc_ele.length > 0){
			active_acc_ele.click();
		}else{
			jEle.find('.kkart-acc-tab').first().click();
		}
		
	});
}

// Accordion handler
function kkart_accordion_toggler(){
	
	// On Click accordion title
	jQuery('.kkart-accordion-holder').find('.kkart-accordion-title').on('click', function(){
		var ele = jQuery(this);
		var cItem = ele.closest('.kkart-accordion-item');
		
		if(cItem.hasClass('kkart-accordion-open')){
			cItem.removeClass('kkart-accordion-open');
			return;
		}
		
		ele.closest('.kkart-accordion-holder').find('.kkart-accordion-item').removeClass('kkart-accordion-open');
		cItem.addClass('kkart-accordion-open');
		
	});

}

// Accordion handler
function kkart_product_data_actions(){
	
	var metaHolder = jQuery('.kkart-product-meta');
	var product_type = metaHolder.find('select[name="product_type"]');
	var product_val = product_type.val();
	
	// Show tabs by product type
	var showTab = function(value){
		var mEle = metaHolder.find('[kkart-show-tab*="'+value+'"]');
		
		metaHolder.find('.kkart-accordion-item').hide();
		mEle.first().find('.kkart-accordion-title').click();
		mEle.show();
	}
	
	showTab(product_val);
	
	// On change product type handler
	product_type.on('change', function(){
		showTab(jQuery(this).val());
	});
	
	// If product sale date is ON
	var sDateHolder = jQuery('.kkart-sale-date');
	var sFrom = sDateHolder.find('[name="product_price_sale_from"]');
	var sTO = sDateHolder.find('[name="product_price_sale_to"]');
	
	if(sFrom.val()){
		sDateHolder.show();
	}else{
		sDateHolder.hide();
	}
	
	// Cancel the Schedule
	sDateHolder.find('.kkart-cancel-schedule').on('click', function(){
		metaHolder.find('.kkart-set-schedule').show();
		sFrom.val('');
		sTO.val('');
		sDateHolder.hide();
	});
	
	// Set the Schedule
	metaHolder.find('.kkart-set-schedule').on('click', function(){
		jQuery(this).hide();
		sDateHolder.show();
	});
	
	// If product is downloadable
	var isDownload = metaHolder.find('[name="product_is_downloadable"]');
	
	var showDownloadSec  = function(val){
		if(val){
			metaHolder.find('.kkart-product-downloadable').show();
		}else{
			metaHolder.find('.kkart-product-downloadable').hide();
		}
	}
	
	// download fields
	showDownloadSec(isDownload.is(':checked'));
	isDownload.on('change', function(){
		showDownloadSec(jQuery(this).is(':checked'));
	});
	
	// If product tracker on
	var isTracker = metaHolder.find('[name="product_track"]');
	
	var showQuantitySec  = function(val){
		if(val){
			metaHolder.find('.kkart-product-quantity').show();
			metaHolder.find('.kkart-product-status').hide();
		}else{
			metaHolder.find('.kkart-product-quantity').hide();
			metaHolder.find('.kkart-product-status').show();
		}
	}
	
	// Show download fields
	showQuantitySec(isTracker.is(':checked'));
	isTracker.on('change', function(){
		showQuantitySec(jQuery(this).is(':checked'));
	});
	
	// If product shippable
	var isShippable = metaHolder.find('[name="product_is_virtual"]');
	
	var showhippableSec  = function(val){
		if(val){
			metaHolder.find('.kkart-product-shipping').hide();
		}else{
			metaHolder.find('.kkart-product-shipping').show();
		}
	}
	
	// Show download fields
	showhippableSec(isShippable.is(':checked'));
	isShippable.on('change', function(){
		showhippableSec(jQuery(this).is(':checked'));
	});
	
	// Calculate the profit
	var product_price_actual = metaHolder.find('[name="product_price_actual"]');
	
	product_price_actual.on('change', function(){
		
		var actual_val = product_price_actual.val();
		var marginDiv = metaHolder.find('.kkart-margin-value');
		var profitDiv = metaHolder.find('.kkart-profit-value');
		
		if(!actual_val){
			marginDiv.html(0);
			profitDiv.html(0);
			return;
		}
		
		var price_val = metaHolder.find('[name="product_sale_price"]').val();
		
		if(!price_val){
			price_val = metaHolder.find('[name="product_price"]').val();
		}
		
		var profit = price_val - actual_val;
		var margin = profit*100/price_val;
		
		marginDiv.html(margin.toFixed(2));
		profitDiv.html(profit.toFixed(2));

	});
	
	product_price_actual.trigger('change');
	
}

// Product gallery handler
function kkart_product_gallery_handler(){
	
	var gallery_ids = jQuery('[name="kkart_product_gallery_ids"]');
	var gallery_preview = jQuery('.kkart-product-gallery-preview');
	var ids = new Array();
	
	gallery_preview.empty();
	
	// Any IDs ?
	if(gallery_ids.val() != '' && gallery_ids.val() !== undefined){
		ids = gallery_ids.val().split(',');
	}
	
	// Add to current selection
	for(var i = 0; i < ids.length; i++){
		// preload your attachment
		wp.media.attachment(ids[i]).fetch().then(function (data) {
			var url = data.url;
			// Create thumbnails
			gallery_preview.append('<div class="kkart-product-gallery-thumb" style="background-image: url(\''+url+'\');"></div>');
		});
	}
	
	
	// Set an Image
	jQuery('.kkart-add-product-gallery').on('click', function(){
	
		var button = jQuery(this);
		var state = 'gallery-library';
		
		ids = new Array();
	
		// Any IDs ?
		if(gallery_ids.val() != ''){
			ids = gallery_ids.val().split(',');
			state = 'gallery-edit';
			//console.log(ids);
		}

		// Load the frame
		var frame = wp.media({
			id: 'kkart-wp-multi-image-library',
			frame: 'post',
			title: 'KKART Product gallery',
			state: state,
			multiple: true,
			library: wp.media.query({type: 'image'}),
			button: {
				text: 'Insert'
			},
		});
		
		frame.on({
		'menu:render:default': function(view){
				view.unset('insert');
				view.unset('gallery');
				view.unset('featured-image');
				view.unset('playlist');
				view.unset('video-playlist');
			},
		}, this);
		
		// On select update the stuff
		frame.on({
			
			'select': function(){
				
				var state = frame.state();
				var id = url = '';
				var urls = {};

				// External URL
				if('props' in state){
					//console.log(state);
					var urls_str = state.props.attributes.url;
					
					var urls_arr = urls_str.split(',');
					//console.log(urls_arr);
					
					gallery_preview.empty();
					
					// Add to current selection
					for(var i = 0; i < urls_arr.length; i++){
						var single_url = pagelayer_parse_theme_vars(urls_arr[i]);
						urls['i'+i] = single_url;
						
						// Create thumbnails
						gallery_preview.append('<div class="kkart-product-gallery-thumb" style="background-image: url(\''+single_url+'\');"></div>');
					}
					
					urls_arr = Object.values(urls);
					
					//_pagelayer_set_tmp_atts(row, 'urls', JSON.stringify(urls));
					gallery_ids.val(urls_arr.join());
					
				}
			},
			
			// Set the current selection if any
			'open': function(){

				// Do we have anything
				if(ids.length > 0){
										
					if(state == 'gallery-edit'){
						selection = frame.state().get('library');
					}else{
						selection = frame.state().get('selection');
					}
					
					// Add to current selection
					//if(!selection){
						for(var x in ids){
							attachment = wp.media.attachment(ids[x]);
							attachment.fetch();
							selection.add(attachment ? [ attachment ] : [] );
						}
					//}
				}
			},
			
			// When images are selected
			'update': function(selection){
				
				//console.log(selection);
				
				// Remove thumbnails
				gallery_preview.empty();

				//Fetch selected images
				var attachments = selection.map(function(attachment){
					attachment.toJSON();
					return attachment;
				});
				
				//console.log(attachments);
				
				var img_ids = [];
				
				for(var i = 0; i < attachments.length; ++i){
					
					// Add Id and urls to array
					var id = attachments[i].id;
					img_ids.push(id);
					
					// Create thumbnails
					gallery_preview.append('<div class="kkart-product-gallery-thumb" style="background-image: url(\''+attachments[i].attributes.url+'\');"></div>');
										
				}
								
				// Update the IDs incase the user clicks on it again
				gallery_ids.val(img_ids);
			}
			
		});
		
		frame.open(button);
		
		return false;
		
	});
}

function kkart_show_addressform(){
	
	// On Click edit title
	jQuery('.kkart-edit-address').click(function(){
		var context = jQuery(this);
		var cEpe = $(context).parent().closest('.kkart-order-address');
		
		var cEce = cEpe.find('.kkart-address-edit');
		
		if(cEce.hasClass('kkart-hide-data')){
			cEpe.find('.dashicons').removeClass('dashicons-edit');
			cEpe.find('.dashicons').addClass('dashicons-minus');
			cEce.removeClass('kkart-hide-data');
		}else{
			cEpe.find('.dashicons').addClass('dashicons-edit');
			cEpe.find('.dashicons').removeClass('dashicons-minus');
			cEce.addClass('kkart-hide-data');
		}
	});
}