// @name      Cycle Colors
// @author    Michael Laszlo


var CCycle = {
	
	cur_hue: 0,
	cur_saturation: 0,
	cur_value: 0,
	cur_huedelta: 0,
	cur_id : 0,

	rgb_to_hex: function(r, g, b) {
		 var r = Math.floor(r * 255).toString(16);
		 var g = Math.floor(g * 255).toString(16);
		 var b = Math.floor(b * 255).toString(16);
	
		 return "#" + (r.length == 1? "0" : "") + r
		   + (g.length == 1? "0" : "") + g
		   + (b.length == 1? "0" : "") + b;
    },
	
    hsv_to_hex: function(h, s, v) {
		 var sextant = Math.floor(h / 60) % 6;
	
		 var f = h / 60 - sextant;
		 var p = v * (1 - s);
		 q = v * (1 - f * s);
		 t = v * (1 - (1 - f) * s);
		 
		 var r, g, b;
	
		 switch (sextant) {
			 case 0: r = v; g = t; b = p; break;
			 case 1: r = q; g = v; b = p; break;
			 case 2: r = p; g = v; b = t; break;
			 case 3: r = p; g = q; b = v; break;
			 case 4: r = t; g = p; b = v; break;
			 case 5: r = v; g = p; b = q; break;
		 }
		 
		 return this.rgb_to_hex(r, g, b);

   },
	
	cycle_element : function (id, duration, hue, saturation, value, fps) {
		if (!duration) duration = 20;
		if (!hue) hue = 0;
		if (!saturation) saturation = .5;
		if (!value) value = .5;
		if (!fps) fps = 20;
		var delay = 1000.0 / fps;
		var huedelta = 360.0 / (fps * duration);
		
		hue = Math.random() * 360;
				
		this.cur_id = id;
		this.cur_hue = hue;
		this.cur_saturation = saturation;
		this.cur_value = value;
		this.cur_huedelta = huedelta;

		setInterval("CCycle.paint_color()",delay);

	},
	
	paint_color	: function() {
		var rgbstring = this.hsv_to_hex(this.cur_hue, this.cur_saturation, this.cur_value);
		this.set_bgcolor(this.cur_id, rgbstring);
		this.cur_hue += this.cur_huedelta;
		if (this.cur_hue >= 360.0)
			this.cur_hue = 0.0;
	},

	set_bgcolor : function (id, c) {
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	}

}

