// Test source, list of tags from http://del.icio.us/tag/


// Our instance for the element with id "autocomplete"
/* new Autocompleter.Local('changes.townLocalityPostcode.value', tokens, {
 'minLength': 1, // We need at least 1 character
 'selectMode': 'type-ahead', // Instant completion
 'multiple': false // Tag support, by default comma separated
 });
 */
var autocompleteName;
var autocompletePostcode;
var form;

window.addEventMoo('domready', function() {
    form = $$('form')[0];
    autocompleteName = $$('.autocompleteName')[0];
    autocompletePostcode = $$('.autocompletePostcode')[0];
    var tokens = [];
    $try(function() {
        autocompleteTownLocalityPostcode(autocompletePostcode.id, tokens);
        autocompleteEstablishmentName(autocompleteName.id, tokens);
    })
})
var postcodeAutocompleter;
var nameAutocompleter;

function autocompleteEstablishmentName(elemntId, tokens) {
    nameAutocompleter = new Autocompleter.Local(elemntId, tokens, {
        'minLength': 1, // We need at least 1 character
        'multiple': false,
        'onSelection':function() {

           window.location = '' + contextPath + '/quickSearchResult.xhtml?establishmentName=' + escape(this.selected.inputValue) + ''
        }
    });
}


function autocompleteTownLocalityPostcode(elemntId, tokens) {
    postcodeAutocompleter = new Autocompleter.Local(elemntId, tokens, {
        'minLength': 1, // We need at least 1 character
        'multiple': false
    });
}

var flag = true;
function update_autocompleter(value, el) {
    if (value != '') {
        if (el.id == autocompletePostcode.id) {
            predictiveSearchService.getTownLocalityPostcodeList(value, 20, function(values) {
                if (values.length < 10) {
                    postcodeAutocompleter.choices.addClass('autoHeight');
                } else {
                    postcodeAutocompleter.choices.removeClass('autoHeight');

                }
                postcodeAutocompleter.prefetch();
                postcodeAutocompleter.update(values);

            });
        }
        if (el.id == autocompleteName.id) {
           $try( //Unresolved DWR bug. So call to dwr is wrapped. http://directwebremoting.org/jira/browse/DWR-249
                predictiveSearchService.getEstablishmentNames(value, 20, function(values) {
                    if (values.length < 10) {
                        nameAutocompleter.choices.addClass('autoHeight');
                    } else {
                        nameAutocompleter.choices.removeClass('autoHeight');

                    }
                    nameAutocompleter.prefetch();
                    nameAutocompleter.update(values);

                })
               )
        }
    }
}

