var bloq = false;
var menos = 0;
var pos =0;

/*Función para escribir sólo caracteres numéricos*/
function filtrar(evt,tipo,ctrl) 
{
	//tipo 1=nuemric entero ; 2= numeric decimal ; 3=alfanumeric ; 4: permite negativos
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (tipo == 1)
	{
		if ((charCode >= 48 && charCode <= 57))
		{
		return true;
		}
		else
		{
		return false;
		}
	}
	if (tipo == 2)
	{
		if ((charCode >= 48 && charCode <= 57) || (charCode == 44 || charCode == 46 || charCode == 45))
		{
		return true;
		}
		else
		{
		return false;
		}
	}
	if (tipo == 3)
	{
		if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || (charCode >= 128 && charCode <= 165) || (charCode == 44 || charCode == 46 || charCode == 32))
		{
		return true;
		}
		else
		{	   
		return false;
		}
	}
	if (tipo == 4)
		{
			
			if ((charCode >= 48 && charCode <= 57) || (charCode == 44 || charCode == 46 || charCode == 45))
			{
				if(charCode == 45)
				{
					menos = 1;
				}
				if(charCode == 45 && ctrl.value.length!=0)
				{
					return false;
				}
				if(charCode == 44 || charCode == 46)
				{ 
					if(bloq==true || ctrl.value.length == menos)
					{
						return false;
					}
					else
					{
						bloq = true;
						pos = ctrl.value.length;
					}
				}
			}
			else
			{
				return false;
			}
		}
	}
function filtrarCaracteres(evt,ctrl)
{
	evt = (evt) ? evt : event;
	
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	
	if ((charCode >= 48 && charCode <= 57) || (charCode == 44 || charCode == 46 || charCode == 45))
	{
		if(charCode == 45)
		{
			menos = 1;
		}
		if(charCode == 45 && ctrl.value.length!=0)
		{
			var caracter = String.fromCharCode(charCode);
			ctrl.value = ctrl.value.toLowerCase().replace(caracter.toLowerCase(),"");
			return;
		}
		if(charCode == 44 || charCode == 46)
		{ 
			if(bloq==true || ctrl.value.length == menos)
			{
				var caracter = String.fromCharCode(charCode);
				ctrl.value = ctrl.value.toLowerCase().replace(caracter.toLowerCase(),"");
				return;
			}
			else
			{
				bloq = true;
				pos = ctrl.value.length;
			}
		}
	}else if((charCode >= 96 && charCode <= 105) || charCode == 188)
	{
		bloq = true;
		pos = ctrl.value.length;
	}
	else
	{
		var caracter = String.fromCharCode(charCode);
		ctrl.value = ctrl.value.toLowerCase().replace(caracter.toLowerCase(),"");
		return;
	}
}
function debloq(actual)
{
	if(pos == actual || actual == 0)
	{
		menos = 0;
		pos = 0;
		bloq = false;
	}
	return true;
}

/*Abrir buscaitem*/
function BuscaItem(pagina,txtnombre,txtid)
{		
	var f = new Date();
	var n = f.getTime();				
	OcultarDDL();									
	args = "dialogWidth=720px;dialogHeight=500px;dialogLeft=190;dialogTop=220;status=no;help=no";

	objeto = showModalDialog(pagina + "&nocache=" + n,'',args);
	
	if(objeto != null)
	{
		txtnombre.value = objeto.Nombre + " (Valor: " + objeto.Valor +")";
		txtid.value = objeto.Id;
		document.getElementById('txtValor').value = objeto.Valor;
		
	}
}
function BuscaItemEnlaza(pagina,txtnombre,txtid)
{		
	var f = new Date();
	var n = f.getTime();				
									
	args = "dialogWidth=705px;dialogHeight=500px;dialogLeft=190;dialogTop=220;status=no;help=no";

	objeto = showModalDialog(pagina + "&nocache=" + n,'',args);
	
	if(objeto != null)
	{
		txtnombre.value = objeto.Nombre + " (Valor: " + objeto.Valor + ")";
		txtid.value = objeto.Id;
		document.getElementById('lblValorItem').innerHTML = objeto.Valor;	
	}
}
/*Validacion del txt del item*/
function ComprobarTxT(source, value)
{
    if (document.getElementById('txtItem').value.length >= 1)
    {
        ValidatorEnable(document.getElementById("RFVItem"), false);
        value.IsValid = true;
    }
    else
    {
        value.IsValid = false;
    }
    CerrarEnProceso();
}

/*Botón Calcular Total*/


/*Ocultar el DDL*/
function OcultarDDL() //<
{			
	document.getElementById('txtVerDDL').value='false';
	document.getElementById('txtItem').value='';				
	document.getElementById('imgtxt').className='novisible';
	document.getElementById('ddlItems').className='novisible';				
	document.getElementById('lnkddl').className='';
}
/*Ver el DDL*/
function VerDDL() //>
{
	document.getElementById('txtVerDDL').Text='true'
	document.getElementById('imgTxt').className='';
	document.getElementById('ddlItems').className='ve-dropdownlist';	
	document.getElementById('lnkddl').className='novisible';	
	document.getElementById('txtItem').value='****';	
}
function NoPunto(Valor)
{
	cantidad = Valor.value;
	Valor.value = cantidad.replace(".","");
}
function NoDecimal(Valor)
{
	cantidad = Valor.value;
	Valor.value = cantidad.replace(".","").replace(",","");
}
function XDecimales(Valor,decimales)
{
	indice = Valor.value.lastIndexOf(",");
	if(indice != -1)
	{
		cantidad = new String(Valor.value);	
		
		if(cantidad.length > indice+decimales+1)
		{
			Valor.value = Valor.value.substring(0,indice+decimales+1);
		}
	}
}
function XDecimales(Valor,decimales,simbolo)
{
	indice = Valor.value.lastIndexOf(simbolo);
	if(indice != -1)
	{
		cantidad = new String(Valor.value);	
		
		if(cantidad.length > indice+decimales+1)
		{
			Valor.value = Valor.value.substring(0,indice+decimales+1);
		}
	}
}
function UnaComa(Valor)
{
	var coma = 0;
	var svalor;
	indice = Valor.value.indexOf(",");
	if(indice != -1)
	{
		resto = (Valor.value.length-indice);
		fin = indice + resto;
		svalor = Valor.value.substring(indice+1,fin);
		if(svalor.indexOf(",") != -1)
		{
			Valor.value = Valor.value.substring(0,Valor.value.length-1);
		}
	}
}
function UnSimboloDecimal(Valor,simbolo)
{
	var coma = 0;
	var svalor = new String();
	indice = Valor.value.indexOf(simbolo);
	if(indice != -1)
	{
		svalor = Valor.value.substr(indice+1,Valor.value.length-indice-1);
		Valor.value = Valor.value.substr(0,indice+1) + svalor.replace(simbolo,"");
	}
}
function Numerico(Valor,simbolo)
{
	var numeros = "0123456789"+simbolo;
	var sresultado = new String();
		
	for(i=0;i<Valor.value.length;i++)
	{
		if(numeros.indexOf(Valor.value.charAt(i)) != "-1")
		{
			sresultado = sresultado + Valor.value.charAt(i);			
		}
		
	}
	Valor.value = sresultado;
}
function NumericoNoDecimal()
{
    var numeros = "0123456789";
    var codigo = event.keyCode;
    
    if(codigo != 37 & codigo != 39)
    {
        for(i=0;i<event.srcElement.value.length;i++)
	    {
		    if(numeros.indexOf(event.srcElement.value.charAt(i)) == "-1")
		    {
			    event.srcElement.value = event.srcElement.value.replace(event.srcElement.value.charAt(i),'');	
		    }    		
	    }
    }
    
}
function NumericoNegativo(Valor,simbolo)
{
	var numeros = "-0123456789"+simbolo;
	var sresultado = new String();
	
	for(i=0;i<Valor.value.length;i++)
	{
		if(numeros.indexOf(Valor.value.charAt(i)) != "-1")
		{
			if(Valor.value.charAt(i) != "-")
			{
				sresultado = sresultado + Valor.value.charAt(i);
			}else
			{
				if(i==0)
				{
					sresultado = sresultado + Valor.value.charAt(i);
				}
			}
		}
	}
	Valor.value = sresultado;
}


function NumericoDecimalNegativo(simbolo)
{
    var numeros = "0123456789";
    var codigo = event.keyCode;
    var nSeparadores = 0;
    
    if(codigo != 37 & codigo != 39)
    {
        for(i=0;i<event.srcElement.value.length;i++)
	    {
		    if(numeros.indexOf(event.srcElement.value.charAt(i)) == "-1")
		    {
		        if ((i==0) && (event.srcElement.value.charAt(i)=='-'))
	            {
	                continue;
	            }
	            
	            if ((event.srcElement.value.charAt(i)==simbolo) && (nSeparadores==0))
	            {
	                nSeparadores++;
	                continue;
	            }

			    event.srcElement.value = event.srcElement.value.substr(0,i) + event.srcElement.value.substr(i+1, event.srcElement.value.length - i);
		    }    		
	    }
    }
}
function GetCursorPosition()
{
    var _range = document.selection.createRange();
    var contador = 0;
    
    while (_range.move('character', -1))
          contador++;
          
    cursor = contador;
    
    return cursor;
}
function NumDecimalNegativo(simbolodecimal,precision,nenteros)
{  
    poscursor = GetCursorPosition();
    
    var numeros = "0123456789";    
    var codigo = event.keyCode;
    
    if(codigo != 37 & codigo != 39)
    {
        var valor = event.srcElement.value.charAt(poscursor-1);
        
        if(numeros.indexOf(valor) == "-1")
        {
            if((poscursor-1 == 0) && (valor == '-'))
            {
                return;
            }
            
            if ((valor==".") | (valor==","))
	        {
	            event.srcElement.value = event.srcElement.value.replace(valor,simbolodecimal);
	            
	            /*Comprobamos que no hayan más símbolos decimales*/
	            var ndecimales = 0;
	            for(i=0;i<event.srcElement.value.length;i++)	            
	            {
	                if(event.srcElement.value.charAt(i) == simbolodecimal)
	                {
	                    ndecimales++;
	                }
	            }
	            if(ndecimales > 1)
	            {
	                event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
	            }
	            return;
	        }
	        
	        event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
	        
        }else
        {
            /*Total de dígitos antes del símbolo decimal*/
            var posdecimal = 0;
            posdecimal = event.srcElement.value.indexOf(simbolodecimal);
            
            var totaldigitos=0;
            var pentera = 0;
            
            if(posdecimal != -1)
            {
                pentera = event.srcElement.value.substr(0,posdecimal).replace('-','').length;
            }
            
            if(pentera > nenteros)
            {
                event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
                return;
            }
            
            totaldigitos = event.srcElement.value.replace('-','').replace(simbolodecimal,'').length;
            
            if(posdecimal != -1)
            {
                if(totaldigitos > precision)
	    	    {/*Se han escrito más numeros de los permitidos*/		             
		                event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
		        }
		    }else
		    {
		        if(totaldigitos > nenteros)
	    	    {/*Se han escrito más numeros de los permitidos*/		             
		                event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
		        }
		    }
        }
        /*for(i=0;i<event.srcElement.value.length;i++)
	    {
		    if(numeros.indexOf(event.srcElement.value.charAt(i)) == "-1")
		    {
		        if ((i==0) && (event.srcElement.value.charAt(i)=='-'))
	            {
	                continue;
	            }
	            
	            if (((event.srcElement.value.charAt(i)==".") | (event.srcElement.value.charAt(i)==",")) & (nSeparadores==0))
	            {
	                nSeparadores++;
	                event.srcElement.value = event.srcElement.value.replace(event.srcElement.value.charAt(i),simbolodecimal);
	                continue;
	            }
                
			    event.srcElement.value = event.srcElement.value.substr(0,i) + event.srcElement.value.substr(i+1, event.srcElement.value.length - i);
			    
		    }else
		    {
		        if(ndigitos >= precision)
		        {*Se han escrito más numeros de los permitidos*
	*	            event.srcElement.value = event.srcElement.value.substr(0,poscursor-1)+event.srcElement.value.substr(poscursor, event.srcElement.value.length - poscursor);
		        }else
		        {
		            ndigitos++;
		        }
		    }
	    }*/
    }
}

function NumDecimalNegativoGridAW(numero, simbolodecimal, precision, nenteros)
{    
    //Vemos que simbolo millar hay
    var simbolomillar = '.';
    if(simbolodecimal == '.')
        simbolomillar = ',';
    //No permitimos la introduccion del separador de millares
    if(numero.indexOf(simbolomillar) != -1)
        return false;
        
    //Comprobamos que no haya puesto 2 separadores de decimales
    var pos1 = numero.indexOf(simbolodecimal);
    var pos2 = numero.lastIndexOf(simbolodecimal);
    if(pos1 != pos2)
        return false;
    
//	var textoaux = '';
//	//Determina si texto contiene un número (separador decimal: coma o punto)
//	var texto = Input.innerText.toString().replace(/,/g, '.');
	
	if (numero.length == 0 || (numero.length == 1 && numero == '-'))	//no comprobamos más (vacio o negativo)
		return true;
	
	//Como javascript trabaja con separador decimal . lo formateamos
	numero = numero.replace(',','.');
	
	//Vemos que es un Decimal bien formado
	if(parseFloat(numero) == NaN)
	    return false;
	
	//Comprobamos las longitudes de enteros y decimales	
	var grupo = numero.split('.');
	var ndecimales = precision - nenteros;
	if(numero.length > precision+1) //precision + el separador decimales
	{	    
	    return false;
	}
	else if(grupo.length == 2)
	{
	    if(grupo[1].length > ndecimales)
	        return false; //Mas decimales de los permitidos
	}	
    return true;
}

function NumericoNoDecimalNegativoGridAW(numero, precision)
{
	
	if (numero.length == 0 || (numero.length == 1 && numero == '-'))	//no comprobamos más (negativo)
		return true;
	
    if (parseInt(numero).toString() != numero)	//no es ok
		return false;
      
	if (numero.length > precision)
		return false;   
    
    return true;
}

function NumericoNoDecimalNegativo()
{
    var numeros = "0123456789";
    var codigo = event.keyCode;
    
    if(codigo != 37 & codigo != 39)
    {
        for(i=0;i<event.srcElement.value.length;i++)
	    {
		    if(numeros.indexOf(event.srcElement.value.charAt(i)) == "-1")
		    {
		        if ((i==0) && (event.srcElement.value.charAt(i)=='-'))
	            {
	                continue;
	            }

			    event.srcElement.value = event.srcElement.value.substr(0,i) + event.srcElement.value.substr(i+1, event.srcElement.value.length - i);
		    }    		
	    }
    }
}

function QuitarSeparador(campo, separador)
{
    while (campo.value.indexOf(separador)>0)
    {
        campo.value = campo.value.replace(separador,'');
    }
}

function PonerSeparador(campo, separadorMillares, separadorDecimal)
{
    var posDecimal = campo.value.indexOf(separadorDecimal);
    var cantidadEntera;
    var cantidadDecimal;
    var nMillares;
    var nNeg;
    
    if (posDecimal > 0)
    {
        cantidadEntera = campo.value.substring(0,posDecimal);
        cantidadDecimal = campo.value.substring(posDecimal+1, campo.value.length);
    }
    else
    {
        cantidadEntera = campo.value;
        cantidadDecimal = '';
    }
    
    while ((cantidadEntera.length > 1) && (cantidadEntera.substring(0,1) == '0'))
    {
        cantidadEntera = cantidadEntera.substring(1,cantidadEntera.length);
    }
    
    if (cantidadEntera.substring(0,1)=='-')
    {
        nNeg = 1;
    }
    else
    {
        nNeg = 0;
    }
    
    nMillares = Math.floor((cantidadEntera.length -1 - nNeg) / 3);
    for(i=0; i<nMillares; i++)
    {
        cantidadEntera = cantidadEntera.substring(0, cantidadEntera.length - i - ((i+1)*3)) + separadorMillares + cantidadEntera.substring(cantidadEntera.length - i - ((i+1)*3), cantidadEntera.length);
    }
    
    campo.value = cantidadEntera;
    if (cantidadDecimal != '')
    {
        campo.value = campo.value + separadorDecimal + cantidadDecimal;
    }
}

function CargaDigitos(campo, digitos)
{    
    var resultado = campo.value;
    var negativo = false;
    var digitosCampo = campo.value.length;            

    if (campo.value.indexOf('-') > -1)
    {
        negativo = true;
        resultado = campo.value.substring(1,campo.value.length);
        digitosCampo--;
    }

    if (digitosCampo < digitos)
    {
        var numdigitos = digitos - digitosCampo;
        for (var i = 0; i < numdigitos; i++)
            resultado = "0" + resultado;
    }
    else
    {
        if (negativo)
            resultado = campo.value.substring(1, digitos+1);
        else
            resultado = campo.value.substring(0, digitos);
    }

    if (negativo)
        resultado = '-' + resultado;

     campo.value = resultado;
}

