/*
These vars are declared in the main .aspx page

var sections = 2;
var sectionMultiples = new Array(4,2);
var sectionPrices = new Array(50,28);
*/

var sectionItemCounts = new Array();
var sectionBoxCounts = new Array();
var sectionBoxCountsAct = new Array();
var sectionSpaceCounts = new Array();
var sectionTotals = new Array();
var sectionAddInactive = new Array();

$(document).ready(function() { init(); });

function init() {
    //Add a change event to the postcode box
    $("#Postcode").change(function() { checkValidPostcode($(this).val()); });

    //Add a change event to the delivery date dropdown
    $("#Delivery_date").change(function() { updateDisplay();});

    //Add a change event to the voucher box
    $("#Voucher").change(function() { updateDisplay(); });

    //Create the 0 counts and totals arrays
    for (var i=0; i<=sections; i++)
    {
	    sectionItemCounts.push(0);
	    sectionBoxCounts.push(0);
	    sectionBoxCountsAct.push(0);
	    sectionSpaceCounts.push(0);
	    sectionTotals.push(0);
	    sectionAddInactive.push(0);
    }
}

function checkValidPostcode(postcode) {
    postcodeCheckActive = false;
    pcRegEx = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;
    if (postcode.match(pcRegEx) || postcodeCheckActive == false) {
        var date = new Date();
        var timeStamp = date.getTime();
        var params = new Object();
        params.Postcode = postcode;

        $("#placeDate").load("asyncDeliveryDate.aspx?noChache=" + timeStamp, params, function() { updateDisplay(); $("#Delivery_date").change(function() { updateDisplay();});  });
    } else {
        alert("Sorry, that doesn't appear to be a valid UK Postcode.");
    } 
    return (false);
}


function updateQuantity(sectionNo, itemNo, howMuch)
{
	if (sectionAddInactive[sectionNo] == 1 && howMuch == 1)
	{
	    howMuch = 0;
	}
	
	var theItem = "item_" + sectionNo + "_" + itemNo;
	var theItemQuantity = document.forms["form1"][theItem + "_quantity"];
	var theItemObject = document.getElementById(theItem);
	if (theItemObject)
	{
		var newValue = eval(theItemQuantity.value) + howMuch;
		
		newValue = (newValue <= 0) ? 0 : newValue;
		
		theItemQuantity.value = newValue;
		theItemObject.innerHTML = newValue;
		
		updateDisplay(sectionNo);
	}
}

function updateDisplay(sectionNoTrigger)
{   
    //Create our params object to pass back to the DB
	var params = new Object();
	var valid = true;
	var totalItems = 0;
	
	//Loop through all the sections and update them
	for (var sectionNo = 0; sectionNo < sections; sectionNo++)
	{
	    var sectionItemQuantityTotal = 0;
	    var sectionPriceTotal = 0;
		
		//Loop through all the items to get the total - we'll break out of this loop when no more items are found
		for (var itemNo = 0; itemNo > -1; itemNo++)
		{
			var theItem = "item_" + sectionNo + "_" + itemNo;
			var theItemQuantity = document.forms["form1"][theItem + "_quantity"];
			var theItemPrice = document.forms["form1"][theItem + "_price"];
			
			if (theItemQuantity)
			{
				sectionItemQuantityTotal = sectionItemQuantityTotal + eval(theItemQuantity.value);
				sectionPriceTotal = sectionPriceTotal + (eval(theItemPrice.value) * eval(theItemQuantity.value));
				
				//Update our master param
				if (theItemQuantity.value != "0")
				{
				    var itemParamName = "item_" + document.forms["form1"][theItem + "_dbId"].value;
				    var itemParamValue = theItemQuantity.value;

				    params[itemParamName] = itemParamValue;
			    }
			}
			else
			{
				break;
			}
		}
		
		sectionItemCounts[sectionNo] = sectionItemQuantityTotal;
		sectionTotals[sectionNo] = sectionPriceTotal;
		
		//Update the bottom line for the section
		var theItemsObject = document.getElementById("items_" + sectionNo);
		if (theItemsObject)
		{
		    theItemsObject.innerHTML = sectionItemCounts[sectionNo];
						
			var theTotalObject = document.getElementById("total_" + sectionNo);

            var toSplit = String(sectionTotals[sectionNo])
			if (toSplit.indexOf(".") >= 0)
			{
			    var secondPart = toSplit.split(".")[1];
			    if (secondPart.length < 2) {
			        sectionTotals[sectionNo] = sectionTotals[sectionNo] + "0";
			    }
			}
			
			theTotalObject.innerHTML = "&pound;" + formatCurrency(sectionTotals[sectionNo]);
			totalItems = totalItems + formatCurrency(sectionItemCounts[sectionNo]);
		}
	}
	
	//Order validation
	var deliveryDate = $("#Delivery_date").val();
	var postcode = $("#Postcode").val();
	var basketFull = true;

    //Must have a postcode and delivery date
	if (postcode == "" || deliveryDate == "-1") {
	    valid = false;
	}
	//Must have more than two items
	if (totalItems < 1) {
	    valid = false;
	    basketFull = false;
	}
	//Must have more than two jars
	if (((sectionItemCounts[0] + sectionItemCounts[2]) >= 1) && ((sectionItemCounts[0] + sectionItemCounts[2]) < 2) || ((sectionItemCounts[0] + sectionItemCounts[2]) == 0))
	{
	    valid = false;
	    basketFull = false;
	}
	//Work-around for multipack
	if (sectionTotals[0] >= 52.75 && postcode != "" && deliveryDate != "-1") {
	    valid = true;
	    basketFull = true;
	}

	params.delivery = deliveryDate;
	params.postcode = postcode;
	params.basketFull = basketFull;
	params.valid = valid;
	params.voucher = $("#Voucher").val();

	var date = new Date();
	var timeStamp = date.getTime();

	$("#asyncFeedback").load("asyncBasket.aspx?noChache=" + timeStamp, params);
	$("#Delivery_date").blur();
}

function showHideAdd(sectionNo, show)
{
    for (var itemNo = 0; itemNo > -1; itemNo++)
	{
		var theItem = "item_" + sectionNo + "_" + itemNo + "_add";
		var obj = document.getElementById(theItem);
		
		if (obj)
		{
            if (show == 0)
            {
                obj.style.visibility = "hidden";
		    }
		    else
		    {
		        obj.style.visibility  = "visible";
		    }
		}
		else
		{
			break;
		}
	}
}

function showMessage()
{
    $("#checkoutFeedback").show();
}

function disableEnterKey(e) {
    var key;
    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox     

    return (key != 13);
}

//Show as currency
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '' + num + '.' + cents);
}