var xmlhttp;
var xmlhttp2;
var alista=new Array();
var statusdata=new Array();
var checkfields=new Array('statreceiver','sw1','sw2','sw3','fl1','fl2','fl3','fl4','fl5','fl6','fl7','fl8','fl9','fl10','sel1','hid1','hid2');
var fotos=new Array();
var textos=new Array();
var linxx=new Array();
var opacix= new Array();
var opacie= new Array();
var parto=new Array();
var isbroad=0;
var whoison='';
var keynum='';
var to='';
var unst=''
var globalfunction='';
var heldkey='';
var noaplica=0;
var targetllave='';

function loadexp(llave) {
	targetllave=llave;
	var fbk=document.getElementById('fbk');
	fbk.innerHTML="Editando Registro";
	fbk.style.color="#008";
	buscayuda('',llave,'','toolsqueryformout')
}

function toerase(dest,dato) {
	var dest=document.getElementById(dest);
	dest.value+=dato+" ";
}

function focusea2(id) {
	var pops=document.getElementById(id);
	whoison=pops;
	whoison.focus();
	whoison='';
	clearTimeout(to);
}

function poperoff(id) {
	heldkey='';
	var pops=document.getElementById('pops');
	pops.style.visibility='hidden';
	if (whoison!='') {
		to=setTimeout("focusea2(\""+id+"\")",100);
	}
	keynum='';
}

function loadfield(e,modo) {
	if (whoison!='') {
		var pops=document.getElementById('pops');
		if (modo==0) {
			whoison.value=pops.options[pops.selectedIndex].value;
		}
		else {
			if (window.event) {
				keynum=e.keyCode;
			}
			else if (e.which) {
				keynum=e.which;
			}
			if (keynum==13 || modo==2) {
				pops.style.visibility='hidden';
				whoison.value=pops.options[pops.selectedIndex].value;
				poperoff(whoison.id);
			}
		}
	}
}

function cmdetect(id,campo,enumlist,e) {
	if (window.event) {
		keynum=e.keyCode;
	}
	else if (e.which) {
		keynum=e.which;
	}
	if (keynum==17 || heldkey!='') {
		heldkey+=keynum+" ";
		var gama=document.getElementById('gama');
		gama.innerHTML=heldkey;
	}
}

function poper1(id,campo,enumlist,e) {
		if (window.event) {
			keynum=e.keyCode;
		}
		else if (e.which) {
			keynum=e.which;
		}
	if (heldkey=='' && keynum!=17) {
		var elc=document.getElementById(id);
		var pops=document.getElementById('pops');
		if (keynum!=9 && whoison=='' && keynum!=13) {
			whoison=elc;
			while (pops.options.length>0) {
				pops.options.remove(0);
			}
			pops.style.visibility='hidden';
			var patron=/\d+/;
			var cx=elc.style.left;
			cx=cx.match(patron);
			var cy=elc.style.top;
			cy=cy.match(patron);
			var ch=elc.style.height;
			ch=ch.match(patron);
			pops.style.left=cx+"px";
			cy=cy/1+ch/1+3;
			pops.style.top=cy+"px";
			pops.style.visibility='visible';
			buscayuda(id,campo,enumlist,'tools');
		}
		else if (whoison!='' && keynum==40){
			pops.focus();
			pops.selectedIndex=0;
		}
		else if (keynum==13) {
			pops.style.visibility='hidden';
			buscayuda(id,campo,enumlist,'toolsquery');
		}
	}
	if (keynum==17) {
		heldkey='';
	}
}

function popon(idnum,visi) {
	var box=document.getElementById("drop"+idnum);
	if (box) {
		if (visi==1) {
			box.style.visibility='visible';
		}
		if (visi==0) {
			box.style.visibility='hidden';
		}
	}
}

function addthis(num,elem,updname) {
	var updates=document.getElementById(updname);
	var updatesh=document.getElementById(updname+"-hidden");
	var sourcex=document.getElementById("doc-"+num);
	if (sourcex.checked) {
		alista[alista.length]=elem;
	}
	else {
		for (i in alista) {
			if (alista[i]==elem) {
				alista.splice(i,1);
			}
		}
	}
	updates.innerHTML=alista.join("| ");
	updatesh.value=alista.join("|");
}

function broadmain() {
	var menleft=document.getElementById('menleft');
	var ppal=document.getElementById('ppal');
	var menbot=document.getElementById('menbot');
	var theform=document.getElementById('theform');
	if (menleft && ppal && menbot) {
		if (isbroad==0) {
			isbroad=1;
			ppal.style.position="absolute";
			ppal.style.left="0px";
			menleft.style.visibility="hidden";
			menbot.style.visibility="hidden";
			if (theform) {
				theform.style.visibility="hidden";
				theform.style.position="absolute";
			}
		}
		else {
			isbroad=0;
			ppal.style.position="relative";
			ppal.style.left="0px";
			menleft.style.visibility="visible";
			menbot.style.visibility="visible";
			if (theform) {
				theform.style.visibility="visible";
				theform.style.position="relative";
			}
		}
	}
}

function showpic(dest,picture,zone) { //ideal para cambiar el src de un <img>, debe ser jpg minúsculas
  progress=document.getElementById('loading'+zone);
  progress.style.visibility='visible';
  img=document.getElementById(dest);
  img.src="fotos/"+picture+".jpg";
}

function progressout(zone) {
  progress=document.getElementById('loading'+zone);
  progress.style.visibility='hidden';
}

function correvideo(divmovile)
{
  divmovil=divmovile;
  bh=Math.round(bandelta/10);
  bstart=banheight;
  floc=bstart;
  document.getElementById(divmovil+"0").style.opacity=1;
  document.getElementById(divmovil+"1").style.opacity=1;
  document.getElementById(divmovil+"0").style.backgroundImage="url(\"fotos/"+fotos[1]+"\")";
  document.getElementById(divmovil+"1").style.backgroundImage="url(\"fotos/"+fotos[0]+"\")";
  if (textos[0]!='') {
   document.getElementById("linkmovil").href=linxx[0];
   document.getElementById("linkicon").href=linxx[0];
   document.getElementById("linkmovil").innerHTML=textos[0]; 
  }
  t=setTimeout("loopvideo()",7000);
  moviendo=1; //div que está recibiendo el cambio de opacidad
  signo=-1; //descendiendo o perdiendo opacidad; +1 = adquiriendo más opacidad
  nivelactual=100;
  proximage=1;
  imagesign=1;
  bm=0;
}

function traebanner(sense,modo) {
	if (bm!=0) {
		clearTimeout(bm);
	}
	floc+=sense*bh;
	if (sense>0 && floc>(banheight+bandelta)) {
		floc=banheight+bandelta;
		modo=0;
	}
	if (sense<0 && floc<banheight){
		floc=banheight;
		modo=0;
	}
	if (document.getElementById("banfon")) {
		document.getElementById("banfon").style.top=floc + "px";
		document.getElementById("banfo").style.top=floc + "px";
		if (modo==1) {
			bm=setTimeout("traebanner("+sense+",1)",50);
		}
	}
}

function loopvideo()
{
  t=setTimeout("loopvideo()",10);
    nivelactual=nivelactual+signo;
    manda=opacix[nivelactual];
    mandie=opacie[nivelactual];
    document.getElementById(divmovil+"1").style.opacity=manda;
    document.getElementById(divmovil+"1").style.filter=mandie;
    if (document.getElementById("banfon")) {
	if (nivelactual>1 && nivelactual<99) {
		traebanner(1,1);
	}
	else {
		traebanner(-1,1);
	}
    }
//    document.getElementById(divmovil+"1").innerHTML=manda;
    if (nivelactual<1) {
     clearTimeout(t);
    if (textos[proximage]!='') {
      document.getElementById("linkmovil").href=linxx[proximage];
      document.getElementById("linkicon").href=linxx[proximage];
      document.getElementById("linkmovil").innerHTML=textos[proximage]; 
     }
     t=setTimeout("loopvideo()",7000);
      signo=1;
      proximage=proximage+imagesign;
      if (proximage>fotos.length-1) {
        proximage=0;
      }
      document.getElementById(divmovil+"1").style.backgroundImage="url(\"fotos/"+fotos[proximage]+"\")";
    }
    if (nivelactual>99) {
     clearTimeout(t);
    if (textos[proximage]!='') {
      document.getElementById("linkmovil").href=linxx[proximage];
      document.getElementById("linkicon").href=linxx[proximage];
      document.getElementById("linkmovil").innerHTML=textos[proximage]; 
     }
     t=setTimeout("loopvideo()",7000);
      signo=-1;
      proximage=proximage+imagesign;
      if (proximage>fotos.length-1) {
        proximage=0;
      }
      document.getElementById(divmovil+"0").style.backgroundImage="url(\"fotos/"+fotos[proximage]+"\")";
    }
}

function showsubfloat(n) {
  for (i=1; i<=maxsubfloats; i++) {
    asub=document.getElementById("subfloat"+i);
      if (i != n) {
       asub.style.visibility='hidden';
      }
      else {
       asub.style.visibility='visible';
      }
  }
}

function openclose(inicio,fin,delx) {
  clearTimeout(t);
  if (avance==-1) {
    avance=inicio;
  }
  avance=avance+(delx);
  wall.style.left=avance+"px";
  if (delx<0 && avance>fin || delx>0 && avance<fin) {
    t=setTimeout('openclose('+inicio+","+fin+","+delx+')',25);
  }
}

function showhide() {
  ocbutton=document.getElementById("showhideicon");
  wall=document.getElementById("wall");
  avance=-1;
  if (wall.style.left=="0px") {
    ocbutton.src='gifs/ocultarmenu.jpg';
    t=setTimeout("openclose(0,200,50)",25);
  }
  else {
    ocbutton.src='gifs/vermenu.jpg';
    t=setTimeout("openclose(200,0,-50)",25);
  }
}

function getwhichkey(e) {
if(window.event) // IE
  {
  keynum = e.keyCode;
  }
else if(e.which) // Netscape/Firefox/Opera
  {
  keynum = e.which;
  }
}

function focusea(cual)
{
   document.getElementById(cual).focus();
}

function remuevefila(e,proceso) {
  getwhichkey(e);
  if (keynum == 13) {
    valore=document.getElementById("delreceiv").value;
    document.getElementById("delreceiv").value='';
    valore=valore - 1;
    if (valore>=0 && valore<alista.length) {
      alista.splice(valore,1);
      transmite(proceso);
    }
  }
}

function conectafila(e,proceso) {
  getwhichkey(e);
  if (keynum == 13) {
    valore=document.getElementById("linkreceiv").value;
    document.getElementById("linkreceiv").value='';
    valore=valore - 1;
    if (valore>=0 && valore<alista.length) {
      str=getfields();
      if (str && str.length>0) {
        alista[valore]=str;
        transmite(proceso);
      }
    }
  }
}

function saver(fieldid,timedelay,sesion) {
	clearTimeout(to);
	to='';
	var sourceobj=document.getElementById(fieldid);
	alista[0]=sourceobj.value;
	alista[0]=alista[0].replace(/\n/g,"|");
	transmite2('autosave',sesion);
	to=setTimeout("saver(\""+fieldid+"\","+timedelay+","+sesion+")",timedelay);
}

function saveretrieve(fieldid,sesion) {
	transmite2('saveretrieve',sesion)
}

function verifysaved(fieldid,sesion){
	transmite2('verifysaved',sesion);
}

function autosave(fieldid,timedelay,sesion) {
	if (to=='') {
		to=setTimeout("saver(\""+fieldid+"\","+timedelay+","+sesion+")",timedelay);
	}
	alista.length=0;
}

function transmite2(proceso,sesion)
{
    str=alista[0];

// agregar concatenando más valores a str separando con pipes, según otras cosas que requieran leerse.
    xmlhttp=GetXmlHttpObject();

    if (xmlhttp==null)
    {
      alert ("Your browser does not support AJAX!");
      return;
    }

    var url="ajaxer.php";
        url=url+"?q="+proceso+"&sesion="+sesion+"&data="+str; 
//proceso es pdv u otro, o más si se crean en ajaxer.php, el cual es un distribuidor con encabezado XML y de ahí se llaman otras rutinas según el valor de q.  Data lleva el dato leído en el campo statreceiver.
    xmlhttp.onreadystatechange=stateChanged2;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
    
}

function stateChanged2()
{
	if (xmlhttp.readyState==4)
	{
		st=xmlhttp.responseText;
		var larris=new Array();
		larris=st.split("|"); //primer posición código de comando, segundo, mensaje, tercero datos para mostrar en campo cuarto el campo que ha de cargarse.
		document.getElementById('statreturn').innerHTML=larris[1]; //muestra el status
		if (larris[0]==1) { //0=enviar, 1=recibir y mostrar
			larris[2]=larris[2].replace(/=br=/g,"\n");
			var destino=document.getElementById(larris[3]);
			destino.value=larris[2];
		}
	}
}


function transmite(proceso)
{
    str=alista.join(";");

// agregar concatenando más valores a str separando con pipes, según otras cosas que requieran leerse.
    xmlhttp=GetXmlHttpObject();

    if (xmlhttp==null)
    {
      alert ("Your browser does not support AJAX!");
      return;
    }

    var url="ajaxer.php";
        url=url+"?q="+proceso+"&data="+str; 
//proceso es pdv u otro, o más si se crean en ajaxer.php, el cual es un distribuidor con encabezado XML y de ahí se llaman otras rutinas según el valor de q.  Data lleva el dato leído en el campo statreceiver.
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
    
}

function getfields()
{
  ssx=document.getElementById("statreceiver").value;
  document.getElementById("statreceiver").value='';
  if (ssx.length>0) {
    for (a in checkfields) {
       if (document.getElementById(checkfields[a])) {
         if (checkfields[a]=='sw1' || checkfields[a]=='sw2' || checkfields[a]=='sw3') {
           if (document.getElementById(checkfields[a]).checked) {
             ssx=ssx+"|"+document.getElementById(checkfields[a]).value;
           }
         }
         else if (checkfields[a]=='sel1') {
           ssx=ssx+"|"+document.getElementById(checkfields[a]).selectedIndex;
         }
         else {
           sub3=checkfields[a].substr(0,3);
           if (sub3=='hid') {
               ssx=ssx+"|("+document.getElementById(checkfields[a]).value+")";
           }
           else {
             if (document.getElementById(checkfields[a]).value != '') {
               ssx=ssx+"|"+document.getElementById(checkfields[a]).value
             }
           }
         }
       }
    }
    return ssx;
  }
}

function extrae(e,proceso,sp)
{
  getwhichkey(e);
  if (keynum == 13) {
    if (!document.getElementById("linkreceiv") || document.getElementById("linkreceiv") && document.getElementById("linkreceiv").value=='') {
      str=getfields();
      alista[alista.length]=str;
      if (str && str.length>0) {
        transmite(proceso);
      }
    }
    else {
      conectafila(e,proceso)
    }
  }
  else if (sp=='transmite') {
    transmite(proceso);
  }
}

function buscayuda(lugar,campo,enumlist,funcion){

//PUEDE FUNCIONAR TAMBIEN CON LA FUNCION SEPARADA
//PRESENTA ERRORES SI EL ENCODING DEL DATO TRANSMITIDO VIENE MAL ESCRITO
//EJEMPLO encoding= utf8 (espacio luego del igual y falta de guion en utf-8) etc.

	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		var myxmlhttp=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		var myxmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	myxmlhttp.onreadystatechange=function()
	{
		if (myxmlhttp.readyState==4 && myxmlhttp.status==200)
		{
			unst=myxmlhttp.responseText;
			//window.alert(unst);
			if (globalfunction=='tools') {
				loadselect();
			}
			if (globalfunction=='toolsquery' && noaplica==0) { //para cargar el area GAMA
				loadgama();
			}
			if (globalfunction=='toolsqueryformout') { //para cargar el formulario
				loadformulario();
			}
			if (globalfunction=='toolsqueryformin') { //para cargar el formulario
				reloadgama();
			}
		}
	}
	if (lugar!='') {
		var subenum=enumlist.split("|");
		if (subenum[1]!='' && document.getElementById(subenum[1])) {
			subenum[1]=document.getElementById(subenum[1]).value;
			enumlist=subenum.join("|");
		}
		str=document.getElementById(lugar).value+"|"+campo+"|"+enumlist;
	}
	else {
		str=campo+"|";
	}
	//document.getElementById('gama').innerHTML=str;
	
	if (myxmlhttp==null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	}
	
	var url="ajaxer.php";
	globalfunction=funcion;
	if (globalfunction=='toolsquery' && noaplica==0) {
		var destino=document.getElementById('gama');
		destino.innerHTML="<img src=\"gifs/loading2.gif\">Espere un momento, consultando al servidor...";
	}
	url=url+"?q="+funcion+"&data="+str.replace("#","%23"); 


	myxmlhttp.open("GET",url,true);
	myxmlhttp.send(null);
}

function setstyle(theid,mode) {
	var destino=document.getElementById(theid);
	var cont=destino.value;
	if (cont.match(/sólo captura/i)) {
		if (mode==0) {
			destino.style.color="#000";
			destino.style.fontSize="8pt";
			destino.value='';
		}
		if (mode==1) {
			destino.style.color="#666";
			destino.style.fontSize="20pt";
		}
	}
	if (cont=='' && mode==2) {
		destino.style.color="#666";
		destino.style.fontSize="20pt";
		destino.value='Sólo Captura Aquí';
	}
	
}

function reloadgama() {
	noaplica=0;
	buscayuda('',targetllave,'','toolsquery');
}

function envixreg2() {
	var allids=document.getElementById('allids').value;
	var colector = new Array();
	allids=allids.split(",");
	for (i=0; i<allids.length; i++) {
		colector[i]=document.getElementById(allids[i]).value;
	}
	var toenviar=targetllave+"|"+colector.join("|");
	buscayuda('',toenviar,'','toolsqueryformin');
}

function loadformulario() {
	unst=unst.replace(/^\s+/,"");
	parto=unst.split("|");
	for (i=0; i<parto.length; i++) {
		var pares=parto[i].split("=");
		if (document.getElementById(pares[0])) {
			var destino=document.getElementById(pares[0]);
			destino.value=pares[1];
			if (pares[1].match(/sólo captura/i)) {
				setstyle(pares[0],1);
			}
		}
	}
}

function loadgama() {
	parto=unst.split("|");
	var destino=document.getElementById('gama');
	destino.innerHTML='';
	for (i=0; i<parto.length; i++) {
		destino.innerHTML+=parto[i]+"<hr>\n";
	}
	var fbk=document.getElementById('fbk');
	fbk.innerHTML="Nuevo Registro";
	fbk.style.color="#800";

}

function loadselect() {
	var destino=document.getElementById('pops');
	if (!unst.match(/no aplica/i)) {
		parto=unst.split("|");
		for (i=0; i<parto.length; i++) {
			if (parto[i] != '' && !parto[i].match(/^\s+$/)) {
				var nuevo = document.createElement('option');
				nuevo.value=parto[i];
				nuevo.text=parto[i];
				if (i==0) {
					var anterior=null;
				}
				else {
					var anterior=destino.options[i-1];
				}
				try {
					destino.add(nuevo,anterior);
				}
				catch(error) {
					destino.add(nuevo,i-1);
				}
			}
		}
		if (destino.options.length>=0 && keynum==40) {
			destino.focus();
			destino.selectedIndex=0;
		}
		noaplica=0;	
	}
	else {
		destino.style.visibility='hidden';
		noaplica=1;	
	}
}

function buscaregistros(){
    xmlhttp2=GetXmlHttpObject();

    str=document.getElementById("statreceiver").value;
    if (xmlhttp2==null)
    {
      alert ("Your browser does not support AJAX!");
      return;
    }

    var url="ajaxer.php";
        url=url+"?q=search"+"&data="+str; 
//proceso es pdv u otro, o más si se crean en ajaxer.php, el cual es un distribuidor con encabezado XML y de ahí se llaman otras rutinas según el valor de q.  Data lleva el dato leído en el campo statreceiver.
    xmlhttp2.onreadystatechange=stateChangedSearch;
    xmlhttp2.open("GET",url,true);
    xmlhttp2.send(null);
    
}


function stateChanged()
{
if (xmlhttp.readyState==4)
{

st=xmlhttp.responseText;
document.getElementById('statreturn').innerHTML=st;
document.getElementById("statreceiver").focus();
statusdata=st.split("-");
folio=statusdata[2];
folionum=folio.split(":");
  if (folionum[1]!='') {
    alert("La operación se ha cerrado con el folio #"+folionum[1]);
    document.getElementById("enviar").disabled=true;
    document.getElementById("enviar").style.backgroundColor="#cccccc";
    document.getElementById("enviar").style.color="#ffffff";
  }
}
}

function cargamain() {
  var main = document.getElementById("statreceiver");
  var elsel = document.getElementById("selectboxchooser");
  main.value=elsel.options[elsel.selectedIndex].value;
  main.focus();
}

function stateChangedSearch()
{
if (xmlhttp2.readyState==4)
{

var st=xmlhttp2.responseText;
var partes = new Array();
var campos = new Array();
partes=st.split("|")
var elsel=document.getElementById('selectboxchooser');
while (elsel.length>0) {
  elsel.remove(0);
}
for (dx in partes ) {
  auxrecord=partes[dx];
  campos=auxrecord.split(";");
  var moreopts = document.createElement('option');
  moreopts.text =  campos[1] + "|" +campos[2] + "|" +campos[3]+ "|$" +campos[4];
  moreopts.value = campos[0];
  try
  {
    elsel.add(moreopts,null); // standards compliant
  }
  catch(ex)
  {
    elsel.add(moreopts); // IE only
  }
}

document.getElementById("statreceiver").focus();
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}


       function tdactiva(a,cn)
       {
         document.getElementById(a).className=cn;
       }
       function incdec(a,masmenos)
       {
         valor=document.getElementById(a).value;
         if (masmenos==-1) {
           valor--;
         }
         if (masmenos==1) {
           valor++;
         }
         if (masmenos==0) {
           valor='';
         }
         document.getElementById(a).value=valor;
       }

      function findinselect(formaname,selname,sample)
      {
        selector=eval("document."+formaname+"."+selname);
        muestra=eval("document."+formaname+"."+sample+".value");
        muestrau=muestra.toUpperCase();
        for (i=0; i<selector.length; i++) {
          var stron=selector.options[i].text;
          strup=stron.toUpperCase();
          testeado=strup.match(muestrau);
          result=eval(testeado);
          if (result) {
            selector.selectedIndex=i;
            break;
          }
        }
      }


