// JavaScript Document

var imageSrc = 'images/showmenu.gif';

// =================================================================
// VALIDATION FUNCTIONS
// =================================================================
/*
 * Put a message in the div with id 'mensajes'.
 */
function putMessage(strMsg, add, id){
	var field = "";
	if(id)
	{
//		document.getElementById(id).focus();
		//alert(id+"*"+document.getElementById(id));
//		alert(window.parent.document.getElementById('" + id + "'));
//		alert(window.location);
		field = "<a href=\"javascript:document.getElementById('" + id + "').focus();\"><img src=\"" + imageSrc + "\" border=\"0\" /></a>";
	}
	var text = (strMsg == "")?"":strMsg;
	if(add){
		alert(strMsg);/////
//		alert("á");
//			alert('á'.charCodeAt(0));
		document.getElementById(id).focus();
		/*document.getElementById('mensajeAlert').innerHTML = text;
		anotherwindow.openAlert();
		*/
		return false;
	}else{
		//document.getElementById('message').innerHTML = text;
	}
}

/*
 * Validation usign Regular Expressions.
 */
function validate(str,pattern,error, id){
	var bReturn;
	var reg_exp = new RegExp(pattern);
	if(reg_exp.test(str)){
		bReturn = true;
	}else{
		bReturn = false;
		putMessage(error,true, id);
	}
	return bReturn;
}

/*
 * Funcion that indicate if a variable is Null (empty).
 */
var NOT_EMPTY = /[^|^ |^-]/;
function isNull(value){
	var bReturn = false;
	if(!NOT_EMPTY.test(value) || value == "-1"){
		bReturn = true;
	}
	return bReturn;
}

/*
 * A set of validations for send the form 'search',
 * using the Polymorphic Array RESTRICTIONS.
 */
 function doValidations(url, divSeccion, formName){
	var bValid = true;
	var objX;
	putMessage('');	
	for(var i=0; i < RESTRICTIONS.length; i++){
		objX = document.getElementById(RESTRICTIONS[i].field);		
		//alert(objX.type);
		if( objX == null )
		{
			alert( 'No se encontró el campo [' + RESTRICTIONS[i].field + ']' );
			return null;
		}
		// When the object is select
		
		if(objX.type == "select-one"){
			// We must get the text of the selected option
			bValid &= RESTRICTIONS[i].validate(objX.options[objX.selectedIndex].value);
		}
		else if(objX.type == "radio"){
			// We must get the text of the selected option
			radioButtons = eval("document." + formName + "." + RESTRICTIONS[i].field);
			bValid &= RESTRICTIONS[i].validate(radioButtons);
		}
		else if(objX.type == "checkbox"){
			// We must get the text of the selected option
			checkButtons = eval("document." + formName + "." + RESTRICTIONS[i].field);
			bValid &= RESTRICTIONS[i].validate(checkButtons);
		}else{
			bValid &= RESTRICTIONS[i].validate(objX.value);	
		}				
		if(!bValid){
			i =RESTRICTIONS.length;
		}
	}	
	// Show the error message of do submit.
	if(!bValid){
		return false;
	}else{
		//alert(document.getElementById('formName'));
		new Ajax.Updater(divSeccion, url, {asynchronous:true,evalScripts:true,parameters:Form.serialize(document.getElementById(formName))})
		document.getElementById(divSeccion).innerHTML = '<br><div align="center"><img src="images/loading.gif"/></div>';
		//document.search.action = url;
		//document.search.submit();
	}
	return bValid;
}


function doValidationsSinAjax(url, formName){
	var bValid = true;
	var objX;
	putMessage('');	
	for(var i=0; i < RESTRICTIONS.length; i++){
		objX = document.getElementById(RESTRICTIONS[i].field);		
//		alert(objX.type);
		if( objX == null )
		{
			alert( 'No se encontró el campo [' + RESTRICTIONS[i].field + ']' );
			return null;
		}
		// When the object is select
		if(objX.type == "select-one"){
			// We must get the text of the selected option
			bValid &= RESTRICTIONS[i].validate(objX.options[objX.selectedIndex].value);
		}
		else if(objX.type == "radio"){
			// We must get the text of the selected option
			radioButtons = eval("document." + formName + "." + RESTRICTIONS[i].field);
			bValid &= RESTRICTIONS[i].validate(radioButtons);
		}
		else if(objX.type == "checkbox"){
			// We must get the text of the selected option
			checkButtons = eval("document." + formName + "." + RESTRICTIONS[i].field);
			bValid &= RESTRICTIONS[i].validate(checkButtons);
		}else{
			bValid &= RESTRICTIONS[i].validate(objX.value);	
		}				
		if(!bValid){
			i =RESTRICTIONS.length;
		}
	}	
	// Show the error message of do submit.
	if(!bValid){
		return false;
	}else{
		//alert(document.getElementById('formName'));
		var formularioEnvio = eval("document."+formName);
		formularioEnvio.action = url;
		formularioEnvio.submit();
		//document.search.submit();
	}
	return bValid;
}

// =================================================================
// VALIDATION CLASSES
// =================================================================
/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function Validacion(pField,pPattern,pMessage){
	this.field = pField;
	this.pattern = pPattern;
	this.message = pMessage;
	this.validate = ValidacionTest;
} 
function ValidacionTest(value){	
	var bReturn = true;
	if(!isNull(value)){
		bReturn = validate(value,this.pattern,this.message, this.field);
	}
	return bReturn;
}
function compareTest(value){	
	var bReturn = true;
	if(!isNull(value)){
		bReturn = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value);
		if(!bReturn){
			putMessage(this.message,true,this.field);
		}
	}
	return bReturn;
}
/*
 * pField is the name of the field.
 * pLength is the length. F.e.: 
 *		3 if must have length 3
 * 		3, if must have length 3 or higher 
 * pMessage is the message that appear if is not valid
 */
function Longitud(pField,pLength,pMessage){
	this.field = pField;
	this.pattern = pLength;
	this.message = pMessage;
	this.validate = LongitudTest;
} 
function LongitudTest(value){	
	var bReturn = true;
	if(!isNull(value)){
		bReturn = validate(value,"^[^?]{" + this.pattern + "}$",this.message, this.field);
	}
	return bReturn;
}
/*
 * pField is the name of the field.
 * pMessage is the message that appear if is null
 */
function NotNull(pField,pMessage){
	this.field = pField;
	this.pattern = "[^|^ |^-]";
	this.message = pMessage;
	this.validate = NotNullTest;
} 
function NotNullTest(value){	
	return validate(value,this.pattern,this.message, this.field);
}
function ifSelectField(checkfiel,pField,pMessage){
	this.field = pField;
	this.checkfiel = checkfiel;
	this.message = pMessage;
	this.pattern = "[^|^ |^-]";
	this.validate = ifSelectFieldTest;
}
function ifSelectFieldTest(value){	
	if(document.getElementById(this.checkfiel).checked){
		return validate(value,this.pattern,this.message, this.field);
	}else{
		return true;
	}
}
function equalFields(pField,field2,pMessage){
	this.field = pField;
	this.field2 = field2;
	this.message = pMessage;
	this.validate = isEqual;
}
function isEqual(val){
	if(document.getElementById(this.field2).value==val){
		return true
	}else{
		putMessage(this.message,true, this.field);
		return false;
	}
}
function EqualCombos(pField,field2,pMessage){
	this.field = pField;
	this.field2 = field2;
	this.message = pMessage;
	this.validate = isEqual2;
}
function isEqual2(val){
	var combo2;
	combo2 = document.getElementById(this.field2);
	combo2 = combo2.options[combo2.selectedIndex].text;
	if(combo2!=val){
		return true
	}else{
		putMessage(this.message,true, this.field);
		return false;
	}
}

/*
 * pField is the name of the field.
 * pMessage is the message that appear if is null
 */
function IsValidRange(pField,field2,pMessage){
	this.field = pField;
	this.field2 = field2;
	this.message = pMessage;
	this.validate = isValidRange;
}
function isValidRange(val){
	var tmpfecha1;
	var tmpfecha2;
	var retorno;
	tmpfecha1 = val.split("-");
	tmpfecha2 = document.getElementById(this.field2).value.split("-");
	
	tmpfecha1 = new Date(tmpfecha1[2], tmpfecha1[1], tmpfecha1[0]);
	tmpfecha1 = tmpfecha1.valueOf();
	
	tmpfecha2 = new Date(tmpfecha2[2], tmpfecha2[1], tmpfecha2[0]);
	tmpfecha2 = tmpfecha2.valueOf();
	
	if(tmpfecha1 <= tmpfecha2){
		return true
	}else{
		putMessage(this.message,true, this.field);
		return false;
	}
}

/*
 * pField is the name of the field.
 * pMessage is the message that appear if is null
 */
function NotIs(pField,pValue,pMessage){
	this.field = pField;
	this.pattern = pValue;
	this.message = pMessage;
	this.validate = NotIsTest;
} 
function NotIsTest(value){
	var bReturn = (value != this.pattern);
	if(bReturn == false){ putMessage(this.message,true, this.field); }
	return bReturn;
}
/*
 * pField is the name of the field.
 * pMessage is the message that appear if is null
 */
function BiggerThat(pField,pValue,pMessage){
	this.field = pField;
	this.pattern = pValue;
	this.message = pMessage;
	this.validate = BiggerThatTest;
} 
function BiggerThatTest(value){
	var bReturn = (Number(value) > Number(this.pattern));
	if(bReturn == false){ putMessage(this.message,true, this.field); }
	return bReturn;
}
/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function OnlyNumericField(pField,pMessage){
	this.field = pField;
	
/*	if(document.getElementById(pField).type == "select-one")
		this.pattern = '^[0-9]*$';
	else*/
	this.pattern = '^[0-9]*$';
	this.message = pMessage;
	this.validate = ValidacionTest;
} 
/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function NumericField(pField,pMessage){
	this.field = pField;
	this.pattern = '^[\-\+0-9]*$';
	this.message = pMessage;
	this.validate = ValidacionTest;
}

/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function IsLetter(pField,pMessage){
	this.field = pField;
	this.pattern = '^[a-z]*$';
	this.message = pMessage;
	this.validate = ValidacionTest;
} 
/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function TextField(pField,pMessage){
	this.field = pField;
	this.pattern = '^[a-zA-Zá-úÁ-Ú\-\+0-9., ]*$';
	this.message = pMessage;
	this.validate = ValidacionTest;
} 
/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function EmailField(pField,pMessage){
	this.field = pField;
	this.pattern = '/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/';
	this.message = pMessage;
	this.validate = compareTest;
} 

/*
 * pField is the name of the field.
 * pPattern is the complete pattern for RegExp
 * pMessage is the message that appear if is not valid
 */
function RadioField(pField,pMessage){
	this.field = pField;
	this.pattern = '^[a-zA-Zá-úÁ-Ú\-\+0-9., ]*$';
	this.message = pMessage;
	this.validate = RadioFieldTest;
} 

function RadioFieldTest(value){	
	var bReturn = false;
	var i = 0;
	for( ; i < value.length; i++ )
	{
		if(value[i].checked)
		{
			bReturn = true;
		}
	}

	if(!bReturn)
	{
		putMessage(this.message,true, this.field);
	}

	return bReturn;
}

function isDate(pField,pMessage){
	this.field = pField;
	this.message = pMessage;
	this.validate = CheckDateTest;
}
function CheckDateTest(str_date){
	var retorno;
	var mensaje;
	var RE_NUM = /^\-?\d+$/;
	var arr_date = str_date.split('-');
	var dt_date = new Date();
	dt_date.setDate(1);
	mensaje = '';
	retorno = true;
	if (arr_date.length != 3){
		mensaje = "Formato de fecha invalido: '" + str_date + "'.\nEl formato correcto es dd-mm-aaaa.";
		retorno = false;
	}
	else if (!arr_date[0]){
		mensaje = "Formato de fecha invalido: '" + str_date + "'.\nNo se encontro dia de mes.";
		retorno = false;
	}
	else if (!RE_NUM.exec(arr_date[0])){
		//mensaje = "Valor de dia de mes invalido: '" + arr_date[0] + "'.\nValores permitidos son enteros sin signo.";
		mensaje = "Valor de dia de mes invalido: '" + arr_date[0];
		retorno = false;
	}
	else if (!arr_date[1]){
		mensaje = "Formato de fecha invalido: '" + str_date + "'.\nNo se encontro valor del mes.";
		retorno = false;
	}
	else if (!RE_NUM.exec(arr_date[1])){
		//mensaje = "Valor de mes invalido: '" + arr_date[1] + "'.\nValores permitidos son enteros sin signo.";
		mensaje = "Valor de mes invalido: '" + arr_date[1] + "'.\nEl rango permitido es 01-12.";
		retorno = false;
	}
	else if (!arr_date[2]){
		mensaje = "Formato de fecha invalido: '" + str_date + "'.\nNo se encontro valor del a&ntilde;o.";
		retorno = false;
	}
	else if (!RE_NUM.exec(arr_date[2])){
		mensaje = "Valor de a&ntilde;o invalido: '" + arr_date[2];
		retorno = false;
	}
	else if (arr_date[1] < 1 || arr_date[1] > 12){
		mensaje = "Valor de mes invalido: '" + arr_date[1] + "'.\nEl rango permitido es 01-12.";
		retorno = false;
	}
	else {
		dt_date.setMonth(arr_date[1]-1);
		dt_date.setFullYear(arr_date[2]);
		var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
		dt_date.setDate(arr_date[0]);
		if (dt_date.getMonth() != (arr_date[1]-1)){
			mensaje = "Valor de dia de mes invalido: '" + arr_date[0] + "'.\nEl rango permitido es 01-"+dt_numdays.getDate()+".";
			retorno = false;
		}
	}
	 if(!retorno){
		putMessage(mensaje,true, this.field);
	}
	return retorno;
}
function isTime(pField,pMessage){
	this.field = pField;
	this.message = pMessage;
	this.validate = CheckTimeTest;
}
function CheckTimeTest(str_time) {
	var retorno;
	var mensaje;
	var RE_NUM = /^\-?\d+$/;
	var arr_time = String(str_time ? str_time : '').split(':');
	
	mensaje = '';
	retorno = true;
		
	if (!arr_time[0]){
		mensaje = "No se encontro valor de la hora";
		retorno = false;
	}
	else if (!RE_NUM.exec(arr_time[0]) || (arr_time[0] >= 24)){
		mensaje = "El valor de hora es invalido: '" + arr_time[0] + "'.\nEl rango permitido es 00-23.";
		retorno = false;
	}
	else if (!arr_time[1]){
		mensaje = "No se encontro valor de los minutos";
		retorno = false;
	}
	else if (!RE_NUM.exec(arr_time[1]) || (arr_time[1] >= 60)){
		mensaje = "El valor de minutos es invalido: '" + arr_time[1] + "'.\nEl rango permitido es 00-59.";		
		retorno = false;
	}
	if(!retorno){
		putMessage(mensaje,true, this.field);
	}
	return retorno;
}
function ValidRangeDate(pField,field2,field3,field4,pMessage){
	this.field = pField;
	this.field2 = field2;
	this.field3 = field3;
	this.field4 = field4;
	this.message = pMessage;
	this.validate = isValidRangeDate;
}
function isValidRangeDate(val){
	var fecha1 = val;
	var hora1 = document.getElementById(this.field2).value;	
	var fecha2 = document.getElementById(this.field3).value;
	var hora2 = document.getElementById(this.field4).value;
	var tmpFecha1 = fecha1.split('-');
	var tmpHora1 = hora1.split(':');
	var tmpFecha2 = fecha2.split('-');
	var tmpHora2 = hora2.split(':');
	fecha1 = new Date (tmpFecha1[2], tmpFecha1[1]-1, tmpFecha1[0], tmpHora1[0], tmpHora1[1], 0);
	fecha2 = new Date (tmpFecha2[2], tmpFecha2[1]-1, tmpFecha2[0], tmpHora2[0], tmpHora2[1], 0);
	if(fecha1.getTime() <= fecha2.getTime()){
		return true
	}else{
		putMessage(this.message,true, this.field);
		return false;
	}
}
function CheckField(pField,pMessage){
	this.field = pField;
	this.pattern = '^[a-zA-Zá-úÁ-Ú\-\+0-9., ]*$';
	this.message = pMessage;
	this.validate = CheckFieldTest;
} 

function CheckFieldTest(value){	
	var bReturn = false;
	var i = 0;
	
	if(value.checked)
	{
		bReturn = true;
	}

	if(!bReturn)
	{
		putMessage(this.message,true, this.field);
	}

	return bReturn;
}
