// Copyright (c) 2008 Andrew Dockery
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// worldpay.js
// Nov 11, 2008
//
// Contains javascript necessary for managing forms submitting data to Worldpay.

<!-- hide from oldie browsers -->
function defocus(x)
{
//    document.BuyForm.qty.focus();
}

<!-- The next two functions round numbers to numerical formatting. -->
function roundOff(value, precision)
{
    return places(value,1,precision);
}

function places(X, M, N) 
{
    var T, S=new String(Math.round(X*Number("1e"+N)))
    while (S.length<M+N) S='0'+S
    var y = S.substr(0, T=(S.length-N));
    if(N>0) 
    {
        y += '.' + S.substr(T, N);
    }

    return y;
}

<!-- This function checks for empty quantities. -->
function CheckNull(value)
{
    if (value == "")
    {
        value = "0";
    }

    return value;
}

<!-- This function defines the postage and packaging location. -->
function typeOfCarriage(form, whereabouts)
{
    form.carriage_amount.value = whereabouts;
}

<!-- This function addeds the postage and packaging to the total price of the products. To see an example of adding postage and packaging rates to this page see example 0.4 -->
function calculate(form)
{
	// First ensure that all the Worldpay fields are populated from custom fields.
    populateWPDetails(form);
    
    basicprice = calc(form);

    if(Number(basicprice) > 0)
    {

//        switch (form.carriage_amount.value)
//        {
//            case "uk":
//                form.postage_and_packaging.value = 0.00;
//                break
//            case "europe":
//                form.postage_and_packaging.value = 0.00;
//                break
//            default:
//                form.postage_and_packaging.value = 0.00;
//                break;
//        }

        form.amount.value = Number(basicprice); // + Number(form.postage_and_packaging.value);
        form.desc.value = add_items(form);
    }
    else
    {
        form.amount.value = "0";
    }

    form.amount.value = roundOff(form.amount.value,2);
}

<!-- The standard price, exluding postage and packaging is calculated here. -->
function calc(form) {
    form.amount.value = 0;
    var num_prices = form.price.length;
    var num_qtys   = form.qty.length;
    var amount     = Number(form.amount.value);
    var price, qty, valid_qty;
    valid_qty = true;

    while(num_prices > 0) {
        price = Number(CheckNull(form.price[num_prices - 1].value));
        qty   = Number(CheckNull(form.qty[num_prices - 1].value));
        if (form.qty[num_prices-1].type == "checkbox" && !form.qty[num_prices-1].checked) {
            qty = 0;
        }      
        if(price < 0) {
            valid_qty = false;
            price = 0;
            form.price[num_prices-1].value = 0;
        }
        if(qty < 0) {
            valid_qty = false;
            qty = 0;
            form.qty[num_prices-1].value = qty;
        }
		form.subtotal[num_prices - 1].value = roundOff(price * qty, 2);

        amount += (price * qty);
        num_prices--;
    }

    if(valid_qty == false) {
        alert("Negative quantities not permitted; these have been set to zero.");
    }

    return amount;
}

<!-- These two functions add the items descriptions and prices, to be sent to the WorldPay secure server. -->
function add_items(form)
{
    var num_prices = form.price.length;
    var num_codes  = form.code.length;
    var item_list = "";
    if(num_prices != num_codes) alert("Missing items in form; found "+num_prices+" occurrences of price and "+num_codes+" of code.");
    var i = 0;

    while (i < num_prices)
    {
        if(Number(CheckNull(form.qty[i].value)) > 0)
        {
            if (form.qty[i].type != "checkbox") {
                item_list += add_item(item_list, form.qty[i].value, form.code[i].value);
            } else if (form.qty[i].checked) {
                item_list += add_item(item_list, form.qty[i].value, form.code[i].value);
            }
        }

        i++;
    }

    <!-- Add the memberships. -->
//    if (standard_memberships(form) == 1) {
//        item_list += add_item(item_list, standard_memberships(form), "Membership");
//    } else if (standard_memberships(form) > 1) {
//        item_list += add_item(item_list, standard_memberships(form), "Memberships");
//    }  

//    if (student_memberships(form) == 1) {
//        item_list += add_item(item_list, student_memberships(form), "Student membership");
//    } else if (student_memberships(form) > 1) {
//        item_list += add_item(item_list, student_memberships(form), "Student memberships");
//    }  
    return item_list;
}

function add_item(item_list, qty, code)
{
    var item = "";
    if(item_list != "")
    {
        item += ", ";
    }

    item += qty + " " + code;

    if(Number(CheckNull(qty)) > 1) 
    {
        item += "";
    }

    return item;
}



<!-- This validates the details input by the customer. This is where you may wish to include more sophisticated checking in the 'if' arguments if you wish. -->
function validate_form(form)
{
    var error_message = "";
    var is_valid = true;
    var i, negative_quantities, quantity;

    quantity = 0;
    negative_quantities = 0;


    // Individual form validations
    error_message += customValidation(form);
    if (error_message != "") {
    	is_valid = false;
    }
    
    // Check quantities for valid values.
    for(i =0; i < form.qty.length; i++)
    {
        if(Number(CheckNull(form.qty[i].value)) < 0)
        {
            negative_quantities++;
        }
        else 
        {
            if (form.qty[i].type != "checkbox") {
                quantity += Number(CheckNull(form.qty[i].value));
            } else if (form.qty[i].checked) {
                quantity += Number(CheckNull(form.qty[i].value));
            }
        }

    }

    if(negative_quantities > 0)
    {
        error_message += "\nYou have entered "+negative_quantities+" negative quantit";
        if(negative_quantities == 1)
        {
            error_message += "y.";
        }
        else
        {
            error_message += "ies.";
        }

        is_valid = false;
    }

	// Validate name and contact detail fields.
    if(form.name.value == "") {
        error_message += "\nPlease enter your full name.";
	    is_valid = false;
    }
    if(form.address.value == "") {
        error_message += "\nPlease enter your complete address.";
        is_valid = false;
    }
    if(form.country.value == "" || form.country.value == undefined) {
	    error_message += "\nPlease select a country.";
        is_valid = false;
    }
    if(form.postcode.value == "") {
        error_message += "\nPlease enter your postcode.";
        is_valid = false;
    }
    if(form.email.value == "") {
        error_message += "\nPlease enter your e-mail address.";
        is_valid = false;
    }

	// Display all errors as one message
    if(is_valid == false) 
    {
        alert("The following must be completed first:\n" + error_message);
    } else {
    	customSubmit(form);
    }

    return is_valid;
}


function radio(checkbox) {
    if(checkbox.checked) {
        form = checkbox.form;
        for(i = 0; i < form.length; i++) {
            if (form[i].type == "checkbox" && form[i] != checkbox) {
                form[i].checked = false;
            }
        }
    }
}

function validateQuantityBox(box) {
	if (box.value.indexOf(".") != -1 || isNaN(box.value) || box.value < 0) {
		alert ("Whole, positive numbers allowed only");
		box.value="0";
		box.focus();
		return false;
	}
	return true;
}

function validateQuantity(form) {
	if (form.qty.length == undefined) {
		return validateQuantityBox(form.qty);
	}
    for(i =0; i < form.qty.length; i++) {
		if(!validateQuantityBox(form.qty[i])) {
			return false;
		}
	}
	return true;
}

