/* Copyright 2009 Palm, Inc.  All rights reserved. */

var ColorPickerDialogAssistant = Class.create({
	initialize: function(sceneAssistant, onselect) {
		this.sceneAssistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
		this.onselect = onselect;
	},

	show: function() {
		this.controller.showDialog({
			template: 'common/colorpicker-dialog',
			assistant: this
		});
	},

	setup : function(widget) {
		this.widget = widget;
		var colorTable = this.controller.get('color-table');
		var colors = ["00", "80", "FF"];
		var colorHash;
		var controller = this.controller;
		var row = colorTable.insertRow();
		var insertCell = this.insertCell;
		colors.each(function(red) {
			colors.each(function(green) {
				colors.each(function(blue) {
					if (row.cells.length === 6) {
						row = colorTable.insertRow(0);
					}
					colorHash = "#" + red + green + blue;
					insertCell(row, colorHash);
				});
			});
		});

		colorHash = "#C0C0C0";
		this.insertCell(row, colorHash);
		colorHash = "#A9A9A9";
		this.insertCell(row, colorHash);
		colorHash = "#696969";
		this.insertCell(row, colorHash);

		this.controller.get('cancel_button').addEventListener(Mojo.Event.tap, this.handleClose.bindAsEventListener(this));
		colorTable.addEventListener(Mojo.Event.tap, this.handleColorSelect.bindAsEventListener(this));
	},

	insertCell: function(row, colorHash) {
		var cell = row.insertCell(0);
		cell.id = colorHash;
		cell.setStyle({height:'40px', 'background-color':colorHash});
	},

	handleColorSelect: function(event) {
		Event.stop(event); // stop the tap because it causes the underlying text item to lose focus
		this.onselect(event.target.id);
		this.widget.mojo.close();
	},

	handleClose: function(event) {
		Event.stop(event); // stop the tap because it causes the underlying text item to lose focus
		this.widget.mojo.close();
	}
});

