/**
 * pii-ui.js
 * Public Interruption Information - User Interface - JavaScript
 */

/**
 * Message to display when nothing has been entered yet.
 */
var MSG_BLANK_INPUT = "Type into the input field above and a shortlist will appear below.";

/**
 * Message to display when no options are available.
 */
var MSG_NO_OPTIONS = "No results matched your input, please check your spelling and try again.";

/**
 * Message to display before a list of options.
 */
var MSG_OPTIONS_LIST = "The following locations match your input:";

/**
 * Message to display if a non-alpha and non-digit character is entered.
 */
var MSG_UNKNOWN_INPUT = "Unknown input: Please type your location name or postcode.";

/**
 * Used for searching all initial letters.
 */
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/**
 * This function determines the list of locations that match the user's 
 * (partial) input into the field specified by inputId, and displays the list,
 * or a message where appropriate, in the document element specified by
 * selectorId.
 *
 * @param inputId The ID / name value of the <input> to read the input from.
 * @param selectorId The ID value of the <div> or other element to display the
 *   results in.
 * @param viewProvider Value of the viewProvider parameter when creating links.
 */
function refreshLocationSelector(inputId, selectorId, viewProvider) {
    // Initialise variables and DOM references
    var locationSelector = document.getElementById(selectorId);
    var locationInput = document.getElementById(inputId);

    // Get the input and covert to upper case (the displayed value also)
    var input = locationInput.value.toUpperCase();
    locationInput.value = input;
    var initialLetter = input.charAt(0);

    // Determine the available options, or a string value to be displayed
    var options; 
    if (initialLetter >= '0' && initialLetter <= '9') {
        // Postcode search
        if (input.length == 4) {
            // Complete postcode is entered
            options = locationsByPostcode[input];
        } else {
            // Keep typing...
            options = "Please type your postcode completely.";
        }
    } else if (initialLetter >= 'A' && initialLetter <= 'Z') {
        // Initial letter search
        if (input.length == 1) {
            // Only first character typed, show all options
            options = locationsByInitialLetter[input];
        } else {
            // More than one character typed, more filtering required
            var allOptions = locationsByInitialLetter[initialLetter];
            options = new Array();
            for (var i=0; i<allOptions.length; i++) {
                var option = allOptions[i];
                if (option.indexOf(input) == 0) {
                    options[options.length] = option;
                }
            }
        }
    } else if (typeof(initialLetter) === 'undefined' || input.length == 0) {
        // Nothing entered (or all input deleted), display nothing.
/*
        options = new Array();
        for (i=0; i<26; i++) {
            var letter = ALPHABET.charAt(i);
            var optionsWithInitialLetter = locationsByInitialLetter[letter];
            for (var j=0; j<optionsWithInitialLetter.length; j++) {
                options[options.length] = optionsWithInitialLetter[j];
            }
        }
*/
        options = MSG_BLANK_INPUT;
    } else {
        // Unknown character, bork!
        options = MSG_UNKNOWN_INPUT;
    }

    // Remove the current contents of the selector element
    while (locationSelector.childNodes[0]) {
        locationSelector.removeChild(locationSelector.childNodes[0]);
    }

    // Display the results, i.e. the discovered options or message
    if ((typeof(options)).toLowerCase() === 'undefined' || options.length == 0) {
        // Nothing to select
        var paraElem = document.createElement("p");
        paraElem.appendChild(document.createTextNode(MSG_NO_OPTIONS));
        locationSelector.appendChild(paraElem);
    } else if ((typeof(options)).toLowerCase() === 'string') {
        // Any other message
        var paraElem = document.createElement("p");
        paraElem.appendChild(document.createTextNode(options));
        locationSelector.appendChild(paraElem);
    } else {
        // List of options displayed as links
        var listElem = document.createElement("ul");
        for (var i=0; i<options.length; i++) {
            // The option value is of the form: "NAME (POSTCODE)".
            // Find the location name, which is used for creating the link URL,
            // by removing everything after the first bracket, and then trimming
            // the result.  This is not ideal from a robustness point of view,
            // but the only other solution would be to supply two matching 
            // arrays, one with the name only and the other with the display
            // values; however this is bad for efficiency.
            var locationName = options[i].substring(0, options[i].indexOf("(")).replace(/^\s+|\s+$/g, '');
            var listItemElem = document.createElement("li");
            var linkElem = document.createElement("a");
            linkElem.setAttribute("href", "?location=" + locationName); /* + "&viewProvider=" + viewProvider */
            linkElem.setAttribute("title", "Click this link to display information for " + locationName);
            linkElem.appendChild(document.createTextNode(options[i]));
            listItemElem.appendChild(linkElem);
            listElem.appendChild(listItemElem);
        }
        var paraElem = document.createElement("p");
        paraElem.appendChild(document.createTextNode(MSG_OPTIONS_LIST));
        locationSelector.appendChild(paraElem);
        locationSelector.appendChild(listElem);
    }
}

/**
 * Basic initialisation, called on body.onload.
 *
 * @param inputId The ID / name value of the <input> to read the input from.
 *   Passed to {@link #refreshLocationSelector()}.
 * @param viewProvider Value of the viewProvider parameter when creating links.
 *   Passed to {@link #refreshLocationSelector()}.
 * @param focusOnInput If true, the input field will be given focus.  If not,
 *   the default focus will be maintained.
 */
function initPII(inputId, viewProvider, focusOnInput) {
    document.getElementById('pii_locationSelector').style.height = '200px'; 
    refreshLocationSelector(inputId, 'pii_locationSelector', viewProvider);
    if (focusOnInput) {
        document.getElementById(inputId).focus();
    }
}

