// TheSTUDIO.net order form JavaScript
// written by Schuyler Erle
// last mod 31 May 2000

function toCurrency (v) {
	var w = Math.floor(v * 100 + .999) / 100;
	var x = w.toString(); w = x.indexOf(".");
	if (w == -1) {
	    x += ".00";
	} else {
	    if (w == x.length - 2)
	    	x += "0";
	}
	return x;
}

function getProduct (elem, name, num) {
	if (!num) num = elem.name.charAt(elem.name.indexOf("_") - 1);
	return elem.form.elements["product" + num + "_" + name];
}

function calculateTotal (elem) {
    with (elem.form) {
	var subtotal = 0, units = 0, i;

	for (i = 1; i <= numProducts.value; i++) {
	    var check = getProduct(elem, "check", i),
		qty   = getProduct(elem, "qty", i),
		tot   = getProduct(elem, "total", i),
		cost  = getProduct(elem, "cost", i);

	    if (qty.value < 1) {
		qty.value = 0;
		if (check) check.checked = false;
	    } else {
	    	qty.value = Math.floor(qty.value);
	    	if (check) check.checked = true;
	    }

	    tot.value = toCurrency( qty.value * cost.value );
	    units += parseInt(qty.value); subtotal += parseFloat(tot.value);
	}

	tax.value = toCurrency((state.options[state.selectedIndex].value.toUpperCase()
	    == salesState.value.toUpperCase()) ? subtotal * salesTax.value : 0);

	if (shipping.options[shipping.selectedIndex].value) { 
 	    extra.value = toCurrency( units > 1 ? (units - 1) * unitExtra.value : 0 );
	    total.value = toCurrency( units ? 1 * subtotal + 1 * tax.value + 
	        1 * extra.value + 1 * shipping.options[shipping.selectedIndex].value : 0 );
	}
    }
    return true;
}

function toggleProduct (check) {
    var qty = getProduct(check, "qty");
    if (check.checked) {
	if (qty.value < 1) qty.value = qty.defaultValue || 1;
    } else {
	qty.defaultValue = qty.value;
	qty.value = 0;
    }
    return calculateTotal(check);
}

function validateForm (f) {
    if (!f.state.options[f.state.selectedIndex].value) {
	alert("You must supply your state.");
	return false;	
    }
    if (!f.first.value) {
	alert("Please supply your first name")
	return false;
    }
    if (!f.last.value) {
	alert("Please supply your last name")
	return false;
    }
    if (!f.address.value) {
	alert("Please supply your address")
	return false;
    }
    if (!f.city.value) {
	alert("Please supply your city")
	return false;
    }
    if (!f.zip.value) {
	alert("Please supply your zip code")
	return false;
    }
    if (!f.phone.value) {
	alert("Please supply your phone number")
	return false;
    }

    if (!f.card_num.value) {
	alert("You must supply a valid credit card number.");
    } else if (!f.card_month.options[f.card_month.selectedIndex].value || 
	!f.card_year.options[f.card_year.selectedIndex].value) {
	alert("You must supply a valid credit card expiration date.");
    } else {
	return true;
    }
    return false;
}
