MAJOR_VERSION = "Validator-1.0";
MINOR_VERSION = parseFloat(("$Revision: 00150 $").match(/\d+/)) - 100000;

IsLoaded = false;
if (typeof(LR_LibCore) != 'undefined') {
	IsLoaded = (LR_LibCore.NewLibrary(MAJOR_VERSION, MINOR_VERSION, "Inheritance-2.0", "WebDocument-2.0") != null) ? true : false;
}

if ((typeof(LR_LibCore) != 'undefined' && IsLoaded) || (typeof(LR_LibCore) == 'undefined')) {



LR_DocumentValidator = Class.create();

LR_DocumentValidator = Class.extend ({
	initialize: function() {
		// Debug
		this.Debug = false;

		// Properties
		this.getNotify_StyleBG = function () { return this.Notify_StyleBG };
		this.setNotify_StyleBG = function (vNewValue) { this.Notify_StyleBG = vNewValue; };

		this.getMaxErrors = function () { return this.MaxErrors };
		this.setMaxErrors = function (vNewValue) { this.MaxErrors = vNewValue; };

		this.MaxErrors = 10;
		this.Notify_StyleBG = '#FFFF99';
		
		this.Items = new Array();
		this.Errors = new Array();
	},

	Validator: function(Form, Name) {
		var Found = false;
		var I_Found, I_New;
		
		if (!(this.Items[Form])) {
			if (this.Debug == true) alert('Added ['+ Form +'] Form.');
			this.Items[Form] = new Array();
		}

		this.Items[Form].Each(function(el, i) {
			if (el.Name == Name)	{
				Found = true;
				I_Found = i;
			}
		})

		if (!(Found)) {
			if (this.Debug == true) alert('Added ['+ Form +'_'+ Name +'] Validator.');

			I_New = this.Items[Form].length;
			this.Items[Form][this.Items[Form].length] = new LR_Validator(Form, Name);

			return this.Items[Form][I_New];
		} else {
			return this.Items[Form][I_Found];
		}
	},
	

	Validate: function() {
		var i, x, result;

		//alert('3.1) - Quanti errori ha LR_WebDocument prima di essere ripulito? '+ this.Errors.length);
		this.Errors.Clear();
		//alert('3.2) - Quanti errori ha LR_WebDocument? '+ this.Errors.length);

		this.Items.Each(function (elX, i) {
			//alert('Forms['+ i +']');
			elX.Each(function (elY, y) {
				result = elY.Validate();
				if (result.state == true)	this.Errors.push(result.errors);
			}, this)
		}, this)

		//alert('3.3) - Quanti errori ha LR_WebDocument? '+ this.Errors.length);		

		// Controlla gli errori interlacciati tra i campi del Document
		if (this.Compute) this.Compute();
	},

	HasErrors: function() {
		var i, y, result = false;

		//alert('1.1) - Quanti errori ha LR_WebDocument? '+ this.Errors.length);
		
		this.Items.Each(function (elX, i) {
			//elX.Each(function (elY, y) {
			elX.Some(function (elY, y) {
				if (elY.HasErrors()) {
					//alert(elY.Name +' errato');
					result = true; return true;
				}
			}, this)
		}, this)
		
		//alert('result:'+ result);
		//alert('1.2) - Quanti errori ha LR_WebDocument? '+ this.Errors.length);
		if (this.Errors.length > 0) return true; else return result;
	},

	ShowError: function() {
		var TotalErrors = 0;
		var i, y, Message = '';
	
		Message = 'Sono stati riscontrati i seguenti errori:\n';
		Message += '---------------------------------------------\n\n'

		// Controlla gli errori sul Document
		this.Errors.Each(function (el, i) {
			TotalErrors++;
			if (TotalErrors <= this.MaxErrors) Message += '- ' + el + '\n';
		}, this)
		
		// Visualizza gli errori a video
		if (TotalErrors > this.MaxErrors) {
			Message += '\n'
			Message += '- [ ...Altri errori non visualizzati... ]\n'
		}
		Message += '\n'
		Message += 'Errori riscontrati: '+ TotalErrors +'\n'

		alert (Message);
	},
	
	ShowNotify: function() {
		var tmpColor = this.Notify_StyleBG;

		this.Items.Each(function (elY, y) {
			elY.Each(function (elX, x) {
				if (this.Debug == true) {
					alert('Class LR_Validator - Function ShowNotify\n' +
						  'Constructor [Form: '+ i +' - Name: '+ elX.Name +']\n' +
						  'HasErrors: '+ elX.HasErrors() );
				}
				
				if (elX.HasErrors()) {
					elX.Each(function(el, i) { this.CSS('backgroundColor', tmpColor); }, elX);
				}
				
			}, this)
		})
	},

	AddError: function(ErrorMessage) {
		if (this.Debug == true) alert('Debug Message\n' + ErrorMessage);
		this.Errors.push(ErrorMessage);
	}
	
})





LR_Validator = Class.create();

LR_Validator = Class.extend(LR_WebControl, {

	initialize: function(Form, Name) {
		this.Form = Form;
		this.Name = Name;

		// Debug
		this.Debug = false;

		// Properties
		this.getRequired = function () { return this.Required };
		this.setRequired = function (vNewValue) { this.Required = vNewValue; };

		this.getDescription = function () { return this.Description };
		this.setDescription = function (vNewValue) { this.Description = vNewValue; };

		this.getErrorMessage = function () { return this.errorMessage };
		this.setErrorMessage = function (vNewValue) { this.errorMessage = vNewValue; };

		this.getErrors = function () { return this.Err };

		//this.Min = Min;				//Non sono ancora certo se inserirlo
		//this.Max = Max;				//Non sono ancora certo se inserirlo
		//this.MinLength				//String - Lunghezza minima
		//this.MaxLength = MaxLength;	//String - Lunghezza massima
		
		this.Err = new Array();
		
		//initialize the Control
		this.parent(Form, Name);
	},


    Validate: function() {
		var result;
		 
		//this.Err = new Array();
		this.Err.Clear();

		if (!(this.Description)) this.Description = this.Name;

		if ((this.getRequired() == true) || (this.GetValue() != "")) {

			if (this.DataType == 'Time') {				// matches 5:04 or 12:34 but not 75:83
				if ( this.GetValue().match(/^([1-9]|1[0-2]):[0-5]\d$/) ) {
					this.AddError('Campo ['+ this.Description +']: formato Ora non corretto.', this.Err);
				 }
			} else if (this.DataType == 'Date') {		// Date xx/xx/xxxx
				if ( !(this.GetValue().match(/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/)) ) {
						/*
						sub isvaliddate {
						  my $input = shift;
						  if ($input =~ m!^((?:19|20)\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$!) {
							# At this point, $1 holds the year, $2 the month and $3 the day of the date entered
							if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) {
							  return 0; # 31st of a month with 30 days
							} elsif ($3 >= 30 and $2 == 2) {
							  return 0; # February 30th or 31st
							} elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) {
							  return 0; # February 29th outside a leap year
							} else {
							  return 1; # Valid date
							}
						  } else {
							return 0; # Not a date
						  }
						}
						*/
					this.AddError('Campo ['+ this.Description +']: formato Data non corretto.', this.Err);
				}
			} else if (this.DataType == 'Email') {		//matches email
				if ( !(this.GetValue().match(/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/)) ) {
					this.AddError('Campo ['+ this.Description +']: E-Mail non corretta.', this.Err);
				}
			} else if (this.DataType == 'IPAddress') {	// IP Address
				if ( !(this.GetValue().match(/^((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])$/)) ) {
					this.AddError('Campo ['+ this.Description +']: indirizzo IP non corretto.', this.Err);
				}
			} else if (this.DataType == 'Path') {		// matches Windows Path or UNC
				if ( !(this.GetValue().match(/^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\\/:\*\?"\|<>\. ](([^\\\/:\*\?"\|<>\. ])|([^\\\/:\*\?"\|<>]*[^\\\/:\*\?"\|<>\. ]))?))\\)*[^\\\/:\*\?"\|<>\. ](([^\\\/:\*\?"\|<>\. ])|([^\\\/:\*\?"\|<>]*[^\\\/:\*\?"\|<>\. ]))?$/)) ) {
					this.AddError('Campo ['+ this.Description +']: sintassi del percorso non corretta', this.Err);
				}
			} else if (this.DataType == 'Integer') {
				if ( !(this.GetValue().match(/^\d*$/)) ) {
					this.AddError('Campo ['+ this.Description +']: accetta solo numeri interi positivi', this.Err);
				}
			} else if (this.DataType == 'SignedInteger') {
				if ( !(this.GetValue().match(/^[-+]?[1-9]+[0-9]*$/)) ) {
					this.AddError('Campo ['+ this.Description +']: accetta solo numeri interi', this.Err);
				}
			} else if (this.DataType == 'Decimal') {
				if ( !(this.GetValue().match(/^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) ) {
					this.AddError('Campo ['+ this.Description +']: accetta solo numeri decimali positivi', this.Err);
				}
			} else if (this.DataType == 'SignedDecimal') {
				if ( !(this.GetValue().match(/^[-+]?\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/)) ) {
					this.AddError('Campo ['+ this.Description +']: accetta solo numeri decimali', this.Err);
				}
			} else if (this.DataType == 'Currency') {	// matches 17.23 or 14,281,545.45 or ...
				if (!(this.GetValue().match(/\d{1,3}(,\d{3})*\.\d{2}/))) {
					this.AddError('Campo ['+ this.Description +']: valore valuta non corretto', this.Err);
				}
				if (this.Min) {
					if (!(this.GetValue() >= this.Min)) {	this.AddError('Campo ['+ this.Description +']: il campo deve contenere un valore superiore a '+ this.Min, this.Err); }
				}
				if (this.Max) {
					if (!(this.GetValue() <= this.Max)) { this.AddError('Campo ['+ this.Description +']: il campo deve contenere un valore inferiore a '+ this.Max, this.Err); }
				}
			} else if (this.DataType == 'String') {
				if (this.MinLength) { if (!(this.GetValue().length >= this.MinLength)) this.AddError('Campo ['+ this.Description +']: il campo deve contenere un valore lungo almeno '+ this.MinLength +' caratteri', this.Err); }
				if (this.MaxLength) { if (!(this.GetValue().length <= this.MaxLength)) this.AddError('Campo ['+ this.Description +']: il campo deve contenere un valore non piu\' lungo di '+ this.MaxLength +' caratteri', this.Err); }
			} else {
				if (this.GetValue() == "") { this.AddError('Campo ['+ this.Description +']: e\' obbligatorio inserire un valore', this.Err); };
			}

			if ((this.Compute) && (this.GetValue() != "")) {
				var ComputeResult = this.Compute();
				if (ComputeResult != '') { this.Err.push(ComputeResult); }
			}
		}

		if (this.Debug == true) {
			alert('Class LR_Validator - Function Validate\n' +
				  'Constructor [Form: '+ Form +' - Name: '+ Name +']\n' +
				  'Description: '+ this.Description +'\n' +
				  'Required: '+ this.getRequired() +'\n' +
				  'DataType: '+ this.DataType + '\n' +
				  'Errors.length: '+ this.Err.length);
		}

		if (this.Err.length > 0) result = {state: true, errors: this.Err}; else result = {state: false};

		if (this.Debug == true) {
			alert(this.Name +'.Validate(): \n'+
					'Result {'+ result.state +',\n'+
					result.errors);
		}
		
		return result;
    },

	HasErrors: function() {
		if (this.Err.length > 0) return true; else return false;
	},

	AddError: function(ErrorMessage, Errors) {
		if (this.Debug == true) alert('Debug Message\n' + ErrorMessage);
		if (typeof(this.getErrorMessage()) != 'undefined') ErrorMessage = this.getErrorMessage();
		Errors.push(ErrorMessage);
		return Errors;
	}

})



}
