var itemIds;
function newQty(item) {
//	console.log('new quantity entered')
	var priceEl, lineEl, qtyEl;
	qtyEl = document.getElementById('qty_'+item);
	lineEl = document.getElementById('linetotal_'+item);
	priceEl = document.getElementById('unitprice_'+item);

	if (qtyEl && lineEl && priceEl) {
		var qty = parseInt(qtyEl.value.replace(/[^0-9]+/,''), 10);
		var price = parseFloat(priceEl.value);
		var line = qty * price * 100;
	//	console.log('qtyEl.value:'+qtyEl.value+' qty:'+qty+' price:'+price+' calc\'d line:'+line)
		
		if (isNaN(line) || line=='0') {
			lineEl.value = '';
		} else {
			line = parseInt(line,10);
			line = new String(line);
			line = line.replace(/^([0-9]*)([0-9]{2})$/, '$1.$2');
//			console.log('string line:'+line)
			lineEl.value = line;
		}
	}
	updatePrices();
}

function updatePrices() {
//	console.log('itemlist currently: '+itemIds);
	var ids = itemIds.split(",");
	var total = 0.0, el, totalEl, deliveryEl;
	
	totalEl = document.getElementById('grandTotal');
	deliveryEl = document.getElementById('deliveryCharge');
	if (totalEl) {
		for (var i=0; i<ids.length; ++i) {
			el = document.getElementById('linetotal_'+ids[i]);
			if (el && el.value.match(/^[0-9\.]+$/)) {
				total += parseFloat(el.value);
			}
		}
		
		if (deliveryEl && deliveryEl.value && !isNaN(deliveryEl.value)) {
			total += parseFloat(deliveryEl.value);
		}
		
		total = (new String(total)).replace(/^[ 0]+([0-9])/,'$1');
		if (total.indexOf('.') == -1) {
			total += '.';
		}
		while (!total.match(/^[-0-9\.]+[0-0]{2}$/)) {
			total += '0';
		}
		
		if (total == '0.00') {
			total = 'FREE'
		}
//		console.log('calculated total is :'+total);		
		
		totalEl.value = total;
	}
}

function validate(f) { /*http=null;*/
//	console.log('validating... (value of changed = '+f.elements['deliveryChanged'].value+')')
	if (f.elements['deliveryChanged'].value == 1) {
		f.elements['deliveryChanged'].value = 0;	// reset
		
		// attempt to send a remote update and if successful, terminate this submission.
		console.log('http is... '+(http?'true':'false'))

		if (http) {
//			console.log('got xmlrequest object present - request issued... - waiting...')
			sendUpdateDeliveryCharge(f.elements['deliveryTo'].value);
			return false; // wait for the AJAX update
		} else {
//			console.log(' ajax request returned false. Submitting as form...')
			f.elements['deliveryChanged'].value = 'pending';	// replay the form with updated prices
		}
	}
	
	// default action - submit the form
	return true;
}

function pickItem(id) {
	var q = document.getElementById('qty_'+id);
	if (q) {
		if (q.value=='') {
			q.value='1';
		} else {
			var val = parseInt(q.value, 10);
			q.value=val+1;
		}
		newQty(id);
	}
}

