//-----------------------------------------------------------------------------
// File:  search.js
//
// Purpose:  This file contains the javascript code that is specicific to
//           the advanced and basic search.
//
// Depenedencies:  CollectionTreeManager.js, common.js
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------

// regexp for empty field expression test.
var emptyString = /^\s*$/;

// holds the errors we'll display
var errors = [];

/**
 * set focus on the first search field.
 */
function focusOnSearch()
{
    if (tab_state == "simple")
    {
        document.simple_search_form.expression.focus();
    }
    else
    {
        // Find the first input element in the form and set focus to it
        var formElements = document.search.elements;
        for (var i = 0; i < formElements.length; ++i)
        {
            if (formElements[i].type == "text")
            {
                formElements[i].focus();
                break;
            }
        }
    }
}

/**
 * add an error the the array of errors to display.
 * @param errorArray the array of errors
 * @param errorMessage the error message to add
 */
function addError(errorArray, errorMessage)
{
    errorArray[errorArray.length] = errorMessage;
}

/**
 * An associative array that contains the name of test elements to ignore when
 * determininng if at least one field is filled out
 */
var textElementsToIgnore = {"toYear":"toYear",
                            "fromYear":"fromYear",
                            "alertName":"alertName",
                            "description":"description",
                            "frequency.multiplier": "frequency.multiplier"};

/**
 * Ensure that at least one of the required fields is filled out.
 * @param errors object to add errors to if any have occurred
 * @param form the form to validate against
 */
function atLeastOne(errors, form)
{
    var isNoSearchTerms = true;
    var formElements = form.elements;
    for (var i = 0; i < formElements.length; ++i)
    {
        if (formElements[i].type == "text")
        {
            if (typeof textElementsToIgnore[formElements[i].name] != "undefined")
            {
                continue;
            }

            isNoSearchTerms &= emptyString.test(formElements[i].value);
            if (!isNoSearchTerms)
            {
                break;
            }
        }
    }

    if (isNoSearchTerms)
    {
        addError(errors, searchEmptyMessage);
    }
}

//-----------------------------------------------------------------------------
// Finds out if any of the checkboxes in the search form are checked
//-----------------------------------------------------------------------------
function areAnyCollectionsChecked()
{
    var root = document.getElementById("categoryBlock");
    var nodes = root.getElementsByTagName("input");
    if (!nodes)
    {
        return false;
    }

    for (var i = 0; i < nodes.length; i++)
    {
        if (nodes[i].type == "checkbox" && nodes[i].checked)
        {
            return true;
        }
    }

    return false;
}

//-----------------------------------------------------------------------------
// Handler for the onload event from the body element
//-----------------------------------------------------------------------------
function onLoad()
{
    g_collectionTreeManager.setupCategoryTree();
    focusOnSearch();

    //Store initial values of search form to be used onreset.
    //assumes non-changing form
    var form = document.search;
    for (var i = 0; i < form.elements.length; i++)
    {
        var element = form.elements[i];
        if (element.type == "text")
        {
            initSearchFormVals[i] = element.value;
        }
        else if (element.tagName.toLowerCase() == "select")
        {
            initSearchFormVals[i] = element.selectedIndex;
        }
    }
}

function switchTabs(caller)
{
    var simple_tab   = document.getElementById('simple-tab');
    var advanced_tab = document.getElementById('advanced-tab');
    var simple_tab_container = document.getElementById('simple-tab-content');
    var advanced_tab_container = document.getElementById('advanced-tab-content');
    //do nothing if the user clicks on the currently highlighted tab
    if(caller == tab_state){
        return;
    }
    if (tab_state == 'simple' ) {
        // switch to advanced
        simple_tab.className = '';
        advanced_tab.className = 'Selected';
        advanced_tab.blur();
        simple_tab_container.className = 'Removed';
        advanced_tab_container.className = '';
        tab_state = 'advanced';
    } else {
        // switch to simple
        simple_tab.className = 'Selected';
        simple_tab.blur();
        advanced_tab.className = '';
        simple_tab_container.className = '';
        advanced_tab_container.className = 'Removed';
        tab_state = 'simple';
    }

    focusOnSearch();
}

function validateThisForm(form)
{
    // Reset the errors array
    errors = [];

    var ret = true;

    atLeastOne(errors, form);

    var validDates = validateDates();

    if (!areAnyCollectionsChecked())
    {
        addError(errors, noCategoriesSelected);
    }

    if (errors.length > 0)
    {
        var errorString = "";
        for (i = 0; i < errors.length; ++i)
        {
            errorString += errors[i];
            errorString += '\n';
        }

        window.alert(errorString);

        ret = false;
    }
    return ret && validDates;
}

// TODO:  The min year should be settable through the presentation properties
var g_minYear = 1874;
var g_currentYear = new Date().getFullYear();

function validateDates()
{
    var a = document.getElementById('fromYear');
    var b = document.getElementById('toYear');

    if (a == null || b == null)
    {
        return true;
    }

    // assume the fields are not valid until set otherwise
    var field_a_valid = false; // is the date start field valid?
    var field_b_valid = false; // is the date end field valid?
    var date_errors = document.getElementById('date-range-errors');
    date_errors.style.visibility = 'hidden'; // hide errors to start with
    var errs = new Array();

    field_a_valid = dateFieldIsValid(a, errs);
    field_b_valid = dateFieldIsValid(b, errs);
    if (! field_a_valid || ! field_b_valid) {
        showErrors(errs);
        return false;
    }

    if (field_a_valid && field_b_valid) {
        // if both date fields are valid check for sanity next
        if ((a.value > b.value) && (a.value.length > 0) && (b.value.length > 0)) {
            // if the start value is later than the end value and they're both filled in, swap them
            var tmp = a.value;
            a.value = b.value;
            b.value = tmp;
        //deal with blank from date
        } else if (a.value.length == 0 && b.value.length > 0) {
            a.value = g_minYear;
        //and blank to date
        } else if (b.value.length == 0 && a.value.length > 0) {
            b.value = g_currentYear;
        }
        return true;
    } else {
        // form is not valid
        delete errs; // reset errors
        return false;
    }
}

function showErrors(eObj)
{
    var html = '<ul>';
    for (var i = 0; i < eObj.length; i++)
    {
            html += '<li>' + eObj[i] + '</li>';
    }
    html += '</ul>';

    var date_errors = document.getElementById('date-range-errors');
    date_errors.innerHTML = html;
    date_errors.style.visibility = 'visible'; // show errors
}

function dateFieldIsValid(field, errs)
{
    var retVal = false;

    field.className = 'TextInput'; // reset class if we've touched it
    if (field.value.length == 0)
    {
        // empty fields are fine
        retVal = true;
    }
    else if (! field.value.match(/^[0-9]{4}$/))
    {
        if (field.name == 'fromYear')
        {
            errs.push('The start date must have four digits.');
        }
        else
        {
            errs.push('The end date must have four digits.');
        }
        field.className = field.className + ' ValidationError';
    }
    else if (field.value < g_minYear)
    {
        if (field.name == 'fromYear')
        {
            errs.push('The earliest searchable start year is '+g_minYear);
        }
        else
        {
            errs.push('The earliest searchable end year is ' +g_minYear);
        }
        field.className = field.className + ' ValidationError';
    }
    else if (field.value > g_currentYear)
    {
        if (field.name == 'fromYear')
        {
            errs.push('The latest searchable start year is ' + g_currentYear + '.');
        }
        else
        {
            errs.push('The latest searchable end year is ' + g_currentYear + '.');
        }
        field.className = field.className + ' ValidationError';
    }
    else
    {
        retVal = true;
    }

    return retVal;
}