var bkColor = "red";

//-------------------------------------------------------------------------------------------------
function revisarDigito( dvr )
{	
	dv = dvr + ""	
	if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')	
	{		
		alert("Debe ingresar un digito verificador valido");		
		window.document.form1.Txt_Rut.focus();		
		window.document.form1.Txt_Rut.select();		
		return false;	
	}	
	return true;
}

function revisarDigito2( crut )
{	
	largo = crut.length;	
	if ( largo < 2 )	
	{		
		alert("Debe ingresar el rut completo")		
		window.document.form1.Txt_Rut.focus();		
		window.document.form1.Txt_Rut.select();		
		return false;	
	}	
	if ( largo > 2 )		
		rut = crut.substring(0, largo - 1);	
	else		
		rut = crut.charAt(0);	
	dv = crut.charAt(largo-1);	
	revisarDigito( dv );	

	if ( rut == null || dv == null )
		return 0	

	var dvr = '0'	
	suma = 0	
	mul  = 2	

	for (i= rut.length -1 ; i >= 0; i--)	
	{	
		suma = suma + rut.charAt(i) * mul		
		if (mul == 7)			
			mul = 2		
		else    			
			mul++	
	}	
	res = suma % 11	
	if (res==1)		
		dvr = 'k'	
	else if (res==0)		
		dvr = '0'	
	else	
	{		
		dvi = 11-res		
		dvr = dvi + ""	
	}
	if ( dvr != dv.toLowerCase() )	
	{		
		alert("EL rut ingresado es incorrecto")	
		window.document.form1.Txt_Rut.value = "";
		window.document.form1.Txt_Rut.focus();		
		window.document.form1.Txt_Rut.select();		
		return false	
	}

	return true
}

function RutValidator(intexto)
{	
    texto = intexto.value;
	var tmpstr = "";	
	for ( i=0; i < texto.length ; i++ )		
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
			tmpstr = tmpstr + texto.charAt(i);	
	texto = tmpstr;	
	largo = texto.length;	

	if ( largo < 2 )	
	{		
		alert("Debe ingresar el rut completo")		
		window.document.form1.Txt_Rut.value = "";
		window.document.form1.Txt_Rut.focus();		
		window.document.form1.Txt_Rut.select();		
		return false;	
	}	

	for (i=0; i < largo ; i++ )	
	{			
		if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" )
 		{			
			alert("El valor ingresado no corresponde a un R.U.T valido");
			window.document.form1.Txt_Rut.value = "";
			window.document.form1.Txt_Rut.focus();		
			window.document.form1.Txt_Rut.select();			
			return false;		
		}	
	}	

	var invertido = "";	
	for ( i=(largo-1),j=0; i>=0; i--,j++ )		
		invertido = invertido + texto.charAt(i);	
	var dtexto = "";	
	dtexto = dtexto + invertido.charAt(0);	
	dtexto = dtexto + '-';	
	cnt = 0;	

	for ( i=1,j=2; i<largo; i++,j++ )	
	{		
		//alert("i=[" + i + "] j=[" + j +"]" );		
		if ( cnt == 3 )		
		{			
			dtexto = dtexto + '.';			
			j++;			
			dtexto = dtexto + invertido.charAt(i);			
			cnt = 1;		
		}		
		else		
		{				
			dtexto = dtexto + invertido.charAt(i);			
			cnt++;		
		}	
	}	

	invertido = "";	
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ )		
		invertido = invertido + dtexto.charAt(i);	

	/*window.document.form1.rut.value = invertido.toUpperCase()		*/
	/*intexto.value = invertido.toUpperCase()		*/

	if ( revisarDigito2(texto) )		
		return true;	

	return false;
}
//-------------------------------------------------------------------------------------------------
function getEvent(e){
  if(window.event != null) {
    return event;
  }
  return e;
}

function setBKColor(e){
 e = getEvent(e);
 var src =  e.srcElement || e.target;
 window.status="t";
 if(src != null) {
   src.style.bkColor = src.style.backgroundColor;
   src.style.backgroundColor = bkColor;
 }
}

function reSetBKColor(e){
 e = getEvent(e);
 var src =  e.srcElement || e.target;
 if(src != null) {
   src.style.backgroundColor = src.style.bkColor;
 }
}

function attachEvent(name,element,callBack) {
    if (element.addEventListener) {
      element.addEventListener(name, callBack,false);
    } else if (element.attachEvent) {
      element.attachEvent('on' + name, callBack);
    }
  }

function setListner(eve,func) {
   var ele = document.forms[0].elements;

   window.alert("setListener called");

   for(var i = 0; i <ele.length;i++) {
    element = ele[i];
    if (element.type) {


      switch (element.type) {
        case 'checkbox':
        case 'radio':
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
           attachEvent(eve,element,func);

	   // window.alert( element.type + eve );
       }
     }
  }
}




function validateMail() {

  txtbox = document.getElementById("txtMail");
  pError =  document.getElementById("parrafoErrores");
  textoavalidar = txtbox.value;
 

  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(txtbox)) {


    new Effect.Shake(txtbox);
    new Effect.Highlight(txtbox);
    txtbox.style.backgroundColor = "Yellow";

    pError.innerHTML = "El mail ingresado no es valido'";
    pError.style.backgroundColor = "Yellow";
    //new Effect.Fade(pError);
    //new Effect.Appear(pError);
    new Effect.Highlight(pError);

    
  }
  else {
        txtbox.style.backgroundColor = "White";
	pError.innerHTML = "";
  }
  // txtbox.size = 200;   // cambia el tamaño del textbox
  //txtbox.background-color = "#FFFFCC";


  //window.alert(textoavalidar);

}

function validateUsuario() {

  txtbox = document.getElementById("txtUsuario");
  pError =  document.getElementById("parrafoErrores");
  //textoavalidar = txtbox.innerHTML;
  textoavalidar = txtbox.value;



  txtbox.size = 8;
  txtbox.maxlength = 10;  //longitud maxima de  string permitido
  if ( textoavalidar == "seba" ) {
    txtbox.style.backgroundColor = "White";
    pError.innerHTML = "";
  }
  else {  
    new Effect.Shake(txtbox);
    //new Effect.Highlight(txtbox);
    txtbox.style.backgroundColor = "Yellow";

    //pError.style.visibility="hidden";
    pError.innerHTML = "El nombre debe ser = 'seba'";
    pError.style.backgroundColor = "Yellow";
    
    //new Effect.Fade(pError);
    //new Effect.Appear(pError);
    new Effect.Highlight(pError);
    

  }
  //window.alert(textoavalidar);

}


function findLabelFor (elOrId) {
  var el = typeof elOrId == 'string' ? document.getElementById(elOrId) : elOrId;
  var labels = document.getElementsByTagName('LABEL');
  var found = false;
  for (var l = 0; l < labels.length; l++)
    if (found = el.id == labels[l].htmlFor)
      break;
  if (found)
    return labels[l];
  else
    return null;
}
function findLabelTextFor (elOrId) {
  return findLabelFor(elOrId).firstChild.nodeValue;
}


function txtNombreOnChange() {
validarTxtBox_with2args( "nombres", regExpNombre, reqNombre );
}


// se dispara cuando se modifica el txtBox del RUT.
// Cablear el evento agregando OnChange al txtbox en el codigo asp.net
// Ejemplo:
//<span class="path">*</span> <label for="rut">
//&nbsp; RUT:</label> <asp:TextBox ID="rut" onChange="txtRutOnChange()" 
//runat="server" meta:resourcekey="rutResource1" CausesValidation="True" Width="202px" />
function txtRutOnChange() 
{
    var field = document.getElementById("rut");
    
  // matchea 6 a 8 digitos seguido de "-" seguido de 1 alfanumerico
  var regExpRUT = /(^\d{6,8}-\w$)/ ;      
  if (!regExpRUT.test(field.value)) {
    ErrorField_Msg( field, "El formato del RUT es incorrecto.");

  } else {
     
     ClearErrorField( field );   
    // el formato es correcto, chequear rangos    
    chequearRangosRUT();      
  }

}

 
 function chequearRangosRUT( ) {
 
    var field = document.getElementById("rut");
 
    str = field.value;
    strarray=str.split("-");
    var strrut1=strarray[0]; 
    //window.alert( strarray[0] );
    var strrut2=strarray[1]; 
    if ( ( strrut1 < 500000) || ( strrut1 > 99999999 ) ) {
        //window.alert("El RUT esta fuera del rango establecido.");
        //ErrorField_Msg( field, "El RUT esta fuera del rango establecido.");   
    } else {
        //ClearErrorField( field );
    }
 }
 
 
 // sirve para validar campos alfanumericos
 function txtAlfaNumOnChange( str_idfield ) {
 
    //window.alert("txtAlfaNumOnChange");
    
    var field = document.getElementById( str_idfield );
     
    // \uxxxx  Matches the ASCII character expressed by the UNICODE xxxx. 
    // "\u00A3" matches "£". 
 
    // para matchear letras acentuadas y eÑes en expresiones regulares
    // de javascript hay que usar el codigo unicode, porque sino no los toma.
 
    // codigos \u00D1  = Ñ
    //         \u00F1 = ñ
    //         \u00E1 = á
    //          \u00E9 = é
    //          \u00ED = í
    //          \u00F3 = ó
    //          \u00FA = ú
    //          \u00FC = ü
    
    // matchea alfanumericos, incluidos letras 
    // con acentos (minusculas) y las eñes
    
    var regExpAlfaNum = /(^[a-zA-Z0-9\u00D1\u00F1\u00E1\u00E9\u00ED\u00F3\u00FA\u00FC\u0020]*$)/ ;

    if (!regExpAlfaNum.test(field.value)) {
        ErrorField_Msg( field, "El formato del campo es incorrecto.");
    } else { 
     ClearErrorField( field );    
    }

 }
 
  // sirve para validar campos numericos en forma general
 function txtNumOnChange( str_idfield ) {
 
    //window.alert("txtNumOnChange");
    
    var field = document.getElementById( str_idfield );
    
    var regExpAlfaNum = /(^\d*$)/ ;

    if (!regExpAlfaNum.test(field.value)) {
        ErrorField_Msg( field, "El formato del campo numerico es incorrecto.");
    } else { 
     ClearErrorField( field );    
    }

 }
 
 
 
 
 
 function txtApellidosOnChange() {
 validarTxtBox_with2args( "apellidos", regExpApellidos, reqApellidos );
 }  
   

function suscriptorOnChange() {
    validarTxtBox_with2args( "suscriptor", compSuscriptor, reqSuscriptor );
}

function emailOnChange() {
    validarTxtBox_with( "email", regExpMail)        //, reqMail );
}

function claveOnChange() {
    validarTxtBox_with("clave", reqClave );   
}

function clave2OnChange() {
    validarTxtBox_with2args(  "clave2", reqClave2, compClave );
}

function respOnChange() {
    validarTxtBox_with("resp", reqResp );
}

   function validarTxtBox_with( idcampo, aValidator ) {
//window.alert("Evento txtNombreOnChange disparado");
    txtbox = document.getElementById(idcampo);
    label = findLabelFor (idcampo);

   // Do nothing if client validation is not active
   if (typeof(Page_Validators) == "undefined")  return;
   // Change the color of the label
   
   // nombres
   //lblZip.style.color = regExpNombre.isvalid ? "Black" : "Red";
   
   if ( aValidator.isvalid ) {
     //window.alert("nombre es valido");
     //txtbox.style.color =  "Black" ;
     //label.style.color = "Black";
     //ocultarErrores();
   }
   else {
      //window.alert("nombre es invalido");
      //label.style.color = "Red";
      //txtbox.style.backgroundColor = "Yellow";
      txtbox.focus();
      //new Effect.Shake(txtbox);
      //mostrarError( aValidator.errormessage  );

   }
}


   function validarTxtBox_with2args( idcampo, aValidator1, aValidator2 ) {
//window.alert("Evento txtNombreOnChange disparado");
    txtbox = document.getElementById(idcampo);
    label = findLabelFor (idcampo);

   // Do nothing if client validation is not active
   if (typeof(Page_Validators) == "undefined")  return;
   // Change the color of the label
   
   // nombres
   //lblZip.style.color = regExpNombre.isvalid ? "Black" : "Red";
   
   if ( aValidator1.isvalid && aValidator2.isvalid) {
     //window.alert("nombre es valido");
     //txtbox.style.backgroundColor =  "White" ;
     //label.style.color = "Black";
     //ocultarErrores();
   }
   else {
      //window.alert("nombre es invalido");
      //label.style.color = "Red";
      //txtbox.style.backgroundColor = "Yellow";
      txtbox.focus();
      //new Effect.Shake(txtbox);
      //mostrarError( aValidator1.errormessage + aValidator2.errormessage );

   }
}


function mostrarError( strError ) {

lblError = document.getElementById("parrafoErrores");
lblError.innerHTML = strError;
lblError.style.color = "Red";
new Effect.Highlight(lblError);

}

function ocultarErrores( ) {
lblError = document.getElementById("parrafoErrores");
lblError.innerHTML = "";

}

function ErrorField_Msg( field, strError ) {

   label = findLabelFor (field);
    
   //label.style.color = "Red";
   //field.style.backgroundColor = "Yellow";
   field.focus();
   //new Effect.Shake(field);
   //mostrarError( strError );

}

function ClearErrorField( field ) {

   label = findLabelFor (field);
     //window.alert("nombre es valido");
     //field.style.backgroundColor =  "White" ;
     //label.style.color = "Black";
     //ocultarErrores();
}


//window.alert("Seccion codigo suelto dentro del archivo javascript");
//window.alert(navigator.appName);

function Startup() {

 // window.alert("dentro de la funcion Startup");
 // setListner("focus",setBKColor);
 // setListner("blur",reSetBKColor);

}

//window.onload=Statup;

// forma standard de la w3c para cablear eventos
// cablea el evento onload con la funcion Startup()
// NO FUNCIONA EN IE7
//window.addEventListener('load', Startup, false);


attachEvent('load', window, Startup);

//attachEvent('Change', document.getElementById("nombres"), txtNombreOnChange );

// movido al codigo html
//setListner("focus",setBKColor);
//setListner("blur",reSetBKColor);


