var nav4 = window.Event ? true : false;
function acceptNum(evt){
// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57
var key = nav4 ? evt.which : evt.keyCode;
return (key <= 13 || (key >= 48 && key <= 57));
}


function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		}
		else
		return true;
}  // fin handleEnter


function checkEmail(myForm) {
if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))
{
return (true)
}

alert("Dirección de E-mail inválida.")
myForm.email.focus()
return (false)
}


function borra() {
return confirm("¿Confirma el borrado del formulario?");
}

function Validar(carac){

/* Funcion que valida los datos ingresados al formulario previo a su envio   */

var ok=true;
var foco=0; //indica que si hay error, luego del mensaje mande el foco a la password

if (window.document.form1.usuario.value.length == 0)
{
	ok=false;
 var mensaje="Ingrese usuario (o E-mail)";
	foco=1; //para que mande el foco al nombre
}

if (window.document.form1.clave.value.length == 0)
{
	if(ok) //se ingreso usuario pero no contraseña
		{
			ok=false;
			mensaje="Ingrese su contraseña";
		}
	else // no ingreso ni usuario ni clave
		{
			mensaje = mensaje + ' y contraseña';

		}
} // fin if ... == 0


else // ingreso una clave
	{


		if(window.document.form1.clave.value.length < carac) // clave mas corta que lo requerido
		{
			if(ok) //se ingreso usuario y contraseña corta
			{
				ok=false;
				mensaje="La clave debe tener " + carac + " caracteres";

			}
			else // no ingreso usuario e ingreso clave corta
				mensaje = mensaje + ' y la clave debe tener ' + carac + ' caracteres';
		}
		else // la clave esta bien
		{
			if(ok) //se ingreso usuario y contraseña correcta
				window.document.form1.submit();
		}
	} // fin else ingreso una clave

if(!ok) //disparamos el mensaje de error si en algun momento se cambio el ok a false
	{
		alert(mensaje);
		if(foco==1) // el nombre esta mal
			window.document.form1.usuario.focus();
		else // lo que esta mal es solo la clave
			window.document.form1.clave.focus();
	}

}	// fin funcion Validar



//******

function VerificaCheck(fm)
// verifica si hay al menos algun checkbox tildado. En tal caso envia el formulario

{

	var numelements= fm.elements.length

	almenosuno=false
	for (i=0;i<numelements;i++)
	{
		if (fm.elements[i].checked)
			{
				almenosuno=true;
				break;
			}

	}
 	if (almenosuno)
	{
		if (confirm('¿Confirma el borrado?'))
				fm.submit()
	}
	else
		alert('Seleccione al menos una IP')

} // fin VerificaCheck

////////



function ValidarBusq(carac){

if (window.document.buscador.termino.value.length < carac)
{
	alert('Ingrese al menos '+ carac +' caracteres');
	window.document.buscador.termino.focus();
}
else
	if(window.document.buscador.termino.value == "Ingrese palabra a buscar" )
		{
			alert(window.document.buscador.termino.value) ;
			window.document.buscador.termino.focus();
		}
		else
		window.document.buscador.submit();
}

///
function cargaCat(op){ // recarga la pagina con la opcion de la categoria seleccionada

	cat = document.getElementById('categ').value ;
	location.href = "index.php?op="+op+"&cat="+cat;

}

///

function cargaSubcat(op, cat){ // recarga la pagina con la opcion de la subcategoria seleccionada

	subcat = document.getElementById('subcateg').value ;
	location.href = "index.php?op="+op+"&cat="+cat+"&subCat="+subcat;

}
////////

function cargaCatSitio(idSubsec){ // recarga la pagina con la opcion de la categoria seleccionada

	cat = document.getElementById('categ').value ;
	location.href = "Servicios.php?subsec="+idSubsec+"&cat="+cat;

}

///

function cargaSubcatSitio(idSubsec, cat){ // recarga la pagina con la opcion de la subcategoria seleccionada

	subcat = document.getElementById('subcateg').value ;
	location.href = "Servicios.php?subsec="+idSubsec+"&cat="+cat+"&subCat="+subcat;

}


////

function formCheck_altaUser(formobj){

	//1) Enter name of mandatory fields
	var fieldRequired = Array("nombre", "usuario", "clave", "clave2");
	//2) Enter field description to appear in the dialog box
	var fieldDescription = Array("Nombre","Usuario", "Clave", "Reingreso de Clave");
	//3) Enter dialog message
	var alertMsg = "Por favor, complete los siguientes campos:\n";

	var listo=false;

	var l_Msg = alertMsg.length;

	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == 0 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

if (alertMsg.length == l_Msg){
	//if(2+2 == 5){
      if(verificaClaves(formobj)){
         if(formobj.name=='alta')
     		 mensaje = '¿Confirma el alta del usuario?';
         else
      		mensaje = '¿Confirma la modificacion de los datos del usuario?'

  	  listo=confirm(mensaje );
	  if (listo)
			 return true;
     else return false

      }else{

      	 return false;
      }
 }else{
  alert(alertMsg);
  return false;
 }



}// fin formCheckaltaUser


function verificaClaves(formobj){//
  if(formobj.clave.value != formobj.clave2.value){
    alert('Las contraseñas ingresadas no coinciden');
    return false;
  }else{
      if(formobj.clave.value.length < 4 || formobj.clave.value.length > 12){
        alert('La contraseña debe tener entre 4 y 12 caracteres');
        return false;
      }else
          return true
   }
}// fin verificaClaves


function validaReg(formobj){
 //1) Enter name of mandatory fields
 var fieldRequired = Array("nombre", "apellido", "email", "telefono", "calle_y_num", "localidad", "clave", "clave2");
 //2) Enter field description to appear in the dialog box
 var fieldDescription = Array("Nombre", "Apellido", "E-mail","Teléfono/s", "Calle y Número", "Localidad", "Clave", "Confirmación de Clave");
 //3) Enter dialog message
 var alertMsg = "Por favor, complete los siguientes campos:\n";

 var listo=false;

 var l_Msg = alertMsg.length;
 for (var i = 0; i < fieldRequired.length; i++){
  var obj = formobj.elements[fieldRequired[i]];
  if (obj){
   switch(obj.type){
   case "select-one":
    if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
    break;
   case "select-multiple":
    if (obj.selectedIndex == -1){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
    break;
   case "text":
   case "textarea":
    if (obj.value == "" || obj.value == null){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
    break;
   default:
    if (obj.value == "" || obj.value == null){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
   }
  }
 }

 if (alertMsg.length == l_Msg){
 	if(checkEmail(formobj)){

 			if(verificaClaves(formobj)){

      	listo=confirm('¿Confirma el envío del formulario?' );

	   if (listo)
		  	 formobj.submit();
 			}
 }


}else
    alert(alertMsg);

}// fin validaReg();
///////////
function borrar(id, titulo, seccion) {
    confirma=confirm('¿Confirmas el borrado de la nota "'+ titulo +'"?')
    if(confirma){
      location.href = 'index.php?op=cont&sec='+ seccion +'&borra='+id
    }
  }// fin borrar


///////////

function borrarSec(Nombre , id) {
    confirma=confirm('¿Confirma el borrado de la Sección "'+ Nombre +'"?\n \nATENCION:\nSe borrarán todas las subsecciones y las notas de esa sección')
    if(confirma){
      location.href = 'borraSec.php?id='+id
    }
  }// fin borrarSec

  //////////////

  function borrarSecFotogaleria(Nombre , id) {
    confirma=confirm('¿Confirma el borrado de la Sección "'+ Nombre +'"?\n \nATENCION:\nSe borrarán todas las fotogalerías de esta sección')
    if(confirma){
      location.href = 'borraSecFg.php?id='+id
    }
  }// fin borrar SecFotogaleria

/////////

function borrarSubsec(Nombre , id) {
    confirma=confirm('¿Confirma el borrado de la Subsección "'+ Nombre +'"?\n \nATENCION:\nSe borrarán todas las notas de esa Subsección')
    if(confirma){
      location.href = 'borraSubsec.php?id='+id
    }
  }// fin borrarSubSec

//////////////

function borrarNovedad(id) {
    confirma=confirm('¿Confirma el borrado de la Novedad '+ id +'?')
    if(confirma){
      location.href = 'index.php?op=nov&borranovedad='+ id
    }
  }// fin borrarSubSec

////////////
function borrarFg(id) {
    confirma=confirm('¿Confirma el borrado de la Fotogaleria?')
    if(confirma){
      location.href = 'borrar.php?id='+ id +'&op=fotogaleria&objeto=fotogaleria'
    }
  }// fin borrarSubSec

////////////

function borrarCliente(id, Nombre, tipo) {

   if(tipo) {
      cli = 'del canal de ventas'
   }else{
      cli = ' de la empresa'
   }
    confirma=confirm('¿Confirma el borrado '+cli+ '"'+ Nombre +'"?')
    if(confirma){
      location.href = 'index.php?op=clientes&tipo='+tipo+'&accion=borrar&id='+id

     }
  }// fin borrarCliente

//////////////


function borrarArticulo(cat, subcat , id) {
    confirma=confirm('¿Confirma el borrado del artículo?')
    if(confirma){
      location.href = 'accionArticulos.php?accion=borrarArt&id='+id+'&cat='+cat+'&subCat='+subcat
    }
  }// fin borrarCliente


function borrarMiembro(id, Nombre) {
    confirma=confirm('¿Confirma el borrado de datos de "'+ Nombre +'"?')
    if(confirma){
      location.href = 'index.php?op=staff&borraMiembro='+id
    }
  }// fin borrarCia


//////////////



function panelUpload(id , dest){// abre la ventana de upload imagenes para fotogalerias (dest = 1) o articulos (dest = 2)

 if(dest == 1)
  var ficha = window.open("panelImgFotoGal.php?id="+id , 'formU', 'menubar=no, location=no, width=610 , height=645, top=46 , left=175, scrollbars=yes');
 else if(dest == 2)
   var ficha = window.open("panelImgArt.php?id="+id , 'formU', 'menubar=no, location=no, width=610 , height=645, top=46 , left=175, scrollbars=yes');
   ficha.focus();
} // fin panelUpload()

////////



//////////
function panelUploadIm(id,tipo,ancho,carpeta){// abre la ventana de upload de archivos: pdf o jpg chico

  window.open("subeImagen.php?idArt="+id+"&tipo="+tipo+"&ancho="+ancho+"&carpeta="+carpeta, 'formU', 'menubar=no, location=yes, width=697 , height=600, top=16 , left=165, scrollbars=yes');

} // fin panelUploadIm()

//////////
function panelUploadLogo(id){// abre la ventana de upload de archivos: pdf o jpg chico

  window.open("subeLogo.php?idCia="+id , 'formU', 'menubar=no, location=yes, width=630 , height=599, top=16 , left=165, scrollbars=yes');

} // fin panelUploadLogo()

////////////

function panelUploadLogo2(id){// abre la ventana de upload de archivos: pdf o jpg chico

  window.open("subeLogo2.php?idCli="+id , 'formU', 'menubar=no, location=yes, width=630 , height=599, top=16 , left=165, scrollbars=yes');

} // fin panelUploadLogo()



///////
function posicionar(ancho,margenTop){
x = (screen.width - ancho) / 2;
moveTo(x, margenTop);
}

////////

function salir(){

   if(confirm('Confirma la salida del Panel de Administración')){
            location.href='salir.php'

   }else
      return 0;

} // fin salir();

//////////////
function registro(){// abre la ventana de registro de nuevo producto

  window.open("admin/nuevo_prod.php", 'form', 'menubar=no, scrollbars=yes, width=568, height=605, top=4 , left=133');

} // fin registro()

function abreFichaCli(idCli , tipo){
   ficha1Cli=window.open('fichaCliente.php?tipo=1&idCliente='+idCli,'cliente','status=no, modal=yes, scrollbars=yes, location=no, width=549, height=539')
   ficha1Cli.focus()
}



function abreFichaEmpresa(idCli , tipo){
   ficha1Empr=window.open('fichaEmpresa.php?tipo=0&idCliente='+idCli,'empresa','status=no, modal=yes, scrollbars=yes, location=no, width=549, height=539')
   ficha1Empr.focus()
}


////////
function abreFichaArt(idArt){
   ficha1Art=window.open('fichaArt.php?id='+idArt,'art','status=no, modal=yes, scrollbars=yes, location=no, width=638, height=389')
   ficha1Art.focus()
}////////

function abreFichaImagenes(idArt){
   ficha2Art=window.open('fichaImagenes.php?id='+idArt,'fotos','status=no, modal=yes, scrollbars=yes, location=no, width=714, height=559')
   ficha2Art.focus()
}


////////

function validaFechaSinHora(Dia, Mes, Ano){
// no acepta hora y recibe los tres valores por separado
//alert(Dia)
// Valido el año
if (isNaN(Ano) || Ano.length != 4 || parseFloat(Ano)<1900){
        alert('Año inválido')
return false
}
// Valido el Mes
if (isNaN(Mes) || parseFloat(Mes)>12){
alert('Mes inválido')
return false
}
// Valido el Dia
if (isNaN(Dia) || parseInt(Dia, 10)>31){
alert('Día inválido')
return false
}
if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2) {
if (Mes==2 && Dia > 28 || Dia>30) {
   if(Dia == 29 && Ano % 4 == 0) return true;
alert('Día inválido')
return false
}
}
 // validamos que la fecha ingresada no sea posterior a la actual

var mydate=new Date();
var year=mydate.getYear();
if (year < 1000)
year+=1900;
var day=mydate.getDay();
var month=mydate.getMonth()+1;
if (month<10)
   month="0"+month;
var daym=mydate.getDate();
if (daym<10)
   daym="0"+daym;
//alert(year+"-"+month+"-"+daym+" 23:59:00")
hoy = year+"-"+month+"-"+daym+" 23:59:00"
if (Mes<10)
   Mes="0"+Mes;

if (Dia<10)
   Dia="0"+Dia;

         Fecha = Ano+"-"+Mes+"-"+Dia+" 23:59:00"

//alert(Fecha)


if(Fecha > hoy){
//*alert(Fecha)
alert('La fecha no puede ser posterior a la actual')
return false
}

return true;
}


////////

function buscar(loQue){

   var termino = document.getElementById('busq').value
//   alert(termino)

   location.href = 'index.php?op='+loQue+'&termino='+termino

}
//////////////

function validaFormDatosNodo(formobj){
 //1) Enter name of mandatory fields
 var fieldRequired = Array("nombre");
 //2) Enter field description to appear in the dialog box
 var fieldDescription = Array("Nombre");
 //3) Enter dialog message
 var alertMsg = "Por favor, complete \n";

 var listo=false;

 var l_Msg = alertMsg.length;
 for (var i = 0; i < fieldRequired.length; i++){
  var obj = formobj.elements[fieldRequired[i]];
  if (obj){
   switch(obj.type){
   case "text":
   case "textarea":
    if (obj.value == "" || obj.value == null){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
    break;
   default:
    if (obj.value == "" || obj.value == null){
     alertMsg += " - " + fieldDescription[i] + "\n";
    }
   }
  }
 }

 if (alertMsg.length == l_Msg){
		  	 formobj.submit();
 			}
else
    alert(alertMsg);

}// fin validaFormDatosNodo();

//////////

function borrarNota(nombre , id){
	confirma=confirm('Confirma el borrado de la nota \n "'+ nombre +'"? ')
    if(confirma){
      location.href = 'borraNota.php?id='+id
    }

 }// fin borrarNodo()


 //////


   function borrarPDF(idNodo, idPadre){

      if(confirm('¿Confirma el borrado del archivo adjunto?'))
         location.href = "borrarPDF.php?nodo="+idNodo+'&padre='+idPadre
   }
//////////////////////////


function calcular(){


   var subtotal_P = 0
   var subtotal_S = 0
   var totalGeneral = 0

   for(i=2 ; i < document.presup.elements.length; i++){


      valor = parseFloat(document.presup.elements[i].value)
//      alert(valor)
     if(!isNaN(valor)){
      if(i % 2) {

         subtotal_S = subtotal_S + valor

      }else{
         subtotal_P = subtotal_P + valor
      }

      totalGeneral = totalGeneral + valor
   }
   }
//alert(subtotal_S)
document.getElementById('subtotalP').innerHTML = '<b>' + subtotal_P + '</b>&nbsp;&nbsp;&nbsp;';
document.getElementById('subtotalS').innerHTML = '<b>' + subtotal_S + '</b>&nbsp;&nbsp;&nbsp;';
document.getElementById('total').innerHTML = '<b>u$s ' + totalGeneral + '</b>&nbsp;&nbsp;&nbsp;';
}

////////////////

function calcularConfig(){

  var totalGeneral = 333
  var valorSol = parseFloat(document.getElementById('ValSolucion').value)
  var valorServ = parseFloat(document.getElementById('ValServicio').value)



//  alert(valorSol) ;
//  alert(valorServ)

  if (!isNaN(valorSol)  && !isNaN(valorServ)   ) {
      totalGeneral = valorSol + valorServ
   }else{
      alert('Ingrese un valor numérico')
      return
   }
//alert(totalGeneral)

   document.getElementById('total').innerHTML = '<b>u$s ' + totalGeneral + '</b>&nbsp;&nbsp;&nbsp;';
}


////////////////



function restablecer(){

   if(confirm('¿Cancela los cambios introducidos?')){

      document.presup.reset()
      calcular()

   }

}

// confirma el submit de presupuesto

function confirmarSubmit(){

      if(confirm('¿Confirma la carga de datos?')){
         document.presup.submit()
      }
}
/////////////////////



function enviarPresupuesto(id , origen){

   if(confirm('¿Confirma el envío del presupuesto al cliente?')){

      location.href = 'enviaPresupuesto.php?id='+id+'&origen='+origen

   }

}
///////////

function abrirDatosCliente(){

   var w

   w=window.open("datosClienteFinal.php?origen=carrito" , "ventana1" , "width=653,height=586,scrollbars=yes, location=NO, menubar=NO, status=NO, toolbar=NO, resizable=NO, top=23, left=77");

 w.focus()

}

////////

function validarFormCateg(nombreForm){

   idNombreES = 'nombreES'+nombreForm

   if(document.getElementById(idNombreES).value.length == 0){
      alert('Ingrese el nombre de la categoría')
      document.getElementById(idNombreES).focus()
      return false
   }

   else
      document.getElementById(nombreForm).submit();

}
///////////


function validarFormSubCateg(nombreForm){

   var idNombre = 'nombre'+nombreForm
   var mensaje = '';
   var foco = '';

   if(document.getElementById('categEdit').value == 0){
      mensaje = "\n - Categoría"

    }

   if(document.getElementById(idNombre).value.length == 0){
      mensaje = mensaje + "\n - Nombre"
      foco = idNombre;

   }

   if(mensaje != ''){

        alert ("Ingrese los siguientes campos: \n ----------------------------------------------  " + mensaje);
        if (foco != '') document.getElementById(foco).focus()
        return false

   }else  {
     if(confirm('¿Confirma la carga de datos?')) {
      document.getElementById(nombreForm).submit();
      return true
     }
     else return false
    }
}

/////////////////

function confirmaBorrado(nombre, id){


   if(confirm('¿Confirma el borrado de la categoría "'+nombre+'"?'))
   location.href="index.php?op=categorias&id="+id+"&accion=borrar"

}

/////////

function confirmaBorradoSubcat(nombre, id, cat){


   if(confirm('¿Confirma el borrado de la Subcategoría "'+nombre+'"? \n\n * * * * * * * *  A T E N C I O N  * * * * * * * *  \n\n Se borrarán todos los articulos de esta subcategoría \n ' ))
   location.href="accionSubcat.php?subcategorias&id="+id+"&cat="+cat+"&accion=borrarSubCat"


}

/////////

function cargaListaSubcat(){

    var idCat = document.getElementById('categ').value ;

    location.href = 'index.php?op=subcategorias&idCat='+idCat

}
/////////

    function habilitarBusquedaOld(cant){

	     if(document.getElementById('busqueda').value.length >= cant){

		      document.getElementById('botonBuscar').style.visibility = 'visible'

		   }else{

  		      document.getElementById('botonBuscar').style.visibility = 'hidden'

		   }
		}

////////////

function habilitarBusqueda(cant , e) {

  var textBusq = document.getElementById('busqueda').value
   //alert (e);
  var key;
        var keychar;
    if(window.event || !e.which) // IE
    {
       key = e.keyCode; // para IE
    }
    else if(e) // netscape
    {
        key = e.which;
    }
    if(textBusq.length >= cant) {

        document.getElementById('botonBuscar').style.visibility = 'visible'

        if (key==13) buscar();


  }else{
        if (key == 13) alert('Ingrese al menos '+cant+' caracteres para la búsqueda')
		document.getElementById('botonBuscar').style.visibility = 'hidden'
  	}
  
}

////////////

function buscar(){

		   var termino = document.getElementById('busqueda').value

		   location.href="resultado_de_busqueda.php?busq="+termino


		}

