Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

var Configurator = function(obj)
{
	if(typeof obj != 'undefined')
	{
		if(typeof obj.originalPrice != 'undefined') {
			this.originalPrice = $(obj.originalPrice).val();
			this.newPrice = this.originalPrice;
		}
		if(typeof obj.newPricetag != 'undefined')
			this.newPricetag = obj.newPricetag;
		if(typeof obj.observers != 'undefined') {
			this.observers = new Array();
			this.observersValues = new Array();
			this.setObservers(obj.observers);
			
		}
	}
};

Configurator.prototype = {
	setObservers: function(observers)
	{
		var self = this;
		$(observers).each(function(index, selectBox)
		{
			self.observers.push(selectBox);
			if($('#variantPrice_'+$(selectBox).val()).size() > 0)
				self.observersValues.push($('#variantPrice_'+$(selectBox).val()).val());
				
			$(selectBox).change(function() {
			//	var index = self.observers.indexOf(this);
				var value = $(this).val();
				var $variantPricetag = $('#variantPrice_'+value);
				if($variantPricetag.size() > 0)
				{
					self.observersValues[index] = $variantPricetag.val();
					self.updatePrice();
				}
				else if(value == '---')
				{
					self.observersValues[index] = 0;
					self.updatePrice();
				}
			});
		});
		this.updatePrice();
	},
	
	
	updatePrice: function()
	{
		var newPrice = parseFloat(this.originalPrice);
		$(this.observersValues).each(function(index, price)
		{
			newPrice = newPrice+parseFloat(price);
		});
		
		this.newPrice = newPrice;
		var formattedNewPrice = this.formatPrice(newPrice);
		if($(this.newPricetag).size() > 0)
			$(this.newPricetag).html('<span class="text">Nypris:</span><span class="price">'+formattedNewPrice+',-</span>');
			
	},
	
	formatPrice: function(price)
	{
		return (price).formatMoney(2, '.', ',');
	}
};

$(function()
{
	var SykkelbutikkenProductConfigurator = new Configurator({
		originalPrice: '#originalPrice',
		observers: 'ul.configurables select',
		newPricetag: '#newPricetag'
	});
});