/*
 * A Practically Custom Text Dropdown Class, Since Le Original Smelt of Elderberries
 * - Artur
 */

(function($) {
	$.fn.textdropdown = function(text, args) {		
		return this.each(function() {
			
			// These variables, although in effect are in a constructor of sorts 
			// are actually static class scoped, so we make them instance...
			var input
			var dropdown
			var value
			var selected
			
			input = $(this)
			
			// Grab Dropdown
			dropdown = input.next('ul.dropdown:first')
			
			// Hide Dropdown Initially
			dropdown.hide()
			
			// Trigger on Focus (Show Dropdown)
			// Dynamically Style Dropdown
			// Bind Keyboard Handling
			$(input).bind('focus', function() {
				setDropdownPosition()
				dropdown.slideDown(200)
				$(this).bind('keydown', handleKeyboard)
			})
			
			// Mouseover Values
			// Update value on mouseover. Can be confusing to the user, 
			// but it retains consistancy...
			$(dropdown).children().bind('mouseover', function() {
				selectValue(this)
			})
			
			// This Doesn't Even Trigger 100%, Keeping It Here Because Somebody 
			// Won't Believe The Assertion...
			// On Click, Select Value...
			//$(dropdown).bind('click', function() {
			//	console.log('Clicking Something...', this)
			//	selectValue(this)				
			//})
			
			// Trigger on Blur (Hide Dropdown)
			$(input).bind('blur', function() { handleHide(this) })
			
			function setDropdownPosition() {
				dropdown.css('position', 'absolute')
				dropdown.css('width', input.innerWidth());
				dropdown.css('left', input.position().left);
				dropdown.css('top', input.position().top + input.innerHeight());
			}
			
			function handleHide(e) {
				dropdown.slideUp(200)				
				$(e).unbind('keydown', handleKeyboard)
			}
			
			function selectValue(e) {
				$(dropdown).children().removeClass('selected')
				$(e).addClass('selected')
				selected = e
				value = $(e).text()
				input.val(value)
			}
			
			function handleKeyboard(e) {
				
				if(e.which == '13') {
					handleHide(input)
				}
				
				// UP or DOWN
				if(e.which == 40 || e.which == 38){

					element = $(dropdown).children().filter('.selected')
					
					if(element.length) {
						if(e.which == '40') {
							next = $(element).next()
						}
						else {
							next = $(element).prev()
						}
						
						if(next) {
							selectValue(next)
						}
						
					} else {
						selectValue($(dropdown).children('li:first'))
					}
				}
			}

		})
	}
})(jQuery);
