/**
 * Code for auto-complete functionality
 *
 * @author David Winterbottom
 * @copyright Tangent Labs
 */ 

// Globals
var objAutoComplete;
var booAutoComplete = true; 

// Functions on start-up - warning, these will overwrite any other onload functions
window.onload = function() 
{
    // Select search form
    $('search_field').activate();
    
    // Autocomplete object
    objAutoComplete = new Ajax.Autocompleter('search_field', 'autocomplete_choices', 'pages/get_autocomplete_choices_with_caching.tao', {callback: processSearchData, updateElement: goToSearchResults})
}

// Toggling whether auto-complete is used (not currently implemented).
function toggleAutoComplete()
{
    if (booAutoComplete) {
        //objAutoComplete.disable();
        objAutoComplete = null;
        //console.log('Autocomplete disabled');
        booAutoComplete = false;
    } else {
        objAutoComplete.enable();
        //console.log('Autocomplete enabled');
        booAutoComplete = true;
    }
}

/**
 * Custom function for passing query string to server.  This appends the media type to 
 * the end of the passed string so server can make the appropriate query to the 
 * database
 */ 
function processSearchData()
{
    var strQuery = arguments[1];
    //console.log('Searching for "'+strQuery+'" with media type '+$('media_type').value);
    
    // Pass media type separated from search string by '|||'
    return strQuery+'|||'+$('media_type').value;
}

/** 
 * Custom function for handling user selecting an item from 
 * the auto-complete option box 
 */ 
function goToSearchResults()
{
    // Manipulate form data for passing to search page...
    //console.log('Search query: "'+$('search_field').value);
    
    // Submit form
    $('searchForm').submit();
    //alert('Page now redirects to ' + arguments[0].innerHTML.stripTags() + ' page');
}