let page = 0;

// Modules functions
// Page 1 - Listing
function newRequest() {
	try {
		location.search = "moduleName=new";
	} catch (error) {
		console.log(error);
	}
}

function checkStockReturn(orderID, orderID2, locCode) {
	try {
		location.search = "moduleName=check&code=" + orderID + "&code2=" + orderID2 + "&locationCode=" + encodeURIComponent(locCode);
	} catch (error) {
		console.log(error);
	}
}

function loadRecords() {
	try {
		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) {
			page++;

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

			xhr.open("GET", "data/stockReturnData.asp?q=" + page, true);

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

					// Generate Content
					response.transfers.forEach(transfer => {
						count++;
						let evenRow = "";

						if (count % 2 == 0) { evenRow = "evenRow"; }

						let orderID = "";
						if (transfer.orderID2 != "") {
							orderID = transfer.orderID2;
						} else {
							orderID = transfer.orderID;
						}

						let status = "";
						if (transfer.status == "Draft" || transfer.status == "Submitted") {
							status = `<div class="${transfer.status}">
										${transfer.status} by ${transfer.createdBy}
									</div>
									<button class="btn btn-primary checkBtn" onclick="checkStockReturn('${transfer.orderIDURL}', '${transfer.orderID2URL}', '${transfer.location}')" id="checkBtn${count}">CHECK</button>`;
						} else {
							status = `<div>
										${transfer.status} by ${transfer.createdBy}
									</div>
									<div>
										${transfer.statusID}
									</div>`;
						}

						records += `<div class="list-group-item ${evenRow}" id="request${count}" data-code="${transfer.orderID}" data-code2="${transfer.orderID2}" data-loc="${transfer.location}">
									<div class="stockReturn-listing-sb">
										<b>${orderID}</b>&nbsp;&nbsp;
										<span class="stockReturn-listing-date">${transfer.daterecorded}</span>
									</div>
									<div>
										<div class="stockReturn-listing-sb">
											<div class="stockReturn-listing-label">
												Location
											</div>
											<div>
												${transfer.location}
											</div>
										</div>
										<div class="stockReturn-listing-sb">
											<div class="stockReturn-listing-label">
												Loc.&nbsp;Desc
											</div>
											<div style="text-align: right;">
												${transfer.locationDesc}
											</div>
										</div>
									</div>

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

									<div class="stockReturn-listing-sb stockReturn-listing-status ${transfer.status}">
										${status}
									</div>
								</div>`;
					});

					toggleModal();
				}

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

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

// Page 2 - New / Check
function addType(ref) {
	try {
		if (ref.value == "item_no") {
			document.getElementById("forAddItem").classList.remove("hide");
			document.getElementById("searchItem").classList.remove("hide");
			document.getElementById("forAddArticle").classList.add("hide");
			document.getElementById("forAddArticle").classList.add("disabled");
			document.getElementById("searchArticle").classList.add("hide");
			document.getElementById("Quad_article").value = "";
		} else {
			document.getElementById("forAddArticle").classList.remove("hide");
			document.getElementById("searchArticle").classList.remove("hide");
			document.getElementById("forAddItem").classList.add("hide");
			document.getElementById("forAddItem").classList.add("disabled");
			document.getElementById("searchItem").classList.add("hide");
			document.getElementById("Secondary_item_no").value = "";
		}
	} catch (error) {
		console.log(error);
	}
}

function showSuggestion(ref, article) {
	try {
		let locCode = document.getElementById("selectLoc").value;

		if (document.getElementById("selectLoc").getAttribute("data-loc") != "") {
			locCode = document.getElementById("selectLoc").getAttribute("data-loc");
		}

		if (article == "Y") {
			let e = event.keyCode; 
			if (e != 13 && e != 27){
				ajax_showOptions(ref,'', '../articlelist_groups.asp?TransType=TR&locCode=' + encodeURIComponent(locCode), 1)}
		} else {
			let e = event.keyCode;
			if (e != 13 && e != 27){
				ajax_showOptions(ref,'', '../itemlist_groups.asp?TransType=TR&locCode=' + encodeURIComponent(locCode), 1)}
		}
	} catch (error) {
		console.log(error);
	}
}



function checkItemExists(ref, article) {
	try {
		let code = ref.value.trim();
		let codeStr = "";
		let enable = false;

		if (code != "") {
			let itemRows = document.querySelectorAll(".itemRow");

			if (article == "Y") {
				for (let i = 0; i < itemRows.length; i++) {
					if (itemRows[i].getAttribute("data-article") == code) {
						codeStr += "|" + itemRows[i].getAttribute("data-code") + "|";
					}
				}

				let xhr = new XMLHttpRequest();

				xhr.open("GET", "data/stockReturnData.asp?moduleName=new&code=" + encodeURIComponent(code) + "&codeStr=" + codeStr + "&article=" + encodeURIComponent(article) + "&q=check", true);

				xhr.onload = function () {
					// console.log(this.responseText);
					let response = JSON.parse(this.responseText);
					enableAddStock(response.enable, article);
				}

				xhr.send();
			} else {
				let i = 0;

				for (i = 0; i < itemRows.length; i++) {
					if (itemRows[i].firstElementChild.innerHTML == code) {
						break;
					}
				}

				if (i == itemRows.length) {
					let xhr = new XMLHttpRequest();

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

					xhr.onload = function () {
						// console.log(this.responseText);
						let response = JSON.parse(this.responseText);
						enableAddStock(response.enable, article);
					}

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

function enableAddStock(enable, article) {
	try {
		if (article == "Y") {
			if (enable) {
				document.getElementById("forAddArticle").classList.remove("disabled");
			} else {
				document.getElementById("forAddArticle").classList.add("disabled");
			}
		} else {
			if (enable) {
				document.getElementById("forAddItem").classList.remove("disabled");
			} else {
				document.getElementById("forAddItem").classList.add("disabled");
			}
		}
	} catch (error) {
		console.log(error);
	}
}

function addStock(article) {
	try {
		toggleModal();
		let code = "";
		let codeStr = "";
		let locCode = document.getElementById("selectLoc").value;
		let html = "";

		if (article == "Y") {
			code = document.getElementById("Quad_article").value.trim();
			let itemRows = document.querySelectorAll(".itemRow");

			for (let i = 0; i < itemRows.length; i++) {
				if (itemRows[i].getAttribute("data-article") == code) {
					codeStr += "|" + itemRows[i].getAttribute("data-code") + "|";
				}
			}
		} else {
			code = document.getElementById("Secondary_item_no").value.trim();
		}

		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockReturnData.asp?moduleName=new&code=" + encodeURIComponent(code) + "&codeStr=" + codeStr + "&locationCode=" + encodeURIComponent(locCode) + "&article=" + encodeURIComponent(article) + "&q=add", true);

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

				response.items.forEach(item => {
					let itemList = document.getElementById('itemList');
					let newRow = itemList.childNodes.length + 1;

					let newNode = document.createElement("tr");
					newNode.classList.add("itemRow");
					if (newRow % 2 == 0) { newNode.classList.add("evenRow"); }
					newNode.setAttribute("align", "center");
					newNode.setAttribute("data-code", item.codeURL);
					newNode.setAttribute("data-article", item.article);
					newNode.setAttribute("data-UOM", item.u_measure);
					newNode.innerHTML = `<td width="30" class="rowNumber">${newRow}</td>
										<td align="left">
											<b>${item.code}</b>
											<br>
											<span class="stockReturn-listing-label stockReturn-priceLevel">${item.priceLevel}</span>
											<br>
											<span class="stockReturn-listing-itemDesc">${item.description}</span>
										</td>
										<td>
											<div style="display: flex; flex-direction: row; flex-wrap: nowrap;">
												<button class="btn btn-danger details-qty-btn mBtn disabled" id="minusQty-${newRow}" onclick="minusQty('${newRow}', ${response.maxQty})">
													<i class="fa fa-minus" aria-hidden="true"></i>
												</button>

												<input class="form-control stockReturn-qty" type="text" name="qty" id="${newRow}" value="0" onkeypress="return onlyNumberKey(event)" onblur="validateQty('${newRow}', ${response.maxQty})" onfocus="this.select()" maxlength="${response.maxQty.toString().length}">

												<button class="btn btn-success details-qty-btn aBtn" id="addQty-${newRow}" onclick="addQty('${newRow}', ${response.maxQty})">
													<i class="fa fa-plus" aria-hidden="true"></i>
												</button>
											</div>
										</td>
										<td class="stockReturn-price" id="price${newRow}">${priceFormatter.format(item.price)}</td>
										<td>
											<span class="btn btn-outline-danger py-1 px-2" onclick="deleteItem('${item.codeURL}', ${response.maxQty})">
												<i class="fa fa-trash" aria-hidden="true" style="font-size: 18px;"></i>
											</span>
										</td>`;

					itemList.appendChild(newNode);
				});

				document.getElementById("Secondary_item_no").value = "";
				document.getElementById("Quad_article").value = "";
				document.getElementById("forAddItem").classList.add("disabled");
				document.getElementById("forAddArticle").classList.add("disabled");
				document.getElementById("selectLoc").setAttribute("disabled", "disabled");
				filterSearch();

				document.body.scrollTop = document.body.scrollHeight; // For Safari
  				document.documentElement.scrollTop = document.documentElement.scrollHeight; // For Chrome, Firefox, IE and Opera
				toggleModal();
			} else {
				toggleFailed(this.responseText);
				setTimeout( function () { toggleModal(); }, 1000);
			}
		}

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

function deleteItem(code, maxQty) {
	try {
		let itemList = document.getElementById('itemList');
		let itemRows = document.querySelectorAll(".itemRow");
		for (let i = 0; i < itemRows.length; i++) {
			if (itemRows[i].getAttribute("data-code") == code) {
				itemList.removeChild(itemRows[i]);
				break;
			}
		}

		let rowNumber = document.querySelectorAll(".rowNumber");
		let mqty = document.querySelectorAll(".mBtn");
		let qty = document.querySelectorAll(".stockReturn-qty");
		let aqty = document.querySelectorAll(".aBtn");
		let price = document.querySelectorAll(".stockReturn-price");
		itemRows = document.querySelectorAll(".itemRow");
		for (let j = 0; j < itemRows.length; j++) {
			rowNumber[j].innerHTML = (j + 1);
			mqty[j].setAttribute("id", "minusQty-" + (j + 1));
			mqty[j].setAttribute("onclick", "minusQty('" + (j + 1) + "', " + maxQty + ")");
			qty[j].setAttribute("id", j + 1);
			aqty[j].setAttribute("id", "addQty-" + (j + 1));
			aqty[j].setAttribute("onclick", "addQty('" + (j + 1) + "', " + maxQty + ")");
			price[j].setAttribute("id", "price" + (j + 1));

			if ((j + 1) % 2 == 0) {
				itemRows[j].classList.add("evenRow");
			} else {
				itemRows[j].classList.remove("evenRow");
			}
		}

		if (itemRows.length == 0) {
			document.getElementById("selectLoc").removeAttribute("disabled");
		}
	} catch (error) {
		console.log(error);
	}
}

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

		if (qty.value == "") {
			qty.value = 0;
		}

		enableMinusQty(index, qty.value);
		enableAddQty(index, qty.value, max);
	} 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);
	} 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);
	} 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 saveStockReturn(mode) {
	try {
		let codeStr = "";
		let qtyStr = "";
		let priceStr = "";
		let UOMStr = "";
		let qty = 0;
		let price = 0;
		let totalAmt = 0;
		let count = 0;
		let runnoset = document.getElementById("selectRunNo").value;
		let locCode = document.getElementById("selectLoc").value;

		if (document.getElementById("selectLoc").getAttribute("data-loc") != "") {
			locCode = document.getElementById("selectLoc").getAttribute("data-loc");
		}

		let itemRows = document.querySelectorAll(".itemRow");

		for (let i = 0; i < itemRows.length; i++) {
			if (document.getElementById(i + 1).value != 0) {
				count++;

				if (codeStr != "") { codeStr += "|"; }
				codeStr += itemRows[i].getAttribute("data-code");

				if (qtyStr != "") { qtyStr += "|"; }
				qtyStr += document.getElementById(i + 1).value;

				if (priceStr != "") { priceStr += "|"; }
				priceStr += document.getElementById("price" + (i + 1)).innerHTML;

				if (count != 1) { UOMStr += "|"; }
				UOMStr += itemRows[i].getAttribute("data-UOM");

				qty = parseFloat(document.getElementById(i + 1).value);
				price = parseFloat(document.getElementById("price" + (i + 1)).value);
				totalAmt += qty * price;
			}
		}

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

			if (params.get("moduleName") == "new") {
				xhr.open("GET", "data/stockReturnData.asp?moduleName=save&codeStr=" + codeStr + "&qtyStr=" + encodeURIComponent(qtyStr) + "&priceStr=" + encodeURIComponent(priceStr) + "&UOMStr=" + encodeURIComponent(UOMStr) + "&totalAmt=" + encodeURIComponent(totalAmt) + "&locationCode=" + encodeURIComponent(locCode) + "&runnoset=" + encodeURIComponent(runnoset), true);
			} else {
				let TRNo = document.getElementById("TRNo").getAttribute("data-URL");
				let TRNo2 = document.getElementById("TRNo").getAttribute("data-URL2");

				xhr.open("GET", "data/stockReturnData.asp?moduleName=save&code=" + TRNo + "&code2=" + TRNo2 + "&codeStr=" + codeStr + "&qtyStr=" + encodeURIComponent(qtyStr) + "&priceStr=" + encodeURIComponent(priceStr) + "&UOMStr=" + encodeURIComponent(UOMStr) + "&totalAmt=" + encodeURIComponent(totalAmt) + "&locationCode=" + encodeURIComponent(locCode) + "&runnoset=" + encodeURIComponent(runnoset), true);
			}

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

						toggleSuccess(response.successMsg);
						setTimeout(function () { toggleModal(); location.href = 'stockReturn.asp'; }, 1500);
					} else {
						toggleFailed(this.responseText);
						setTimeout(function () { toggleModal(); }, 5000);
					}
				}
			} else {
				xhr.onload = function () {
					// console.log(this.responseText);
					if (this.responseText.startsWith("{")) {
						let response = JSON.parse(this.responseText);

						toggleSuccess(response.successMsg);
						setTimeout(function () { toggleModal(); location.search = "moduleName=submit&code=" + response.TRNo + "&code2=" + response.TRNo2 + "&locationCode=" + encodeURIComponent(locCode); }, 1500);
					} else {
						toggleFailed(this.responseText);
						setTimeout(function () { toggleModal(); }, 5000);
					}
				}
			}

			xhr.send();
		} else {
			alert("Please fill in the quantity of at least ONE item!");
		}
	} catch (error) {
		console.log(error);
	}
}

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

function enableConfirmStockReturn() {
	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 confirmStockReturn(code, code2) {
	try {
		toggleModal();
		let password = document.getElementById("password").value;
		let listItems = document.querySelectorAll(".commentSection");
		let commentStr = "";

		for (let i = 0; i < listItems.length; i++) {
			if (listItems[i].value.trim() != "") {
				if (commentStr != "") { commentStr += "||"; }
				commentStr += listItems[i].value.trim();
			}
		}

		let xhr = new XMLHttpRequest();

		xhr.open("GET", "data/stockReturnData.asp?moduleName=confirm&code=" + code + "&code2=" + code2 + "&password=" + encodeURIComponent(password) + "&commentStr=" + encodeURIComponent(commentStr), true);

		xhr.onload = function () {
			// console.log(this.responseText);
			if (this.responseText.startsWith("Success")) {
				toggleSuccess(this.responseText);
				setTimeout(function () { toggleModal(); location.href = 'stockReturn.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);
	}
}

function validateDate(ref) {
	try {
		let dateFormat = new RegExp("[0-3][0-9]/[0-1][0-9]/[0-9]{4}");
		if (!dateFormat.test(ref.value) && ref.value != "") {
			ref.value = "";
			alert("Invalid Date Input!");
		}
	} catch (error) {
		console.log(error);
	}
}

// Search functions
function filterSearch() {
	try {
		let searchVal = "";

		if (!params.has("moduleName")) {
			searchVal = document.getElementById("search").value.trim().toUpperCase();
			let listItems = document.querySelectorAll(".list-group-item");
			for (let i = 0; i < listItems.length; i++) {
				if (listItems[i].getAttribute("data-code").includes(searchVal) || listItems[i].getAttribute("data-code2").includes(searchVal) || listItems[i].getAttribute("data-loc").includes(searchVal)) {
					listItems[i].classList.add("visible");
					listItems[i].classList.remove("hide");
				} else {
					listItems[i].classList.remove("visible");
					listItems[i].classList.add("hide");
				}
			}
		} else {
			if (document.getElementById("addType").value == "article") {
				searchVal = document.getElementById("Quad_article").value.trim().toUpperCase();
			} else {
				searchVal = document.getElementById("Secondary_item_no").value.trim().toUpperCase();
			}
			let listItems = document.querySelectorAll(".itemRow");
			for (let i = 0; i < listItems.length; i++) {
				if (listItems[i].firstElementChild.innerHTML.includes(searchVal) || listItems[i].getAttribute("data-article").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 Mark Received Data function
function getStockReturnData() {
	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/stockReturnData.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>

							<!-- 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>`;

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

					if (response.noTransfer) {
						main += `<h1 class="stockReturn-listing-label">${response.noTransfer}</h1>`
					} else {
						response.transfers.forEach(transfer => {
							count++;
							let evenRow = "";

							if (count % 2 == 0) { evenRow = "evenRow"; }

							let orderID = "";
							if (transfer.orderID2 != "") {
								orderID = transfer.orderID2;
							} else {
								orderID = transfer.orderID;
							}

							let status = "";
							if (transfer.status == "Draft" || transfer.status == "Submitted") {
								status = `<div class="${transfer.status}">
											${transfer.status} by ${transfer.createdBy}
										</div>
										<button class="btn btn-primary checkBtn" onclick="checkStockReturn('${transfer.orderIDURL}', '${transfer.orderID2URL}', '${transfer.location}')" id="checkBtn${count}">CHECK</button>`;
							} else {
								status = `<div>
											${transfer.status} by ${transfer.createdBy}
										</div>
										<div>
											${transfer.statusID}
										</div>`;
							}

							main += `<div class="list-group-item ${evenRow}" id="request${count}" data-code="${transfer.orderID}" data-code2="${transfer.orderID2}" data-loc="${transfer.location}">
										<div class="stockReturn-listing-sb">
											<b>${orderID}</b>&nbsp;&nbsp;
											<span class="stockReturn-listing-date">${transfer.daterecorded}</span>
										</div>
										<div>
											<div class="stockReturn-listing-sb">
												<div class="stockReturn-listing-label">
													Location
												</div>
												<div>
													${transfer.location}
												</div>
											</div>
											<div class="stockReturn-listing-sb">
												<div class="stockReturn-listing-label">
													Loc.&nbsp;Desc
												</div>
												<div style="text-align: right;">
													${transfer.locationDesc}
												</div>
											</div>
										</div>

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

										<div class="stockReturn-listing-sb stockReturn-listing-status ${transfer.status}">
											${status}
										</div>
									</div>`;
						});
					}

					main += `</div>`;

					// Generate Footer
					footer += `<button class="btn btn-warning doneBtn" onclick="newRequest();">NEW</button>`;

				} else if (moduleName == "new") {
					// Generate Header
					header += `<div class="header-content">
								<div class="stockReturn-listing-sb hide" style="margin-bottom: 5px;">
									<div class="stockReturn-listing-label">
										TR No.
									</div>
									<div>
										<select class="form-select" id="selectRunNo">
											${response.newIDStr}
										</select>
									</div>
								</div>
								<div class="stockReturn-listing-sb">
									<div class="stockReturn-listing-label">
										Location
									</div>
									<div>
										<select class="form-select" id="selectLoc" data-loc="">
											${response.locations}
										</select>
									</div>
								</div>
							</div>
							<!-- Search Bar -->
							<div role="search" class="row searchBar">
								<div class="col-4 col-m-3 g-0">
									<select class="form-select" id="addType" onchange="filterSearch(); addType(this);">
										<option value="article">Article</option>
										<option value="item_no">Item No</option>
									</select>
								</div>

					        	<div class="col-6 col-m-7 gx-2" id="searchArticle">
					        		<input class="form-control" type="search" name="article" id="Quad_article" placeholder="Search" data-groups="${encodeURIComponent(response.locationGroups)}" aria-label="Search" onkeyup="filterSearch(); showSuggestion(this, 'Y')" onblur="filterSearch(); checkItemExists(this, 'Y');">
					        	</div>
					        	<div class="col-6 col-m-7 gx-2 hide" id="searchItem">
					        		<input class="form-control" type="search" name="item_no" id="Secondary_item_no" placeholder="Search" data-groups="${encodeURIComponent(response.locationGroups)}" aria-label="Search" onkeyup="filterSearch(); showSuggestion(this, 'N')" onblur="filterSearch(); checkItemExists(this, 'N');">
					        	</div>

					        	<label for="addArticle" id="forAddArticle" class="col-2 g-0 py-1 px-0 btn btn-primary disabled">
					        		<i class="fa fa-plus" aria-hidden="true" style="font-size: 14px;"></i>
					        	</label>
					        	<label for="addItem" id="forAddItem" class="col-2 g-0 py-1 px-0 btn btn-primary hide disabled">
					        		<i class="fa fa-plus" aria-hidden="true" style="font-size: 14px;"></i>
					        	</label>

				        		<input type="button" id="addArticle" onclick="addStock('Y')" hidden>
				        		<input type="button" id="addItem" onclick="addStock('N')" hidden>
					        </div>`;

					// Generate Content
					main += `<!-- Page 2 - New -->
							<table class="stockReturn-table" cellpadding="3px" cellspacing="0">
								<thead>
									<tr class="table-header" align="center">
										<td></td>
										<td>Item</td>
										<td>Qty</td>
										<td width="40">Price</td>
										<td>&nbsp;</td>
									</tr>
								</thead>
								<tbody id="itemList"></tbody>
								</table>`;

					// Generate Footer
					footer += `<button class="btn btn-secondary saveBtn" onclick="saveStockReturn('SAVE')">SAVE</button>
							<button class="btn btn-success submitBtn" onclick="saveStockReturn('SUBMIT')">SUBMIT</button>`;

				} else if (moduleName == "check") {
					let TRNo = response.TRNo;

					if (response.TRNo2 != "") { TRNo = response.TRNo2; }

					let disabled = "";
					
					if (response.draft == "") { disabled = "disabled"; }

					let searchBar = "";

					if (response.draft == "Y") {
						searchBar = `<!-- Search Bar -->
							<div role="search" class="row searchBar">
								<div class="col-4 col-m-3 g-0">
									<select class="form-select" id="addType" onchange="filterSearch(); addType(this);">
										<option value="article">Article</option>
										<option value="item_no">Item No</option>
									</select>
								</div>

					        	<div class="col-6 col-m-7 gx-2" id="searchArticle">
					        		<input class="form-control" type="search" name="article" id="Quad_article" placeholder="Search" aria-label="Search" onkeyup="filterSearch(); showSuggestion(this, 'Y')" onblur="filterSearch(); checkItemExists(this, 'Y');">
					        	</div>
					        	<div class="col-6 col-m-7 gx-2 hide" id="searchItem">
					        		<input class="form-control" type="search" name="item_no" id="Secondary_item_no" placeholder="Search" aria-label="Search" onkeyup="filterSearch(); showSuggestion(this, 'N')" onblur="filterSearch(); checkItemExists(this, 'N');">
					        	</div>

					        	<label for="addArticle" id="forAddArticle" class="col-2 g-0 py-1 px-0 btn btn-primary disabled">
					        		<i class="fa fa-plus" aria-hidden="true" style="font-size: 14px;"></i>
					        	</label>
					        	<label for="addItem" id="forAddItem" class="col-2 g-0 py-1 px-0 btn btn-primary hide disabled">
					        		<i class="fa fa-plus" aria-hidden="true" style="font-size: 14px;"></i>
					        	</label>

				        		<input type="button" id="addArticle" onclick="addStock('Y')" hidden>
				        		<input type="button" id="addItem" onclick="addStock('N')" hidden>
					        </div>`;
					} else {
						searchBar = `<!-- Search Bar -->
							<div role="search" class="row searchBar">
								<select class="form-select hide" id="addType" onchange="filterSearch(); addType(this);">
									<option value="item_no">Item No</option>
								</select>
					        	<div class="col-10 g-0">
					        		<input class="form-control" type="search" name="item_no" id="Secondary_item_no" 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>`;
					}

					// Generate Header
					header += `<div class="header-content">
								<div class="stockReturn-listing-sb" style="margin-bottom: 5px;">
									<div class="stockReturn-listing-label">
										TR No.
									</div>
									<div>
										<input class="form-control" type="text" id="TRNo" data-URL="${response.TRNoURL}" data-URL2="${response.TRNo2URL}"value="${TRNo}" readonly>
										<input type="text" id="selectRunNo" value="${response.runnoset}" readonly hidden>
									</div>
								</div>
								<div class="stockReturn-listing-sb">
									<div class="stockReturn-listing-label">
										Location
									</div>
									<div>
										<input class="form-control" type="text" id="selectLoc" data-loc="${response.locationCode}" value="${response.location}" readonly>
									</div>
								</div>
							</div>
							${searchBar}`;

					// Generate Content
					main += `<!-- Page 2 - Check -->
							<table class="stockReturn-table" cellpadding="3px" cellspacing="0">
								<thead>
									<tr class="table-header" align="center">
										<td></td>
										<td>Item</td>
										<td>Qty</td>
										<td width="40">Price</td>
										<td>&nbsp;</td>
									</tr>
								</thead>
								<tbody id="itemList">`;

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

						if (count % 2 == 0) { evenRow = "evenRow"; }

						let mdisabled = "";
						let adisabled = "";

						if (item.quantity == 0) { mdisabled = 'disabled'; }
						if (item.quantity == response.maxQty) { adisabled = 'disabled'; }

						let readOnly = "";

						if (disabled != "") {
							readOnly = "readonly";
						} else {
							readOnly = `onblur="validateQty('${count}', ${response.maxQty})"`;
						}

						if (item.entrytype != "C") {
							main += `<tr class="itemRow ${evenRow}" align="center" data-code="${item.codeURL}" data-article="${item.article}" data-UOM="${item.u_measure}">
										<td width="30" class="rowNumber">${item.rowNumber}</td>
										<td align="left">
											<b>${item.code}</b>
											<br>
											<span class="stockReturn-listing-label stockReturn-priceLevel">${item.priceLevel}</span>
											<br>
											<span class="stockReturn-listing-itemDesc">${item.description}</span>
										</td>
										<td>
											<div style="display: flex; flex-direction: row; flex-wrap: nowrap;">
												<button class="btn btn-danger details-qty-btn mBtn ${mdisabled} ${disabled}" id="minusQty-${count}" onclick="minusQty('${count}', ${response.maxQty})">
													<i class="fa fa-minus" aria-hidden="true"></i>
												</button>

												<input class="form-control stockReturn-qty ${disabled}" type="text" name="qty" id="${count}" value="${item.quantity}" onkeypress="return onlyNumberKey(event)" onfocus="this.select()" maxlength="${response.maxQty.toString().length}" ${readOnly}>

												<button class="btn btn-success details-qty-btn aBtn ${adisabled} ${disabled}" id="addQty-${count}" onclick="addQty('${count}', ${response.maxQty})">
													<i class="fa fa-plus" aria-hidden="true"></i>
												</button>
											</div>
										</td>
										<td class="stockReturn-price" id="price${count}">${priceFormatter.format(item.price)}</td>
										<td>
											<span class="btn btn-outline-danger py-1 px-2 ${disabled}" onclick="deleteItem('${item.codeURL}', ${response.maxQty})">
												<i class="fa fa-trash" aria-hidden="true" style="font-size: 18px;"></i>
											</span>
										</td>
									</tr>`;
						} else {
							main += `<tr class="itemRow ${evenRow}" align="center" data-code="" data-article="" data-UOM="">
										<td width="30" class="rowNumber">${item.rowNumber}</td>
										<td style="padding-left: 5px;" align="left" colspan="4">
											Comment:&nbsp;&nbsp;&nbsp;&nbsp;${item.description}
										</td>
									</tr>`;
						}
				});

				main += `</tbody>
						</table>`;

					// Generate Footer
					footer += `<button class="btn btn-secondary saveBtn ${disabled}" onclick="saveStockReturn('SAVE')">SAVE</button>
							<button class="btn btn-success submitBtn ${disabled}" onclick="saveStockReturn('SUBMIT')">SUBMIT</button>`;

				} else if (moduleName == "submit") {
					let TRNo = response.TRNo;

					if (response.TRNo2 != "") { TRNo = response.TRNo2; }

					// Generate Header
					header += `<div class="header-content">
								<div class="stockReturn-listing-sb" style="margin-bottom: 5px;">
									<div class="stockReturn-listing-label">
										TR No.
									</div>
									<div>
										<input class="form-control" type="text" id="TRNo" data-URL="${response.TRNoURL}" data-URL2="${response.TRNo2URL}"value="${TRNo}" readonly>
										<input type="text" id="selectRunNo" value="${response.runnoset}" readonly hidden>
									</div>
								</div>
								<div class="stockReturn-listing-sb" style="margin-bottom: 5px;">
									<div class="stockReturn-listing-label">
										Location
									</div>
									<div>
										<input class="form-control" type="text" id="selectLoc" data-loc="${response.locationCode}" value="${response.location}" readonly>
									</div>
								</div>
								<div class="stockReturn-listing-sb">
									<div class="stockReturn-listing-label">
										Date
									</div>
									<div>
										<input class="form-control" type="text" value="${response.daterecorded}" readonly>
									</div>
								</div>
							</div>`;

					// Generate Content
					main += `<!-- Page 3 - Confirm -->
							<div class="list-group stockReturn-listing">
								<div class="list-group-item">
									<div>
										<div class="stockReturn-listing-bl" style="font-size: 18px; margin-bottom: 5px;">
											<b>Comment :</b>
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
										<div class="stockReturn-listing-bl" style="justify-content: center; font-size: 18px; margin-bottom: 5px;">
											<input type="text" class="form-control commentSection" maxlength="60">
										</div>
									</div>
								</div>
								<br>
								<div class="list-group-item">
									<div>									
										<div class="stockReturn-listing-sb">
											<div class="stockReturn-listing-label" style="margin-bottom: 10px;">
												Promoter ID : <span style="color: #000; font-size: 16px;">${response.name} (${response.curuser})</span>
											</div>
										</div>
										<div class="stockReturn-listing-sb">
											<div class="stockReturn-listing-label">
												Password :
											</div>
											<div>
												<input type="password" id="password" class="form-control" onfocus="this.scrollIntoView();" onkeyup="enableConfirmStockReturn()" onkeydown="submitPassword(event)">
											</div>
										</div>
									</div>

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

									<div class="stockReturn-listing-sb">
										<div class="stockReturn-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="confirmStockReturn('${response.TRNoURL}', '${response.TRNo2URL}');">CONFIRM</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 == "" && count > 0) {
				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;

				let extraLoad = Math.ceil((availableSpace / itemHeight) - recPerPage)

				if (extraLoad > 0) {
					for (let i = 0; i < extraLoad; i++) {
						loadRecords();
					}
				}
			}

			toggleModal();
		}

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

getStockReturnData();