var validation_msg_validation_head = "Validation errors";
var validation_exc_mandatory = "is mandatory";
var validation_exc_number_format = "number format incorrect";
var validation_exc_date_format = "date format incorrect";
var validation_exc_length = "length wrong";
var validation_exc_range = "out of range";
var validation_exc_regexp = "error on validation rules";

var validation_msg_component="";

// =======================================================================
// GLOBAL VARIABLES
// =======================================================================
var validation_form;
var formName;
var validation_widgets  = new Array(); // WIDGET'S DATATYPE
var validation_widgetsI18N = new Array(); // WIDGET I18N descrizione nome campo
var validation_required = new Array(); // IS REQUIRED?
var validation_format   = new Array(); // SPECIAL FORMAT
var validation_user     = new Array(); // CUSTOM USER FUNCTION
var validation_length   = new Array(); // LENGTH
var validation_range    = new Array(); // RANGE
var validation_regexp   = new Array(); // REGEXP
var validation_accept 	= new Array(); // ACCEPT KEYS
var validation_pad	 	= new Array(); // AUTOMATI

var server_side_form  = new Array();
var server_side_errors = new Array();

var validation_messages = new Array(); // VALIDATION ERROR MESSAGES
var validation_constraint_messages = new Array(); //Added for constraint specific messages
var validation_mask_messages = new Array(); 
var validation_datatype_messages = new Array();
var validation_docheck   = new Array(); // WHICH FORMS TO CHECK

var errorsWithIdsAsKey   = new Array(); //TO MAP WIDGET'S ID'S TO ERROR MESSAGES

// Validator Object
var valid = new Object();

// REGEX Elements

// matches all digits
valid.digits = /^[0-9]+$/;

// matches everything except digits
//valid.Alphabets = /^[^0-9]+$/;
//valid.Alphabets = /^[a-zA-Z]+\s*[\.]*\s*[a-zA-Z]+\s*[\.]*\s*[a-zA-Z]+$/;
//valid.Alphabets = /^[a-zA-Z]+\s*[\.]*\s*[a-zA-Z]+$/;
valid.Alphabets = /^[a-zA-Z]+[\s|\.|\-]?[a-zA-Z]+[\s|\.|\-]?[a-zA-Z]*$/;
valid.AccountID = /^[0-9]+$/;
valid.LPAlphabets = /^[a-zA-Z]+[\s|\.|\-]?[a-zA-Z]+[\s|\.|\-]?[a-zA-Z]*$/;

// matches zip codes
valid.zipCode = /\d{5}(-\d{4})?/;

// matches $17.23 or $14,281,545.45 or ...
valid.Currency = /\$\d{1,3}(,\d{3})*\.\d{2}/;

// matches 5:04 or 12:34 but not 75:83
valid.Time = /^([1-9]|1[0-2]):[0-5]\d$/;

//matches email
valid.emailAddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;

//matches phone ###-###-#######
// valid.phoneNumber = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
valid.phoneNumberCountryCode = /^\d{3}$/;
valid.phoneNumberCityCode = /^\d{3}$/;
valid.phoneNumber = /^\d{7}$/;

// International Phone Number
valid.phoneNumberInternational = /^\d(\d|-)*$/;

// IP Address
valid.ipAddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;

// Date xx/xx/xxxx
valid.Date = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;

valid.dateDay = /^\d{1,2}$/;

valid.dateYear = /^\d{4}$/;

// State Abbreviation
valid.State = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;

// Social Security Number
//valid.SSN = /^\d{3}\-\d{2}\-\d{4}$/;
valid.SSN1 = /^\d{3}$/;
valid.SSN2 = /^\d{2}$/;
valid.SSN3 = /^\d{4}$/;

// Anumber
valid.Anumber = /^\d{7,9}$/;
valid.password = /^\w{6,11}$/;
// New Phone Tag
valid.areaCode1 = /^\d{3}$/;
//valid.areaCode1WithoutHash = /^\d{3}$/;
valid.areaCode2 = /^\d{2,5}$/;
valid.newphone1 = /^\d{3}$/;
//valid.newphone1WithoutHash = /^\d{3}$/;
valid.newphone2 = /^\d{4}$/;
//valid.newphone2WithoutHash = /^\d{4}$/;
valid.newphone3 = /^\d{6,10}$/;
function setDoCheck(iWidget,doIt) {
   validation_docheck[iWidget] = doIt;
}

function setRequired(iWidget,isRequired) {
   validation_required[iWidget] = isRequired;
}

function getWidgetValue( iName )
{

  var element = document.getElementsByName( iName );
  if(element[0] != null && element[0].type != null && element[0].type != undefined && element[0].type == "radio"){
        for (var i = 0; i < element.length; i++) {
            if (element[i].checked) {
                return element[i].value;
            }
        }
  }
  else if (element[0] != null && element[0].type != null && element[0].type != undefined && element[0].type == "radio")
  {
       for (var i = 0; i < element.length; i++) {
         if (element[i].checked) {
             return element[i].value;
         }
       }	
  }
  else if (element[0] != null && element[0].type != null && element[0].type != undefined && element[0].type == "checkbox")
  {
       for (var i = 0; i < element.length; i++) {
         if (element[i].checked) {
             return element[i].value;
         }
       }
	
  }
  else
  { 
	var field = document.forms[formName].elements[ iName ];
	if( field != null )
	    return field.value;
  }
  return null;
}

function setWidgetValue( iName , value )
{
  var field = validation_form.elements[ iName ];
  if( field != null )
    field.value = value;
}

function isBlank(val)
{
	if(val==null)
	{
		return true;
	}
	for(var i=0;i<val.length;i++)
	{
		if((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r"))
		{
			return false;
		}
	}
	return true;
}

function isDigit(num)
{
	if(num.length>1)
	{
		return false;
	}
	var string="1234567890";
	if(string.indexOf(num)!=-1)
	{
		return true;
	}
return false;
}

function isInteger(val)
{
if(isBlank(val))
	{
		return false;
	}
for(var i=0;i<val.length;i++)
{
	if(!isDigit(val.charAt(i)))
	{
		return false;
	}
}
return true;
}

function isFloat( iValue )
{
  if( iValue == null || iValue == "" )
    return true;

  //TODO TEST ONLY THE TRUE CURRENCY FORMAT AND NOT BOTH
  //var reFloatF1 = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/;
  //var reFloatF2 = /^((\d+(\,\d*)?)|((\d*\,)?\d+))$/;
  //return reFloatF1.test( iValue ) || reFloatF2.test( iValue );
  //TODO works only with italian number pattern; extend to other locales
  var newReFloat = /^([\d\.]*(\,\d*)?)$/;
  return newReFloat.test(iValue);
}        
function validation_preRegister(iWidget,iMaskErrorMessage,iDataTypeErrorMessage)
{
validation_mask_messages[iWidget]=iMaskErrorMessage;
if(iDataTypeErrorMessage != '' && iDataTypeErrorMessage != null)
validation_datatype_messages[iWidget]=iDataTypeErrorMessage;
}

function validation_register( iWidget, iWidgetI18N, iRequired, iDatatype, iFormat, iUserFunction,iLength, iRange, iRegexp, iAccept, iErrorMessage) {
//  var applyValidation= getApplyValidation();

//  if(applyValidation=="false")
//        return;
  validation_widgets[iWidget] = iDatatype;
  
  validation_widgetsI18N[iWidget] = iWidgetI18N;

  // REQUIRED
  if( iRequired )
    validation_required[iWidget] = true;

  // FORMAT
  if( iFormat )
    validation_format[iWidget] = iFormat;

  // USER FUNCTION
  if( iUserFunction )
    validation_user[iWidget] = iUserFunction;

  // LENGTH
  if( iLength )
    validation_length[iWidget] = iLength;

  // RANGE
  if( iRange )
    validation_range[iWidget] = iRange;
    
  // REGEXP
  if( iRegexp ){
    validation_regexp[iWidget] = iRegexp;
  }	
    
  if ( iAccept ) {
  	validation_accept[iWidget] = iAccept;
  } /*else {
  	if (iDatatype == 'integer' || iDatatype == 'long') {
  	  validation_accept[iWidget] = '[0-9\.]';
  	} else if (iDatatype == 'double' || iDatatype == 'decimal') {
  	  validation_accept[iWidget] = '[0-9\.\,]';  	
  	} else if (iDatatype == 'date') {
  	  validation_accept[iWidget] = '[0-9\\\/]';  	
  	} else if (iRegexp && iRegexp != null && iRegexp[0] != '') {
  	  var nre = iRegexp[0].toString();
  	  var removebrackets = new RegExp('\\{[0-9]*[\\,]?[0-9]*\\}','g');
  	  nre = nre.replace(removebrackets,'');
  	  var removesyntax = new RegExp('[\\(\\)\\|\\^\\$\\*\\+\\?\\[\\]]*','g');
  	  nre = nre.replace(removesyntax,'');  	  
  	  validation_accept[iWidget] = '[' + nre + ']';
  	}
  }*/
  
  if ( iErrorMessage ) {
	validation_msg_component = iErrorMessage;
  	validation_messages[iWidget] = iErrorMessage;
  }
}
/* the following function returns the trimmed value of the argument */

function trim(val) {
    if(val != null)
	return val.replace(/^\s+|\s+$/g,"");
        return null;
}

function validation_precheck_widget( iWidget )
{
  if( !iWidget || iWidget == null )
    return;
  var value = getWidgetValue( iWidget );
  var ret = null;
  // LENGTH
  var length = validation_length[iWidget];
  if( length != null && value != null )
  {
    var min   = length[0];
    var max   = length[1];
    var exact = length[2];

	var maxval = (max && max != null && value.length > max) ? max : 999999;
	if (exact && exact != null && exact < maxval) maxval = exact;
	if (maxval && maxval != null && value.length > maxval) {
		if (window.confirm(validation_widgetsI18N[widget] + validation_msg_trunk)) {
			value = value.substring(0,maxval);
			setWidgetValue(iWidget, value);
			ret = validation_msg_recheck;
		}
	} else if( min && min   != null && value.length < min) {
	
		var pad = validation_pad[iWidget];
		if (pad != null && value && value != null && value != '') {
			var side = pad[0];
			var val = pad[1];
			if (!side || side == null || side == '') side = 'left';
			if (val && val != null && val != '') {
				while (value.length < min) {
					if (side == 'left') {
						value = val + value;
					} else {
						value = value + val;
					}
				}
				if (maxval && maxval != null && value.length > maxval) {
					value = value.substring(0,maxval);
				}
				setWidgetValue(iWidget, value);
				ret = validation_msg_padrecheck;				
			}
		}
	}
  }
  return ret;
}


function validation_check_widget( iWidget )
{
  //if( !iWidget || iWidget == null || !validation_required[iWidget] || validation_required[iWidget] == null || validation_required[iWidget] == undefined)
    //return;
  var value = getWidgetValue( iWidget );

  if (iWidget=='newTelephone.country' && value=="1"){
      validation_required["newTelephone.areaCode2"]=false;
      validation_required["newTelephone.phone3"]=false;
      validation_regexp["newTelephone.areaCode2"]="undefined";
      validation_regexp["newTelephone.phone3"]="undefined";
      validation_docheck["newTelephone.areaCode2"]=false;
      validation_docheck["newTelephone.phone3"]=false;
  }
   
  if (iWidget=='mobile.country' && value=="1"){
      validation_required["mobile.areaCode2"]=false;
      validation_required["mobile.phone3"]=false;
      validation_regexp["mobile.areaCode2"]="undefined";
      validation_regexp["mobile.phone3"]="undefined";
      validation_docheck["mobile.areaCode2"]=false;
      validation_docheck["mobile.phone3"]=false;
  }
  
  var datatype = validation_widgets[iWidget];
  
  if( datatype == "passwordcheck" )
  {
	confirmpasswordiWidget = "confirm" + iWidget.substring(0,iWidget.length);
	var passwordValue = getWidgetValue(iWidget);
	var confirmpasswordValue = getWidgetValue(confirmpasswordiWidget);
	var passwordStatus;
	var regexp = validation_regexp[iWidget];
	if ((passwordValue != null && passwordValue != '' && passwordValue != undefined) || (confirmpasswordValue != null && confirmpasswordValue != '' && confirmpasswordValue != undefined ))
	{
	 passwordStatus = doPasswordCheck(getWidgetValue(iWidget),getWidgetValue(confirmpasswordiWidget));
	}
	if (passwordStatus == false)
	{
           pushErrorsId(iWidget, 'error on validation rules');
           pushErrorsId(confirmpasswordiWidget, 'error on validation rules');
   	   validation_constraint_messages[iWidget] = validation_datatype_messages[iWidget];
	}
	if(passwordStatus == false)
	    return passwordStatus;
 
  }

  if( datatype == "emailcheck" )
  {
        confirmemailiWidget = "confirm" + iWidget.substring(0,iWidget.length);
        var emailValue = getWidgetValue(iWidget);
        var confirmemailValue = getWidgetValue(confirmemailiWidget);
        var emailStatus;
	var regexp = validation_regexp[iWidget];
        if ((emailValue != null && emailValue != '' && emailValue != undefined) || (confirmemailValue != null && confirmemailValue != '' && confirmemailValue != undefined ))
        {
         emailStatus = doEmailCheck(getWidgetValue(iWidget),getWidgetValue(confirmemailiWidget));
        }
        if (emailStatus == false)
        {
	
	  pushErrorsId(iWidget, 'error on validation rules');
	  pushErrorsId(confirmemailiWidget, 'error on validation rules');
          validation_constraint_messages[iWidget] = validation_datatype_messages[iWidget];
        }
	if(emailStatus == false)
	    return emailStatus;
 
  }


  if( datatype == "creditcardcheck" )
  {
        cardTypeiWidget = "card_cardType";
        var cardNumberValue = getWidgetValue(iWidget);
        var cardTypeValue = getWidgetValue(cardTypeiWidget);
        var creditcardStatus;
        if ((cardNumberValue != null && cardNumberValue != '' && cardNumberValue != undefined) || (cardTypeValue != null && cardTypeValue != '' && cardTypeValue != undefined ))
        {
         creditcardStatus = doCreditCardCheck(getWidgetValue(iWidget),getWidgetValue(cardTypeiWidget));
        }
        if (creditcardStatus == false)
        {
	  pushErrorsId(iWidget, 'error on validation rules');
          validation_constraint_messages[iWidget] = validation_datatype_messages[iWidget];
          return creditcardStatus;
        }

  }


  if( datatype == "expirydate" )
  {
        yeariWidget = "year";
	monthyeariWidget = "monthyear";
        var yearValue = getWidgetValue(yeariWidget);
        var monthValue = getWidgetValue(iWidget);
        var monthyearValue = getWidgetValue(monthyeariWidget);
        var expirydateStatus;
        if ((yearValue != null && yearValue != '' && yearValue != undefined) || (monthValue != null && monthValue != '' && monthValue != undefined ) || (monthyearValue != null && monthyearValue != '' && monthyearValue != undefined ))
        {
         expirydateStatus = doExpiryDateCheck(getWidgetValue(iWidget),getWidgetValue(yeariWidget),getWidgetValue(monthyeariWidget));
        }
        if (!expirydateStatus)
        {
	  pushErrorsId(iWidget, 'error on validation rules');
          validation_constraint_messages[iWidget] = validation_datatype_messages[iWidget];
          return expirydateStatus;
        }
	
        else if (yearValue != null && yearValue != '' && yearValue != undefined)
        {
          return null;
        }

  }

  if( datatype == "date" )
  {
    	iWidget=iWidget.substring(0,iWidget.lastIndexOf('.'));
	var dateValue = getWidgetValue( iWidget+".month") +" "+getWidgetValue( iWidget+".day")+" "+ getWidgetValue( iWidget+".year");
    if( dateValue && dateValue != "" && !chkdate( dateValue) )
    {	
	return validation_exc_date_format;
    }	
  }

  // VALUE NULL AND FIELD NOT REQUIRED RETURN NULL
  if( datatype=="nonZero" && value==0)
      return validation_exc_mandatory;

  if( !value || value == undefined || value == null || value == '' || value == "UNKNOWN")  {
     if( validation_required[iWidget] || validation_required[iWidget] != null ) return validation_exc_mandatory;
  }

  // DATATYPE
  //var datatype = validation_widgets[iWidget];
  if( value && (datatype == "integer" || datatype == "long" ))
  {
    // INTEGER-LONG
    if( !isInteger( value ))
      return validation_exc_number_format;
  }
  else if( datatype == "double" || datatype == "decimal" )
  {
    // FLOAT-DOUBLE
    if( !isFloat( value ))
      return validation_exc_number_format;
  }
  
  // LENGTH
  var length = validation_length[iWidget];
  if( length != null && value != null )
  {
    var min   = length[0];
    var max   = length[1];
    var exact = length[2];
    var msg   = length[3];  

    if( !msg || msg == null )
      msg = validation_exc_length;

    if( min && min   != null && value.length < min ||
        max && max   != null && value.length > max ||
        exact && exact != null && value.length != exact )
      return msg;
  }

  // RANGE
  var range = validation_range[iWidget];
  if( range != null && value != null )
  {
    var min   = range[0];
    var max   = range[1];
    var exact = range[2];
    var msg   = range[3];
    
    if( !msg || msg == null )
      msg = validation_exc_range;

    if( min && min   != null && value < min ||
        max && max   != null && value > max ||
        exact && exact != null && value != exact )
      return msg;
    }

  // REGEXP
  var regexp = validation_regexp[iWidget];
  if( regexp != null && value != null )
  {
    var msg   = regexp[1];
    if( !msg || msg == null )
      msg = validation_exc_regexp;
      if(regexp != null) {
	      var regexpResult = value.search( valid[regexp] );
	      if( regexpResult == -1 && (value != null && value != '' && value != undefined))
	      {
                if(regexp == "password" )
                {
		 pushErrorsId(iWidget, 'error on validation rules');
                 if(validation_constraint_messages[iWidget] != undefined)
                 {
                 validation_constraint_messages[iWidget]=validation_constraint_messages[iWidget] + "<br/>" +validation_mask_messages[iWidget];
		 }
                 else 
                 {
                   validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
                 }

		 return msg;
                }
                if(regexp == "emailAddress" )
                {
		 pushErrorsId(iWidget, 'error on validation rules');
		 if(validation_constraint_messages[iWidget] != undefined)
		 {
                   validation_constraint_messages[iWidget]=validation_constraint_messages[iWidget] + "<br/>" + validation_mask_messages[iWidget];
		 }
		 else
		 {
		   validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		 }
		 return msg;
                }
		if(regexp == "phoneNumberInternational")
		{
                  pushErrorsId(iWidget, 'error on validation rules');
		  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
		}
                if(regexp == "AccountID")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
		/*if(regexp == "areaCode1")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "areaCode1WithoutHash")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "areaCode2")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "newphone1")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                /*if(regexp == "newphone1WithoutHash")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "newphone2")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "newphone2WithoutHash")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }
                if(regexp == "newphone3")
                {
		  pushErrorsId(iWidget, 'error on validation rules');
                  validation_constraint_messages[iWidget]= validation_mask_messages[iWidget];
		  return msg;
                }*/
                
		if(regexp != "password" && regexp != "emailAddress" && regexp != "phoneNumberInternational" && regexp != "AccountID" )
		{
		  pushErrorsId(iWidget, 'error on validation rules');
		  validation_constraint_messages[iWidget]=validation_mask_messages[iWidget];
                  return msg;
		}
                if((regexp != "areaCode1"  && regexp != "newphone1" && regexp != "newphone2") || (regexp != "areaCode2" && regexp != "newphone3")){
                  pushErrorsId(iWidget, 'error on validation rules');
		  validation_constraint_messages[iWidget]=validation_mask_messages[iWidget];
                  return msg;
                }
	      }	
      }
  }

  // USER FUNCTION (CALL IT WITH ITSELF AS ARGUMENT)
  var userFunction = validation_user[iWidget];
  if( userFunction != null )
  {
    return eval( userFunction + "(" + iWidget + ")" );
  }

  return null;
}

function validation_check_form( iForm )
{
    validation_form = iForm != null ? iForm : document.forms[formName];
    errors = new Array();
    //errorsWithIdsAsKey= new Array();
    var msg;
    //Call the listener method to set/unset veto on field validation?
    if (typeof(preInitCheck) == 'function') preInitCheck();

    for( widget in validation_widgets ) {
        if(document.getElementById(widget) != null || document.getElementsByName(widget)[0] != null) {
            if (!validation_docheck[widget] || validation_docheck[widget]=='' || validation_docheck[widget] == 'true') {
	        msg = validation_precheck_widget( widget );
	        if( msg != null ) {
		    errors.push( [ validation_widgetsI18N[ widget ], msg ] );
	        }
	    }
         }
     }

    var teleCountry = getWidgetValue("newTelephone.country");
    var mobileCountry = getWidgetValue("mobile.country");
    var teleArea2 = getWidgetValue("newTelephone.areaCode2");
    var mobArea2  = getWidgetValue("mobile.areaCode2");
    var tele3     = getWidgetValue("newTelephone.phone3");
    var mob3      = getWidgetValue("mobile.phone3");
    var usCodes = "/1/ 1";

    if ((teleCountry=="UNKNOWN" ) && (mobileCountry=="UNKNOWN" )){
	errorsWithIdsAsKey.push( ["newTelephone.country", "" ] );
	errorsWithIdsAsKey.push( ["mobile.country", "" ] );
	errors.push( [ validation_widgetsI18N[ "newTelephone.country" ], "Please provide phone number or mobile number" ] );
    }else if(teleCountry=="UNKNOWN"&&(teleArea2!=""||tele3!="")){
	errorsWithIdsAsKey.push( ["newTelephone.country", "" ] );
	errors.push( [ validation_widgetsI18N[ "newTelephone.country" ], "Please provide phone country" ] );
    }else if(mobileCountry=="UNKNOWN"&&(mobArea2!=""||mob3!="")){
	errorsWithIdsAsKey.push( ["mobile.country", "" ] );
	errors.push( [ validation_widgetsI18N[ "mobile.country" ], "Please provide mobile country" ] );
    }


     for(widget in validation_widgets) {
	var temp = getParentSectionDiv(widget);
	tempWidget = document.getElementsByName(widget)[0];
	var tempId = getParentTAG(tempWidget,"TD");
	var sectionDiv = document.getElementById(temp);

	if(sectionDiv != null && sectionDiv.style.display !="none"){
	    if(document.getElementById(widget) != null || document.getElementsByName(widget)[0] != null) {
 	        if (!validation_docheck[widget] || validation_docheck[widget]=='' || validation_docheck[widget] == 'true') {
	            msg = validation_check_widget( widget );
	            if( msg != null ){
                        if (((widget=="newTelephone.areaCode2")||(widget=="newTelephone.phone3"))&&(usCodes.indexOf(teleCountry)>0)){
                           // Just a patch - need to fix this
                        }
                        else if (((widget=="newTelephone.areaCode1")||(widget=="newTelephone.phone1")||(widget=="newTelephone.phone2"))&&(usCodes.indexOf(teleCountry)<0)){
                           // Just a patch - need to fix this
                        }
                        else if(((widget=="mobile.areaCode2")||(widget=="mobile.phone3"))&&(usCodes.indexOf(mobileCountry)>0)){
                           // Just a patch - need to fix this
                        }
                        else if(((widget=="mobile.areaCode1")||(widget=="mobile.phone1")||(widget=="mobile.phone2"))&&(usCodes.indexOf(mobileCountry)<0)){
                           // Just a patch - need to fix this
                        }
                        else if (((widget=="newTelephone.areaCode2")||(widget=="newTelephone.phone3"))&&(teleCountry=="UNKNOWN")){
                           // Just a patch - need to fix this
                        }
                        else if(((widget=="mobile.areaCode2")||(widget=="mobile.phone3"))&&(mobileCountry=="UNKNOWN")){
                           // Just a patch - need to fix this
                        }
                         else{
	                    errorsWithIdsAsKey.push( [widget, msg ] );
		            errors.push( [ validation_widgetsI18N[ widget ], validation_messages[ widget ] ] );
                        }
                    } 
	        }
	    }
	}
    }
  
    //Call the listener method to add message errors by other external validations
    if (typeof(postInitCheck) == 'function') {
 	errors = postInitCheck(errors);
    }
    return errors;
}

// =======================================================================
// Display all validation errors found. The array containing errors can be
// generated by calling validation_check_form(). If you want to add other errors to
// display, just update the array returned from validation_check_form() with yours 
// before calling this function.
//
// Usage:
function pushErrorsId(iWidget, msg)
{
   var check = "false";
   for(var i=0; i < errorsWithIdsAsKey.length; ++i)
   {
	if(iWidget == errorsWithIdsAsKey[i][0])
	{
	    check = "true";
	    break;
	}
   }
      if(check == "false")	
      {
         errorsWithIdsAsKey.push( [iWidget, msg ] );
      }
}
 function form_submit(arg)
{
   formName = arg;
   validation_form = document.forms[formName];
   var form = document.forms[formName];
   errors = new Array();
   errorsWithIdsAsKey=new Array();
   validation_constraint_messages = new Array(); 

   refreshErrorDivs();

   refreshStyles(form);   

   if( !validation_show_errors( validation_check_form( form ) ) )
   {
       if(document.getElementById("acceptPrivacyPolicy") !=null && document.getElementById("acceptPrivacyPolicy").checked == false) {
	   document.getElementById("acceptPrivacyPolicy").checked=true;
       }
      return false;	
   }
   else
   {
	if(document.getElementById("payment") != null || document.getElementsByName("payment")[0] != undefined) 
	{
	iwidget="payment";
        var result = confirm (validation_mask_messages[iwidget]);
	}

      form.submit();
   }
 }


//
// param: iErrors It contains couples of field-name/error message
// 	 === MODIFIED TO DISPLAY ERROR MESSAGES ON DIV'S - ANIL 2006/03/16
// return: true if there are no errors, otherwise false
// =======================================================================
function validation_show_errors( iErrors )
{
  if( iErrors == null || iErrors.length == 0 )
    return true;

  //document.getElementById("errors-section").innerHTML="<b>Please correct the entries highlighted below.</b><br>";
 // document.getElementById("errors-section").className = "page-errors";
  //ShowContent('errors-section');		

  //var msg="<b>Please complete the fields highlighted below.</b>";  
  var msgCommon="";
  var msg="";
  var msgOnDiv="";
  var commoniWidjet="common";
  var sectionNameSubscript="errors-section";
  for( var i = 0; i < errorsWithIdsAsKey.length; ++i )
  {
   var temp = getParentDiv(errorsWithIdsAsKey[i][0]);
  // var temp = document.getElementById(sectionNameSubscript);
   var firstElement = document.getElementsByName(errorsWithIdsAsKey[i][0])[0];
    if(firstElement == null)
    {
	firstElement = document.getElementById(errorsWithIdsAsKey[i][0]);	   
    }
   if(firstElement == null)
	{
	return true;
	}
	
   highlight(firstElement);
   if(temp != sectionNameSubscript){
        var sectionName=sectionNameSubscript;
        document.getElementById(sectionName).innerHTML=msgOnDiv;
       // document.getElementById(sectionName).className = "section-errors";
            ShowContent(sectionName);
        msgOnDiv="";
            msg="";
        sectionNameSubscript=temp;
    }
    if(i < iErrors.length)
    {

    msg += "<br>" +  iErrors[i][1];
    msgOnDiv = "<br>" + msg;
    }
    if(iErrors.length > 0)
    {
       if(iErrors.length > 1)
       {
       if(validation_mask_messages["common"] != null && validation_mask_messages["common"] != undefined)
       {
	  msgCommon = validation_mask_messages["common"];
       }
       else
       {
          msgCommon = "<b>Please complete the fields highlighted below.</b>";
       }
       for( message in validation_constraint_messages )
       {
	  //if(validation_constraint_messages[message] != undefiened)
          msgCommon += '<br>' + validation_constraint_messages[message];
       }
     //  document.getElementById("errors-section").innerHTML=msg;
     //  ShowContent("errors-section");
	msgOnDiv = msgCommon;
       }
       if(iErrors.length == 1)
       {
       //msg = "<b>Please complete the fields highlighted below.</b>";
       var check=false;
       msgCommon="";
       for( message in validation_constraint_messages )
       {
          msgCommon += '<br>' + validation_constraint_messages[message];
	  check = true;
	  
       }
       if(check)
       {
       if(validation_mask_messages["common"] != null && validation_mask_messages["common"] != undefined)
       {
          msgCommon = validation_mask_messages["common"] + msgCommon;
       }
       else
       {
	msgCommon = "<b>Please complete the fields highlighted below.</b>" +msgCommon;
       }
       }	
       else
	{
	 msgCommon = msg;
	}
	msgOnDiv = msgCommon;	
       }
    }

  }
  sectionName=sectionNameSubscript;
 
  document.getElementById(sectionName).innerHTML=msgOnDiv;
  //document.getElementById(sectionName).className = "section-errors";
  ShowContent(sectionName);
  return false;
}

//param:tagName
//function to retreive the immediate parent DIV with "id" attribute starting with "errors-section-xxx"
function getParentDiv(idValue){
	//var errorSection;
	//if(document.getElementById(idValue)!=null)
        //{
	//        errorSection = "errors-section-" + formName;
	//	var id=document.getElementById(idValue);
	//	if(id != null){
	//		return id;
	//	}
	//}
	//else
	//	return "errors-page";

        if(document.getElementById(idValue)!=null && document.getElementById(idValue).parentNode.tagName=="DIV" )
        {
		if(document.getElementById(idValue).parentNode.getAttribute("id") != null && document.getElementById(idValue).parentNode.getAttribute("id") != undefined && document.getElementById(idValue).parentNode.getAttribute("id") != '')
		{
                var id=document.getElementById(idValue).parentNode.getAttribute("id");
		
                if(id.substring(0,14)=="errors-section")
		{
                    return id;
                }
		}
        }
        //else
        {
                var node = document.getElementsByName(idValue)[0];
	        if (node == null && node == undefined)
		{
			node = document.getElementById(idValue);
		}
                while(node != null && node != undefined)
                {
                      if(node.tagName == "DIV" && node.getAttribute("id") != null && node.getAttribute("id").substring(0,
14)=="errors-section")
                                break;

                        if(node.previousSibling !=null)
                        {
                                node = node.previousSibling;
                        }
                        else
                        {
                                node = node.parentNode;
                        }
                }
                if(node != null && node != undefined) {
                var id=node.getAttribute("id");
                if(id.substring(0,14)=="errors-section")
                        return id;
                }
                else
                        return "errors-page";
        }
}

function getParentTAG(idValue,tag){
        if(idValue!=null && idValue.parentNode.tagName == tag )
        {

                return idValue.parentNode;
        }
        else
        {
                var node = idValue.parentNode;
                while(node != null && node != undefined)
                {
                      if(node.tagName == tag)
                                break;

                        if(node.previousSibling !=null)
                        {
                                node = node.previousSibling;
                        }
                        else
                        {
                                node = node.parentNode;
                        }
                }
                if(node != null && node != undefined) {
                return node;
                }
                else
                        return null;
        }
}



//param:tagName
//function to retreive the immediate parent DIV with "id" attribute starting with "errors-section-xxx"
function getParentSectionDiv(idValue)
{
        if(document.getElementById(idValue)!=null && document.getElementById(idValue).parentNode.tagName=="DIV")
        {
		if(document.getElementById(idValue).parentNode.getAttribute("id") != null && document.getElementById(idValue).parentNode.getAttribute("id") != undefined && document.getElementById(idValue).parentNode.getAttribute("id") != '')
		{
                var id=document.getElementById(idValue).parentNode.getAttribute("id");
				if(id.substring(0,7)=="section"){
                 	       	    return id;
                		}
		}
        }
        //else
        {
                var node = document.getElementsByName(idValue)[0];
		if (node == null || node == undefined)
		{
			node = document.getElementById(idValue);
		} 	
				while(node != null && node != undefined)
                {
                        if(node.tagName == "DIV" && node.getAttribute("id") != null && node.getAttribute("id").substring(0,7)=="section")
                                break;
                        if(node.previousSibling !=null)
                        {
                                node = node.previousSibling;
                        }
                        else
                        {
                                node = node.parentNode;
                        }
                }
                if(node != null && node != undefined) {
                var id=node.getAttribute("id");
                if(id.substring(0,7)=="section")		
                        return id;
                }
                else
                        return "errors-page";
        }
}


function validation_execute( iForm )
{
  if( !validation_show_errors( validation_check_form( iForm ) ) )
    return;
  validation_form.submit();
}

function checkdate(objName)
{
	var datefield = objName;
	if (chkdate(objName) == false)
	 {
		//alert("That date is invalid.  Please try again.");
		datefield.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function chkdate(strDate)
{
	var strDatestyle = "US"; //United States date style
	//var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	//var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	//strDate = datefield.value;
	if (strDate.length < 1)
	{
		return true;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++)
	{
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1)
		{
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3)
			{
				err = 1;
				return false;
			}
			else
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}	
			booFound = true;
		   }
	}
	if (booFound == false)
	{
		if (strDate.length>5)
		{
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
	}
	if (strYear.length == 2)
	{
		strYear = '20' + strYear;
	}
	// US style
	if (strDatestyle == "US")
	{
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	intday = parseInt(strDay, 10);
	if (isNaN(intday))
	{
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth))
	{
		for (i = 0;i<12;i++)
		{
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase())
			{
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth))
		{
			err = 3;
			return false;
		}
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear) || (intYear < 1900 || intYear > 2100))
	{
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1)
	{
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
	{
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
	{
		err = 7;
		return false;
	}
	if (intMonth == 2)
	{
		if (intday < 1)
		{
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true)
		{
			if (intday > 29)
			{
				err = 9;
				return false;
			}
		}
		else
		{
			if (intday > 28)
			{
				err = 10;
				return false;
			}
		}	
	}
	return true;
}


function LeapYear(intYear)
{
	if (intYear % 100 == 0)
	{
		if (intYear % 400 == 0)
		{
			 return true;
		}
	}
	else
	{
		if ((intYear % 4) == 0)
		{
			 return true;
		}
	}
	return false;
}

function doDateCheck(from, to)
{
      var fromDate=new Date(from);
      var toDate=new Date(to);

      if (Date.parse(fromDate) > Date.parse(toDate))
              return false;
      else
              return null;
}

function doPasswordCheck(password,confirmpassword)
{
      if(password != confirmpassword)

           return false;
      else
	   return null;		
}

function doEmailCheck(email,confirmemail)
{
      if(email != confirmemail)

           return false;
      else
           return null;
}


function doCreditCardCheck(cc,type)
{

    var cctype=type;
    var ccno=cc;
    // Check if it is a master Card
    if(cctype=="002")
    {
        firstdig = cc.substring(0,1);
        seconddig = cc.substring(1,2);
        if((cc.length == 16) && (firstdig == 5) && (seconddig >= 1) && (seconddig <= 5))
           return null;
    }

    // Check if it is a Visa Card
    if(cctype=="001")
    {
       if (((cc.length == 16) || (cc.length == 13)) &&(cc.substring(0,1) == 4))
           return null;
    }

    // Check if it is a American Express Card
    if(cctype=="003")
    {
         firstdig = cc.substring(0,1);
         seconddig = cc.substring(1,2);
         if ((cc.length == 15) && (firstdig == 3) &&((seconddig == 4) || (seconddig == 7)))
             return null;
    }

    // Check if it is a Discover Card
    if(cctype=="004")
    {
        first4digs = cc.substring(0,4);
        if ((cc.length == 16) && (first4digs == "6011"))
            return null;
    }

    // Check if it is a Discover Card
    if(cctype=="ccothers")
    {
        if(isInteger(ccno))
           return null;
    }

    return false;
  }

function doExpiryDateCheck(month,year,monthyear)
{
    var strMonthArray = new Array(12);
    var intMonth;	
    strMonthArray[0] = "01";
    strMonthArray[1] = "02";
    strMonthArray[2] = "03";
    strMonthArray[3] = "04";
    strMonthArray[4] = "05";
    strMonthArray[5] = "06";
    strMonthArray[6] = "07";
    strMonthArray[7] = "08";
    strMonthArray[8] = "09";
    strMonthArray[9] = "10";
    strMonthArray[10] = "11";
    strMonthArray[11] = "12";
    for (i = 0;i<12;i++)
    {
        if (month.toUpperCase() == strMonthArray[i].toUpperCase())
        {
            intMonth = i+1;
            break;
         }
    }

    monthyear = monthyear.split(/_/);
    mon = monthyear[0];
	
    if(((monthyear[1] - year == 0) && (intMonth - monthyear[0] >= 0)) || (monthyear[1] - year < 0))
    {
        return true;
    }	
    else
        return false;

}


// Clear all background highlighting once we start validation 

function refreshStyles(form) {
    var fields = form.elements;
    for(var i=0;i<fields.length;i++){
        if(fields[i].className != null || fields[i].className != undefined)
        {
             var cName=fields[i].className;
             if(cName.indexOf("error") >= 0)
             {
                if(cName.lastIndexOf(" ") >= 0)
                {
                   cName=cName.substring(0,cName.lastIndexOf(" "));
                }
               fields[i].className=cName;
             }
        }
        var parentElement = getParentTAG(fields[i],"DIV");
        if(parentElement != null)
        {
           var cName=parentElement.className;
           if(cName.indexOf("error") > 0)
           {
              cName=cName.substring(0,cName.lastIndexOf(" "));
              parentElement.className = cName;
           }
        }
        parentElement = getParentTAG(fields[i],"P");
        if(parentElement != null)
        {
           var cName=parentElement.className;
           if(cName.indexOf("error") > 0)
           {
              cName=cName.substring(0,cName.lastIndexOf(" "));
              parentElement.className = cName;
           }
        }
    }
}

// Before validation is done, clear up any error messages shown in the errors-section

function refreshErrorDivs() {
        var divList= document.getElementsByTagName("div");
        for(var i=0;i<divList.length;i++) {
                if(divList[i].id.substring(0,14)=="errors-section"){
                        divList[i].innerHTML="";
                }
        }
}

//function getApplyValidation() {
//        var applyValidation = document.getElementById("applyValidation");
//        return applyValidation.value;
//}

function highlight(firstElement)
{
        if(validation_widgets[firstElement.name]=="expirydate"){
	//document.getElementsByName(monthiWidget)[0].style.border="1px solid red";
	}
        if(validation_widgets[firstElement.name]=="daterange"){

            var widgetName = firstElement.name;
            fromDateiWidget=widgetName.substring(0,widgetName.lastIndexOf('.'));

            document.getElementsByName(fromDateiWidget+".day")[0].style.border="1px solid red";
            document.getElementsByName(fromDateiWidget+".month")[0].style.border="1px solid red";
            document.getElementsByName(fromDateiWidget+".year")[0].style.border="1px solid red";

            toDateiWidget=widgetName.substring(0,widgetName.lastIndexOf('.')).replace('from','to');

            document.getElementsByName(toDateiWidget+".day")[0].style.border="1px solid red";
            document.getElementsByName(toDateiWidget+".month")[0].style.border="1px solid red";
            document.getElementsByName(toDateiWidget+".year")[0].style.border="1px solid red";
          }
        else
	{
	//firstElement.style.border = "1px solid red";	
	//alert(document.getElementById(firstElement)!=null && document.getElementById(firstElement).parentNode.tagName=="TR");
        //if(document.getElementById(firstElement)!=null && document.getElementById(firstElement).parentNode.tagName=="TR" )
        //{
	//	alert("parentNode" + document.getElementById(idValue).parentNode);
        //        document.getElementById(idValue).parentNode.className = "errorHighlight";
        //}
        if(firstElement.className != null && firstElement.className != undefined && firstElement.className != '' && firstElement.className.indexOf("error") <= 0)
        {
            firstElement.className = firstElement.className + " error";
        }
        else if(firstElement.className.indexOf("error") <= 0)
        {
            firstElement.className = firstElement.className + "unknown error";
        }
        var parentElement = getParentTAG(firstElement,"DIV");
        if(parentElement != null && parentElement.className.indexOf("error") <= 0)
                parentElement.className = parentElement.className + " error";
	parentElement ="";
        parentElement = getParentTAG(firstElement,"P");
        if(parentElement != null && parentElement.className.indexOf("error") <= 0)
                parentElement.className = parentElement.className + " error";
	

	}
}


// Script for ServerSide error display
var errorid;
function serverSideErrorDisplay(formId,errMsg)
{
      var errorDivId;	
        var sectionName="errors-section";
        var node = document.getElementById(formId);
	
        if(node == null)
        {
                node = document.getElementsByName(formId)[0];
        }
        if(node != null && node.tagName=="FORM" )
        {
	    getErrorDiv(node);
	}
	errorDivId = errorid;

	if(errorDivId == null)
	{
	        document.getElementById("errors-section");
               // document.getElementById("errors-page").className = "page-errors";
                document.getElementById("errors-section").innerHTML=errMsg;
                ShowContent("errors-section");	
	}
        else {
		document.getElementById(errorDivId).className = "section-errors";	
		document.getElementById(errorDivId).innerHTML=errMsg;
		ShowContent(errorDivId);
	}
}

function getErrorDiv(node)
{
	var nodelist=node.childNodes;
          	
	if (nodelist != null)
	{
	var i;
	for(i=0;i < nodelist.length ;i++)
	{
		if(nodelist[i].tagName == 'DIV')
		{
                   nodeid=nodelist[i].getAttribute("id");
                   if(nodeid.substring(0,14) == "errors-section")
		   {
			errorid = nodeid;
                   }
		}
	        getErrorDiv(nodelist[i]);
        }
	}
	return errorid;	
}
