// -- (c) 2003 Infogate AB
// -- CVS revision: $Revision: 1.5 $


// -- Disclaimer
// -- --------------------
// -- This script may not work as intended on older browsers
// --
// -- This script is tested and verified in the following browsers
// -- Microsoft Internet Explorer 6.0
// -- Netscape 7.0


// -- Requirements
// -- --------------------
// -- This script requires 'insert_DM_standard.js' to work.


// -- How to use
// -- --------------------
// -- Create new object
// -- var obj = new DM_form( document.myForm );
// --
// -- Add conditions
// -- obj.setEmail( "myField" ); - verifies that, if the field isn't empty, it's in an email format.
// -- obj.setMandatory( "myField" ); - makes the field mandatory
// -- obj.setNumeric( "myNumericField" ); - requires a numeric input, digits between 0 and 9, ',' and '.' are allowed
// -- obj.setFixedLenght( "myZipCode", 5 ) - this field must contain 5 characters
// -- obj.setCopyTo( "myField", "myFieldCopy" ) - copies the value from one field to a textfield or textarea
// -- obj.setMandatoryIf( "myField", "myOtherField" ) - the values in these two fields must be the same
// -- obj.setCompare( "myField", "myOtherField" ) - the textvalue in 'myField' must be 'myOtherField'
// -- obj.setRegExp( "myField", "????-??-??" ) - the value in 'myField' must match the pattern, in this example '2003-03-06' would be a match
// -- obj.setCopyToIf( "myField", "myFieldCopy", "Field", "Value" ) - copies the value from one field to a textfield or textarea if Field == Value


// -- How to validate
// -- --------------------
// -- obj.validate(), returns true or false


// -- Errorcontrol
// -- --------------------
// -- obj.getErrorField() returns fieldname
// -- obj.getErrorCondition() returns which condition failed (int)
// -- obj.getErrorConditionText() returns which condition failed (text)
// --
// -- obj.enableErrorAlert(), alerts() errormessages if submitted.
// -- example:
// -- obj.setEmail("myField", "The field 'myField' isn't a valid emailformat" ); - If the value in "myField" isn't a email,
// -- the text will popup if obj.enableErrorAlert() has been called.
// -- 
// -- obj.disableErrorAlert() - do not alert() errors (this is the default value)





// -- File identifier
var insert_DM_form = true;
// --------------------------------------------------

function DM_form( formObj ) {
			
			// -- All needed includes present?
			if( !(window.insert_DM_standard) )
				alert("DM error: Script missing!\n\nThis script needs 'insert_DM_standard.js' to work correctly.");
			// --------------------------------------------------
			
			
			
			// -- Creating objects and variables
			var errorField = "";
			var errorCondition = 0;
			var errorConditionText = ["","email","mandatory","numeric","fixedlength","copyto","addto","mandatoryif","compare","regexp","copytoif"];
			var errorMsgArray = new Array();
			var errorAlert = false;
			
			var arrayField = new Array();
			var arrayCondition = new Array();
			var arrayType = new Array();
			var arrayParamOne = new Array();
			var arrayParamTwo = new Array();
			var arrayParamThree = new Array();
			
			var fieldCount = 0;
			// --------------------------------------------------
			
			
			
			// -- Initiating condition ids
			var
				conditionEmail = 1,
				conditionMandatory = 2,
				conditionNumeric = 3,
				conditionFixedLength = 4,
				conditionCopyTo = 5,
				conditionAddTo = 6,
				conditionMandatoryIf = 7,
				conditionCompare = 8,
				conditionRegExp = 9;
				conditionCopyToIf = 10;
			// --------------------------------------------------
			
			
			
			// -- Register condition
			this.registerConditions = function( field, condition, msg, paramOne, paramTwo, paramThree ) {
				arrayField[fieldCount] = formObj[field];
				arrayCondition[fieldCount] = condition;
				errorMsgArray[ fieldCount ] = msg;
				arrayType[fieldCount] = this.getType( formObj[field] );
				arrayParamOne[fieldCount] = paramOne;
				arrayParamTwo[fieldCount] = paramTwo;
				arrayParamThree[fieldCount] = paramThree;
				fieldCount++;
			}
			// --------------------------------------------------
			
			
			
			// -- Functions
			this.setEmail = function( field, msg ) {			
				this.registerConditions( field, conditionEmail, msg );
			}
			
			this.setMandatory = function( field, msg ) {
				this.registerConditions( field, conditionMandatory, msg );
			}
			
			this.setNumeric = function( field, msg ) {
				this.registerConditions( field, conditionNumeric, msg );
			}
			
			this.setFixedLength = function( field, paramOne, msg ) {
				this.registerConditions( field, conditionFixedLength, msg, paramOne );
			}
			
			this.setCopyTo = function( field, paramOne, msg ) {
				this.registerConditions( field, conditionCopyTo, msg, paramOne );
			}
			
			this.setAddTo = function( field, paramOne, msg ) {
				this.registerConditions( field, conditionAddTo, msg, paramOne );
			}
			
			this.setMandatoryIf = function( field, paramOne, paramTwo, msg ) {
				this.registerConditions( field, conditionMandatoryIf, msg, paramOne, paramTwo );
			}
			
			this.setCompare = function( field, paramOne, msg ) {
				this.registerConditions( field, conditionCompare, msg, paramOne );
			}
			
			this.setRegExp = function( field, paramOne, msg ) {
				this.registerConditions( field, conditionRegExp, msg, paramOne );
			}
			
			this.setCopyToIf = function( field, paramOne, paramTwo, paramThree, msg ) {
				this.registerConditions( field, conditionCopyToIf, msg, paramOne, paramTwo, paramThree );
			}
			// --------------------------------------------------
			
			
			
			// -- Internal validate functions			
			this.validateEmail = function( index ) {
				
				var address = this.getValue( arrayField[index] );
				var cont = true;
				address.toString();
				address = address.trim();
				
				if( ! address.length )
					return true;
					
				var result = true;
				var posAt = address.indexOf("@");
				var posLastAt = address.lastIndexOf("@");
				var posDot = address.lastIndexOf(".");
				var length = address.length;
				
				// -- Only one '@' allowed
				if( posAt < 1 || posAt != posLastAt )
					result = false;
				
				// -- A '.' must be present and not to far at the end
				if( posDot == -1 || (posDot+2) >= length )
					result = false;
				
				// -- No '.' next to '@'
				if( (posAt + 1) >= posDot )
					result = false;
				
				// -- No spaces
				if( address.indexOf(" ") != -1 )
					result = false;
				
				if( !result )
					this.reportError( index );
				
				return result;
			}
			
			this.validateMandatory = function( index ) {
				
				var result = false;
				var value = this.getValue( arrayField[index] );
				
				if( value.length > 0 ) {
					result = true;
				} else {
					this.reportError( index );
				}
				
				return result
			}
			
			this.validateNumeric = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				
				value.toString();
				value = value.trim();
				
				if( !value.isNum() ) {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			
			this.validateFixedLength = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				
				value.toString();
				value = value.trim();
				
				if( value.length > 0 && value.length != arrayParamOne[index] ) {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			
			this.validateCopyTo = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				var type = this.getType( formObj[ arrayParamOne[index] ] );
				
				if( type == "hidden" || type.substring(0,4) == "text" ) {
					formObj[ arrayParamOne[index] ].value = value;
				} else {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			
			this.validateAddTo = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				var type = this.getType( formObj[ arrayParamOne[index] ] );
				
				if( type == "hidden" || type.substring(0,4) == "text" ) {
					var targetValue = formObj[ arrayParamOne[index] ].value;
					if( targetValue.length )
						targetValue += " ";
					targetValue += value;
					
					formObj[ arrayParamOne[index] ].value = targetValue.trim();
				} else {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			
			this.validateMandatoryIf = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				
				if( formObj[ arrayParamOne[index] ].value == arrayParamTwo[index] ) {
					if( value.length == 0 ) {
						result = false;
						this.reportError( index );
					}
				}
				
				return result
			}
			
			this.validateCompare = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				
				if( value != arrayParamOne[index] ) {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			
			this.validateRegExp = function( index ) {
			
				var sCount = 0;
				var rCount = 0;
				var regexp = arrayParamOne[ index ];
				var value = this.getValue( arrayField[index] );
				var sLength = value.length;
				var rLength = regexp.length;
				var isMatch = true;
				var doLoop = true;
				var sChar = "", rChar = "";
				
				if( ! value.length )
					return true;
					
				while( doLoop ) {
					
					sChar = value.substring( sCount, sCount+1 );
					rChar  = regexp.substring( rCount, rCount+1 );
					
					if( rChar == "?" && sChar!="" ) {
						// -- If a '?' is found, move one step ahead
						sCount++;
						rCount++;
					} else if( rChar == "*" ) {
						
						// -- Find next char to compare with (after all '*' and '?') in regexp
						while( doLoop && ( regexp.substring( rCount, rCount+1 ) == "*" || regexp.substring( rCount, rCount+1 ) == "?" ) ) {
							
							if( regexp.substring( rCount, rCount+1 ) == "*" ) {
								// -- If another '*' is found, ignore it
								rCount++;
							} else if( regexp.substring( rCount, rCount+1 ) == "?" ) {
								// -- If a '?' is found, check if string is long enough
								if( sCount == sLength ) {
									doLoop = false;
									isMatch = false;
								}
								sCount++;
								rCount++;
							}
						}
						// --------------------------------------------------
						
						// -- Find the char in the string
						while( doLoop && value.substring( sCount, sCount+1 ) != regexp.substring( rCount, rCount+1 ) ) {
							sCount++;
							
							if( sCount > sLength ) {
								doLoop = false;
								isMatch = false;
							}
						}
						// --------------------------------------------------
						
					} else if( sChar == rChar ) {
						// -- If the char in the string matches the char in the regexp, move one step ahead
						sCount++;
						rCount++;
					} else {
						// -- If not this is not a match
						doLoop = false;
						isMatch = false;
					}
					
					// -- No more regexp?
					if( rCount > rLength) {
						doLoop = false;
					}
				}
				
				// -- Error control
				if( !isMatch )
					this.reportError( index );
					
				return isMatch;
			}
			
			this.validateCopyToIf = function( index ) {
				
				var result = true;
				var value = this.getValue( arrayField[index] );
				var type = this.getType( formObj[ arrayParamOne[index] ] );
				
				if( type == "hidden" || type.substring(0,4) == "text" ) {
				
					if( formObj[ arrayParamTwo[index] ].value == arrayParamThree[index] ) {
						formObj[ arrayParamOne[index] ].value = value;
					}
				} else {
					result = false;
					this.reportError( index );
				}
				
				return result;
			}
			// --------------------------------------------------
			
			
			
			// -- Main (external) validate function
			this.validate = function() {
				
				var formValid = true;
				for( count = 0; count < fieldCount; count++ ) {
					
					if( formValid ) {
						
						switch( arrayCondition[ count ] ) {
						
							case conditionEmail:
								formValid = this.validateEmail( count );
								break;
								
							case conditionMandatory:
								formValid = this.validateMandatory( count );
								break;
							
							case conditionNumeric:
								formValid = this.validateNumeric( count );
								break;
							
							case conditionFixedLength:
								formValid = this.validateFixedLength( count );
								break;
							
							case conditionCopyTo:
								formValid = this.validateCopyTo( count );
								break;
							
							case conditionAddTo:
								formValid = this.validateAddTo( count );
								break;
							
							case conditionMandatoryIf:
								formValid = this.validateMandatoryIf( count );
								break;
							
							case conditionCompare:
								formValid = this.validateCompare( count );
								break;
							
							case conditionRegExp:
								formValid = this.validateRegExp( count );
								break;
							
							case conditionCopyToIf:
								formValid = this.validateCopyToIf( count );
								break;
							
						}
					}
				}
				return formValid;
			}
			// --------------------------------------------------
			
			
			
			// -- Error control
			this.reportError = function( index ) {
				errorField = arrayField[ index ].name;
				errorCondition = arrayCondition[ index ];
				this.doErrorAlert( index );
			}
			
			this.getErrorField = function() {
				var temp = errorField;
				errorField = 0;
				return temp;
			}
			this.getErrorCondition = function() {
				var temp = errorCondition;
				errorCondition = 0;
				return temp;
			}
			this.getErrorConditionText = function() {
				return errorConditionText[ errorCondition ];
			}
			
			this.enableErrorAlert = function() {
				errorAlert = true;
			}
			this.disableErrorAlert = function() {
				errorAlert = false;
			}
			this.doErrorAlert = function( index ) {
				if( errorAlert && errorMsgArray[ index ] ) {
					alert( errorMsgArray[ index ] );
				}
			}
			// --------------------------------------------------
			
			
			
			// -- Handle field properties
			this.getType = function( fieldObj ) {
								
				if( fieldObj.type ) {
					return fieldObj.type;
				} else if( fieldObj[0].type ) {
					return fieldObj[0].type;
				}
			}
			
			this.getValue = function( fieldObj ) {
				
				var type = this.getType( fieldObj );
				var value = "";
				
				if( type == "hidden" || type.substring(0,4) == "text" ) {
				
					// -- Textfield or textarea
					value = fieldObj.value;
					
				} else if( type == "checkbox" || type == "radio" ) {
					
					// -- Checkbox or radiobutton
					if( fieldObj.length ) {
						// -- Multiple checkboxes or radiobuttons
						for( count = 0; count < fieldObj.length; count++ ) {
							if( fieldObj[ count ].checked ) {
								if( value.length )
									value += " ";
								value += fieldObj[ count ].value;
							}
						}
					} else {
						// -- Single checkbox or radiobutton
						if( fieldObj.checked )
							value = fieldObj.value;
					}
				} else if( type.substring(0,6) == "select" ) {
				
					// -- Selectboxes
					type = type.split("-");
					if( type[1] == "one" ) {
						// -- Single choice selectbox
						value = fieldObj.options[fieldObj.selectedIndex].value;
					} else if( type[1] == "multiple" ) {
						// -- Multiple choice selectbox
						for( count = 0; count < fieldObj.length; count++ ) {
							if( fieldObj[ count ].selected ) {
								if( value.length )
									value += " ";
								value += fieldObj[ count ].value;
							}
						}
					}
				}
				
				return value;
			}
			// --------------------------------------------------
		}