/********************************************************************
                         nts onfly v1.0
						 
********************************************************************/

function NtsOnfly(){
	
	var global1;
	var global2;
	var coma = 1;
	
	this.coma = coma;
	this.global1 = global1;
	this.global2 = global2;
	
	//private methods
	this.inverse = inverse;
	this.mySetCaret = mySetCaret;
	this.setCaret = setCaret;
	this.getCaret = getCaret;
	this.mask = mask;
	this.transform = transform;
	
	
	//public methods
	this.onlyNumbers = onlyNumbers;
	this.onlyDecimalNumbers = onlyDecimalNumbers;
	this.onlyDateNumbers = onlyDateNumbers;
	this.onlyDate = onlyDate;
	this.dateUP = dateUP;
	this.dateDOWN = dateDOWN;
	this.allUpper = allUpper;
	this.allLower = allLower;
	this.decimalPrice = decimalPrice;
	this.price = price;
	this.firstUpper = firstUpper;
	this.percentage = percentage;
	this.bankAccount = bankAccount;		
	this.phone = phone;
	this.login = login;
	
	//INVERTIR (PRIVATE)
	//invierte la cadena
	function inverse(c){
		var returnValue="";
		for(var i=c.length-1;i>=0;i--)
			returnValue+=c.charAt(i);
	
		return (returnValue);
	}


	//PONER CURSOR (PRIVATE)
	//situa el cursor en la posicion especificada
	
	//input: objeto formulario (input.value es la cadena de texto)
	//pos1: posicion inicio
	//pos2: posicion fin
	function setCaret(input, pos1, pos2) {
	
		if( (pos1==-1)){
			pos1 = input.value.length;
			pos2=input.value.length;
			
		}
			
		if (input.setSelectionRange) { //netscape
			input.focus();
			input.setSelectionRange(pos1, pos2);
		}else
			if (input.createTextRange) { //explorer
				var selec = input.createTextRange();
				selec.collapse(true);
				selec.moveEnd('character', pos2);
				selec.moveStart('character', pos1);
				selec.select();
			}
	
	}
	
	//GET POS CURSOR (PRIVATE)
	//obtiene la posicion actual del cursor
	
	//input: objeto formulario (input.value es la cadena de texto)
	function getCaret(input){
		var caretPos = -1;
		var selection = input.ownerDocument.selection;
		var selec = selection.createRange().duplicate();
		var longSel = selec.text.length; //longitud de seleccion
		var aux = input.value; //guardamos el texto
	
		var key = "¬";//la key es un texto al azar q no puede estar repetido
		selec.text = key;		//insertamos la key en el texto seleccionado (ande esta el cursor)
		caretPos = input.value.indexOf(key);//y donde esta la key sera la pos del cursor
		input.value = aux; //ponemos el texto original (sin la key) otra vez
	
		setCaret(input,caretPos,caretPos+longSel);	//ponemos el cursor en su sitio otra vez
	
		var returnValue= [caretPos,caretPos+longSel]; //y a tomar por culo
		return returnValue;
	}
	
	//FUNCION MASCARA PRIVATE
	//llama a mascara transformar si es necesario
	
	//input: objeto formulario (input.value es la cadena de texto)
	//mascara: separaciones (ej: "2,3,2" - _ _ - _ _ _ - _ _)
	//tope: max de caracteres
	function mask(input,m){
	
		var key = event.keyCode ? event.keyCode: event.which;  //netscape o explorer?

		var sel = getCaret(input);
		var end = sel[1];
		var start = sel[0];
			
		this.global1 = start;
		this.global2 = end;
			
		if((key >= '0'.charCodeAt()) && (key <= '9'.charCodeAt()))
			returnValue =this.transform(input,m);
		else{
	
			returnValue = input.value;
		}
	
		return returnValue;
	}
	
	//FUNCION MASCARA TRANSFORMAR PRIVATE
	//convierte el texto a formato especificado por los parametros
	
	//input: objeto formulario (input.value es la cadena de texto)
	//mascara: separaciones (ej: "2,3,2" - _ _ - _ _ _ - _ _)
	//tope: max de caracteres
	function transform (input,m) {
	
		var nBlanks=0;
		var pos =  m.split(",");
		pos[0] = parseInt(pos[0]);
	
		for(k=1;k<pos.length;k++)
			pos[k] = parseInt(pos[k])+pos[k-1]+1;
	
		var num = input.value;
		var returnValue = "";
		var j=0;
		var c =  num.split(" ");
		var cc = "";
	
		for(n=0;n<c.length;n++)
			cc+=c[n];
	
		for(var i=0;i<pos.length;i++)
			if(cc.length > pos[i]){
				var aux1 = cc.slice(0,pos[i]);
				var aux2 = cc.slice(pos[i]);
				cc = aux1+" "+aux2;
				nBlanks++;
			}
	
		returnValue = cc;
	
		var offset = 0;
	
		if(nBlanks> c.length-1)
			offset=1;
		
		if(returnValue.charAt(this.global1-1)== ' ')
			offset=1;
	
		this.global1 +=offset;
		this.global2 += offset;
	
		//deprecated! ya no nos preocupamos del tope
		//returnValue = returnValue.substr(0,t);
	
		return (returnValue);
	}
	
	//PUBLIC:
	
	function login () {
		var key = event.keyCode ? event.keyCode: event.which;  // recoje el evento, segun sea netscape o explorer
		
		if( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() )
			return true;
			
		if ( key >= 'a'.charCodeAt() && key <= 'z'.charCodeAt() )
			return true;
			
		if ( key >= 'A'.charCodeAt() && key <= 'Z'.charCodeAt() )
			return true;
			
		if (key=='-'.charCodeAt() || key=='_'.charCodeAt())
			return true;
			
		return false;

	}
	
	//only numbers
	//event: onkeypress
	function onlyNumbers () {
		var key = event.keyCode ? event.keyCode: event.which;  // recoje el evento, segun sea netscape o explorer
		return ( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() );
	}
	
	//only decimal numbers
	//only numbers and decimal separator char (usually ',')
	//event onkeypress
	function onlyDecimalNumbers (sep) {
		
		if(sep==undefined)
			sep = ',';
			
		var key = event.keyCode ? event.keyCode: event.which;  
	    var returnValue = (key >= '0'.charCodeAt() && key <= '9'.charCodeAt())||(key == sep.charCodeAt());
	
		if(key == ','.charCodeAt()){
	        if(this.coma==1)
	        	this.coma=0;
	         else{
	         	returnValue=false;
			 }
		}
		return (returnValue);
	}
	
	function onlyDateNumbers(){
		return this.onlyDecimalNumbers('/');
	}
	
	
	//DATE MASK
	
	//user input to date format
	//helper: SPACE key puts'/'
	
	//uses three event hanlders!!
	//onKeyPress='var a = new NtsOnfly(); return a.onlyDate();' (validator)
	//onKeyUp='var a = new NtsOnfly(); a.dateUP(this);'
	//onKeyDown='var a = new NtsOnfly(); a.dateDOWN(this);'
	
	//date input validator
	//only numbers, '/' and SPACE
	//event: onkeypress
	function onlyDate () {
		var key = event.keyCode ? event.keyCode: event.which; 
		return ( (key >= '0'.charCodeAt() && key <= '9'.charCodeAt()) || (key == '/'.charCodeAt()) || (key == ' '.charCodeAt()) ) ;
	}
	
	//event:  onkeyup 
	//input: text form object
	function dateUP(input){
		
		var returnValue = "";
		var offset=0;
		var aux;
		var sel = getCaret(input);
	
		var end = sel[1];
		var start = sel[0];
	
		var part = input.value.split("/");
		var numBars = part.length -1;
	
		if(numBars<2){
			var returnValue = input.value;
			var key = event.keyCode ? event.keyCode: event.which;
	
	        if( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() )
				if( (((start - numBars)%2 == 0)&&(start!=0)&&(start!=3)) || ((start==4)&&(part[0].length==1)) ){
					if(returnValue.charAt(returnValue.length-1)!='/'){
						returnValue+='/';
						offset=1;
						numBars++;
				     }
				}
				
				
					
			if(key == ' '.charCodeAt()){
				if(returnValue.charAt(returnValue.length-1)!='/'){
					
					returnValue = returnValue.slice(0,returnValue.length-1);
					returnValue+='/';
					offset=1;
					numBars++;
				}
			}
			
		}else{ //numbars == 2
			returnValue += part[0] +'/'+part[1]+'/'+part[2].slice(0,4);
	
			offset=( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() )?1:0;
	
		}
	
		this.global1 = start+offset;
		this.global2 = end+offset;
	
		input.value = returnValue;
		
		this.mySetCaret(input)	
		
	}
	
	//event:  onkeydown 
	//input: text form object
	function dateDOWN(input){
		
		var returnValue = "";
		var offset=0;
		var aux;
		var sel = getCaret(input);
	
		var end = sel[1];
		var start = sel[0];
	
		var part = input.value.split("/");
		var numBars = part.length -1;
	
		if(numBars<2){
			var returnValue = input.value;
			var key = event.keyCode ? event.keyCode: event.which;
	
	        if( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() )
				if( (((start - numBars)%2 == 0)&&(start!=0)&&(start!=3)) || ((start==4)&&(part[0].length==1)) ){
					if(returnValue.charAt(returnValue.length-1)!='/'){
						returnValue+='/';
						offset=1;
						numBars++;
				     }
				}
				
			
		}else{ //numbars == 2
			returnValue += part[0] +'/'+part[1]+'/'+part[2].slice(0,4);
	
			offset=( key >= '0'.charCodeAt() && key <= '9'.charCodeAt() )?1:0;
	
		}
	
		this.global1 = start+offset;
		this.global2 = end+offset;
	
		input.value = returnValue;
		
		this.mySetCaret(input)	
		
	}
	
	//event:  onkeyup
	//input: text form object
	function allUpper (input) {
		var sel = getCaret(input);
		var end = sel[1];
		var start = sel[0];
	
		this.global1 = start;
		this.global2 = end;
	
		var solution =  input.value.toUpperCase();

		input.value = solution;
		
		this.mySetCaret(input)		
		
	}
		
	//event:  onkeyup
	//input: text form object
	function allLower (input) {
		var sel = getCaret(input);
		var end = sel[1];
		var start = sel[0];
		
		this.global1 = start;
		this.global2 = end;
	
		var solution = input.value.toLowerCase();
		
		input.value = solution;
		
		this.mySetCaret(input)
	}
	
	//price text formatting, plus 2 decimal digits
	//use decimal number validator!!
	//onKeyPress='var a = new NtsOnfly(); return a.onlyDecimalNumbers();'
	//onKeyUp='var a = new NtsOnfly(); a.decimalPrice(this);'
	//event:  onkeyup
	//input: text form object
	function decimalPrice (input) {
		var sel = getCaret(input);
		var end = sel[1];
		var start = sel[0];
	
		var returnValue = "";
	    var aux="";
	    var nPts=0;
	
		var part = input.value.split(",");
		if(coma==0)
			if(part.length==1)
				coma=1;
	
		var num = part[0].split(".");
		for(var i=0;i<num.length;i++)
			aux+=num[i];
	
		aux = inverse(aux);
		var flag =true;
	    
		for(var j=0;flag;j+=3){
			var aux1 = aux.slice(j,j+3);
	
			if(!aux1) aux1=aux.slice(j);
	
			if(aux1.length==3){
				returnValue += aux1+".";
				nPts++;
			}else{
				returnValue+= aux1;
				flag=false;
			}
		}
		returnValue = inverse(returnValue);
	
		if(returnValue.charAt(0)=="."){
			returnValue = returnValue.slice(1);
			nPts--;
		}
	
		if(part.length >1)
			returnValue+=","+part[1].slice(0,2);
	
		var key = event.keyCode ? event.keyCode: event.which;  //netscape o explorer?
	    var flag = ( (key >= '0'.charCodeAt()) && (key <= '9'.charCodeAt()) || (key >= 96) && (key <= 105) );
		if( flag && (nPts> num.length-1) ){
			this.global1 = start+1;
			this.global2 = end+1;
		}else{
			this.global1 = start;
			this.global2 = end;
		}
	
		input.value = returnValue;
		
		this.mySetCaret(input)
	}
	
	//price
	//use number validator
	//onKeyPress='var a = new NtsOnfly(); return a.onlyNumbers();'
	//onKeyUp='var a = new NtsOnfly(); a.price(this);'
	//event:  onkeyup
	//input: text form object
	function price (input) {
		var sel = getCaret(input);
	
		var end = sel[1];
		var start = sel[0];
	
		var returnValue = "";
		var aux="";
		var nPts=0;
		var num = input.value.split(".");

		for(var i=0;i<num.length;i++)
			aux+=num[i];
	
		aux = inverse(aux);
		
		var flag =true;
		for(var j=0;flag;j+=3){
	
			var aux1 = aux.slice(j,j+3);
			if(!aux1) aux1=aux.slice(j);
	
			if(aux1.length==3){
				returnValue += aux1+".";
				nPts++;
			}else{
				returnValue+= aux1;
				flag=false;
			}
		}
	
		returnValue = inverse(returnValue);
			
		if(returnValue.charAt(0)=="."){
			returnValue = returnValue.slice(1);
			nPts--;
		}
		
		var key = event.keyCode ? event.keyCode: event.which;  
		
	    var flag = ( (key >= '0'.charCodeAt()) && (key <= '9'.charCodeAt()) || (key >= 96) && (key <= 105) );
		if( flag && (nPts> num.length-1) ){
			this.global1 = start+1;
			this.global2 = end+1;
		}else{
			
			this.global1 = start;
			this.global2 = end;
		}
	
		input.value = returnValue;
		
		this.mySetCaret(input)
	}

	//event:  onkeypress
	//input: text form object
	function phone(input){
		input.value = this.mask(input,"3,3,3");	
		this.mySetCaret(input)
		
	}
	
	//event:  onkeypress
	//input: text form object
	function bankAccount(input){
		input.value = this.mask(input,"4,4,2,3");
		this.mySetCaret(input)
	}
	
	//event:  onkeyup
	//input: text form object
	function percentage (input) {
		var sel = getCaret(input);
		var end = sel[1];
		var start = sel[0];
	
		this.global1 = start;
		this.global2 = end;
	
		var num = input.value.split("%");
		var returnValue = "";
	
		if((num[0].length > 0)&&(num[0]!='.'))
			returnValue = num[0] + "%"
		else
			returnValue = num[0];
	
		input.value = returnValue;
		
		this.mySetCaret(input)
	}


	//event:  onkeyup
	//input: text form object
	function firstUpper(input){

		var c = input.value;
	
   		c = c.toLowerCase();
		var cAux="";
		var sel = getCaret(input);

		var end = sel[1];
		var start = sel[0];

		var part=c.split(" ");
		var token="";
   		var head="";
		var body="";
		var solution="";

		for (var i=0;i<part.length;i++){
			token=part[i];
			head=token.charAt(0);

   	    	for (var j=1;j<token.length;j++)
  				body+=token.charAt(j);
	
			head=head.toUpperCase();
	
			solution+=head+body;
	
			if(i<part.length-1)
				solution+=" ";
	
			body="";
		}
	
		this.global1 = start;
		this.global2 = end;
		
		input.value = solution;
		
		this.mySetCaret(input)
	
	}
	
	function mySetCaret(input){
		
		this.setCaret(input,this.global1,this.global2);
		
	}
	
}
	

