//  --------------------------------------
//  Purpose : Trims all fields passed in
//  Usage   : Pass in a set of text fields
//  --------------------------------------
function trimField( listOfFields )
{
    for ( var iField = 0; iField < arguments.length; iField++ )
    {
        var oThisField      = arguments[iField];
        var sFieldValue     = oThisField.value;
        if (sFieldValue != '')
        {
            var reStartSpaces   = /^ */;
            var reEndSpaces     = / *$/;
            sFieldValue         = sFieldValue.replace( reStartSpaces, '' );
            sFieldValue         = sFieldValue.replace( reEndSpaces, '' );
            oThisField.value    = sFieldValue;
        }
    }
}


//  ------------------------------------------------------------------
//  Purpose : Trims all fields in a form
//  Usage   : Removes whitespace from front and end of all text fields
//  ------------------------------------------------------------------
function trimAll( oForm )
{
    for ( iElem = 0; iElem < oForm.length; iElem++ )
    {
        var oThisElem   = oForm[iElem];
        var sFieldType  = getFieldType( oThisElem );

        if ( sFieldType == 'file' || sFieldType == 'password' || sFieldType == 'text' || sFieldType == 'textarea' )
            trimField( oThisElem );
    }
}


//  ------------------------------------------------------------------------------------
//  Purpose : Checks a postcode text-input against a preset mask for validity
//  Usage   : Pass in field and field 'label' to get back a comma-prefixed error message
//  ------------------------------------------------------------------------------------
function checkPostcode( oField, sFieldDesc )
{
    var sNewError       = '';
    var reValidPostcode = /[A-Z]{1,2}\d{1,2}[A-Z]? {1}\d[A-Z]{2}/;   // 1-2 LETTERS, 1-2 NUMBERS, optional LETTER, a SPACE, a NUMBER, 2 LETTERS
    if (oField.value != '' && !reValidPostcode.test(oField.value.toUpperCase()))
        sNewError   = ',"' +sFieldDesc+ '" contains an invalid postcode';
    return sNewError;
}

function postcodeHelp()
{
    alert('Postcodes must be entered in standard postcode format\n\n1-2 LETTERS\n1-2 NUMBERS\noptional LETTER\na SPACE\na NUMBER\n2 LETTERS\n\nExamples:\n\n\'W1N 4DJ\'\n\'BS34 1RE\'\n\'L15 3FT\'');
}


//  ------------------------------------------------------------------------------------
//  Purpose : Checks a phone number text-input against a preset mask for validity
//  Usage   : Pass in field and field 'label' to get back a comma-prefixed error message
//  ------------------------------------------------------------------------------------
function checkPhone( oField, sFieldDesc )
{
    var sNewError       = '';
    var reValidPhone    = /0\d{3,4} ?\d{5,8}/;   // a ZERO, 3-4 NUMBERS, an optional SPACE, 5-8 NUMBERS
    if (oField.value != '' && !reValidPhone.test(oField.value))
        sNewError   = ',"' +sFieldDesc+ '" contains an invalid phone number';
    return sNewError;
}

function phoneHelp()
{
    alert('Phone numbers must be entered using the following format\n\nA ZERO\n3-4 NUMBERS\nan optional SPACE\n5-8 NUMBERS\n\nExamples:\n\n\'01234 567890\'\n\'0208 1234567\'\n\'020 87654321\'\n\'07970 123456\'\n\'01234567890\'');
}


//  ------------------------------------------------------------------------------------
//  Purpose : Checks an email address text-input against a preset mask for validity
//  Usage   : Pass in field and field 'label' to get back a comma-prefixed error message
//  ------------------------------------------------------------------------------------
function checkEmail( oField, sFieldDesc )
{
    var sNewError       = '';
    var reValidEmail    = /^[a-zA-Z0-9_!#$%&'*+\-\/=?^`{.|}~\\]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/;
    if (oField.value != '' && !reValidEmail.test(oField.value))
        sNewError  = ',"' +sFieldDesc+ '" contains an invalid email address';
    return sNewError;
}

function emailHelp()
{
    alert('Email addresses must be entered using the following format\n\nuser@domain\n\nExamples:\n\n\'test@promap.co.uk\'\n\'fred.bloggs@myemail.com\'');
}


//  -----------------------------------------------------------------------------------------------------------------------
//  Purpose : Checks for length errors in text-inputs
//  Usage   : Pass in field, field 'label' and minimum and maximum length values to get back a comma-prefixed error message
//  -----------------------------------------------------------------------------------------------------------------------
function checkLength( oField, sFieldDesc, iMin, iMax )
{
    var sNewError   = '';
    if (oField.value.length < iMin)
    {
        sNewError  = (iMin != 1) ? ',"' +sFieldDesc+ '" cannot be less than ' +iMin+ ' characters in length' : ',"' +sFieldDesc+ '" cannot be blank';
    }
    else if (oField.value.length > iMax && iMax != -1)
    {
        sNewError  = ',"' +sFieldDesc+ '" cannot be greater than ' +iMax+ ' characters in length';
    }

    return sNewError;
}


//  ------------------------------------------------------------------------------------
//  Purpose : Checks for any value in a text-input
//  Usage   : Pass in field and field 'label' to get back a comma-prefixed error message
//  ------------------------------------------------------------------------------------
function checkMandatory( oField, sFieldDesc )
{
    if ( getFieldType(oField) == 'radio' || getFieldType(oField) == 'checkbox' )
    {
        return checkNotEmpty( oField, sFieldDesc );
    }
    else
    {
        return checkLength( oField, sFieldDesc, 1, -1 );
    }
}


//  ------------------------------------------------------------------------------------
//  Purpose : Checks for at least one value in radiobuttons and checkboxes
//  Usage   : Pass in field and field 'label' to get back a comma-prefixed error message
//  ------------------------------------------------------------------------------------
function checkNotEmpty( oField, sFieldDesc )
{
    var sNewError   = '';

    if ( getFieldValue(oField) == '' )
        sNewError  = ',"' +sFieldDesc+ '" must have at least one value selected';

    return sNewError;
}


//  ----------------------------------------------------------------------------------------------
//  Purpose : Checks that a field matches another one (useful for confirmation of passwords)
//  Usage   : Pass in the two fields and field 'labels' to get back a comma-prefixed error message
//  ----------------------------------------------------------------------------------------------
function checkSame( oField1, oField2, sFieldDesc1, sFieldDesc2 )
{
    var sNewError   = '';

    if ( getFieldValue(oField1) != getFieldValue(oField2) )
        sNewError  = ',"' +sFieldDesc1+ '" does not match "' + sFieldDesc2 + '"';

    return sNewError;
}


//  -------------------------------------------------------------------------------------------------------------------------------
//  Purpose : Prevents illegal keypresses
//  Usage   : onKeyPress="return allowKeyPress('L');" would allow only letters to be entered in this field when set on a text input
//  -------------------------------------------------------------------------------------------------------------------------------
function allowKeyPress( sAllowedCharacterset )
{
    var iKeyCode            = event.keyCode;
    var aAllowedCharacters  = new Array();
    var bCharacterAllowed   = false;

    var lowercase           = [97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,216,217,218,219,220,221,222]
    var uppercase           = [65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,248,249,250,251,252,253,254,255]
    var digits              = [48,49,50,51,52,53,54,55,56,57]
    var enter               = [13]
    var whitespace          = [32]
    var punctuation         = [33,39,40,41,44,45,46,47,58,59,63]
    var searchid            = [45]

    if (sAllowedCharacterset.indexOf('a') != -1) aAllowedCharacters = aAllowedCharacters.concat(lowercase);
    if (sAllowedCharacterset.indexOf('A') != -1) aAllowedCharacters = aAllowedCharacters.concat(uppercase);
    if (sAllowedCharacterset.indexOf('9') != -1) aAllowedCharacters = aAllowedCharacters.concat(digits);
    if (sAllowedCharacterset.indexOf('E') != -1) aAllowedCharacters = aAllowedCharacters.concat(enter);
    if (sAllowedCharacterset.indexOf('W') != -1) aAllowedCharacters = aAllowedCharacters.concat(whitespace);
    if (sAllowedCharacterset.indexOf('P') != -1) aAllowedCharacters = aAllowedCharacters.concat(punctuation);
    if (sAllowedCharacterset.indexOf('S') != -1) aAllowedCharacters = aAllowedCharacters.concat(searchid);
    if (sAllowedCharacterset.indexOf('L') != -1)
    {
        aAllowedCharacters = aAllowedCharacters.concat(lowercase);
        aAllowedCharacters = aAllowedCharacters.concat(uppercase);
    }

    for (i=0; i<aAllowedCharacters.length; i++)
        if (iKeyCode == aAllowedCharacters[i]) bCharacterAllowed = true;

    if (!bCharacterAllowed)
    {
        window.defaultStatus    = 'Character not permitted in this field!!';
        window.setTimeout( function() { window.defaultStatus='' }, 2000 );
        event.returnValue = false;
    }

}


//  --------------------------------------
//  Purpose : Get the type of form element
//  Usage   : Utility Function
//  --------------------------------------
function getFieldType( oField )
{
    //  ------------------------------------------------------------------
    //  Possible return values are ...
    //
    //  "button", "checkbox", "file", "hidden", "password"
    //  "radio", "reset", "select" (covers select-one and select-multiple)
    //  "submit", "text", "textarea"
    //
    //  Can also return "invalid" if field passed in is not an object
    //  ------------------------------------------------------------------

    var sFieldType  = false;

    if ( typeof oField == 'undefined' )
        return 'invalid';

    sFieldType  = ( typeof oField.type == 'undefined' ) ? oField[0].type : oField.type;

    if (sFieldType.indexOf('select') != -1)
        sFieldType = 'select';

    return sFieldType;
}


//  -----------------------------------------
//  Purpose : Get the value of a form element
//  Usage   : Utility Function
//  -----------------------------------------
function getFieldValue( oField )
{
    if (typeof oField != 'object')
        oField  = document.getElementById(oField);
    if (typeof oField != 'object')
        return '';                                  // Return empty string if unable to get object from either argument or by using getElementById

    var sFieldType  = getFieldType(oField);
    var sFieldValue = '';

    if (sFieldType == 'checkbox')
    {
        for ( iCheckBox = 0; iCheckBox < oField.length; iCheckBox++ )
        {
            if ( oField[iCheckBox].checked )
                sFieldValue = ( sFieldValue.length > 0 ) ? sFieldValue + '|' + oField[iCheckBox].value : oField[iCheckBox].value;
        }
    }
    else if (sFieldType == 'radio')
    {
        for ( iRadioButton = 0; iRadioButton < oField.length; iRadioButton++ )
        {
            if ( oField[iRadioButton].checked )
                sFieldValue = oField[iRadioButton].value;
        }
    }
    else if ( sFieldType == 'select' )
    {
        if ( oField.options.length > 0 && oField.selectedIndex != -1)
            sFieldValue = oField.options[oField.selectedIndex].value;
    }
    else if ( sFieldType != 'invalid' )
    {
        sFieldValue = oField.value;
    }

    return sFieldValue;
}

//  ----------------------------------------------------
//  Check to see if user has entered a string containing
//  characters problematic for us - returns boolean.
//  ----------------------------------------------------
function isLegalPromapInput( sInputString, bBackslashOmitted )
{
    if ( arguments.length == 1 )
    {
        var re = /[¦"%&+#\\]+/;
        return !re.test( sInputString );
    }
    if ( arguments.length == 2 )
    {
        var re = /[¦"%&+#]+/;
        return !re.test( sInputString );
    }
}
// Read the tin...
function illegalInputAlert( bBackslashOmitted )
{
    if ( arguments.length == 0 )
    {
        alert('You cannot use any of the following characters in this field:\n\n                            ¦ " % & + # \\');
    }
    if ( arguments.length == 1 )
    {
        alert('You cannot use any of the following characters in this field:\n\n                             ¦ " % & + # ');
    }
}

function isLegalEnvirocheckInput( sInputString )
{
    if ( arguments.length == 1 )
    {
        var re = /[¦"%+#\\]+/;
        return !re.test( sInputString );
    }
}

//  ----------------------------------------------------------------------------------
//  Strip the carriage returns/new lines from a string and returns the modified string
//  ----------------------------------------------------------------------------------

function removeCarriageReturns( sString )
{
    var re = /\r\n/g;
    return sString.replace( re, '' );
}