/*********************
 * VFC for javascript
 *
 *@copyright Varga, 2003
 *@author Varga
 *@version 2.00.20031016
 *@editors Varga, Tiplady
 *
 *
 * for explanation see the word document VFC.doc also available in this folder
 * you can use it for free, but don't remove the copyright
 *
 * revision history:
 *@revision 2005-03-08: _VrgCheckFields(): when the year was introduced only with 2 digits it will be expanded to 19xx
 *@revision 2005-12-26: (VP): A completely rebuild of all functions. now it differs between browsers which can handle document.all (IE) and which can't (FF). so all functions are now working properly
 *@revision 2006-11-09: (ST) Added 3 functions to simulate the php functions ltrim, rtrim and trim
 */

/**********************************/
function _VrgCheckFields (form_name)
/* *********************************
 * checks, if all NN fields have a value
 * it also checks, if the "date" fields has a valid date
 * if all checks are ok then return is true, otherwise false
 * if you have to make more checks, make them AFTER you called this function with return true,
 * so you can be sure, that you check valid data!
 * read VFC.doc for exact description
************************************/
{
    form_name = form_name.name;
    // check if we got a right formname
    if ( !(obj = _VrgIVO_form (form_name)) )
        return false;
    // get the number of the form items
    var elemente = obj.elements.length;

    var date_fields = new Array ();
    var idate_fields = 0;

    // prepare for
    // check every element's name, if it has to be proved
    for ( i = 0 ; i < elemente ; i++ ) {
        var fieldraw = obj.elements [i].name;
        if ( fieldraw.substr (0, 7) == '__ende__' )
            break;

        if ( !obj.elements [i].type )
           // no valid field
           continue;

        // either 'v' or 'f'
        var prefix = fieldraw.substr (0, 1);
        // check VFC.doc
        var suffix = fieldraw.substr (1, 1);

        if ( prefix == 'v' || prefix == 'f' ) {
            // a valid field

            if ( prefix != '_' ) {
                // get the fieldname without the prefix and suffix
                var fieldname = fieldraw.substr (2, fieldraw.length - 2);
            }   else {
                fieldname = fieldraw.substr (1, fieldraw.length - 1);
                suffix = 'n';
            }

            if ( prefix == 'v' ) {
                // check for date field
                if ( suffix.search ('[dmyDMY]') != -1 ) {
                    // make sure, that we look for all date fields - either upper case or lower case
                    // see for further information the documentation
                    if ( trim(obj.elements [i].value) == '' && suffix.search ('[dmy]') != -1 && _VrgModus != 'search' ) {
                        // date value not entered
                        switch (suffix) {
                            case 'd':
                                if ( __VrgIVO_gEBNo (obj, 'EnterDay') )
                                    alert (obj.EnterDay.value);
                                break;
                            case 'm':
                                if ( __VrgIVO_gEBNo (obj, 'EnterMonth') )
                                    alert (obj.EnterMonth.value);
                                break;
                            case 'y':
                                if ( __VrgIVO_gEBNo (obj, 'EnterYear') )
                                    alert (obj.EnterYear.value);
                                break;
                        }

                        obj.elements [i].focus ();
                        return false;
                    }
                    if ( suffix.search ('[dD]') != -1 ) {
                        // add the date field only at the first 'd' for each...
                        // for an easy differ I save if its an upper or lower suffix
                        date_fields [idate_fields++] = suffix.charAt (0) + fieldname;
                    }
                }
            }
            if ( suffix == 'n' && _VrgModus != 'search' ) {
                // check only NOT NULL fields...
                if ( trim(obj.elements [i].value) == '' ) {
                    // date value not entered
                    if ( __VrgIVO_gEBNo (obj, 'EnterValue') ) {
                        alert (obj.EnterValue.value);
                    }
                    obj.elements [i].value = '';
                    obj.elements [i].focus ();
                    obj.elements [i].style.border = "1px solid #000000";
                    return false;
                }
            }
        }
    }

    // once you reached this point, so you can be sure that all NOT NULL fields have a value
    // all date fields have also a value

    // now merge the date fields to one field
    for ( i = 0 ; i < idate_fields ; i++ ) {
        if ( !_VrgDateMerge (form_name, date_fields [i]) )
            return false;
    }

    return true;
}

function trim(str)
{
    for (i = 0; i < str.length; )
    {
        if ( str.charAt(i) == " " )
            str = str.substring( i + 1, str.length);
        else
            break;
    }

    for ( i = str.length - 1; i >= 0; i = str.length - 1)
    {
        if ( str.charAt(i) == " " )
            str = str.substring(0, i);
        else
            break;
    }

    return str;
}

/*******************************************/
function _VrgDateMerge (form_name, date_field)
/********************************************
 * merges a date field into the main 'fx' field
 * and checks also if the date is valid
 */
{
    // check if we got a right formname
    if ( !( obj = _VrgIVO_form (form_name)) )
        return false;

    if ( date_field.charAt (0) == 'd' ) {
        // the null and not null fields have to be merged...
        _s1 = 'vd';
        _s2 = 'vm';
        _s3 = 'vy';
    }    else {
        _s1 = 'vD';
        _s2 = 'vM';
        _s3 = 'vY';
    }
    date_field = date_field.substr (1);
    _s1 = _s1 + date_field;
    _s2 = _s2 + date_field;
    _s3 = _s3 + date_field;
    _s4 = 'fx' + date_field;
    if ( !document.getElementsByName (_s4)[0] ) {
        if ( !document.getElementsByName ('vx' + date_field)[0] ) {
            __VrgIVO_gEBN (_s4);
            return false;
        }
        _s4 = 'vx' + date_field;
    }

    // assure that all needed fields are available in the form..
    if ( !__VrgIVO_gEBNo (obj, 'InvalidDate') )
        return false;

    if ( !__VrgIVO_gEBN (_s1) || !__VrgIVO_gEBN (_s2) || !__VrgIVO_gEBN (_s3) || !__VrgIVO_gEBN (_s4) )
        return false;

    var day = document.getElementsByName (_s1)[0].value;
    var month = document.getElementsByName (_s2)[0].value;
    var year = document.getElementsByName (_s3)[0].value;
    var bDatumOK = true;

    if ( day == '' ) {
        document.getElementsByName (_s4)[0].value = 'NULL';
        return true;
    }

    if ( month == 2 && day > 28 )
        if ( year % 4 != 0 )
            bDatumOK = false;

    if ( day == 31 )
        if ( month % 2 == 0 && month != 8 && month != 10 && month != 12 )
            bDatumOK = false;

    if ( !bDatumOK ) {
        if ( __VrgIVO_gEBNo (obj, 'InvalidDate') ) {
            alert (obj.InvalidDate.value);
        }
        document.getElementsByName (_s1)[0].focus ();
        return false;
    }

    if ( day < 10 )
        day = '0' + day;
    if ( month < 10 )
        month = '0' + month;

    if ( year < 100 )
        year = '19' + year;

    // the date will be now set in this format: YYYY-MM-DD as a text; MySQL will do it right....
    document.getElementsByName (_s4)[0].value = year + '-' + month + '-' + day;
    return true;
}

var AktFieldbgColor;
var AktFieldColor;
var AktborderColor = "#868686";
var bChangeColor   = true;
var MarkBackground = "#E0E0E0";
var MarkColor      = "#000000";
var MarkBorder = "#000000";

/*************************/
function _VrgMarkField (id)
{
    if ( !bChangeColor )
        return;

    AktFieldbgColor = id.style.backgroundColor;
    AktborderColor  = id.style.borderColor;
    AktFieldColor   = id.style.color;

    id.style.backgroundColor = MarkBackground;
    id.style.borderColor = MarkBorder;
    id.style.color = MarkColor;
}

/**************************/
function _VrgResetField (id)
{
    if ( !bChangeColor )
        return;

    id.style.backgroundColor = AktFieldbgColor;
    id.style.borderColor = AktborderColor;
    id.style.color = AktFieldColor;
}

/***********************************/
function __VrgIVO_gEBN (object_name)
/*
 * Is Valid Object (requested by) getElementsByName
 *
 * internal function
 * checks, if the requested object by calling 'document.getElementsByName ()' will result in a valid object
 * is used to assure that a runtime access to an object won't result in a browser error
 * resulting in a very difficult conditions for the developr to fix this problem.
 * if the object is not a valid object, an alert occurs, where the name of the invalid
 * object will be prompted, so its much easier to find out where the problem is
 */
{
    var _tmp = document.getElementsByName (object_name)[0];

    if ( !_tmp )
        alert ('__VrgIVO_gEBN: invalid object "' + object_name + '"');

    return _tmp;
}

/**************************************************/
function __VrgIVO_gEBNo (object_handle, object_name)
/*
 * Is Valid Object (requested by) getElementsByName (for other) objects
 *
 * internal function
 * checks, if the requested object by calling 'getElementsByName ()' will result in a valid object
 * is used to assure that a runtime access to an object won't result in a browser error
 * resulting in a very difficult conditions for the developr to fix this problem
 * if the object is not a valid object, an alert occurs, where the name of the invalid
 * object will be prompted, so then its much easier to find out where the problem is
 */
{
    var i;

    for ( i = 0 ; i < object_handle.length ; i++ ) {
        if ( object_handle.elements [i].name == object_name ) {
            return true;
        }
    }
    alert ('__VrgIVO_gEBNo: object(' + object_handle.name + ').' + object_name + ' is invalid');
    return false;
}

/******************************/
function _VrgIVO_form (form_name)
/*******************************
 *
 * internal function to ensure that we got a valid form name
 *
 */
{
    // get the object handle to the form
    if ( document.all)
        _obj = document.all[form_name];
    else
        _obj = document.forms[form_name];

    // assure that its a valid one
    if ( !_obj ) {
        alert ('Invalid form "' + form_name + '"');
        return 0;
    }
    return _obj;
}

// the handle to the actual tool tip object
/*
 * this variables must be set before using VrgToolTip
 */
var ActToolTip = document.all;
var TT_pos_abs = 0;
var TT_posX = -50;
var TT_posY = 15;


/*********************************/
function _VrgShowToolTip (TT_id)
{
    // nothing, for compatibility reasons (mostly used in the backoffice) - should be substituted consequently by the new function
}

/************************/
function _VrgHideToolTip ()
{
    // nothing, for compatibility reasons (mostly used in the backoffice) - should be substituted consequently by the new function
}

/***************************/
function _VrgMarkChange (id)
{
    if ( id.name.substr (0, 2) == 'fs' )
        name = 'logc_' + id.name.substr (id.name.lastIndexOf ('__')+2);
    else
        name = 'logc_' + id.name.substr (3);
    document.getElementsByName(name)[0].value=true;
}

/******************************/
function _VrgFocus (form_name)
/*
 * this function checks also, if a duplicate key vialotion message should be prompted
 */
{
    if ( _DuplicateAlert ) {
        alert (_DuplicateAlert);
        _DuplicateAlert = '';
    }

    // check if we got a right formname
    if ( !(obj = _VrgIVO_form (form_name)) )
        return false;

    // get the number of the form items
    var elemente = obj.elements.length;
    for ( i = 0 ; i < elemente ; i++ ) {
        if ( obj.elements [i].type != 'hidden' ) {
            obj.elements [i].focus ();
            return true;
        }
    }
    return true;
}

////////////////////////////
function _ChkEMailAddress(s)
////////////////////////////
// from drweb.de
{
    var a = false;
    var res = false;
    if(typeof(RegExp) == 'function') {
        var b = new RegExp('abc');
        if(b.test('abc') == true){a = true;}
    }

    if(a == true) {
        reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+
                         '(\\@)([a-zA-Z0-9\\-\\.]+)'+
                         '(\\.)([a-zA-Z]{2,4})$');
        res = (reg.test(s));
    } else {
        res = (s.search('@') >= 1 &&
               s.lastIndexOf('.') > s.search('@') &&
               s.lastIndexOf('.') >= s.length-5)
    }
    return(res);
}

/////////////////////////////////////
function _VrgChkIBAN(iban, error_msg)
/////////////////////////////////////
// this function require the checkibank.js
// the error message must be provided as well because its not a PHP script...
{
    tmp_iban = '';
    orig_iban = iban;
    for ( i = 0 ; i < orig_iban.length ; i++ ) {
        c = orig_iban.charCodeAt(i);
        if ( c != 0x20 && c != 0x2d  )
            tmp_iban = tmp_iban + String.fromCharCode(c);
    }

    if ( checkiban(tmp_iban) == 0x4321 ) {
        alert(error_msg);
        return false;
    }
    return true;
}

/* from the phpMyAdmin project - thank you */
/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */


function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;
    var firefox = false;
    if ( navigator.userAgent.indexOf("Firefox") != -1 )
        firefox = true;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"

    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined'
        && !firefox ) {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if ( domDetect && !firefox ) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


// Removes leading whitespaces
function LTrim( value ) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) {
    return LTrim(RTrim(value));
}