/* GENERAL-PURPOSE FUNCTION */

/* Taken from:
http://frogsbrain.wordpress.com/2007/04/28/javascript-stringformat-method/
*/
String.format = function(text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ ) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
    }

    return text;
};

/* ORDER-FORM SPECIFIC */

jQuery(document).ready(function(){
	//Load the validation script
	jQuery("#order_form").validate();
	
	//Update order summary (should just say €0.00)
	updateOrder();
});


var itemQtys = Array();
var itemNames = Array();
var itemPrices = Array();
var feeRate;
var varRate;

function initItem(id, name, price) {
	itemNames[id] = name;
	itemPrices[id] = price;
	itemQtys[id] = 0;
}

function updateItemQuantity(id, qty) {
	if (qty > 0)
		itemQtys[id] = qty;
	else
		itemQtys[id] = 0;
}

function updateOrder() {
	var out = "<ul>";
	var total = 0.00;
	var empty = true;
	for (var i in itemQtys) {
		if (itemQtys[i] > 0) {
			var subTotal = itemPrices[i] * itemQtys[i];
			total += subTotal;
			empty = false;
			out += String.format("<li>{0} x {1} @ &euro; {2} = &euro; {3}</li>", itemQtys[i], itemNames[i], itemPrices[i], subTotal.toFixed(2));
		}
	}
	if (empty) {
		out += "<li>No items ordered</li>";
	}
	out += "</ul>"
	
	//Calculate totals
	var subTotal = total;
	var feeCharged = subTotal * feeRate / 100;
	total += feeCharged;
	
	var vatCharged = total * vatRate / 100;
	total += vatCharged;
	
	out += "<table>"
	out += String.format("<tr><td align='right'>Subtotal:</td><td>&euro; {0}</td></tr>", subTotal.toFixed(2));
	out += String.format("<tr><td align='right'>Delivery Charge ({0}%):</td><td>&euro; {1}</td></tr>", feeRate, feeCharged.toFixed(2));
	out += String.format("<tr><td align='right'>Vat Charge ({0}%):</td><td>&euro; {1}</td></tr>", vatRate, vatCharged.toFixed(2));
	out += String.format("<tr><td align='right'>Order Total:</td><td>&euro; {0}</td></tr>", total.toFixed(2));
	out += "</table>"
	document.getElementById('order_summary').innerHTML = out;
}
