YUI.add('game-input', function(Y) {
var NS = Y.namespace('mazzle');
NS.GameInput = GameInput;
function GameInput(config) {
GameInput.superclass.constructor.apply(this, arguments);
}
GameInput.NAME = "game-input";
GameInput.ATTRS = {
input: {
value: null
},
output: {
value: null
},
tags: {
value: []
}
};
GameInput.LIST_CLASS = 'tag-list';
GameInput.LIST_TEMPLATE = '
';
/* GameInput extends the Base class */
Y.extend(GameInput, Y.Base, {
initializer: function() {
this._tagNodes = {};
if(this.get("input")) {
this.input = Y.one(this.get("input"));
this.input.on("keydown", this._onKeyDown, this);
}
if(this.get("output")) {
this.output = Y.one(this.get("output"));
this.list = this._renderTagList();
this._renderTags();
}
},
destructor : function() {
},
updateTags : function(tags) {
for(var i=0; i < tags.length; i++) {
var tag = tags[i];
if(tag.id) {
var node = this._tagNodes[tag.id];
if(node) {
this._setStyle(node, tag.match);
}
}
}
},
_renderTagList : function() {
// add list
var list = this.output.one("."+GameInput.LIST_CLASS);
if(!list) {
list = Y.Node.create(GameInput.LIST_TEMPLATE);
this.output.appendChild(list);
}
return list;
},
_renderTags : function() {
var tags = this.get("tags");
if(tags) {
for(var i=0; i < tags.length; i++) {
var tag = tags[i],
tagNode = Y.Node.create(this.formatTag(tag));
this._setStyle(tagNode, tag.match);
this.list.append(tagNode);
if(tag.id) {
this._tagNodes[tag.id] = tagNode;
}
}
}
},
formatTag : function(tag) {
var score = (tag.match&&tag.match.score) ? tag.match.score : "";
return ''
+tag.label+' '
+''+score+'';
},
_addTag : function(tag) {
var tagNode = Y.Node.create(this.formatTag(tag));
this._setStyle(tagNode, tag.match);
this.list.prepend(tagNode);
return tagNode;
},
_setStyle : function(node, match) {
if(match) {
var type = (match.multiplier>=2) ? "first" : "exact";
node.addClass(type);
if(match.score) {
node.one('.score').setContent(match.score);
}
}
},
_onKeyDown : function(e) {
if(e.charCode === 13) {
var label = this.input.get("value"),
node = this._addTag({label:label});
this.input.set("value", "");
this.fire("addTag", {label:label, node:node});
}
}
});
}, 'gallery-2010.03.02-18' ,{requires:['node','base']});