/// <reference path="jquery-vsdoc.js" /> 

jQuery(function()
{
	var selectedColor = 
	{
		_R: 255,
		_G: 255,
		_B: 255,
		
		R: 255, 
		G: 255, 
		B: 255 
	};
	
	selectedColor.reset = function()
	{
		this.R = this._R;
		this.G = this._G;
		this.B = this._B;
	};
	
	selectedColor.getBrightness = function()
	{
		var maxValue = Math.max(this.R, this.G, this.B);
		var minValue = Math.min(this.R, this.G, this.B);
		return (maxValue + minValue) / 510;
	};
	
	selectedColor.getTextColor = function()
	{
		var brightness = this.getBrightness();
		return (0.4 > brightness) ? "#ffffff" : "#000000";
	};
	
	selectedColor.makeSafe = function()
	{
		var value = 51;
		this.R = value * Math.floor(this.R / value);
		this.G = value * Math.floor(this.G / value);
		this.B = value * Math.floor(this.B / value);
	};
	
	var toHex = function(value)
	{
		var result = parseInt(value).toString(16);
		if (0 === result.length) { return "00"; }
		if (1 === result.length) { return "0" + result; }
		return result;
	};
	
	var setBarValue = function(bar, value)
	{
		var width = 100 * value / 255;
		if (0 > width)
		{
			width = 0;
		}
		else if (100 < width)
		{
			width = 100;
		}
		
		bar.width(width + "%");
	};
	
	var updateColor = function()
	{
		setBarValue(jQuery("#rb"), selectedColor.R);
		setBarValue(jQuery("#gb"), selectedColor.G);
		setBarValue(jQuery("#bb"), selectedColor.B);
		
		var r = toHex(selectedColor.R);
		var g = toHex(selectedColor.G);
		var b = toHex(selectedColor.B);
		
		jQuery("#redLabel").css("color", "#" + r + "0000");
		jQuery("#greenLabel").css("color", "#00" + g + "00");
		jQuery("#blueLabel").css("color", "#0000" + b);
		
		var colorValue = "#" + r + g + b;
		var textValue = selectedColor.getTextColor();
		
		jQuery("#colourDiv").css("background-color", colorValue);
		jQuery("#colourText").css("color", textValue).text("Colour: " + colorValue);
	};
	
	var readBarValue = function(sender, event)
	{
		var x = (new Sys.UI.DomEvent(event)).offsetX;
		var value = 256 * x / jQuery(sender).width();
		
		if (0 > value)
		{
			value = 0;
		}
		else if (255 < value)
		{
			value = 255;
		}
		
		selectedColor[sender.id] = value;
		updateColor();
	};
	
	jQuery("div.colorbar").mousedown(function(event)
	{
		readBarValue(this, event);
		
		if (!this._mouseHooked)
		{
			this._mouseHooked = true;
			
			var onMove = function(event) { readBarValue(this, event); };
			
			jQuery(this)
				.mousemove(onMove)
				.one("mouseup", function() 
				{
					jQuery(this).unbind("mousemove", onMove);
					this._mouseHooked = false;
				});
		}
	});
	
	jQuery("#safeButton, a[rel=picker-safe]").click(function()
	{
		selectedColor.makeSafe();
		updateColor();
		return false;
	});
	
	jQuery("#resetButton, a[rel=picker-reset]").click(function()
	{
		selectedColor.reset();
		updateColor();
		return false;
	});
	
	updateColor();
});
