(function () {
	var prices = [];
	var inputs = [];

	function parsePrice(text) {
		return +(text.replace(/[^\d.]+/g, ''));
	}

	function formatPrice(num) {
		if (num === 0) {
			return 'Not Available';
		}
		var new_num = num.toString();
		
		while (new_num.match(/(\d+)(\d{3})/)) {
			new_num = new_num.replace(/(\d+)(\d{3})/,'$1,$2');
		}
		new_num = currency_symbol() + new_num;
		
		return new_num;
	}

	function calculate_totals () {
		/* sanity-check for staff numbers */
	    inputs.n_staff.value = inputs.n_staff.value || 1;

		var total = 0;
		var num_staff = +(inputs.n_staff.value);

		if (num_staff == 1) {
			/* 1 user gets the single user pack */
			total = prices.PSsingle;
		} else if (num_staff == 2) {
			/* 2 staff need the network pack, but it covers the user licenses too */
		    total = prices.PSnetwork;
		} else {
		    var user_licenses_cost = 0;
			var per_staff = prices['PSstaff1-10'];
			if (num_staff < 11) {
				/* Less than 11 users -- all at one price */
				user_licenses_cost += (num_staff * prices['PSstaff1-10']);
			} else if (num_staff >= 11) {
				/* More than 10 users -- we need to calculate the first 10 at one price, subsequent at the lower price */
				user_licenses_cost += (10 * prices['PSstaff1-10']);
				user_licenses_cost += ((num_staff - 10) * prices['PSstaff11+']);
			}
			/* Now we subtract the two user-licenses included with the network pack */
			var included_user_licenses = 2 * prices['PSstaff1-10'];
			total = (user_licenses_cost - included_user_licenses) + prices.PSnetwork;
		}
		/* Total staff licenses cost must be in 'total' by this point */

		total += +inputs.n_hours.value * prices.PShourlyRate;
		total += +inputs.n_stationery.value * prices.PSStationeryRate;

		$('#calc_table').hide();
		$('#total').html(formatPrice(total));
		$('#results').fadeIn(400);
		// yellow_fade(document.getElementById('total'));
		return false;
	}

	function recalc () {
		$('#results').hide();		
		$('#calc_table').fadeIn(400);
		return false;
	}


	function yellow_fade(elem) {
	}

	function dom_ready () {
	    var els = document.getElementsByTagName('span');
	    for (var i=0; i<els.length; i++) {
	        if (els[i].id.match(/^PS/)) {
	            prices[els[i].id] = parsePrice(els[i].innerHTML);
	        }
	    }
	    els = document.getElementsByTagName('input');
	    for (i=0; i<els.length; i++) {
	        if (els[i].id.match(/^n_/)) {
	            inputs[els[i].id] = els[i];
	        }
	    }
    
	    $('#calc_table').submit(calculate_totals);
	    $('#recalc').click(recalc);
	}

	$(dom_ready);
})();
