let page = 0;
let totalItems = 0;

// Modules functions
// Page 1 - Main page
function startCheck() {
	try {
		let batchNo = document.getElementById("select-batchNo");

		if (batchNo.value != "") {
			location.search = "moduleName=start&batchNo=" + encodeURIComponent(batchNo.value);
		} else {
			alert("Please select a batch no.");
			batchNo.focus();
		}
	} catch (error) {
		console.log(error);
	}
}

// Page 2 - Listing
function checkDetails(code, article, batchNo) {
	try {
		location.search = "moduleName=check&code=" + code + "&article=" + encodeURIComponent(article) + "&batchNo=" + encodeURIComponent(batchNo);
	} catch (error) {
		console.log(error);
	}
}

function addStock(batchNo) {
	try {
		location.search = "moduleName=add&batchNo=" + encodeURIComponent(batchNo);
	} catch (error) {
		console.log(error);
	}
}

function submitStockTake(batchNo) {
	try {
		let done = true;
		let result = true;
		let count = document.querySelectorAll('.list-group-item').length;
		let i = 0;
		for (i = 1; i <= count; i++) {
			if (document.getElementById("status" + i).innerHTML == "") {
				done = false;
				break;
			}
		}

		if (!done) {
			alert("Some items are not DONE. Please ensure all items are checked.")
			let top = document.getElementById("item" + i).offsetTop - 180;
			document.body.scrollTop = top; // For Safari
			document.documentElement.scrollTop = top; // For Chrome, Firefox, IE and Opera
			setTimeout(function () {document.getElementById("checkBtn" + i).focus();}, 750);
		} else {
			location.search = "moduleName=confirm&batchNo=" + encodeURIComponent(batchNo);
		}
	} catch (error) {
		console.log(error);
	}
}

function loadRecords() {
	try {
		// This section is commented out due to change in onLoad behaviour
		// let recPerPage = document.body.getAttribute("data-maxRec");
		// let itemHeight = document.querySelector('.list-group-item').clientHeight;
		// let availableSpace = screen.availHeight - document.querySelector('header').clientHeight - document.getElementById('header').clientHeight - document.getElementById('footer').clientHeight;

		// if (document.body.scrollTop > (recPerPage * itemHeight * (page + 1)) - availableSpace || document.documentElement.scrollTop > (recPerPage * itemHeight * (page + 1)) - availableSpace) {
		// 	// Code to retrieve records
		// }

		page++;

		let records = '';
		let count = document.querySelectorAll('.list-group-item').length;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockTakeData.asp?moduleName=start&batchNo=" + params.get("batchNo") + "&q=" + page, true);

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

				// Generate Content
				response.items.forEach(item => {
					count++;

					records += `<div class="list-group-item" id="item${count}" data-code="${item.code}" data-desc="${item.description}">
								<div class="stockTake-listing-bl">
									<b>${item.code}</b>&nbsp;&nbsp;
									<span class="stockTake-listing-itemDesc">${item.description}</span>
								</div>
								<div class="stockTake-listing-sb">
									<span class="stockTake-listing-label">
										Info&nbsp;1&nbsp;&nbsp;
									</span>
									<span class="stockTake-listing-itemDesc">
										${item.info1}
									</span>
								</div>
								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-label">
										Price Level
									</div>
									<div class="stockTake-priceLevel">
										${item.priceLevel}
									</div>
								</div>
								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-label">
										${item.regionLabel}
									</div>
									<div>
										${response.currcode + priceFormatter.format(item.region)}
									</div>
								</div>

								<hr style="margin: 5px 0;">

								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-status" id="status${count}">${item.status}</div>

									<button class="btn btn-primary checkBtn" onclick="checkDetails('${item.codeURL}', '${item.article}', '${response.batchNo}')" id="checkBtn${count}">CHECK</button>
								</div>
							</div>`;
				});

				toggleModal();

				document.getElementById('recordList').innerHTML += records;
				
				updateProgress(count);

				loadRecords();
			} else {
				document.getElementById("submitBtn").classList.remove("disabled");
			}

		}

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

function updateProgress(current) {
	try {
		let container = document.getElementById("progressBar-container");
		let progress = document.getElementById("progressBar-progress");

		let percentage = current / totalItems * 100;

		progress.style.width = percentage + "%";
	} catch (error) {
		console.log(error);
	}
}

// Page 3 - Check
function sumQty() {
	try {
		let index = document.getElementById("count").value;
		let totAcQty = 0;
		for (let i = 1; i <= index; i++) {
			if (document.getElementById(i).value != "") {
				totAcQty += parseInt(document.getElementById(i).value);
			}
		}

		document.getElementById("totAcQty").value = totAcQty;
	} catch (error) {
		console.log(error);
	}
}

function validateQty(index, max) {
	try {
		let qty = document.getElementById(index);

		if (qty.value == "") {
			qty.value = qty.getAttribute("data-oriQty");
		}

		enableMinusQty(index, qty.value);
		enableAddQty(index, qty.value, max);
		sumQty();
	} catch (error) {
		console.log(error);
	}
}

function minusQty(index, max) {
	try {
		let qty = document.getElementById(index);
		qty.value = parseInt(qty.value) - 1;

		enableMinusQty(index, qty.value);
		enableAddQty(index, qty.value, max);
		sumQty();
	} catch (error) {
		console.log(error);
	}
}

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

function addQty(index, max) {
	try {
		let qty = document.getElementById(index);
		qty.value = parseInt(qty.value) + 1;

		enableMinusQty(index, qty.value);
		enableAddQty(index, qty.value, max);
		sumQty();
	} catch (error) {
		console.log(error);
	}
}

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

function doneDetails(code, article, batchNo) {
	try {
		toggleModal();

		let index = document.getElementById("count").value;
		let acQtyStr = "";

		for (let i = 1; i <= index; i++) {
			if (i != 1) { acQtyStr += ","; }
			acQtyStr += document.getElementById(i).value;
		}

		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockTakeData.asp?moduleName=done&code=" + code + "&article=" + encodeURIComponent(article) + "&acQtyStr=" + encodeURIComponent(acQtyStr) + "&batchNo=" + encodeURIComponent(batchNo), true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("S")) {
				toggleSuccess(this.responseText);
				setTimeout(function () { toggleModal(); location.search = "moduleName=start&batchNo=" + encodeURIComponent(batchNo); }, 1500);
			} else {
				toggleFailed(this.responseText);
				setTimeout(function () { toggleModal(); location.reload(); }, 1500);
			}
		}

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

// Page 4 - Add
function addType(ref) {
	try {
		if (ref.value == "item_no") {
			params.set("addType", "item_no");
		} else {
			params.set("addType", "article");
		}

		location.search = params.toString();
	} catch (error) {
		console.log(error);
	}
}

function checkItemExists(batchNo, article) {
	try {
		let codeStr = "";
		let count = document.getElementById("listContent").getAttribute("data-count");

		for (let i = 1; i <= count; i++) {
			let code = "";

			if (article == "Y") {
				code = document.getElementById("Quad_article" + i).value;
			} else {
				code = document.getElementById("Secondary_item_no" + i).value;
			}
			

			if (code != "") {
				if (!codeStr.includes(code)) {
					codeStr += code;

					let xhr = new XMLHttpRequest();

					xhr.open("GET", "data/stockTakeData.asp?moduleName=add&code=" + encodeURIComponent(code) + "&batchNo=" + encodeURIComponent(batchNo) + "&article=" + encodeURIComponent(article) + "&q=check", true);

					xhr.onload = function () {
						// console.log(this.responseText);
						document.getElementById("itemStatusMsg" + i).innerHTML = this.responseText;
						enableConfirmAdd(article);
					}

					xhr.send();
				} else {
					document.getElementById("itemStatusMsg" + i).innerHTML = "Item Already Filled In";
				}
			} else {
				document.getElementById("itemStatusMsg" + i).innerHTML = "";
			}
		}

		enableConfirmAdd(article);
	} catch (error) {
		console.log(error);
	}
}

function clearRow(index, article) {
	try {
		if (article == "N") {
			document.getElementById("Secondary_item_no" + index).value = "";
		} else {
			document.getElementById("Quad_article" + index).value = "";
		}
		
		document.getElementById("itemStatusMsg" + index).innerHTML = "";
		enableConfirmAdd(article);
	} catch (error) {
		console.log(error);
	}
}

function newRow(batchNo, article) {
	try {
		let list = document.getElementById("listContent");
		let newIndex = parseInt(list.getAttribute("data-count")) + 1;
		let newRow = document.createElement("div");
		newRow.classList.add("list-group-item");

		if (article == "N") {
			newRow.innerHTML = `<div>
									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-label">
											Item No :
										</div>
										<div>
											<input type="text" name="item_no${newIndex}" id="Secondary_item_no${newIndex}" class="form-control" onkeyup="e = event.keyCode; if (e != 13 && e != 27){ajax_showOptions(this,'', '../itemlist_ajax_full.asp?', 1)}" onblur="checkItemExists('${batchNo}', 'N')">
										</div>
									</div>
								</div>

								<hr style="margin: 5px 0;">

								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-itemStatus" id="itemStatusMsg${newIndex}"></div>

									<button class="btn btn-secondary checkBtn" onclick="clearRow(${newIndex}, 'N')">CLEAR</button>
								</div>`;
		} else {
			newRow.innerHTML = `<div>
									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-label">
											Article :
										</div>
										<div>
											<input type="text" name="article${newIndex}" id="Quad_article${newIndex}" class="form-control" onkeyup="e = event.keyCode; if (e != 13 && e != 27){ajax_showOptions(this,'', '../articlelist.asp?', 1)}" onblur="checkItemExists('${batchNo}', 'Y')">
										</div>
									</div>
								</div>

								<hr style="margin: 5px 0;">

								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-itemStatus" id="itemStatusMsg${newIndex}"></div>

									<button class="btn btn-secondary checkBtn" onclick="clearRow(${newIndex}, 'Y')">CLEAR</button>
								</div>`;
		}

		list.appendChild(newRow);
		list.setAttribute("data-count", newIndex);
	} catch (error) {
		console.log(error);
	}
}

function enableConfirmAdd(article) {
	try {
		let index = document.getElementById("listContent").getAttribute("data-count");
		let error = false;
		let codeStr = "";

		for (let i = 1; i <= index; i++) {
			if (article == "Y") {
				codeStr += document.getElementById("Quad_article" + i).value;
			} else {
				codeStr += document.getElementById("Secondary_item_no" + i).value;
			} 

			if (document.getElementById("itemStatusMsg" + i).innerHTML != "") {
				error = true;
				break;
			}
		}

		if (error || codeStr == "") {
			document.getElementById("confirmBtn").classList.add("disabled");
		} else {
			document.getElementById("confirmBtn").classList.remove("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function confirmAdd(batchNo) {
	try {
		toggleModal();

		let addType = params.get("addType");
		let index = document.getElementById("listContent").getAttribute("data-count");
		let codeStr = "";
		let article = "Y";
		if (addType == "item_no") { article = "N"; }

		// For multiple add
		// for (let i = 1; i <= index; i++) {
		// 	let code = "";

		// 	if (article == "N") {
		// 		code = document.getElementById("Secondary_item_no" + i).value;
		// 	} else {
		// 		code = document.getElementById("Quad_article" + i).value;
		// 	}

		// 	if (code != "") {
		// 		if (codeStr != "") { codeStr += "||"; }
		// 		codeStr += code;
		// 	}
		// }

		// For single add
		if (article == "N") {
			code = document.getElementById("Secondary_item_no1").value;
		} else {
			code = document.getElementById("Quad_article1").value;
		}

		if (code != "") {
			codeStr = code;
		}


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

			xhr.open("GET", "data/stockTakeData.asp?moduleName=add&batchNo=" + encodeURIComponent(batchNo) + "&codeStr=" + encodeURIComponent(codeStr) + "&article=" + encodeURIComponent(article) + "&q=confirm", true);

			xhr.onload = function () {
				// console.log(this.responseText);
				if (this.responseText.startsWith("S")) {
					toggleSuccess(this.responseText);
					// For multiple add
					// setTimeout(function () { location.search = 'moduleName=start&batchNo=' + params.get("batchNo"); }, 1500);

					// For single add
					setTimeout(function () { toggleModal(); location.search = 'moduleName=check&batchNo=' + encodeURIComponent(params.get("batchNo")) + '&code=' + encodeURIComponent(code) + '&article=' + encodeURIComponent(article); }, 1500);
				} else {
					toggleFailed(this.responseText);
					setTimeout(function () { toggleModal(); location.reload(); }, 1500);
				}
			}

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

// Page 5 - Confirm
function clearPassword() {
	try {
		document.getElementById("password").value = "";
		document.getElementById("errMsg").innerHTML = "";
	} catch (error) {
		console.log(error);
	}
}

function enableConfirmStockTake() {
	try {
		let password = document.getElementById("password").value;

		if (password != "") {
			document.getElementById("confirmBtn").classList.remove("disabled");
		} else {
			document.getElementById("confirmBtn").classList.add("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

function confirmStockTake(batchNo) {
	try {
		toggleModal();
		let password = document.getElementById("password").value;

		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockTakeData.asp?moduleName=confirm&batchNo=" + encodeURIComponent(batchNo) + "&password=" + encodeURIComponent(password), true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("S")) {
				toggleSuccess(this.responseText);
				setTimeout(function () { toggleModal(); location.href = 'stockTake.asp'; }, 1500);
			} else {
				toggleModal();
				document.getElementById("errMsg").innerHTML = this.responseText;
			}
		}

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

function submitPassword(evt) {
	try {
		// Enter key to confirm
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if (ASCIICode == 13) {
			if (!document.getElementById("confirmBtn").classList.contains("disabled")) {
				document.getElementById("confirmBtn").click();
			}
		}
	} catch (error) {
		console.log(error);
	}
}

// Search functions
function filterSearch() {
	try {
		let listItems = document.querySelectorAll(".list-group-item");
		let searchVal = document.getElementById("search").value.toUpperCase();

		for (let i = 0; i < listItems.length; i++) {
			if (listItems[i].getAttribute("data-code").includes(searchVal) || listItems[i].getAttribute("data-desc").includes(searchVal)) {
				listItems[i].classList.add("visible");
				listItems[i].classList.remove("hide");
			} else {
				listItems[i].classList.remove("visible");
				listItems[i].classList.add("hide");
			}
		}
	} catch (error) {
		console.log(error);
	}
}

function submitSearch(evt) {
	try {
		// Enter key is not allowed
		let ASCIICode = (evt.which) ? evt.which : evt.keyCode;
		if (ASCIICode == 13) {
			return false;
		}
	} catch (error) {
		console.log(error);
	}
}

// Main Stock Take Data function
function getStockTakeData() {
	try {
		toggleModal();
		let query = location.search;
		if (query == "") { query = "?"; }

		let moduleName = "";
		if (params.has("moduleName")) {
			moduleName = params.get("moduleName"); 
		}

		let header = '';
		let main = '';
		let footer = '';
		let count = 0;
		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockTakeData.asp" + query, true);

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

				if (moduleName == "") {
					// Generate Header
					header += `<!-- User Details -->
							<h1>USER ID: ${response.curuser}<br><span class="secHeader">(${response.name})</span></h1>`;

					// Generate Content
					main += `<!-- Page 1 - Main -->
							<div class="component" style="margin-top: 10px;">`;
					
					if (response.noBatch) {
						main += `<h1 class="stockTake-listing-label">${response.noBatch}</h1>`
					} else {
						main += `<!-- Select Batch No -->
								<select class="form-select" id="select-batchNo">
									<option value="">-- SELECT A BATCH NO --</option>`;

						response.batchNos.forEach(batchNo => {
							count++;
							main += `<option value="${batchNo.batchNo}">${batchNo.batchNo} -- ${batchNo.locationDesc}</option>`;
						});

						main += `</select>

								<hr>

								<!-- Action Buttons -->
								<div style="display: flex; flex-direction: column;">
									<button onclick="startCheck();" class="btn btn-primary mb-2" style="width: 100%;">Start Check</button>
								</div>
							</div>`;
					}

				} else if (moduleName == "start") {
					// Generate Header
					header += `<div class="header-content">
								Batch No : ${response.batchNo}
								<br>
								Outlet : ${response.locationDesc} (${response.locationCode})
							</div>

							<!-- Search Bar -->
							<div role="search" class="row searchBar">
					        	<div class="col-10 g-0">
					        		<input class="form-control" type="search" name="search" id="search" placeholder="Search" aria-label="Search" onkeydown="submitSearch(event)" onkeyup="filterSearch()">
					        	</div>
					        	<label for="searchBtn" class="col-2 g-0 searchBtn">
					        		<i class="fa fa-search" aria-hidden="true" style="font-size: 18px;"></i>
					        	</label>
					        	<input type="button" id="searchBtn" onclick="filterSearch()" hidden>
					        </div>`;

					totalItems = response.totalItems;

					// Generate Content
					main += `<!-- Page 2 - Listing -->
							<div class="list-group stockTake-listing" id="recordList">`;

					response.items.forEach(item => {
						count++;

						main += `<div class="list-group-item" id="item${count}" data-code="${item.code}" data-desc="${item.description}">
									<div class="stockTake-listing-bl">
										<b>${item.code}</b>&nbsp;&nbsp;
										<span class="stockTake-listing-itemDesc">${item.description}</span>
									</div>
									<div class="stockTake-listing-sb">
										<span class="stockTake-listing-label">
											Info&nbsp;1&nbsp;&nbsp;
										</span>
										<span class="stockTake-listing-itemDesc">
											${item.info1}
										</span>
									</div>
									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-label">
											Price Level
										</div>
										<div class="stockTake-priceLevel">
											${item.priceLevel}
										</div>
									</div>
									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-label">
											${item.regionLabel}
										</div>
										<div>
											${response.currcode + priceFormatter.format(item.region)}
										</div>
									</div>

									<hr style="margin: 5px 0;">

									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-status" id="status${count}">${item.status}</div>

										<button class="btn btn-primary checkBtn" onclick="checkDetails('${item.codeURL}', '${item.article}', '${response.batchNo}')" id="checkBtn${count}">CHECK</button>
									</div>
								</div>`;
					});

					main += `</div>`;

					// Generate Footer
					footer += `<button class="btn btn-warning addBtn" onclick="addStock('${response.batchNo}')">ADD</button>
							<button id="submitBtn" class="btn btn-success submitBtn disabled" onclick="submitStockTake('${response.batchNo}')">SUBMIT</button>`;

				} else if (moduleName == "check") {
					// Generate Header
					header += `<div class="header-content">
								<div class="stockTake-listing-bl">
									<b>${response.code}</b>&nbsp;&nbsp;
									<span class="stockTake-listing-itemDesc">${response.description}</span>
								</div>
								<div class="stockTake-listing-sb">
									<span class="stockTake-listing-label">
										Info&nbsp;1&nbsp;&nbsp;
									</span>
									<span style="text-align: right;">
										${response.info1}
									</span>
								</div>
								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-label">
										Price Level
									</div>
									<div class="stockTake-priceLevel">
										${response.priceLevel}
									</div>
								</div>
								<div class="stockTake-listing-sb">
									<div class="stockTake-listing-label">
										${response.regionLabel}
									</div>
									<div>
										${response.currcode + priceFormatter.format(response.region)}
									</div>
								</div>
							</div>`;

					// Generate Content
					main += `<!-- Page 3 - Details -->
							<table class="stockTake-table" cellpadding="3px" cellspacing="0">
								<tr class="table-header" align="center">
									<td>Item No</td>
									<td>Sys Qty</td>
									<td>Act Qty</td>
									<td>UOM</td>
								</tr>`;

					response.items.forEach(item => {
						count++;
						let maxQty = 99999;
						let evenRow = "";
						if (count % 2 == 0) {
							evenRow = "evenRow";
						}

						let acQtyReadonly = "";
						if (item.sysQty === "") {
							acQtyReadonly = "readonly";
						}

						let mdisabled = "";
						let adisabled = "";
						if (item.acQty == 0 || acQtyReadonly != "") { mdisabled = 'disabled'; }
						if (item.acQty == maxQty || acQtyReadonly != "") { adisabled = 'disabled'; }


						main += `<tr class="${evenRow}" align="center">
									<td align="left">${item.itemNo}</td>
									<td>
										<input class="form-control stockTake-qty" type="text" value="${item.sysQty}" style="background-color: #EEE;" readonly>
									</td>
									<td>
										<div style="display: flex; flex-direction: row; flex-wrap: nowrap;">
											<button class="btn btn-danger details-qty-btn ${mdisabled}" id="minusQty-${count}" onclick="minusQty('${count}', ${maxQty})">
												<i class="fa fa-minus" aria-hidden="true"></i>
											</button>

											<input class="form-control stockTake-qty" type="text" name="acQty" id="${count}" value="${item.acQty}" onkeypress="return onlyNumberKey(event)" onblur="validateQty('${count}', ${maxQty})" onfocus="this.select()" data-oriQty="${item.acQty}" maxlength="${maxQty.toString().length}" ${acQtyReadonly}>

											<button class="btn btn-success details-qty-btn ${adisabled}" id="addQty-${count}" onclick="addQty('${count}', ${maxQty})">
												<i class="fa fa-plus" aria-hidden="true"></i>
											</button>
										</div>
									</td>
									<td>${item.UOM}</td>
								</tr>`;
					});

					main += `	<tr>
									<td colspan="4">
										<hr style="margin: 5px;">
									</td>
								</tr>
								<tr>
									<td width="60" style="padding-bottom: 10px;">Total Qty</td>
									<td style="padding-bottom: 10px;"><input class="form-control stockTake-qty" type="text" value="${response.totSysQty}" style="background-color: #EEE;" readonly></td>
									<td style="padding-bottom: 10px;">
										<div style="display: flex; flex-direction: row; flex-wrap: nowrap;">
											<button class="btn btn-danger details-qty-btn" style="visibility: hidden;">
												<i class="fa fa-minus" aria-hidden="true"></i>
											</button>
											<input class="form-control stockTake-qty" type="text" id="totAcQty" value="${response.totAcQty}" readonly>
											<button class="btn btn-success details-qty-btn" style="visibility: hidden;">
												<i class="fa fa-plus" aria-hidden="true"></i>
											</button>
										</div></td>
									<td>&nbsp;</td>
								</tr>
							</table>
							<input type="text" id="count" value="${count}" hidden>`;				

					// Generate Footer
					footer += `<button class="btn btn-success doneBtn" onclick="doneDetails('${response.codeURL}', '${response.article}', '${response.batchNo}');">DONE</button>`;

				} else if (moduleName == "confirm") {
					// Generate Header
					header += `<div class="header-content">
								Batch No : ${response.batchNo}
								<br>
								<table cellpadding="0">
									<tr>
										<td>Outlet :&nbsp;</td>
										<td>${response.locationDesc} (${response.locationCode})</td>
									</tr>
								</table>
							</div>`;

					// Generate Content
					main += `<!-- Page 5 - Confirm -->
							<div class="list-group stockTake-listing" style="margin-bottom: 0;">
								<div class="list-group-item">
									<div class="stockTake-listing-bl" style="justify-content: center; font-size: 18px;">
										<b>STOCK TAKE SUMMARY</b>
									</div>
								</div>`;

					if (response.noItem == undefined) {
						response.items.forEach(item => {
							main += `<div class="list-group-item">
										<div>
											<b>${item[0].article}</b>
										</div>`;

							item.forEach(i => {
								main += `<div class="stockTake-listing-sb">
											<div>
												${i.itemNo}
											</div>
											<div>
												${i.acQty}
											</div>
										</div>`;
							});
									
							main += `</div>`;
						});
					} else {
						main += `<div class="stockTake-listing-sb">
									<div>
										${response.noItem}
									</div>
								</div>`;
					}					
									
					main += `	</div>
							</div>
							<div class="list-group stockTake-listing">
								<div class="list-group-item">
									<div>
										<div class="stockTake-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 10px;">
											<b>SUBMIT STOCK TAKE</b>
										</div>
										<div class="stockTake-listing-sb">
											<div class="stockTake-listing-label" style="margin-bottom: 10px;">
												Promoter ID : <span style="color: #000; font-size: 16px;">${response.name} (${response.curuser})</span>
											</div>
										</div>
										<div class="stockTake-listing-sb">
											<div class="stockTake-listing-label">
												Password :
											</div>
											<div>
												<input type="password" id="password" class="form-control" onkeyup="enableConfirmStockTake()" onkeydown="submitPassword(event)">
											</div>
										</div>
									</div>

									<hr style="margin: 5px 0;">

									<div class="stockTake-listing-sb">
										<div class="stockTake-listing-itemStatus" id="errMsg"></div>

										<button class="btn btn-secondary checkBtn" onclick="clearPassword()">CLEAR</button>
									</div>
								</div>
							</div>`;
					

					// Generate Footer
					footer += `<button class="btn btn-success doneBtn disabled" id="confirmBtn" onclick="confirmStockTake('${response.batchNo}');">CONFIRM</button>`;

				} else if (moduleName == "add") {
					count = 1;
					let aSelected = "";
					let iSelected = "";

					if (params.get("addType") == "item_no") {
						iSelected = "selected";
					} else {
						aSelected = "selected";
					}

					// Generate Header
					header += `<div class="header-content">
								Batch No : ${response.batchNo}
								<br>
								<table cellpadding="0" style="margin-bottom: 5px;">
									<tr>
										<td>Outlet :&nbsp;</td>
										<td>${response.locationDesc} (${response.locationCode})</td>
									</tr>
								</table>

								<select class="form-select" id="addType" onchange="addType(this)">
									<option value="article" ${aSelected}>Add by Article</option>
									<!-- <option value="item_no" ${iSelected}>Add by Item No</option> -->
								</select>
							</div>`;

					// Generate Content
					if (params.get("addType") == "item_no") {
						main += `<!-- Page 4 - Add (Item No) -->
								<div class="list-group stockTake-listing-add" id="listContent" data-count="${count}">
									<div class="list-group-item">
										<div>
											<div class="stockTake-listing-sb">
												<div class="stockTake-listing-label">
													Item No :
												</div>
												<div>
													<input type="text" name="item_no${count}" id="Secondary_item_no${count}" class="form-control" onkeyup="e = event.keyCode; if (e != 13 && e != 27){ajax_showOptions(this,'', '../itemlist_ajax_full.asp?', 1)}" onblur="checkItemExists('${response.batchNo}', 'N')">
												</div>
											</div>
										</div>

										<hr style="margin: 5px 0;">

										<div class="stockTake-listing-sb">
											<div class="stockTake-listing-itemStatus" id="itemStatusMsg${count}"></div>

											<button class="btn btn-secondary checkBtn" onclick="clearRow(${count}, 'N')">CLEAR</button>
										</div>
									</div>
								</div>
								<div class="list-group stockTake-listing-add" style="margin-bottom: 110px;">
									<button class="btn btn-primary newRowBtn hide" onclick="newRow('${response.batchNo}', 'N')">New Row</button>
								</div>`;

					} else {
						main += `<!-- Page 4 - Add (Article) -->
								<div class="list-group stockTake-listing-add" id="listContent" data-count="${count}">
									<div class="list-group-item">
										<div>
											<div class="stockTake-listing-sb">
												<div class="stockTake-listing-label">
													Article :
												</div>
												<div>
													<input type="text" name="article${count}" id="Quad_article${count}" class="form-control" onkeyup="e = event.keyCode; if (e != 13 && e != 27){ajax_showOptions(this,'', '../articlelist.asp?', 1)}" onblur="checkItemExists('${response.batchNo}', 'Y')">
												</div>
											</div>
										</div>

										<hr style="margin: 5px 0;">

										<div class="stockTake-listing-sb">
											<div class="stockTake-listing-itemStatus" id="itemStatusMsg${count}"></div>

											<button class="btn btn-secondary checkBtn" onclick="clearRow(${count}, 'Y')">CLEAR</button>
										</div>
									</div>
								</div>
								<div class="list-group stockTake-listing-add" style="margin-bottom: 110px;">
									<button class="btn btn-primary newRowBtn hide" onclick="newRow('${response.batchNo}', 'Y')">New Row</button>
								</div>`;
					}

					// Generate Footer
					footer += `<button class="btn btn-success doneBtn disabled" id="confirmBtn" onclick="confirmAdd('${response.batchNo}');">CONFIRM ADD</button>`;
				}
			} else {
				toggleFailed(this.responseText);
				// setTimeout( function () { toggleModal(); history.back(); }, 1000);
			}

			document.getElementById('header').innerHTML = header;
			document.getElementById('main').innerHTML = main;
			document.getElementById('footer').innerHTML = footer;

			// Onload functions
			if (moduleName == "start") {
				loadRecords();
				updateProgress(count);
			}

			toggleModal();
		}

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

getStockTakeData();