if(!window.TBP) window.TBP = {};

TBP.calculatorCache = {};

TBP.fireCalculatorChange = function(calculatorId) {
	TBP.calculatorCache[calculatorId].change();
};

TBP.Calculator = Class.create();
TBP.Calculator.prototype = {
	initialize: function(calculatorId, options) {
		this.calculator = $(calculatorId);
		this.options = options;
		this.multiplierId = options.multiplierId;
		this.multipliers = options.radioMultipliers;
		this.sliderIds =  options.slidersIds;
		this.sliderMultipliers = options.sliderMultipliers;
		this.totalUsageId = options.totalUsageId;
		this.total = 0;
		this.multipliervalue = "";
		this.slidervalue = "";
		
		if (this.options.onchange != ""){
				this.eventChanged = new Function("event",this.options.onchange).bindAsEventListener(this);
		}
		
		this.initialized = true;
		
		TBP.calculatorCache[calculatorId]=this;
	},
	
	change : function(){
		this.total = 0;
		this.multipliervalue = "";
		this.slidervalue = "";
		this.sliderChange();
		this.multiplierChange();
	},

	multiplierChange : function(){
		var optionClicked = document.getElementsByName(this.multiplierId);
		var isClicked = false;
		if(optionClicked != null){
		for(var i =0;i< optionClicked.length;i++){
			if(optionClicked[i].checked){
					this.total = this.total * this.multipliers[i];
					this.multipliervalue = optionClicked[i].value + ";";
					isClicked = true;
				}
			}
		}
		if(!isClicked){
			this.multipliervalue = "null" + ";";
		}
		var totalUsage = document.getElementsByName(this.totalUsageId);
		totalUsage[0].value = this.total;
		this.values = this.multipliervalue + this.slidervalue + this.total;
		this.setValue();
	},
	
	setValue: function() {
			var newValue = this.total;
			var hiddenElement = document.getElementById(this.calculator.id + "Input");
			if(hiddenElement != null){
				hiddenElement.value = this.values;
			}
			if (this.eventChanged) {
					this.eventChanged();
				}
	},
	
	sliderChange: function(){
		for(var i=0;i < this.sliderIds.length;i++){
				var sliderInputId = this.sliderIds[i] + "Input";
				var slider = document.getElementById(sliderInputId);
				if(slider.value  != null && slider.value > 0){
					var sliderTotal = slider.value * this.sliderMultipliers[i];
					this.total = this.total + sliderTotal;
					this.slidervalue = this.slidervalue + slider.value + ";";
				}else{
					this.slidervalue = this.slidervalue + "0" + ";";
				}
		}
	}
}
