var flag = 0;
var offset = 6;
var pageNumber = 1;
var keyword = document.getElementById('q').value;

function loadMore(){
	console.log('I can read the javascript');
	$('#load-more').html('Loading..');
	pageNumber = pageNumber + 1;
	var keyword = '';
	var category_id = '';
	
	const queryString = window.location.search;
	const urlParams = new URLSearchParams(queryString);
	if(urlParams.has('q')){
		var keyword = urlParams.get('q');
	}else if(urlParams.has('scid')){
		var sub_category_id = urlParams.get('scid');
	}
	
	$.ajax({
		type: "POST",
		url:  "process.php",
		data: {
			get_product : 1,
			limit : 6,
			offset : offset,
			keyword : keyword,
			sub_category_id : sub_category_id
		},
		success: function(data){
			offset  += 6;
			$('#products').append(data);
			$('#load-more').html('Click to load more');
		}
	})
}

function querySearch(searchType, value){
	var search = document.getElementById('q').value;
	
	if(searchType == 'subcategory'){
		keyword = value;
	}else if(searchType == 'search'){
	    keyword = search;
	}
	console.log(keyword);
	
	$.ajax({
		type: "POST",
		url: "process.php",
		data: {
			get_product : 1,
			offset : 0,
			searchType : searchType,
			keyword : keyword,
			limit : 6
		},
		success: function(data){
				$('#products').html(data);
				flag  += 6;
				console.log(data);
		}
	});
}

function addToCart(pid, price, product_name, product_image){
	console.log(product_image + ' ' + product_name + ' ' + price + ' ' + pid );
	var query = 'add';
	var quantity = 1;
	var action = 'increment';
	
	$.ajax({
		type: "POST",
		url: "process.php",
		data: {
			query_cart : 1,
			query : query,
			product_id : pid,
			product_name : product_name,
			product_image : product_image,
			price: price,
			quantity : quantity,
			action : action
		},
		success: function(data){
				location.reload(true);
		}
	});
}

function removeFromCart(pid, price, product_name, product_image){
	
	var query = 'remove';
	var quantity = 1;
	var action = '';
	
	$.ajax({
		type: "POST",
		url: "process.php",
		data: {
			query_cart : 1,
			query : query,
			product_id : pid,
			product_name : product_name,
			product_image : product_image,
			price: price,
			quantity : quantity,
			action : action
		},
		success: function(data){
				location.reload(true);
		}
	});
}

function updateCart(pid, price, product_name, product_image){
	
	var query = 'replace';
	var quantity = $('#qty_'+pid).val();
	var action = 'replace';
	
	$.ajax({
		type: "POST",
		url: "process.php",
		data: {
			query_cart : 1,
			query : query,
			product_id : pid,
			product_name : product_name,
			product_image : product_image,
			price: price,
			quantity : quantity,
			action : action
		},
		success: function(data){
			    location.reload(true);
		}
	});
}