// suggestion duplicate
// (c) 2008 Loco (Loohuis Consulting), http://www.loohuis-consulting.nl/
// This work is licensed under a 
// Creative Commons Attribution-Share Alike 3.0 Netherlands License
// see http://www.loohuis-consulting.nl/development/cc-by-sa.php

// script url
var url = window.location.protocol + '//' + window.location.host + window.location.pathname;
// search application interface
var searchAppURL = 'http://www.vaneigenerf.nl/search/app.php';

// suggestions
// minimum length to show suggestions for
var minSuggestLength = 3;
// timeout before fetching suggestions in milliseconds
var suggestTimeout = 400;
var suggestTimer;

// get suggestions for location
function getSuggestions(e)
{
    var elm = Event.element(e);
    clearTimeout(suggestTimer);
    $('suggestions').hide();
    var suggestBase = elm.value;
    // only retrieve suggestions if minimum length
    // and doesn't start with digit (exclude pcodes)
    if ((suggestBase.length >= minSuggestLength) && (!suggestBase.match(/^\s*\d/))) {
        suggestTimer = setTimeout("getDelayedSuggestions('" + escape(suggestBase) + "')", suggestTimeout);
    }
}

// delayed suggestion fetch
function getDelayedSuggestions(suggest)
{
    debug = new Ajax.Request(searchAppURL, {
        parameters: { 
            'suggest': suggest
        },
        onSuccess: function(r) {
            if (r.responseJSON.length) {
                // empty suggestions and add new options
                $('suggestions').update();
                r.responseJSON.each(function(l) {
                    // add links
                    $('suggestions').insert({bottom: '<li><a href="#" name="' + l + '">' + l + '</a></li>'});
                });
                // add handler to all options
                $$('#suggestions a').each(function(a) {
                    Event.observe(a, 'click', setCity, false);
                });
                $('suggestions').show();
            }
        }
    });
}

// set a city as the location
function setCity(e)
{
    elm = Event.element(e);
    if ($('vind'))
        var infield = $('vind');
    else
        var infield = $('location');
    infield.value = elm.name;
    $('suggestions').hide();
//    infield.form.submit();
}

// clear all content of an input on focus
function clearContent(e)
{
    Event.element(e).clear();
}

// overall application setup
function initSuggest()
{
    if ($('vind')) {
        Event.observe($('vind'), 'keyup', getSuggestions, false);
    }
}

Event.observe(window, 'load', initSuggest, false);
