// ----------------------------------------------------------------------------
//       File Name: enduser.js
//       Subsystem: enduser
//   Document Type: Javascript include file
//         Purpose: contains all non-page specific enduser page Javascript
// ----------------------------------------------------------------------------
var inside_check_mask = 0;

function utf8_len(str)
{
    var i, sz, len = 0;

    for (i = 0, sz = str.length; i < sz; i++) 
        if (str.charCodeAt(i) < 0x0080)
            len += 1;
        else if (str.charCodeAt(i) < 0x0800)
            len += 2;
        else
            len += 3;

    return(len);
}

// ----------------------------------------------------------------------------

function utf8_excess_chars(str, maxlen)
{
    var i, sz, len = 0; excess = 0;

    for (i = 0, sz = str.length; i < sz; i++)
    {
        if (str.charCodeAt(i) < 0x0080)
            len += 1;
        else if (str.charCodeAt(i) < 0x0800)
            len += 2;
        else
            len += 3;

        if (len > maxlen)
            excess += 1;
    }

    return(excess);
}

// ----------------------------------------------------------------------------

function is_furigana_string(str)
{
    var i, sz, c;

    for (i = 0, sz = str.length; i < sz; i++)
    {
        c = str.charCodeAt(i);

        if ((c >= 0x3041  &&  c <= 0x309E) || // hiragana
            (c >= 0x30A1  &&  c <= 0x30FE) || // full-width katakana
            (c == 0x2212) || (c == 0x2025) || // full-width hyphens
            (c == 0xFF0E) || (c == 0x0020) || // nakaguro, ' '
            (c >= 0x0030  &&  c <= 0x0039) || // '0' - '9'
            (c >= 0x0041  &&  c <= 0x005A) || // 'A' - 'Z'
            (c >= 0x0061  &&  c <= 0x007A) || // 'a' - 'z'
            (c == 0x0028) || (c == 0x0029) || // '('   ')'
            (c == 0x002C) || (c == 0x002E) || // ','   '.'
            (c == 0x0026) || (c == 0x002D) || // '&'   '-'
            (c == 0xFF0D) || (c == 0xFF06) || // full-width hypen and ampersand
            (c == 0xFF08) || (c == 0xFF09) || // full-width parenthesis
            (c == 0x3000))                    // full-width space
            continue;

        return(false);
    }

    return(true);
}

// ----------------------------------------------------------------------------

function submenu(code, items)
{
    this.code  = code;
    this.items = items;
}

// ----------------------------------------------------------------------------

function subitem(code, name)
{
    this.code = code;
    this.name = name;
}

// ----------------------------------------------------------------------------

function field_data(int_msg, reqd_msg, not_complete_msg, oversz_msg,
                    ascii_msg, email_msg, furigana_msg, 
                    too_few_options_msg, too_many_options_msg,
                    mon_lbl, day_lbl, yr_lbl, hr_lbl, min_lbl,
                    email_expr, date_order, no_html_msg, pos_int_msg,
                    fld_too_mny_chars_msg, must_cont_valid_format_char_msg,                    
                    not_valid_format_char_msg, must_cont_valid_num_msg,
                    not_valid_num_msg, must_cont_valid_alphanum_msg,
                    not_valid_alphanum_msg, must_cont_valid_letter_msg,
                    not_valid_letter_msg, must_cont_valid_char_msg,
                    not_valid_char_msg, corr_fmt_is_msg)
{
    this.int_msg                           = int_msg;
    this.reqd_msg                          = reqd_msg;
    this.not_complete_msg                  = not_complete_msg;
    this.oversz_msg                        = oversz_msg;
    this.ascii_msg                         = ascii_msg;
    this.email_msg                         = email_msg;
    this.furigana_msg                      = furigana_msg;
    this.no_html_msg                       = no_html_msg;    
    this.pos_int_msg                       = pos_int_msg;
    this.fld_too_mny_chars_msg             = fld_too_mny_chars_msg;
    this.must_cont_valid_format_char_msg   = must_cont_valid_format_char_msg;
    this.not_valid_format_char_msg         = not_valid_format_char_msg;
    this.must_cont_valid_num_msg           = must_cont_valid_num_msg;
    this.not_valid_num_msg                 = not_valid_num_msg;
    this.must_cont_valid_alphanum_msg      = must_cont_valid_alphanum_msg;
    this.not_valid_alphanum_msg            = not_valid_alphanum_msg;
    this.must_cont_valid_letter_msg        = must_cont_valid_letter_msg;
    this.not_valid_letter_msg              = not_valid_letter_msg;
    this.must_cont_valid_char_msg          = must_cont_valid_char_msg;
    this.not_valid_char_msg                = not_valid_char_msg;
    this.corr_fmt_is_msg                   = corr_fmt_is_msg;
    this.too_few_options_msg               = too_few_options_msg;
    this.too_many_options_msg              = too_many_options_msg;


    // can't do a cfg_get in javascript, so store it in a javascript variable
    switch (date_order) 
    {
    case 0: // American
        this.dt_lbl     = new Array(mon_lbl, day_lbl, yr_lbl, hr_lbl, min_lbl);
        this.dt_sfx     = new Array('_mon', '_day', '_yr');
        break;
    case 1: // Japanese
        this.dt_lbl     = new Array(yr_lbl, mon_lbl, day_lbl, hr_lbl, min_lbl);
        this.dt_sfx     = new Array('_yr', '_mon', '_day');
        break;
    case 2: // European
        this.dt_lbl     = new Array(day_lbl, mon_lbl, yr_lbl, hr_lbl, min_lbl);
        this.dt_sfx     = new Array('_day', '_mon', '_yr');
        break;
    }

    email_expr = email_expr.replace(/^\s+|\s$/g,''); // trim any return characters or whitespace
    this.email_expr = new RegExp(email_expr ? email_expr : '.*');
}

// ----------------------------------------------------------------------------

function field(name, label, type, maxlen, flags)
{
    this.name   = name;
    this.label  = label;
    this.type   = type;
    this.maxlen = maxlen;

    // flags is a bitmask:
    //  0x0001  required
    //  0x0002  ascii only
    //  0x0004  must match email pattern
    //  0x0008  cannot contain HTML
    //  0x0010  valid furigana characters only
    //  0x0020  cannot contain < >
    //  0x0040  int must be greater than 0
    //  0x0080  field is a checkbox (unselected value doesn't show in post params)
    this.flags  = flags;
}

// ----------------------------------------------------------------------------

function _upd_submenu(menu, submenu, submenu_data, all_str)
{
    var i, j = 1, sz;

    submenu.length = 0;

    submenu.options[0]       = new Option();
    submenu.options[0].text  = all_str;
    submenu.options[0].value = '';

    for (i = 0, sz = submenu_data.length; i < sz; i++)
        if (submenu_data[i].code == menu.options[menu.selectedIndex].value)
        {
            for ( ; j <= submenu_data[i].items.length; j++)
            {
                submenu.options[j]       = new Option();
                submenu.options[j].text  = submenu_data[i].items[j-1].name;
                submenu.options[j].value = submenu_data[i].items[j-1].code;
            }

            break;
        }

    submenu.length        = j;
    submenu.selectedIndex = 0;
}

// ----------------------------------------------------------------------------

function _alp_onload(page, gridsort)
{
    if (document.grid)
    {
        if (document.grid.p_page)
            document.grid.p_page.selectedIndex = page - 1;
        if (document.grid.p_gridsort)
            document.grid.p_gridsort.value = gridsort;
    }
}

// ----------------------------------------------------------------------------

function _adp_print(url)
{
    window.open(url, 'print_answer', 'resizable,menubar,toolbar,scrollbars');
}

// ----------------------------------------------------------------------------

function _adp_email(url)
{
    window.open(url, 'email_answer', 'resizable,width=700,height=392');
}

// ----------------------------------------------------------------------------
// CDT_DATE and CDT_DATETIME components are processed as individual CDT_MENU
// fields

function _check_fields(form_name, fld_data, fields)
{
    var fld, i, j, numSet, str;
    var ws_exp      = new RegExp("(^\\s+|\\s*$)", "g");
    var strtok_exp  = new RegExp("%s");
    var numtok_exp  = new RegExp("%d");
    var valid_ascii = new RegExp("^[\x20-\x7e]+$");
    var no_html     = new RegExp("[<>]");
    
    with (fld_data) for (i = 0; (i < fields.length) && fields[i].type; i++)
    {
        if ((fields[i].type != 4) && (fields[i].type != 7))
            fld = eval('document.'+form_name+'.'+fields[i].name);

        switch (fields[i].type)
        {
            case 1: // CDT_MENU
                if ((fields[i].flags & 1) &&
                    (fld.length > 1) && (fld.selectedIndex < 1))
                {
                    alert('\''+fields[i].label+'\' '+reqd_msg);
                    fld.focus();
                    return(false);
                }
                break;

            case 2: // CDT_BOOL
            case 8: // CDT_OPT_IN
                if ((fields[i].flags & 1) &&
                    !fld[0].checked && !fld[1].checked)
                {
                    alert('\''+fields[i].label+'\' '+reqd_msg);
                    fld[0].focus();
                    return(false);
                }
                break;

            case 3: // CDT_INT
                fld.value = fld.value.replace(ws_exp, '');
                if (fld.value.length && isNaN(fld.value))
                {
                    alert('\''+fields[i].label+'\' '+int_msg);
                    fld.focus();
                    return(false);
                }
                if (fields[i].flags & 0x40 && fld.value < 0)
                {
                    alert('\''+fields[i].label+'\' '+pos_int_msg);
                    fld.focus();
                    return(false);                     
                }

                // deliberate drop through

            case 5: // CDT_VARCHAR
                if (fields[i].maxlen && (fields[i].maxlen < fld.value.length))
                {
                    str = oversz_msg.replace(strtok_exp, fields[i].label);
                    str = str.replace(numtok_exp, fields[i].maxlen);
                    str = str.replace(numtok_exp,
                                      fld.value.length - fields[i].maxlen);

                    alert(str);
                    fld.focus();
                    return(false);
                }
            case 6: // CDT_MEMO
                if ((fields[i].type == 6) && fields[i].maxlen && (fields[i].maxlen < utf8_len(fld.value)))
                {
                    var extra;
                    var rough_mbcs = parseInt(utf8_len(fld.value) / (fld.value.length));
                    if(utf8_len(fld.value) % (fld.value.length) != 0)
                        rough_mbcs++;
                    str = oversz_msg.replace(strtok_exp, fields[i].label);
                    str = str.replace(numtok_exp, parseInt(fields[i].maxlen/rough_mbcs));
                    extra = parseInt((utf8_len(fld.value) - fields[i].maxlen)/rough_mbcs);
                    if((utf8_len(fld.value) - fields[i].maxlen) % (rough_mbcs) != 0)
                        extra++;
                    str = str.replace(numtok_exp, extra);

                    alert(str);
                    fld.focus();
                    return(false);
                }

                if (fields[i].type != 3)
                    fld.value = fld.value.replace(ws_exp, '');

                if ((fields[i].flags & 1) && (fld.value.length == 0))
                {
                    alert('\''+fields[i].label+'\' '+reqd_msg);
                    fld.focus();
                    return(false);
                }

                // if not required and not set, don't do checks
                if ((fld.value.length == 0))
                    break;

                if ((fields[i].flags & 2) && !valid_ascii.test(fld.value))
                {
                    alert('\''+fields[i].label+'\' '+ascii_msg);
                    fld.focus();
                    return(false);
                }

                if ((fields[i].flags & 4) && !email_expr.test(fld.value))
                {
                    alert('\''+fields[i].label+'\' '+email_msg);
                    fld.focus();
                    return(false);
                }

                if ((fields[i].flags & 0x10) && !is_furigana_string(fld.value))
                {
                    alert('\''+fields[i].label+'\' '+furigana_msg);
                    fld.focus();
                    return(false);
                }
                
                if (fields[i].flags & 0x20 && no_html.test(fld.value))
                {
                    alert('\''+fields[i].label+'\' '+ no_html_msg);
                    fld.focus();
                    return(false);
                }
                
                break;


            case 4: // CDT_DATETIME
            case 7: // CDT_DATE
                fld = new Array();

                fld[0] = eval('document.'+form_name+'.'+fields[i].name+dt_sfx[0]);
                fld[1] = eval('document.'+form_name+'.'+fields[i].name+dt_sfx[1]);
                fld[2] = eval('document.'+form_name+'.'+fields[i].name+dt_sfx[2]);

                if (fields[i].type == 4)
                {
                    fld[3] = eval('document.'+form_name+'.'+fields[i].name+'_hr');
                    fld[4] = eval('document.'+form_name+'.'+fields[i].name+'_min');
                }

                if (!(fields[i].flags & 1))  // not required
                {
                    for (j = numSet = 0; j < fld.length; j++)
                        numSet += (fld[j].selectedIndex > 0) ? 1 : 0;

                    if ((numSet > 0) && (numSet != fld.length))
                    {
                        // field is only partially filled out
                        alert('\''+fields[i].label+'\' '+not_complete_msg);
                        fld[0].focus();
                        return(false);
                    }

                    break;
                }

                for (j = 0; j < fld.length; j++)
                    if ((fld[j].selectedIndex < 1))
                    {
                        alert('\''+fields[i].label+' ('+dt_lbl[j]+')\' '+reqd_msg);
                        fld[j].focus();
                        return(false);
                    }

                break;
        }
    }

    return(true);
}

// ----------------------------------------------------------------------------

function _validate_acctinfo(userid, passwd1, passwd2, min_passwd_len, msgs)
{
    var msg = -1, fld;

    if (userid.value.indexOf(' ') != -1)
         msg = 0, fld = userid;

    if (userid.value.indexOf('\"') != -1)
         msg = 1, fld = userid;

    if (passwd1 && (passwd1.value != passwd2.value))
         msg = 2, fld = passwd1;

    if (passwd1 && (passwd1.value.length < min_passwd_len))
        msg = 3, fld = passwd1;

    if (msg != -1)
    {
        alert(msgs[msg]);
        fld.focus();
        fld.select();
        return(false);
    }

    return(true);
}

// ----------------------------------------------------------------------------

var cursor_set = false;

function _set_cursor()
{
    var i, j;

    if (cursor_set)
        return;

    cursor_set = true;

    if (document.location.href.indexOf('#') > -1)
        return;

    for (i = 0; i < document.forms.length; i++)
        for (j = 0; j < document.forms[i].length; j++)
           with (document.forms[i])
               if (elements[j].type && ((elements[j].type == 'text') || (elements[j].type == 'textarea')))
               {
                   elements[j].focus();
                   if (elements[j].value.length)
                       elements[j].select();
                   return;
               }
}

// ----------------------------------------------------------------------------
 
function check_mask(mask_fld)
{
    var i, ln, js_msg = '';
    var val = '', code = '', echar = '', fchar = '';

    inside_check_mask = 1;

    if (mask_fld.value == eval(mask_fld.name+'_dmask'))
    {
        inside_check_mask = 0;
        return;
    }

    if (eval(mask_fld.name + '_emask.length') < mask_fld.value.length)
        js_msg = fld_data.fld_too_mny_chars_msg;
    else        
        for (i = 0, ln = eval(mask_fld.name + '_emask.length'); i < ln; i++)
        {

            val = mask_fld.value.charAt(i);
            code = mask_fld.value.charCodeAt(i);
            echar = eval(mask_fld.name + '_emask.charAt(i)');
            fchar = eval(mask_fld.name + '_fstr.charAt(i)');

            if (fchar == 'F' && val != echar)
            {
                if (val == ' ')
                    js_msg = fld_data.must_cont_valid_format_char_msg;
                else
                    js_msg = val + ' ' + fld_data.not_valid_format_char_msg;
                break;
            }    
            else if ((echar == '#') &&
                (!((code >= 48) && (code <= 57))))
            {
                if (val == '')
                    js_msg = fld_data.must_cont_valid_num_msg;
                else
                    js_msg = val + ' ' + fld_data.not_valid_num_msg;
                break;
            }
            else if ((echar == 'A') &&
                    (!(((code >= 48) && (code <= 57)) || 
                      ((code >= 65) && (code <= 90)) ||
                      ((code >= 97) && (code <= 122)))))
            {
                if (val == '')
                    js_msg = fld_data.must_cont_valid_alphanum_msg;
                else            
                    js_msg = val + ' ' + fld_data.not_valid_alphanum_msg;
                break;
            }
            else if ((echar == 'L') &&
                    (!(((code >= 65) && (code <= 90)) || 
                      ((code >= 97) && (code <= 122)))))
            {
                if (val == '')
                    js_msg = fld_data.must_cont_valid_letter_msg;
                else
                    js_msg = val + ' ' + fld_data.not_valid_letter_msg;
                break;
            }
            else if ((echar == 'C') &&
                    (!(((code >= 32) && (code <= 126)) || 
                     ((code >= 128) && (code <= 255)))))
            {
                if (val == '')
                    js_msg = fld_data.must_cont_valid_char_msg;
                else
                    js_msg = val + ' ' + fld_data.not_valid_char_msg;
                break;
            }
            
            // ensure letters are propper case
            if (echar == 'L')
            {
                if (fchar == 'U')
                {
                    mask_fld.value = mask_fld.value.substring(0, i) +
                                     mask_fld.value.charAt(i).toUpperCase() +
                                     mask_fld.value.substring(i + 1);
                }
                else if (fchar == 'L')
                {
                    mask_fld.value = mask_fld.value.substring(0, i) +
                                     mask_fld.value.charAt(i).toLowerCase() +
                                     mask_fld.value.substring(i + 1);
                }
            }
        }
    
    if (js_msg)
    {
        alert(js_msg + ' ' + fld_data.corr_fmt_is_msg + ' ' + eval(mask_fld.name+'_dmask')+ '.');
        mask_fld.focus();
        inside_check_mask = 0;
        return(false);
    }
    inside_check_mask = 0;
    return(true);
}

// ----------------------------------------------------------------------------

function put_mask(mask_fld, val, formelm, nn)
{
    var mtmp = '', ftmp = '', dtmp = '';
    var i, sl;   

    for (i = 0, sl = val.length; i < sl; i++)
    {
        ftmp += val.charAt(i);

        if (val.charAt(i) == 'F')
            dtmp += val.charAt(i+1);
        else
            dtmp += (val.charAt(i+1) == '#') ? '#' : '@';

        mtmp += val.charAt(++i);

    }
    if (!nn)  
        eval("document.getElementById('"+mask_fld+"_mask').innerHTML='"+dtmp+"'");

    eval(mask_fld + '_fstr = ftmp');
    eval(mask_fld + '_emask = mtmp');
    eval(mask_fld + '_dmask = dtmp');

}

// ----------------------------------------------------------------------------

function answer_window_preview(ansid, created)
{
    var agt=navigator.userAgent.toLowerCase();
    var is_major = parseInt(navigator.appVersion);
    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
        && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
        && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    var query_str = location.search.substring(1);
    var pairs = query_str.split('&');
    var args = new Object( );
    var pos = 0;
    var argname = '';
    var value = '';
    var i = 0;

    for (i = 0; i < pairs.length; i++)
    {
        pos = pairs[i].indexOf('=');
        if (pos == -1)
            continue;
        argname = pairs[i].substring(0, pos);
        value = pairs[i].substring(pos + 1);
        args[argname] = unescape( value );
    } // end for i loop

    // Check browser version numbers.
    // Netscape version 6+ uses is_major == 5, previous versions < 5
    if(is_nav && (is_major < 5))
    {
        h_size = top.innerWidth;
        v_size = top.innerHeight;
    }
    // Netscape version 6+
    else if(is_nav && (is_major < 7))
    {
        h_size = document.body.offsetWidth;
        v_size = document.body.offsetHeight;
    }
    // All others (including IE)
    else
    {
        h_size = document.body.clientWidth;
        v_size = document.body.clientHeight;
    }

    h_size -= 20;
    v_size = Math.floor(v_size * 0.8);

    if (v_size < 200)
        v_size = 200;

    window.open('popup_adp.php?p_sid=' + args.p_sid + '&p_lva=' + args.p_lva +
                '&p_li=' + args.p_li + '&p_faqid=' + ansid + '&p_created=' +
                created + '&p_sp=' + args.p_sp, 'suggested_answer',
                'scrollbars,resizable,toolbar,menubar,width=' + h_size +
                ',height=' + v_size);
}

// ----------------------------------------------------------------------------
function check_valid_ascii(fld, valid_ascii_msg)
{
    var valid_ascii = new RegExp("^[\x0a\x0d\x20-\x7e]+$");
    if (fld.value.length > 0 && valid_ascii.test(fld.value) == false)
    {
        alert(valid_ascii_msg);
        fld.focus();
    }
}

// ksingleton@rightnow.com Sep-2007 above is default 8.0.2, below is custom 
// ---------------------------------------------------------------------------
function openASAWindow(page,name,width,height)
    {
        var win = window.open(page,name, "resizable=0,scrollbars=0,width=" + width + ",height=" + height + ",toolbar=no,menubar=no,status=no");
        win.focus();
    }

/* Start of Customization for validations using AFD Tool */

var alertLanguage = ((navigator.systemLanguage)?((navigator.systemLanguage.indexOf("de")>=0)?("de"):((navigator.userLanguage)?((navigator.userLanguage.indexOf("de")>=0)?("de"):("en")):("en"))):((navigator.language)?((navigator.language.indexOf("de")>=0)?("de"):("en")):("en")));

String.prototype.trim = function()
{
  return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}
// returns true if the field contains any value and false if the field contains null
function fn_PerformMandatoryCheck(fieldValue, fieldLabel, fieldName , fieldType){
    var ls_Mandatory = "true";
    var la_Result ="true";
    if (fieldType.toLowerCase() == "checkbox") 
    {
        if (fieldValue == "false")
            {
              alert("Please select a value for '" + fieldLabel+"'");
            la_Result = "false";    
            }
    }
    if (fieldValue == ""){
        if (fieldType.toLowerCase() == "text") {
          alert("Please enter a value for '" + fieldLabel+"'");
        } else {
              alert("Please select a value for '" + fieldLabel+"'");
        }
//      document._afd_submit.setAttribute('autocomplete','off');
//      setTimeout("document._afd_submit."+fieldName+".focus();",0);
//      eval("document.getElementById('" + fieldName + "').select()");
        if (fieldType.toLowerCase() == "text"||fieldType.toLowerCase() == "menu"||fieldType.toLowerCase() == "radio") 
        {
        eval("document.getElementById('" + fieldName + "').focus()");
        }
        la_Result = "false";
    }
    return la_Result;
}

function fn_PerformConditionalCheck(fieldValue, fieldLabel, fieldName , fieldType){
   var ls_Mandatory = "true";
   var la_Result ="true";
   var depFieldName = "";
   var depFieldType = "";
   var depFieldValue = "";

   if (fieldName == "afd_call_time") {
        depField = "afd_contact_preference";
        depFieldType = "checkbox";
        depFieldValue = GetFieldValue(depFieldType, depField)

    if (fieldValue == "" && depFieldValue == "") {
        if (fieldType.toLowerCase() == "text") {
          alert("Please enter a value for '" + fieldLabel+"'");
        } else {
              alert("Please select a value for '" + fieldLabel+"'");
        }
        //document._afd_submit.setAttribute('autocomplete','off');

        //alert("Please enter a value for '" + fieldLabel + "'");
        //eval("document.getElementById('" + fieldName + "').select()");
        eval("document.getElementById('" + fieldName + "').focus()");
        la_Result = "false";
    }

   }
   return la_Result;
}

function GetFieldValue (fieldType, fieldName){
    var fieldValue = "";
    if (fieldType.toLowerCase() == "text"){
        fieldValue = eval("document._afd_submit."+fieldName+".value");
        fieldValue=fieldValue.trim();// Used to trim the field value
    }
    if (fieldType.toLowerCase() == "radio"){
        radioCheck = 0;
        colButtons = eval("document.getElementsByName('"+fieldName+"')");
        var i = 0;
        for(i = 0; i < colButtons.length; i++)
        {
          if(colButtons[i].checked){
            radioCheck = 1;
            break;
          }
        }
        if(radioCheck){
            fieldValue = "Selected"
        }
        else{
            fieldValue = "";
        }

    }
    if (fieldType.toLowerCase() == "menu"){
        fieldValue = eval("document.getElementById('"+fieldName+"').selectedIndex");
        if (fieldValue == "0"){
            fieldValue == "";
        }
    }
    if (fieldType.toLowerCase() == "checkbox"){
        fieldValue = eval("document._afd_submit."+fieldName+".checked");
    //  alert("fieldValue "+fieldValue);
    }


return fieldValue;
}

function ValidateFields(parameters)
{
    // Call to parse the URL and set the necessary hidden parameters
    parseString();
    var continueval="true";
    var la_Result;
    var i=0,j=0,ls_FieldLabel;
    while(i<parameters.length)
    {
       var ls_FieldLabel="";
       var ls_FieldName="";
       var ls_FieldType="";
       var continueval="true";
       var res=new Array();
       res=parameters[i].split("~");
       ls_FieldLabel=res[0];
       ls_FieldNameType=res[1].split("-");
       ls_FieldName=ls_FieldNameType[0];
if (ls_FieldName=='afd_order_web_publisher')
{
// alert(ls_FieldNameType);
}
       ls_FieldType=ls_FieldNameType[1];
       var ls_FieldValue = GetFieldValue(ls_FieldType, ls_FieldName);
       j=2;
           while(j<=res.length && continueval == "true")
           {
            switch(res[j])
            {
                case "M":
                {
                    la_Result=fn_PerformMandatoryCheck(ls_FieldValue, ls_FieldLabel, ls_FieldName, ls_FieldType);
                    if (la_Result=="false") {
                        continueval="false";
                    }
                    break;
                }

                case "CC":
                {
                    la_Result=fn_PerformConditionalCheck(ls_FieldValue, ls_FieldLabel, ls_FieldName, ls_FieldType);
                    if (la_Result=="false") {
                        continueval="false";
                    }
                    break;
                }


                case "BIC":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_CheckBTInternet(ls_FieldValue,ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false" )
                        {
                            continueval="false";
                        }
                     }
                    break;
                }
                case "BTCONNECT":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_CheckBTConnect(ls_FieldValue,ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false" )
                        {
                            continueval="false";
                        }
                     }
                    break;
                }
                case "Fname":
                {
                    if(ls_FieldValue !="") {
                        la_Result=Fname(ls_FieldValue,ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }
                case "Lname":
                {
                    if(ls_FieldValue !="") {
                        la_Result=Lname(ls_FieldValue,ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }
                case "Alpha":
                {
                    /*
                    if(ls_FieldValue !="") {
                        la_Result=Alpha(ls_FieldValue,ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }*/
                    break;
                }

                case "TLC":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_PerformTelLenCheck(ls_FieldValue, ls_FieldLabel, ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }

                case "TLCheck":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_PerformTelInitCheck(ls_FieldValue, ls_FieldLabel, ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }
                    
                case "EC":
                {
                   if(ls_FieldValue !="") {
                        la_Result=emailCheck(ls_FieldValue.toLowerCase(),ls_FieldLabel,ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }   
                                            
                break;
                }

                case "AC":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_CheckAccountNumber(ls_FieldValue, ls_FieldLabel, ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                     }
                    break;
                }


                case "DNEC":
                {
                    if(ls_FieldValue !="") {
                        var res1=parameters[i-1].split("~");
                        var prev_FieldLabel=res1[0];
                        var prev_FieldNameType=res1[1].split("-");
                        var prev_FieldName=prev_FieldNameType[0];
                        var prev_FieldType=prev_FieldNameType[1];
                        var prev_FieldValue = GetFieldValue(prev_FieldType, prev_FieldName);
                        if(ls_FieldValue!=prev_FieldValue) {
                            alert(prev_FieldLabel+" and "+ls_FieldLabel+" are not same");
                            eval("document.getElementById('" + ls_FieldName + "').focus()");
                            continueval="false";
                        }
                    }
                    break;
                }
                case "Domain":
                    {
                     if(ls_FieldValue !="") {
                       var pos=ls_FieldValue.indexOf('.');
                       if(pos!=-1){
                         var emailType="text";
                         var emailName=res[ res.length-1];
                         var emailValue = GetFieldValue (emailType,emailName);
                         emailValue=emailValue.trim();// Used to trim the field value
                         emailValue=emailValue.toLowerCase();
                         var emailDomainValue= emailValue.split("@");
                         var res1=emailDomainValue[1].split(".");
                         var ehost=res1[0];
                         var eextn1=res1[1];
                         var eextn2=res1[2];  
                         var res2,dhost,dextn1,dextn2,domainValue,dValue; 
                         var dValue=ls_FieldValue.toLowerCase();
                         // Removing spaces in the supplied string.
                         domainValue="";
                         for(i = 0; i < dValue.length; i++){
                          if(dValue.charAt (i)!=' ')
                          domainValue=domainValue+dValue.charAt(i);
                         }
                         //alert(domainValue); 
                         domainValue=domainValue.replace("http://www.",""); 
                         domainValue=domainValue.replace(/www./, "");
                         domainValue=domainValue.replace("http://", "");
                         //alert(domainValue); 
                         res2=domainValue.split("."); 
                         dhost=res2[0];
                         dextn1=res2[1];
                         dextn2=res2[2];
                         //alert("dhost = "+dhost+"  dextn1 = "+dextn1+"  dextn2 = "+dextn2);
                         //alert("ehost = "+ehost+"  eextn1 = "+eextn1+"  eextn2 = "+eextn2); 
                         if (dhost==ehost && dextn1==eextn1 && dextn2==eextn2) {
                          alert("Domain can not be same as domain of the '"+ls_FieldLabel+"'");
                          eval("document.getElementById ('" + ls_FieldName + "').focus()");
                          continueval="false";
                         }  
                       }
                       else{
                         alert("Please enter a valid Domain \n Eg: example.com \n www.example.com \n http://example.com \n http://www.example.com");
                         eval(" document.getElementById('" + ls_FieldName + "').focus()");
                         continueval="false";
                       }
                     }
                             break;
                    } 

                case "UKPC":
                {
                    if(ls_FieldValue!="")
                    {
                        if((/^\s*[a-z]{1,2}[0-9][a-z0-9]?\s*[0-9][a-z]{2}\s*$/i).test(ls_FieldValue))
                        break;
                        else{
                            alert(" This postcode is not recognised..");
                            eval("document.getElementById('" + ls_FieldName + "').focus()");
                            continueval="false";
                        }
                    }
                    break;
                }
                
                case "PHLL":
                {
                    if(ls_FieldValue!="")
                    {
                        if((/^\s*0(((1[0-9]{3})|(28[0-9]{2})\s*[0-9]{6})|(20[7|8]{1}\s*[0-9]{7}))\s*$/).test(ls_FieldValue))
                        break;
                        else{
                            alert(" This phone number is not a valid UK landline..");
                            eval("document.getElementById('" + ls_FieldName + "').focus()");
                            continueval="false";
                        }
                    }
                    break;
                }
                
                                case "Sortcode":
                {
                    if(ls_FieldValue!="")
                    {
                        if((/^\s*[0-9]{2}\s*[-]\s*[0-9]{2}\s*[-]\s*[0-9]{2}\s*$/).test(ls_FieldValue))
                        break;
                        else{
                            alert(" This Sort code is not in a valid format..");
                            eval("document.getElementById('" + ls_FieldName + "').focus()");
                            continueval="false";
                        }
                    }
                    break;
                }
                
                                case "BankAccNo":
                {
                    if(ls_FieldValue !="") 
                    {
                        la_Result=fn_PerformIsNumericCheck(ls_FieldValue);
                        if (la_Result=="false") 
                            {
                            alert(" This field should include only numbers..");
                            eval("document.getElementById('" + ls_FieldName + "').focus()");
                            continueval="false";
                            }                   }
                    break;
                }

                case "FR":
                {
                    if(ls_FieldValue !="") 
                    {
                        la_Result=fn_CheckFaultReference(ls_FieldValue, ls_FieldLabel, ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }

                case "Date":
                {
                    if(ls_FieldValue !="") {
                        la_Result=fn_dateValidation(ls_FieldValue,ls_FieldName);
                        if (la_Result=="false") {
                            continueval="false";
                        }
                    }
                    break;
                }
                                    case "Orderno":         
                                    {
                     if(ls_FieldValue!=""){
                     if((/^([a-zA-Z]{3}[0-9]{3})$/).test(ls_FieldValue))
                        break;
                     else{
                        alert("Your order number should be formatted 'ABC123' please re-enter");
                        eval("document.getElementById('" + ls_FieldName + "').focus()");
                        continueval="false";
                         }
                      }
                      break;
                }
                                     case "PreNo":
                      {
                      if(ls_FieldValue!=""){
                      if((/^08/).test(ls_FieldValue))
                        break;
                      else{
                        alert("Presentation number must begin with 08 ");
                        eval("document.getElementById('" + ls_FieldName + "').focus()");
                        continueval="false";
                       }
                       }
                       break;
                  }
                  default:
                  {
                    if (la_Result=="false"){
                        continueval="false";
                    }
                    break;
                   }
            } // End of switch statement
            j++;
        }// End of inner while

        if (continueval=="false"){
            break;
        }
        else{
            i++;
        }
    }// End of Outer while

    //Returning a value here
    if (continueval=="true"){
         return afdValForm();
    }
    else
        return false;
} // End of function ValidateFields

// function to check first name for alphabetics values and single quotes
function Fname(ls_FieldValue,ls_FieldLabel,ls_FieldName) 
{
    var la_Result="true";
    valRegex =/^([a-zA-Z\s]{1,30}`?[a-zA-Z\s]{1,30}'?[a-zA-Z\s]{0,20})$/;
    if(!valRegex.exec(ls_FieldValue)){
              alert("'"+ls_FieldLabel+"' contains invalid characters");
              eval("document.getElementById('" + ls_FieldName + "').focus()");
              la_Result="false";
     }
    else{
        la_Result="true";
    }
    return la_Result;
}
// function to check last name for alphabetics values and hyphen
function Lname(ls_FieldValue,ls_FieldLabel,ls_FieldName) 
{
    var la_Result="true";
    valRegex =/^([a-zA-Z\s]{1,40}-?[a-zA-Z\s]{1,40})$/;
    if(!valRegex.exec(ls_FieldValue)){
              alert("'"+ls_FieldLabel+"' contains invalid characters");
              eval("document.getElementById('" + ls_FieldName + "').focus()");
              la_Result="false";
     }
    else{
        la_Result="true";
    }
    return la_Result;
}
// function to check a field for alphabetics values
function Alpha(ls_FieldValue,ls_FieldLabel,ls_FieldName) //Purpose : This function checks whether the given value contains any alphabet.
{
    var la_Result="true";
    valRegex = /^([a-zA-Z\s]{1,255})$/;
    if(!valRegex.exec(ls_FieldValue)){
              alert("'"+ls_FieldLabel+"' contains invalid characters");
              eval("document.getElementById('" + ls_FieldName + "').focus()");
              la_Result="false";
     }
    else{
        la_Result="true";
    }
    return la_Result;
}

// function to check a field for numeric value
function fn_PerformIsNumericCheck(ls_FieldValue){   // returns true if the fieldvalue is number and false if the fieldvalue is not a number
   var ls_ValidChars = "0123456789.";
   var ls_IsNumber="true";
   var la_Result = "true";
   var ls_Char1;
   la_Result = "true";
   if ( ls_FieldValue == "" )
   return la_Result
   for (i = 0; i < ls_FieldValue.length && ls_IsNumber == "true"; i++)
   {
      ls_Char1 = ls_FieldValue.charAt(i);
        if (ls_Char1 == '-' && i==0){
            i = iU;
            ls_Char1 = ls_FieldValue.charAt(i);
        }
        if (ls_ValidChars.indexOf(ls_Char1) == -1){
            la_Result = "false";
            return la_Result;
        }
    }
}

/* Below function Clearfields has been added by TCS-RightNow ASG team on 01/12/08. For reference please refer the following cR BD422632 */

// To clear all the form fields customer entries
function Clearfields() 
{ 
document.forms["_afd_submit"].reset(); 
}

//function to check telephone number
function fn_PerformTelLenCheck(ls_FieldValue , ls_FieldLabel, ls_FieldName)
{
    var la_Result="true",num="0123456789",res,count=0;

    if (ls_FieldValue.charAt(0)!=="0" && ls_FieldValue.charAt(0)!=="1"){
        alert("'"+ls_FieldLabel+ "'  must begin with either zero or one.");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    
    // To find whether telno contain numbers or spaces.
    for(i = 0; i < ls_FieldValue.length; i++)   {
        res="true";
        if(ls_FieldValue.charAt(i)!=' ') {
            for(j = 0; j < num.length; j++){
            if(ls_FieldValue.charAt(i)==(num.charAt(j))) {
                res="false";
                count++;
                break;
            }
            }
            if(res=="true"){
                la_Result="false";
                alert("'"+ls_FieldLabel+"' must contain only numbers.");
                eval("document.getElementById('" + ls_FieldName + "').focus()");
                return la_Result;
                break;
            }
        }
    }
    if (count>25 || count<8){
        alert("'"+ls_FieldLabel+ "' must contain between 8 and 25 digits");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    
    count=0;//To find whether telno contain all Zeros.
    for(i = 3; i < ls_FieldValue.length; i++) {
        if(ls_FieldValue.charAt(i-1)=="0" && ls_FieldValue.charAt(i)=="0" )
        count++;
    }
    if(count>2) {
        alert("There is an error with this phone number. Please re-enter");
        continueval="false";
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }

    return la_Result;
}

//function to check telephone number
function fn_PerformTelInitCheck(ls_FieldValue , ls_FieldLabel, ls_FieldName)
{
    var la_Result="true",num="0123456789",res,count=0;
    //alert(ls_FieldValue.charAt(1));
    if (ls_FieldValue.charAt(0)!=="0"){
        alert("'"+ls_FieldLabel+ "'  must begin with zero.");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
     if (ls_FieldValue.charAt(1)!=="1" && ls_FieldValue.charAt(1)!=="2"){
        alert("'"+ls_FieldLabel+ "'  must begin with either '01' or '02'.");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    
    // To find whether telno contain numbers or spaces.
    for(i = 0; i < ls_FieldValue.length; i++)   {
        res="true";
        if(ls_FieldValue.charAt(i)!=' ') {
            for(j = 0; j < num.length; j++){
            if(ls_FieldValue.charAt(i)==(num.charAt(j))) {
                res="false";
                count++;
                break;
            }
            }
            if(res=="true"){
                la_Result="false";
                alert("'"+ls_FieldLabel+"' must contain only numbers.");
                eval("document.getElementById('" + ls_FieldName + "').focus()");
                return la_Result;
                break;
            }
        }
    }
    if (count>25 || count<8){
        alert("'"+ls_FieldLabel+ "' must contain between 8 and 25 digits");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    
    count=0;//To find whether telno contain all Zeros.
    for(i = 3; i < ls_FieldValue.length; i++) {
        if(ls_FieldValue.charAt(i-1)=="0" && ls_FieldValue.charAt(i)=="0" )
        count++;
    }
    if(count>2) {
        alert("There is an error with this phone number. Please re-enter");
        continueval="false";
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }

    return la_Result;
}

/*function fn_PerformTelLenCheck(ls_FieldValue , ls_FieldLabel, ls_FieldName)
{
    var la_Result="true";
    valRegex=/^\d*\d$/;
    if(!valRegex.test(ls_FieldValue)){
        la_Result="false";
        alert("'"+ls_FieldLabel+"' must contain only numbers.");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    var res="true";
    for(i = 0; i < ls_FieldValue.length; i++)
    {
        if(ls_FieldValue[i]!="0")
        res="false";
            }
    if(ls_FieldValue.substr(1,1)=="0" || res=="true"){
        alert("There is an error with this phone number.Please re-enter");
        continueval="false";
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    if (ls_FieldValue.length>11 || ls_FieldValue.length<8){
        alert(ls_FieldLabel+ " must contain between 8 and 11 digits");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    else{
        la_Result="true";
    }
    if (ls_FieldValue.charAt(0)!=="0"){
        alert("'"+ls_FieldLabel+ "'  must begin with a zero.");
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
    else{
        la_Result="true";
    }
    return la_Result;
}*/

// Function to check BT Internet Address
function fn_CheckBTInternet(emailStr,ls_FieldLabel,ls_FieldName)  // Function to check BT Internet Address
{
    var la_Result;
    var resEmailCheck=emailCheck (emailStr.toLowerCase(),ls_FieldLabel,ls_FieldName);
    if (resEmailCheck=="true"){
        la_Result="true";
        var spl= new Array();
        spl=emailStr.split("@");
        if (((spl[1].toLowerCase()!="btinternet.com") && (spl[1].toLowerCase()!="btconnect.com") && (spl[1].toLowerCase()!="btclick.com") && (spl[1].toLowerCase()!="btopenworld.com") )){
                alert("'BT Internet Email Address' must end either with btinternet.com or btconnect.com or btclick.com or btopenworld.com");
                la_Result="false";
                eval("document.getElementById('" + ls_FieldName + "').focus()");
                return la_Result;
        }
    }
    else if(resEmailCheck=="false"){
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
}
// End of Function

// Function to check BT Connect Address
function fn_CheckBTConnect(emailStr,ls_FieldLabel,ls_FieldName)  // Function to check BT Internet Address
{
    var la_Result;
    var resEmailCheck=emailCheck (emailStr.toLowerCase(),ls_FieldLabel,ls_FieldName);
    if (resEmailCheck=="true"){
        la_Result="true";
        var spl= new Array();
        spl=emailStr.split("@");
        if (((spl[1].toLowerCase()!="btconnect.com"))){
                alert("'Primary user account' must end with btconnect.com");
                la_Result="false";
                eval("document.getElementById('" + ls_FieldName + "').focus()");
                return la_Result;
        }
    }
    else if(resEmailCheck=="false"){
        la_Result="false";
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return la_Result;
    }
}

//  Function to check email addresses
function emailCheck (emailStr,ls_FieldLabel,ls_FieldName) {
/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */
var checkTLD=1;
/* The following is the list of known TLDs that an e-mail address must end with. */
var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */
//var emailPat=/^[a-z,A-Z](.+)@(.+)$/;
var emailPat=/^[a-z,A-Z,0-9]?(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ -, ; : \ " . [ ] */
//var specialChars="\\(\\)!`~,?/*{}+=|><@,;:#$%&\\\\\\\"\\.\\[\\]";
var specialChars="\\(\\)!`~,?/*{}+=|><@,;:#$%&\\\\\\\"\\\[\\]";
/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/
var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of non-special characters.) */
var atom=validChars + '+';
/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
/* Finally, let's start trying to figure out if the supplied address is valid. */
/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat);

if (matchArray==null) {
    /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
    alert("'"+ls_FieldLabel+ "' is not in a recognised format (Please check @,- and .'s)");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return"false";
}
var user=matchArray[1];
var domain=matchArray[2];
// Following  code is added ..
// To check  number of dots and positions

var dotrepeat="false";
var hyphenrepeat="false";
for (i=1; i<user.length; i++) {
    if (user.charAt(i-1)=='.' && user.charAt(i)=='.')
        dotrepeat="true";
    if (user.charAt(i-1)=='-' && user.charAt(i)=='-')
        hyphenrepeat="true";

 }
if (user.charAt(user.length-1)=='.' || dotrepeat=="true" || hyphenrepeat=="true") {
    /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
    alert("'"+ls_FieldLabel+ "' is not in a recognised format (Please check @,- and .'s)");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return"false";
}
//End of the code..
// Start by checking that only basic ASCII characters are in the strings (0-127).
for (i=0; i<user.length; i++) {
    if (user.charCodeAt(i)>127) {
        alert("The '"+ls_FieldLabel+"' contains invalid characters.");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return "false";
      }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127 ) {
    alert("The domain name in '" + ls_FieldLabel + "' contains invalid characters.");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return "false";
    }
}

// See if "user" is valid
// Added one condition in the IF statement
if (user.match(userPat)==null && user.charAt(0)!='.') {

    alert("The '"+ls_FieldLabel+"' contains invalid characters.");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return "false";
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
    if (IPArray[i]>255) {
        alert("Destination IP address is invalid! '"+ls_FieldLabel+"'");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        return "false";
    }
}
return "true";
}
// Domain is symbolic name.  Check if it's valid.
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
//Added  condition in IF statement
        if (domArr[i].search(atomPat)==-1 || domArr[0].length<2 || i>3) {
            alert("The domain name does not seem to be valid in '"+ls_FieldLabel+"'");
            eval("document.getElementById('" + ls_FieldName + "').focus()");
            return "false";
         }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */
//Added and modified the conditions in the IF statement ..
if (checkTLD && domArr[domArr.length-1].length<2 || ( domArr[domArr.length-1].length>2 && domArr[domArr.length-1].search(knownDomsPat)==-1 )) {
    alert("'"+ls_FieldLabel+ "' should end in a well-known domain or two letter " + "country code ");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return "false";
}
// Make sure there's a host name preceding the domain.

if (len<2) {
    alert("This address is missing a hostname in '"+ls_FieldLabel+"'");
    eval("document.getElementById('" + ls_FieldName + "').focus()");
    return "false";
}

// If we've gotten this far, everything's valid!
return "true";
}

//  End -->
// End of function to check email addresses
//Function to perform the format check for Account Number
function fn_CheckAccountNumber(ls_FieldValue, ls_FieldLabel, ls_FieldName)
{
    var la_Result;
    ls_Result="true";
    ls_Chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    if (ls_FieldValue.length!==10){
        alert ("'"+ls_FieldLabel+ "' should be of 10 characters with first two characters as letters and last eight as numeric.\n For eg. WM12345678");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }

    if (fn_PerformIsNumericCheck(ls_FieldValue.substr(2,9),ls_FieldLabel)=="false"){
        alert ("'"+ls_FieldLabel+ "' should be of 10 characters with first two characters as letters and last eight as numeric.\n For eg. WM12345678");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }
    if(fn_PerformSplCharCheck(ls_FieldValue.substr(0,2), ls_FieldLabel, ls_Chars)=="false"){
        alert ("'"+ls_FieldLabel+"' should be of 10 characters with first two characters as letters and last eight as numeric.\n For eg. WM12345678");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }
    return la_Result;
}

//Function to perform the format check for Fault Reference Number
function fn_CheckFaultReference(ls_FieldValue, ls_FieldLabel, ls_FieldName)
{
    var la_Result;
    ls_Chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    if (ls_FieldValue.length!==8){
        alert ("Incorrect format for fault reference please re-enter.\n For eg. AB1ABC12");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }
    if (fn_PerformIsNumericCheck(ls_FieldValue.substr(2,1),ls_FieldLabel)=="false" || fn_PerformIsNumericCheck(ls_FieldValue.substr(6,7),ls_FieldLabel)=="false")
    {
        alert ("Incorrect format for fault reference please re-enter.\n For eg. AB1ABC12");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }

    if((fn_PerformSplCharCheck(ls_FieldValue.substr(0,2), ls_FieldLabel, ls_Chars))=="false" || (fn_PerformSplCharCheck(ls_FieldValue.substr(3,3), ls_FieldLabel, ls_Chars))=="false")
    {
        alert ("Incorrect format for fault reference please re-enter.\n For eg. AB1ABC12");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    else{
        la_Result="true";
    }

    return la_Result;
}
// function to perform special character check
function fn_PerformSplCharCheck(ls_FieldValue, ls_FieldLabel, ls_Chars)
{
     // returns true if the fieldvalue  contains only valid chars and false if it contains
     // any invalid characters
      var ls_SplChar = "true" ;
      var ls_Char1;
      var la_Result ;
      la_Result = "true";

     if (ls_FieldValue == "" )
      return la_Result;

      for (i=0; i<ls_FieldValue.length && ls_SplChar == "true"; i++)
      {
           ls_Char1 = ls_FieldValue.charAt(i);
           if (ls_Chars.indexOf(ls_Char1) == -1){
              la_Result = "false";
            }
       }
       return la_Result;
}
function isInteger(s)
{
    var i;
    for (i = 0; i < s.length; i++)
    {
       // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function stripCharsInBag(s, bag)
{
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
function daysInFebruary (year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n)
{
    for (var i = 1; i <= n; i++)
    {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
    }
   return this
}

function fn_dateValidation(dtStr,ls_FieldName)
{
    var param=dtStr;
    dtCh="/";
    var minYear=0;
    var maxYear=99;
    var daysInMonth = DaysArray(12);
    var count=0;
    for (var i = 0; i <= dtStr.length; i++)
    {
        if (dtStr.charAt(i)=='/') count++;
    }
    res=param.split("/");
    var strDay=res[0];
    var strMonth=res[1];
    var strYear=res[2];
    var strYr=strYear;
    if(count!=2 || strDay.length==0){
        alert("Date in wrong format please re-enter using format DD / MM /YY");
        eval("document.getElementById('" + ls_FieldName + "').focus()");
        la_Result="false";
        return la_Result;
    }
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
    month=parseInt(strMonth);
    day=parseInt(strDay);
    year=parseInt(strYr);
    if (strMonth.length==0 || month<1 || month>12 ){
            alert("Date in wrong format please re-enter using format DD /MM /YY")
            eval("document.getElementById('" + ls_FieldName + "').focus()");
            la_Result="false";
            return la_Result;
    }
    if (day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month] ) {
            alert("Date in wrong format please re-enter using format DD / MM /YY")
            eval("document.getElementById('" + ls_FieldName + "').focus()");
            la_Result="false";
            return la_Result;
    }
    if (strYear.length==0 || strYear.length > 2|| year<minYear || year>maxYear ){
            alert("Date in wrong format please re-enter using format DD / MM /YY")
            eval("document.getElementById('" + ls_FieldName + "').focus()");
            la_Result="false";
                return la_Result;
    }
    if (isInteger(stripCharsInBag(dtStr, dtCh))==false ){
            alert("Date in wrong format please re-enter using format DD /MM / YY")
            eval("document.getElementById('" + ls_FieldName + "').focus()");
            la_Result="false";
            return la_Result;
    }
    else{
        la_Result="true";
    }
}
// Function to be called by each AFD FAQ to parse the string
function parseString() {
    var param = "p_param=";
    var url = replaceSubstring(location.href, "%20", " ");
    var indparam = "";
    //url = "p_param=p_afd_subject=Complaints&p_afd_inc_router=Kana&p_afd_form_id=contactus_send_bboff_bb_billing&p_afd_customer_classification=COMPLAINT&p_afd_customer_category=BTB BBOFF BB Complaint&p_afd_cat_lvl1_hidden=426&p_afd_cat_lvl2_hidden=427&p_afd_cat_lvl3_hidden=438&p_source=helpandsupport";
    //alert("URL : "+url);
    if(url.indexOf(param) != -1) {
        var parameter = url.substring(url.indexOf(param)+param.length, url.length)
        //alert("parameter : "+parameter);
        var values = parameter.split("&");
        //alert("values : "+values);
        for (i = 0; i < values.length; i ++) {
            indparam = values[i].split("=");
            if (indparam[0] != "p_source")
            {
            //alert("indparam[0] : "+indparam[0]+"indparam[0].substring(0, indparam[0].length) : "+indparam[0].substring(0, indparam[0].length));   
            //alert("indparam[0].substring(2, indparam[0].length) : "+indparam[0].substring(2, indparam[0].length));    
            eval("document._afd_submit."+ indparam[0].substring(2, indparam[0].length) + ".value = '"+ indparam[1] + "';");

            }
        }
    }
}
//Function for replace Substring
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function
