/*
	CHECK_ORDER.JS
	The following script is based on an original script 
	written by Paul McFedries and Logophilia Limited, 
	and used with permission.

	-------------------------------------------------------------------------------------
	Used with permission of the author and modified by Website Expressions Pty Ltd (2005)
	-------------------------------------------------------------------------------------
	
	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	
	09/07/2005
					
	Version 1.1		Adjust hidden PayPal fields ready for checkout.
	22/07/2006
					
*/	


/* This script is Copyright (c) Paul McFedries and 
Logophilia Limited (http://www.mcfedries.com/).
Permission is granted to use this script as long as 
this Copyright notice remains in place.*/


function disableAllHiddenPayPalFields(frm)
{
	// Disable all actual form fields 
	for (var i = 0; i < frm.elements.length; ++i) {
		
        // Get the current field
        actual_form_field = frm.elements[i]

        // Get the field's name
        actual_field_name = actual_form_field.name

        // Check for a matching field name?
        if (actual_field_name.search("item_name_") == 0) {
        	actual_form_field.name = "x_item_name_" + actual_field_name.substring(actual_field_name.indexOf("item_name_") + 10)
        } else if (actual_field_name.search("amount_") == 0) {
        	actual_form_field.name = "x_amount_" + actual_field_name.substring(actual_field_name.indexOf("amount_") + 7)
        } else if (actual_field_name.search("quantity_") == 0) {
        	actual_form_field.name = "x_quantity_" + actual_field_name.substring(actual_field_name.indexOf("quantity_") + 9)
        } else if (actual_field_name.search("on0_") == 0) {
        	actual_form_field.name = "x_on0_" + actual_field_name.substring(actual_field_name.indexOf("on0_") + 4)
        } else if (actual_field_name.search("os0_") == 0) {
        	actual_form_field.name = "x_os0_" + actual_field_name.substring(actual_field_name.indexOf("os0_") + 4)
        }
	}
}	

function updateQuantityField(frm, item_num, quantity) 
{
//alert("update item_num " + item_num)
	// Run through all the form fields to find and update the
	// matching saved quantity field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the quantity field for this item?
        if (saved_field_name == "saved_quantity_" + item_num) {
//alert(saved_field_name + " = " + quantity)
			// If so, update the quantity
			saved_form_field.value = quantity
	    }      
	}
}

function getSavedItemName(frm, saved_item_num)
{
	// Run through all the form fields to find and return the
	// matching saved item field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the saved item name field for this item?
        if (saved_field_name == "saved_item_name_" + String(saved_item_num)) {
//alert(saved_field_name + " = " + saved_form_field.value)
			return saved_form_field.value
	    }      
	}
	// Otherwise return an empty string
	return ""
}	

function getSavedAmount(frm, saved_item_num)
{
	// Run through all the form fields to find and return the
	// matching saved amount field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the saved amount field for this item?
        if (saved_field_name == "saved_amount_" + String(saved_item_num)) {
//alert(saved_field_name + " = " + saved_form_field.value)
			return saved_form_field.value
	    }      
	}
	// Otherwise return an empty string
	return ""
}	

function getSavedQuantity(frm, saved_item_num)
{
	// Run through all the form fields to find and return the
	// matching saved quantity field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the saved quantity field for this item?
        if (saved_field_name == "saved_quantity_" + String(saved_item_num)) {
//alert(saved_field_name + " = " + saved_form_field.value)
			return saved_form_field.value
	    }      
	}
	// Otherwise return an empty string
	return ""
}	

function getSavedOptionName(frm, saved_item_num)
{
	// Run through all the form fields to find and return the
	// matching saved quantity field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the saved option name field for this item?
        if (saved_field_name == "saved_on0_" + String(saved_item_num)) {
//alert(saved_field_name + " = " + saved_form_field.value)
			return saved_form_field.value
	    }      
	}
	// Otherwise return an empty string
	return ""
}	

function getSavedOptionValues(frm, saved_item_num)
{
	// Run through all the form fields to find and return the
	// matching saved quantity field
    for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it the saved option values field for this item?
        if (saved_field_name == "saved_os0_" + String(saved_item_num)) {
//alert(saved_field_name + " = " + saved_form_field.value)
			return saved_form_field.value
	    }      
	}
	// Otherwise return an empty string
	return ""
}	

function adjustHiddenPayPalFields(frm)
{
	// Firstly disable all hidden PayPal fields
	disableAllHiddenPayPalFields(frm)
	
	// Initialise the saved item number
	saved_item_num = 1
	
	// Run through all the saved form fields to find all those
	// with a non-zero quantity
	  for (var i = 0; i < frm.elements.length; ++i) {

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

        // Get the field's name
        saved_field_name = saved_form_field.name

        // Is it a saved quantity field with a non-zero value?
        if (saved_field_name.search("saved_quantity_") == 0 && saved_form_field.value > 0) {
//alert("non-zero quantity: " + saved_field_name + " = " + saved_form_field.value)

			// Initialise the actual item numbers
			actual_item_name_num = 1
			actual_amount_num = 1
			actual_quantity_num = 1
			actual_on0_num = 1
			actual_os0_num = 1
			
			all_actual_fields_num = 0
			
			// Initialise the disabled item numbers
			actual_x_item_name_num = 1
			actual_x_amount_num = 1
			actual_x_quantity_num = 1
			actual_x_on0_num = 1
			actual_x_os0_num = 1
			

			// Run through all the actual form fields to rewrite
			// all of the actual hidden PayPal fields
		    for (var j = 0; j < frm.elements.length; ++j) {
		        // Get the current field
		        actual_form_field = frm.elements[j]
		
		        // Get the field's name
		        actual_field_name = actual_form_field.name
		
		        // Check the matching fields for this item?
		        if (actual_field_name.search("x_item_name_") == 0 || actual_field_name.search("item_name_") == 0) {
//alert("*****actual_item_name_num=" + actual_item_name_num +" saved_item_num=" + saved_item_num)
					if (actual_item_name_num + actual_x_item_name_num - 1 == saved_item_num) {
						if (getSavedQuantity(frm, saved_item_num) > 0) {
			      		  	actual_form_field.name = "item_name_" + String(actual_item_name_num)
							actual_item_name_num++	
				        } else {
			      		  	actual_form_field.name = "x_item_name_" + String(actual_x_item_name_num)				        	
							actual_x_item_name_num++	
			        	}
						actual_form_field.value = getSavedItemName(frm, saved_item_num) // i.e. the matching item name
						all_actual_fields_num++
//alert(actual_form_field.name + " = "+ actual_form_field.value + " (" + String(actual_item_name_num + actual_x_item_name_num - 1) + "-" +  all_actual_fields_num + ")");
					}
		        } else if (actual_field_name.search("x_amount_") == 0 || actual_field_name.search("amount_") == 0) {
					if (actual_amount_num + actual_x_amount_num - 1 == saved_item_num) {
						if (getSavedQuantity(frm, saved_item_num) > 0) {
				        	actual_form_field.name = "amount_" + String(actual_amount_num)
							actual_amount_num++	
				        } else {
			      		  	actual_form_field.name = "x_amount_" + String(actual_x_amount_num)				        	
							actual_x_amount_num++	
			        	}
			        	actual_form_field.value = getSavedAmount(frm, saved_item_num) // i.e. the matching amount
						all_actual_fields_num++
//alert(actual_form_field.name + " = "+ actual_form_field.value + " (" + String(actual_item_name_num + actual_x_item_name_num - 1) + "-" +  all_actual_fields_num + ")");
					}
		        } else if (actual_field_name.search("x_quantity_") == 0 || actual_field_name.search("quantity_") == 0) {
					if (actual_quantity_num + actual_x_quantity_num - 1 == saved_item_num) {
						if (getSavedQuantity(frm, saved_item_num) > 0) {
				        	actual_form_field.name = "quantity_" + String(actual_quantity_num)
							actual_quantity_num++	
				        } else {
			      		  	actual_form_field.name = "x_quantity_" + String(actual_x_quantity_num)				        	
							actual_x_quantity_num++	
			        	}
			        	actual_form_field.value = getSavedQuantity(frm, saved_item_num) // i.e. the matching quantity
						all_actual_fields_num++
//alert(actual_form_field.name + " = "+ actual_form_field.value + " (" + String(actual_item_name_num + actual_x_item_name_num - 1) + "-" + all_actual_fields_num + ")");
					}
		        } else if (actual_field_name.search("x_on0_") == 0 || actual_field_name.search("on0_") == 0) {
					if (actual_on0_num + actual_x_on0_num - 1 == saved_item_num) {
						if (getSavedQuantity(frm, saved_item_num) > 0) {
				        	actual_form_field.name = "on0_" + String(actual_on0_num)
							actual_on0_num++	
				        } else {
			      		  	actual_form_field.name = "x_on0_" + String(actual_x_on0_num)				        	
							actual_x_on0_num++	
			        	}
			        	actual_form_field.value = getSavedOptionName(frm, saved_item_num) // i.e. the matching option name
						all_actual_fields_num++
//alert(actual_form_field.name + " = "+ actual_form_field.value + " (" + String(actual_item_name_num + actual_x_item_name_num - 1) + "-" +  all_actual_fields_num + ")");
					}
		        } else if (actual_field_name.search("x_os0_") == 0 || actual_field_name.search("os0_") == 0) {
					if (actual_os0_num + actual_x_os0_num - 1 == saved_item_num) {
						if (getSavedQuantity(frm, saved_item_num) > 0) {
				        	actual_form_field.name = "os0_" + String(actual_os0_num)
							actual_os0_num++	
				        } else {
			      		  	actual_form_field.name = "x_os0_" + String(actual_x_os0_num)				        	
							actual_x_os0_num++	
			        	}
			        	actual_form_field.value = getSavedOptionValues(frm, saved_item_num) // i.e. the matching option values
						all_actual_fields_num++
//alert(actual_form_field.name + " = "+ actual_form_field.value + " (" + String(actual_item_name_num + actual_x_item_name_num - 1) + "-" +  all_actual_fields_num + ")");
					}
		        }
//alert("all_actual_fields_num=" + all_actual_fields_num)	
				// Increment the saved item number only when all corresponding actual fields have been updated
				if (all_actual_fields_num % 5 == 0 && all_actual_fields_num > 0) {
					all_actual_fields_num = 0
					saved_item_num++
//alert("Increment saved_item_num to " + saved_item_num)
				}
			}

	    }      
	}
}

function CalculateTotal(frm) {

    var order_total = 0
    item_counter = 1

    // 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
        field_name = form_field.name

        // Is it a "qty" field?
        if (field_name.substring(0,3) == "qty") {
        
            // If so, extract the price from the name
            item_price = parseFloat(field_name.substring(field_name.lastIndexOf("_") + 1))
            
            // Get the quantity
            item_quantity = parseInt(form_field.value)
            
	        // Get the qty field and item number
	        qty_field = form_field
	        qty_item_number = field_name.substring(3, field_name.indexOf("_"))

            // Find the corresponding item total field
		    for (var j=0; j < frm.elements.length; ++j) {

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

		        // Get the field's name
		        field_name = form_field.name

		        // Get the total field's item number
		        total_item_number = field_name.substring(5);

		        // Is it the matching total field?
		        if (field_name.substring(0,5) == "total" && qty_item_number == total_item_number) {

		            // If so, update the item total
		            if (item_quantity >= 0 
		            	&& item_quantity <100 
		            	&& qty_field.value.indexOf(".") < 0
		            	&& isFinite(qty_field.value)) { 
		                item_total = item_quantity * item_price
		                
					    // Display the total rounded to two decimal places
					    form_field.value = round_decimals(item_total, 2)
					    
					    // Update saved quantity
			            updateQuantityField(frm, item_counter++, item_quantity) 

		            } else {
					    // Clear the item qty and item total 
					    qty_field.value = ""
					    form_field.value = ""
					    
					    // Update saved quantity
			            updateQuantityField(frm, item_counter++, 0) 
		            }
		        }
	            
			}

            // Update the order total
            if (item_quantity >= 0) { 
                order_total += item_quantity * item_price
            }
        }
    }
    
	// Add freight to the order total
	freight = frm.freight.value
	freight_amount = parseFloat(freight)
	if (freight_amount >= 0) {
	    order_total += freight_amount
	}

    // Display the total rounded to two decimal places
    frm.order_total.value = round_decimals(order_total, 2)

    // Adjust hidden PayPal fields
	adjustHiddenPayPalFields(frm)
}

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 AddFreight(frm) {

	// Get the freight
	freight = frm.freight.value;
	freight_amount = parseFloat(freight)
	
	// Check for valid format
	if (freight_amount >= 0 
	&& freight_amount <1000 
	&& isFinite(freight)) { 
	
		// Allow a maximum of 2 decimal places
		dotpos = freight.indexOf(".")
		if (dotpos >= 0) {
			decimals = freight.substring(dotpos + 1)
			if (decimals.length > 2) {
				frm.freight.value = freight.substring(0,freight.length - 1)
			}	
		}	
			
	} else {
	
		// Clear the freight 
		frm.freight.value = ""
	}
	
	
	//---------------
	
	// Update the hidden PayPal field if required
	if(frm.shipping_1 != null) {
		frm.shipping_1.value = frm.freight.value
	}
	
	//---------------

	// Update the order total
	CalculateTotal(frm)  
}

function submitOrderCheck(frm)
{
	if(frm.cust_name.value &&
	   frm.address.value &&
	   frm.suburb.value &&
	   frm.state.value &&
	   frm.postcode.value) {
		// Allow the order to proceed
		return true;
	} else {
		// Stop the order from proceeding
		alert("Please enter your details      ");
		return false;
	}	
}