/*
 * @dependsOn config.js
 * @dependsOn application.js
 */
var Address = {
	autocomplete: function() {
		$('input[name*=\[street\]]').autocomplete( ADDRESS_AUTOCOMPLETE_URL, {
			formatItem: function (row) {
				var town = row.town;
				if(row.town != row.nbh) {
					town += ' - ' + row.nbh
				}
				return "<strong>" + row.street + "</strong>, " + town;
			},
			parse: function(data) {
				return $.map(eval(data.addresses), function( row) {
					return {
						data: row,
						value: row.street,
						result: row.address
					}
				});
			},
			matchContains: true,
			autoFill: false,
			minChars: 4,
			max: 1000,
			extraParams: {
				town: function() { return $("input[name*=\[town\]]").val(); }
			}
		});
		$('input[name*=\[street\]]').result( function(event, data, formatted) {
			$('input[name*=\[town\]]').val( data.town);
			$('input[name*=\[address_attributes\]\[id\]]').val( data.id);
			$('input[name*=\[addressId\]]').val( data.id);
		});


		$('input[name*=\[town\]]').autocomplete( ADDRESS_TOWN_AUTOCOMPLETE_URL, {
			formatItem: function (row) {
				return row.town;
			},
			parse: function(data) {
				return $.map(eval(data.addresses), function( row) {
					return {
						data: row,
						value: row.town,
						result: row.town
					}
				});
			},
			matchContains: true,
			autoFill: false,
			minChars: 2
		});
	}
}


