/*******************************************/
/*                                         */
/* Update totals on Yumee Bear order form  */
/* IM - Digital Ink                        */
/* http://www.digitalink.com.au/           */
/*                                         */
/*******************************************/


function toFixed2(x) {
	if (Number().toFixed) return Number(x).toFixed(2);
	var k = (Math.round(x * 100) / 100).toString();
	k += (k.indexOf('.') == -1)? '.00' : '00';
	return k.substring(0, k.indexOf('.') + 3);
}

function pad_with_zeros(rounded_value, decimal_places) {
    // Convert the number to a string
    var value_string = rounded_value.toString()    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")
    // Is there a decimal point?
    if (decimal_location == -1) {        	    
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    } else {
        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length    
    if (pad_total > 0) {        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
    }
    return value_string
}

function SumTotals (frm) {
	var order_total = 0
    // Run through all the form fields
    for (var i=0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        form_name = form_field.name
        
        // Is it a total field? (can't use substr due to IE being stupid)
        fnArr = form_name.split(" ");
               
        if (fnArr.pop() == "Total") {
	        if (form_field.value) {
	        	order_total += parseFloat(form_field.value)
        	}
		}		
	}
	// Add deliveryt charge
	order_total += 8
	frm.elements["Total Charge"].value = toFixed2(pad_with_zeros(parseFloat(order_total),2))
}


function UpdateTotals (frm,el) {		
	// Work out current item information
	bTemp = el.name.split("_")	
	daitem = (bTemp[0])
	cost = bTemp[1]	
	quantity = el.value		
	qt = (parseFloat(quantity) * parseFloat(cost))		
	frm.elements[daitem + " Total"].value = toFixed2(pad_with_zeros((parseFloat(quantity) * parseFloat(cost)),2))
	// Update total
	SumTotals(frm)
}