﻿
// this requires jQuery to be installed

function AddToBasket(productID, quantity, doReload) {
	return ChangeBasket(productID, quantity, doReload)
}

function AddMultipleToBasket(jQele, productID) {
	return AddToBasket(productID, parseInt(jQele.val()), false);
}

function DeleteFromBasket(productID, quantity, doReload) {
	return ChangeBasket(productID, quantity * -1, doReload)
}

function ChangeBasket(productID, quantity, doReload) {
	// add quantity to the basket icon
	var totalItems = $("#basket_total").html();
	if (totalItems != null) {
		totalItems = parseInt(totalItems);
		totalItems = totalItems + quantity;
		$("#basket_total, #basket_total2").html(totalItems);
	}

	var taskType = 'add';
	if (quantity < 0) {
		taskType = 'delete';
		quantity = quantity * -1
	}

	// update the basket
	$.get('services/update_basket.aspx', { task: taskType, id: productID, qty: quantity, rnd: Math.random() })

	if (doReload) document.location = document.location + ''; //  + '&rnd=' + Math.random(); // doesn't work: location.reload(true);
	return false;
}

function DeleteSavedOrder(ele, order) {
	if (!confirm('Are you sure you want to delete this saved order?')) return false;

	var rowsLeft = $('TR', GetRow(ele).parent()).length;

	// delete the row
	GetRow(ele).remove();
	// delete from the system
	$.get('services/update_basket.aspx', { task: 'deleteorder', id: order, rnd: Math.random() })

	if (rowsLeft <= 2) {
		location.reload(true);
	}

	return false;
}

function GetRow(somethingInACell) {
	return $(somethingInACell).parent().parent();
}

function AddSearchResultToBasket(ele) {
	var productID = $.trim($('.productCode', GetRow(ele)).html());
	var quantity = $.trim($('.quantity_field', GetRow(ele)).val());

	AddToBasket(productID, quantity, false)
	UpdateBasketCount(quantity)

	return false;
}

function TallyUpSelectedSearchResults() {
	var selectedItems = '';
	$('.item_selected:checked').each(function (index) {
		var item = $.trim($(this).val());
		var quantity = $('.quantity_field', GetRow(this)).val();
		selectedItems += item + '\t' + quantity + '\n';
	})

	$('#SelectedSearchResults').val(selectedItems);
	//alert($('#SelectedSearchResults').val());
	return true;
}

function UpdateBasketCount(quantity) {
	var basketCount = $('.basket-count').html();
	if (basketCount == null || basketCount == '') {
		// do nothing more - can't find the basket total on page
	}
	else {
		var total = parseFloat(basketCount);
		total += parseFloat(quantity);
		$('.basket-count').html(total);
	}
}
