 var tipoUsuario=0;
 
 jQuery.fn._blank = function() {

	function clickHandler(e) {
		// si el usuario ha utilizado una tecla de control
		// no hacemos nada
		if (e.ctrlKey || e.shiftKey || e.metaKey)
			return;

		// abrimos la ventana
		var w = window.open(this.href, '_blank');
		if (w && !w.closed) {
			// si efectivamente hemos logrado abrirla
			// la ponemos en foco
			w.focus();
			// y cancelamos el comportamiento por defecto
			// del enlace
			e.preventDefault();
		}
	}

	this
		.filter('a[@href]') // que no se nos cuele algo que no sea un enlace
		.bind('click', clickHandler);

	return this; // permitimos concatenabilidad

}


function trim(cadena)
{
 
	for(i=0; i<cadena.length;i++ )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i--)
	{
	 
		if(cadena.substr(i,i)==" ")
		  {
			cadena=cadena.substring(0,i);
	 
		  }
		else
			break;
	}
	
	return cadena;
}
function DoBuscaUsuario(usr) {
 
 if (usr==null || usr=="")
   var usr=jQuery("#usuario").val();

 if (usr>"")
     {
 var parametros = {nombre:usr};
  
  var urlServer = "buscauser.php" 
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType: "json",
				   async:false,
                                    error: function (xhr, desc, exceptionobj) {
                                        
                                   tipoUsuario=2;
                                    DoBuscaUsuarioM(usr);
                     },
				   
				   success: function(data) 
	                {
                            
                        tipoUsuario=1;
                     recogeUser( data);
					}         
                  });
  }else
    alert(" usuario no Encontrado");  
}
function DoBuscaUsuarioM() {
 var usr=jQuery("#CTLMTOID_USUARIO").val();
 var parametros = {nombre:usr};

  var urlServer = "buscauserm.php"
   jQuery.ajax({type: "POST",
		 url: urlServer,
				   data: parametros,
				   dataType: "json",
				   async:false,
                                    error: function (xhr, desc, exceptionobj) {
                                   alert("DoBuscaUsuarioM ERROR "+xhr.responseText+desc+ exceptionobj);
                     },
				   
				   success: function(data)
	                {
                     recogeUser( data);
					}
                  });
}
function recogeUser(valorretornado){
   try 
      {
	  
	  $("#CTLMTONOMBRE_USUARIO").val("");
	  $("#CTLMTOFECHA_NAC").val("");
	  $("#CTLMTOCORREO_ELECTRONICO").val("");
	  $("#CTLMTOTELMOVIL").val("");
	  $("#CTLMTOTELOFI").val("");
	  $("#CTLMTOTELCASA").val("");
	  $("#CTLMTOPAIS_USUARIO").val("");
	  $("#CTLMTOESTADO").val("");
	  $("#CTLTIPO_USUARIO").val();
	  
      $("#CTLMTONOMBRE_USUARIO").val(valorretornado["NOMBRE_USUARIO"]);
	  $("#CTLMTOFECHA_NAC").val(valorretornado["FECHA_NAC"]);
	  $("#CTLMTOCORREO_ELECTRONICO").val(valorretornado["CORREO_ELECTRONICO"]);
	  $("#CTLMTOTELMOVIL").val(valorretornado["TELMOVIL"]);
	  $("#CTLMTOTELOFI").val(valorretornado["TELOFI"]);
	  $("#CTLMTOTELCASA").val(valorretornado["TELCASA"]);
	  $("#CTLMTOPAIS_USUARIO").val(valorretornado["CODIGO_PAIS"]);
	  $("#CTLMTOESTADO").val(valorretornado["ESTADO"]);
	  $("#CTLMTOPASSWORD").val(valorretornado["PWD"]);
	  $("#CTLTIPO_USUARIO").val(valorretornado["TIPO_USUARIO"]);
         
	}  
     catch(err) 
     {
     
     }       
    	
}
function DoSalvaUsuario() {
  
  var parametros = {
  ID_USUARIO:jQuery("#CTLMTOID_USUARIO").val(),
  PASSWORD:jQuery("#CTLMTOPASSWORD").val(),
  ESTADO :$("#CTLMTOESTADO  :selected").val(),
  NOMBRE_USUARIO:jQuery("#CTLMTONOMBRE_USUARIO").val(),
  FECHA_NAC:jQuery("#CTLMTOFECHA_NAC").val(),
  CORREO_ELECTRONICO:jQuery("#CTLMTOCORREO_ELECTRONICO").val(),
  TELMOVIL:jQuery("#CTLMTOTELMOVIL").val(),
  TELOFI:jQuery("#CTLMTOTELOFI").val(),
  TELCASA:jQuery("#CTLMTOTELCASA").val(),
  PAIS_USUARIO:jQuery("#CTLMTOPAIS_USUARIO").val(),
  TIPO_USUARIO:$("#CTLTIPO_USUARIO  :selected").val() 
  };
  
  var urlServer = "salvauser.php" 
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType: "text",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("al actualizar usuario "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data) 
	                {
                     
					   if (data.indexOf("OK")>=0)
							showDialog('Success', "Proceso Correcto",'success',3);
					   else
						 alert("Se Presento un Error "+data);
					}         
                  });
}
// SALVA USUARIOS ADMINISTRADORES
function DoSalvaUsuarioM() {

  var parametros = {
  ID_USUARIO:jQuery("#CTLMTOID_USUARIO").val(),
  PASSWORD:jQuery("#CTLMTOPASSWORD").val(),
  ESTADO :$("#CTLMTOESTADO  :selected").val(),
  NOMBRE_USUARIO:jQuery("#CTLMTONOMBRE_USUARIO").val(),
  FECHA_NAC:jQuery("#CTLMTOFECHA_NAC").val(),
  CORREO_ELECTRONICO:jQuery("#CTLMTOCORREO_ELECTRONICO").val(),
  TELMOVIL:jQuery("#CTLMTOTELMOVIL").val(),
  TELOFI:jQuery("#CTLMTOTELOFI").val(),
  TELCASA:jQuery("#CTLMTOTELCASA").val(),
  PAIS_USUARIO:jQuery("#CTLMTOPAIS_USUARIO").val(),
  TIPO_USUARIO:$("#CTLTIPO_USUARIO  :selected").val()
  };

  var urlServer = "salvauserm.php"
   jQuery.ajax({type: "POST",
		 url: urlServer,
				   data: parametros,
				   dataType: "text",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("al actualizar usuario "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data)
	                {

					   if (data.indexOf("OK")>=0)
						alert("datos Ingresados Correctamente");
					   else
						 alert("Se Presento un Error "+data);
					}
                  });
}
function DoActualizaUsuarios()
 {
   var parametros = {};
  
  $("#PROCESA").html('<img border="0" alt="Usuario ICON" src="../images2/ajaxwork.gif">');
  
   var urlServer = "actualizaUsuarios.php" 
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType:  "json",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("Actulizando Usuarios "+xhr.responseText+desc+ exceptionobj);
								   
								   $("#PROCESA").html("Actulizando Usuarios "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data) 
	                {
					alert(data['valor']);
					//showDialog('Success', "Se Actualizaron ",'success',3);
					$("#PROCESA").html("Se "+data['valor']);
					}         
        });
		
       
}

 function DoCambiaPassword(idUsuario)
 {
  
  var clavevieja=$("#clave").val();
  var parametros = {textoencriptar:clavevieja};
  
  var urlServer = "encriptatexto.php" 
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType:  "json",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("Obtieniendo texto encriptado "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data) 
	                {
					clavevieja=data["valor"];
					}         
                  });
  
   
  if ((jQuery("#CLAVENUEVA").val()==$("#CLAVENUEVAREP").val()) && jQuery("#CLAVENUEVA").val()>"" )
	 {
		 jQuery("#CTLMTOID_USUARIO").val(idUsuario);
		
		 DoBuscaUsuario(idUsuario);
                
                  
		  
		 if (clavevieja!=$("#CTLMTOPASSWORD").val())
		  
		   showDialog('Error', "Clave anterior no es correcta",'error',3);
		 else	
		    {
			 jQuery("#CTLMTOESTADO").val('E');
			DoCambiaPass();
			}
			
	 
	 }
	 else
	 showDialog('Error', "claves diferentes o nulas ",'error',3);
	    
	 }
 
 
 function DoCambiaPass() {
     
	 
  var parametros = {
  ID_USUARIO:jQuery("#CTLMTOID_USUARIO").val(),
  PASSWORD:jQuery("#CLAVENUEVA").val(),
  ESTADO :$("#CTLMTOESTADO  :selected").val(),
  
  NOMBRE_USUARIO:jQuery("#CTLMTONOMBRE_USUARIO").val(),
  FECHA_NAC:jQuery("#CTLMTOFECHA_NAC").val(),
  CORREO_ELECTRONICO:jQuery("#CTLMTOCORREO_ELECTRONICO").val(),
  TELMOVIL:jQuery("#CTLMTOTELMOVIL").val(),
  TELOFI:jQuery("#CTLMTOTELOFI").val(),
  TELCASA:jQuery("#CTLMTOTELCASA").val(),
  PAIS_USUARIO:jQuery("#CTLMTOPAIS_USUARIO").val() ,
  TIPO_USUARIO:$("#CTLTIPO_USUARIO  :selected").val()  
  };
  
  if (tipoUsuario==1)
  var urlServer = "salvauser.php" 
  else
      var urlServer = "salvauserm.php"  
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType: "text",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("al actualizar usuario "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data) 
	                {
					 
					   if (data.indexOf("OK")>=0)
					   {
							showDialog('Success', "Cambio Correcto",'success',3);
						}
					   else
					     showDialog('Error', "Al Cambiar Pass"+data,'error',3);
						  
					}         
					    
                  });
               
}

   

function ChecaSecurity(ses,usuario) {
 
var parametros = { session:ses,usuario:usuario};
  
  var urlServer = "../login/checasecurity.php" 
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   //data: parametros,
				   dataType: "text",
				   async:false,
				   success: function(data) 
	                {
                     recogeInfos2( data);
					}         
                  });
}
function recogeInfos2(valorretornado){ 
   
   if (valorretornado.indexOf("OK")>=0)
    {
	
	}
   else	
   {
     alert("no esta logueado");
   document.location.href="../index.php";
  return true;
   }
    
}
function DoRiniciaPass() {
	 
  if (jQuery("#CTLMTONOMBRE_USUARIO").val()>"") 
  {
  var parametros = {
  ID_USUARIO:jQuery("#CTLMTOID_USUARIO").val()
  };
  
  var urlServer = "reiniciaUser.php" 
   jQuery.ajax({type: "POST",
		 url: urlServer,
				   data: parametros,
				   dataType: "text",
				   async:false,
				   error: function (xhr, desc, exceptionobj) {
                                   alert("al actualizar usuario "+xhr.responseText+desc+ exceptionobj);
                     },
				   success: function(data) 
	                {
					 
					   if (data.indexOf("OK")>=0)
					   {
						showDialog('Success', "Clave Actualizada Exitosamente",'success',3);
						}
					   else
					    showDialog('Error', "Al Cambiar Pass"+data,'error',3);
					}         
					    
                  });
 }
else
  alert( "Debe busar El usuario Primero");
}

function regresaprincipal() {
 document.location.href="../index.php"
 return true;
}

function DoLogin() {
  
 var usr=jQuery("#usuario").val();
 var pwd=jQuery("#clave").val();
 var ses=jQuery("#session").val();
 if (ses==null ||ses==0)
     ses=1;
  
  //alert(usr+pwd);
  var parametros = {nombre:usr, pass: pwd, session:ses};
  
   var urlServer = "login/ingresa.php"
   jQuery.ajax({type: "POST", 
		 url: urlServer,
				   data: parametros,
				   dataType:    "json",
				   async:true,
			           error: function (xhr, desc, exceptionobj) {
                                   alert("Dologin ERROR "+xhr.responseText+desc+ exceptionobj);
                     },
				   
				   success: function(data) 
	                {
                             
                            if (data["valor"]==1)
                                {
                                      var ses=jQuery("#session").val();
                                      if (data["tipousario"]=="A")
                                        {
                                        // alert(valorretornado["roles"])
                                         document.location.href="../administrador/administracion.php?usuario="+usr+"&roles="+data["roles"];
                                         //debe buscar los roles que tiene asociado
                                         }
                                      else
                                         document.location.href="Coopeande5virtual.php?usuario="+usr;
                                    }
                               else
                                  alert("fallo tu login"+data["nombre"]);
     	            }
                  });
}



   
 
   

  

function limpiauser()
{
   try 
      {  
      $("#CTLMTOID_USUARIO").val("");	  
	  $("#CTLMTONOMBRE_USUARIO").val("");
	  $("#CTLMTOFECHA_NAC").val("");
	  $("#CTLMTOCORREO_ELECTRONICO").val("");
	  $("#CTLMTOTELMOVIL").val("");
	  $("#CTLMTOTELOFI").val("");
	  $("#CTLMTOTELCASA").val("");
	  $("#CTLMTOPAIS_USUARIO").val("");
	  $("#CTLMTOESTADO").val("");
	}  
     catch(err) 
     {
     
     }       
    	
}

function regreso(){ 
  document.location.href="../index.php";
  return true;
} 
 
function coopeeFylDigital() {
  document.location.href="Coopeande5Virtual.php";  
}  

function DoLogout(raizprogram) {
    document.location.href=raizprogram;
    /*
  var urlServer = "../login/logout.php"
  alert(urlServer);
  jQuery.ajax({type: "POST", 
		 url: urlServer,
				   type:"text",
				   async:true,
				   error: function (xhr, desc, exceptionobj) {
                                   alert(xhr.responseText);
                     },
				   
				   success: function(data) 
	                {
			alert(data);
                      document.location.href="http://www.pruebas.grupodivisoft.com/";
					}         
                  });*/
}   
  
  
  
// Login Form

$(function() {
    var button = $('#loginButton');
    var box = $('#loginBox');
    var form = $('#loginForm');
    button.removeAttr('href');
    button.mouseup(function(login) {
        box.toggle();
        button.toggleClass('active');
    });
    form.mouseup(function() { 
        return false;
    });
    $(this).mouseup(function(login) {
        if(!($(login.target).parent('#loginButton').length > 0)) {
            button.removeClass('active');
            box.hide();
        }
    });
});

