function copyAddress() {

    var company = document.forms['orderForm'].shippingcompany.value;    
    var address1 = document.forms['orderForm'].shippingaddress1.value;  
    var address2 = document.forms['orderForm'].shippingaddress2.value;  
    var city = document.forms['orderForm'].shippingcity.value;  
    var state = document.forms['orderForm'].shippingstate.value;    
    var country = document.forms['orderForm'].shippingcountry.value;    
    var zip = document.forms['orderForm'].shippingzip.value;    
    var phone = document.forms['orderForm'].shippingphone.value;    
    var fax = document.forms['orderForm'].shippingfax.value;    
    var email = document.forms['orderForm'].shippingemail.value;    
    var department = document.forms['orderForm'].shippingdepartment.value;  


    document.forms['orderForm'].billingdepartment.value =   department;
    document.forms['orderForm'].billingcompany.value =  company;
    document.forms['orderForm'].billingaddress1.value = address1;
    document.forms['orderForm'].billingaddress2.value = address2;
    document.forms['orderForm'].billingcity.value = city;
    document.forms['orderForm'].billingstate.value =    state;
    document.forms['orderForm'].billingcountry.value =  country;
    document.forms['orderForm'].billingzip.value =  zip;
    document.forms['orderForm'].billingphone.value =    phone;
    document.forms['orderForm'].billingfax.value =  fax;
    document.forms['orderForm'].billingemail.value =    email;

}

function todayDate() {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.forms['orderForm'].today.value = month + "/" + day + "/" + year;
}

function copyConfMethod() {

    if (document.forms['orderForm'].confMethod.value == 'fax') {
        var faxDetail = document.forms['orderForm'].fax.value;  
        document.forms['orderForm'].confDetail.value =  faxDetail;
    } else {
        var emailDetail = document.forms['orderForm'].email.value;  
        document.forms['orderForm'].confDetail.value =  emailDetail;
    }
}

function ccPayment() {
    if (document.forms['orderForm'].payMethod.value ==  'cc' || document.forms['orderForm'].payMethod.value ==  'wire') {
			document.getElementById('paymentAlert').innerHTML = '<b>Note:</b> Customer service will contact you to obtain your payment information.';
    } else {
			document.getElementById('paymentAlert').innerHTML = "&nbsp;";
		}
}


        function getElementLabel(elem) {
            return document.getElementById('lbl_' + elem.id);
        }

        function getRequiredFormElements(theForm) {
            var result = [];
            var elements = theForm.elements;
            var elemCount = elements.length;

            for (var i=0; i<elemCount; i++) {
                var elem = elements[i];
                var classes = elem.className.split(' ');
                var classesCount = classes.length;

                for (var j=0; j<classesCount; j++) {
                    if (classes[j] == 'required') {
                        result.push(elem);
                        break;
                    }
                }
            }
            return result;
        }

        function markElementInvalid(elem) {
            if (lbl = getElementLabel(elem)) {
                lbl.className = 'invalid';
            }
        }

        function markElementValid(elem) {
            if (lbl = getElementLabel(elem)) {
                lbl.className = 'valid';
            }
        }

        function setValidState(elem, isValid) {
            if (isValid) {
                markElementValid(elem);
            } else {
                markElementInvalid(elem);
            }
        }

        function validate(theForm) {
            var formIsValid = true;
            var elems = getRequiredFormElements(theForm);
            var elemCount = elems.length;

            for (var i=0; i<elemCount; i++) {
                var elemIsValid = true;
                var elem = elems[i];
                var tagName = elem.tagName.toLowerCase();

                if (tagName == 'input') {
                    var elemType = elem.attributes['type'].value.toLowerCase();

                    if (elemType == 'text') {
                        if (elem.value.replace(/^\s+/, '') == '') {
                            elemIsValid = false;
                        }
                    }
                } else if (tagName == 'select') {
                    if (elem.selectedIndex == 0) {
                        elemIsValid = false;
                    }
                }

                if (!elemIsValid) {
                    formIsValid = false;
                }
                setValidState(elem, elemIsValid);
            }
            return formIsValid;
        }

function modifyOrder(selectBox) {
	// these are the base names of the line item inputs; they get
	// a number appended to them to determine the specific inputs
	var desc = "prodDesc";
	var size = "unitSize";
	var cat = "catalog";
	var qty = "quantity";
	var cost = "unitcost";
	var total = "totalcost";
	
    var products = getProductCatalog();

    // get all the details about the select box that was changed
    var selectorId = selectBox.id;
    var lineNum = getLineNum(selectorId);
    var index = selectBox.selectedIndex;
    var selectorVal = selectBox[index].value;

    // now we can get all the associated inputs so we can modify them
    var prodDesc = document.getElementById(desc+lineNum);
    var unitSize = document.getElementById(size+lineNum);
    var catalog = document.getElementById(cat+lineNum);
    var quantity = document.getElementById(qty+lineNum);
    var unitcost = document.getElementById(cost+lineNum);
    var totalcost = document.getElementById(total+lineNum);

    if (index > 0) {
        if (selectorId.indexOf(size) < 0) {
            // this is a product type selectbox, so we need to
            // add the appropriate unit sizes to the unit size selectbox
            var catalogNumbers = products[selectorVal];

            clearSelectOptions(unitSize);

            // then loop through the catalog numbers for the selected product,
            // adding them as options in the unit size selectbox
            for (catalogNo in catalogNumbers) {
                var size = catalogNumbers[catalogNo]["unitSize"];
                var opt = document.createElement("option");
                opt.text = size;
                opt.value = catalogNo;

                try {
                    unitSize.add(opt, null);
                } catch(ex) {
                    unitSize.add(opt); // fix for IE
                }
            }
        } else {
            // this is a unit size selectbox, so we need to
            // fill out the order form with the right values
            var selectedProduct = prodDesc[prodDesc.selectedIndex].value;
            var productDetails = products[selectedProduct][selectorVal];
            var cost = productDetails["unitcost"];

            catalog.value = selectorVal;
            quantity.value = 1;
            unitcost.value = formatCurrency(cost);
            totalcost.value = formatCurrency(cost);

			calculateOrderTotal();
        }
    } else {
        // if we're here, it means we deselected a product
		calculateOrderTotal();

		// empty out the details of the line item
        catalog.value = "";
        quantity.value = "";
        unitcost.value = "";
        totalcost.value = "";

        // if this is a product type selector (not a unit size selector)
        // then we need to clear the size selector
        if (selectorId.indexOf(size) < 0) {
            clearSelectOptions(unitSize);
        }
    }
}

function calculateOrderTotal() {
	var totalAmt = 0.00;

	// get all the line item totals
	var elems = document.orderForm.elements;

	for (var i=0, max=elems.length; i<max; i++) {
		var elem = elems[i];
		if (elem.id.indexOf("totalcost") >= 0 && elem.value.length > 0) {
			totalAmt += currencyToNumber(elem.value);
		}
	}

	var productSubtotal = document.getElementById("productSubtotal");
    var grandTotal = document.getElementById("grandTotal");

	productSubtotal.value = formatCurrency(totalAmt);
    grandTotal.value = formatCurrency(totalAmt);
}

function modifyQuantity(which) {
	var qty = which.value;

	if (qty != parseInt(qty)) {
		alert("Please enter whole numbers into the quantity field.");
		return;
	}

    var lineNum = getLineNum(which.id);
    var unitcost = document.getElementById("unitcost"+lineNum);
    var totalcost = document.getElementById("totalcost"+lineNum);

	totalcost.value = formatCurrency(currencyToNumber(unitcost.value)*qty);

	calculateOrderTotal();
}

function getLineNum(id) {
	return id.charAt(id.length-1);
}

function getProductCatalog() {
    // These are the product types. They are organized like so:
    // products[productDesc][catalogNo]
    var products = new Object();
    products["HTSFRS"] = new Object();
    products["HTSFRS"]["101102 (609142)"] = new Object();
    products["HTSFRS"]["101102 (609142)"]["unitSize"] = "1x100mL bottle";
    products["HTSFRS"]["101102 (609142)"]["unitcost"] = 149.00;
	products["HTSFRS"]["101104 (609144)"] = new Object();
    products["HTSFRS"]["101104 (609144)"]["unitSize"] = "1x500mL bottle";
    products["HTSFRS"]["101104 (609144)"]["unitcost"] = 299.00;
    products["HTSFRS"]["101204 (609146)"] = new Object();
    products["HTSFRS"]["101204 (609146)"]["unitSize"] = "1x500mL IV bag";
    products["HTSFRS"]["101204 (609146)"]["unitcost"] = 309.00;

    products["CryoStorCS2"] = new Object();
    products["CryoStorCS2"]["202102 (650212)"] = new Object();
    products["CryoStorCS2"]["202102 (650212)"]["unitSize"] = "1x100mL bottle";
    products["CryoStorCS2"]["202102 (650212)"]["unitcost"] = 229.00;

    products["CryoStorCS5"] = new Object();
    products["CryoStorCS5"]["205102 (610202)"] = new Object();
    products["CryoStorCS5"]["205102 (610202)"]["unitSize"] = "1x100mL bottle";
    products["CryoStorCS5"]["205102 (610202)"]["unitcost"] = 239.00;
	

    products["CryoStorCS10"] = new Object();
    products["CryoStorCS10"]["210102 (640222)"] = new Object();
    products["CryoStorCS10"]["210102 (640222)"]["unitSize"] = "1x100mL bottle";
    products["CryoStorCS10"]["210102 (640222)"]["unitcost"] = 249.00;

    return products;
}

function currencyToNumber(amt) {
    return parseFloat((amt.charAt(0) == "$") ? amt.substring(1) : amt);
}

function formatCurrency(amt) {
    amt -= 0;
    amt = (Math.round(amt*100))/100;

    var val = (amt == Math.floor(amt)) ? amt + ".00"
        : ((amt*10 == Math.floor(amt*10)) ?
        amt + "0" : amt);

    return "$" + val;
}

function clearSelectOptions(selectBox) {
    selectBox.selectedIndex = 0;

    for (var i=selectBox.length-1; i>0; i--) {
        selectBox.remove(i);
    }
}

