$(document).ready(function() {
	var outcome = new Bloodhound({
		datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		prefetch: 'remote.php?op=species/search/%QUERY&encode=json',
		remote: {
			url: 'remote.php?op=species/search/%QUERY&encode=json',
			wildcard: '%QUERY'
		}
	});
	
	$('#add').click( function(){
		var valid_form_data = true;
		var required_fields = '<br>';
		var tsn = $.trim($("#tsn").val());

		if( tsn.length == 0 ){
			valid_form_data = false;
			required_fields += $('label[for="itis-search"]').html() + '<br>';
			required_fields += $('label[for="complete-name"]').html() + '<br>';
		}
		
		// check note text if is required and not empty
		var familiar_name = $.trim($("#familiar-name").val());
		if ( familiar_name.length == 0 ) {
			valid_form_data = false;
			required_fields += $('label[for="familiar-name"]').html() + '<br>';
			
		}
		
		if( valid_form_data != true ){
			bootbox.alert({
				title: translated_messages[0],
				message: translated_messages[1] + required_fields
			});
		}else{
			$('#species-form').submit();
		}
	});

	
	// search autocomplete button
	$('#itis-search').typeahead(null, {
		name: 'input-itis-search',
		display: 'complete_name',
		source: outcome
		});
	}).bind("typeahead:selected", function(obj, data, name) {
			$('#itis-search').typeahead('val', '');
			$('#tsn').val( data.tsn );
			$('#complete-name').val( data.complete_name );
	});
	
