/*
	PRODUCT_OPTIONS.JS
	Script to make adjustments to the product price based on the various 
	options selected. 

	--------------------------------------------------------------------
	Copyright (c) 2006 Website Expressions Pty Ltd. All rights reserved.
	--------------------------------------------------------------------
	
	ABN:	  87 108 587 131
	Internet: www.websiteexpressions.com
	Email:	  mail@websiteexpressions.com
	Phone:	  +61 2 4948 1555
	Fax:	  +61 2 4948 1666

	Version 1.0
	22/07/2006
					
*/	

function adjustInitialPrices() 
{
    // Get all the form fields on the page 
    form_fields = document.getElementsByTagName('form'); 
    
    // Initialise the form number
    var form_num
    
    //  Cycle trough all of the form fields 
    for (form_num = 0; form_num < form_fields.length; form_num++) { 

	    // Get the form name
	    if (form_fields[form_num].getAttribute('name') == 'Products') {
		break
		}	
	}
	
    // Get all the options fields on the page 
    options = document.getElementsByTagName('select'); 
    
    //  Cycle trough all of the option fields 
    for (var i = 0; i < options.length; i++) { 

        // Get the option name
        option_name = options[i].getAttribute('name')

        // Adjust the price
		adjustPrice(form_fields[form_num], option_name) 
	}
} 

function deleteBraces(frm, field_name)
{
    for (var i = 0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Does the name match?
        if (form_field.name == field_name) {

            // If so, delete any braces
			form_field.value = form_field.value.replace(/{/, "")
			form_field.value = form_field.value.replace(/}/, "")
	    }      
	}
}

function round_decimals(original_number, decimals) 
{
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

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 getItemSpecification(option_selection) 
{
	// Extract and return the item specification from the option selection. 
	pos = option_selection.indexOf("Category")
	item_spec = option_selection.substring(pos)
	return item_spec
}	

function getBasePrice(frm, item_spec) 
{
	// Run through all the form fields to find and return the base price 
	// which corresponds to the item specification.
    for (var i = 0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        field_name = form_field.name

        // Is it the base price field for this item?
        if (field_name == "BasePrice-" + item_spec) {

            // If so, return the base price without the dollar sign
            base_price = parseFloat(form_field.value.replace(/\$/, ""))
			return base_price
	    }      
	}
	
	// Otherwise return an error
	return -1
}

function calculateNewPrice(frm, item_spec, base_price) 
{
	// Find all option values which correspond to the item specification, apply
	// these to the base price, and return the calculated value as the new price.
	
	// Initially, set the new price to the value of the base price
	new_price = base_price

	// Run through all the form fields to find option selections which correspond 
	// to the item specification.
    for (var i = 0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        field_name = form_field.name

        // Is it an option selection field for this item?
        if (field_name.substring(0,field_name.indexOf("-")) == "OptionSelection" && field_name.substr(field_name.indexOf("Category")) == item_spec) {
        
            // If so, use zero if it is a text field, or extract the value from the
            // enclosed braces if it is a select field, and apply it to the base price
            if (form_field.type == 'text') {
            	new_price += 0	
            } else {
            	new_price += parseFloat(form_field.value.substring(1, form_field.value.indexOf("}")));
            }
	    } 
	}

	// Prevent negative amounts
	if (new_price < 0)
	{
		new_price = 0
	}
		
	return new_price	
}

function updateAdjustedPrice(frm, item_spec, new_price) 
{
	// Run through all the form fields to find and return the adjusted price which 
	// corresponds to the item specification, and update it with the new price.
    for (var i = 0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        field_name = form_field.name

        // Is it the adjusted price field for this item?
        if (field_name == "AdjustedPrice-" + item_spec) {

			// If so, display the new adjusted price rounded to two decimal places,
			// add a preceding dollar sign, and return a no error status
			form_field.value = "$" + String(round_decimals(new_price, 2))
			
			// Return no error
			return 0
	    }      
	}
	
	// Otherwise return an error
	return -1
}

function adjustPrice(frm, option_selection) 
{
	item_spec = getItemSpecification(option_selection)
	base_price = getBasePrice(frm, item_spec) 
	new_price = calculateNewPrice(frm, item_spec, base_price) 
	updateAdjustedPrice(frm, item_spec, new_price) 
}