﻿
var PricesCalc = {
	Models: {},
	ModelOptions: {},
	Options: {},
	CurrentPrice: 0,
	Start: function() {
		PricesCalc.Models = $('#ProductPrices input');
		PricesCalc.ModelOptions = $('.OptionPrices');
		PricesCalc.Options = $('.OptionPrices input');
		$('#formBtn').hide();
		
		PricesCalc.Models.click( function() {
			var temp = this.value.split("-");
			PricesCalc.UpdatePrice(temp[1],"reset");
			PricesCalc.ShowOptions(temp[0].split('_')[0]);
			PricesCalc.Options.removeAttr('checked');
		});
		
		PricesCalc.Options.click( function() {
			var temp = this.value.split("-");
			var mod = "add";
			if(!this.checked)
				mod = "subtract";
				
			PricesCalc.UpdatePrice(temp[1], mod);
		});
	},
	UpdatePrice: function(price, action) {
		switch(action)
		{
			case "reset":
				PricesCalc.CurrentPrice = price * 1;
				break;
			case "add":
				PricesCalc.CurrentPrice += price * 1;
				break;
			case "subtract":
				PricesCalc.CurrentPrice -= price * 1;
				break;
		}
		$('#TotalPrice span').html(PricesCalc.Format(PricesCalc.CurrentPrice));
	},
	ShowOptions: function(Id) {
		PricesCalc.ModelOptions.hide();
		$('#Options'+Id).show();
	},
	Format: function(price) {
		price += '';
		var styledPrice = '£';
		price = price.split('.');
		styledPrice += PricesCalc.AddComma(price[0], 3);
		if(price[1])
			styledPrice += '.'+price[1];
		else
			styledPrice += '.00';
			
		return styledPrice;
	},
	AddComma: function(price, count) {
		if(price.length > count)
		{
			var length = price.length;
			var diff = length-count;
			price = PricesCalc.AddComma(price.substring(0, diff), count)+','+price.substring(diff, length);
		}
		
		return price;
	}
};

$(document).ready( function() { 
	PricesCalc.Start();
});
