var dom = (document.getElementById) ? true : false;

function add_item()
{
	var browser = BrowserDetect.browser;
	
	// some quick JS validation
	var form = document.order;
	if (!form.facility_name.value ||
	    !form.phone.value ||
		!form.name.value ||
		!form.address1.value ||
		!form.address2.value ||
		!form.email.value
	)
	{
		alert('Please complete all required contact fields before adding items.');
		return;
	}
	var table = get_element('table_items');
	
	// let's create the list that will reside inside the new_item div
	var f = add_item_input('code[]');
	table.appendChild(f);
	var f = add_item_input('qty[]', true);
	// add the onkeyup event handler
	if ('Explorer' == browser) {
		f.attachEvent('onkeyup', function(e) { calculate_price() } );
	}
	else {
		f.setAttribute('onkeyup', 'calculate_price()');
	}
	table.appendChild(f);
	var f = add_item_input('desc[]');
	table.appendChild(f);
	var f = add_item_input('colour[]');
	table.appendChild(f);
	var f = add_item_input('cost[]', true);
	// add the onkeyup event handler
	if ('Explorer' == browser) {
		f.attachEvent('onkeyup', function(e) { calculate_price() } );
	}
	else {
		f.setAttribute('onkeyup', 'calculate_price()');
	}
	table.appendChild(f);
}

function get_element(id)
{
	return (dom) ? document.getElementById(id) : document[id];
}

function add_item_input(name, addClause)
{
	var nf = document.createElement('input');
	nf.setAttribute('type', 'text');
	nf.setAttribute('name', name);
	
	var div = document.createElement('div');
	div.className = (name != 'desc[]') ? 'small_td input_small' : 'large_td input_large';
	div.appendChild(nf);
	
	return div;
}

function calculate_price()
{
	var table = get_element('table_items');
	var total = 0;
	var qty = 0;
	var cost = 0;
	
	// get all the input elements from within the table element
	var fields = table.getElementsByTagName('input');
	for (var i = 0; i < fields.length; i++)
	{
		var f = fields[i];
		var name = f.name;
		
		if (name)
		{
			switch (name.substr(0,3))
			{
				case 'qty':
					qty = f.value;
					break;
				case 'cos':
					cost = f.value;
					break;
			}
		}
		
		// if both fields are present and completed, calculate the total
		if (qty && cost)
		{
			total += (qty * cost);
			
			qty = 0;
			cost = 0;
		}
	}
	
	tc = get_element('t_c');
	tc.innerHTML = (total) ? total.toFixed(2) : '0.00';
}