

function insertImage (img){
     var text=img;
	 opener.document.editor.imagen_actual.value=text;
 	 opener.document.editor.imagen_aa.src=text;
  	 opener.document.editor.imagen_aa.style.display="block";
	 opener.document.getElementById('confirm').style.display='block';
     //window.parent.close();
     close();
}

/*
 * Muestra lac capa con el select cif en admin.php cuando se selecciona avatares.
 */
function mostrar_capa_cif (){

if (document.getElementById('section').value=='Avatares judiciales'){
  document.getElementById('block_cif').style.display='block';
  }
 else {
     document.getElementById('block_cif').style.display='none';
     }
}

/*
 * Valida addresses ip
 */
function validate_ip() {

newip=new String(document.getElementById('ip_deny').value);

var regexIP = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;

;

valid=newip.search(regexIP);

if (valid==0) document.getElementById('refuse_ip').submit();
else { alert ("La address IP no es valida");}
} 
/*
 * Oculta y despliega la capa pasada como parametro
 */
function ocultacapa(capa){
  var menu = document.getElementById(capa);
  if (menu!=null){
    menu.style.display = "none";
  }
}
function despliegacapa(capa){
  var menu = document.getElementById(capa);

  /* Soberana chapuza, hay que quitar este código y 
     hacer que recorra bien los elementos ul del documento
	 y excluir el que le pasamos por parámetro
  */
  switch (menu.id){
	  case "admin_general":
         document.getElementById('admin_sections').style.display="none";
         document.getElementById('admin_edicion').style.display="none";
         document.getElementById('admin_usuario').style.display="none";
         document.getElementById('admin_copia').style.display="none";
	  break;
	  case "admin_sections":
         document.getElementById('admin_general').style.display="none";
         document.getElementById('admin_edicion').style.display="none";
         document.getElementById('admin_usuario').style.display="none";
         document.getElementById('admin_copia').style.display="none";
	  break;
	  case "admin_edicion":
         document.getElementById('admin_general').style.display="none";
         document.getElementById('admin_sections').style.display="none";
         document.getElementById('admin_usuario').style.display="none";
         document.getElementById('admin_copia').style.display="none";
	  break;
	  case "admin_usuario":
         document.getElementById('admin_general').style.display="none";
         document.getElementById('admin_sections').style.display="none";
         document.getElementById('admin_edicion').style.display="none";
         document.getElementById('admin_copia').style.display="none";
	  break;
	  case "admin_copia":
         document.getElementById('admin_general').style.display="none";
         document.getElementById('admin_sections').style.display="none";
         document.getElementById('admin_edicion').style.display="none";
         document.getElementById('admin_usuario').style.display="none";
	  break;
  }
  
  if(menu.style.display == "none" || menu.style.diplay==""){
      menu.style.display = "block";
    }
    else{
      menu.style.display = "none";
    }
}


/* Pop up */
function popup(pagina){
 window.open (pagina,"Historial de pedido", 'width=450px, scrollbars=1,top=50%; left=50%');
}

/* Pop up */
function popup_manual(pagina){
  window.open (pagina,"manual", 'width=480px, toolbar=yes, scrollbars=1,top=50%; left=50%');
}
/* Pop up */
function popup_visor(pagina){
  window.open (pagina,"visor", 'width=510px, toolbar=no, scrollbars=1,top=50%; left=50%');
}

/* Pop up */
function popup_files(pagina){
  window.open (pagina,"manual", 'width=800px,height=600px,toolbar=yes, scrollbars=1,top=1%; left=1%');
}



/*
 Forma no intrusiva de llamar al pop up
<!--<a href="pagina.html" onclick="popup(this.href);return false">Lorem</a>-->

*/

// Vuelve a la página anterior del historial.
function atras (){
  window.history.back();
}

// Imprimir una página
function imprimirPagina() {
  if (window.print){
    window.print();

 }
  else {
      alert("Su navegador no le permite sort imprimir\n" +
      "Imprima desde el menú Files->Imprimir, o pulse CTRL+P simultaneamente.\n"+
      "Si sigue sin funcionar actualice su navegador\n");
      }
}
/**
  * Valida los datos de los forms en el cliente.
  *
  * Tambíen son validados en el servidor
  * en el archivo pedido.cliente.hpp
  */
function validate_datos_pedido (){

  if (document.getElementById('name').value=='' ||
      document.getElementById('lastname').value=='' ||
      document.getElementById('address').value=='' ||
      document.getElementById('cp').value=='' ||
      document.getElementById('city').value=='' ||
      document.getElementById('province').value=='' ||
      document.getElementById('country').value=='' ||
      document.getElementById('phone').value=='' ||
      document.getElementById('nif').value=='') {

  alert  (
   "Debe rellenar al menos los campos de la dirección de facturación\n"+
   "Nombre: "+document.getElementById('name').value+"\n"+
   "Apellidos: "+document.getElementById('lastname').value+"\n"+
   "Dirección: "+document.getElementById('address').value+"\n"+
   "Código Postal: "+document.getElementById('cp').value+"\n"+
   "Ciudad: "+document.getElementById('city').value+"\n"+
   "Provincia: "+document.getElementById('province').value+"\n"+
   "País: "+document.getElementById('country').value+"\n"+
   "Teléfono: "+document.getElementById('phone').value+"\n"+
   "CIF/NIF: "+document.getElementById('nif').value+"\n"
   );
    window.location.href='pedido.php?error=true'
   }
   else {
    window.location.href='pedido.cliente.php';
   }

}
//
function check_all(field) {

  for (i = 0; i < field.length; i++){ 
    if (field[i].checked==false){
      field[i].checked = true;
    }
    else {
     field[i].checked = false;
    }
  }
}

// Borra el boletín
function confirmar_delete_newsletter ()
{
   resultado=confirm ("¿Quiere delete el boletín?");
              if (resultado==false){
                 window.history.back();
              }
 }


// Valida la búsqueda del pedido.
function validate_search_order(){
	
	// Xor Operation. Only returns true if both terms are equal. Beautiful, isn't it?
	if ( document.getElementById('year_from').value=='' ^ document.getElementById('year_still').value==''){
  		    alert ("Si rellena una fecha debe rellenar todos los campos");
	}
	else {
         document.getElementById('search_order').submit();
    }

/*
var campos_no_rellenos=0;
if ( document.getElementById('year_from').value=='' ) campos_no_rellenos++;
if ( document.getElementById('month_from').value=='' ) campos_no_rellenos++;
if ( document.getElementById('day_from').value=='' ) campos_no_rellenos++;

if ( document.getElementById('year_still').value=='' ) campos_no_rellenos++;
if ( document.getElementById('month_still').value=='' ) campos_no_rellenos++;
if ( document.getElementById('day_still').value=='' ) campos_no_rellenos++;


// Si no es correcto mostramos cartel de advertencia.
if ( campos_no_rellenos>=1 && campos_no_rellenos <6) {
        alert ("Si rellena una fecha debe rellenar todos los campos");
   }
else
  {
   document.getElementById('search_order').submit();
  }
  */
}



// El producto seleccionado para añadir ya existe.
function producto_existe(){
  alert ("El producto seleccionado para añadir ya existe")
}

function change_brand(marca){
      if (marca!="-- Seleccione marca --")

      document.getElementById('marca').value=marca;
}
function cambiar_subcategorie(subcategorie){

       if (subcategorie!="-- Seleccione subcategorie --")
        document.getElementById('subcategorie').value=subcategorie;
}

/**
 *  Javascript para la edición del text.
 *  David Ramón Yanes Fariña
 *  Falta adaptarlo para opera, konqueror.
 *  Funciona correctamente en Iexplorer 6.0, y navegadores con el motor *     Gecko.(mozilla,firefox,netscape).
 *
 */
// Captura la selección, y añade las etiquetas.
 function getSel(ini_etiqueta,fin_etiquita)
{
    // Si mozilla o firefox.
   if (window.getSelection)
      {
                editor=document.getElementById('editor');

                ini=editor.message.selectionStart;
                fin=editor.message.selectionEnd;
                pretext=editor.message.value.substring (0,ini);
                addtext=ini_etiqueta+editor.message.value.substring (ini,fin)+fin_etiqueta;
                fintext=editor.message.value.substring (fin, editor.message.value.length);

                final_text=pretext+addtext+fintext;
                editor.message.value='';
                editor.message.value=final_text;
                return final_text;
        }
    // If ¿Que navegador sería este?
    else if (document.getSelection){
                editor=document.getElementById('editor');

                if (fin_etiqueta.indexOf ('[/fr]')>=0 )
                    meter (fin_etiqueta);
                else {
                   final_text=prompt ("Introduzca text");
                   meter (ini_etiqueta+final_text+fin_etiqueta);
                }
      return 1;
   }
    // Si es explorer 6.0
    else if (document.selection)
      {
      // Damos el foco al editor.
       document.editor.message.focus();

      //Capturamos la seleccion hecha por el usuario.
      sel=document.selection.createRange().text;
      addtext=ini_etiqueta+sel+fin_etiqueta;
      meter(addtext);
	  return 1;
     }
        else return 0;
}

function delete_todo (){
  // Si es mozilla
  if (window.getSelection){
     editor=document.getElementById('editor');
     editor.message.value='';
     
  }
  
  // Si es ie
  else if (document.selection){
             document.editor.message.value='';
   }

}

// ----------------------------------------------------------------------------
// Este genial Script fue desarrollado por Tukzone, SirMatrix y Unknow,
// all users del Foro.. Gracias a ellos por su colaboración

  function storeCaret(text) {
   if (text.createTextRange) {
    text.caretPos = document.selection.createRange().duplicate();
   }
  }

  function meter(text) {

   var postopic = document.editor.message;

   if (postopic.createTextRange && postopic.caretPos) {
      var caretPos = postopic.caretPos;

      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?

     text + ' ' : text;
   }
   else postopic.value += text;

   postopic.focus(caretPos)
  }

  function codigo(accion) {
   switch(accion) {
    case "url":
     url=prompt ('Introduzca dirección','http://');
     ini_etiqueta='[a href=\"'+url+'\"]';
     fin_etiqueta='[/a]'
      break;
     case "bold":
     ini_etiqueta='[b]';
     fin_etiqueta='[/b]'
      break;
    case "italics":
     ini_etiqueta='[i]';
     fin_etiqueta='[/i]'
      break;
    case "quote":
     ini_etiqueta='[quote]';
     fin_etiqueta='[/quote]';
     break;
    case "underlayed":
     ini_etiqueta='[u]';
     fin_etiqueta='[/u]';
     break;
    case "fin_summary":
     ini_etiqueta='';
     fin_etiqueta='[/fr]';
     break;
    default:
     break;
   }
   getSel(ini_etiqueta,fin_etiqueta);
  }
// Contador progresivo. Account la quanty de text que hay en el campo.
  function textCounter(field, countfield, maxlimit) {
   if (field.value.length > maxlimit)
    field.value = field.value.substring(0, maxlimit);
   else
    countfield.value = field.value.length;
  }

// Contador regresivo. Account la quanty de text que hay en el campo la cual es restada
// de max limit.
  function reverseTextCounter(field, countfield, maxlimit) {
   if (field.value.length > maxlimit)
    field.value = field.value.substring(0, maxlimit);
   else
    countfield.value = maxlimit - field.value.length;
   }
// Ocultar email.
function MailLink (usuario, dominio, tld, texto) {
 //codifica los caracteres mas significativos
 var arroba = '@'
 var punto = '.'

 //utiliza variables para ocultar las palabras clave
 var etiqueta = 'ma' + '' + 'il'
 var dospuntos = 'to:'
 var localizador = usuario
 localizador = localizador + arroba + dominio
 localizador = localizador + punto + tld

 //escribe en enlace
 document.write('<a href="' + etiqueta + dospuntos + localizador + '">'+ localizador + '</a>')
}   


/**
 * Comprueba el Cif 
 */
function comprobarcif(cif){
	mal=false;
letras="ABCDEFGHKLMNPQS"
caracteres=[];

for(a=0;a<cif.length;a++){
caracteres[a]=cif.charAt(a);
}
if(letras.indexOf(caracteres[0])==-1){
esto=cif;
validar(esto);
return false;
}
resultadoImpares=0;
for(a=1;a<8;a=a+2){
numero=caracteres[a]*2;
numero=parseInt(numero/10)+numero%10;
resultadoImpares+=numero
}

resultadoImpares=parseInt(resultadoImpares/10)+resultadoImpares%10;

numeroPar=0;
for(a=2;a<8;a=a+2){
numeroPar+=parseInt(caracteres[a]);
}
total=resultadoImpares+numeroPar;
total=11-(total%10)+1;
if(total!=caracteres[8]){mal=true;}
if(mal){
pepe=alert("Parece ser que el C.I.F. no es correcto.\nPor favor corrijalo.");
document.introducir.CIF.focus();return false
}
return true;
}
/*******************************
 Validación del nif. Por Carlitos. [email]carlosbernad@teleline.es[/email]
 Si usas este script, deja intactas estas líneas (créditos). Vale?
 También te agradecería un e-mail con tus comentarios.
*******************************/
function validate_nif(abc)
{
dni=abc.substring(0,abc.length-1)
let=abc.charAt(abc.length-1)
if (!isNaN(let))
 {
  alert('Introduzca el nº del DNI seguido de la letra, sin guiones ni espacios.')
  documento.registro.nif.focus()
  return false
 }
else
 {
  cadena="TRWAGMYFPDXBNJZSQVHLCKET"
  posicion = dni % 23
  letra = cadena.substring(posicion,posicion+1)
  if (letra!=let.toUpperCase())
   {
    alert("Nif no válido");
    documento.registro.nif.focus();
    return false
   }
 }
return true;
}

/*
  Comprueba si el email pasado como parámetro es válido.
*/
function validate_email(email){
	
	//expresion regular
        var regex=/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/
        
        //comentar la siguiente linea si no se desea que aparezca el alert()
		
		if (regex.test(email)){
			return true;
		}
		else {
			alert ('Introduzca un email válido');
            documento.registro.email.focus();
            window.scrollBy(0,-30);															 
           return false;
		}
		
    
}

/**
 * Comprueba si el email pasado como parámetro es válido.
 */
function validate_phone(phone){
    var er_phone = /(^([0-9]{9,9})|^)$/				//9 numeros o cadena vacia
    //comprueba campo codigo postal
    if(er_phone.test(phone.value) && phone.value!='') {
        return true;
    }
    else {
        alert('El número de teléfono debe estar compuesto de 9 cifras.');
        getFormToValidate().phone.focus();
        window.scrollBy(0,-30);
        return false;
    }
}
/**
 * Función que consigue el ide del formulario a validar
 * Esta función es imprescidible que esté
 * si no no funciona la validación correctamente.
 */
function getFormToValidate () {
    var frms = document.getElementsByTagName('form');
    for (var i=0; i<frms.length; i++) {
        if (frms[i].className.indexOf('validate') != -1) {
            return (frms[i]);
        }
    }
}

// Script Source: CodeLifter.com
// Copyright 2003
// Do not remove this notice.

// SETUPS:
// ===============================

// Set the horizontal and vertical position for the popup

var PositionX = 100;
var PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)

var defaultWidth  = 550;
var defaultHeight = 367;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows

var AutoClose = true;

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;
function popImage(imageURL,imageTitle){
if (isNN){imgWin=window.open('about:blank','',optNN);}
if (isIE){imgWin=window.open('about:blank','',optIE);}
with (imgWin.document){
writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
writeln('width=100-(document.body.clientWidth-document.images[0].width);');
writeln('height=100-(document.body.clientHeight-document.images[0].height);');
writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
writeln('window.innerWidth=document.images["George"].width;');writeln('window.innerHeight=document.images["George"].height;}}');
writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
else writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
writeln('<img name="George" src='+imageURL+' style="display:block"></body></html>');
close();		
}}

