﻿// Add product to shopping basket
function AddProduct(productIndex)
{
	// Check if the product info is valid
	if (ValidateProductInfo(productIndex))
	{
		// Post data to server
		PostProductInfoToServer(productIndex);
	}
}

// Validate product info
function ValidateProductInfo(productIndex)
{
	if (top.document.getElementById("ProductId_" + productIndex) == null) 
	{
		return false; // Admin mode
	}

	var Quantity = top.document.getElementById("Quantity_" + productIndex).value;
		
	if (Quantity.search("[^0-9]") != -1)
	{
		alert('Please enter numeric quantity value(s).');
		return false;
	}
	if (Quantity == '')
	{
		alert('Please enter at least one item quantity to order.');
		return false;
	}
	return true;
}

// Post product info to server in order to add it to shopping basket
function PostProductInfoToServer(productIndex)
{
	// Get required data
	var ProductId = top.document.getElementById("ProductId_" + productIndex).value;
	var Quantity = top.document.getElementById("Quantity_" + productIndex).value;
	
	if (Quantity == '') return;

        var formObject = top.document.getElementById("ProductDataForm");
	var productIdObject = top.document.getElementById("newitem");
	var quantityObject = top.document.getElementById("quantity");
	var locationObject = top.document.getElementById("newlocation");

	productIdObject.value = ProductId;
	quantityObject.value = Quantity;
	locationObject.value = window.location.href;
	formObject.submit();
}

function fnCheckKey()
{
	var intKeyCode = event.keyCode;
	if((intKeyCode < 48) || (intKeyCode > 57))
	{
		event.returnValue = false;
		return false;
	}
}
function fnCheckQnty(ctrl)
{
	var re = /\D/;
	var str = re.test(ctrl.value);

	var minQuantityObject = ctrl.parentElement.childNodes[8];
	var lotSizeObject = ctrl.parentElement.childNodes[8];

	if (str)
	{
		alert("De indtastede antal indeholder ugyldige karakterer.");
		if (minQuantityObject != null)
		{
			ctrl.value = minQuantityObject;
		}
		ctrl.focus();
	}
	else
	{
		if (lotSizeObject.value != null)
		{
			var lotSize = lotSizeObject.value;
			if((ctrl.value % lotSize) != 0)
			{
				alert("Det mindste antal der kan købes er minimumordern (" + ctrl.parentElement.childNodes[8].value + ") eller\net antal der kan deles med denne.");
				ctrl.value = lotSize;
				ctrl.focus();
			}
		}
	}
}
