function getQuickOrderData() {
	try {
		let html = '';
		let itemCount = 0;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/quickOrderData.asp?query=get", true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("{")) {
				let response = JSON.parse(this.responseText);

				html += `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8">
							<div class="breadcrumbs">
								<span>Profile</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Quick Order
							</div>
							<div class="component pageHeader">
								<span class="pageHeader-label">Quick Order</span>
								<div class="pageHeader-addToCart">
									<div class="btn btn-warning addToCartBtn" onclick="addToCart()" id="addToCart">Add To Cart</div>
								</div>
							</div>
							<div class="component">
								<div class="list-group">`;

				response.items.forEach(item => {
					let itemDisc = '';
					if (item.showItemDisc && item.discount > 0) {
						itemDisc = `<p class="quickOrder-itemDisc"><span class="quickOrder-oriPrice">${response.currcode}${priceFormatter.format(item.oriPrice)}</span>&nbsp;&nbsp;<span class="quickOrder-discLabel">-${item.discount}%</span></p>`;
					}

					html += `<div class="list-group-item quickOrder-list-item">
								<div style="background: url('${item.pictpath}');" class="quickOrder-list-item-img"></div>

								<div class="quickOrder-list-item-desc">
									${item.gcatalogue}
				        			<p class="quickOrder-itemLabel">${item.icatalogue}</p>
				        			<p class="quickOrder-itemNo">${item.item_no + " " + item.item_no2}</p>
				        			<p class="quickOrder-price">
				        				<span class="quickOrder-price-label">${response.currcode}</span>${priceFormatter.format(item.price)}
				        			</p>
				        			${itemDisc}

				        			<div class="quickOrder-qty">
			        					<span class="btn btn-danger quickOrder-qty-btn disabled" onclick="minusQty(${itemCount})" id="minusQtyq-${itemCount}">
			        						<i class="fa fa-minus" aria-hidden="true"></i>
			        					</span>

			        					<input type="text" class="quickOrder-qty-amount" id="q-${itemCount}" onkeypress="return validateQty(event, this, ${response.maxOrderPerItem})" onblur="setDefaultQty(this, ${response.maxOrderPerItem})" onfocus="this.select()" value="0" maxlength="${response.maxOrderPerItem.toString().length}" data-itemNo="${item.item_no}"/>

			        					<span class="btn btn-success quickOrder-qty-btn" id="addQtyq-${itemCount}" onclick="addQty(${itemCount}, ${response.maxOrderPerItem})">
			        						<i class="fa fa-plus" aria-hidden="true"></i>
			        					</span>
			        				</div>
								</div>
							</div>`;
					itemCount++;
				});

				if (itemCount == 0) {
					html += `<div id="error" class="error">
								<h2>Quick Order Unavailable</h2>
								<p>None of the items in your previous orders can be displayed.</p>
							</div>`;
				}

				html += `		</div>
							</div>
						</div>`;
			} else {
				html = `<div class="col-12 col-lg-11 col-xl-9 col-xxl-8 breadcrumbs">
							<span>Profile</span>&nbsp;&nbsp;<i class="fa fa-angle-double-right" aria-hidden="true"></i>&nbsp;&nbsp;Quick Order
						</div>
						<!-- Error -->
						<div id="error" class="error col-12 col-lg-11 col-xl-9 col-xxl-8 component">
							<h2>Quick Order Unavailable</h2>
							<p>You have not made any previous orders.</p>
						</div>`;
			}

			document.getElementById('quickOrder').innerHTML = html;
		}

		xhr.send();
	} catch (error) {
		console.log(error);
	}
}

function validateQty(evt, ref, max) {
	try {
		// Only numbers are allowed
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if ((ASCIICode < 48 || ASCIICode > 57) && ASCIICode != 127 && ASCIICode != 8) {
			return false;
		} else {
			if (parseInt(ref.value + evt.key) >= max) {
				ref.value = max;
				enableAddQty(ref.getAttribute("id"), ref.value, max);
				return false;
			}
			
			enableMinusQty(ref.getAttribute("id"), parseInt(ref.value + evt.key));
			enableAddQty(ref.getAttribute("id"), parseInt(ref.value + evt.key), max);

			return true;
		}
	} catch (error) {
		console.log(error);
	}
}

function setDefaultQty(ref, max) {
	try {
		if (!(ref.value > 0)) {
			ref.value = 0;
		}

		enableMinusQty(ref.getAttribute("id"), ref.value);
		enableAddQty(ref.getAttribute("id"), ref.value, max);
	} catch (error) {
		console.log(error);
	}
}

function addQty(index, max) {
	try{
		let qty = document.getElementById("q-" + index);

		if (qty.value < max) { 
			qty.value = parseInt(qty.value) + 1;
			document.getElementById('minusQtyq-' + index).classList.remove("disabled");
		}

		enableAddQty("q-" + index, qty.value, max);
	} catch (error) {
		console.log(error);
	}
}

function minusQty(index) {
	try{
		let qty = document.getElementById("q-" + index);

		if (qty.value > 0) { 
			qty.value = parseInt(qty.value) - 1;
			document.getElementById('addQtyq-' + index).classList.remove("disabled");
		}

		enableMinusQty("q-" + index, qty.value);
	} catch (error) {
		console.log(error);
	}
}

function enableMinusQty(index, value) {
	try {
		if (value <= 0 || value == "") {
			document.getElementById('minusQty' + index).classList.add("disabled");
		} else {
			document.getElementById('minusQty' + index).classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function enableAddQty(index, value, max) {
	try {
		if (value >= max) {
			document.getElementById('addQty' + index).classList.add("disabled");
			document.getElementById('minusQty' + index).classList.remove("disabled");
		} else {
			document.getElementById('addQty' + index).classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function toggleModal() {
	try {
		document.getElementById('modal').classList.toggle("hide");
	} catch (error) {
		console.log(error);
	}
}

function toggleQuickOrderSuccess() {
	try {
		document.getElementById('loading').classList.toggle("hide");
		document.getElementById('quickOrderSuccess').classList.toggle("hide");
		setTimeout(function () { location.reload(); }, 2000);
	} catch (error) {
		console.log(error);
	}
}

function toggleQuickOrderFailed(message) {
	try {
		document.getElementById('loading').classList.toggle("hide");
		document.getElementById('quickOrderFailed').classList.toggle("hide");
		document.getElementById('failedMessage').innerHTML = message;
		setTimeout(function () { location.reload(); }, 1500);
	} catch (error) {
		console.log(error);
	}
}

function addToCart() {
	try {
		toggleModal();

		let index = 0;
		let itemList = "";
		let qtyList = "";

		while (document.getElementById("q-" + index) != undefined) {
			if (document.getElementById("q-" + index).value != 0) {
				if (itemList != "") { itemList += "+"; qtyList += "+"; }
				itemList += document.getElementById("q-" + index).getAttribute("data-itemNo");
				qtyList += document.getElementById("q-" + index).value;
			}

			index++;
		}

		if (itemList != "") {
			let xhr = new XMLHttpRequest();

			xhr.open("GET", "data/quickOrderData.asp?itemList=" + encodeURIComponent(itemList) + "&qtyList=" + encodeURIComponent(qtyList) + "&query=add", true);

			xhr.onload = function () {
				// console.log(this.responseText);
				if (this.responseText == "") {
					toggleQuickOrderSuccess();
				} else {
					toggleQuickOrderFailed(this.responseText);
				}
			}

			xhr.send();
		} else {
			toggleQuickOrderFailed("No items to be added");
		}
	} catch (error) {
		console.log(error);
	}
}

getQuickOrderData();