var WordEditor = Class.create();

WordEditor.prototype = {
	
	instance : null,
	
	initialize : function() {
		instance = this;
		var words = document.getElementsByClassName( "word" );
		for( var i = 0; i < words.length; i++ ) {
			this.bindEditor( words[i] );
		}
	},
	
	editWord : function() {
		// disconnect the javascript onclick event
		this.onclick = null;
		var prevValue = this.innerHTML;
		this.innerHTML = '<input type="text" name="word" id="'+ this.id +'" value="'+ prevValue +'" style="width: 120px;"/>';
		this.onchange = instance.submitWord.bindAsEventListener( this );
	},
	
	submitWord : function() {
		
		var word = this.firstChild.value;
		var wordId = this.id;
		var editorNode = this;
		
		new Ajax.Request( '/req/word-editor.php',
			{
				parameters	: 'id='+ wordId +'&word=' + encodeURI( word ),
				method		: 'get',
				onComplete	: function( resp ) {
					instance.replaceWord( editorNode, word );
					instance.bindEditor( editorNode );
				}
			}
		);

	},
	
	replaceWord : function( editorNode, word ) {
		editorNode.innerHTML = word;
	},
	
	bindEditor : function( editorNode ) {
		editorNode.onclick = this.editWord.bindAsEventListener( editorNode );
	}
	
}
var we;
Event.observe( window, 'load', function() { we = new WordEditor(); }, false);

