var SEPARADOR_CAMPO = ",";
var SEPARADOR_LINEA = "|";

function cleanSQL(str) {
	var aux;
	if (str.length == 0) {
		aux=' ';
	} else {
		aux = str.replace(new RegExp( "[^A-Za-z0-9_:.éáíóúñ/ @\n<>-]" ,"ig"), " ");
	}
	return(aux);
}
function Aplicar_formato_SQL(campo)
{
	campo.value = cleanSQL(campo.value);	
}

function Aplicar_formato_Replace(campo)
{
	campo.value = Replace(campo.value, "'", " ");	
}

function Aplicar_formato(campo)
{
	campo.value = formatCurrency(campo.value);	
}

function Aplicar_formato_Num(campo)
{
	campo.value = formatNumero(campo.value);	
}

function formatCurrency(num) 
{
	num = Replace (num, ",", ".");
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	/*for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));*/
	return (((sign)?'':'-') + num + '.' + cents);
}


function formatNumero(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	/*for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));*/
	return (((sign)?'':'-') + num);
}

function Fecha_menor_a_hoy(campo, mensaje)
{
	var strA = new String(campo.value);
	var strB = new String('<% = Date %>');
	var A = strA.split('/');
	var B = strB.split('/');
	var Hoy = new Date(B[1] + '/' + B[0] + '/' + B[2]);
	var Fecha = new Date(A[1] + '/' + A[0] + '/' + A[2]);
	if(Hoy.valueOf() > Fecha.valueOf())
	{
		alert(mensaje);
		campo.focus();
		campo.select();
		return(false);
	}
	return(true);
}

function Asignar_valor(Nombre_campo, Valor)
{
	for(i = 0; i < form.elements.length; i++)
	{
		if(form.elements[i].name == Nombre_campo) 
		{
			switch(form.elements[i].type)
			{	
				case "text":
					form.elements[i].value = Valor;
					return;
				case "password":
					form.elements[i].value = Valor;
					return;
				case "hidden":
					form.elements[i].value = Valor;
					return;
				case "textarea":
					form.elements[i].value = Replace(Valor, "._.", String.fromCharCode(13, 10));
					return;
				case "select-one":
					Buscar_valor_en_combo(form.elements[i], Valor);
					return;		
				case "radio":
					if(form.elements[i].value == Valor){
						form.elements[i].checked = true;
						return;							
					}
					else {form.elements[i].checked = false;}
			}
		}
	}
	return;
}


function Replace(Cadena, ValorBuscado, Reemplazo){
   var r, re                   
   var ss = Cadena
   re = new RegExp(ValorBuscado, "g")
   r = ss.replace(re, Reemplazo)    
   return(r);                   
}
/* Devuelve true si el valor del campo es numero entero */

function Es_numero(campo, mensaje)
{
	if (isNaN(campo.value) || campo.value <= 0)
	{
		Error_validacion(campo, mensaje);
		return(false);
	} 
	else 
	{
		var s = new String(parseInt(campo.value));
		if(s != campo.value)
		{	
			Error_validacion(campo, mensaje);
			return(false);
		} else return(true);
	}
}

/* Devuelve true si el valor del campo es numero */

function Es_numero_valido(campo, mensaje)
{
	if (isNaN(campo.value) || campo.value <= 0)
	{
		Error_validacion(campo, mensaje);
		return(false);
	} 
	else return(true);
}
		
/* Devuelve true si el valor de ambos campos es igual */

function Son_campos_iguales(campo1, campo2)
{
  if (campo1.value != campo2.value)
  {
    Error_validacion(campo1, "La confirmación del password no es correcta.");
	return(false);	
  } else 
    return(true);
}

/* Devuelve true si el valor del campos no es una cadena vacia */

function Es_campo_con_datos(ctrl, mensaje)
{
  if (ctrl.value == "") 
  {
    Error_validacion (ctrl, mensaje)
    return (false);
  } else
    return (true);
}  

function Es_campo_con_datos_cbo(ctrl, mensaje)
{
  if (ctrl == "") 
  {
   Error_validaciones (mensaje)
    return (false);
  } else
    return (true);
}  


/* Muestra un mensaje y asigna el foco a un campo */

function Error_validacion(ctrl, PromptStr) 
{
  alert (PromptStr)
  ctrl.select();
  ctrl.focus();
  return;
}

function Error_validaciones(PromptStr) 
{
  alert (PromptStr)
  return;
}

/* Selecciona en un combo la opcion con el valor pasado como parametro */

function Buscar_valor_en_combo(combo, valor)
{
  i = 0;
  while(i < combo.length)
  {
    if(combo.options[i].value == valor)
    {
      combo.selectedIndex = i;
      break;
    }
    i++;
  }
  return;
}

/* Selecciona en un combo la opcion con el texto igual al parametro */

function Buscar_texto_en_combo(combo, valor)
{
  i = 0;
  while(i < combo.length)
  {
    if(combo.options[i].text == valor)
    {
      combo.selectedIndex = i;
      break;
    }
    i++;
  }
  return;
}

/* Devuelve el valor de la opcion de un combo con el texto igual al pasado como parametro */ 

function Posicion_en_combo(combo, valor)
{
  i = 0;
  while(i < combo.length)
  {
    if(combo.options[i].text == valor) return(combo.options[i].value);
    i++;
  }
  return(-1);
}

/* Devuelve el texto de la opcion de un combo con el valor igual al pasado como parametro */ 

function Texto_valor_en_combo(combo, valor)
{
{
  i = 0;
  while(i < combo.length)
  {
    if(combo.options[i].value == valor) return(combo.options[i].text);
    i++;
  }
  return(-1);
}

}

function Es_fecha_valida(objName, mensaje) {
	if (chkdate(objName) == false) {
		Error_validacion(objName, mensaje)
		return false;
	}
	else {
		return true;
	}
}

function chkdate(objName) {
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("/");
	var intElementNr;
	var err = 0;
	strDate = datefield.value;
	if (strDate.length < 1) 
	{
		return true;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
	{
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
		{
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3)
			{
				err = 1;
				return false;
			}
			else 
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
	   }
	}
	if (booFound == false) 
	{
		return false;
	}
	if (strYear.length == 2) 
	{
		strYear = '20' + strYear;
	}
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) 
	{
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) 
	{
		if (isNaN(intMonth)) 
		{
			err = 3;
			return false;
	    }
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) 
	{
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) 
	{
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) 
	{
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
	{
		err = 7;
		return false;
	}
	if (intMonth == 2) 
	{
		if (intday < 1) 
		{
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) 
		{
			if (intday > 29) 
			{
				err = 9;
				return false;
			}
		}
		else
		{
			if (intday > 28) 
			{
				err = 10;
				return false;
			}
		}
	}
	return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) { return true; }
	}
	else 
	{
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}

function Compara_fecha(campo1,campo2,mensaje)
{
	/* campo1 comparacion campo2 */
	var strA= new String(campo1.value);
	var strB= new String(campo2.value);
	var A= strA.split('/');
	var B= strB.split('/');
	var Fecha1= new Date (A[1] + '/' + A[0] +'/'+ A[2]);
	var Fecha2= new Date (B[1] + '/' + B[0] +'/'+ B[2]);
	if(Fecha1.valueOf() > Fecha2.valueOf())
	{
		alert (mensaje);
		campo2.focus();
		campo2.select();
		return(false);
	}
	return(true);
}

// ----------------------------- Rutinas para tabla DHTML ---------------------------

var cellSelect = null

function insertSelector(r,contents) {
// Create a selector cell
	var c
	if (arguments[2]!=null)  // Insert before a particular cell
		c = r.insertCell(arguments[2])
	else
		c = r.insertCell()
	c.className = "selector"
    c.innerText = contents
}

function insertRow(Valores) {
// Insert Row
	var r
    if ((null==cellSelect) || (cellSelect.parentElement.id=="columns")) {
		r = document.all.editor.insertRow() // Insert at end of list
        insertSelector(r,"4")
      } else {
        // Insert before selected row
        var el = cellSelect.parentElement
        r = document.all.editor.insertRow(cellSelect.parentElement.rowIndex)
        insertSelector(r,"4")
        // Copy the currently selected row's layout
        for (var intLoop = 1; intLoop < el.cells.length; intLoop++) {
			var c = r.insertCell()
			c.innerHTML = Valores[intLoop-1]
			c.colSpan = el.cells[intLoop].colSpan
        } 
    }
}


function insertCell() {
	var el = document.all.editor
    var c
    if (null!=cellSelect) {
		var r = el.rows[0]
        if (cellSelect.parentElement.id == "columns") {
			for (var intLoop = 0 ; intLoop < el.rows.length; intLoop++) {
				if (0==intLoop) {
					insertSelector(r,"6", cellSelect.cellIndex)
				} else {
					if (cellSelect.cellIndex<=el.rows[intLoop].cells.length) {
						var c = el.rows[intLoop].insertCell( cellSelect.cellIndex)
						c.innerHTML = ""
					}
				}
			}
        } else
        {
			if (cellSelect.parentElement.cells.length == r.cells.length) 
				insertSelector(r,"6")
			if (cellSelect.cellIndex==0)
				c = el.rows[cellSelect.parentElement.rowIndex].insertCell()
			else
				c = el.rows[cellSelect.parentElement.rowIndex].insertCell(cellSelect.cellIndex)
			c.innerHTML = ""
        }
    }
}

function cleanupSelection() {
	if (null!=cellSelect) {
		if (cellSelect.className=="selector") {
			cellSelect.style.background = "#EAEAEA"
			cellSelect.style.color = "black"
        } else {
			cellSelect.innerHTML = cellSelect.children[0].value          
			cellSelect.rowSpan  = parseInt(rs.value); cellSelect.colSpan = parseInt(cs.value)
        }
    }
}

    function docellSelect(el) {
      cleanupSelection()
      el.style.background = "black"
      el.style.color = "#EAEAEA"
      cellSelect = el
    }

    function getCell() {
      var el = event.srcElement
      while (("TH"!=el.tagName) && ("TD"!=el.tagName) && ("TABLE"!=el.tagName))
        el = el.parentElement
      return el
    }

    function editCell(cell) {
      cell.innerHTML = "<TEXTAREA>"+cell.innerHTML+"</TEXTAREA>"
      rs.value = cell.rowSpan
      cs.value = cell.colSpan
      rs.disabled = cs.disabled = false
      cell.children[0].focus()
      cellSelect = cell
    }

    function doClick() {
      var el = event.srcElement      
      if ("selector"==el.className) {
//        rs.disabled = cs.disabled = true
        docellSelect(el)
      }
      else {
        var cell = getCell()

        if (el.tagName=="TABLE") return
        if ((cell.tagName!="TH") && (cell!=cellSelect)) {
          cleanupSelection()
//          editCell(cell)
        }
      }        
    }

    function deleteRow() {
	// Prueba
	  var e = document.all.editor
	  if (e.rows.length==2)
	  {
        for (var intLoop = 1; intLoop < e.rows[0].cells.length; intLoop++) {
          e.rows[1].cells[intLoop].innerHTML = ""
		}
	  }

	  var el = cellSelect.parentElement
      if (("columns"!=el.id) && (document.all.editor.rows.length!=2)) {
        document.all.editor.deleteRow(el.rowIndex)
        docellSelect(document.all.editor.rows[1].cells[0])
      }
    }

    function deleteCell() {
      var col = cellSelect.cellIndex  
      if (0==col) return   
      if (cellSelect.parentElement.id!="columns") 
        cellSelect.parentElement.deleteCell(col)
      else
        for (var intLoop=0; intLoop < document.all.editor.rows.length; intLoop++)
          if (col<document.all.editor.rows[intLoop].cells.length)
            document.all.editor.rows[intLoop].deleteCell(col)
      cellSelect = null
      docellSelect(document.all.editor.rows[1].cells[0])
    }
	
		   function esDigito(sChr){ 
			var sCod = sChr.charCodeAt(0); 
			return ((sCod > 47) && (sCod < 58)); 
	   } 

	   function valSep(oTxt){ 
			var bOk = false; 
			bOk = bOk || ((oTxt.value.charAt(2) == "-") && (oTxt.value.charAt(5) == "-")); 
			bOk = bOk || ((oTxt.value.charAt(2) == "/") && (oTxt.value.charAt(5) == "/")); 
			return bOk; 
	   } 

	   function finMes(oTxt){ 
			var nMes = parseInt(oTxt.value.substr(3, 2), 10); 
			var nAno = parseInt(oTxt.value.substr(6), 10); 
			var nRes = 0; 
			switch (nMes){ 
				 case 1: nRes = 31; break; 
				 case 2: nRes = 28; break; 
				 case 3: nRes = 31; break; 
				 case 4: nRes = 30; break; 
				 case 5: nRes = 31; break; 
				 case 6: nRes = 30; break; 
				 case 7: nRes = 31; break; 
				 case 8: nRes = 31; break; 
				 case 9: nRes = 30; break; 
				 case 10: nRes = 31; break; 
				 case 11: nRes = 30; break; 
				 case 12: nRes = 31; break; 
			} 
   			return nRes + (((nMes == 2) && (nAno % 4) == 0)? 1: 0); 
   		} 
		
			 function valDia(oTxt){ 
				var bOk = false; 
				var nDia = parseInt(oTxt.value.substr(0, 2), 10); 
				bOk = bOk || ((nDia >= 1) && (nDia <= finMes(oTxt))); 
				return bOk; 
			} 
		
		   function valMes(oTxt){ 
				var bOk = false; 
				var nMes = parseInt(oTxt.value.substr(3, 2), 10); 
				bOk = bOk || ((nMes >= 1) && (nMes <= 12)); 
				return bOk; 
		   } 
		
		   function valAno(oTxt){ 
				var bOk = true; 
				var nAno = oTxt.value.substr(6); 
				bOk = bOk && ((nAno.length == 2) || (nAno.length == 4)); 
				if (bOk){ 
					 for (var i = 0; i < nAno.length; i++){ 
						  bOk = bOk && esDigito(nAno.charAt(i)); 
					 } 
				} 
				return bOk; 
		   } 
		
		   function valFecha(oTxt){ 
				var bOk = true; 
				if (oTxt.value != ""){ 
					 bOk = bOk && (valAno(oTxt)); 
					 bOk = bOk && (valMes(oTxt)); 
					 bOk = bOk && (valDia(oTxt)); 
					 bOk = bOk && (valSep(oTxt)); 
					 return bOk; 
				} 
		   } 
		
		   function fechaMayorOIgualQue(fec0, fec1){ 
				var bRes = false; 
				var sDia0 = fec0.value.substr(0, 2); 
				var sMes0 = fec0.value.substr(3, 2); 
				var sAno0 = fec0.value.substr(6, 4); 
				var sDia1 = fec1.value.substr(0, 2); 
				var sMes1 = fec1.value.substr(3, 2); 
				var sAno1 = fec1.value.substr(6, 4); 
				if (sAno0 > sAno1) bRes = true; 
				else { 
					 if (sAno0 == sAno1){ 
						  if (sMes0 > sMes1) bRes = true; 
					 else { 
						   if (sMes0 == sMes1) 
								if (sDia0 >= sDia1) bRes = true; 
					} 
				} 
			} 	
			return bRes; 
		   } 
		
		   function valFechas(){ 
				var bOk = false; 
				if (valFecha(document.form.f1)){ 
				 	if (valFecha(document.form.f2)){ 
				  		if (fechaMayorOIgualQue(document.form.f2, document.form.f1)){ 
				   			bOk = true; 
							//alert("Ok"); 
							return bOk; 
				 		 } else { 
				   			alert("Verifique que el campo desde no sea mayor que el campo hasta"); 
				   			document.form.f1.focus(); 
							return bOk; 
				  		 } 
				 	} else { 
				  		alert("Formato de fecha invalido. Recuerde que el mismo debe ser DD/MM/YYYY"); 
				  		document.form.f1.focus(); 
						return bOk; 
				 	} 
				} else { 
					 alert("Formato de Fecha inválida"); 
					 document.f1.fec0.focus(); 
					 return bOk; 
				} 
		   } 
		   
		   	function valFechaComprobante(){ 
				var bOk = false; 
				if (valFecha(document.form.f1)){ 
				 	if (valFecha(document.form.f2)){ 
				  		if (fechaMayorOIgualQue(document.form.f2, document.form.f1)){ 
				   			bOk = true; 
							//alert("Ok"); 
							return bOk; 
				 		 } else { 
				   			alert("La fecha de devolucion no puede ser menor al dia de hoy"); 
				   			document.form.f2.focus(); 
							return bOk; 
				  		 } 
				 	} else { 
				  		alert("Formato de fecha invalido. Recuerde que el mismo debe ser DD/MM/YYYY"); 
				  		document.form.f2.focus(); 
						return bOk; 
				 	} 
				} else { 
					 alert("Formato de Fecha inválida"); 
					 document.form.f2.focus(); 
					 return bOk; 
				} 
		   } 


//esta funcion verifica el formato de la hora ingresada
//por ej:la hora debe ser hora menor  que 0  y hora mayor que 23
function tiempo(txt) {
	timeStr = txt.value;
	if(timeStr.length > 0){
		var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
		var matchArray = timeStr.match(timePat);
		if (matchArray == null) {
			alert("Formato Invalido.");
			txt.value="";
			txt.focus();
			return false;
		}
		hour = matchArray[1];
		minute = matchArray[2];

		if (hour < 0  || hour > 23) {
			alert("La Hora debe estar entre 0 y 23.");
			txt.value="";
			txt.focus();
			return false;
		}
		if (minute<0 || minute > 59) {
			alert ("Los Minutos deben estar entre 0 y 59.");
			txt.value="";
			txt.focus();
			return false;
		}
	}
	return false;
}

