 /**
 * jQuery Autocomplete Plugin for Calcun5
 * little modifications (adapter for autocomplete)
 * 
 * @version 1.0.0
 * @copyright Webconsult.hu Kft
 * @author PorfyP
 */
if(jQuery)( function() {
	$.extend($.fn, {
		
		/**
		* Params:
		* source: url
		*/
		calcuncomplete: function(params) {
			this.source = params.source;
			this.limit = params.limit ? params.limit : 10;
			this.list = [];
			this.addClass('ui-autocomplete-input');
			this.lastMatched = '';
			var text = this;
			var hiddenId = $(this).attr('name') + '_id';
			
			$(text).attr('disabled', 'disabled');
			$.ajax({
				url: text.source, 
				dataType: 'json', 
				success: function(data) {
					text.list = data;
					$(text).attr('disabled','');
					
				
				$(text).autocomplete({
    				source: function(req, add) {
						var source = [];
						var value = $(text).attr('value').toLowerCase();
						var valid = false;
						var limit = 1;
						for(var x in text.list) {
							if(text.list[x].text.toLowerCase().substr(0, value.length) == value) {
								if(!valid) {
									text.lastMatched = text.list[x].text;
									$('#'+hiddenId).attr('value', text.list[x].id);
									valid = true;
								}
								source.push(text.list[x].text);
								if(limit > text.limit) {
									break;
								} else {
									limit++;
								}
							}
						}
						
						if(!valid) {
							$(text).attr('value', text.lastMatched);
						}	
						
						add(source);	
					}, select: function(event, ui) {
						var value = $(text).attr('value').toLowerCase();
						for(var x in text.list) {
							if(text.list[x].text.toLowerCase() == value) {
								$(text).attr('value', text.list[x].text);
								$('#'+hiddenId).attr('value', text.list[x].id);
								break;
							}
						}
					}
				});
				/**
				* check default value
				* mannerg @ 2011-04-13
				*/
				text.validity();
			}});
			
			text.validity = function() {
				var value = $(this).attr('value').toLowerCase();
				var valid = false;
				for(var x in text.list) {
					if(text.list[x].text.toLowerCase() == value) {
						valid = true;
						$(text).attr('value', text.list[x].text);
						$('#'+hiddenId).attr('value', text.list[x].id);
						break;
					}
				}
				if(!valid) {
					$(text).attr('value', text.lastMatched);
				}	
			};
			
			$(this).keyup(function(event) {
				if(event.keyCode == 13) { // enter 
					text.validity();
				}
			});
			
			$(this).blur(function() {
				text.validity();
			});
			
							
			$(this).after('<input type="hidden" value="0" name="' + hiddenId + '" id="' + hiddenId + '"/>');
		}
	});
})(jQuery);
