
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES THE VALIDATOR CLASS AND 2 FUNCTIONS FOR CHECKING FORM MANDATORY FIELDS //////////
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////

DCsValidator = Class.create();

DCsValidator.prototype={

	/////////////////////////////////////////////////////////////////////////////////////////
	// INITIALIZATION ///////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////
	initialize: function(options) {
		this.options=options;

		// CHECK ALL PARAMETERS /////////////////////////////////////////////////////////////
		if (!options)
			alert("DCsValidator ERROR: you didn't set any parameters for the object.");
		// CHECK MANDATORY PARAMETERS ///////////////////////////////////////////////////////
		// input id
		if (!this.options.inputId)
			alert("DCsValidator ERROR: you didn't set the 'inputId' parameter for the object.");
		// input type
		if (!this.options.inputType)
			alert("DCsValidator ERROR: you didn't set the type of the input.");

		input=$(this.options.inputId);
		input.validator=this;

		Event.observe(input, 'blur', this.blurAction.bind(input), false);
		Event.observe(input, 'keypress', this.keypressAction.bind(input), false);



	},


	/////////////////////////////////////////////////////////////////////////////////////////
	// VALIDATION ///////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////
	validateField:function() {

		fieldOk=1; msgType=new Array();

		/////////////////////////////////////////////////////////////////////////////////////
		// TYPE SPECIFIC VALIDATEIONS ///////////////////////////////////////////////////////
		// these will be done depending on the input's type /////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////

		switch (this.validator.options.inputType.toUpperCase()) {

			// ----------------------------------------------------------------------------------
			// NUMERIC VALIDATIONS
			// ----------------------------------------------------------------------------------

			case 'NUMERIC': {

				// VALIDATE NUMERIC INPUT ///////////////////////////////////////////////////////
				var invalidInput=0;

				if (isNaN(this.value)) invalidInput=1;
				if (isNaN(parseInt(this.value))) invalidInput=1;
				if (isNaN(parseFloat(this.value))) invalidInput=1;

				if (invalidInput) {
					if (this.validator.options.dontEmptyOnBlur) {
						fieldOk=0; msgType=msgType.concat(['invalidNumeric']);
					}
					else
						this.value='';
				}

				// if input is really numeric, start the other validations
				else {

					// INPUT ROUNDING ///////////////////////////////////////////////////////////
					if (this.validator.options.rounding) {
						var precisionDecimalValue=Math.pow(10,this.validator.options.rounding);
						this.value=Math.round(this.value*precisionDecimalValue)/precisionDecimalValue;
					}


					// VALIDATE MIN AND MAX VALUES //////////////////////////////////////////////////
					if (this.validator.options.minValue!=null && Number(this.value)<Number(this.validator.options.minValue)) {
						fieldOk=0; msgType=msgType.concat(['invalidMinValue']);
					}
					if (this.validator.options.maxValue!=null && (Number(this.value)>Number(this.validator.options.maxValue))) {
						fieldOk=0; msgType=msgType.concat(['invalidMaxValue']);
					}

					// VALIDATE POSITIVE / NEGATIVE NUMBERS /////////////////////////////////////////
					if (this.validator.options.zeroOperator=='>')
						if (Number(this.value)<=0) {
							fieldOk=0; msgType=msgType.concat(['invalidStrictPositive']);
						}
					if (this.validator.options.zeroOperator=='>=')
						if (Number(this.value)<0) {
							fieldOk=0; msgType=msgType.concat(['invalidPositive']);
						}
					if (this.validator.options.zeroOperator=='<')
						if (Number(this.value)>=0) {
							fieldOk=0; msgType=msgType.concat(['invalidStrictNegative']);
						}
					if (this.validator.options.zeroOperator=='<=')
						if (Number(this.value)>0) {
							fieldOk=0; msgType=msgType.concat(['invalidNegative']);
						}
				}
				break;
			}

			// ----------------------------------------------------------------------------------
			// STRING VALIDATIONS
			// ----------------------------------------------------------------------------------

			case 'STRING': {

				// TRANSFORM TO UPPERCASE ///////////////////////////////////////////////////////
				if (this.validator.options.uppercase==true)
					this.value=this.value.toUpperCase();

				break;
			}

			// ----------------------------------------------------------------------------------
			// EMAIL VALIDATION
			// ----------------------------------------------------------------------------------

			case 'EMAIL': {
				// set regular expression filter and then check mail
				filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; // set filter
				if (!filter.test(this.value)) {
					fieldOk=0; msgType=msgType.concat(['invalidEmail']);
				}

				break;
			}

			// ----------------------------------------------------------------------------------
			// DATE VALIDATION
			// ----------------------------------------------------------------------------------

			case 'DATE': {
				dateValidation(this, this.validator.options.standard);
				break;
			}
		}

		/////////////////////////////////////////////////////////////////////////////////////
		// UNIVERSAL VALIDATIONS ////////////////////////////////////////////////////////////
		// these will be done regardless of the input's type or for more than one type //////
		/////////////////////////////////////////////////////////////////////////////////////

		// VALIDATE MIN AND MAX INPUT LENGTH ////////////////////////////////////////////////
		if (this.validator.options.minLength && this.value.length<this.validator.options.minLength) {
			fieldOk=0; msgType=msgType.concat(['invalidMinLength']);
		}
		if (this.validator.options.maxLength && this.value.length>this.validator.options.maxLength) {
			fieldOk=0; msgType=msgType.concat(['invalidMaxLength']);
		}

		// CHECK INPUT EXACT LENGTH /////////////////////////////////////////////////////////
		if (this.validator.options.fixLength) {
			if (this.value.length!=this.validator.options.fixLength) {
				fieldOk=0; msgType=msgType.concat(['invalidFixLength']);
			}
		}


		/////////////////////////////////////////////////////////////////////////////////////
		// CREATE FUNCTION RETURN ///////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////

		// send the variable that indicates if the field is ok
		// and the type of the warning message to display to the user
		response= {
			valid: fieldOk,
			messages: msgType
		}

		return response;
	},


	/////////////////////////////////////////////////////////////////////////////////////////
	// COMPLEMENTARY FUNCTIONS //////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////

	// SHOW ALERTS/ERRORS ///////////////////////////////////////////////////////////////////
	inputAlert:function(message, width, color, posX, posY){

		// set DEFAULTS
		width=200; color="#000000";
		posX=$(this).getLeft(); posY=$(this).getTop()+$(this).getHeight();

		// get USER PARAMETERS (if set)
		if (this.validator.options.msgWidth)
			width=this.validator.options.msgWidth;

		if (this.validator.options.msgColor)
			color=this.validator.options.msgColor;

		if (this.validator.options.msgOffsetX)
			posX=posX+this.validator.options.msgOffsetX;

		if (this.validator.options.msgOffsetY)
			posY=posY+this.validator.options.msgOffsetY;

		overlib(message, FIXX, posX, FIXY, posY, WIDTH, width);
		setTimeout('nd()', 4000);
	},

	// COMPUTE FINAL WARNING MESSAGE FROM AN ARRAY OF MESSAGE TYPES ///////////////////////////
	generateUserMsg:function(messages){

		// initialize msgContent and the separator of messages
		msgContent=''; separator="<br />";

		// form string of message types
		for (i=0; i<messages.length; i++) {
			// get message type
			thisMsgType=messages[i];


			// check for user message
			switch (thisMsgType) {
				case 'invalidNumeric': {

					if (this.validator.options.msg_invalidNumeric) {
						msgContent=msgContent+this.validator.options.msg_invalidNumeric+separator;
					}
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

				case 'invalidMinValue': {

					if (this.validator.options.msg_invalidMinValue) {
						msgContent=msgContent+this.validator.options.msg_invalidMinValue+separator;
					}
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+this.validator.options.minValue+separator;

					break;
				}

				case 'invalidMaxValue': {
					if (this.validator.options.msg_invalidMaxValue)
						msgContent=msgContent+this.validator.options.msg_invalidMaxValue+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+this.validator.options.maxValue+separator;

					break;
				}

				case 'invalidPositive': {

					if (this.validator.options.msg_invalidPositive) {
						msgContent=msgContent+this.validator.options.msg_invalidPositive+separator;
					}
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

				case 'invalidStrictPositive': {
					if (this.validator.options.msg_invalidStrictPositive)
						msgContent=msgContent+this.validator.options.msg_invalidStrictPositive+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

				case 'invalidNegative': {

					if (this.validator.options.msg_invalidNegative) {
						msgContent=msgContent+this.validator.options.msg_invalidNegative+separator;
					}
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

				case 'invalidStrictNegative': {
					if (this.validator.options.msg_invalidStrictNegative)
						msgContent=msgContent+this.validator.options.msg_invalidStrictNegative+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

				case 'invalidMinLength': {
					if (this.validator.options.msg_invalidMinLength)
						msgContent=msgContent+this.validator.options.msg_invalidMinLength+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+this.validator.options.minLength+separator;

					break;
				}

				case 'invalidMaxLength': {
					if (this.validator.options.msg_invalidMaxLength)
						msgContent=msgContent+this.validator.options.msg_invalidMaxLength+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+this.validator.options.maxLength+separator;

					break;
				}

				case 'invalidFixLength': {
					if (this.validator.options.msg_invalidFixLength)
						msgContent=msgContent+this.validator.options.msg_invalidFixLength+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+this.validator.options.fixLength+separator;

					break;
				}

				case 'invalidEmail': {
					if (this.validator.options.msg_invalidEmail)
						msgContent=msgContent+this.validator.options.msg_invalidEmail+separator;
					else
						msgContent=msgContent+DCsValidator_MSG[thisMsgType]+separator;

					break;
				}

			}
		}

		return msgContent;

	},

	/////////////////////////////////////////////////////////////////////////////////////////
	// THE TRIGGER FUNCTIONS ////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////

	// ACTION ON BLUR ///////////////////////////////////////////////////////////////////////
	blurAction:function(event) {

		$(this).removeClassName('invalidField');
		if (this.value) {

			// validate field and extract required information
			response=this.validator.validateField.bind(this)();

			if (response.valid==false) {
				// add invalid field class
				$(this).addClassName('invalidField');

				// USER ALERT
				finalMsg=this.validator.generateUserMsg.bind(this)(response.messages);
				this.validator.inputAlert.bind(this)(finalMsg);
				Event.stop(event); this.focus();
				setTimeout(function(){this.focus()}.bind(this), 1)
			}

		}
	},

	// ACTION ON KEYPRESS ///////////////////////////////////////////////////////////////////
	keypressAction:function(event) {

		$(this).removeClassName('invalidField');

		if (event.keyCode==Event.KEY_RETURN && this.value) {
			// validate field and extract required information
			response=this.validator.validateField.bind(this)();

			if (response.valid==false) {
				// add invalid field class
				$(this).addClassName('invalidField');

				// USER ALER
				finalMsg=this.validator.generateUserMsg.bind(this)(response.messages);
				this.validator.inputAlert.bind(this)(finalMsg);
				Event.stop(event); this.focus();
				setTimeout(function(){this.focus()}.bind(this), 1)
			}

		}

	}

}


// --------------------------------------------------------------------------------------------
// CHECK MANDATORY FIELDS FUNCTIONS
// returns either the id of the first mandatory input in the given form (in case there are
// empty mandatory fields), or 'ok' (in case none of the mandatory fields are empty
// --------------------------------------------------------------------------------------------
function checkMandatoryFields(formId) {

	formFields=$(formId).getElements();

	var firstInput=null;

	for (i=0; i<formFields.length; i++) {
		thisInput=$(formFields[i]);

		if (!Field.present(thisInput) && thisInput.getAttribute('mandatory')==1 && !thisInput.getAttribute('disabled')) {
			new Effect.Pulsate($(thisInput),{pulses:3, from:0.1});

			// rememener first input
			if(firstInput==null){
				firstInput=thisInput;
			}
		}
	}
	if(firstInput!=null){
		firstInput.focus();
		return firstInput;
	}

	return 'ok';
}

// --------------------------------------------------------------------------------------------
// CHECK MANDATORY FIELDS WITH MESSAGE
// uses the function checkMandatoryFields; in case all mandatory fields are ok, submits the form
// in case some mandatory fields are not ok, returns a warning message
// --------------------------------------------------------------------------------------------
function checkMandatoryFieldsWithMessage(triggerObj, message) {

	triggerObj=$(triggerObj);
	if(triggerObj.form!=null)
		triggerObj=triggerObj.form;

	response=checkMandatoryFields(triggerObj);

	if (response!='ok') {
		messageDiv.show('thisMessage', message, 'MSG_WARNING');
		setTimeout(function(){ window.scrollTo($('thisMessage').getLeft(),$('thisMessage').getTop()-10)},100);
		return false;
	}
	else{
		return true;
	}
}
