var sa_basicmatch = /[a-z0-9]/i;
var hasChanged = false;

function sa_getquery(p_Suggestions, p_Query)
{
    q = ltrim(p_Query);
    q = q.replace('\s+', ' ');
    if (q.length == 0 || !sa_basicmatch.test(q)) {
        sa_emptyresults(p_Suggestions);
        return '';
    }

    if (p_Suggestions.currentQuery && (p_Suggestions.currentQuery == q || p_Suggestions.tempQuery == q))
        return '';

    p_Suggestions.currentQuery = q;
    return q;
}

function sa_emptyresults(p_Suggestions)
{
    if (!p_Suggestions) return;

    p_Suggestions.innerHTML = '';
    p_Suggestions.numResults = 0;
    p_Suggestions.selectedIndex = 0;
    p_Suggestions.resultsText = [];
    p_Suggestions.resultsID = [];
    hide(p_Suggestions);
    // Show the select form element - In IE this will always be displayed on top regardless of
    // any z-index we may set. (We hid it earlier when we displayed the suggestions div)
    // perform for any possible select form elements
    if (document.getElementById('sex'))
        document.getElementById('sex').style.visibility = "visible";
    if (document.getElementById('race'))
        document.getElementById('race').style.visibility="visible";
}

function sa_addresult(p_Suggestions, p_Query, person, p_Name, p_Details, p_PersonId, selected)
{
    if (!p_Suggestions) return;

    if (selected) p_Suggestions.selectedIndex = p_Suggestions.numResults;

    idx = p_Suggestions.numResults++;
    p_Suggestions.resultsText[idx] = p_Name;
    p_Suggestions.resultsID[idx] = p_PersonId;    

    var _res = '';
    _res += '<div class="' + (selected ? 'srs' : 'sr') + '"'
         +  ' onmouseover="sa_mouseover(\'' + p_Suggestions.id + '\', \'' + p_Query.id + '\', ' + idx + ')"'
         +  ' onmouseout="sa_mouseout(\'' + p_Suggestions.id + '\', ' + idx + ')"'
         +  ' onclick="sa_mouseclick(\'' + p_Suggestions.id + '\', \'' + p_Query.id + '\', \'' + person.id + '\', ' + idx + ')">';
    _res += '<span class="srt">' + p_Name + '</span>';
    if (p_Details.length > 0)
        _res += '<span class="src">' + p_Details + '</span>';
    _res += '</div>';

    // Hide the select form element - In IE this will always be displayed on top regardless of
    // any z-index we may set
    if (document.getElementById('sex'))
        document.getElementById('sex').style.visibility="hidden";
    if (document.getElementById('race'))
        document.getElementById('race').style.visibility="hidden";
    p_Suggestions.innerHTML += _res;
}

function sa_mouseover(p_Suggestions, p_Query, idx)
{
    elt = document.getElementById(p_Suggestions);
    elt.selectedIndex = idx;
    qElt = document.getElementById(p_Query);
    qElt.focus();

    sa_highlightsel(elt);
}

function sa_mouseout(id, idx)
{
    elt = document.getElementById(id);
    elt.selectedIndex = -1;

    sa_highlightsel(elt);
}

function sa_mouseclick(p_Suggestions, p_Query, person, idx)
{
    suggestionsElement = document.getElementById(p_Suggestions);
    
    document.getElementById(p_Query).value = suggestionsElement.resultsText[idx];
    document.getElementById(person).value = suggestionsElement.resultsID[idx];
    
    document.getElementById('querybutton').click();
}

function sa_handleup(elt, qElt)
{
    if (elt.numResults > 0 && ishidden(elt)) {
        show(elt);
        return;
    }

    if (elt.selectedIndex == 0)
        return;
    else if (elt.selectedIndex < 0)
        elt.selectedIndex = elt.numResults - 1;
    else
        elt.selectedIndex--;
    sa_highlightsel(elt, qElt);
}

function sa_handledown(elt, qElt)
{
    if (elt.numResults > 0 && ishidden(elt)) {
        show(elt);
        return;
    }

    if (elt.selectedIndex == elt.numResults - 1)
        return;
    else if (elt.selectedIndex < 0)
        elt.selectedIndex = 0;
    else
        elt.selectedIndex++;
    sa_highlightsel(elt, qElt);
}

function sa_highlightsel(elt, qElt)
{
    divs = elt.getElementsByTagName('div');

    for (i = 0; i < divs.length; i++) {
        if (i == elt.selectedIndex) {
            divs[i].className = 'srs';
            elt.tempQuery = elt.resultsText[i];

            if (qElt) {
                qElt.value = elt.resultsText[i];
                document.getElementById('person').value=elt.resultsID[i];
                if (qElt.createTextRange) {
                    r = qElt.createTextRange();
                    r.moveStart('character', elt.currentQuery.length);
                    r.moveEnd('character', qElt.value.length);
                    r.select();
                }
            }
        }
        else
            divs[i].className = 'sr';
    }
}

{
// Element of the person webpage
var forenameEle = document.getElementById('forename');
var surnameEle = document.getElementById('surname');
var sexEle = document.getElementById('sex');
var clubnameEle = document.getElementById('clubname');

function clearResults()
{
    selectPerson(document.getElementById('race'));

    // Hide the results table
    hide(document.getElementById('event-results'));
}

function selectPerson(race)
{
    race.options.length = 0;
    race.options[0] = new Option(race.emptyDefault);
    race.disabled = 1;
}

function handleselection(data)
{  
    if (data.length != 0) {
        // Load the data into the INPUT fields
        document.getElementById('person').value = data[0];
        document.getElementById('forename').value = data[1];
        document.getElementById('surname').value = data[2];
        document.getElementById('sex').value = data[3];
        document.getElementById('clubname').value = data[4];
    }
    
    // Clear the input query field
    document.getElementById('query').value = '';
    sa_emptyresults(document.getElementById('search-results'));

    return true;
}

function enableRace(race, status)
{
    race.options[0] = new Option(race.fullDefault, '');
    race.selectedIndex = 0;
    race.disabled = 0;

    status.value = race.fullDefault;
}

function loadingRace(race, status)
{
    race.options.length = 0;
    race.options[0] = new Option(race.loadingText);
    race.disabled = 1;

    status.value = race.loadingText;
}

function loadedResults(status)
{
    status.value = status.fullDefault;
}

function deleteResults()
{
    var table = document.getElementById("results-table");
    // Have to delete TR elements from the end as the number of childNodes in
    // table will decrease as we delete them
    var rows = table.tBodies[0].rows.length;
    for (var i = rows - 1; i >=0; i--) {
        try {
            if (table.tBodies[0].rows[i].className != "result-row-template") {
                table.tBodies[0].removeChild(table.tBodies[0].rows[i]);
            }
        } catch (DOMException) {
            alert("Error. DOMException code: " + DOMException.code);
        }
    }
}

function populateResults(data)
{
    // Hide the results table and delete any exitsing results
    hide(document.getElementById("event-results"));
    deleteResults();

    var table = document.getElementById("results-table");
    var rows = table.rows.length;

    // For each entrant returned add a row to the table
    for (var i = 0; i < data.length; i++) {                                
        // Create a copy of the template row
        var template = document.getElementById("result-row-template");
        var row = template.cloneNode(true);
        // highlight alternate rows
        if (i % 2 == 0) {
            row.className = 'highlighted';
        } else {
            row.className = 'unhighlighted';
        }
        // Attach row to table
        // Note: We have to do this before setting the data otherwise row.cells.length 
        // will be zero in IE.
        table.tBodies[0].appendChild(row);

        // For each table cell set the content of the text
        for (var j = 0; j < row.cells.length; j++) {
            var tableCell = row.cells[j];
            // Have to add check for existing childNodes otherwise FireFox concatenates the new
            // text value to any previous value.
            try {
                for (var k=0; k < tableCell.childNodes.length; k++) {
                    tableCell.removeChild(tableCell.childNodes[k]);
                }
            } catch (DOMException) {
                // Do nothing
            }
            //tableCell.textContent = data[i][j]; // Introduced in DOM Level 3
            var textNode = document.createTextNode(data[i][j]);
            tableCell.appendChild(textNode);
        }
    }

    // Show the new results
    show(document.getElementById('event-results'));
}
}

__query.onkeydown = function(e)
                            {
                                key = ajaxac_getkeycode(e);
                                switch (key) {
                                    case 13: // enter
                                    case 27: // escape
                                        hide(__suggestions);
                                        return false;
                                        break;
                                    case 38: // up arrow
                                        sa_handleup(__suggestions, __query);
                                        return false;
                                        break;
                                    case 40: // down arrow
                                        sa_handledown(__suggestions, __query);
                                        return false;
                                        break;
                                    default:
                                        __satimer.start();
                                }
                                return true;
                            }
__querybutton.onclick = function()
                            {
                                try {
                                    __buttonclick = ajaxac_createXMLHttp();

__buttonclick.open('post', '/personresults.php/getpersondata' + '?' + 'person=' + encodeURIComponent(__person.value));

__buttonclick_xmlhttpsuccess = function()
                            {
                                _data = ajaxac_receivejsarray(__buttonclick.responseText);
                                
                                if (handleselection(_data)) {

                                    // If result exists in database - runnerid not zero.
                                    if (_data[0] != 0) {
                                        try {
                                            __athleteraces = ajaxac_createXMLHttp();

__athleteraces.open('post', '/personresults.php/getraces' + '?' + 'person=' + encodeURIComponent(__person.value));

__athleteraces_xmlhttpsuccess = function()
                            {                      
                                clearResults();
                                
                                _data = ajaxac_receivejsarray(__athleteraces.responseText);
                                if (_data.length > 0) {
                                    loadingRace(__race, __status);

                                    populateSelect(__race, _data);

                                    enableRace(__race, __status);  
                                }
                            }

__athleteraces_onreadystatechange = function()
                                {
                                    if (__athleteraces.readyState == 4) {
                                        switch (__athleteraces.status) {
                                            case 200: if (__athleteraces_xmlhttpsuccess) __athleteraces_xmlhttpsuccess(); break;
                                        }
                                    }
                                }

__athleteraces.onreadystatechange = __athleteraces_onreadystatechange;

__athleteraces.send(null);
                                        }
                                        catch (e) { alert(e.message); }
                                    }
                                }
                                return false;
                            }

__buttonclick_onreadystatechange = function()
                                {
                                    if (__buttonclick.readyState == 4) {
                                        switch (__buttonclick.status) {
                                            case 200: if (__buttonclick_xmlhttpsuccess) __buttonclick_xmlhttpsuccess(); break;
                                        }
                                    }
                                }

__buttonclick.onreadystatechange = __buttonclick_onreadystatechange;

__buttonclick.send(null);
                                }
                                catch (e) { alert(e.message); }

                                return false;
                            }
__suggestions.onload = function()
                            {
                                __query.emptyDefault = '';
                                __query.emptyDefaultDate = '';
                                __query.fullDefault = '';
                                __query.loadingText = '';

                                sa_emptyresults(this);
                            }

__suggestions.onload();

__satimer = new ajaxac_countdowntimer('__satimer.ontimerexpire()', 350);
__satimer.ontimerexpire = function()
                            {
                                _q = sa_getquery(__suggestions, __query.value);
                                if (_q.length == 0) {
                                    return false;
                                }
                                try {
                                    __safetch = ajaxac_createXMLHttp();

__safetch.open('post', '/personresults.php/getsuggestions' + '?' + 'query=' + encodeURIComponent(__query.value));

__safetch_xmlhttpsuccess = function()
                         {
                             _data = ajaxac_receivejsarray(__safetch.responseText);
                             sa_emptyresults(__suggestions);
                             if (_data.length > 0) {
                                 for (i = 0; i < _data.length; i++) {
                                     sa_addresult(__suggestions, __query, __person,
                                                   _data[i][0], _data[i][1], _data[i][2],
                                                   i == 0);
                                 }
                                 show(__suggestions);
                             } else {
                                __person.value = 0;
                             }
                         }

__safetch_onreadystatechange = function()
                                {
                                    if (__safetch.readyState == 4) {
                                        switch (__safetch.status) {
                                            case 200: if (__safetch_xmlhttpsuccess) __safetch_xmlhttpsuccess(); break;
                                        }
                                    }
                                }

__safetch.onreadystatechange = __safetch_onreadystatechange;

__safetch.send(null);
                                }
                                catch (e) { }

                                return false;
                            }
__race.onload = function()
                            {
                                this.emptyDefault = '';
                                this.fullDefault = 'Please select an event';
                                this.loadingText = 'Loading ...';

                                __status.emptyDefault = 'Please select an event';
                                __status.fullDefault = 'Click a table column header to sort the data';
                                __status.loadingText = 'Loading results ...';
                                
                                clearResults();
                            }

__race.onload();

__race.onchange = function()
                            {
                                try {
                                    // Hide the results table
                                    hide(document.getElementById('event-results'));

                                    if (this.selectedIndex == 0) {
                                        enableRace(this, __status);
                                    } else {
                                        __r2 = ajaxac_createXMLHttp();

__r2.open('post', '/personresults.php/getresults' + '?' + 'race=' + encodeURIComponent(__race.value) + '&' + 'person=' + encodeURIComponent(__person.value));

__r2_xmlhttpsuccess = function()
                            {
                                _data = ajaxac_receivejsarray(__r2.responseText);
                                populateResults(_data);
                                loadedResults(__status);
                            }

__r2_onreadystatechange = function()
                                {
                                    if (__r2.readyState == 4) {
                                        switch (__r2.status) {
                                            case 200: if (__r2_xmlhttpsuccess) __r2_xmlhttpsuccess(); break;
                                        }
                                    }
                                }

__r2.onreadystatechange = __r2_onreadystatechange;

__r2.send(null);
                                    }
                                }
                                catch (e) { alert('event_racechange exception:'+e); }

                                return false;
                            }

__download.onclick = function()
                            {
                                try {
                                    __download = ajaxac_createXMLHttp();

__download.open('post', '/personresults.php/exportresults' + '?' + 'race=' + encodeURIComponent(__race.value) + '&' + 'person=' + encodeURIComponent(__person.value));

__download_xmlhttpsuccess = function()
                            {
                                filename = __download.responseText;
                                var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=yes,directories=no';
                                window.open(filename, 'Results', props);
                            }

__download_onreadystatechange = function()
                                {
                                    if (__download.readyState == 4) {
                                        switch (__download.status) {
                                            case 200: if (__download_xmlhttpsuccess) __download_xmlhttpsuccess(); break;
                                        }
                                    }
                                }

__download.onreadystatechange = __download_onreadystatechange;

__download.send(null);
                                }
                                catch (e) { alert(e.message); }

                                return false;
                            }