﻿function nuevoAjax()
{ 
        var xmlhttp=false; 
        try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");     }
        catch(e){ try{   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } 
                  catch(E) { xmlhttp=false; }
                }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 
        return xmlhttp; 
}
function logIn(tipoUsuario){
	document.getElementById("mensajeSecLogin").innerHTML="";
	if(document.getElementById("Login").value==""){
		document.getElementById("mensajeSecLogin").innerHTML="<div class='error'>Campo Login Vacio</div>";
		return;
	}
	if(document.getElementById("Pass").value==""){
		document.getElementById("mensajeSecLogin").innerHTML="<div class='error'>Campo Password Vacio</div>";
		return;
	}
	
	var ajax_1=nuevoAjax();
	ajax_1.open("GET","libreria/libAjax.php?action=login&login="+document.getElementById("Login").value+"&tipoUsuario="+tipoUsuario+"&pass="+hex_md5(document.getElementById("Pass").value), true);
	ajax_1.onreadystatechange=function() 
	 { 	
			  if(ajax_1.readyState==4) {
				var texto=ajax_1.responseText; 
				var datos=texto.split("-");
				if(texto.indexOf("@Error")!=-1)				   
				   {
				   if(datos[1].indexOf("Password")!=-1) {
					   document.getElementById("intentos").value++;
					   if(document.getElementById("intentos").value==3){
						   intentosFallidos(tipoUsuario);
						   }
				   }
				   if(texto.indexOf("ChangeStatus")!=-1){
					   datos[1]+="<br><a onclick='ChangeStatus()' >Cambiar Estatus</a>";
					 }
				   document.getElementById("mensajeSecLogin").innerHTML="<div class='error'>"+datos[1]+"</div>"; 
				   }
				else
				   location.reload();
			  }
	 }
	 ajax_1.send(null);
}
function intentosFallidos(tipoUsuarios){
	var ajaxInt=nuevoAjax();
	ajaxInt.open("GET","libreria/libAjax.php?action=loginFallido&login="+document.getElementById("Login").value+"&tipoUsuario="+tipoUsuarios+"&pass="+hex_md5(document.getElementById("Pass").value), true);
	ajaxInt.onreadystatechange=function() 
	 { 	
			  if(ajaxInt.readyState==4) {
				var texto=ajaxInt.responseText; 
			    alert("LLEVA 3 INTENTOS FALLIDOS ");
			  }
	 }
	 ajaxInt.send(null);
	 enviarCorreo(document.getElementById("Login").value,1);
}

function logOutWindow(){ 
    var ajax_6=nuevoAjax();
	ajax_6.open("GET","libreria/libAjax.php?action=logout", true);
	ajax_6.onreadystatechange=function() 
	 { 	
			  if(ajax_6.readyState==4) { 
			     
			  }
	 }
	 ajax_6.send(null);
	 
	} 	
function logOut(){
	pagina="";
	if(arguments.length>0) 	pagina=arguments[0];

	var gcko = navigator.userAgent.toLowerCase(); 
    /*if (gcko.indexOf('gecko')!=-1)
       window.removeEventListener("beforeunload", logOutWindow, true); 
    else
       window.detachEvent("onbeforeunload", logOutWindow);*/ 
	 var ajax_3=nuevoAjax(); 
	ajax_3.open("GET","libreria/libAjax.php?action=logout", true);
	ajax_3.onreadystatechange=function() 
	 { 	
			  if(ajax_3.readyState==4){ 
			     if(pagina!="") 	location.href=pagina;
					else   location.reload();
			  }
	}
	 ajax_3.send(null);
	}
function enviarCorreo(camplogin,tipo){
	var lon=enviarCorreo.arguments.length;
    var ajaxEnv=nuevoAjax();
	var dir="libreria/";
	if(lon==3)dir=enviarCorreo.arguments[2]; 
	ajaxEnv.open("GET",dir+"libAjax.php?action=enviarCorreo&login="+camplogin+"&tipo="+tipo, true);
	ajaxEnv.onreadystatechange=function() 
	 { 	
			  if(ajaxEnv.readyState==4) {
				var texto=ajaxEnv.responseText; 
			    
			  }
	 }
	 ajaxEnv.send(null);
}	
function forgetPass(){
	document.getElementById("mensajeSecLogin").innerHTML="<div class=email>Login (*) <br> <input name='LoginEma' type='text' id='LoginEma' size='20' class=secLoginBody-text maxlength='25' onblur=document.getElementById('msjForget').innerHTML='' /><br><div id='msjForget' name='msjForget'></div><br> <a onClick=validaForget()>Enviar</a><br><div id='erroremail' name='erroremail'></div></div>";
	/*
	Email (*) <br> <input name='Email' type='text' id='Email' size='30' class=secLoginBody-text maxlength='25'><br>
	*/
}
function  validaForget(){
	var datosF;
if(document.getElementById("LoginEma").value==""){
		document.getElementById("erroremail").innerHTML="<div class='error'>Campo Login Vacio</div>";
		document.getElementById("LoginEma").focus();
		return;
	}
	
	document.getElementById("erroremail").innerHTML="";
	if(document.getElementById("response")==null){
	var ajaxFor=nuevoAjax();
	ajaxFor.open("GET","libreria/libAjax.php?action=olvidoPassword&login="+document.getElementById("LoginEma").value, true);
	ajaxFor.onreadystatechange=function() 
	 { 	
			  if(ajaxFor.readyState==4) {
				var texto=ajaxFor.responseText; 
				if(texto.indexOf("@forget")!=-1){
					 datosF=texto.split("-");
					if(datosF[0]==""){
						document.getElementById("erroremail").innerHTML="<div class='error'>Login no existe</div>";
		                document.getElementById("LoginEma").focus();
						return;
					}
					document.getElementById("msjForget").innerHTML=datosF[0]+"<br><input type=password maxlength=30 id=response name=response size=20 class='secLoginBody-text' /><input type=hidden id=resBd name=resBd/>";
					document.getElementById("resBd").value=datosF[1];
				}
			    
			  }
	 }
	 ajaxFor.send(null);
	 }
	 else{
		 if(document.getElementById("response").value==""){
		 		document.getElementById("erroremail").innerHTML="<div class='error'>Campo respuesta Vacio</div>";
		document.getElementById("response").focus();
		return;
	     }
		 if(hex_md5(document.getElementById("response").value.toLowerCase())!=document.getElementById("resBd").value){
			 document.getElementById("erroremail").innerHTML="<div class='error'>Respuesta no coincide</div>";
		document.getElementById("response").focus();
			 return;
			 }
			 
			 alert("Password enviado al Correo");
			 enviarCorreo(document.getElementById("LoginEma").value,2);
			 document.getElementById("mensajeSecLogin").innerHTML="";
		 }
	 

}
function ChangeStatus()
{
  enviarCorreo(document.getElementById("Login").value,3);
  alert("Revise su correo Por favor");
  document.getElementById("mensajeSecLogin").innerHTML="";
  document.getElementById("Login").value="";
  document.getElementById("Pass").value="";
}
function cargarFrameAdm(pagina){
  document.getElementById("frameSecCentroAdm").src=	pagina;
}
//-----------------------------------------------------------------------------------------------------
function validarEmail(valor) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor))  return (true)
  else   return (false)
 }

function validarExpresionRegula(campo, caract_extra,opc) {
  var ubicacion="";
  var enter = "\n";
  var caracteres="";
  var letras="abcdefghijklmnopqrstuvwxyzñ ABCDEFGHIJKLMNOPQRSTUVWXYZÑáéíóúÁÉÍÓÚ-/_,?:";
  var numeros="1234567890";
  if(opc==1) // 1=letras y numeros  ,,,, 2=letras ,, 3=numeros
    caracteres =letras + numeros + String.fromCharCode(13) + enter + caract_extra
  else if(opc==2)
  		caracteres =letras + String.fromCharCode(13) + enter + caract_extra
		else caracteres = numeros + String.fromCharCode(13) + enter + caract_extra
  var contador = 0
  var sw=true;
  var lonCampo=campo.length;
  for (i=0; i < lonCampo && sw; i++) {
    ubicacion = campo.substring(i, i + 1)
    if (caracteres.indexOf(ubicacion) != -1) {
      contador++
    } else {
      alert("ERROR: No se acepta el caracter '" + ubicacion + "'.")
      sw=false;
    }
  }
  return (sw);
}

function validarFormulario(formulario) {  
  idRespuesta=0;
  var numElement=formulario.length;
  var error=0;
  var i=0;
  var campoObligatorio="";
  var campoEspecial="";
   for(i=0;i<numElement && error==0;i++)
  { 
    var objElement=formulario[i];
	if(objElement.lang !='' )
	{  
	  
	  valor=objElement.lang.split('-');
	   campoObligatorio=valor[0];
	   campoEspecial=valor[1];
	   
	} else{
	   campoObligatorio="";
       campoEspecial="";
	  	}
	var caract_ext=":";
	objElement.style.border="";//"1px  #666666 solid";
     switch(objElement.type){
	 case 'text': //alert('esto es un texto');
	              valCarat=1;
				  caract_ext="?=,/:.;&";//ojo si general
				  if(campoEspecial=="especial") caract_ext="@.-º?=,/:"; 
				  if(campoEspecial=="float") { 
				  		caract_ext=".,"; 
						valCarat=3;
				  }
	 			  if(campoObligatorio=="si" && objElement.value=="") 
				  { error=1;
				    alert("campo obligatorio vacio");			
				  }
				  if( error!=1 && ((campoObligatorio=="si" && campoEspecial=="email") || (campoObligatorio=="no" && campoEspecial=="email" && objElement.value!="")) )
				    {   caract_ext="@.";
					    if(!validarEmail(objElement.value)) 
					 		{ error=1;
							  alert("campo email invalido");	
							}
					}
				  if(error!=1 && campoObligatorio=="si" && campoEspecial=="confirmacion") {
						  caract_ext="@.";
					     campo=objElement.name;//
				  		 campo=campo.substring(0,campo.length-1);
						 if(document.getElementById(campo).value!=objElement.value){
						 	error=1;
					  		alert("campos de emails no son iguales");	
						 }
					  }

				 if( error!=1 && campoEspecial=="number" && objElement.value!="" && isNaN(objElement.value) ){
					  error=1;
					  valCarat=3;
					  alert("campo numerico invalido");	
					}
				 if(error!=1 && campoEspecial!="noValidar" && !validarExpresionRegula(objElement.value,caract_ext,valCarat)) error=1;
	 			  break;
	 case 'password': 
	 				  if(campoObligatorio=="si" && objElement.value=="") 
				 		 {  error=1;
				    		alert("campo obligatorio vacio");			
				  		 }	
					  if(error!=1 && campoObligatorio=="si" && campoEspecial=="confirmar") {
					     campo=objElement.name;//
				  		 campo=campo.substring(0,campo.length-1);
						 if(document.getElementById(campo).value!=objElement.value){
						 	error=1;
					  		alert("campos de passwords no son iguales");	
						 }
					  }
	 				  if(error!=1 && campoObligatorio=="si" && campoEspecial=="clave") caract_ext="&*@#$";
				      if(error!=1 && !validarExpresionRegula(objElement.value,caract_ext,1)) error=1;
	 				 break;
	 case 'textarea': //alert('esto es un texto_area'); 
	 			 if(campoObligatorio=="si" && objElement.value=="") 
				  { alert("campo obligatorio vacio");
					error=1;
				  }
				  
	 			  break;
	 case 'checkbox': if(campoObligatorio=="si" && objElement.checked==false) 
				  { alert("campo obligatorio vacio");
					error=1;
				  }
	 			  break;
	 case 'select-one': //alert('esto es un select - one'); 
	 			if(campoObligatorio=="si" && objElement.selectedIndex<=0) 
				  { alert("campo obligatorio debe estar seleccionado");
					error=1;
				  }
	 			  break;
	 case 'select-multiple': 
//	 alert('esto es un select - multiple');
	 			if(campoObligatorio=="si" && objElement.selectedIndex<0) 
				  { alert("campo obligatorio debe elegir al menos una opción");
					error=1;
				  }
	 			  break;
	 case 'hidden': //alert('esto es un select - one'); 		
				if(error!=1 && campoObligatorio=="si" && campoEspecial=="repetido" && objElement.value==1)
				  { 
				  error=1;
				  campo=objElement.name;//
				  campo=campo.substring(0,campo.length-1);
				  objElement=document.getElementById(campo);
				  alert("Valor ya existe ");
				  }
				  
	 			  break;
	 case 'submit': //alert('esto es un submit'); 
	 			  break;
	 }
  }

   if(error==1) 
  { objElement.style.border="1px #FF0000 solid";
    objElement.focus();	 
	return (false);	
  }	else return (true);
  
}


//----------------------------------------------------------------------------------------------------
function cargarDiv(url) { // url="viewMarca.php?action=1&edit=10"
	 if(url.indexOf('edit=11')!= -1)
	     { abrirVentana(url,800,600,1,0,0,"centrar",1);
		   return;
		 } 
	if(url.indexOf('edit=4')!= -1)
	     { 
		 if(!confirm("¿ Esta seguro de eliminar este registro ?"))
		    return;
		 } 	 
		 location.href=url;
}
function copiarURL(meintext){
if (window.clipboardData)
    {
    // the IE-manier
   window.clipboardData.setData("Text", meintext);
   // waarschijnlijk niet de beste manier om Moz/NS te detecteren;
   // het is mij echter onbekend vanaf welke versie dit precies werkt:
   }
   else if (window.netscape)
   {

   // dit is belangrijk maar staat nergens duidelijk vermeld:
   // you have to sign the code to enable this, or see notes below
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

   // maak een interface naar het clipboard
   var clip = Components.classes['@mozilla.org/widget/clipboard;1']
       .createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;

   // maak een transferable
   var trans = Components.classes['@mozilla.org/widget/transferable;1']
       .createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;

   // specificeer wat voor soort data we op willen halen; text in dit geval
   trans.addDataFlavor('text/unicode');

   // om de data uit de transferable te halen hebben we 2 nieuwe objecten
   // nodig om het in op te slaan
   var str = new Object();
   var len = new Object();

   var str = Components.classes["@mozilla.org/supports-string;1"]
       .createInstance(Components.interfaces.nsISupportsString);

   var copytext=meintext;

   str.data=copytext;

   trans.setTransferData("text/unicode",str,copytext.length*2);

   var clipid=Components.interfaces.nsIClipboard;

   if (!clip) return false;

   clip.setData(trans,null,clipid.kGlobalClipboard);

   }
   alert("Link Copiado Exitosamente");
   return false;
}
//---------------------------------------contraer y expandir DIVs-----------------------------------------
	function divExtenderContraer (divEle) {
		var objeto = document.getElementById(divEle);
		if(objeto.style.display == 'block') objeto.style.display = 'none';
		else objeto.style.display = 'block';
	}
//---------------------------------------cargar secciones / portales-----------------------------------------
	function cargarSeccion(obj) {
		//var objeto_ = document.getElementById("objSeccion");
		if(obj.value==0)return;
		
		s=obj.value.substr(0,7);
		if(s=='http://')
		window.open(obj.value);
		else location.href="?idSeccion="+obj.value;

	}
//--------------------------------------------------------------------------------------------------------
//vectorOpcion={"_blank","_parent","_self","_top","frameSecCentro"};
function cargarFrame(pagina){
	//opc=opcion.split("-");
  top.document.getElementById("frameSecCentro").src=pagina;
}

function marcarSec(num){
	if(num==1) opc=true;
	else opc=false;
    obj=document.getElementById("seccion[]");
	k=obj.length;
	for(i=0;i<k;i++){
		obj.options[i].selected=opc;
	}
}
//--------------------------------------------------------------------------------------------------------
var idDiv=1;
var idDivMax=3;

function _buscarFiltro(){
for(i=1;i<=idDivMax;i++) {  
	filtId="filtro_"+i;
	document.getElementById(filtId).style.display="none";
}
if(idDiv<idDivMax) idDiv=idDiv+1;
else idDiv=1;
document.getElementById("filtro_"+idDiv).style.display="block";
document.getElementById("opcionFiltro").value=idDiv;
document.getElementById("pie").innerHTML=document.getElementById("ayuda_"+idDiv).value;

}

function _buscar(){ document.formaFiltro.submit(); }

function _initFecha(fecha,boton){
Zapatec.Calendar.setup({firstDay : 0,weekNumbers : false, inputField : fecha, ifFormat : '%Y-%m-%d', button : boton});
}

function _inicializarVarFiltros(cantidad){
idDivMax=cantidad;
idDiv=1;
for(i=1;i<=idDivMax;i++) {  
	filtId="filtro_"+i;
	if(document.getElementById(filtId)!=null)document.getElementById(filtId).style.display="none";
}
if(document.getElementById("filtro_1")!=null)
document.getElementById("filtro_1").style.display="block";
}
//--------------------------------------------------------------------------------------------------------

function cargarBanner(){
  	
  var ajaxban=nuevoAjax();
	ajaxban.open("GET","libreria/libAjax.php?action=banner", true);
	ajaxban.onreadystatechange=function() 
	 { 	
			  if(ajaxban.readyState==4) {
				  
				document.getElementById("banner").innerHTML=ajaxban.responseText; 
			    
			  }
	 }
	 ajaxban.send(null);
	 setTimeout("randomBanner()",2000);
}
function randomBanner(){
   if(document.getElementsByName("randomBan")==null)return;
   var long=document.getElementsByName("randomBan").length;
   for(indexban=0;indexban<long;indexban++)
   document.getElementsByName("randomBan")[indexban].style.display="none";
   var rand=Math.floor(Math.random()*long);
   if(document.getElementsByName("randomBan")[rand]!=null)
   document.getElementsByName("randomBan")[rand].style.display="block";
   setTimeout("randomBanner()",2000);
}
//----------------------------------------------------------------------------------------------------
function cargarPoll(opcion){
	var ajaxPoll=nuevoAjax();
	var valor=0;
	if(document.getElementsByName("opEnc")!=null){
	for(i=0;i<document.getElementsByName("opEnc").length;i++)
       if(document.getElementsByName("opEnc")[i].checked) 
	     {valor=document.getElementsByName("opEnc")[i].value;
		  break;
		 }
	}
	ajaxPoll.open("GET","libreria/libAjax.php?action=poll&tipo="+opcion+"&id="+valor, true);
	ajaxPoll.onreadystatechange=function() 
	 { 	
			  if(ajaxPoll.readyState==4) {
				var respAj = ajaxPoll.responseText;
				if(respAj.indexOf("<span></span>")!=-1)
				document.getElementById("poll").style.display="none";
				else
				document.getElementById("poll").style.display="block";
				document.getElementById("poll").innerHTML=respAj;
			    if(document.getElementById("aVotar")!= null && opcion==1)
				document.getElementById("aVotar").onclick="";
			  }
	 }
	 ajaxPoll.send(null);
}


function end_frame(){  
hEnd=document.getElementById("frameSecCentro").contentWindow.document.body.scrollHeight; 
document.getElementById("frameSecCentro").contentWindow.scrollTo(0, hEnd); 
}
function Buscar(obj,evt)
	{
         var valor=obj.value;
		var evto = (evt) ? evt : event
		var charCode = (evto.charCode) ? evto.charCode : evto.keyCode
	
		if (charCode==13&&document.getElementById("objBuscador").value!="") {
		cargarFrame("libreria/portal.php?caso=3&page=0&palabras="+document.getElementById("objBuscador").value);
		document.getElementById("objBuscador").value="";
		}
		else{
			//alert(charCode)
			if (charCode==8)return true;
			valor+=String.fromCharCode(charCode);
			//alert(valor)
			//alert(/^[A-Za-z]+[\+]*/.test(valor))
			if(/^[A-Za-z]+(\+[A-Za-z]+)*/.test(valor))return true;
			else return false;
		}
		
		return true;
	}

function activarSeccion(id,base){
	id_='padre_'+id;
img_='img_'+id;
if(document.getElementById(id_).style.display=="none") { 	
	document.getElementById(id_).style.display="block";
	document.getElementById(img_).src=base+"/imagen/menos_gris.gif";
}
else{
	document.getElementById(id_).style.display="none";
	document.getElementById(img_).src=base+"/imagen/mas_gris.gif";
}
}



function calcHeight()
{
  //find the height of the internal page
  var the_height=
    document.getElementById('frameSecCentro').contentWindow.
      document.body.scrollHeight;

  //change the height of the iframe
  document.getElementById('frameSecCentro').height=
      the_height;
}



//////////////////////////////////////////////////////7777
    function getElement(aID)
    {
        return (document.getElementById) ?document.getElementById(aID):document.all[aID];
    }

    function getIFrameDocument(aID){ 
        var rv = null; 
        var frame=getElement(aID);
       if (frame.contentDocument)
            rv = frame.contentDocument;
        else 
            rv = document.frames[aID].document;
        return rv;
    }

    function adjustMyFrameSize()
    {
        var frame = getElement("frameSecCentro");
        var frameDoc = getIFrameDocument("frameSecCentro");
        frame.height = frameDoc.body.offsetHeight+20;
		
    }
//-------------------------
function resize() {
height = $("#frameSecCentro").contents().find("body").outerHeight();
$("#frameSecCentro").attr("height", height + "px");
}

