/*Copyright (c) 2008 Marco M. Jaeger, net4visions.com

MIT licence

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

var ColorPicker = new Class({
	Implements: [Options, Events],	
	
	options: {
		id			: 'colorPicker',
		className	: 'colorPicker',
		hoverClass	: 'hover',
		cursor		: 'pointer',		
		columns		: 8,
		palette		: 'default',
		lowerCase	: true,
		offset		: { x: 0, y: 20 },
		//onPick: $empty,
		//onShow: $empty,
		//onHide: $empty		
	},
	
	// initialize
	initialize: function(options) {
		this.setOptions(options);
		if (!$defined($(this.options.id))) {
			this.element = this.buildContainer();			
			this.setPalette(this.options.palette, this.options.columns);
			
			// add event
			$(document.body).addEvent('click', function(ev) {
				if(this.element.isVisible()) {
					ev.stop();
					this.hide();
				}
			}.bind(this)); 
		}
		
		this.callerEl = null;
		this.targetEl = null;
	},
	
	// build container
	buildContainer: function() {
		return new Element('div', {
			id		: this.options.id,
			'class'	: this.options.className,
			styles	: { display: 'none', position: 'absolute', top: 0, left: 0 },
			events	: {
				'mouseleave': function() { // hide color picker when leaving container
					this.hide.delay(500,this);
				}.bind(this)
			}
		}).inject(document.body);
	},
	
	// create grey palette
	createGreyPalette: function() {		
		var num = 16; // could be set in options ?!
		var int = (255/num-1).round() || 8;
		var max = 255 + int;		
		var colors = [];
		var s = '';
		
		for (var r = 0; r < max; r+= int) {			
			g = b = r;
			s = r.limit(0,255)+','+g.limit(0,255)+','+b.limit(0,255);
			colors.push(s.rgbToHex().replace('#', ''));
		}
		
		return colors;
	},

	// create default palette
	createDefaultPalette: function() {
		var r = 0, g = 0, b = 0, s = '';
		var int = 102;
		var max = 255 + int;
		var colors = [];
		
		for (var r = 0; r < max; r+=int) {
			for (var g = 0; g < max; g+=int) {
				for (var b = 0; b < max; b+=int) {
					s = r.limit(0,255)+','+g.limit(0,255)+','+b.limit(0,255);
					colors.push(s.rgbToHex().replace('#', ''));
				}
			}
		}
		return colors;
	},

	// create websafe palette
	createWebsafePalette: function() {
		var r = 0, g = 0, b = 0, s = '';
		var int = 51;
		var max = 255 + int;
		var colors = [];
		
		for (var r = 0; r < max; r+=int) {
			for (var g = 0; g < max; g+=int) {
				for (var b = 0; b < max; b+=int) {
					s = r.limit(0,255)+','+g.limit(0,255)+','+b.limit(0,255);
					colors.push(s.rgbToHex().replace('#', ''));
				}
			}
		}
		return colors;
	},
	
	// build color palettes
	buildPalette: function() {		
		this.colors = new Hash({
			'default':	this.createDefaultPalette(),
			'websafe':	this.createWebsafePalette(),
			'grey':		this.createGreyPalette(),
			'simple':	['000000', '8B4513', '008000', '800080', 'ffff00',
						 '0000ff', '808080', 'ffa500', 'ff0000', 'ffffff']		
		});		
		
		return this.colors;
	},

	// get color palette
	getPalette: function(palette, addGrey) {
		var colors = ($defined(this.colors))  ? this.colors : this.buildPalette();
		palette = palette || this.options.palette
		addGrey = addGrey || this.options.addGrey;
		
		return ( (palette != 'grey' && addGrey) ? colors[palette].combine(colors['grey']) : colors[palette] );
	},
	
	// set color palette
	setPalette: function(palette, columns) {
		palette = palette || this.options.palette;
		columns = columns || this.options.columns;
		
		if (palette != this.currentPalette) { // rebuild palette
			this.currentPalette = palette;
			this.element.empty();
			
			var table = this.buildTable(this.getPalette(palette), columns);
			table.inject(this.element);
		}
	},

	// build color table
	buildTable: function(paletteColors, columns) {
		var table	= new Element('table');
		var tbody 	= new Element('tbody').inject(table);
		var tr, td;
		
		$each(paletteColors, function(color, i) {				
			if (i % columns == 0) tr = new Element('tr').inject(tbody);
			
			td = new Element('td', {
				text:	'&nbsp;',
				title: 	'#' + color,
				styles: {
					'width': 10,
					'height': 10,
					'line-height': 10,
					'color': '#' + color,
					'background-color': '#' + color,
					'cursor': this.options.cursor
				},
				events: {
					'click'		:  	this.pick.pass(color, this),
					'mouseenter':	this.onMouseenter.bind(this),
					'mouseleave': 	this.onMouseleave.bind(this),
				}
			}).inject(tr);
		}.bind(this));
		
		return table;
	},
	
	// hover on color
	onMouseenter: function(event) {
		event.stop();		
		event.target.addClass(this.options.hoverClass);
	},
	
	onMouseleave: function(event) {
		event.stop();		
		event.target.removeClass(this.options.hoverClass);
	},
	
	// pick color
	pick: function(color) {
		
		color = (this.options.lowerCase) ? '#' + color.toLowerCase() : '#' + color.toUpperCase();
		
		// update caller and target fields
		if ($chk(this.callerEl)) {
			this.callerEl.set({ styles: { 'color' : color, 'background-color' : color } });
			this.targetEl.set('value', color);
		}
		var args = { caller: this.callerEl, target: this.targetEl, color: color};		
		this.fireEvent('onPick', args);
		this.hide();
	},
	
	// toggle color picker
	toggle: function(args) {
		// close previous session
		if (this.callerEl && this.callerEl != args.caller) this.hide(); // end and close previous session
		
		// toggle 
		(this.element.isVisible()) ? this.hide() : this.show(args);
		return this;
	},
	
	// show color picker
	show: function(args) {
		this.load(args).position();		
		this.element.show();		
		this.fireEvent('onShow', this);
		return this;
	},
	
	// hide color picker
	hide: function() {			
		this.element.hide();
		this.callerEl = null;
		this.targetEl = null;
		this.fireEvent('onHide', this);		
		return this;
	},
	
	// load color palette
	load: function(args) {			
		var palette = this.options.palette;
		var columns = this.options.columns;
		
		if (args) {
			if (args.colors)	palette = 			(this.colors.has(args.colors)) ? args.colors : this.options.palette;
			if (args.columns) 	columns = 			args.columns;
			if (args.caller) 	this.callerEl = 	args.caller;
			if (args.target) 	this.targetEl = 	args.target;
		};		
		
		this.setPalette(palette, columns);	
		return this;
	},
	
	// position color picker
	position: function() {		
		var el = $chk(this.callerEl) ? this.callerEl : $(document.body);		
		var pos = el.getPosition();			
		this.element.set({ styles: { top: pos.y+this.options.offset.y, left: pos.x+this.options.offset.x } });	
		return this;
	}
})
