window.addEvent('domready', function () {
	var connects = $$('.connectionValue');
	
	if(connects) {
		connects.each(function(elem){
			var myConnectionBar = new ConnectionBar({
				parent:elem,
				connectionValue:elem.get('text').replace(',','.')
			});
		});	
	}
});


var ConnectionBar = new Class({
	Implements: [Options, Events], 
	options: {
		barWidth:200,
		colorLow:'#FF0000',
		colorMid:'#FFFF00', 
		colorHig:'#00FF00'
	}, 
	initialize: function (options){
		this.setOptions(options);
		this.connectionPercent = this.options.connectionValue*100;
		this.setColors();
		this.setBarWidth();
		this.createBoxes();
		this.getColor();
		this.getWidth();
		this.setConnectionBar();
	},
	setColors: function () {
		var lowClass = new Fx.CSS().search('.colorLow');
		this.colorLow = (lowClass.backgroundColor) ? lowClass.backgroundColor : this.options.colorLow;
		
		var midClass = new Fx.CSS().search('.colorMid');
		this.colorMid = ( midClass.backgroundColor) ? midClass.backgroundColor : this.options.colorMid;
		
		var higClass = new Fx.CSS().search('.colorHig');
		this.colorHig = (higClass.backgroundColor) ? higClass.backgroundColor : this.options.colorHig;
	},
	setBarWidth: function () {
		var barWidthElement = new Fx.CSS().search('.connectionBorder');
		this.connectionBorderWidth = (barWidthElement.width) ? barWidthElement.width.toInt() : this.options.barWidth;
		
	},
	getColor: function () {
		this.connectionColor;
		this.connectionValue = this.connectionPercent;

		if (this.connectionValue < 50){
			this.connectionValue = Math.ceil(this.connectionValue / 0.5);
			this.connectionColor = new Color(this.colorLow).mix(this.colorMid, this.connectionValue);	
		} else if (this.connectionValue > 60) {
			this.connectionValue = Math.ceil((this.connectionValue - 60) / 0.4);
			this.connectionColor = new Color(this.colorMid).mix(this.colorHig, this.connectionValue);	
		} else {
			this.connectionColor = new Color(this.colorMid);
		}		

	},
	getWidth: function() {
		this.connectionWidth = Math.round(this.connectionPercent/100 * this.connectionBorderWidth);
	},
	createBoxes: function () {
		
		var connectionTitle = parseFloat(this.connectionPercent);
		
		this.connectionBorder = new Element('div',{
			'class':'connectionBorder', 
			'title':connectionTitle + '%', 
			'styles': {
				'width':this.connectionBorderWidth
			}
		});
		this.connectionBar = new Element('div',{
			'class':'connectionBar'
		});
	},
	setConnectionBar: function () {
		this.connectionBar.setStyles({
			'width':this.connectionWidth,
			'background-color':this.connectionColor
		});
		this.connectionBorder.inject(this.options.parent);
		this.connectionBar.inject(this.connectionBorder);
	}
});


