/**
 * Project Reckoning 3.0a, Editor Structural Component
 *
 * File: check_required.js
 *
 * Javascript library to handle checking required fields on a form.
 *
 * Copyright 2000, Data House, Inc. Authored by Jeff Malins
 **/

/** Process input validations and submit the form **/
function doRequiredCheck(form) {

    var req_fields = new Array();
    var dt_fields = new Array();
    var num_fields = new Array();
    var time_fields = new Array();
    var float_fields = new Array();
    var file_fields = new Array();
    var alphanum_fields = new Array();

    var items = form.elements;
    for (var i = 0; i < items.length; i++) {
        var con = items.item(i);
        if (con.getAttribute('required') == 'true' && !checkRequired(con, form, req_fields)) {
            req_fields[req_fields.length] = con;
        }
        if (con.getAttribute('datevalue') == 'true' && !checkDate(con.value)) {
            dt_fields[dt_fields.length] = con;
        }
        if (con.getAttribute('numvalue') == 'true' && !checkNum(con.value)) {
            num_fields[num_fields.length] = con;
        }
        if (con.getAttribute('timevalue') == 'true' && !checkTime(con.value)) {
            time_fields[time_fields.length] = con;
        }
        if (con.getAttribute('floatvalue') == 'true' && !checkFloat(con.value)) {
            float_fields[float_fields.length] = con;
        }
        if (con.getAttribute('filename') == 'true' && !checkFilename(con.value)) {
            file_fields[file_fields.length] = con;
        }
        if (con.getAttribute('alphanumeric') == 'true' && !checkAlphaNumeric(con.value)) {
            alphanum_fields[alphanum_fields.length] = con;
        }
    }

    if (req_fields.length == 1) {
        window.showMessage('RequiredField', req_fields);
        return false;
    } else if (req_fields.length > 1) {
        window.showMessage('RequiredFields', req_fields);
        return false;
    }

    if (dt_fields.length == 1) {
        window.showMessage('InvalidDate', dt_fields);
        return false;
    } else if (dt_fields.length > 1) {
        window.showMessage('InvalidDates', dt_fields);
        return false;
    }

    if (num_fields.length == 1) {
        window.showMessage('InvalidNumber', num_fields);
        return false;
    } else if (num_fields.length > 1) {
        window.showMessage('InvalidNumbers', num_fields);
        return false;
    }

    if (float_fields.length == 1) {
        window.showMessage('InvalidNumber', float_fields);
        return false;
    } else if (float_fields > 1) {
        window.showMessage('InvalidNumbers', float_fields);
        return false;
    }

    if (time_fields.length == 1) {
        window.showMessage('InvalidTime', time_fields);
        return false;
    } else if (time_fields.length > 1) {
        window.showMessage('InvalidTimes', time_fields);
        return false;
    }

    if (file_fields.length >= 1) {
        window.alert(getStringMessage('InvalidFilename'));
        return false;
    }

    if ( alphanum_fields.length == 1 ) {
        window.showMessage('InvalidAlphaNumeric', alphanum_fields);
        return false;
    } else if ( alphanum_fields.length > 1 ) {
        window.showMessage('InvalidAlphaNumerics', alphanum_fields);
        return false;
    }

    return true;
}

/** Show a message with the field names **/
function showMessage(msg, fields) {
    var text = '\n\n';
    for (var i = 0; i < fields.length; i++) {
        text += fields[i].title + '\n';
    }
    // Since we don't have the text resource bundles for i18n
    // like in PR, we'll just hardcode the different types of messages
    // we can have.

    if ( msg == 'RequiredField' ) {
        window.alert( "Please fill in this required field:" + text );
    } else if ( msg == 'RequiredFields' ) {
        window.alert( "Please fill in these required fields:" + text );
    } else if ( msg == 'InvalidDate' ) {
        window.alert( "Please enter the correct date format\n(MM/DD/YYYY) for this field:" + text );
    } else if ( msg == 'InvalidDates' ) {
        window.alert( "Please enter the correct date format\n(MM/DD/YYYY) for these fields:" + text );
    } else if ( msg == 'InvalidNumber' ) {
        window.alert( "Please enter a valid number in this field:" + text );
    } else if ( msg == 'InvalidNumbers' ) {
        window.alert( "Please enter a valid number in these fields:" + text );
    } else if ( msg == 'InvalidAlphaNumeric' ) {
        window.alert( "Please enter non-special characters in this field:" + text );
    } else if ( msg == 'InvalidAlphaNumerics' ) {
        window.alert( "Please enter non-special characters in these fields:" + text );
    } else {
    }
    
//    window.alert(getFieldMessage(msg, text.substring(0, text.length - 1)));

    try {
        // set the focus to the first offending field
        fields[0].select();
    } catch (e) {
        // an error may occur if the field is not on the currently visible page
        // we will ignore this error
    }
}

/** Check a required field **/
function checkRequired(con, form, fields) {
    var tname = con.tagName.toUpperCase();
    if (tname == 'INPUT') {
        var kind = con.getAttribute('type').toUpperCase();
        if (((kind == 'TEXT') || (kind == 'PASSWORD') || (kind == 'FILE')) &&
            (isBlank(con.value)))
        {
            return false;
        } else if ((kind == 'RADIO') && !window.checkContains(fields, con)) {
            var radios = form.elements(con.name);
            var oneChecked = false;
            for (var j = 0; j < radios.length; j++) {
                if (radios.item(j).checked) {
                    oneChecked = true;
                    break;
                }
            }
            if (!oneChecked) {
                return false;
            }
        }
    } else if ((tname == 'TEXTAREA') && (isBlank(con.value))) {
        return false;
    } else if (tname == 'SELECT') {
        var opts = con.options;
        var oneChecked = false;
        for (var j = 0; j < opts.length; j++) {
            if(opts[j].selected && opts[j].value != '') {
                oneChecked = true;
                break;
            }
        }

        if (!oneChecked) {
            return false;
        }
    }
    return true;
}

/** See if an array contains an element with the specified item's title **/
function checkContains(array, value) {
    if (array == null) return false;

    for (var j = 0; j < array.length; j++) {
        if (array[j].title == value.title) return true;
    }

    return false;
}

/** Check if a string is blank **/
function isBlank(text) {
    for (var i = 0; i < text.length; i++) {
        if (text.charAt(i) != ' ') {
            return false;
        }
    }
    return true;
}

/** Check a date to see if it is in M/d/yyyy format **/
function checkDate(val) {

    if (isBlank(val)) {
        return true;
    }

    var pieces = val.split("/");
    if (pieces.length != 3) {
        return false;
    }

    // swap pieces if this is japanese
    if (window.prlocale == 'Japanese') {
        val = pieces[1] + '/' + pieces[2] + '/' + pieces[0];
        pieces = val.split("/");
    }

    if (pieces[2].length != 4) {
        return false;
    }

    // we have to pass in the radix here because numbers with leading 0
    // are assumed octal otherwise.
    var month = parseInt(pieces[0], 10);
    var day = parseInt(pieces[1], 10);
    var year = parseInt(pieces[2], 10);
    var dt = new Date(val);
    if (((dt.getMonth() + 1) != month) || (dt.getDate() != day) || (dt.getFullYear() != year)) {
        return false;
    }
    return true;
}


/** Check if a field is numeric **/
function checkNum(val) {
    if (isBlank(val)) {
        return true;
    }
    var re = /^\d+$/;
    return(re.test(val));
}

/** Check if a field is a float **/
function checkFloat(val) {
    if (isBlank(val)) {
        return true;
    }
    var re = /^\d*\.?\d*$/;
    return re.test(val);
}

/** Check if a field is a time value **/
function checkTime(val) {
    if (isBlank(val)) {
        return true;
    }
    var re = /^(1[0-2]|[1-9]):[0-5][0-9] [aApP][mM]$/;
    return(re.test(val));
}

/** Check if a field is a valid filename **/
function checkFilename(val) {
    if (val.indexOf('/') != -1) {
        return false;
    }
    return true;
}

/** Check if the field is alphanumeric **/
function checkAlphaNumeric(val) {
    var re = /[^a-zA-Z0-9]/;
    return !re.test( val );
}
