/* Movielens Q&A extensions to scriptaculous
 * 
 * These provide auto-complete functionality for the movie linking
 * They are based on and depend on the scriptaculous library.
 */

var ML = {Movie: {}};

ML.Movie.QuickPick = {};
ML.Movie.QuickPick.Autocompleter = Class.create();
//This is a subclass of Ajax.Autocompleter.
Object.extend(Object.extend(ML.Movie.QuickPick.Autocompleter.prototype, Ajax.Autocompleter.prototype), {
	updateElement: function(selectedElement) {
		var movieId = selectedElement.getAttribute("movieId");
		var title = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
		if(movieId != null) addElement(movieId, title);
		this.element.value = '';
	}
});

ML.Movie.QnaLinker = {};
ML.Movie.QnaLinker.Autocompleter = Class.create();
//This is a subclass of Ajax.Autocompleter.
Object.extend(Object.extend(ML.Movie.QnaLinker.Autocompleter.prototype, Ajax.Autocompleter.prototype), {
	// Selecting a movie from the auto-complete dropdown causes some 
	// specially-formatted text to appear in another textarea on the page
	// as well as *deletes* the contents of the auto-complete text box.
	updateElement: function(selectedElement) {
		var movieId = selectedElement.getAttribute("movieId");
		var title = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
		if(movieId != null) this.movielink(movieId, title);
	},

	movielink: function(id, text) {
		regexpr = new RegExp(" \\(\\d\\d\\d\\d\\)");
		text = text.replace(regexpr,"");
		var ml = "[movie id=" + id + "]" + text + "[/movie]";
		
		var txtarea = this.element; //document.getElementById(this.element.id);
		var ret = txtarea.value;
		var len = ret.length;
		
		var firstHalf = ret.substr(0, this.caretPos);
		var hashIndex = firstHalf.lastIndexOf('#');
   	 	if(hashIndex == -1) return '';
   	 	
   	 	var movielen = this.caretPos - hashIndex;
   	 	if (movielen <= 0) return '';
    	
		txtarea.value = txtarea.value.substring(0, hashIndex) + ml + " " + txtarea.value.substring(this.caretPos, len);
		this.setCaretTo(hashIndex + ml.length + 1);
		
		if (this.qnaTextLen != null)
			this.qnaTextLen.innerHTML = 150 - this.element.value.length;
	}
});

//var caretPos  = this.getCaretPosition();

