// EMC Flyout
// By: R Brown
// May 2009

$.emc = $.emc || {};  // Make the EMC namespace availible

(function ( $ ) {                  // Compliant with jquery.noConflict()
	$.fn.emc_predictiveText = function(o) {
		
		o = $.extend({
				partner : '' //the id of the partner field - used to filter options based on another field's value, e.g. for dependant lists, e.g. departure/destination airports
		}, o || {});
		
		var field, partner, predictions;
		
		field = $(this);
		partner = $('#' + o.partner);
		
		field.each(init);
		
		function init(){
			field.attr('autocomplete','off').focus( closeFlyouts ).blur( hidePredictions ).keyup( showPredictions );
			
			predictions = $('<div class="flyout predictive"><div class="tl"><div class="tr"></div></div><div class="ml"><div class="mr"></div></div><div class="bl"><div class="br"></div></div></div>').insertAfter(field).css({ 'margin-left':'-2px','margin-top':'-3px','min-width':field.innerWidth()+22+'px'});
			//reposition for internet explorer
			if($.browser.msie){
				predictions.css({
					'margin-left' : -(2+field.outerWidth()) + 'px',
					'margin-top' : field.outerHeight() + 'px'
				});
			}
		}
		
		function hidePredictions(){
			if($.browser.msie) field.parent().eq(0).css('z-index','0');
			predictions.hide();
		}
		
		function showPredictions(){
			if(field.val().length > 1){
				found = '';
				var optionsList = $('<ul></ul>');
				var fieldValue = field.val();
				var partnerValue = '';
				
				//get the value of the partner field
				if(partner.length){
					jQuery.each(keyArray, function(){
						if (this.meaning == partner.val()) {
							partnerValue = this.code;
						}
					});
				}
				
				if($.browser.msie) field.parent().eq(0).css('z-index','1');
				
				//loop through the options adding relevant ones to the list
				jQuery.each(keyArray, function(){
					if(this.meaning.toLowerCase().match(fieldValue.toLowerCase()) || this.code.toLowerCase().match(fieldValue)) {
						//if there's no partner value or the options is valid for the partner field add it to the options list
						if (partnerValue=='' || (departureArray[partnerValue] && jQuery.inArray(this.code, departureArray[partnerValue]) != -1)) {
							$('<li><a href="#none">' + this.meaning + '</a></li>').appendTo(optionsList);
							found += '1';
						}
					}
				});
				
				//add the list of options to the predictions flyout and display it
				if (found) {
					$('div.mr',predictions).html(optionsList);
					$('a',predictions).mousedown( function(){
						field.val($(this).html());
						hidePredictions();
						return false;
					}).click( function(){
						return false;
					});
					predictions.show();
				}
				else {
					hidePredictions();
				}
			} 
			else{
				hidePredictions();
			}
			
		}
		
		function closeFlyouts(){
			if($.emc.flyouts.length) for(n=0;n<$.emc.flyouts.length;n++) $.emc.flyouts[n].hide();
		}
		
			
	}
})(jQuery);
