// Array con los Dias que tiene cada Mes
var diasCadaMes = CrearArray(12);
diasCadaMes[1] = 31;
diasCadaMes[2] = 29;
diasCadaMes[3] = 31;
diasCadaMes[4] = 30;
diasCadaMes[5] = 31;
diasCadaMes[6] = 30;
diasCadaMes[7] = 31;
diasCadaMes[8] = 31;
diasCadaMes[9] = 30;
diasCadaMes[10] = 31;
diasCadaMes[11] = 30;
diasCadaMes[12] = 31;




function HacerAnd(param1, param2)
{
	return param1 && param2;
}
//Funcion: download
//
//Descripcion: Llamada bajo Iframe a pagina de Descarga de Ficheros
//
//Parametro: fileId, id unico de Fichero
//
function download(fileId)
{
	var iframe = document.getElementById('SAMAttachmentsIFRAME');
 
	if (!iframe)
	{
		iframe = document.createElement('iframe');
	}

	document.body.appendChild(iframe);

	var iframe_id  = 'SAMAttachmentsIFRAME';
	var iframe_src = 'SAMAttachmentsService.aspx?FileId=' + fileId;

	//Incluir Tiempo en Milisegundos a QueryString para evitar Cacheo
	var ticksec = (new Date()).getTime();
	iframe_src += '&time=' + ticksec;				

	iframe.id = iframe_id;
	iframe.style.visibility = "hidden";
	iframe.src = iframe_src;
}

function trim(s)
{
	while (s.substring(0,1) == ' ')
		s = s.substring(1,s.length);
	
	while (s.substring(s.length-1,s.length) == ' ')
		s = s.substring(0,s.length-1);

	return s;
}

//### CSS Review!
//Constantes Colores:

//A. Control Requeridos
var color_Requerido		= new String('lightgoldenrodyellow');
var color_NoRequerido	= new String('White');

//B. Control DataGrid
var color_Habilitado	= new String ('White');
var color_Inhabilitado	= new String ('#E0E0E0');
var colorTexto			= '#0051BD';
var colorTextoSelect	= '#FFFFFF';
var colorGridAlt1		= '#C1D1E4';
var colorGridAlt2		= '#EDEFEA';

//### CSS Review!

// BEGIN Gestion Busqueda Avanzada
var nombreTablaAlias = null;
nombreTablaControles = null;

function busquedaAvanzada(pagina, tablaAlias, tablaControles, ancho, alto)
{
	nombreTablaAlias = tablaAlias;
	nombreTablaControles = tablaControles;
	
	var url = pagina + '?AEBA=Simple&Parametros';

	var valor;
	var parametros = '';
	
	var separador = '=';
	
	for(i=0; i < tablaAlias.length; i++)
	{
		if (tablaControles[i].indexOf('~') == -1)
		{
			valor = document.forms[0].elements[tablaControles[i]].value;
		}
        else
		{
			valor = sacaValorDeGrid (tablaControles[i].split('~')[0],tablaControles[i].split('~')[1]);
		}

		parametros = parametros + separador + tablaAlias[i] + ',' + valor;
		separador = '|';
	}

	url = url + parametros;
	var win = window.open(url,'','resizable=yes,top=10000,left=10000,width='+ ancho + ',height=' + alto);
}

function busquedaAvanzada(pagina, mple, tablaAlias, tablaControles, ancho, alto, accionPostAsignacion, modo)
{
	nombreTablaAlias = tablaAlias;
	nombreTablaControles = tablaControles;

	var url = pagina + '?' + ((mple == true)? 'Mple=true' : 'Mple=false') +  '&modo=' + modo+ '&AEBA=Simple&Parametros';
	
	var valor;
	var separador = '=';
	var parametros =  '';

	for(i=0; i < tablaAlias.length; i++)
	{
		if (tablaControles[i].indexOf('~') == -1)
		{
			valor = document.forms[0].elements[tablaControles[i]].value;
		}
        else
		{
			valor = sacaValorDeGrid (tablaControles[i].split('~')[0],tablaControles[i].split('~')[1]);
		}

		parametros = parametros + separador + tablaAlias[i] + ',' + valor;
		separador = '|';
		
	}//for i

	url = url + parametros;
        
	if (accionPostAsignacion != '') 
		url = url + '&accion=' + accionPostAsignacion;

	var win = window.open(url,'','resizable=yes,top=10000,left=10000,width='+ ancho + ',height=' + alto);
}

// Funcion para Reestablecer el Estilo de Seleccionados de un Grid tras Submit
function restoreSelectedStyle (latabla)
{ 
        
        var tabla = document.getElementById(latabla); 

        if (tabla.rows.length!=0) 
        { 
        var multiple = (tabla.rows[0].onclick.toString().indexOf('false') != -1) ? 'false':'true'; 

        for (var j=0; j < tabla.rows.length; j++) 
        { 
                if (ifSelected (latabla, j) == true) 
                { 
                        if (j%2 == 0) 
                        { 
                                cambiaCheck (tabla.rows[j], latabla, multiple, colorTexto, tabla.rows[j].style.backgroundColor.toString()); 
                                cambiaCheck (tabla.rows[j], latabla, multiple, colorTexto, tabla.rows[j].style.backgroundColor.toString()); 
                        } 
                        else 
                        { 
                                cambiaCheck (tabla.rows[j], latabla, multiple, colorTexto, tabla.rows[j].style.backgroundColor.toString());         
                                cambiaCheck (tabla.rows[j], latabla, multiple, colorTexto, tabla.rows[j].style.backgroundColor.toString());         
                        } 
                } 
        }//for j 
        } 
        
} 

function ifSelected (latabla, lafila)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;
	var miCadena = '';
	var nocurr = 0;
	
	var columna;
	
	var i = parseInt (lafila);
	
	for (var j=0; j<mitabla.rows[i].cells.length; j++)
		if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
		{
			var ado = mitabla.rows[i].cells[j].innerHTML;
			var st = new Array();
			st = ado.split(' ');
			for (h=0; h < st.length; h++)
			{
				if (st[h].indexOf('id=') != -1)
				{
					var st2 = new Array();
					st2 = st[h].split('=');
					var check = document.getElementById(st2[1]);
					
					if (check.checked == true)
						return true;
				}
			}//for h

		}//if for j
	
	return false;
}

//Extraccion de Filas Seleccionadas de Grid
function obtieneFilasSeleccionadas(latabla)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;
	var resultado;
	var miCadena='';
		
	for (var i=0; i < mitabla.rows.length; i++)
	{
		for (var j=0; j<mitabla.rows[i].cells.length; j++)
		{
			if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
			{
				var ado = mitabla.rows[i].cells[j].innerHTML;
				var st = new Array();
				st = ado.split(' ');

				for (h=0; h < st.length; h++)
				{
					if ( st[h].indexOf('id=') != -1)
					{
						var st2 = new Array();
						st2 = st[h].split('=');
						var check = document.getElementById(st2[1]);
						if (check.checked == true)
						{
							if (miCadena == '') miCadena = i.toString();
							else miCadena = miCadena + ',' +i.toString();
						}
					}
				}//for h
			}
		}//for j
	}//for i

	return miCadena;
}

// Obtener Valor de Grid para Busqueda Avanzada de Grids
function sacaValorDeGrid (latabla, nombrecol)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;
	var miCadena = '';
	var nocurr = 0;

	var columna;
	
	for (var y=0; y<mitabla.rows[0].cells.length; y++)
		if (mitabla.rows[0].cells[y].innerText == nombrecol)
			columna = parseInt(y);

	for (var i=0; i < mitabla.rows.length; i++)
	{
		for (var j=0; j<mitabla.rows[i].cells.length; j++)
		{
			if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
			{
				var ado = mitabla.rows[i].cells[j].innerHTML;
				var st = new Array();
				st = ado.split(' ');
				
				for (h=0; h < st.length; h++)
				{
					if (st[h].indexOf('id=') != -1)
					{
						var st2 = new Array();
						st2 = st[h].split('=');
						var check = document.getElementById(st2[1]);
						if (check.checked == true)
						{
							miCadena = miCadena + mitabla.rows[i].cells[columna].innerText;
							nocurr = nocurr+1;
						}
					}
				}//for h
			}//if
		}//for j
	}//for i
	
	if (nocurr == 1)
		return miCadena;
	else
		return '';
}

// Obtener Valor de Grid segun Numero de Columna
function sacaValorDeGridIndex (latabla, numerocol)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;
	var miCadena = '';
	var nocurr = 0;

	var columna = parseInt (numerocol);

	for (var i=0; i < mitabla.rows.length; i++)
	{
		for (var j=0; j<mitabla.rows[i].cells.length; j++)
		{
			if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
			{
				var ado = mitabla.rows[i].cells[j].innerHTML;
				var st = new Array();
				st = ado.split(' ');
	
				for (h=0; h < st.length; h++)
				{
					if ( st[h].indexOf('id=') != -1)
					{
						var st2 = new Array();
						st2 = st[h].split('=');
						var check = document.getElementById(st2[1]);
		
						if (check.checked == true)
						{
							miCadena = miCadena + mitabla.rows[i].cells[columna].innerText;
							nocurr = nocurr+1;
						}
					}
				}//for h
			}//if
		}//for j
	}//for i

	if (nocurr == 1)
		return miCadena;
	else
		return '';
}

// Marcar / DesMarcar todas las Filas de un Grid
function MarcaDesMarca (latabla, valor)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;

	for (var i=0; i < mitabla.rows.length; i++)
	{
		for (var j=0; j<mitabla.rows[i].cells.length; j++)
		{
			if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
			{
				var ado = mitabla.rows[i].cells[j].innerHTML;
				var st = new Array();
				st = ado.split(' ');

				for (h=0; h < st.length; h++)
				{
					if (st[h].indexOf('id=') != -1)
					{
						var st2 = new Array();
						st2 = st[h].split('=');
						var check = document.getElementById(st2[1]);
						check.checked = valor;
					}
				}//for h
			}
		}//for j
	}//for i
}

// Funcion de Regeneracion de Tabla/Grid en Busqueda Avanzada
function regeneraGrid (mitabla)
{
	var latabla = document.getElementById(mitabla);
	for (var i=1; i < mitabla.rows.length; i++)
	{
		for (var j=0; j < mitabla.rows[0].cells.length-1; j++)
		{
			if (mitabla.rows[i].cells.length +1 != mitabla.rows[0].cells.length)
				var nuevaCelda = mitabla.rows[i].insertCell(parseInt(j));
				
		}//for j
	}//for i
}

// Funcion de Relleno de Columnas para Busqueda Avanzada de Grid
function rellanaColumnaDelGrid (mitabla, nombrecol, arrayval)
{
	var miCheck;
	var miCadena = '';
	var nocurr = 0;
	var columna;
	
	regeneraGrid (mitabla);

	for (var y=0; y < mitabla.rows[0].cells.length; y++)
	{
		if (mitabla.rows[0].cells[y].innerText == nombrecol)
			columna = parseInt(y);
	}

	for (var i=1; i < mitabla.rows.length; i++)
	{
		mitabla.rows[i].cells[columna].innerText = arrayval[parseInt(i)-1];
	}
}

function quitaSelected (idls)
{
	var lal = document.getElementById(idls);

	if (lal.selectedIndex != -1)
	{
		var txt = lal.options[lal.selectedIndex].text;
		var val = lal.options[lal.selectedIndex].value;
		
		// lo borramos del hidden donde se persiste.
		var elhid = document.getElementById(idls +'_hiddenArray');
	
		if (elhid != null)
		{
			if (elhid.value.length > 0)
			{			
				elhid.value = elhid.value.replace(txt + ':' + val,'');
				elhid.value = elhid.value.replace('||', '|');	
				
				if (elhid.value.toString().charAt(elhid.value.toString().length-1) == '|')
					elhid.value = elhid.value.substring(0, elhid.value.toString().length-1);
				if (elhid.value.toString().charAt(0) == '|')
					elhid.value = elhid.value.substring(1, elhid.value.toString().length);
			}
		}

		lal.options[lal.selectedIndex] = null;
	}
}

function ocurrenciaanterior (array, valor, position)
{
	for (u=0; u < position; u++)
	{
		if (array[u] == valor)
			return u;
	}
	return -1;
}

function enLaLista (idlista, cod)
{
	for (var k=0; k < idlista.options.length; k++)
	{
		if (idlista.options[k].value == cod)
			return k;
	}

	return -1;
}

function enLaListaText (idlista, cod)
{
	for (var k=0; k < idlista.options.length; k++)
	{
		if (idlista.options[k].text == cod)
			return k;
	}
	
	return -1;
}

function setEstilo (latabla)
{
	var mitabla = document.getElementById(latabla);
	var ordcolumncheck = -1;
	
	// Localizar Columna de CheckBox e insertar Fila de Checks
	for (var l=0; l < mitabla.rows[0].cells.length; l++)
	{
		if (mitabla.rows[0].cells[l].innerText == ' ')
			ordcolumncheck	= parseInt(l);
	}

	for (var f=1; f < mitabla.rows.length; f++)
	{
		var h = f;
		setTR (mitabla.rows[f], f);
		for (var u=0; u < mitabla.rows[f].cells.length; u++)
		{
			setCell(mitabla.rows[f].cells[u]);
		}
	
		if (ordcolumncheck != -1)
		{
			var celdaCheck = mitabla.rows[h].insertCell(ordcolumncheck);
			celdaCheck.className ='clR_RowGrid';
			celdaCheck.innerHTML = '<input name="' + latabla + ':_ctl' + (f+1).toString() + ':' + latabla + '_ColumnaCheck" id="' + latabla + '__ctl' + (f+1).toString() + '_' + latabla + '_ColumnaCheck" type="checkbox" onclick="if (this.checked == true) { this.checked=false; } else { this.checked=true;}" />';
		}
	}//for
}

function setCell (lacelda)
{
	lacelda.className = 'clR_RowGrid';
}

function setTR (lafila, orden)
{
	if (parseInt(orden) % 2 == 0)
	{
		lafila.lang = colorGridAlt1;
		lafila.style.backgroundColor = colorGridAlt1;
	}
	else
	{
		lafila.lang = colorGridAlt2;
		lafila.style.backgroundColor = colorGridAlt2;
	}

	lafila.onclick = clicka;
}

function clicka()
{
	// Obtener TR emisor de Evento de Datagrid
	var elevento = window.event.srcElement;
	var multiple = 'false';
	while (elevento && elevento.nodeName.toLowerCase()!="table")
		elevento = elevento.parentNode;
  
	if(elevento.rows[0].onclick.toString().indexOf('false') != -1)
		multiple = 'false';
	else
		multiple = 'true';
 
	var me = window.event.srcElement
  
	while (me && me.nodeName.toLowerCase()!="tr")
		me = me.parentNode;
 
	///### CSS Review
	cambiaCheck(me,elevento.id,multiple.toString(), '#0051BA', me.style.backgroundColor.toString());
}

function muestraResultados (valores, modo)
{
	var griddeleted = false;
	var gridsimplicados = '';

	if (valores != null) 
	{
		// Reemplazar Espacios en blanco HTML (&nbsp;) por blancos normales
		for (var m=0; m < valores.length; m++)
			if (valores[m].indexOf('&nbsp;') != -1)
				valores[m] = ' ';

		for(var i = 0; i < nombreTablaAlias.length; i++)
		{
			//Recuperar Valores para ListBox
			var idcontrol = nombreTablaControles[i];

			//**************************************************
			//****  CASO DE UN DATAGRID                      ***
			//**************************************************
			if (idcontrol.indexOf('~') != -1)
			{
				if (valores[i] != '')
				{
					// Usar este Hidden para recuperar el valor
					// de Filas en Servidor
					var elhid = document.getElementById('HiddenRecovery_'+idcontrol.split('~')[0]);

					var latabla = document.getElementById(idcontrol.split('~')[0]);
					gridsimplicados += (gridsimplicados =='') ? '' : '@';
					gridsimplicados += latabla.id;

					var losvalores = new Array();
					losvalores = valores[i].split('|');
					
					// borramos el contenido del grid antes de rellenarlo
					if (griddeleted == false)
					{
						elhid.value = ''; //reseteamos el hidden
						while (latabla.rows.length > 1)
						{
							latabla.deleteRow();
						}
						
						griddeleted = true;
					}

					elhid.value += (elhid.value == '') ? '' : '~';
					elhid.value += idcontrol.split('~')[1] + '}'; 
					elhid.value += valores[i];

					// Si Filas no Creadas, Insertarlas.
					if (latabla.rows.length < 2)
					{	
						for (var t=0; t < losvalores.length; t++)
							latabla.insertRow();		
					}
					
					rellanaColumnaDelGrid (latabla, idcontrol.split('~')[1], losvalores);

				}//if valores
			}//if Caso Grid
			
			else
			{
				var elcontrol = document.getElementById(nombreTablaControles[i]);
				
				//********************************************************
				//****  ES UN COMBO (size = 0) O UNA LISTA (size > 0 ) ***
				//********************************************************
				if (elcontrol.outerHTML.toLowerCase().indexOf('<select ') != -1)		
				{
					listaIDs = valores[i].split('|');
					var lalista = document.getElementById(nombreTablaControles[i]);
				
					var paraHiddenArrayValue;
					var paraHiddenArrayText; 

					var ifanterior = ocurrenciaanterior(nombreTablaAlias, nombreTablaAlias[i], i);

					if (ifanterior == -1)
					{
						paraHiddenArrayValue = i;
						for (k = 0; k < valores[i].split('|').length; k++)
						{
							if (modo == 'selection')
							{
								if (enLaListaText (lalista, listaIDs[k]) != -1)
									lalista.options[parseInt(enLaListaText(lalista, listaIDs[k]))].selected = true;
							}//if seleccion
							else
							{
								if (enLaListaText (lalista, listaIDs[k]) == -1)
								{
									if (lalista.options.length == 0)
									{
										lalista.options[0] = new Option();
										lalista.options[0].value = listaIDs[k];
										lalista.options[0].text = listaIDs[k];
									}
									else
									{
										lalista.options[lalista.options.length] = new Option();
										lalista.options[lalista.options.length-1].value = valores[i].split('|')[k];
										lalista.options[lalista.options.length-1].text = valores[i].split('|')[k];
					   				}
				   				}		
							}// else
						} //for
				} //if Anterior == -1
				else
				//if Anterior - Incluir Descripcion
				{
					paraHiddenArrayText = i;

					for (m=0; m < valores[i].split('|').length; m++)
					{
						var enla = enLaLista (lalista, valores[ifanterior].split('|')[m]);
						if (modo == 'selection')
						{
							if (enla != -1)
								lalista.options[parseInt(enla)].selected = true;
						}
						else if (enla != -1)
						{
							lalista.options[parseInt(enla)].value = listaIDs[m];
						}// En La Lista
					} //for
				}//else if Anterior
					
				// Metemos los valores en HiddenArray
				if (modo != 'selection' &&
				    ifanterior != -1)
				{
					var elhiddenArray = document.getElementById(nombreTablaControles[i] + '_hiddenArray');
					elhiddenArray.value;
			
					for (var q=0; q < valores[parseInt(paraHiddenArrayValue)].split('|').length; q++)
					{
						if (elhiddenArray.value.indexOf(valores[parseInt(paraHiddenArrayValue)].split('|')[q]) == -1);
						{
							if (elhiddenArray.value!= '')
								if (elhiddenArray.value.toString().charAt(elhiddenArray.value.toString().length-1) != '|')
									elhiddenArray.value += '|';
							elhiddenArray.value += valores[parseInt(paraHiddenArrayValue)].split('|')[q] +':'+valores[parseInt(paraHiddenArrayText)].split('|')[q] + '|';
						}
					}

					if (elhiddenArray.value != '')
					{
						elhiddenArray.value = elhiddenArray.value.substring(0, elhiddenArray.value.length-1);
					}
				}
			}
			else
			{
				document.forms[0].elements[nombreTablaControles[i]].value = valores[i];
				CambiaColor(document.forms[0].elements[nombreTablaControles[i]]);
				
			}// else Split
		} //else Datagrid
	} // for
			
	//Detectar si hay DataGrid implicado para redefinir su estilo
	if (gridsimplicados != '')
	{
		var arragrids = new Array();
		arragrids = gridsimplicados.split('@');
		for (var r=0; r < arragrids.length; r++)
		{
			var inarray = false;
			for (var o=0; o < r; o++)
				if (arragrids[o] == arragrids[r])
					inarray = true;
			if (inarray == false)
				setEstilo (arragrids[r]);
		}
	}
} //if null

}//function 

// END Gestion Busqueda Avanzada

//Validacion de Fechas Desde-Hasta
function ValidaFechas(sParam1, sParam2, sMensaje)
{
	var sFechaDesde=new String(document.getElementById(sParam1).value);
	var sFechaHasta=new String(document.getElementById(sParam2).value);

	var oFechaDesde=new Object(document.getElementById(sParam1).value);
	var oFechaHasta=new Object(document.getElementById(sParam2).value);
	
	if(sFechaDesde.length >= 8 &&
	   sFechaHasta.length >= 8)
	{
		sFechaDesde=sFechaDesde.split("/");
		var sDia = sFechaDesde[0];
		if(sFechaDesde[0].length > 2)
			sFechaDesde = sFechaDesde[0].split("-");
		var sDia = sFechaDesde[0]
		var sMes = sFechaDesde[1]
		var sYear = sFechaDesde[2]
		var oDateDesde = new Date( sMes + "/" + sDia + "/" + sYear)

		sFechaHasta = sFechaHasta.split("/")
		if( sFechaHasta[0].length >2)
			sFechaHasta = sFechaHasta[0].split("-");
		var sDia = sFechaHasta[0]
		var sMes = sFechaHasta[1]
		var sYear = sFechaHasta[2]
		var oDateHasta = new Date( sMes + "/" + sDia + "/" + sYear)
		
		if(oDateDesde > oDateHasta)
		{
			ShowMensaje(sMensaje);
			var as = document.getElementById(sParam1);

			if (as.hidefocus == true)
			{
				document.getElementById(sParam1).select();
				document.getElementById(sParam1).focus();
				as.hidefocus = false;
			}
			else
			{
				document.getElementById(sParam2).select();
				document.getElementById(sParam2).focus();
				as.hidefocus = true;
			}
			
			document.getElementById(sParam1).value = '';
			document.getElementById(sParam2).value = ''
			return false;
		}
	}
}

//Validacion de Expresion Regular
function Validar_ER(er, componente, idioma)
{
	var eltext = document.getElementById(componente);
	var midato = eltext.value;

	if (midato!='' && !er.test(midato))
	{ 
		document.getElementById(componente).value='';
		if (idioma=='ES')
			ShowMensaje('Datos Invalidos');
		else
			ShowMensaje ('Invalid Data');
		return false;
	}
	return true;
}

//Validacion de Pulsacion segun Formato
function Validar_Pulsacion_Personalizado(formato, componente)
{
	var eltext = document.getElementById(componente);
	var eldato = eltext.value;

	//Parsing de formato recibido.
	var elformato = formato.substring(1, formato.length-1);

	var sep ='', nosep=',', nuevodec='';
	var dec,num;
	var valido = true; 
	var entero = false;

	if (elformato.indexOf(',') != -1) sep =',';
	if (elformato.indexOf('.') != -1) sep ='.';
	if (sep==',') nosep='.';

	var mantisa = parseInt(elformato.split(sep)[0]);
	var precision = parseInt(elformato.split(sep)[1]);

	if (eldato == '') valido = false;
	if (eldato.indexOf(nosep) != -1) valido = false;

	if (eldato.indexOf(sep) == -1) 
	{
		try 
		{
			num = parseInt(eldato);
			entero = true;
		}
		catch(e) 
		{
			valido = false;
		}
	}
	
	if (entero)
	{
		if (eldato.length > mantisa) valido = false;
	}
	
	if (valido && !entero)
	{
		try
		{
			dec=parseInt(eldato.split(sep)[1]);
			num=parseInt(eldato.split(sep)[0]);
		}
		catch(e)
		{
			valido = false;
		}
		
		if(valido)
		{
			if (eldato.split(sep)[0].length > mantisa)
				valido = false;
			if (eldato.split(sep)[1].length > precision)
			{
				nuevodec = TruncoDato(eldato.split(sep)[1],precision);
				if (nuevodec == 'X')
				{
					entero = true;
					num++;
					if (num.toString().length > mantisa) valido = false;
				}
			}
			else nuevodec = dec;
		}
	}
	if (valido)
	{
		if (!entero)
		{
			eldato = num.toString() + sep.toString() + nuevodec.toString();
			eltext.value = eldato;
		}
		else
			eltext.value = num.toString();
	}
	else
	{
		eltext.value='';
	}
}

function TruncoDato(num, pre)
{
	var sobrantes = num.length - pre;
	var dato = parseInt(num);
	var aux = dato /(Math.pow(10, sobrantes));
	var res = Math.round(aux);

	if (res.toString().length > pre)
		res='X';

	return res;
}

// Validacion de Pulsacion de Teclado para TextBox
function Validar_Pulsacion(oParam)
{
	var nTipoDato = new Number(oParam);
	var bValor = new Boolean();
	
	bValor=false;
	switch(nTipoDato.toString())
	{
		// Extension del control TextBox para que contemple el tipo DNI/CIF
		case "1":
		case "5": bValor = true; 
				  break; // Tipo de Dato String
				  
		case "2": bValor = Validar_Pulsacion_Numeros();
				  break; // Tipo de Dato Numerico. Enteros
				  
		case "3": bValor = Validar_Pulsacion_Decimales();
				  break; // Tipo de Dato Decimal

		case "4": bValor = Validar_Pulsacion_Fecha();
				  break; // Tipo de Dato Fecha
	}

	return bValor;
}

//////////////////////////////////////////
// TOOL TIP DINAMICO PARA CONTROL TEXT_BOX
//////////////////////////////////////////
function cargaToolTip(oOrigen)
{
	oOrigen.title = oOrigen.value;
	return true;
	
}

// Comprobacion "onPaste" de Control
// oParam:  Tipo de Dato
// oOrigen: control evaluado
function Validar_Pulsacion_OnPaste(oParam, oOrigen)
{
	// Capturar Texto que se quiere pegar
	var sTexto = new String(window.clipboardData.getData("Text"));
	
	// Definir Array donde cargar Valores que se intentan pegar
	var aValores = new Array(window.clipboardData.getData("Text").length);
	var nTipoDato = new Number(oParam);
	
	// Cargar Array con cada uno de los valores que se intentan pegar
	for(var icount = 0; icount< aValores.length; icount++)
		aValores[icount] = sTexto.substr(icount,1);
		
	// Recorrer Array y comprobar si el caracter es valido,
	// en funcion del tipo de dato.
	for(var icount = 0;  icount < aValores.length; icount++)
	{
		if (Comprueba_Caracter( aValores[icount], nTipoDato.toString()) == false)
		{
			ShowMensaje("El valor que se intenta copiar contiene caracteres no validos.");
			return false;
			break;
		}
	}//for
}

// Comprobacion "onBlur" (perdida del Foco).
function Validar_Pierde_Foco(oParam, oOrigen)
{
	var nTipoDato = new Number(oParam);
	
	switch(nTipoDato.toString())
	{
		case "1": break;	// Tipo de Dato String
		case "2": 
				if(Validar_Es_Numerico(oOrigen.value) == false)
				{
					ShowMensaje('El valor introducido es incorrecto.');
					oOrigen.focus();
					return false;
				}
				break; // Tipo de Dato Numerico. Enteros

		case "3":
				if(Validar_Es_Numerico( oOrigen.value )==false)
				{
					ShowMensaje('El valor introducido es incorrecto.');
					oOrigen.focus();
					return false;
				}
				break; // Tipo de Dato Numerico. Enteros
		
		case "4":
				if( Validar_Es_Fecha( oOrigen.value )==false)
				{
					oOrigen.value='';
					return false;
				}
				break; // Tipo de Dato Fecha
				
		// Extension del control TextBox para que contemple el tipo DNI/CIF						
		case "5":
				if( Validar_Es_DNICIF ( oOrigen.value ) == false)
				{
					oOrigen.focus();
					return false;
				}
				break; //Tipo de Dato DNICIF
	}
}

// Comprobacion de Caracter que recibe como
// parametro (sValor) es correcto
// para el Tipo de Dato que le corresponde.
function Comprueba_Caracter(sValor, sTipoDatos)
{
	var sParam = new String(sValor);

	// Devolver ASCII del valor.
	var nAscii = new Number(sParam.charCodeAt(0))
	
	// Valores Numericos
	if (sTipoDatos=="2")
	{
		if (nAscii < 48 || nAscii > 57)
			return false;
	}
	
	// Valores Decimales
	if (sTipoDatos=="3")
	{
		if ((nAscii < 48 || nAscii > 57) && (nAscii != 44))
			return false;
	}
	
	// Valores de Fecha
	if (sTipoDatos=="4")
	{
		if ((nAscii < 48 || nAscii > 57) && (nAscii != 45) && (nAscii != 47))
			return false;
	}
}

// Validacion de Pulsacion para valores Decimales
function Validar_Pulsacion_Decimales()
{
	var sMensaje = new String('El valor introducido es incorrecto para un campo de Tipo Decimal');
	
	// Obtener contenido del Control emisor del Evento
	var sContenido  = new String( document.getElementById(window.event.srcElement.id).value);
	
	// Comprobacion de Existencia de Comas en Control
	var nPosComa = new Number( sContenido.indexOf( ",",1));
		
	// Comprobacion de Existencia de Numeros en Control
	// Numero entre 0 y 9 (ASCIIn 48-57) ó valor es una coma
	if ((window.event.keyCode < 48 || window.event.keyCode > 57) && (window.event.keyCode != 44))
	{
			ShowMensaje(sMensaje);
			return false;
	}

	// Comprobacion de que ya no exista una coma dentro del Control
	if( window.event.keyCode==44 && nPosComa != -1)
	{
			ShowMensaje(sMensaje);
			return false;
	}
}

// Validacion Pulsacion para valores de Fecha
function Validar_Pulsacion_Fecha()
{
	var numKey = new Number(window.event.keyCode);
	var sContenido = new String( document.getElementById(window.event.srcElement.id).value);
	var sMensaje = new String('El valor introducido es incorrecto para un campo de Tipo Fecha.Formato("dd/mm/yyyy" o "dd-mm-yyyy"');
	var intPos1 = new Number();
	var intPos2 = new Number();

	// Obtengo la primera posicion de la "/" ó "-"
	intPos1 = sContenido.indexOf("/", 1);
	if (intPos1 < 0)
		intPos1 =  sContenido.indexOf("-", 1);

	// Obtengo la segunda posicion de la "/" o "-"
	intPos2 =  sContenido.indexOf("/", intPos1+1);
	if (intPos2 < 0)
		intPos2 =  sContenido.indexOf("-", intPos1+1);

	// Compruebo si es un Numero entre 0 y 9 o el valor es "-" o "/"
	if ((numKey < 48 || numKey>57) &&
		(numKey != 45) &&
		(numKey != 47))
	{
		return false;
	}
	
	// Compruebo que no existan mas de 2 "/" o "-"
	if( (numKey==45 || numKey==47) && intPos2 != -1)
	{
		return false;
	}
}

//Validacion Formato Hora para TextBox
function Validar_Hora(id)
{
	var sContenido  = document.getElementById(id).value;
	var valido = true;

	if (sContenido.length!=8 && sContenido.length!=5)
		valido = false;

	var hora ='';
	var min=''; 
	var seg='';

	var nhora= new Number();
	var nmin= new Number();
	var nseg = new Number();

	if (sContenido.length==8)
	{
		if (sContenido.charAt(2)!=':' || sContenido.charAt(5)!=':') 
			valido = false;

		hora = sContenido.substring(0,2);
		min = sContenido.substring(3,5);
		seg = sContenido.substring(6,8);
	}
	else
	{
		if (sContenido.charAt(2)!=':')
			valido = false;

		hora = sContenido.substring(0,2);
		min = sContenido.substring(3,5);
		seg = sContenido.substring(3,5);
	}

	try
	{
		nhora = parseInt(hora);
		nmin = parseInt(min);
		nseg = parseInt(seg);
	}
	catch(e)
	{
		valido = false;
	}
	
	if (valido)
	{
		if (nhora > 23) valido= false;
		if (nmin  > 59) valido= false;
		if (nseg  > 59) valido= false;
	}
	
	if (!valido) document.getElementById(id).value='';
}

// Validacion de Pulsacion para Valores Numericos
function Validar_Pulsacion_Numeros()
{
	var numKey = new Number(window.event.keyCode);
	var sMensaje = new String('Solo se admiten valores numericos.');
	
	// Compruebo si el caracter pulsado es un Numero entre 0 y 9 (ASCII 48-57)
	if ((numKey < 48 || numKey>57) && numKey!=13)
	{
			ShowMensaje(sMensaje);
			return false;
	}
}

// Validacion de Parametro como Numero
function Validar_Es_Numerico( sValor )
{
	var sCompara = new String( sValor );
	var nPosComa = new Number( sValor.indexOf( ",",1));
	
	// Validacion de valor con decimales
	if (nPosComa >= 0)
	{
		// Reemplazo la "," por un "." para poder evaluar si es un numerico o no
		sCompara= sCompara.replace(',','.')
		var nNumero = new Number( sCompara );
	}
	else
		var nNumero = new Number( sCompara );
		
	// Compruebo que el valor es un numerico
	if(isNaN(nNumero))
		return false;
}

// Validacion de Parametro como Fecha correcta.
function Validar_Es_Fecha(sValor)
{
	var sFecha = new String(sValor);
	var strDia = new String();
	var Mes  = new String();
	var Year = new String();
	var intPos1 = new Number();
	var intPos2 = new Number();

	//Si la fecha esta en blanco no hace falta validar, de momento
	if( sFecha.length <= 0)
		return true;
	
	// Obtener la primera posicion de la "/" o "-"
	intPos1 = sFecha.indexOf("/", 1);
	if (intPos1 < 0)
		intPos1 = sFecha.indexOf("-", 1);
	
	// Obtener la segunda posicion de la "/" o "-"	
	intPos2 = sFecha.indexOf( "/", intPos1+1);
	if (intPos2 < 0)
		intPos2 = sFecha.indexOf("-", intPos1+1);
	
	// Si no existe ninguna barra en la primera posicion,
	// igualar la variable a 0 para que no de error al buscar.
	if(intPos1 < 0)
		intPos1 = 0;
	
	// Si no existe ninguna barra en la segunda posicion,
	// igualar la variable a 0 para que no de error al buscar.
	if(intPos2 < 0)
		intPos2=0;
	
	// Partir Fecha en Day, Month, Year
	if(intPos1 <= 0)
		strDia = sFecha.substr(0, sFecha.length);
	else
		strDia = sFecha.substr(0, intPos1);
	
	if(intPos2 <= 0)
		Mes = sFecha.substr(intPos1+1, sFecha.length-(intPos1+1));
	else
		Mes = sFecha.substr(intPos1+1, intPos2-(intPos1+1));
	
	Year = sFecha.substr(intPos2+1,4);
	
	// Convertir el Mes a numerico.
	var Mes1 = new Number(Mes);
	var Dia1 = new Number(strDia);
	var Year1 = new Number(Year);

	// Comprobacion de fecha valida
	if(EsUnaFecha(Mes1, Dia1,Year1) == false)
	{
		return false;
	}
}

// Extension del control TextBox para que contemple el tipo DNI/CIF
//*****************************************************************

// Llama a las funciones de validacion de DNICIF
// Para ver los detalles del algoritmo que se sigue
// y de la normativa espanyola de emision de DNIs/CIFs
// consultar la Documentacion asociada a este Control
function Validar_Es_DNICIF (sValor)
{
	var _DNICIF = new String( sValor );

	// No es preciso validar el campo si no viene informado
	if (sValor.length < 1)
		return true;
	else
	if (sValor.length < 9)
	{
		ShowMensaje('La longitud del DNI/CIF no es correcta');
		return false;
	}
	
	// Eliminamos espacios en blanco de la entrada
	var sDNICIF = quitarEspacios (_DNICIF);	
	sDNICIF = sDNICIF.toUpperCase();
	
	var strTemp, strLetra;
	var i;
	var resultado;
	
	// Tratamiento correspondiente a NIF - DNI si 1er caracter es numerico
	if (parseInt(sDNICIF.charAt(0)))
	{
		resultado = DigitoNIF(sDNICIF.substring(0,8));
	}
	else
	// Tratamiento correspondiente a un CIF
	{
		if (sDNICIF.charAt(0)== "X") // es un NIE
		{
			var sinX=(sDNICIF.toString()).substring(1,(sDNICIF.toString()).length-1);
			resultado = DigitoNIF(sinX);
		}
		else
		{
			// Comprobamos que el caracter de comienzo sea legal
			var letrasComienzoCIF = 'ABCDEFGHKLMNPQS';
			if (letrasComienzoCIF.charAt(sDNICIF.charAt(0)) != -1)
			{
				resultado = DigitoCIF((sDNICIF.toString()));
			}
		}
	}

	// Devolvemos el resultado de comparar el caracter de control calculado
	// con el caracter de control de la cadena de entrada
	if (sDNICIF.charAt(8) == resultado)
		return true;
	else
	{
		ShowMensaje('El DNI/CIF introducido no es correcto');
		return false;
	}
}

//Funcion que Elimina espacios en blanco de principio y fin de una cadena de texto (TRIM)
function quitarEspacios(cadena) 
{
	var cadenaSinEspaciosDelante = "";
	if(cadena != "")
	{
		cadenaSinEspaciosDelante = (cadena.replace(/^\s+/,'')).replace(/\s+$/,'');
	}	
		
	return cadenaSinEspaciosDelante;
}

// Calculo del Caracter de Control correspondiente a la parte numerica del DNI informado
function DigitoNIF(lngDNI)
{
	var res;
	var referenciaLetras = "TRWAGMYFPDXBNJZSQVHLCKE";
	res = referenciaLetras.charAt(lngDNI%23);
	return res;
}

// Calculo de caracter de Control para CIF
// Devuelve 
// A = 1    B = 2    C = 3    D = 4    E = 5
// F = 6    G = 7    H = 8    I = 9    J = 0
function DigitoCIF(strCif)
{
	var i, lngTemp;
	var resultado;
	i=0;
	resultado = " ";
	lngTemp = 0;
	
	var pares=0;
	var impares=0;
	var sumadigitos;

	for (i=1; i < (strCif.toString()).length-1; i++)
	{
		var prueba = (strCif.toString()).length-1;
		var text = (strCif.toString()).substring(1,prueba);

		if (i%2 == 0)
		{
			pares += parseInt(text.substring((i-1),i));
		}
		else
		{
			sumadigitos = parseInt(text.substring((i-1),i));
			sumadigitos = sumadigitos*2;

			if ((sumadigitos.toString()).length < 2)
			{
				sumadigitos = parseInt(sumadigitos);
			}
			else
			{
				sumadigitos = parseInt((sumadigitos.toString()).substr(0,1))+ 
							  parseInt((sumadigitos.toString()).substr(1,1));
			}
			impares += parseInt(sumadigitos);
		}
	}
	
	lngTemp = pares + impares;
	lngTemp = parseInt((lngTemp.toString()).substr((lngTemp.toString()).length-1,1));
	lngTemp = 10 - lngTemp;

	if (lngTemp == 10)
	{
		resultado = "j";
	}
	else
	{
		if (strCif.charAt(0)== 'P')
		{
			if(lngTemp == 1){resultado = "A";}
			if(lngTemp == 2){resultado = "B";}		
			if(lngTemp == 3){resultado = "C";}
			if(lngTemp == 4){resultado = "D";}	
			if(lngTemp == 5){resultado = "E";}	
			if(lngTemp == 6){resultado = "F";}	
			if(lngTemp == 7){resultado = "G";}
			if(lngTemp == 8){resultado = "H";}		
			if(lngTemp == 9){resultado = "I";}		
		}
	  else
		resultado = lngTemp;
	}
	
	return resultado;
}

// Creacion + Inicializacion de Array de longitud n
function CrearArray(n) 
{
   for (var i = 1; i <= n; i++) 
   {
      this[i] = 0;
   } 
   return this;
}

function DiasEnFebrero(whichYear)
{
    return (whichYear % 4 == 0 && (!(whichYear % 100 == 0) || (whichYear % 400 == 0)) ? 29 : 28);
}

// Validacion de Fechas
function EsUnaFecha(mm, dd, yyyy) 
{
	if (dd==0)
	{
		ShowMensaje ("Date Error");
		return false;
	}

	if (dd !="" && !(dd > 0 && dd< 32))
	{
		ShowMensaje ("Date Error");
		return false;
	}
	
	if ((dd!="" && mm!="") && dd > diasCadaMes[mm])
	{
		ShowMensaje ("Date Error")
		return false;
	}

	if( mm==0)
	{
		ShowMensaje ("Date Error");
		return false;
	}
	
	if (mm !="" && !(mm > 0 && mm < 13))
	{
		ShowMensaje ("Date Error");
		return false;
	}
	
	if(yyyy==0)
	{
		ShowMensaje ("Date Error");
		return false;
	}
	
	if (yyyy !="" && !(yyyy > 1889 && yyyy < 2050))
	{
		ShowMensaje ("Date Error");
		return false;
	}

	if ((mm=="2" || mm=="02" && dd!="" && yyyy!="") && dd > DiasEnFebrero(yyyy))
	{
		ShowMensaje ('Date Error');
		return false;
	}

	return true;
}

//////////////////////////////////////////////////////
/// CONTROL EXCLUSION
/////////////////////////////////////////////////////
function quitaDeRequeridos (eElemento, aArray)
{
		aAux = new Array ();
		aAux = aArray;
		ShowMensaje('aAux.length'+ aAux.length)
		
		for (k=0; k<aAux.length; k++)
		{
			ShowMensaje(aAux[k]);
			ShowMensaje('aAux['+k+'].length ='+aAux[k].length);
		}
}

// InHabilitacion de Campos
//Esta funcion bloquea/oculta Controles, pero no funciona bien con controles compuestos,
//es sustituida por HabilitaCamposNuevo.
function HabilitaCampos(aCampos, oOrigen, InBorrar, acer, modo, tipo)
{
	oSplitted = new Array ();
	oTr = new Array ();
	oSplitted = acer.split('|');

	if (tipo == "desactivado")
	{
		if (oOrigen.checked == true || oOrigen.checked == 'checked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');
				var aInput = document.getElementsByName(oTr[0]);

				if (modo=='oculto')
				{
					document.getElementById(oTr[0]).style.display='none';
				}
				else
				{
					try
					{
						aInput[0].disabled = true;			
					}
					catch (ex)
					{}
				}
			}
		}
		else if (oOrigen.checked  == false || oOrigen.checked  == 'unchecked')
		{
			for(i=1; i <= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);
				if (aInput != null)
				{
					if (modo=='oculto')
					{
						document.getElementById(aCampos[i]).style.display='block';
					}
					else
					{
						try
						{
							aInput[0].disabled = false;
						} catch (ex)
						{}
					}
				}//if aInput
			}//for i
		}//else if
	}
	else
	{
		if (oOrigen.checked == false || oOrigen.checked == 'unchecked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');
				
				var aInput = document.getElementsByName(oTr[0]);
				if ( aInput != null)
				{
					if (modo=='oculto')
					{
						try
						{
							aInput[0].style.display = 'none';
						}
						catch(ex)
						{
						}
					}
					else
					{
						try
						{
							aInput[0].disabled = true;			
						} catch (ex)
						{}
					}
				}
			}//for
		}
	
		else if (oOrigen.checked == true || oOrigen.checked == 'checked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);
				if (modo=='oculto')
				{
					document.getElementById(aCampos[i]).style.display = 'block';
				}
				else
				{
					if (aInput[0] != null)
					{
						aInput[0].disabled = false;
					}
				}
			}//for
		}//else if
	}
}

//Funcion Creada para solucionar Problema de Controles compuestos 
//para lo que se anyade un nuevo parametro de entrada,
//un array que contiene el tipo de cada control.
//(Para algunos controles, ademas, anyade cada uno de los controles que lo forman, como el Control FechaDesdeHasta).
function HabilitaCamposNuevo(aCampos, oOrigen, InBorrar, acer, modo, tipo, aTipoControl)
{
	oSplitted = new Array ();
	oTr = new Array ();
	oSplitted = acer.split('|');

	oTipoControles = new Array ();
	oTipoControles = aTipoControl.split('|');
	
	if (tipo == "desactivado")
	{
		if (oOrigen.checked == true || oOrigen.checked == 'checked')
		{
			for(i=1; i <= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');
				var aInput = document.getElementsByName(aCampos[i]);

				if (modo=='oculto')
				{
						
					//Controlar si es un control compuesto, porque en ese caso, 
					//hay que tratar cada uno de sus controles por separado, 
					//esto en principio solo es necesario para ocultar, 
					//ya que si no da fallos(al menos en el control Texto_Fecha_Ayuda),
					//se anyade tambien en el bloqueo por seguridad (aunque el bloqueo lo hace bien).
					if(oTipoControles[i-1]=='FechaAyuda')
					{
						document.getElementById(aCampos[i]+'_TextoFecha').style.display = 'none';
						document.getElementById(aCampos[i]+'_BotonFecha').style.display = 'none';
					}
					else
					{
						document.getElementById(aCampos[i]).style.display='none'
					}					
				}//if modo
				else
				{
					try
					{
						aInput[0].disabled = true;			
					}
					catch (ex)
					{}
				}//else modo
			}//for
		}
		else if (oOrigen.checked  == false || oOrigen.checked  == 'unchecked')
		{
			for(i=1; i <= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);

				if (aInput != null)
				{
					if (modo=='oculto')
					{
						if(oTipoControles[i-1]=='FechaAyuda')
						{
							document.getElementById(aCampos[i]+'_TextoFecha').style.display = 'block';
							document.getElementById(aCampos[i]+'_BotonFecha').style.display = 'block';
						}
						else if(oTipoControles[i-1]=='FechaDesde')
						{
							document.getElementById(aCampos[i]+'_FechaDesde_BotonFecha').style.display = 'block';
							document.getElementById(aCampos[i]+'_FechaDesde_TextoFecha').style.display = 'block';
							document.getElementById(aCampos[i]+'_FechaHasta_BotonFecha').style.display = 'block';
							document.getElementById(aCampos[i]+'_FechaHasta_TextoFecha').style.display = 'block';
						}
						else
						{
							document.getElementById(aCampos[i]).style.display='block';
						}					
					}
					else
					{
						try
						{
							aInput[0].disabled = false;
						}
						catch (ex)
						{}
					}
				}//if aInput
			}//for
		}
	}
	else
	{
		if (oOrigen.checked == false || oOrigen.checked == 'unchecked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');

				var aInput = document.getElementsByName(aCampos[i]);
				if (aInput != null)
				{
					if (modo=='oculto')
					{
						if(oTipoControles[i-1]=='FechaAyuda')
						{
							document.getElementById(aCampos[i]+'_TextoFecha').style.display = 'none';
							document.getElementById(aCampos[i]+'_BotonFecha').style.display = 'none';
						}
						else
						{
							document.getElementById(aCampos[i]).style.display = 'none';
						}
					}
					else
					{
						try
						{
							aInput[0].disabled = true;
						}
						catch (ex)
						{}
					}
				}//if aInput
			}//for
		}
		else if (oOrigen.checked  == true || oOrigen.checked  == 'checked')
		{
			for(i=1; i <= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);

				if (modo=='oculto')
				{
					if(oTipoControles[i-1]=='FechaAyuda')
					{
						document.getElementById(aCampos[i]+'_TextoFecha').style.display='block';
						document.getElementById(aCampos[i]+'_BotonFecha').style.display='block';
					}
					else if(oTipoControles[i-1]=='FechaDesde')
					{
						document.getElementById(aCampos[i]+'_FechaDesde_BotonFecha').style.display='block';
						document.getElementById(aCampos[i]+'_FechaDesde_TextoFecha').style.display='block';
						document.getElementById(aCampos[i]+'_FechaHasta_BotonFecha').style.display='block';
						document.getElementById(aCampos[i]+'_FechaHasta_TextoFecha').style.display='block';
					}
					else
					{
						document.getElementById(aCampos[i]).style.display='block';
					}
				}
				else
				{
					if (aInput[0] != null)
					{
						aInput[0].disabled = false;
					}
				}
			}//for
		}//else if
	}
}

// InHabilitacion de Campos
function HabilitaCampos2( aCampos, oOrigen, InBorrar, acer, modo, tipo)
{
	// Habilitacion
	oSplitted = new Array ();
	oTr = new Array ();
	oSplitted = acer.split('|');

	if (tipo == "desactivado")
	{
		if (oOrigen.checked == true || oOrigen.checked == 'checked')
		{
			for(i=1; i <= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');
				var aInput = document.getElementsByName(oTr[0]);

				if (modo=='oculto')
				{
					document.getElementById(oTr[0]).style.display = 'none';
				}
				else
				{
					aInput[0].disabled = true;
				}
			}
		}
		else if (oOrigen.checked  == false || oOrigen.checked  == 'unchecked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);
				if (modo=='oculto')
				{
					document.getElementById(aCampos[i]).style.display = 'block';
				}
				else
				{
					aInput[0].disabled = false;
				}
			}	
		}
	}
	
	else
	{
		if (oOrigen.checked == false || oOrigen.checked == 'unchecked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				oTr = aCampos[i].split('*');
				var aInput = document.getElementsByName(oTr[0]);

				if (modo=='oculto')
				{
					document.getElementById(oTr[0]).style.display='none'
				}
				else
				{
					aInput[0].disabled = true;			
				}
			}//for
		}//if
	
		else if (oOrigen.checked  == true || oOrigen.checked  == 'checked')
		{
			for( i=1; i<= aCampos.length-1; i++)
			{
				var aInput = document.getElementsByName(aCampos[i]);

				if (modo=='oculto')
				{
					document.getElementById(aCampos[i]).style.display='block'
				}
				else
				{
					aInput[0].disabled = false;
				}
			}//for
		}//elseif
	}
}

function CambiaColorHabilitacion(obj)
{
	if( obj.disabled == true)
	{
		obj.style.backgroundColor=color_Inhabilitado.toString();
	}
	else
	{
		obj.style.backgroundColor=color_Habilitado.toString();
	}
}

/////////////////////////////////////////////////////
/// FIN CONTROL EXCLUSION
/////////////////////////////////////////////////////

// Validacion de Campos
//
function ValidaCampos(aCampos, aMensajes, varBar)
{
	var strMensaje = new String();
	var eldelfoco;

	for(i=1; i <= aCampos.length - 1; i++)
	{
		var aInput = document.getElementsByName(aCampos[i]);
		
		if(aInput.length > 0)
		{
			if(aInput[0].value=='' &&  aInput[0].disabled == false && aInput[0].style.display !='none')
			{
				strMensaje += aMensajes[i] + '\n';
				eldelfoco=aInput[0];
			}
			
			if (aInput[0].disabled == true)
				aInput[0].style.backgroundColor = color_NoRequerido.toString();
		}
	}
	
	if(strMensaje != '')
	{
		ShowMensaje(strMensaje);
		try
		{
			eldelfoco.focus();
		}
		catch(ex)
		{}
		return false;
	}
	return true;
}

function CambiaColor(obj)
{
	if(obj.value=='' && obj.disabled == false)
	{
		document.getElementById(obj.id).style.backgroundColor = color_Requerido.toString();
	}
	else
	{
		document.getElementById(obj.id).style.backgroundColor = color_NoRequerido.toString();
	}
}

function CambiaColor2(id)
{
	var obj = document.getElementById(id);
	if (obj != null)
	{
		if(obj.value=='' && obj.disabled == false)
		{
			document.getElementById(obj.id).style.backgroundColor = color_Requerido.toString();
		}
		else
		{
			document.getElementById(obj.id).style.backgroundColor = color_NoRequerido.toString();
		}
	}
}

function PasarItems(paramOrigen, paramDestino)
{
	var oOrigen = new Object(document.getElementById(paramOrigen));
	var oDestino = new Object(document.getElementById(paramDestino));
	
	for(i=0; i < oOrigen.options.length; i++)
	{
		if(oOrigen.options(i).selected == true)
		{
			var opt = new Option();
			opt.value = oOrigen.options[i].value;
			opt.text = oOrigen.options[i].text;
			oDestino.options.add(opt);
			oOrigen.options.remove(i);
		}
	}
}

/*Gestion de Combo Box */;
function InsertarTextoCampoHidden( cmbOrigen, txtOculto )
{
	var oCombo = new Object(document.getElementById(cmbOrigen));
	try
	{
		var lara = '';
		for (var v=0; v < oCombo.options.length; v++)
		{
			lara += (oCombo.options[v].selected == true) ? oCombo.options[v].text + '|' : '';
		}
		if (lara != '')
			lara = lara.substring (0, lara.length -1);
		document.getElementById(txtOculto).value = lara;
	}
	catch(e)
	{
	}
}

/* Gestion de Listas Dobles */
function BuildArrayInHidden (lstOrigen, txtOculto)
{
	var oLista = new Object(document.getElementById(lstOrigen));
	var miCadena = '';
	try
	{
		for (i=0; i<oLista.options.length; i++)
		{
			miCadena += oLista.options[i].text;
			miCadena += ':';
			miCadena += oLista.options[i].value;
			miCadena += '|';
		}
		
		document.getElementById(txtOculto).value = miCadena.substring(0,miCadena.length-1);
	}
	catch (e)
	{
	}
}

/* URL Coder & URL Decoder 
URL Encoding replaces spaces with "+" signs, and unsafe ASCII characters with 
"%" followed by their hex equivalent. Safe characters are defined in RFC2396. They are the 7-bit ASCII 
alphanumerics and the mark characters "-_.!~*'()". (Note that the standard 
JavaScript escape and unescape functions operate slightly 
differently: they encode space as "%20", and treat "+" as a safe character.) 
*/
function URLEncode(mistring)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = mistring;
	var encoded = "";
	var control1;
	var control2;
	
	for (var i = 0; i < plaintext.length; i++ )
	{
		var ch = plaintext.charAt(i);
	    if (ch == " ")
	    {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		}
		else if (SAFECHARS.indexOf(ch) != -1)
		{
		    encoded += ch;
		}
		else
		{
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255)
			{
			    ShowMensaje("Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" +
							"(URL encoding only supports 8-bit characters.)\n" +
							"A space (+) will be substituted.");
				encoded += "+";
			}
			else
			{
				encoded += "%";
				
				control1 = HEX.charAt((charCode >> 4) & 0xF);
				control2 = HEX.charAt(charCode & 0xF);

				// Adapatacion a Codificacion de Framework.NET
				if (control1 == 'B')
				{
					encoded+= 'c2%B';
					encoded+= control2;
				}
				else
				if (control1 == 'C')
				{
					encoded+= 'c3%8';
					encoded+= control2;
				}
				else
				if (control1 == 'D')
				{
					encoded+= 'c3%9';
					encoded+= control2;
				}
				else
				if (control1 == 'E')
				{
					encoded+= 'c3%a';
					encoded+= control2;
				}
				else
				if (control1 == 'F')
				{
					encoded+= 'c3%b';
					encoded+= control2;
				}
				else
				{
					encoded+= control1;
					encoded+= control2;
				}
			}
		}//else
	} // for
	
	return encoded;
}

function URLDecode(mistring)
{
	// - Replace + with ' '
	// - Replace %xx with equivalent character
	// - Put [ERROR] in output if %xx is invalid.
	var HEXCHARS = "0123456789ABCDEFabcdef"; 
	var encoded = mistring;
	var plaintext = "";
	var i = 0;

	while (i < encoded.length)
	{
       var ch = encoded.charAt(i);
	   if (ch == "+")
	   {
	       plaintext += " ";
		   i++;
	   }
	   else
	   if (ch == "%")
	   {
			if (i < (encoded.length-2) &&
				HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 &&
				HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 )
			{
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			}
			else
			{
				ShowMensaje( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		}
		else
		{
		   plaintext += ch;
		   i++;
		}
	}

	return plaintext;
}

// Funcion de Cambio de Check para DataGrid
function cambiaCheck (fila, latabla, multiple, color, bgColor)
{
	var mitabla = document.getElementById(latabla);

	if (mitabla.disabled != true)
	{

		if (multiple == 'true')
			for (i=0; i < mitabla.rows.length; i++)
			{
				for (j=0; j<mitabla.rows[i].cells.length; j++)
					if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
					{
						var ado = mitabla.rows[i].cells[j].innerHTML
						var st = new Array();
						st = ado.split(' ');
						for (h=0; h < st.length; h++)
						{
							if (st[h].indexOf('id=') != -1)
							{
								var st2 = new Array();
								st2 = st[h].split('=');
			
								var check = document.getElementById(st2[1]);
								if (check.checked == true &&
								    fila != mitabla.rows[i])
								{
									check.checked = false;
									//### CSS Review
									mitabla.rows[i].style.backgroundColor = mitabla.rows[i].lang; 
									mitabla.rows[i].Color = "#FFFFFF";
									cambiaFuente ( mitabla.rows[i], colorTexto);
								}
							}
						}//for h
					}//if
			}//for i
		else
		{
			for (i=0; i < mitabla.rows.length; i++)
			{
				for (j=0; j<mitabla.rows[i].cells.length; j++)
					if (mitabla.rows[i].cells[j].innerHTML.indexOf('checkbox')!=-1)
					{
						var ado = mitabla.rows[i].cells[j].innerHTML
						var st = new Array();
						st = ado.split(' ');
						
						for (h=0; h < st.length; h++)
						{
							if (st[h].indexOf('id=') != -1)
							{
								var st2 = new Array();
								st2 = st[h].split('=');
				
								var check = document.getElementById(st2[1]);
								if (check.checked != true)
								{
									mitabla.rows[i].style.backgroundColor = mitabla.rows[i].lang; 
									cambiaFuente (mitabla.rows[i], colorTexto);						
								}
							}
						}//for h
					}//if
			}//for i
		}//else
		
		for (j=0; j<fila.cells.length; j++)
			if (fila.cells[j].innerHTML.indexOf('checkbox')!=-1)
			{
				var adof = fila.cells[j].innerHTML;
				var stf = new Array();
				stf = adof.split(' ');
				
				for (h=0; h < stf.length; h++)
				{
					if (stf[h].indexOf('id=') != -1)
					{
						var st2f = new Array();
						st2f = stf[h].split('=');
						var checkf = document.getElementById(st2f[1]);
						if (checkf.checked == true)
						{
							checkf.checked = false;
							cambiaFuente (fila, colorTexto);
							fila.style.backgroundColor = fila.lang; 
						}
						else
						{
							checkf.checked = true;
							fila.style.backgroundColor = color; 
							cambiaFuente (fila, colorTextoSelect);
						}
					}
				}//for h
			}
	}//if
}//function

function cambiaFuente (fila, colorSelec)
{	
	for (m=0; m< fila.children.length; m++)
	{
		var elChild = fila.children[m];
		elChild.style.color = colorSelec;

		if (elChild.children.length > 0)
		{
	 		for (v=0; v < elChild.children.length ; v++)	
			{
				var elNieto = elChild.children[v];
				if (elNieto.innerText != '')
					elNieto.style.color = colorSelec;
			}
		}
	}
}

function tratarAccionToolbar(accion)
{
	elhidden=document.getElementById('SAM_ToolbarHidden');
	elhidden.value=accion;
	
	document.forms[0].submit();
	elhidden.value="";
}

function TabClicadoConMensaje(idtab,webform,id,textoconfirma,habilitados,visibles,atrue)
{
	

	document.cookie = id + '_cookie=' + idtab;

	hiddidtab=document.getElementById('SAM_TabClicked');
	hiddtabform=document.getElementById('SAM_TabWebForm');

	var datos = idtab + '|' + habilitados + '|' + visibles + '|' + atrue;
	var texto = '';
	
	var aInput = document.getElementsByName(textoconfirma);
	if (aInput.length > 0)
		texto = aInput[0].mensaje;
	else
		texto = textoconfirma;
	
	var res = 'Aceptar';
	
	if (textoconfirma!=true && textoconfirma!='')
		res = ShowMensajeConfirmacion(texto);
	
	if (res=='Aceptar')
	{
		hiddidtab.value=datos;
		hiddtabform.value=webform;
		document.forms[0].submit();
	}
	
}

function dosubmit ()
{
	document.forms[0].submit();
}

function TabClicadoConConfirmacion(idtab,webform,id,textoconfirma,habilitados,visibles,atrue,boton)
{
	hiddidtab = document.getElementById('SAM_TabClicked');
	hiddtabform = document.getElementById('SAM_TabWebForm');

	var elboton = document.getElementById(boton);

	var datos = idtab + '|' + habilitados + '|' + visibles + '|' + atrue;

	var texto = '';
	var aInput = document.getElementsByName(textoconfirma);
	if (aInput.length>0)
		texto = aInput[0].mensaje;
	else
		texto = textoconfirma;

	if (textoconfirma!=true && textoconfirma!='')
	{
		res = ShowMensajeTab(texto);

		if (res=='Aceptar')
		{
			if (elboton.onmousedown != null)
			{
				var cadmup2 = elboton.onmousedown.toString();	
				var ncad2 =  cadmup2.substring(cadmup2.indexOf('{')+1, cadmup2.indexOf('}'));
				var nF2 = new Function(ncad2);
				var ls2 = nF2();

				if (ls2 == false)
					return false;
			}

			if (elboton.onmouseup != null)
			{
				var cadmup = elboton.onmouseup.toString();	
				var ncad =  cadmup.substring(cadmup.indexOf('{')+1, cadmup.indexOf('}'));
				var nF = new Function(ncad);
				var ls = nF ();

				if (ls == false)	
					return false;						
			}

			if (elboton.onclick != null)
			{
				var cadmup = elboton.onclick.toString();	
				var ncad =  cadmup.substring(cadmup.indexOf('{')+1, cadmup.indexOf('}'));
				var nF = new Function(ncad);
				var ls = nF ();

				if (ls == false)	
					return false;						
			}
		
			//Guardar
			elboton.click();

			hiddidtab.value = datos;
			hiddtabform.value = webform;
			document.cookie = id + '_cookie=' + idtab;

			//Generar Retardo...
			for (var a=0; a < 1000000; a++)
			{
				var k = a;
			}

			dosubmit();
		}
		else if (res=='Cancelar')
		{
			//No guardo y cambio de Tab
			hiddidtab.value=datos;
			hiddtabform.value=webform;
			document.forms[0].submit();
			document.cookie = id + '_cookie=' + idtab;		
		}
		else
		{
			//No cambio de Tab
			hiddidtab.value='';
			hiddtabform.value='';
		}
	}
	else
	{
		hiddidtab.value=datos;
		hiddtabform.value=webform;
		document.forms[0].submit();	
	}
}


function tabclicked(idtab,webform,id,textoconfirma,habilitados,visibles,atrue,boton)
{
	
	if (boton!=null && boton!='' && textoconfirma!=null && textoconfirma!='')
	{
		TabClicadoConConfirmacion(idtab,webform,id,textoconfirma,habilitados,visibles,atrue,boton);
	}
	else if (boton==null || boton=='')
	{
		TabClicadoConMensaje(idtab,webform,id,textoconfirma,habilitados,visibles,atrue);
	}
}

function mostrarAyuda(code)
{
	var util = document.URL;
	util = util.replace(document.domain, '$');
	var util2 = util.split('$')[1];
	var util3 = util2.split('/')[1];
	var app = util3.split('.')[2];

	window.open('/SAM.AE.Web/presentacion/ayuda/ObtenerAyuda.aspx?codigo='+code+'&aplicacion='+util3);
}

function imprimir()
{
	window.print();
}

function returnRow (latabla, arrayMod, hiddenValor)
{
	var mitabla = document.getElementById(latabla);

	var misRows = '';
	for (k=0; k < arrayMod.length; k++)
	{

		for (i=0; i < mitabla.rows.length; i++)
		{
			for (j=0; j<mitabla.rows[i].cells.length; j++)
			{
				if ((mitabla.rows[i].cells[j].innerHTML.toLowerCase().indexOf('input') > -1) && (mitabla.rows[i].cells[j].innerHTML.toLowerCase().indexOf('text') > -1))
				{
					var ado = mitabla.rows[i].cells[j].innerHTML;
					ado = ado.replace('name=', '·');

					var st = new Array();
					st = ado.split('·');
					op = 0;
					var elId = '';
					op = (st[1].charAt(0)!= ' ' && st[1].charAt(0)!= '\'' && st[1].charAt(0)!= '"') ? 0:1;

					do
					{
						elId += st[1].charAt(op);
						op++;
					} while (st[1].charAt(op)!= ' '  && st[1].charAt(op)!= '>' && st[1].charAt(op)!= '\'' && st[1].charAt(op)!= '"' );

					if (rowFromTable(elId, latabla) == arrayMod[k])
					{
						misRows += getRow (mitabla.rows[i]);
						misRows += '¬';
					}
				}
			}
		}
	}

	var elhidden = document.getElementById(hiddenValor);
	elhidden.value =  misRows;
}

function getRow(larow)
{
	var nr = '';
	for (j=0; j < larow.cells.length; j++)
	{
		if ((larow.cells[j].innerHTML.toLowerCase().indexOf('input') > -1) && (larow.cells[j].innerHTML.toLowerCase().indexOf('value') > -1))
		{
			var ado = larow.cells[j].innerHTML;
			var conId = 1;
			if (ado.toLowerCase().indexOf('id=') > -1)
			{
				ado = ado.replace('id=', '·');
			}
			else
			{
				ado = ado.replace('name=', '·');
				conId = 0;
			}
			
			var st = new Array();
			st = ado.split('·');
			op = 0;
			var elId = '';
			op = (st[1].charAt(0)!= ' ' && st[1].charAt(0)!= '\'' && st[1].charAt(0)!= '"') ? 0:1;
			
			do
			{
				elId += st[1].charAt(op);
				op++;
			} while (st[1].charAt(op)!= ' ' && st[1].charAt(op)!= '\'' && st[1].charAt(op)!= '>' && st[1].charAt(op)!= '"' );
			  
			var elInput = (conId != 1) ? document.getElementsByName(elId)[0] : document.getElementById(elId);

			nr += elInput.value;
		}
		else
		{
			nr += larow.cells[j].innerText;
		}
		nr += "|";
	}

	return nr.substring(0, nr.length-1);
}

function rowFromTable (idRaba, tabla)
{
	var latab = document.getElementById(tabla);
	if (idRaba == '')
		return -1;
	for (i=0; i < latab.rows.length; i++)
		if (latab.rows[i].innerHTML.toLowerCase().indexOf(idRaba.toLowerCase()) > -1)
			return i;	

	return -1;
}

// Funciones de Ordenacion de DataGrid

currentCol = 0;
previousCol = -1;
pulsaDos = -1;

function CompareAlpha(a, b)
{
	if (a[currentCol] < b[currentCol])	return -1;
	if (a[currentCol] > b[currentCol])	return 1;
	return 0;
}

//Exactamente Igual a CompareAlpha. Mantenida por Compatibilidad.
function CompareAlpha2(a, b)
{
	if (a[currentCol] < b[currentCol])	return -1;
	if (a[currentCol] > b[currentCol])	return 1;
	return 0;
}

function CompareAlphaIgnore(a, b)
{
	strA = a[currentCol].toLowerCase();
	strB = b[currentCol].toLowerCase();

	if (strA < strB)
		return -1;
	else
	if (strA > strB)
		return 1;
	else
		return 0;
}

function CompareDate(a, b)
{
	// This one works with date formats conforming to Javascript specifications, e.g. m/d/yyyy
	datA = new Date(a[currentCol]);
	datB = new Date(b[currentCol]);
	
	if (datA < datB)
		return -1;
	else
	if (datA > datB)
		return 1;
	else
		return 0;
}

function CompareDateEuro(a, b) 
{	
	var date1, date2;
	var month1, month2;
	var year1, year2;
   
	if (a == '' || a == ' ')
		return -1;
	if (b == '' || b == ' ')
		return 1;

	date1 = a.substring (0, a.indexOf ("/"));
	month1 = a.substring (a.indexOf ("/")+1, a.lastIndexOf ("/"));
	year1 = a.substring (a.lastIndexOf ("/")+1, a.split(' ')[0].length);

	date2 = b.substring (0, b.indexOf ("/"));
	month2 = b.substring (b.indexOf ("/")+1, b.lastIndexOf ("/"));
	year2 = b.substring (b.lastIndexOf ("/")+1, b.split(' ')[0].length);

	try
	{
		if ((year1) > (year2)) return 1;
		else
		if ((year1) < (year2)) return -1;
		else
		if ((month1) > (month2)) return 1;
		else
		if ((month1) < (month2)) return -1;
		else
		if ((date1) > (date2)) return 1;
		else
		if ((date1) < (date2)) return -1;
		else return 0;
		
   } catch (ex)
   {
	   return 0;
   }
}

function CompareNumeric(a, b)
{
	numA = a;
	numB = b;
	
	if (isNaN(numA))
		return 0;
	else
	{
		if (isNaN(numB))
			return 0;
		else
			return numA - numB;
	}
}

function getInnerText(laCelda)
{
	if (laCelda.innerText != '' && laCelda.innerText != ' ')
		return laCelda.innerText;
  
	if ((laCelda.innerHTML.toLowerCase().indexOf('input') > -1) &&
	    (laCelda.innerHTML.toLowerCase().indexOf('value') > -1) &&
	    (laCelda.innerHTML.toLowerCase().indexOf('check') == -1))
	{
		var ado = laCelda.innerHTML;
		var conId = 1;
		if (ado.toLowerCase().indexOf('id=') > -1)
		{
			ado = ado.replace('id=', '·');
		}
		else
		{
			ado = ado.replace('name=', '·');
			conId = 0;
		}
			
		var st = new Array();
		st = ado.split('·');
		op = 0;
		var elId = '';
		op = (st[1].charAt(0)!= ' ' && st[1].charAt(0)!= '\'' && st[1].charAt(0)!= '"') ? 0:1;
		do
		{
			elId += st[1].charAt(op);
			op++;	
		} while (st[1].charAt(op)!= ' ' && st[1].charAt(op)!= '\'' && st[1].charAt(op)!= '>' && st[1].charAt(op)!= '"' );
			  
		var elInput = (conId != 1) ? document.getElementsByName(elId)[0] : document.getElementById(elId);

		return elInput.value;
	}//if

	return '';
}

function clicaServer (columna, sentido, laSource)
{
	var elsentido = document.getElementById(sentido);
	var mySource = document.getElementById (laSource);
	var myCol = 0;
	var images = new Array();

	images = document.getElementsByTagName ('IMG');

	var controlPag;

	for (o=0; o < mySource.rows[0].cells.length; o++)
	{
		if (columna == mySource.rows[0].cells[o])
			myCol = o;
	}

	var columnas=document.getElementById ('hiddenColumnas_'+laSource);
	var ejecuta='false';

	var st = new Array();
	st = columnas.value.split('|');

	for (h=0; h < st.length-1; h++)
		if(st[h] == myCol)
		{
			ejecuta='true';
			break;
		}

	if (ejecuta == 'false') return;
	
	for (var i=0; i < images.length; i++)
	{
		if ((images[i].src.toString().indexOf('firstoff.gif') != -1)|(images[i].src.toString().indexOf('lastoff.gif') != -1)|(images[i].src.toString().indexOf('next.gif') != -1))
			controlPag = images[i].name;
	}

	document.cookie = 'GridServer_cookie=' + myCol + '|' + elsentido.value;

	if (elsentido.value == 'DESC')
		elsentido.value = 'ASC';
	else
		elsentido.value = 'DESC';

	__doPostBack(controlPag,'ordenacion');
}

function TableSort(myTable, lacelda, myType, latab) 
{
	// Create a two-dimensional array and fill it with the table's content
	var mySource = document.getElementById(myTable);
	var myRows = mySource.rows.length;
	var myCols = mySource.rows(0).cells.length;
	var myCol = 0;
	currentCol = myCol;
	myArray = new Array(myRows)
	myArrayHTML = new Array(myRows);

	var dos = document.getElementById(latab);
	for (var qo=0; qo < dos.rows[0].cells.length; qo++)
	{
		if (lacelda == dos.rows[0].cells[qo])
			myCol = qo;
	}
	
	// Determinar el tipo de ordenacion
	var eltipo;
	if (mySource.rows.length > 0)
	{
		// primera con algo
		var latete = '';
		var li=0;
		do
		{
			latete = mySource.rows[li].cells[myCol].innerText;
			li++;
		} while ((latete== '' || latete == ' ' || latete == '&nbsp;') && li < mySource.rows.length)	
		
		if (li < mySource.rows.length)	// Found
		{		
			// Discriminamos por longitud
			if (latete.length < 10) // No es una fecha
			{
				for (var a = 0; a <latete.length ; a++)
				{
					var nn = new Number(latete.charCodeAt(parseInt(a)));

					if (nn < 48 || nn > 57)
						eltipo = 'a'; // Alfanumerico
				}
				
				if (eltipo != 'a')	
					eltipo = 'n'; // Numerico	
			}
			else
			{
				// tratamos de hacer un objeto fecha
				if (latete.split('/').length > 2)
				{
					if (latete.split('/')[2].length > 1 && latete.split('/')[1].length > 0 && latete.split('/')[0].length > 0 )
						eltipo = 'de';  // Date European
				}
				if (eltipo != 'de')
				{
					for (var a = 0; a <latete.length ; a++)
					{
						var nn = new Number(latete.charCodeAt(parseInt(a)));
						if (nn < 48 || nn>57)
							eltipo = 'a'; // Alfanumerico
					}
					
					if (eltipo != 'a')
						eltipo = 'n'; // Numerico	
				}
			}//else
		}//if
	}//if
	
	myType = eltipo;

	for (var l=0; l < myRows; l++)
	{
		myArray[l] = new Array(myCols);
		myArrayHTML[l] = new Array(myCols);

		for (m=0; m < myCols; m++)
		{
			var innerT = getInnerText(mySource.rows(l).cells(m));
			var innerH =  mySource.rows(l).cells(m).innerHTML;

			myArray[l][m] = innerT;
			myArrayHTML[l][m] = innerH;
		}
	}

	var miarr = new Array();

	for (var m=0; m < myArray.length; m++)
	{
		miarr[miarr.length] = myArray[m][myCol];
	}
	
	var miarr2 = miarr;		
	var narr = new Array();
	
	switch (myType)
	{
		case "a":
			narr = miarr.sort();
			break;

		case "ai":
			narr = miarr.sort(CompareAlphaIgnore);
			break;

		case "d":
			narr = miarr.sort(CompareDate);
			break;

		case "de":
			narr = miarr.sort(CompareDateEuro);
			break;

		case "n":
			narr  = miarr.sort(CompareNumeric);
			break;

		default:
			narr = myArray.sort()
	}
	
	if (myCol == previousCol)
	{
		narr = narr.reverse(); // clicked the same column as previously - reverse the sort					
	}
	
	if (previousCol == myCol)
		previousCol = -1;
	else
		previousCol = myCol;
		
	for (i = 0; i < myRows; i++)
	{
		for (j=0; j<myRows; j++)
		{
			if (narr[i] == getInnerText(mySource.rows[j].cells[myCol]))
		    {
				for (x=0; x < myCols; x++)
				{
					myArrayHTML[i][x] = mySource.rows[j].cells[x].innerHTML;
				}
			}
		}
	}

	// Creamos el pivote
	var pivote = mySource.insertRow();

	var styl1 = new Array();
	styl1 =  getStyleNode (mySource.rows[0]);

	var styl2 = new Array();
	styl2 = getStyleNode (mySource.rows[1]);

	for (k=0; k < myRows; k++) 
	{
		var lai = findinnerHTML (mySource, myArrayHTML[k][myCol]);
		cloneRow (mySource.rows[parseInt(lai)], pivote);
	}
	
	deletePivote(pivote);

	for (v=0; v < myRows; v++) 
	{
		setAlternating (mySource.rows[parseInt(v)], v, styl1, styl2)
	}

	return 0;
}

function findinnerHTML (tabla, texto)
{
	for(i=0; i<tabla.rows.length; i++)
	{
		for (j=0; j < tabla.rows[i].cells.length; j++)
			if (tabla.rows[i].cells[j].innerHTML == texto)
				return i;
	}
	return -1;
}

function cloneRow(theRow, pivote)
{
	while(theRow && theRow.nodeName != "TR")
	{
		theRow = theRow.parentNode;
	}
	
	while(pivote && pivote.nodeName != "TR")
	{
		pivote = pivote.parentNode;
	}

    newRow = theRow.cloneNode(true);

	theRow.parentNode.insertBefore(newRow, pivote);
	theRow.parentNode.removeChild(theRow);
}

function setAlternating (theRow, ind, styl1, styl2)
{
	while(theRow && theRow.nodeName!="TR")
	{
		theRow = theRow.parentNode;
	}

    // Para Alternating de Estilos de Filas
	var losAtributos = new Array();

	for (h=0; h < theRow.attributes.length; h++)
	{
		losAtributos[h] = theRow.attributes[h].nodeName;          
	} 

	var origen = theRow.style.backgroundColor.toLowerCase();
	
	for (b=0; b < styl1.length; b++)
		theRow.setAttribute(losAtributos[b],styl1[b]);
	
	var lang1 = theRow.lang.toLowerCase();

	for (b=0; b < styl1.length; b++)
		theRow.setAttribute(losAtributos[b],styl2[b]);

	var lang2 = theRow.lang.toLowerCase();
	
	theRow.setAttribute(losAtributos[b],styl2[b]);
        
	for (b=0; b < styl1.length; b++)
	{
		if ((ind % 2) == 0)
			theRow.setAttribute(losAtributos[b],styl1[b])
		else
			theRow.setAttribute(losAtributos[b],styl2[b]);

		if (lang1 != origen && lang2 != origen )
			theRow.style.backgroundColor = origen;
		else
			theRow.style.backgroundColor = theRow.lang;
	}
}

function deletePivote(pivote)
{
	while(pivote && pivote.nodeName != "TR")
	{
		pivote = pivote.parentNode;
	}

	pivote.parentNode.removeChild(pivote);
}

function getStyleNode (pivote)
{
	while (pivote && pivote.nodeName != "TR")
	{
		pivote = pivote.parentNode;
	}
	
	var oAtr = new Array();

	for (h=0; h < pivote.attributes.length; h++)
	{
		oAtr[h] = pivote.getAttribute(pivote.attributes[h].nodeName);
	}
	
	return oAtr;
}

////////////////
// CALENDARIO //
////////////////

var SpecialDay	= 1;	// 1=Sunday, 2=Monday, . . . 7=Saturday
var SecSpecialD = 7;	// 1=Sunday, 2=Monday, . . . 7=Saturday	
var FontSize	= 1;

//### CSS Review
var ColorBackground	= "#FFFFCC";
var ColorSpecialDay	= "#FF0000";
var ColorSelected	= "#FFFFFF";
var ColorToday		= "#FFFFFF";

function refrescaCalendar(latabla, tipo, currentmo, currentyr, hmax, wmax, FirstMonth, LastMonth)
{
	hmax *= 8;
	wmax *=8;

	var months = new Array();

	if (tipo == 'europea')
		tipo = false;
	else
		tipo = true;

	var lat = document.getElementById(latabla);
	var curdy, curmo, dy, dayofweek, yearmonth, bgn, lastday, jump;

	//MultiIdioma
	var weekdays = new Array();
	if (tipo == true)
	{
		weekdays = weekdaysAnglo;
		months = monthsAnglo;
	}
	else	
	{
		weekdays = weekdaysHispa;
		months = monthsHispa;
	}

	var today = new Date();

	// Save current day and month for comparison
	curdy = today.getDate();
	curmo = today.getMonth()+1;
	yearmonth = (currentyr * 100) + currentmo;
	currentmo = yearmonth % 100;
	currentyr = (yearmonth - currentmo) / 100;
	
	// Constrain to the range of months with events
	if (yearmonth < FirstMonth) 
	{
		currentmo = FirstMonth % 100;
		currentyr = (FirstMonth - currentmo) / 100;
		yearmonth = FirstMonth;
	}
	
	if (yearmonth > LastMonth)
	{
		currentmo = LastMonth % 100;
		currentyr = (LastMonth - currentmo) / 100;
		yearmonth = LastMonth;
	}

	bgn = new Date(monthsAnglo[currentmo] + " 1," + currentyr);
	
	dayofweek = bgn.getDay();
	if (dayofweek == 0)
		dayofweek = 7;

	lastday = NumDaysIn(currentmo, currentyr);
	lat.rows[0].cells[0].innerText = months[currentmo] + currentyr;

	for (var i=1;i<=7;i++)
	{
		lat.rows[1].cells[i-1].innerText = weekdays[i];
	}
	dy = 1;

	for (var i=1;i<=7;i++)
	{
		var compar = (tipo == true) ? dayofweek + 1 : dayofweek;
		if (i < parseInt(compar))
		{
			lat.rows[2].cells[i-1].innerHTML = '<FONT SIZE=1>&nbsp;</FONT>';
		}
		else
		{
			refreshShowDate(currentyr,currentmo,dy,i,curmo,curdy, wmax,hmax, tipo, 2, i, latabla);
			dy++;
		}
	}
	
	var fila = 3;
	while (dy <= lastday)
	{
		for (var i=1;i<=7;i++)
		{
			if (dy > lastday)
			{
				lat.rows[fila].cells[i-1].innerHTML = '<FONT SIZE=1>&nbsp;</FONT>';
			}
			else
			{
				refreshShowDate(currentyr,currentmo,dy,i,curmo,curdy,wmax,hmax, tipo, fila, i, latabla);
				dy++;
			}
		}
		fila++;
	}
}

function refreshShowDate(yr, mo, dy, dayofweek, currentmonth, currentday, wmax,hmax, cultura, introw, intcolumn, latabla) 
{
	var ind, HighlightEvent, tmp='';
	var selectedColor = '';
	//### CSS Review
	selectedColor = '#551229';
	var fontWe = 'normal';
	var tab = document.getElementById(latabla);

	var compar = (cultura != true) ? dayofweek == 7 || dayofweek == 6 
								   : dayofweek == 7 || dayofweek == 1;
	if (compar)
	{
		selectedColor = ColorSpecialDay;
	}
	
	if ((mo == currentmonth) && (dy == currentday)) 
	{
		selectedColor = ColorToday;
	}

	var estilo = '';
	var arrayPre = new Array ();
	var elHid = document.getElementById(latabla+'_Texto');
	arrayPre = elHid.value.toString().split('|');

	if (ifFestivo(yr, mo, dy, arrayPre) == true)
	{
     	estilo += 'Festivos';
     	tdia = 'l';   			
	}
	else
	if (selectedColor == ColorSpecialDay)
	{
		estilo+= 'Findes';
		tdia = 'f';
	}
	else
	if (selectedColor == ColorToday)
	{
		estilo += 'Laborales';
		tdia = 'l';
	}
	else
	{
		estilo += 'Laborales';
		tdia = 'l';
	}
		
	var wboton =  parseInt(wmax)/8;
	var hboton =  parseInt(hmax)/8;

	var elmes = (mo < 10)? '0'+mo.toString():mo.toString();
	var eldia = (dy < 10)? '0'+dy.toString():dy.toString();

	var lacelda= "<input id='"+yr+elmes+eldia+"_"+latabla+"' type=button  class='" +estilo+ "' style='height:"+parseInt(wboton)+"; width:"+parseInt(hboton)+"' value='"+dy+"' onclick=\"cambiaColorCal ('"+yr+elmes+eldia+"_"+latabla+"','"+tdia+"','" + latabla.toString()+"');\"/><FONT SIZE=1>"+tmp+"</FONT></TD>"
	tab.rows[parseInt(introw)].cells[parseInt(intcolumn)-1].innerHTML = lacelda;
}

function cambiaColorCal (objeto, elDia, latabla)
{
	var ida = document.getElementById(objeto);

	var lara = false;
	if (ida.className == '')
	    lara = true;
	    
	if (ida.className == 'Laborales' || ida.className == 'Findes')
	{
		ida.className = 'Festivos';
	}
	else
	{
		if (elDia == 'f')
			ida.className = 'Findes';
		else
			ida.className = 'Laborales';
	}
	
	if (lara == true)
	{
		ida.className = 'Festivo';
	}
	
	var preCharged = new Array();
	var elHid = document.getElementById(latabla+'_Texto');

	preCharged = elHid.value.split('|');	
	
	if (ida.className == 'Festivos')
	{
		var esta = false;
		for (m=0; m< preCharged.length; m++)
			if (preCharged[m] == ida.id)
				esta = true;

		if (esta == false)
		{
			preCharged[preCharged.length] = ida.id.split('_')[0];
	   	}
	}
	else
	{
		for (m=0; m< preCharged.length; m++)
			if (preCharged[m] == ida.id.split('_')[0])
				preCharged[m] = '';
	}
	
	var as ='';
	for (m=0; m < preCharged.length; m++)
	{
		if (preCharged[m] != '')
			as += preCharged[m] + '|';
	}

	elHid.value = as.substring(0,as.length-1);
}

function NumDaysIn(mo,yr)
{
	if (mo==4 || mo==6 || mo==9 || mo==11)
		return 30;
	else
	if ((mo==2) && LeapYear(yr))
		return 29;
	else
	if (mo==2)
		return 28;
	else
		return 31;
}

function LeapYear(yr)
{
	return (((yr % 4 == 0) && yr % 100 != 0) || yr % 400 == 0);
}

// Fixes a Netscape 2 and 3 bug
function GetFullYear(d)
{ 
	// d is a date object
	var yr;

	yr = d.getYear();
	if (yr < 1000)
		yr += 1900;
		
	return yr;
}

function PrevMonth(mth)
{
	if (mth == 1)
		return 12;
	else
		return (mth-1);
}

function NextMonth(mth)
{
	if (mth == 12)
		return 1;
	else
		return (mth+1);
}

function PrevYearMonth(yrmth)
{
	if ((yrmth % 100) == 1)
		return ((yrmth-100)+11);
	else
		return (yrmth-1);
}

function NextYearMonth(yrmth)
{
	if ((yrmth % 100) == 12)
		return ((yrmth-11)+100);
	else
		return (yrmth+1);
}

function forward (id1, id2, lista, matrix, mos)
{
	mos++;
	if (mos > 12)
	{
		mos = 1;
	}

	var elcontrol = document.getElementById(id1);
	var index1 = (parseInt(mos+1)%12 == 0)? 12 : parseInt(mos+1)%12 ;
	elcontrol.title = matrix[index1].toString();

	var elcontrol2 = document.getElementById(id2);
	var index2 = (parseInt(mos-1)%12 == 0)? 12 : parseInt(mos-1)%12 ;
	elcontrol2.title = matrix[index2].toString();

	var lalista = document.getElementsByName(lista)[0];
	if (lalista.options.length > lalista.selectedIndex+1)//Marito --> puse el +1
		lalista.options[lalista.selectedIndex+1].selected = true;
	
	return mos;
}

function rewind (id1, id2, lista, matrix, mo)
{
	mo--;
	if (mo < 1)
	{
		mo = 12;
	}

	var elcontrol = document.getElementById(id1);
	var index1 = (parseInt(mo+1)%12 == 0)? 12 : parseInt(mo+1)%12 ;
	elcontrol.title = matrix[index1].toString();

	var elcontrol2 = document.getElementById(id2);
	var index2 = (parseInt(mo-1)%12 == 0)? 12 : parseInt(mo-1)%12 ;
	elcontrol2.title = matrix[index2].toString();
	
	var lalista = document.getElementsByName(lista)[0];
	if (lalista.selectedIndex > 0)
		lalista.options[lalista.selectedIndex-1].selected = true;

	return mo;
}

function forwardYear (lista, ano)
{
	var lalista = document.getElementsByName(lista)[0];
	if (lalista.options.length > lalista.selectedIndex +12)
		lalista.options[lalista.selectedIndex+12].selected = true;
	ano++;
	return ano;
}

function rewindYear (lista, ano)
{
	ano--;
	var lalista = document.getElementsByName(lista)[0];
	if (lalista.selectedIndex - 12 >= 0)
		lalista.options[lalista.selectedIndex-12].selected = true;
	return ano;
}

function arr() 
{
	for (var n=0;n<arr.arguments.length;n++) 
	{
		this[n+1] = arr.arguments[n];
	}
}

function ifFestivo (yr, mo, dy, preCharged)
{
	var elmes = (mo < 10)? '0'+mo.toString():mo.toString();
	var eldia = (dy < 10)? '0'+dy.toString():dy.toString();
	var lafecha = yr.toString() + elmes + eldia;	

	for (i=0; i < preCharged.length; i++)
    {
	    if (preCharged[i].toString().split('_')[0] == lafecha)
	    	return true;
	}
	return false;
}

function JumpTo(calendar, id1, id2, tipo, latabla, currentmo, currentyr, heightmax, widthwmax, FirstMonth, LastMonth, arrayPre) 
{
	var sel, yrmo;
	yrmo = calendar.options[calendar.selectedIndex].value;
	currentyr = parseInt(yrmo.substring(0,4));
	currentmo = parseInt(yrmo.substring(4,2));
	currentmo = yrmo % 100;
	currentyr = (yrmo - currentmo) / 100;
	var his = document.getElementById(latabla + '_status');
	his.value = yrmo;

	refrescaCalendar(latabla, tipo, currentmo, currentyr, heightmax, widthwmax, FirstMonth, LastMonth, arrayPre);

	return yrmo;
}

function CalculaAltura(texto)
{
	//Calcula la altura que deberia tener una ventana de mensaje que contuviera este texto
	 var k = texto.split('\n').length;
	 var l = 0, i = 0;
	 var res;
	 for (i =0; i<k ; i++)
	 {
		l = l + Math.floor((texto.split('\n')[i].length)/40);
	 }
	 var altura = 150 + 20*k + 12*l;
	 
	 return altura;
}

function ShowMensaje (texto)
{
	 var altura = CalculaAltura(texto);
	 
	 var aux = '/SAM.AE.Web/Errores/' + 'Mensaje.aspx?Tipo=Informativo&Mensaje='; 
	 aux = aux + URLEncode(texto); 
	 window.showModalDialog(aux,'','dialogHeight:'+altura+'px;dialogWidth:400px;center:yes;scroll:no;status:no;help:no;unadorned:yes'); 
}

function ShowMensajeConfirmacion(texto)
{
	 var altura = CalculaAltura(texto);
	 
	 var aux = '/SAM.AE.Web/Errores/' + 'Mensaje.aspx?Tipo=Confirmacion&Mensaje='; 
	 aux = aux + URLEncode(texto); 
	 return window.showModalDialog(aux,'','dialogHeight:'+altura+'px;dialogWidth:400px;center:yes;scroll:no;status:no;help:no;unadorned:yes'); 
}

function ShowMensajeTab(texto)
{
	var altura = CalculaAltura(texto);
	var aux = '/SAM.AE.Web/Errores/' + 'Mensaje.aspx?Tipo=Tab&Mensaje='; 
	aux = aux + URLEncode(texto); 

	return window.showModalDialog(aux,'','dialogHeight:'+altura+'px;dialogWidth:400px;center:yes;scroll:no;status:no;help:no;unadorned:yes'); 
}

function TransfiereCamposDelGrid(tabla,columna,componente)
{
	var dato = sacaValorDeGrid(tabla,columna);
	var alli = document.getElementById(componente);
	
	alli.value = dato;
}
		
// Gestiona los combos como columnas de un grid		
function selectCombo (latabla)
{
	var mitabla = document.getElementById(latabla);
	var miCheck;
	var miCadena = '';
	var nocurr = 0;

	for (var i=0; i < mitabla.rows.length; i++)
	{
		for (var j=0; j<mitabla.rows[i].cells.length; j++)
		{
			if (mitabla.rows[i].cells[j].innerHTML.indexOf('select')!=-1)
			{
				var ado = mitabla.rows[i].cells[j].innerHTML;
				var st = new Array();
				st = ado.split(' ');
				for (h=0; h < st.length; h++)
				{
					if (st[h].indexOf('name=') != -1)
					{
						var st2 = new Array();
						st2 = st[h].split('=');
						var elarray = new Array();
				
						elarray = document.getElementsByName(st2[1]);				
						if (elarray.length >0)
						{
							var lalista = elarray[0];
							if (lalista.textoselected != null)
								fijaSelected(lalista);
						}
					}
				}
			}
		}
	}
}
	
function fijaSelected (elcombo)
{
	var eltexto = elcombo.textoselected;
	for (var i=0; i< elcombo.options.length; i++)
	{
		if (elcombo.options[parseInt(i)].text == eltexto)
			elcombo.options[parseInt(i)].selected = true;
			
	}
}

function replaceSpecialCharacters (stringToConvert)
{
	/*
		var exp = new RegExp('&','g')
		stringToConvert=stringToConvert.replace(exp,'&amp;')
		exp = new RegExp("\"",'g')	
		stringToConvert=stringToConvert.replace(exp,'&quot;')
		exp = new RegExp("<","g")
		stringToConvert=stringToConvert.replace(exp,'&lt;')
		exp = new RegExp(">","g")
		stringToConvert=stringToConvert.replace(exp,'&gt;')
		exp = new RegExp("\'",'g');
		stringToConvert=stringToConvert.replace(exp,'&apos;');
	*/

	return escape(stringToConvert);
}
function reverseSpecialCharacters (stringToConvert)
{	
	return unescape(stringToConvert);
}

function Abrir_Calendario(param1, p)
{ 
	var myObject = new Object(); 
	myObject.fieldValue = document.getElementById(param1).value; 
	myObject.language =  p; 
	var sret = window.showModalDialog('/SAM.AE.Web/Presentacion/generales/calendar.aspx',myObject,'help:no;status:no;dialogTop:'+window.event.screenY+';dialogLeft:'+window.event.screenX+';dialogHeight:210px;dialogWidth:190px;'); 
	document.getElementById(param1).value= sret; 
	if(sret !='') 
		{CambiaColor(document.getElementById(param1))}; 
	document.getElementById(param1).focus(); 
} 