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

ColorPicker = Class.create({
	initialize: function(target, color, changeCallback, controller){
		this.colorList = ["blue", "green", "yellow", "orange", "pink", "red", "purple", "teal"];
  	
		this.colorListLabels = [$L("Blue"), $L("Green"), $L("Yellow"), $L("Orange"), $L("Pink"), $L("Red"), $L("Purple"), $L("Teal")];
		
		// If target is null, then the color picker is used simply to display
		// the popup menu
		if (target != null) {
			//Mojo.Log.info("!!!!!!!!!!!! ColorPicker target is not null");
			this.target = target;
		}
		this.selectedColor = color;
		this.callback = changeCallback;
		this.sceneController = controller;
	},
	
	activate: function() {
		this.colorPickerClickHandler = this.handleColorPickerClick.bindAsEventListener(this);
		this.target.observe('click', this.colorPickerClickHandler);
	},
	
	deactivate: function() {
		if (this.target && this.colorPickerClickHandler) {
			this.target.stopObserving('click', this.colorPickerClickHandler);
		}
	},
	
	getColorLabel: function(color) {
		//Mojo.Log.info("color-picker: getColorLabel");
		var index = 0;
		var label = "";
		
		this.colorList.each(function(colorItem) {
			if (colorItem == color) 
				label = this.colorListLabels[index];
			index++;
		}, this);
		
		return label;
	},
	
	setSelectedColor: function(newColor) {
		// Check to see if the color is a member of the colorList first
		var foundColor = this.colorList.find(function(color) {
			return color == newColor;
		});
		
		if (foundColor != null && foundColor != undefined) {
			this.selectedColor = newColor;
		}
	},
	
	colorChoose: function(color) {
		this.selectedColor = color;
		if (this.callback)
			this.callback(color);
	},
	
	buildColorPickerMenu: function() {
		var listItems = [];
		var index = 0;
		
    this.colorList.each(function(color){
			listItems.push({
				label: this.colorListLabels[index],
				command: color,
				icon: "calendar-color color-chip " + "cal-color-" + color
			});
			index++;
		}, this);
		
		return listItems;
	},
	
	handleColorPickerClick: function(event) {
		this.sceneController.popupSubmenu({
        onChoose: this.colorChoose.bind(this),
    		toggleCmd: this.selectedColor, 
         /* placeNear: event.target,*/
        items: this.buildColorPickerMenu()
    });
	},
	
});
