// Moo basket extensions. Copyright © 2007 Blix Interactive. www.blixinteractive.com

var hVariants = new Class({
							  
	initialize: function(elements){
		this.elements = elements;
		this.qsel = $("ddlQuantity");
		this.plbl = $("lblPrice");
		this.basep = ($("hPrice").value).toFloat();
		this.changep = 0;		
		
		$A(elements).each(function(el){	
			var arr = (el.value.split(","));					
			this.changep += (arr[1]).toFloat();
			this.setchange((arr[1]).toFloat(),el.getProperty('id'));
			el.onchange = function(){
    			this.selected(el);
			}.bind(this);
		}, this);		
		
		this.qsel.onchange = function(){
    		this.setprice();
		}.bind(this);
				
		this.setprice();
	},
	
	selected: function(elem)
	{
		this.changep = 0;		
		$A(this.elements).each(function(el){
			var arr = (el.value.split(","));			
			this.changep += (arr[1]).toFloat();
		}, this);		
		var arr2 = (elem.value.split(","));	
		this.setchange((arr2[1]).toFloat(),elem.getProperty('id'));
		this.setprice();
	},
	
	setchange: function(change,propid)
	{		
		if(change > 0)
		{
			$("l" + propid).setHTML("Adds " + this.correctnum(change) + ".");
		}
		else if(change < 0)
		{
			var subd = Math.abs(change);
			$("l" + propid).setHTML("Subtracts " + this.correctnum(subd) + ".");
		}
		else
		{
			$("l" + propid).setHTML("");
		}
	},
	
	correctnum: function(num)
	{
		price = "$" + num;
		if(price.indexOf(".")>-1)
		{
			var l = price.substring(price.indexOf("."), price.length);
			if(l.length < 3) price += "0";
			else if (l.length > 3)
			{
				var nr = (Math.round(num*100))/100 ;
				price = this.correctnum(nr);
			}
		}
		else
		{
			price += ".00";
		}
		return price;
	},	
	
	setprice: function()
	{
		this.newp = (this.basep + this.changep);		
		var price = this.correctnum(this.newp);
		if((this.qsel.value).toInt() >1) this.plbl.setHTML(price + " x " + this.qsel.value + " (" + this.correctnum((this.newp * (this.qsel.value).toInt())) + ")");
		else this.plbl.setHTML(price);
	}
	
});
