/* Main JS */

function recalculateTotals ()
{
for (var i=0; i < document.forms.length; i++)
{calculateTotals(document.forms[i]);}
}

function calculateTotals (f)
{
if (document.order)
{product_id = f.product.value;}
else
{return false;}

quantity_total = 0;
price_total = 0;

for (var i=0; i < f.elements.length; i++)
{
form_field = f.elements[i];
field_name = form_field.name;

if (field_name.substring(0,8) == "quantity")
{
//item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1));

item_quantity = parseInt(form_field.value); // Parse quantity to whole number
form_field.value = item_quantity; // Pass back parsed quantity

item_minimum = 5;
item_limit = 100; // Default limit

if (product_id == 2) // Gold
{
item_minimum = 1;
item_limit = 10;
}
else if (product_id == 3) // Platinum
{
item_minimum = 1;
item_limit = 10;
}
else if (product_id == 4) // Palladium
{
item_minimum = 1;
item_limit = 20;
}

// Alert minimum limit, update field and quantity value

if (item_quantity < item_minimum && item_quantity != 0)
{
alert('Sorry, minimum purchase ' + item_minimum + ' TOz for that product and shipping combination!\n\nAdjusting Order...');

form_field.value = item_minimum;
item_quantity = item_minimum;
}

// Alert maximum limit, update field and quantity value

if (item_quantity > item_limit)
{
alert('Sorry, limited to ' + item_limit + ' TOz for that product and shipping combination!\n\nAdjusting Order...');

form_field.value = item_limit;
item_quantity = item_limit;
}

ship_out_days = field_name.substring(field_name.lastIndexOf("_") + 1);

if (item_quantity > 0)
{
item_cost = f.elements["item_cost_" + ship_out_days].value;
shipping_cost = f.elements["shipping_cost_" + ship_out_days].value;

item_price_total = (item_cost * item_quantity) + Number(shipping_cost);

f.elements["total_ship_out_" + ship_out_days].value = round_decimals(item_price_total, 2);
}
else
{
form_field.value = '';

item_quantity = 0;
item_price_total = 0;

f.elements["total_ship_out_" + ship_out_days].value = '';
}

price_total += item_price_total;
quantity_total += item_quantity;
}

/*if (field_name.indexOf('quantity_total'))
{
var quantity_total_field = f.elements[i];
}*/

}

f.total_quantity.value = quantity_total;
f.total_price.value = round_decimals(price_total, 2);

//next_field = form_field.tabIndex + 1;

//f.elements[next_field].focus();

//return false;
}

/* BELOW NOTICE ONLY APPLIES TO CODE BELOW!
CODE ABOVE NOT RELEASED IN ANY WAY! */
 
/* 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 CalculateTotal(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 "product" field?
        if (form_name.substring(0,4) == "PROD") {

            // If so, extract the price from the name
            item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))

            // Get the quantity
            item_quantity = parseInt(form_field.value)

            // Update the order total
            if (item_quantity >= 0) {
                order_total += item_quantity * item_price
            }
        }
    }

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

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 checkTotalQuantity (f)
{
var errors = '';

if (f.total_quantity.value == 0)
{errors += 'Must Order an Item!\n\n';}

if (errors != '')
{
alert(errors);

return false;
}

return true;
}

/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
                
function handleEnter (field, event) {

		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				/*if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();*/
			if (field.form.elements[i].tabIndex == field.tabIndex + 1)
			break;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
	}      
 
	
function checkKeyPress (f, form_field, e)
{

if (e.keyCode && e.keyCode == 13)
{
e.keyCode = 9;

alert("IE");

return e.keyCode;
}
else if (e.which == 13)
{
alert("FF");

return false;
}
else if (e.which)
{
alert(e.which);

return false;
}

return true;

/*
if (window.event.keyCode && window.event.keyCode == 13)
{
window.event.keyCode = 9;

return false;
}
else if (window.event.which && window.event.which == 13)
{
return false;
}
*/
/*
if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
{
event.keyCode=9;
}

if (window.event && e.keyCode == 13)
{status = false;}
else if (e.which == 13)
{status = false;}

if (status == false)
{
next = form_field.tabIndex + 1;

try
{
f.elements[next].focus();
}
catch (err)
{alert("no banana");}
}

return status;
*/
}

function validateContactInfo (f)
{
var errors = '';

var emailRegex = /^([a-zA-Z0-9_\-\.\+])+@([a-zA-Z0-9\-])+\.([a-zA-Z0-9\.]){2,}$/; // Test for false.
var phoneRegex = /[a-z]+/i; // Test for true. Disallow letters, but allow everything else.
var nameRegex = /[^a-z]+/i; // Test for true. Disallow any non-letters.

if (f.email.value == '')
{errors += 'Email is required!\n\n';}
else if (emailRegex.test(f.email.value) == false)
{errors += 'Email format not valid!\n\n';}

if (f.first_name.value == '')
{errors += 'First Name is required!\n\n';}
else if (f.first_name.value.length < 2)
{errors += 'Please Use Full First Name!\n\n';}
else if (nameRegex.test(f.first_name.value))
{errors += 'First Name should only contain letters!\n\n';}

if (f.last_name.value == '')
{errors += 'Last Name is required!\n\n';}
else if (f.last_name.value.length < 2)
{errors += 'Please Use Full Last Name!\n\n';}
else if (nameRegex.test(f.last_name.value))
{errors += 'Last Name should only contain letters!\n\n';}

if (f.phone.value == '')
{errors += 'Phone is required!\n\n';}
else if (f.phone.value.length < 10)
{errors += 'Please enter full Phone Number Including Area Code!\n\n';}

if (phoneRegex.test(f.phone.value))
{errors += 'Phone number should not contain letters!\n\n';}

if (errors != '')
{
alert(errors);

//var emailfield = document.getElementById("email");
//emailfield.focus(); 

return false;
}

return true;
}

function checkLength (limitField, limitMax)
{
//, countField = null

if (limitField.value.length > limitMax)
{
alert("Sorry, notes limited to 255 characters\n\nAdjusting field...");

limitField.value = limitField.value.substring(0, limitMax);
}

document.forms["order"].txtacount.value = limitMax - limitField.value.length;

}

function checkLengthToo (field,limit)
{
if (field.value.length > limit)
{
field.value = field.value.substring(0, limit);
}
else
{
txtacount.value = limit - field.value.length;
}
}
// end
