/*
*	Package
*	colorPalette.class.js		2000.09.05
*	Victor A.Spirin,	victor_aspirin@mail.ru
*/




function colorPalette( PaletteColumns, PaletteRows, Element, Consumer )
	{
	var Columns = PaletteColumns;
	var Rows = PaletteRows;

	var ColorFragmentation = Math.round( Math.pow(Columns*Rows, 1/3) );
		if( ColorFragmentation*ColorFragmentation*ColorFragmentation != Columns*Rows ) return null;
	var ColorIncrement = 255/(ColorFragmentation - 1);

	var CellWidth;
	var CellHeight;
	var EventHandler;

		if( window.document.layers != null )
		{
		CellWidth = Element.clip.width/Columns;
		CellHeight = Element.clip.height/Rows;
		EventHandler = Element.document;
	
		function getPointerX( Evt )
			{
			return Evt.layerX;
			}
	
		function getPointerY( Evt )
			{
			return Evt.layerY;
			}
		}
		else if( document.all != null )
		{
		CellWidth = Element.offsetWidth/Columns;
		CellHeight = Element.offsetHeight/Rows;
		EventHandler = Element;

		function getPointerX()
			{
			var X = event.offsetX;
			var E = event.srcElement;
				while( E != Element )
				{
				X += E.offsetLeft;
				E = E.offsetParent;
				}
			return X;
			}

		function getPointerY()
			{
			var Y = event.offsetY;
			var E = event.srcElement;
				while( E != Element )
				{
				Y += E.offsetTop;
				E = E.offsetParent;
				}
			return Y;
			}
		}
		else return null;

	function getCellColor( Index )
		{
		var Value  = Index;
		var Components = [];
			for( var i = 2 ; 0 <= i ; i-- )
			{
			Components[i] = Value%ColorFragmentation;
			Value = (Value - Components[i])/ColorFragmentation;
			}
		return new color( ColorIncrement*Components[0], ColorIncrement*Components[1], ColorIncrement*Components[2] );
		}

	function getCellIndexByPoint( X, Y )
		{
		var Column = Math.floor( X/CellWidth );
		var Row = Math.floor( Y/CellHeight );
		return Row*Columns + Column;
		}

	EventHandler.onclick = function ( Evt )
		{
		var Color = getCellColor( getCellIndexByPoint(getPointerX(Evt), getPointerY(Evt)) );
		Consumer.setColor( Color );
		}

	return Element;
	}
