(function(){

	var 
	airports = [],
	alreadyFocused = {},
	airportNames = [],
	airportNamesById = {};
		
	$.getJSON("js/airports.json", function(json){
	  	airports = json;
		for (var i  in airports) {
			var name = airports[i].name;
			airportNames.push(name);
			airportNamesById[name] = airports[i].id;
		}
	});
	
	$(function(){
		prepareAutoComplete();
	});
	
	var prepareAutoComplete = function() {
	
		$('#dsAeroportoOrigem, #dsAeroportoDestino').focus(function(){
		
			var fieldName = $(this).attr('id'); 
	
			if (typeof alreadyFocused[fieldName] !== 'undefined') {
				return;
			}
			alreadyFocused[fieldName] = true;
	
			$(this).val('');
	
			$(this).autocomplete(airportNames, {		
				matchContains: true,
				minChars: 0,
				max: 100
			}).result(function(event, item) {
				var airportId = airportNamesById[item]; 
				$("input[name='" + fieldName + "']").val(airportId);
			});
		});
	};
	
	var replaceSpecialChars = function(str) {
		
		var
		specialChars = [
			{val:"a",let:"áàãâä"},
			{val:"e",let:"éèêë"},
			{val:"i",let:"íìîï"},
			{val:"o",let:"óòõôö"},
			{val:"u",let:"úùûü"},
			{val:"c",let:"ç"},
			{val:"A",let:"ÁÀÃÂÄ"},
			{val:"E",let:"ÉÈÊË"},
			{val:"I",let:"ÍÌÎÏ"},
			{val:"O",let:"ÓÒÕÔÖ"},
			{val:"U",let:"ÚÙÛÜ"},
			{val:"C",let:"Ç"},
		],
		regex,
		returnString = str;
		
		for (var i in  specialChars) {
			regex = new RegExp("["+specialChars[i].let+"]", "g");
			returnString = returnString.replace(regex, specialChars[i].val);
			regex = null;
		}
		
		return returnString;
	};
	
	String.prototype.filterData = function() { 
		return replaceSpecialChars(this.toLowerCase()); 
	};

	
})();

