var parcels = new Array();	
var itemPrice = new Array();
var itemQty = new Array();    
var outsideFees = new Array();
var itemProductId = new Array();
var itemStockId = new Array();
var totalDeliveryFees = 0;
var totalTransactionFees = 0;
var totalVouchers = 0;
var subTotal = 0;

function addFee(itemCount, delivery_method_id, fee_value) {
	if (outsideFees[itemCount][delivery_method_id] >= 0) {
		outsideFees[itemCount][delivery_method_id] += fee_value;
	} else {
		outsideFees[itemCount][delivery_method_id] = fee_value;
	}
}

function updateItemFees(itemCount, delivery_method_id) {
	var amount = 0;
	
	if (outsideFees[itemCount][-1] >= 0) {
		amount += outsideFees[itemCount][-1];
	}
	
	if (outsideFees[itemCount][delivery_method_id] >= 0) {
		amount += outsideFees[itemCount][delivery_method_id];
		
	}
	
    var itemTotal = (itemPrice[itemCount] * itemQty[itemCount]) + amount;
    
	var itemPriceEl = document.getElementById('itemTotal[' + itemCount + ']');
	var itemOutsideEl = document.getElementById('itemOutside[' + itemCount + ']');
	
	if (itemPriceEl != null) {
		itemPriceEl.value = '$' + itemTotal.toFixed(2);
		itemOutsideEl.value = '$' + amount.toFixed(2);
	}
	
}

/**
 * Makes sure that all totals on the screen are up to date
 * with the latest ticket prices, ticket fees, delivery and
 * transaction fees, and updates all subtotals and grand totals.
 * 
 */
function updateTotals() {
	
	subTotal = 0;
	
	/*
	 * Iterate through the prices in the global itemPrice array
	 * and sum up all prices and fees. Some products have extra
	 * per-ticket fees based on delivery method, so user delivery method
	 * selections must be checked and used in the calculations.
	 */
    for (var itemCount in itemPrice) {
    
    	/* 
    	 * With cpaint included, all arrays contain a toJSONString item
    	 * which needs to be omitted from the calculations (obviously)
    	 */ 
    	if (itemCount !== 'toJSONString') {
	    	var deliveryElement = document.getElementById('item_delivery[' + itemCount + ']');
	    	subTotal += (itemQty[itemCount] * itemPrice[itemCount]);
	    	if (deliveryElement != null) {
	
	    		delivery_method_id = deliveryElement.value;
	    		var amount = 0;
	    		if (outsideFees[itemCount][-1] >= 0) {
	    			amount += outsideFees[itemCount][-1];
	    		}
	    		
	    		if (outsideFees[itemCount][delivery_method_id] >= 0) {
	    			amount += outsideFees[itemCount][delivery_method_id];
	    			
	    		}    		
	    		
	    		subTotal += amount;
	    	} else {
	    		//alert('No delivery method ID?');
	    	}
    	}    	
    }

    showRecalcIndicator(true);
    /* 
     * Make a cpaint call to regenerate the parcels and
     * recalculate all delivery and transaction fees. 
     */ 
    cpaintCalcDelivery();
    
    /*
     * Display a progress icon in the totals field while
     * they are being updated from the server.
     */
    //updateSubTotals();
    
    
}

function showRecalcIndicator(showProgress) {
	
	//var elDelivery = document.getElementById('totalDeliveryFeeInput);
	toggleProgressIndicator(showProgress, 'totalDeliveryFeesInput', 'totalDeliveryFeesProgress');
	toggleProgressIndicator(showProgress, 'subTotalInput', 'subTotalProgress');
	toggleProgressIndicator(showProgress, 'subTotalGrandInput', 'subTotalGrandProgress');
	toggleProgressIndicator(showProgress, 'grandTransactionInput', 'grandTransactionProgress');
	toggleProgressIndicator(showProgress, 'grandTotalInput', 'grandTotalProgress');
//			toggle_visibility('totalDeliveryFeeInput');
//			toggle_visibility('totalDeliveryFeeProgress');
//	var elSubTotal = ;
//	var elGrandTotal = ;
//	var el
	
}

function toggleProgressIndicator(progressOn, divId, progressId) {
	
	var elInput = document.getElementById(divId);
	var elProgress = document.getElementById(progressId);
	
	if (progressOn) {
		elInput.style.display = 'none';
		elProgress.style.display = 'block';
		elProgress.innerHTML = "<img src='images/fee_loader.gif' />";
	} else {
		elInput.style.display = 'block';
		elProgress.style.display = 'none';
		elProgress.innerHTML = "&nbsp;";
	}		
	
}

/**
 * Updates the subtotal section of the page with the latest values,
 * and then calls updateGrantTotals() to make sure any changes flow
 * through.
 * 
 */
function updateSubTotals() {
    var elDeliveryFees = document.getElementById('totalDeliveryFees');
    elDeliveryFees.value = '$' + totalDeliveryFees.toFixed(2); 
    var subTotalElement = document.getElementById('itemSubTotal');
    subTotalElement.value = '$' + (subTotal + totalDeliveryFees).toFixed(2);   
    
    updateGrandTotals();
}

/**
 * Updates the grand total section of the page with the latest
 * values.
 * 
 */
function updateGrandTotals() {

	var elTotalBeforeTxn = document.getElementById('totalBeforeTxn');
	var elTotalTxn = document.getElementById('totalTxn');
	var elGrandTotal = document.getElementById('grandTotal');
	
	var elSubElement = document.getElementById('itemSubTotal');
	
	var subTotal = parseInt(elSubElement.value.substring(1, elSubElement.value.length));
	
	elTotalBeforeTxn.value = '$' + subTotal.toFixed(2);
	elTotalTxn.value = '$' + totalTransactionFees.toFixed(2);
	elGrandTotal.value = '$' + (subTotal + totalTransactionFees + totalVouchers).toFixed(2);

	var elPaymentTable = document.getElementById('payment_details');
	if (subTotal + totalTransactionFees + totalVouchers <= 0) {
		elPaymentTable.style.display = 'none';
	} else {
		elPaymentTable.style.display = 'block';
	}
	
}

/**
 * The callback function for cpaintCalcDelivery().
 * 
 * The function gets the delivery and transaction fee totals from
 * the cpaint result, sets the totalDeliveryFees value (global scope)
 * and then makes a call to the updateSubTotals() method so that
 * the screen can be refreshed with any new values.
 * 
 * @param result (cpaint result - XML)
 */
function cpaintCalcDeliveryCallback(result) {

	var delivery = result.getElementsByTagName('delivery');
	var transaction = result.getElementsByTagName('transaction');
	var vouchers = result.getElementsByTagName('voucher');
	
	if (delivery[0].firstChild != null) {
		totalDeliveryFees = parseFloat(delivery[0].firstChild.nodeValue);
	} else {
		totalDeliveryFees = 0;
	}
	
	if (transaction[0].firstChild != null) {
		totalTransactionFees = parseFloat(transaction[0].firstChild.nodeValue);
	} else {
		totalTransactionFees = 0;
	}

	var elAppliedVouchers = document.getElementById('transaction_table');
		if (elAppliedVouchers != null) { 
				elAppliedVouchers.style.display = 'none';
						while (elAppliedVouchers.hasChildNodes()) {
								
													elAppliedVouchers.removeChild(elAppliedVouchers.lastChild);
																
																		}
																			} else {
																					elAppliedVouchers.style.display = 'block';
																						}
	totalVouchers = 0;
	
	if (vouchers.length > 0) {
		
		var insertPoint = document.getElementById('transaction_fee_tr');

		for (var i = 0; i < vouchers.length; i++) {
			if (vouchers[i] != null) {
				var voucherElementTr = document.createElement('tr');
				var voucherCodeTd = document.createElement('td');
				var voucherDiscountTd = document.createElement('td');
				var voucherRemoveTd = document.createElement('td');
				
				voucherElementTr.title = "voucher_tr";
				voucherElementTr.id = "voucher_tr_" + vouchers[i].getAttribute('voucher_code');
				
				voucherCodeTd.className = "text";
				voucherDiscountTd.className = "subtitles_green";
				voucherDiscountTd.style.textAlign = "right";
				
				voucherCodeTd.innerHTML = "Voucher: " + vouchers[i].getAttribute('voucher_code');
				voucherDiscountTd.innerHTML =  '-$' + (parseFloat(vouchers[i].firstChild.nodeValue)).toFixed(2); // The discount value
				
				totalVouchers = totalVouchers - parseFloat(vouchers[i].firstChild.nodeValue);
				
				var removeElement = document.createElement('input');
				removeElement.type = 'button';
				removeElement.value = 'Remove';
				removeElement.name =   vouchers[i].getAttribute('voucher_code');
				
				removeElement.onclick = function() { removeVoucher(this); };
				
				voucherRemoveTd.appendChild(removeElement);
				
				voucherElementTr.appendChild(voucherCodeTd);
				voucherElementTr.appendChild(voucherDiscountTd);
				voucherElementTr.appendChild(voucherRemoveTd, voucherCodeTd);
				elAppliedVouchers.appendChild(voucherElementTr);
			}			
		}
	}
	
	updateSubTotals();
	showRecalcIndicator(false);
	
}

/**
 * Makes the cpaint call to get up-to-date delivery and transaction
 * fees based on the customer's currently selected delivery methods.
 *
 * @see cpaintCalcDeliveryCallback();
 */
function cpaintCalcDelivery() {
	
	var selectedDelivery = new Array();
	
    for (var itemCount in itemProductId) {
    	if (itemCount !== 'toJSONString') {
	    	var deliveryElement = document.getElementById('item_delivery[' + itemCount + ']');
	    	if (deliveryElement != null) {
		    	selectedDelivery[itemCount] = deliveryElement.value;
	    	}
    	}
    }
	
	var cp = new cpaint();
	cp.set_debug(false);
	cp.set_response_type('XML');
	cp.set_async(true);
    cp.set_persistent_connection(false);	
	
	cp.call('cpaint_calculate.php', 'calculate_delivery', cpaintCalcDeliveryCallback, itemProductId, itemStockId, selectedDelivery);
}
