﻿/***************************************************************************/
/*                              TELELONJAS.JS                              */
/***************************************************************************/

var MiVentana;
var calendario = new CalendarPopup();
var IdAct = '';
calendario.showYearNavigation();
calendario.setReturnFunction("VerFecha");

//-------------------------------------------------------------------------------------------
function Submitir(MiForm)
{
  MiForm.submit()
}

//-------------------------------------------------------------------------------------------
function Trim(szCadena)
{
  return szCadena.replace(/^(\s*)([\W\w]*)/,'$2').replace(/(\s*)$/,'')
}

//-------------------------------------------------------------------------------------------
function addRandom(szPagina)
{

  szDest = szPagina;
  pos    = szDest.indexOf("&rnd=");
  if(pos == -1)
    pos = szDest.indexOf("?rnd=");

   if(pos >= 0) {
    pos2 = szDest.indexOf("&", pos+1);
    if(pos2 >= 0)
      szDest = szDest.substr(0, pos)+szDest.substr(pos2);
    else
      szDest = szDest.substr(0, pos);
  }

  szDest += "&rnd="+Math.round(1000000*Math.random());

  return szDest;

}  // addRandom

//-------------------------------------------------------------------------------------------
function VerNoticia(Destino)
{  
  szDestino = addRandom(Destino);

  MiVentana = window.open("", "Noticias", "scrollbars,height=400,width=540")
  MiVentana.location = szDestino
  MiVentana.focus;
}

//-------------------------------------------------------------------------------------------
function cargarPagina(destino, szPagina)
{

  szDest = addRandom(szPagina);
  destino.location.href = szDest;

}  // cargarPagina()

//-------------------------------------------------------------------------------------------
function setIdActual(id)
{
  IdAct = id;
}

//-------------------------------------------------------------------------------------------
function getCalendario()
{
  return calendario;
}

//-------------------------------------------------------------------------------------------
// Function to get input back from calendar popup
function VerFecha(y,m,d) 
{
  var mm,dd;
  mm = "00" + m;
  mm = mm.substr(mm.length-2,2);
	dd = "00" + d;
	dd = dd.substr(dd.length-2,2);
	document.getElementById(IdAct).value= dd + "/" + mm + "/" + y;
}

//-------------------------------------------------------------------------------------------
function FormateaFecha(obj)
{
  var ano,mes,dia; 
  dia=formatDate(new Date(getDateFromFormat(obj.value,'d/M/y')),'dd');
  mes=formatDate(new Date(getDateFromFormat(obj.value,'d/M/y')),'MM');
  ano=formatDate(new Date(getDateFromFormat(obj.value,'d/M/y')),'yyyy');
  obj.value = dia + "/" + mes + "/" + ano;
}

//-------------------------------------------------------------------------------------------

function emailCheck (emailStr) 
{
  /* The following pattern is used to check if the entered e-mail address
     fits the user@domain format.  It also is used to separate the username
     from the domain. */
  var emailPat=/^(.+)@(.+)$/
  /* The following string represents the pattern for matching all special
     characters.  We don't want to allow special characters in the address. 
     These characters include ( ) < > @ , ; : \ " . [ ]    */
  var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
  /* The following string represents the range of characters allowed in a 
     username or domainname.  It really states which chars aren't allowed. */
  var validChars="\[^\\s" + specialChars + "\]"
  /* The following pattern applies if the "user" is a quoted string (in
     which case, there are no rules about which characters are allowed
     and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
     is a legal e-mail address. */
  var quotedUser="(\"[^\"]*\")"
  /* The following pattern applies for domains that are IP addresses,
     rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
     e-mail address. NOTE: The square brackets are required. */
  var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
  /* The following string represents an atom (basically a series of
     non-special characters.) */
  var atom=validChars + '+'
  /* The following string represents one word in the typical username.
     For example, in john.doe@somewhere.com, john and doe are words.
     Basically, a word is either an atom or quoted string. */
  var word="(" + atom + "|" + quotedUser + ")"
  // The following pattern describes the structure of the user
  var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
  /* The following pattern describes the structure of a normal symbolic
     domain, as opposed to ipDomainPat, shown above. */
  var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


  /* Finally, let's start trying to figure out if the supplied address is
     valid. */

  /* Begin with the coarse pattern to simply break up user@domain into
     different pieces that are easy to analyze. */
  var matchArray=emailStr.match(emailPat)
  if (matchArray==null) {
    /* Too many/few @'s or something; basically, this address doesn't
       even fit the general mould of a valid e-mail address. */  
  	return false
  }
  
  var user   = matchArray[1]
  var domain = matchArray[2]

  if (user.match(userPat)==null) {
      return false
  }

  /* if the e-mail address is at an IP address (as opposed to a symbolic
     host name) make sure the IP address is valid. */
  var IPArray=domain.match(ipDomainPat)
  if (IPArray!=null) {
    for (var i=1;i<=4;i++) {
      if (IPArray[i]>255) {
         return false
      }
    }
    return true
  }

  var domainArray=domain.match(domainPat)
  if (domainArray==null) {
    return false
  }

  /* domain name seems valid, but now make sure that it ends in a
     three-letter word (like com, edu, gov) or a two-letter word,
     representing country (uk, nl), and that there's a hostname preceding 
     the domain or country. */

  /* Now we need to break up the domain to get a count of how many atoms
     it consists of. */
  var atomPat=new RegExp(atom,"g")
  var domArr=domain.match(atomPat)
  var len=domArr.length
  if (domArr[domArr.length-1].length<2 || 
      domArr[domArr.length-1].length>3) {
     return false
  }

  if(len<2) {
    var errStr="A esta direccion le falta el nombre del host!"
   return false
  }

  return true;
}

//-------------------------------------------------------------------------------------------
function enviarMensajeContacto(miForm, objEMail, objContenido)
{
  var msgError = "";

  objEMail.value     = objEMail.value.replace(/^(\s*)([\W\w]*)/,'$2').replace(/(\s*)$/,'')
  objContenido.value = objContenido.value.replace(/^(\s*)([\W\w]*)/,'$2').replace(/(\s*)$/,'')

  if(!emailCheck(objEMail.value)) {
    msgError += "La dirección de correo no parece válida.\n";
  }

  if(objContenido.value.length == 0) {
    msgError += "Debe indicarse algo en el contenido.\n";

  }

  if(msgError == "")
    miForm.submit();
  else
    alert(msgError);

}  // enviarMensajeContacto()

//-------------------------------------------------------------------------------------------
function doCrearNuevaLista(frmLista, txNombre)
{
  var msgError = "";

  txNombre.value = Trim(txNombre.value);

  if(txNombre.value.length == 0) {
    msgError += "Debe indicarse un nombre de lista.\n";
  }

  if(msgError == "") {
    frmLista.Accion.value = "nueva";
    frmLista.CodLista.value = "-1";
    frmLista.submit();
  }
  else
    alert(msgError);
    
}  // doCrearNuevaLista()

//-------------------------------------------------------------------------------------------
function doAccionLista(frmLista, CodLista, szAccion)
{
  var msgError = "";

  szAccion = Trim(szAccion);

  if(CodLista == 0) {
    msgError += "Debe indicarse un id de lista.\n";
  }

  if(szAccion.length == 0) {
    msgError += "Debe indicarse la acción.\n";
  }


  if(msgError == "") {
    var Seguir = true;

    if(szAccion.toLowerCase()== "borrar") {
      Seguir = confirm("¿De verdad quiere borrar esta lista?");
    }

    if(Seguir) {
      frmLista.Accion.value = szAccion;
      frmLista.CodLista.value = CodLista;
      frmLista.submit();
    }
  }
  else
    alert(msgError);

} // doAccionLista()

//-------------------------------------------------------------------------------------------
function enviarSolicitudAlta(miForm)
{
  var msgError = "";

  miForm.szEMail.value       = Trim(miForm.szEMail.value);
  miForm.szNombre.value      = Trim(miForm.szNombre.value);
  miForm.szNIF.value         = Trim(miForm.szNIF.value);
  miForm.szDireccion.value   = Trim(miForm.szDireccion.value);
  miForm.szPrsContacto.value = Trim(miForm.szPrsContacto.value);
  miForm.szTelefono.value    = Trim(miForm.szTelefono.value);
  miForm.szTelMovil.value    = Trim(miForm.szTelMovil.value);
  miForm.szUsuario.value     = Trim(miForm.szUsuario.value);
  miForm.szPass.value        = Trim(miForm.szPass.value);
  miForm.szPass2.value       = Trim(miForm.szPass2.value);
  
  if(!emailCheck(miForm.szEMail.value)) {
    msgError += "La dirección de correo no parece válida.\n";
  }
  if(miForm.szNombre.value.length == 0) {
    msgError += "Debe indicar el Nombre/Razón social.\n";
  }
  if(miForm.szNIF.value.length == 0) {
    msgError += "Debe indicar el NIF/CIF.\n";
  }
  if(miForm.szDireccion.value.length == 0) {
    msgError += "Debe indicar la Dirección.\n";
  }
  if(miForm.szPrsContacto.value.length == 0) {
    msgError += "Debe indicar una Persona de Contacto.\n";
  }
  if(miForm.szTelefono.value.length == 0) {
    msgError += "Debe indicar un teléfono.\n";
  }
  if(miForm.szUsuario.value.length == 0) {
    msgError += "Debe indicar el Usuario que solicita.\n";
  }
  if(miForm.szPass.value.length < 6) {
    msgError += "La contraseña debe tener al menos 6 caracteres.\n";
  }
  else
    if(miForm.szPass.value != miForm.szPass2.value) {
      msgError += "Las contraseñas especificadas no coinciden.\n";
    }
  
  if(msgError == "")
    miForm.submit();
  else
    alert(msgError);

}  // enviarSolicitudAlta()

//-------------------------------------------------------------------------------------------
function calcularPrecioAlta(frmAlta, aPrecios)
{
  var total1     = "";
  var numGrupos = 0;
  var campos    = frmAlta.elements;

  for(i=0; i<campos.length; i++) {
    szNombre = campos[i].name;
    if(szNombre.substr(0, 7) == "cb_grp_")
      if(campos[i].checked == true)
        numGrupos += 1;
  }

  numGrupos = (numGrupos >= aPrecios.length ? aPrecios.length-1 : numGrupos);

  total1 = aPrecios[numGrupos];

  frmAlta.total.value = total1;

}  // calcularPrecioAlta()

//-------------------------------------------------------------------------------------------
function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

//-------------------------------------------------------------------------------------------
function cargarContenido(nombreDiv, szPath)
{ //	alert('invocado por '+ nombreDiv);
//	d_nombreDiv=document.getElementById(nombreDiv);	
	new Ajax.Updater(nombreDiv, szPath, {evalScripts: true
    /*parameters: { text: $F('text') } */
  });
}
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
function cargarFormEnDIV(nombreDiv, szPath, formul)
{
/*	theParams=Form.serialize(document.getElementById(formul))
  	new Ajax.Updater(nombreDiv, szPath, {evalScripts: true, parameters:theParams*/
//	d_nombreDiv=document.getElementById(nombreDiv);	
	new Ajax.Updater(nombreDiv, szPath, {evalScripts: true, parameters:$(formul).serialize(true)
    /*parameters: { text: $F('text') } */
	  });
}

//-------------------------------------------------------------------------------------------

function resize_iframe(nombreiframe, nombrediv)
{
	var height=window.innerWidth;//Firefox
	if (document.body.clientHeight)
	{
		height=document.body.clientHeight;//IE
	}
 document.getElementById(nombreiframe).marginWidth="0px";
 document.getElementById(nombreiframe).marginHeight="0px";

	document.getElementById(nombreiframe).style.height=document.getElementById(nombrediv).style.height;
	//parseInt(height-document.getElementById('iflistapersonal').offsetTop-8)+"px";
}
function ocultarIframe(nombreIF, nombreDiv){
	document.getElementById(nombreIF).style.display="none";
	document.getElementById(nombreDiv).style.visibility='visible';
}
function mostrarIframe(nombreIF, nombreDiv){
//	resize_iframe();
	document.getElementById(nombreIF).style.display="block";
	document.getElementById(nombreDiv).style.visibility='hidden';
}

function loadcontent(nombreIF, nombreDiv){
	if (document.getElementById(nombreDiv)){
	var tempo=document.getElementById(nombreIF);
	document.getElementById(nombreDiv).innerHTML=tempo.contentDocument.body.innerHTML;}
}

/*-------------------------------------------------------------------------------------------
function cambiatamanho(IdGrande, IdInicial, IdTitulos, IdRedim){
	var newHeight=100;
	var oinicial=document.getElementById(IdInicial)
	var ginicial=document.getElementById(IdGrande)
	if (oinicial){
		var tempHeightExt=document.getElementById(IdGrande).offsetHeight;
		var tempHeightInt1=document.getElementById(IdInicial).offsetHeight;
	//these lines split the height value from the 'px' units
		newHeight=tempHeightExt - tempHeightInt1;
		document.getElementById(IdTitulos).style.height=newHeight+'px';
		newHeight=newHeight-40;
		document.getElementById(IdRedim).style.height=newHeight+'px';}
	else if (ginicial){
		var tempHeightExt=document.getElementById(IdGrande).offsetHeight;
		newHeight=tempHeightExt;
		document.getElementById(IdTitulos).style.height=newHeight+'px';
		newHeight=newHeight-20;
		document.getElementById(IdRedim).style.height=newHeight+'px';}
	};
	
	function cambiatamanho2(IdGExterior, IdExterno, IdScroll, divExteriorTotal){
		var newHeight=100;
		var ginicial=document.getElementById(IdGExterior);
			//if (newHeight < 267){newHeight=267}}
		if (document.getElementById(divExteriorTotal).offsetHeight < 730)
			{document.getElementById(divExteriorTotal).style.overflow="auto";
			document.getElementById(IdExterno).style.height='300px';
			document.getElementById(IdScroll).style.height='280px';
			
			}else 
			{document.getElementById(divExteriorTotal).style.overflow="none";
			var tempHeightExt=document.getElementById(IdGExterior).offsetHeight;
//			if (tempHeightExt > 552){
				newHeight=tempHeightExt-255;
				document.getElementById(IdExterno).style.height=newHeight+'px';
				newHeight=newHeight-20;			
				document.getElementById(IdScroll).style.height=newHeight+'px';
			}
		};	
-------------------------------------------------------------------------------------------*/
  function goToPagina(miForm, numPag)
  {
    miForm.Pag.value = numPag;
	miForm.submit();
  }
 /*------de EditarListasPersonales*/
function enviaAccionLista(miForm, szAccion, CodLonja, CodLonjaVer, CodProducto)
  {
    var enviar = true;

    switch(szAccion) {
      case "AddLonja":
        if(CodLonja>0)
          enviar = confirm("¿Quieres añadir todos los productos de la lonja seleccionada?");
        else {
          alert("Debes seleccionar primero una lonja");
          enviar = false;
        }
        break;

      case "SuprLonja":
        if(CodLonja>0)
          enviar = confirm("¿Quieres eliminar todos los productos de la lonja seleccionada?");
        else {
          alert("Debes seleccionar primero una lonja");
          enviar = false;
        }
        break;	

      case "AddProd":
        if(CodLonja>0)
          if(CodProducto > 0)
            enviar = true;
          else {
            alert("Debes seleccionar un producto");
            enviar = false;
          }
        else {
          alert("Debes seleccionar primero una lonja");
          enviar = false;
        }
        break;
    }

    if(enviar) {
      miForm.Accion.value      = szAccion;
      miForm.CodLonjaSel.value = CodLonja;
      if(typeof(CodProducto) != "undefined")
        miForm.CodProducto.value = CodProducto;
      if(typeof(CodLonjaVer) != "undefined")
        miForm.CodLonjaVer.value = CodLonjaVer;
      miForm.submit();
    }
  }
