window.addEvent('domready',function(){
  //configuramos los botones dle navegador
  var navButtons = $$('.navButton');

  navButtons.addEvent('mouseover',function(){
    start = this.src.length - 6;
    this.src = this.src.substring(0,start)+"dn.png";
  });
  navButtons.addEvent('mouseout',function(){
    start = this.src.length - 6;
    if(this.state!='on'){
        this.src = this.src.substring(0,start)+"up.png";
    }
  });

  //tratamos los campos
  var inputs = $$('input.texto');
  var inputsN = $$('input.nulo');

  inputs.addEvent('focus',function(){
    if(this.value==this.name){
      this.value='';
    }
  });
  inputs.addEvent('blur',function(){
    if(this.value==''){
      this.value=this.name;
    }
  });

  inputsN.addEvent('focus',function(){
    if(this.value==this.name){
      if(this.name == 'website'){
        this.value = 'http://';
      }else {
        this.value='';
      }
    }
  });
  inputsN.addEvent('blur',function(){
    if(this.value=='' || this.value=='http://'){
      this.value=this.name;
    }
  });


  //----------------------------------------------------------------
  //precarga de imagenes
  var imagenes = new Array();
  imagenes[0] = 'images/botones/anunciosClasificados_dn.png';
  imagenes[1] = 'images/botones/anunciate_dn.png';
  imagenes[2] = 'images/botones/directorio_dn.png';
  imagenes[3] = 'images/botones/galeria_dn.png';
  imagenes[4] = 'images/botones/inicio_dn.png';
  imagenes[5] = 'images/botones/promociones_dn.png';
  imagenes[6] = 'images/buscador/btnBuscarSG_dn.png';
  imagenes[7] = 'images/buscador/clasificadosSG2_dn.png';
  imagenes[8] = 'images/buscador/directorioSG2_dn.png';
  imagenes[9] = 'images/fondoBtnSendOver.gif';
  imagenes[10] = 'images/popular/pestana_2.gif';
  imagenes[11] = 'images/ajax-loader.gif';
  imagenes[12] = 'images/ajax-loader2.gif';

  var images = new Array();

  cargarImagenes(imagenes,images);

});



function cargarImagenes(arreglo,lista_imagenes){
  for(var i in arreglo){
    lista_imagenes[i] = new Image();
    lista_imagenes[i].src = arreglo[i];
  }
}

function ponerPreloader(capa){
    var tamano = $('cuerpo').getSize();
    var tamano2 = $('contenido').getSize();
    ypos = (tamano.y/2);
    xpos = (tamano2.x/2) - 120;
    var nuevaIMG = new Element('img',{
      id:'nuevoPopup',
      src: 'images/ajax-loader.gif',
      styles:{
        'position':'absolute',
        'top':ypos+'px',
        'left':xpos+'px',
        'z-index':'2100'
      }
    });
    nuevaIMG.inject(capa,'top');
}

function loadPage(destino,capa){
  var req = new Request({
    method: 'get',
    url: destino,
    onRequest: function(){
      //capa.set('html','<p style="text-align:center"><img src="images/ajax-loader.gif" align="center" /></p>');
      var tamano = $('cuerpo').getSize();
      var tamano2 = $('contenido').getSize();
      ypos = (tamano.y/2);
      xpos = (tamano2.x/2) - 120;
      var nuevaIMG = new Element('img',{
        id:'nuevoPopup',
        src: 'images/ajax-loader.gif',
        styles:{
          'position':'absolute',
          'top':ypos+'px',
          'left':xpos+'px',
          'z-index':'2100'
        }
      });
      nuevaIMG.inject(capa,'top');
    },
    onSuccess: function(texto,xml){
      capa.set('html',texto);
    },
    onFailure:function(){
      capa.set('html','No se encontr&oacute; la direcci&oacute;n especificada');
    }
  }).send();
}

function crearCortina(){
  //var tamano = window.getSize();
  var tamano = window.getScrollSize();
  var cortina = new Element('div',{
    id: 'cortina',
    styles: {
      'background-color':'#000000',
      'position':'absolute',
      'top':'0',
      'left':'0',
      'width':tamano.x+'px',
      'height':tamano.y+'px',
      'z-index':'100'
    }
  });
  cortina.inject('container','before');
  cortina.setOpacity(0.2);
}

function enviarFormularioAJAX(formulario,capa){
    if(validar(formulario)){
      url = formulario.action+"?"+formulario.toQueryString();
      metodo = formulario.method;
      req = new Request({
        method:metodo,
        url:url,
        onRequest:function(){
          capa.set('html','<p style="text-align:center"><br /><br /><br /><br /><br /><br /><img src="images/ajax-loader.gif" width="220" height="19" alt="" id="preloader"/></p>');
        },
        onSuccess:function(texto,xml){
          capa.set('html',texto);
        },
        onFailure:function(){
          capa.set('html','Direcci&oacute;n Incorrecta');
        }
      }).send();
    }
}

function validarPostForm(formulario,capa){
  if(valido = validar(formulario)){
    //ponerPreloader(capa);
    formulario.submit();

  }
}

function enviarFormulario(formulario){
    if(validar(formulario)){
        formulario.submit();
    }
}

function enviarLogueo(formulario,capa){
    var completo = true;
    for(var i=0; i<formulario.elements.length; i++){
      var obj = formulario.elements[i];
      if(obj.type == 'text' || obj.type == 'password'){
          if(obj.value == '' || obj.value == obj.name){
            obj.style.color = "#ff3600";
            completo = false;
          }else{
            obj.style.color = "#444";
          }
      }
    }
    //alert(completo);
    if(completo){
      formulario.submit();
    }
}

function validar(formulario){
  var valido = true;
  var frmEl = formulario.elements;
  var contChk = 0;
  var hayChk = false;
  for(var i=0; i<frmEl.length; i++){
    var obj = frmEl[i];
    switch(obj.type){
      case 'text':{
        if((obj.value == '' || obj.value == obj.name) && obj.className != 'nulo'){
          if(obj.name == 'busqueda'){
            obj.style.color = "red";
            valido = false;
          }else{
            obj.style.border = "1px solid red";
            valido = false;
          }

          //alert(obj.name);
        }
        else{
		  if(obj.name == 'correo' && obj.className != 'nulo'){
			if(!(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(obj.value))){
			  alert("direccion de correo invalida");
              valido = false;
              obj.style.border = "1px solid red";
              //alert(obj.name);
			}else{
              obj.style.border = "1px solid #ccc";
            }
          }else{
            obj.style.border = "1px solid #ccc";
		  }
          if(obj.name == 'txtCaptcha' || obj.name == 'codigo_captcha'){
            if(formulario.code.value!=obj.value){
              alert("No Coincide el texto del la imagen, intentelo nuevamente");
              valido = false;
              obj.style.border = "1px solid red";
              //alert(obj.name);
            }
            else{
                obj.style.border = "1px solid #ccc";
            }
          }

          if(obj.name == 'precio'){
            if(isNaN(obj.value)){
              obj.style.border = "1px solid red";
              valido = false;
              alert('precio invalido, ecribir unicamente numero y decimales');
            }else{
              obj.style.border = "1px solid #ccc";
            }
          }
          if(obj.name == 'busqueda'){
            obj.style.color = "#888";
            obj.style.border = "none";
          }

        }
        break;
      }
      case 'file':{
        if(obj.value==''){
          obj.style.border = "1px solid red";
          valido = false;
          //alert(obj.name);
        }else{
          obj.style.border = "1px solid #ccc";
        }
        break;
      }
      case 'password':{
        if(obj.value == ''){
          obj.style.border = "1px solid red";
          valido = false;
          //alert(obj.name);
        }
        else{
          if(obj.name=='confirmacion'){
            if(frmEl['clave'].value!=obj.value){
              alert("los campos de clave y confirmación deben coincidir, verifiquelo e intentelo nuevamente ");
              obj.style.border = "1px solid red";
              valido = false;
              //alert(obj.name);
            }
            else{
              obj.style.border = "1px solid #ccc";
            }
          }else{
             obj.style.border = "1px solid #ccc";
          }
        }
		break;
      }
	 case 'textarea':{
		if(obj.value == '' || obj.value=='<p>&nbsp;</p>'){
          obj.style.border = "1px solid red";
		  valido = false;
          alert("es necesario llenar el campo "+obj.name);
		}
		else{
          obj.style.border = "1px solid #ccc";
		}
        break;
	 }
     case 'checkbox':{
       hayChk = true;
       if(obj.checked) contChk++;

       if(obj.name == 'changePass') hayChk = false;
       if(obj.name == 'changeAvatar') hayChk = false;
       if(obj.className == 'nulo') hayChk = false;
       break;
     }
     case 'select-one':{
       if(obj.value==0){
         obj.style.border="1px solid red";
         valido = false;
         //alert(obj.name);
       }else{
         obj.style.border = "1px solid #ccc";
       }
       break;
     }
     case 'radio':{
       if(obj.value==''){
         valido = false;
         alert("debe seleccionar una opcion");
       }
     }
     case 'hidden':{
          if(obj.name == 'disponible'){
            if(obj.value=='no'){
              valido = false;
              //frmEl['nickname'].value='';
              frmEl['nickname'].style.border="1px solid red";
              //alert(obj.name);
              //$('preloader').set('html','');
              alert('Verifique la disponibilidad del nickname');
            }else{
              frmEl['nickname'].style.border = "1px solid #ccc";
            }
          }
          if(obj.name == 'buscar_en'){
            alert("objeto encontrado");
            if(obj.value!='directorio' && obj.value != 'clasificados'){
              alert("seleccione el lugar a buscar");
              valido = false;
            }
          }
          if(obj.name == 'id_pregunta'){
            if(obj.value==''){
              alert("seleccione la pregunta");
              valido = false;
            }
          }
     }
    }
  }
   if(contChk==0 && hayChk){
      valido = false;
      alert('Debe seleccionar al menos un elemento de la lista');
    }
  return valido;
}

function eliminar(formulario,path,destino,capa){
  if(valido = validar(formulario)){
    if(confirm("Esta Ud. Seguro que desea eliminar estos elementos?")){
        variables = formulario.toQueryString();
        url = path+destino+".php?"+variables;
        if(capa!=''){
          httpRequest = new Request({
            method: 'get',
            url: url,
            onRequest: function(){
              capa.set('html','<p style="text-align:center"><img src="http://www.tuzonadorada.com/home/images/ajax-loader.gif" align="center" /></p>');
            },
            onSuccess: function(texto,xml){
              capa.set('html',texto);
            },
            onFailure: function(){
              capa.set('html','No se pudo encontrar la dirección solicitada');
            }
          }).send();
        }else{
          formulario.method='get';
          formulario.action=path+destino+".php";
          formulario.submit();
        }
    }

  }
}

function eliminarSingle(destino,capa){
  if(confirm("Esta Ud. Seguro que desea eliminar este elemento?")){
    loadPage(destino,capa);
  }
}

function addPhone(){
  var newPhoneHtml = '<label>Telefono 2</label><br /><input name="telefono2" size="30" tabindex="10"/>&nbsp;<input type="button" value=" - " onclick="removePhone()" class="boton" /><br />';
  $('tel2').set('html',newPhoneHtml);
  $('btnAdd').set('html','');
  $('registro').telefono2.focus();
}

function removePhone(){
  $('tel2').set('html','');
  btnAdd = '<input type="button" value=" +"  onclick="addPhone(this)" class="boton"/>';
  $('btnAdd').set('html',btnAdd);
  $('registro').telefono1.focus();
}


function resetearCampos(formulario){
    formEl = formulario.elements;
    for(var i=0; i<formEl.length; i++){
      obj = formEl[i];
      if(obj.type=='text'){
        obj.style.borderStyle = "solid";
        obj.style.borderWidth = "1px";
        obj.style.borderBottomColor = "#CCCCCC";
        obj.style.borderTopColor = "#777777";
        obj.style.borderLeftColor = "#777777";
        obj.style.borderRightColor = "#777777";
      }
      if(obj.type=='password'){
        obj.style.borderStyle = "solid";
        obj.style.borderWidth = "1px";
        obj.style.borderBottomColor = "#CCCCCC";
        obj.style.borderTopColor = "#777777";
        obj.style.borderLeftColor = "#777777";
        obj.style.borderRightColor = "#777777";
      }
      if(obj.type=='textarea'){
        obj.style.borderStyle = "solid";
        obj.style.borderWidth = "1px";
        obj.style.borderBottomColor = "#CCCCCC";
        obj.style.borderTopColor = "#777777";
        obj.style.borderLeftColor = "#777777";
        obj.style.borderRightColor = "#777777";
      }
    }
}


function sessionFields(obj,valor){
    if(valor==''){
      obj.value=valor;
    }else if(obj.value==''){
      obj.value=valor;
    }
}

function addPics(formulario,capa){
  var files = document.getElementsByName("image_file[]");
  if(files.length<3){
    var newSpace = document.createElement('br');
    var newFile = document.createElement('input');
    newFile.type = "file";
    newFile.name = "image_file[]";
    newFile.size = "30";
    capa.appendChild(newSpace);
    capa.appendChild(newFile);
  }
  //capa.inject(newFile,'after');
}

function removePics(capa){
    files = document.getElementsByName("image_file[]");
    if(files.length > 1){
      salto = capa.getElementsByTagName("br");
      child = files[files.length-1];
      capa.removeChild(child);
      capa.removeChild(salto[salto.length-1]);
    }
}

function permite(elEvento, permitidos){
	//variables que definen los caracteres permitidos
	var numeros = "0123456789";
	var letras = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
	var alfa = numeros + letras;
	switch(permitidos){
		case 'num':
			permitidos = numeros;
			break;
		case 'car':
			permitidos = letras;
			break;
		case 'alfa':
			permitidos = alfa;
			break;
	}

	//obtener la tecla pulsada
	var evento = elEvento || window.event;
	var codigoChar = evento.keyCode || evento.charCode;
	var char = String.fromCharCode(codigoChar);

	//comprobar si la tecla pulsada se encuentra entre los caracteres permitidos
	return permitidos.indexOf(char) != -1;
}
//muestra y oculta el campo avatar en la edicion
function showAvatar(capa){
  oldText = capa.get('html');
  texto = '<label><b>Avatar</b></label><br /><input type="file" name="image_file" size="30" /><br />';
  if(oldText==''){
    capa.set('html',texto);
  }else{
    capa.set('html','');
  }
}

//funcion que muestra oculta campo de imagen en publicacion de clasificado
function upFoto(campo,capa){
  var htmlFile = '<label>Im&aacute;gen:</label><br /> ';
  htmlFile += '<input type="file" name="image_file" class="texto" size="50"/><br />';
  htmlFile += '<span style="color:#ed0000;font-size:10px;font-family:arial">Los archivos no podr&aacute;n exceder de 2Mb.</span><br />';
  htmlFile += '<input type="hidden" name="main" value="si" />';
  if(campo.checked){
    capa.innerHTML = htmlFile;
  }else{
    capa.innerHTML = '';
  }
}

//intercambia fotos
function swapPic(capa,foto){
  capa.set('src','clasificados/'+foto);
}

//
function swapPic2(link,capa,foto,desc,capaDesc){
  capa.set('src',foto);
  capaDesc.set('html',desc);
  link.href = foto;
  //alert(capa.previousSibling);
}

//funcion para darle seguimiento a la venta
function continuarVenta(idVenta,url,capa){
  if(confirm("Esta ud. seguro que desea darle continuidad a esta venta?")){

    //formulario.submit();

      //variables = formulario.toQueryString();
      urlCompleta = 'socios/continuarVenta.php?id_venta='+idVenta;
      req = new Request({
        method:'get',
        url:urlCompleta,
        onRequest:function(){
          capa.set('html','<p style="text-align:center"><br /><br /><br /><br /><br /><br /><img src="images/ajax-loader.gif" width="220" height="19" alt="" id="preloader"/></p>');
        },
        onSuccess:function(texto,xml){
          capa.set('html',texto);
        },
        onFailure:function(){
          capa.set('html','Direcci&oacute;n Incorrecta');
        }
      }).send();
  }

}

function cancelarVenta(idVenta,capa){
  if(confirm("Esta ud. seguro que desea cancelar esta venta?")){
    urlCompleta = 'socios/cancelarVenta.php?id_venta='+idVenta;
    req = new Request({
      method:'get',
      url:urlCompleta,
      onRequest:function(){
        capa.set('html','<p style="text-align:center"><br /><br /><br /><br /><br /><br /><img src="images/ajax-loader.gif" width="220" height="19" alt="" id="preloader"/></p>');
      },
      onSuccess:function(texto,xml){
        capa.set('html',texto);
      },
      onFailure:function(){
        capa.set('html','Direcci&oacute;n Incorrecta');
      }
    }).send();
  }
}

function cancelarCompra(idCompra,capa){
  if(confirm("Esta ud. seguro que desea cancelar esta compra?")){
    urlCompleta = 'socios/cancelarCompra.php?id_compra='+idCompra;
    req = new Request({
      method:'get',
      url:urlCompleta,
      onRequest:function(){
        capa.set('html','<p style="text-align:center"><br /><br /><br /><br /><br /><br /><img src="images/ajax-loader.gif" width="220" height="19" alt="" id="preloader"/></p>');
      },
      onSuccess:function(texto,xml){
        capa.set('html',texto);
      },
      onFailure:function(){
        capa.set('html','Direcci&oacute;n Incorrecta');
      }
    }).send();
  }
}

function concluirVenta(idVenta,capa){
  if(confirm("Esta ud. seguro que desea concluir esta venta?")){
    urlCompleta = 'socios/concluirVenta.php?id_venta='+idVenta;
    req = new Request({
      method:'get',
      url:urlCompleta,
      onRequest:function(){
        capa.set('html','<p style="text-align:center"><br /><br /><br /><br /><br /><br /><img src="images/ajax-loader.gif" width="220" height="19" alt="" id="preloader"/></p>');
      },
      onSuccess:function(texto,xml){
        capa.set('html',texto);
      },
      onFailure:function(){
        capa.set('html','Direcci&oacute;n Incorrecta');
      }
    }).send();
  }
}

function eliminarClasificado(id,capa){
    direccion = "socios/eliminarClasificado.php?id="+id;
    if(confirm("Esta ud. seguro que desea eliminar este clasificado?, esta accion eliminará el producto junto con las imagenes de la base de datos")){
        req = new Request({
          method:'get',
          url:direccion,
          onSuccess:function(texto,xml){
            capa.set('html',texto);
          }
        }).send();
    }
}

function bajarClasificado(id,capa){
    direccion = "socios/bajarClasificado.php?id="+id;
    if(confirm("Esta ud. seguro que desea dar de baja este producto?, el producto permanecerá en la base de datos, en caso de que desee publicarlo de nuevo solo modifique el valor de la existencia a un numero mayor a cero")){
        req = new Request({
          method:'get',
          url:direccion,
          onSuccess:function(texto,xml){
            capa.set('html',texto);
          }
        }).send();
    }
}

function agregarTel(){
  //alert($$('.campoTel'));
  telefonos = $$('.campoTel');

  if(telefonos == ''){
    noTel = 1;
  }
  else {
    noTel = telefonos.length;
    noTel++;
  }
  //alert(noTel);
  var newTel = new Element('tr',{
    id:'tel'+noTel
  });
  var firstTd = new Element('td');
  firstTd.set('html','<input type="text" class="campoTel" name="telefonos[]" size="15" />');
  firstTd.inject(newTel,'top');
  var secondTd = new Element('td');
  var telAsinc = new Request({
    method: 'get',
    url: 'socios/newTelForm.php?no='+noTel,
    onSuccess:function(texto,xmlRespuesta){
      secondTd.set('html',texto);
      //alert(texto);
    }
  }).send();
  secondTd.inject(newTel,'bottom');
  newTel.inject('posInsert','before');
  if(noTel==1){
    var separador = new Element('span');
    separador.set('html','&nbsp;');
    var btnEliminar = new Element('input',{
      type: 'button',
      id: 'btnEliminarTel',
      value: 'eliminar telefono'
    });
    btnEliminar.addClass('boton');
    btnEliminar.addEvent('click',function(){
      eliminarTel();
    });
    separador.inject('btnAgregarTel','after');
    btnEliminar.inject(separador,'after');
  }

  //var htmlText = '<td><label>Tel&eacute;fono: </label><input type="text" class="campoTel" name="tel'+noTel+'" size="10" /></td><td></td>';
  //newTel.set('html',htmlText);
  //newTel.inject('btnAgregarTel','before');
  //alert(newTel.innerHTML);

}
//FUNCIÓN PARA ELIMINAR TELÉFONO
function eliminarTel(){
  var telefonos = $$('.campoTel');
  var lastTel = $('tel'+telefonos.length);
  //alert(lastTel);
  if(telefonos.length==1){
    lastTel.destroy();
    $('btnEliminarTel').destroy();
  }else lastTel.destroy();
}
//-----------------------------------------------------------------------------

//CHECAR DISPONIBILIDAD DE USUARIO
function disponibilidad(form,capa){
    var valor = form.nickname.value;
    var req = new Request({
      method: 'get',
      url: 'socios/checarDisponibilidad.php?value='+valor,
      onSuccess: function(texto,xml){
        if(texto=='disponible'){
          capa.set('html','disponible');
          form.disponible.value = 'si';
          capa.setStyles({
            'background-color':'#99CC66',
            'color':'#fff',
            'padding':'5px'
          });
        }else{
          capa.set('html','no disponible');
          form.disponible.value = 'no';
          capa.setStyles({
            'background-color':'#ff3600',
            'color':'#fff',
            'padding':'5px'
          });
        }
      }
    }).send();
}
//-----------------------------------------------------------------------------
// funcion para mostrar ocultar la clave
function claves(caja){
  if(caja.checked){
    htmlTexto = '<label>Clave nueva: <span style="color:#ff3600">*</span></label><br /><input type="password" name="clave" size="30" class="texto" /><br /><label>Confirmar clave: <span style="color:#ff3600">*</span></label><br /><input type="password" name="confirmacion" class="texto" size="30" /><br />';
    $('claves').set('html',htmlTexto);
  }else{
    $('claves').set('html','');
  }
}

//ACTIVA EL CEHCKBOX DE LAS IMAGENES
function checarIMG(pic){
  chkbox = pic.nextSibling.nextSibling;
  if(chkbox.checked){
    chkbox.checked=false;
  }else{
    chkbox.checked=true;
  }
}

//activar los campos del buscador
function activar(opc,clicado,otro){
  form = document.forms['searchGform'];
  if(clicado.state!='on'){
    clicado.state='on';
    otro.state='off';
    start = otro.src.length - 6;
    otro.src = otro.src.substring(0,start)+"up.png";
  }
  form['directorio'].checked = false;
  form['clasificados'].checked = false;
  form[opc].checked = true;
}