// JavaScript Document
var wineArray = [];
//console.log(freightTypeArray);
//wineArray is populated automagically from the Ditto template order-wine-products.config

function calcPrice(f){
	var total=0; var bottleTotal = 0; var orderStr = ''; var maxBottles=0;var numBottles=0;pricePerBottle=0;
	for (var i=0; i<wineArray.length;i++){
		maxBottles = Number(wineArray[i][4]);
		//console.log('maxBottles: ',maxBottles);
		numBottles = Number(wineArray[i][0].value);
		pricePerBottle = wineArray[i][1];
		if(maxBottles > 0 && numBottles > maxBottles){
				//error, set total to max bottles
				numBottles = maxBottles;
				wineArray[i][0].value = numBottles;
		}
		
		total += Number(pricePerBottle) * numBottles;
		
		bottleTotal += Number(numBottles);
		 
		orderStr += wineArray[i][0].value  + ', ' + wineArray[i][2] + ', ' + wineArray[i][1]  + ', ' + wineArray[i][3] + ', '; 
		
	}
	//console.log('orderStr=',orderStr);
	//apply discount
	if( undefined === window.productPriceMultiplier){
		productPriceMultiplier = 1;	
	}
		//console.log(productPriceMultiplier,'productPriceMultiplier');
total = total * productPriceMultiplier;
	total += (bottleTotal>0) ? Number(f.freightTotal.value) : 0;
	
	f.priceTotal.value = total.toFixed(2);
	$('priceTotalLabel').innerHTML = '$' + f.priceTotal.value;
	f.bottleTotal.value = String(bottleTotal);
	$('bottleTotalLabel').innerHTML = String(bottleTotal) + ((Number(bottleTotal) >=12) ? '' : ' (Minimum Order 1 Dozen)');
	$('bottleTotalLabel').className = (Number(bottleTotal) >=12) ? 'minimum' : 'less-than-minimum';
	$('buttonSubmit').disabled = (Number(bottleTotal) >=12) ? false : true;
	
	$('order_details').value = orderStr ;
	
}

function calcFreight(e){
	//console.log(e.options[e.selectedIndex].value);
	var bottleTotal=0;
	for (var i=0; i<wineArray.length;i++){
		wineArray[i][0].value = isNaN(Number(wineArray[i][0].value)) ? 0 : Number(wineArray[i][0].value);
		bottleTotal += Number(wineArray[i][0].value);
	}
	
	//freight is calculated PER DOZEN
	var freightMultiplier = Math.ceil(bottleTotal / 12);
	//console.log('freightMultiplier=',freightMultiplier);
	freightMultiplier = (bottleTotal > 0 && bottleTotal < 12) ? 1 : freightMultiplier;

	//e.form.freightTotal.value = ( (e.options[e.selectedIndex].value == 'Australia') ?  freightTypeArray[0][1] * freightMultiplier : freightTypeArray[1][1] * freightMultiplier);
	//Set Freight Price
	//console.log('e.selectedIndex]',e.selectedIndex)
	e.form.freightTotal.value = freightTypeArray[e.selectedIndex][1] * freightMultiplier;
	e.form.freightTotal.value = Number(e.form.freightTotal.value).toFixed(2);
	$('freightTotalLabel').innerHTML = '$' + e.form.freightTotal.value;
	
	//Set Freight text label
	//e.form.freightType.value = ( (e.options[e.selectedIndex].value == 'Australia') ?  freightTypeArray[0][0]: freightTypeArray[1][0]);
	 e.form.freightType.value = freightTypeArray[e.selectedIndex][0];
	$('freightTypeLabel').innerHTML = e.form.freightType.value;

}