/*
 *	jquery.yinbiao 1.0 - 2009-09-28
 *
 *	All the new stuff written by pwwang (pwwang.com)	
 *	Feel free to do whatever you want with this file
 *
 */

(function($) {
	$.yinbiao = function(input, options) {
		var $input = $(input).attr("autocomplete", "off");
		var $results = $(document.createElement("ul"));	
		$results.addClass(options.resultsClass).appendTo('body');		
		resetPosition();
		$(window)
			.load(resetPosition)		// just in case user is changing size of page while loading
			.resize(resetPosition);
		$input.blur(function() {
			setTimeout(function() { $results.hide() }, 200);
		});
		$input.focus(function() {
			$input.setCaret(); 
			// need jquery.caretInsert, if no, comment it.
			yinbiao();
		});
		
		// help IE users if possible
		try {
			$results.bgiframe();
		} catch(e) { }


		function resetPosition() {
			var offset = $input.offset();
			$results.css({
				top: (offset.top + $input.height()) + 'px',
				left: offset.left + 'px'
			});
		}
		
		function yinbiao() {
			var items = ['θ','æ','ŋ','ə','ð','ɔ','ʒ','ɛ','ʃ','ʌ'];
			displayItems(items);
		}
		
		function displayItems(items) {
			if (!items)	return;		
			if (!items.length) {
				$results.hide();
				return;
			}
			var html = '';
			for (var i = 0; i < items.length; i++)
				html += '<li>' + items[i] + '</li>';
			$results.html(html).show();
			$results
				.children('li')
				.mouseover(function() {
					$results.children('li').removeClass(options.selectClass);
					$(this).addClass(options.selectClass);
				})
				.click(function(e) {
					e.preventDefault(); 
					e.stopPropagation();
					selectCurrentResult();
				});				
		}
		
		function getCurrentResult() {	
			if (!$results.is(':visible')) return false;
			var $currentResult = $results.children('li.' + options.selectClass);	
			if (!$currentResult.length)	$currentResult = false;		
			return $currentResult;
		}
		
		function selectCurrentResult() {
			$currentResult = getCurrentResult();
			if ($currentResult) 	
				$input.insertAtCaret($currentResult.text());
				// need jquery.caretInsert, if no, user the following
				// $input.val($input.val()+$currentResult.text());
				// to add current result to the end of $input.
		}
	}

	$.fn.yinbiao = function(options){
		options = options || {};
		options.resultsClass = options.resultsClass || 'pwwang_com_results';
		options.selectClass = options.selectClass || 'pwwang_com_over';
		this.each(function() {
			new $.yinbiao(this, options);
		});
		return this;
	};
	
})(jQuery);

