﻿/*********************************************************************
*** (C) OK-Systems,2007 (All rights reserved)                      ***
*** Don't make any changes without reporting to oks@ok-systems.com ***
**********************************************************************
*** File____: ui_form.js                                           ***
*** Project_: Virtual Office                                       ***
*** Language: JavaScript                                           ***
*** Tier____: Presentation-services                                ***
*** Author__: Antonio Olmedo Soler (??-Nov-1999)                   ***
*** Description: Form interacion / Validation functions            ***
*********************************************************************/


//==================================================
// FIELD VALIDATION FUNCTIONS (onKeyPress event)
//==================================================

//--------------------
//- Created_: ??-???-????, Antonio Olmedo Soler
//- Modified: 17-Oct-2001, Antonio Olmedo Soler
//- Syntax__: KeyPress_Number([bDecimals=false],[nMin],[nMax])
//- Description: Check if the key pressed is numeric.
//--------------------
function KeyPress_Number() {
	try {
		//--- Optional arguments
		var bDecimals=false;
		var nMin=null;
		var nMax=null;
		if (arguments.length>0) if (arguments[0]!=null)		bDecimals=arguments[0];
		if (arguments.length>1) if (!isNaN(arguments[1]))	nMin=arguments[1];
		if (arguments.length>2) if (!isNaN(arguments[2]))	nMax=arguments[2];
		//--- Check if pressed a number
		var cChar=String.fromCharCode(event.keyCode);
		if (isNaN(cChar)) {
			if (cChar=='-') return true; // Aloow negative numbers
			if (bDecimals) if (cChar=='.') return true; 
			//NOTE: Consider other decimal characters (,) a thousands separators
			return false;
		}
		//--- Compare with Maximum and minimum values if provided.
		if (nMin) { if (cChar<nMin) return false; }
		if (nMax) { if (cChar>nMax) return false; }
	} catch(oError) {}
	//---
	return true;
}

//--------------------
//- Modified: 12-May-1999, Antonio Olmedo Soler
//- Syntax__: KeyPress_TextLength(txt,iLen)
//- Description: Checks the maximum length of the value of an input field.
//--------------------
function KeyPress_TextLength(txt,iLen) {
	var iSelLen = 0;
	//---
	if (ie4) iSelLen=document.selection.createRange().text.length;
	return (txt.value.length-iSelLen)<iLen;
}

//--------------------
//- Created_: 13-May-1999, Antonio Olmedo Soler
//- Modified: 19-Oct-2001, Antonio Olmedo Soler
//- Syntax__: KeyPress_Time(txt)
//- Description: Checks whether the value of the input field is a valid time string (hh:nn)
//--------------------
function KeyPress_Time(txt) {
	if (!ie4) return true;
	//---
	var sChar=String.fromCharCode(event.keyCode);
	if ((! isNaN(sChar)) || (sChar==':'))
		return KeyPress_TextLength(txt,5);
	else
		return false;
}


//==================================================
// FIELD VALIDATION FUNCTIONS (onChange event or equivalent)
//==================================================

//--------------------
//- Created_: ??-???-????, Antonio Olmedo Soler
//- Modified: 18-Oct-2001, Antonio Olmedo Soler
//- Syntax__: FieldValidate_Number(oField,[nMin],[nMax])
//- Description: Check if the field value is numeric.
//--- Optional arguments: Minimum and Maximum
//--------------------
function FieldValidate_Number (oField) {
	//alert('FieldValidate_Number: '+oField.value);
	//--- Accept empty values
	if (oField.value==null || oField.value=='') return true;
	//---
	var nMin=null;
	var nMax=null;
	if (arguments.length>1) if (!isNaN(arguments[1]))	nMin=arguments[1];
	if (arguments.length>2) if (!isNaN(arguments[2]))	nMax=arguments[2];
	//---
	var nValue = parseFloat(oField.value);
	var cValue = nValue.toString();
	var cError='';
	//--- Check if value is a number
	if (cValue=='NaN' || cValue == "undefined") {
		cError+='\nThe value must be a valid number.';
	} else {
		if (nMin) if (nValue<nMin) cError+='\nMinimum value: '+nMin;
		if (nMax) if (nValue>nMax) cError+='\nMaximum value: '+nMax;
	}
	//---
	if (cError) {
		alert('INVALID VALUE:\n'+cError);
		try {
			oField.select();
			oField.focus();
		} catch (oError) {}
		return null;
	} else {
		//oField.value=nValue;
		//return oField;
		return '999';
	}
}

//--------------------
//- Created_: 18-Jun-1999, Antonio Olmedo Soler
//- Modified: 18-Oct-2001, Antonio Olmedo Soler
//- Syntax__: FieldValidate_Time(oField)
//- Description: Check if the field value is a valid time string (hh:mm)
//--------------------
function FieldValidate_Time (oField) {
	//alert('FieldValidate_Time');
	//--- Accept empty values
	var cTime=oField.value;
	if (cTime==null || cTime=='') return true;
	//---
	var cError='';
	var nHours=null;
	var nMins=null;
	var nPos=cTime.indexOf(':');
	var cDefaultError='This is not a valid time string.\nIt should be like "hh:mm" (hours and minutes)';
	//---
	if (nPos<0) {
		cError=cDefaultError;
	} else {
		nHours=parseInt(cTime.substring(0,nPos),10);
		nMins=parseInt(cTime.substr(nPos+1),10);
		//alert('\nV: '+cTime+'\nP: '+nPos+'\nH: '+nHours+'\nM: '+nMins);
		//---
		if (isNaN(nHours) || isNaN(nMins))	cError=cDefaultError;
		else if (nHours<0 || nHours>23)	cError='Wrong time string:\nHour should be between 0 and 23.';
		else if (nMins<0 || nMins>59)		cError='Wrong time string:\nMinutes should be between 0 and 59.';
		else {
			if (nHours<10) nHours='0'+nHours;
			if (nMins<10)  nMins='0'+nMins;
			oField.value=nHours+':'+nMins;
		}
	}
	//---
	if (cError) {
		alert(cError);
		oField.select();
		oField.focus();
		return null;
	}
	//---
	return oField;
}

//--------------------
//- Created_: ??-???-1999, Antonio Olmedo Soler
//- Modified: ??-???-1999, Antonio Olmedo Soler
//- Syntax__: FieldValidate_Date(oField)
//- Description: Check if the field value is a valid time string (dd-mmm-yyyy)
//--------------------
function FieldValidate_Date (oField) {
	if (!ie4) return true;
	//--- Accept empty values
	if (oField.value==null) return true;
	//--- Check if value is a valid date
	if (Date_IsValid(oField.value)) return true;
	//--- If the date format is wrong, abort and focus on field
	alert('Wrong date !\nPlease, enter a valid date,\nusing the following format:\ndd-mm-yyyy');
	try { oField.focus(); } catch (e) {}
	return false;

	// ¿¿¿ HOW ???
	//var dDate = new Date(oField.value);
	//alert(oField.name+': '+oField.value+'\n'+dDate+'\nGMT: '+dDate.toGMTstring+'\nUTC: '+dDate.toUTCstring()+'\nLoc: '+dDate.toLocaleString());
	//alert(oField.name+': '+oField.value+'\n'+dDate+'\nGMT: '+dDate.toGMTstring+'\nUTC: '+dDate.toUTCstring+'\nLoc: '+dDate.toLocaleString);
	//var s = dDate.toString();
	//---
	//if (i <= 0 || s == "NaN" || s == "undefined") {
	//	oField.focus();
	//	return null;
	//}
	//return oField;
}


//--------------------
//- Created_: 29-03-2005, Antonio Olmedo Soler
//- Modified: 29-03-2005, Antonio Olmedo Soler
//- Syntax__: IsValid_Email(cValue)
//- Description: Check if the field value is a valid e-mail address
//- Notes___: Found in www.aspfaq.com/show.asp?id=2238
//--------------------
function IsValid_Email(cValue) {
	return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w{2,}$/.test(cValue);
} 

//--------------------
//- Created_: 29-03-2005, Antonio Olmedo Soler
//- Modified: 29-03-2005, Antonio Olmedo Soler
//- Syntax__: FieldValidate_Email(oField,[cLabel])
//- Description: Check if the field value is a valid e-mail address
//- Notes___: Found in www.aspfaq.com/show.asp?id=2238
//--------------------
function FieldValidate_Email(oField) {
	//--- Optional arguments
	var cLabel	=oField.name;
	if (arguments.length>1) if (arguments[1])		cLabel=arguments[1];
	//---	
	if (IsValid_Email(oField.value)) return true;
	//alert('Wrong e-mail format.\nPlase enter a valid e-mail address');
	alert('El formato del campo '+cLabel+' es erróneo.\nPor favor, introduzca una dirección de correo electrónico válida.');
	try { oField.focus(); } catch (oError) {}
	return false;
} 

//--------------------
//- Created_: 29-Mar-2005, Antonio Olmedo Soler
//- Modified: 10-Mar-2006, Antonio Olmedo Soler
//- Syntax__: FieldValidate_Mandatory(oField,[cLabel])
//- Description: Check if a mandatory field has any value
//- Notes___: Provisional: just for text fields. To be adapted later
//--------------------
function FieldValidate_Mandatory(oField) {
	//--- Optional arguments
	var cLabel	=oField.name;
	if (arguments.length>1) if (arguments[1])		cLabel=arguments[1];
	//---	
	var xValue=null;
	switch (oField.tagName.toLowerCase()) {
	case 'select':
		xValue=lst_selected_value(oField);
		break;
	default:
		xValue=oField.value;
	}
	//alert('FieldValidate_Mandatory('+oField.name+'['+oField.tagName+']) = '+xValue)
	if (!xValue) { 
		alert('El campo "'+cLabel+'" es obligatorio.\nPor favor, introduzca un valor.');
		try { oField.focus(); } catch(oError) { }
		return false;
	}
	return true;
} 


//==================================================
// FIELD VALIDATION FUNCTIONS
//==================================================

//--------------------
//- Created_: 30-Mar-1999, Antonio Olmedo Soler
//- Modified: 16-Oct-2000, Antonio Olmedo Soler
//- Syntax__: IsValidMandatoryField (oField[,cName[,bAlert]])
//- Description: 
//--------------------
function IsValidMandatoryField (oField) {
	if (!oField) {
		alert('Error in function IsValidMandatoryField():\nWrong field object !')
		return false;
	}
	var cName=oField.name;
	var bAlert=true;
	//alert(cName+'->'+oField.value.length);
	if (oField.value.length>0) return true;
	//--- Optional arguments
	if (arguments.length>1) if (arguments[1]) cName=arguments[1];
	if (arguments.length>2) bAlert=arguments[2];
	//---
	if (bAlert) alert(cName+' is mandatory.\nPlease, enter a valid value.'); 
	try { oField.focus(); } catch (oError) { }
	return false;
}

//--- Field validation

//--------------------
//- Modified: 29-Mar-1999, Antonio Olmedo Soler
//- Description: 
//--------------------
function valFld (oField) {
	//--- If field is not empty, return true
	if (oField.value.length>0) return true
	//--- If field is empty, set focus and return false. 
	//- Optionally, show a warning message
	//alert('Empty field: '+oField.name);
	if (arguments.length>1) alert(arguments[1]);
	try { oField.focus(); } catch (oError) { }
	return false;
}




//==================================================
// *SPECIAL* FUNCTIONS
//==================================================

//--------------------
//- Created_: 28-Aug-2001, Josep Auferil
//- Modified: 19-Oct-2001, Antonio Olmedo Soler
//- Syntax__: Show_Tip(nAttributeId)
//- Description: 
//--------------------
function Show_Tip(nAttributeId){
	var cFile=DIR_ROOT+'tool_help/glossary.htm?HelpItem='+nAttributeId;
	var cFeatures='toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600';
	//---
	if (ie4) {
		cFeatures+=',top=20,left=20';
	} else {
		cFeatures+=',screenY=20,screenX=20';
	}
	window.open(cFile,'Atd_Help',cFeatures);
	return void(null);
}

//--------------------
//- Created_: 13-Nov-2001, Antonio Olmedo Soler
//- Modified: 13-Nov-2001, Antonio Olmedo Soler
//- Syntax__: Show_Status([cStatus])
//- Description: 
//--------------------
function Show_Status(){
	var cStatus='';
	//--- Optional arguments
	if (arguments.length>0) cStatus=String_Replace(arguments[0],'\n',' | ');
	//---	
	window.status=cStatus;
	return void(null);
}



//==================================================
// OK-FORM VALIDATION FUNCTIONS 
//==================================================

//--------------------
//- Created_: 30-Sep-2004, Antonio Olmedo Soler
//- Modified: 04-Apr-2006, Antonio Olmedo Soler
//- Syntax__: OKForm_Validate(oThisForm,[cLang=LANG_ES])
//- Description: Use with Form's onsubmit event. Performs generic valudation.
//--------------------
function OKForm_Validate(oThisForm) {
	try {
	   //--- Optional arguments
	   var cLang=LANG_ES;
	   if (arguments.length>1) if (arguments[1])		cLang=arguments[1];
	   //---
		var cField,oField,cValue;
		//--- If there are Mandatory fields, check if they have values
		if (oThisForm.MandatoryFields) {
			//alert('OKForm_Validate - '+oThisForm.MandatoryFields.value)
			if (oThisForm.MandatoryFields.value) {
				var aFields=oThisForm.MandatoryFields.value.split(',');
				for (var nC in aFields) { 
					cField=aFields[nC];
					oField=oThisForm[cField];
					//>>> Pendiente: identificar tipo del campo para poder obtener el valor...
					cValue=oField.value;
					//alert(aFields+'\n'+nC+'\ncField:'+cField+'\nType: '+oField.type+'\nName: '+oField.name+'\nValue: '+cValue)
					//alert(cField+' value='+cValue)
					if (!cValue) {
						switch (cLang) {
						case LANG_EN:  alert('You must fill the mandatory fields !\nMissing the value of '+cField); break;
						case LANG_PT:  alert('¡ Tem de cumprimentar todos os campos obrigatórios !\nFalta o valor para o campo '+cField); break;
						default:       alert('¡ Ha de cumplimentar todos los campos obligatorios !\nFalta el valor para el campo '+cField);
						}
						try { oField.focus() }  catch(oE) {}
						return false;
					}
				}
			}
		}
		//--- Apply field validation rules 
		for (var i=0; i<oThisForm.elements.length; i++) { 
			oField=oThisForm.elements[i];
			cField=oField.name;
			//>>> Pendiente: identificar tipo del campo para poder obtener el valor...
			cValue=oField.value;
			//alert(aFields+'\n'+nC+'\ncField:'+cField+'\nType: '+oField.type+'\nName: '+oField.name+'\nValue: '+cValue)
			if (cValue) {
				//if (!confirm(cField+' = '+cValue)) return false;
				switch (cField.toLowerCase()) {
				case 'email': case 'e-mail':
			      if (!IsValid_Email(cValue)) {
	               switch (cLang) {
						case LANG_EN:  alert('The format of field '+cField+' is wrong.\nPlease, enter a valid e-mail address.'); break;
						case LANG_PT:  alert('O formato do campo '+cField+' é errôneo.\nPor favor, introduza uma direção de correio eletrônico válida.'); break;
						default:       alert('El formato del campo '+cField+' es erróneo.\nPor favor, introduzca una dirección de correo electrónico válida.');
						}
						try { oField.focus() }  catch(oE) {}
						return false; 
	            }
					break;
				default:
				}
			}
		}
		//--- Check Antispam Authentification field
		oField=oThisForm.elements['AuthentiCode'];
		//alert('AuthentiCode='+oField)
		if (oField) {
			var cAuthentiCode=document.getElementById('AuthentiCodeValue');
			//alert('cAuthentiCode:'+cAuthentiCode.innerHTML)
			if ((!oField.value) || (oField.value!=cAuthentiCode.innerHTML)) {
				switch (cLang) {
				case LANG_EN:  alert('You must authenticate the message copying the text show in the form'); break;
				//case LANG_PT:  alert('Ha de autenticar su mensaje copiando el texto mostrado en el formulario');break;
				default:       alert('Ha de autenticar su mensaje copiando el texto mostrado en el formulario');
				}
				try { oField.focus() }  catch(oE) {}
				return false; 
			}
		}

	} catch(oError) { alert('Error OKForm_Validate')}
	//---
	return true;
}

