// alias para ID
function ID(id){
    return document.getElementById(id);
}

function anyadirEvento(objeto,evento,funcion){
	try{
		objeto.addEventListener(evento,funcion,false);
		return true;
	}catch(e){
		try{
			objeto.attachEvent("on"+evento,funcion);
			return true;
		}catch(e){
			return false;
		}
	}
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

//crea un objeto del tipo XMLHttpRequest según el navegador
function XML(){ //no quitar los comentarios condicionales
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function getAbsoluteElementPosition(element) {
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}


var informacionActual = "";

function capaInformacionActivar()
{
  var juegos = document.getElementsByClassName("enlace-juego");
  for (numJuego=0;numJuego<juegos.length;numJuego++){
    //encuentro su capa de información
    if (juegos[numJuego].id && juegos[numJuego].id != ""){
    juegos[numJuego].onmouseover =function(e){
                                              posicion = getAbsoluteElementPosition(this.id)
                                              capasInformacion = this.getElementsByClassName("mas-informacion-juego png");
                                              capaInformacion = capasInformacion[0];
                                              if (capaInformacion.className.indexOf("izquierda")==-1){
                                                capaInformacion.style.top=(posicion.top-130)+"px";
                                                capaInformacion.style.left=(posicion.left+90)+"px";
                                              }else{
                                                capaInformacion.style.top=(posicion.top-130)+"px";
                                                capaInformacion.style.left=(posicion.left-400)+"px";
                                              }
                                              capaInformacion.style.display="";
                                              if (BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 6){
                                                if (ID('filtro-plataforma')) ID('filtro-plataforma').style.display = "none";
                                                if (ID('filtro-genero')) ID('filtro-genero').style.display = "none";
                                                if (ID('filtro-clasificacion')) ID('filtro-clasificacion').style.display = "none";
                                                if (ID('filtro-mes')) ID('filtro-mes').style.display = "none";
                                              }
                                            };
    juegos[numJuego].onmouseout =function(e){
                                              capasInformacion = this.getElementsByClassName("mas-informacion-juego png");
                                              capaInformacion = capasInformacion[0];
                                              capaInformacion.style.display="none";
                                              if (BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 6){
                                                if (ID('filtro-plataforma')) ID('filtro-plataforma').style.display = "";
                                                if (ID('filtro-genero')) ID('filtro-genero').style.display = "";
                                                if (ID('filtro-clasificacion')) ID('filtro-clasificacion').style.display = "";
                                                if (ID('filtro-mes')) ID('filtro-mes').style.display = "";
                                              }
                                            };
    }
  }
}
anyadirEvento(window,"load",capaInformacionActivar);

function filtrarNovedades()
{
  if ( ID('filtro-plataforma').options[ID('filtro-plataforma').selectedIndex].value == "" && 
       ID('filtro-genero').options[ID('filtro-genero').selectedIndex].value == "" && 
       ID('filtro-clasificacion').options[ID('filtro-clasificacion').selectedIndex].value == "" ){
           window.location.href = "/ultimas-novedades/";
   }else{
     window.location.href = "/ult-novedades.php?filtroPlataforma="+ID('filtro-plataforma').options[ID('filtro-plataforma').selectedIndex].value+"&filtroGenero="+ID('filtro-genero').options[ID('filtro-genero').selectedIndex].value+"&filtroClasificacion="+ID('filtro-clasificacion').options[ID('filtro-clasificacion').selectedIndex].value;
   }
   return true;
}

function filtrarProximosLanzamientos()
{
  if ( ID('filtro-plataforma').options[ID('filtro-plataforma').selectedIndex].value == "" && 
       ID('filtro-genero').options[ID('filtro-genero').selectedIndex].value == "" && 
       ID('filtro-mes').options[ID('filtro-mes').selectedIndex].value == "" ){
         window.location.href = "/proximos-lanzamientos/";
   }else{
     window.location.href = "/prox-lanzamientos.php?filtroPlataforma="+ID('filtro-plataforma').options[ID('filtro-plataforma').selectedIndex].value+"&filtroGenero="+ID('filtro-genero').options[ID('filtro-genero').selectedIndex].value+"&filtroMes="+ID('filtro-mes').options[ID('filtro-mes').selectedIndex].value;
   }
   return true;
}

function Ayuda(){
  var etiquetas=new Array('A','IMG');
  var contenido={};
  for (q=0;q<etiquetas.length;q++){
    var enlaces=document.getElementsByTagName(etiquetas[q]);
    for(k=0;k<enlaces.length;k++){
      tit=enlaces[k].title;
      if (tit){
        //enlaces[k].removeAttribute('title');
        enlaces[k].removeAttribute('alt');
        enlaces[k].longdesc=tit;
        try{
          //enlaces[k].firstChild.removeAttribute('title');
          enlaces[k].firstChild.removeAttribute('alt');
          enlaces[k].firstChild.longdesc=tit;
        }catch(ex){}
        /*enlaces[k].onmouseover=function(e){generarAyuda(this.longdesc,e)};
        enlaces[k].onmouseout=function(e){destruirAyuda(e)};
        enlaces[k].onmousemove=function(e){if (!document.getElementById('ayuda_contextual')) generarAyuda(this.longdesc,e);moverAyuda(e)};*/
      }
    }
  }
}

function generarAyuda(titulo,e){
  if (titulo==undefined) return;
  if (!e) var e = window.event;
  var relTarg;
/*try{
if (!e) var e = window.event;
if (e.relatedTarget) relTarg = e.relatedTarget;
else if (e.fromElement) relTarg = e.fromElement;
var reltg=relTarg;
while (reltg.nodeName != 'BODY'){
if(reltg.longdesc==titulo){ return;}
reltg= reltg.parentNode;
}
}catch(ex){}*/
  if(document.getElementById('ayuda_contextual')) document.getElementById('ayuda_contextual').parentNode.removeChild(document.getElementById('ayuda_contextual'));


  this.caja=document.createElement("div");
  this.caja.setAttribute("id","ayuda_contextual");
  this.despl=calcularScroll();
  this.caja.style.top=e.clientY+this.despl[1]+"px";
  this.caja.style.left=e.clientX+this.despl[0]+"px";
  this.frecuencia=60;
  this.opacidad=0;
  this.aumento=0;
  this.caja.innerHTML=titulo;
  cambiarOpacidad(this.caja,this.opacidad);
  document.getElementsByTagName('BODY')[0].appendChild(this.caja);

  try{
    if(document.getElementById('ayuda_contextual').clientWidth>250){
      document.getElementById('ayuda_contextual').style.width="250px";
    }
  }catch(ex){}

  this.aparecer=function(){
    if (this.opacidad<75){
      this.opacidad+=this.aumento;
      if (this.opacidad<1){
        this.aumento+=0.05;
      }else{
        this.aumento+=1;
      }
      cambiarOpacidad(this.caja,this.opacidad);
    }else{
      this.opacidad=75;
      window.clearInterval(this.tempo);
    }
  }

  this.setInterval("this.aparecer()",this.frecuencia);
  return false;
}

function destruirAyuda(e){
  try{
    if (!e) var e = window.event;
    var tg = (window.event) ? e.srcElement : e.target;
    var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
    var reltg1=reltg;
    while (reltg1 != tg && reltg1.nodeName != 'BODY'){
      reltg1= reltg1.parentNode;
    }
    if (reltg1== tg) return;

    while (reltg != tg && tg.nodeName != 'BODY'){
      tg= tg.parentNode;
    }
    if (reltg== tg && tg.longdesc) return;

    document.getElementById('ayuda_contextual').parentNode.removeChild(document.getElementById('ayuda_contextual'));
  }catch(e){}
}

function moverAyuda(e){
  if (!e) var e = window.event;
  try{
    this.despl=calcularScroll();
    document.getElementById('ayuda_contextual').style.top=e.clientY+this.despl[1]+"px";
    document.getElementById('ayuda_contextual').style.left=e.clientX+this.despl[0]+"px";
  }catch(e){}
}

function cambiarOpacidad(objeto,op){
	objeto.style.filter="alpha(opacity="+op+")";
	objeto.style.MozOpacity=op/100;
	objeto.style.opacity=op/100;
}
/****** Calcular cuanto se ha desplazado el scroll de la pantalla ******/
function calcularScroll(){
    var x,y;
    if (self.pageYOffset) // all except Explorer
    {
    	x = self.pageXOffset;
    	y = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    	// Explorer 6 Strict
    {
    	x = document.documentElement.scrollLeft;
    	y = document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
    	x = document.body.scrollLeft;
    	y = document.body.scrollTop;
    }
    resultado=new Array(x,y);
    return resultado;
}

/****** Comprueba si el navegador es Internet Explorer ******/
function esIE(){
    var agt=navigator.userAgent.toLowerCase();
    return ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
}

//generarAyuda.prototype=window;
//anyadirEvento(window,"load",Ayuda);

function buscar()
{
  //Busqueda 
  var url = "";
  var busqueda = $('busqueda').value;
  var re = /\s|,|\./
  palabras = busqueda.split(re);
  //Sólo pueden indicar 3 palabras
  if (palabras.length == 0 || busqueda == ""){
    alert("Introduzca algún criterio de búsqueda.");
    return false;
  }else if (palabras.length > 3 ){
    alert('La búsqueda tiene un máximo de 3 palabras.\nBorre alguna de las que ha introducido.');
    return false;
  }else{
    //Cada una de ellas debe contener al menos 2 caracteres
    for(i=0;i<palabras.length;i++){
      if (palabras[i].length < 2){
      	//alert('Las palabras buscadas deben tener, al menos, 3 caracteres para que la búsqueda sea efectiva.');
        //return false;
      }else url += palabras[i].replace(/\//g,"-")+"/";
    }
  }
  //Si cumple las condiciones anteriores, realizamos la búsqueda.
  window.location.href = "/buscar/"+url;
  return true;
}

function suscripcion()
{
  var email = $('emailSuscriptor').value;
  var accion = "";
  if (email == "" ){
    alert('Por favor, indique su correo electrónico.');
    return false;
  }else if (!emailValidar($('emailSuscriptor'))){
    return false;
  }
  if (!$('altaSuscriptor').checked && !$('bajaSuscriptor').checked){
    alert('Por favor, seleccione la acción que desea realizar');
    return false;
  }
  if ($('altaSuscriptor').checked){
    accion = "alta";
  }else accion = "baja";
  
  url = '?accion='+accion+'&email='+email+'';
  xmlhttp=new XML();
  if (xmlhttp){
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        alert(xmlhttp.responseText);
        $('emailSuscriptor').value = "";
        $('altaSuscriptor').checked = "";
        $('bajaSuscriptor').checked = "";
      }
    }
    xmlhttp.open("GET", "/suscriptor.php"+url,true);
    xmlhttp.send(null);
    return false;
  }
}

/*
Funcion para validar el formato de un e-mail.
Tiene que tener al menos, la @ y un punto indicador del dominio
Fecha: 14/04/03
Autor: Javi Ruiz (Almería)
*/
function emailValidar(campo)
{
	email = campo.value;
	if (email!='' && (email.indexOf("@")==-1 || email.indexOf(".")==-1 ) ){
		alert ("Compruebe que el formato del E-mail es: \nnombre@nombredominio.dominio ")
		return false;
	}
	return true;
}

function contactoEnviar()
{
  if ($('nombre').value == ""){
    alert('Por favor, indica tu nombre. Es obligatorio.');
    $('nombre').focus();
    return false;
  }
  if ($('telefono').value == "" && $('email').value == "" ){
    alert('Por favor, indica una forma de contacto. Teléfono o email.');
    $('email').focus();
    return false;
  }else if (!emailValidar($('email'))){
    return false;
  }
  if ($('consulta').value == ""){
    alert('Por favor, indica la consulta quieres realizarnos. Es obligatorio.');
    $('consulta').focus();
    return false;
  }
  
  url = '?accion=contacto&nombre='+$('nombre').value+'&apellidos='+$('apellidos').value+'&direccion='+$('direccion').value+'&cp='+$('cp').value+'&poblacion='+$('poblacion').value+'&provincia='+$('provincia').value+'&telefono='+$('telefono').value+'&telefono2='+$('telefono2').value+'&email='+$('email').value+'&consulta='+$('consulta').value+'';
  xmlhttp=new XML();
  if (xmlhttp){
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        $('respuestaContacto').innerHTML =xmlhttp.responseText;
        var inputs = ID('form-contacto').getElementsByTagName('input');
        for (i=0;i<inputs.length;i++){
          inputs[i].value = "";
        }
        $('consulta').value = "";
      }
    }
    xmlhttp.open("GET", "/formulario-contacto.php"+url,true);
    xmlhttp.send(null);
    return false;
  }
}

function profesionalesEnviar()
{
  if ($('razonSocial').value == ""){
    alert('Por favor, indica la Razón Social. Es obligatorio.');
    $('razonSocial').focus();
    return false;
  }
  if ($('cif').value == ""){
    alert('Por favor, indica el CIF. Es obligatorio.');
    $('cif').focus();
    return false;
  }
  if ($('direccion').value == ""){
    alert('Por favor, indica la Dirección. Es obligatorio.');
    $('direccion').focus();
    return false;
  }
  if ($('cp').value == ""){
    alert('Por favor, indica el Código Postal. Es obligatorio.');
    $('cp').focus();
    return false;
  }
  if ($('poblacion').value == ""){
    alert('Por favor, indica la Población. Es obligatorio.');
    $('poblacion').focus();
    return false;
  }
  if ($('provincia').value == ""){
    alert('Por favor, indica la Provincia. Es obligatorio.');
    $('provincia').focus();
    return false;
  }
  if ($('personaContacto').value == ""){
    alert('Por favor, indica una Persona de contacto. Es obligatorio.');
    $('personaContacto').focus();
    return false;
  }
  if ($('telefono').value == ""){
    alert('Por favor, indica el teléfono. Es obligatorio.');
    $('telefono').focus();
    return false;
  }
  if ($('email').value == "" ){
    alert('Por favor, indica el email. Es obligatorio.');
    $('email').focus();
    return false;
  }else if (!emailValidar($('email'))){
    return false;
  }
  
  var tiendaAbierta = "";
  if ($('tiendaAbiertaSi').checked){
    tiendaAbierta = "SI"
  }else if ($('tiendaAbiertaNo').checked){
    tiendaAbierta = "NO"
    if ($('tiendaAbiertaOtro').value ==""){
      alert('Por favor, indica si la tienda está en proyecto y tiene fecha prevista de apertura').
      $('tiendaAbiertaOtro').focus();
      return false
    }else{
      tiendaAbierta += ", "+$('tiendaAbiertaOtro').value;
    }
  }
  
  var establecimiento = "";
  if ($('establecimientoCiber').checked){
    establecimiento = "CIBER"
  }else if ($('establecimientoEspecialista').checked){
    establecimiento = "ESPECIALISTA"
  }else if ($('establecimientoMayorista').checked){
    establecimiento = "MAYORISTA"
  }else if ($('establecimientoElectrodomesticos').checked){
    establecimiento = "ELECTRODOMÉSTICOS"
  }else if ($('establecimientoOtros').checked){
    establecimiento = "OTROS"
    if ($('establecimientoOtrosTexto').value ==""){
      alert('Por favor, indica de qué otro tipo es su establecimiento.').
      $('establecimientoOtrosTexto').focus();
      return false
    }else{
      establecimiento += ", "+$('establecimientoOtrosTexto').value;
    }
  }
  
  var conocio = "";
  if ($('conocioHobby').checked){
    conocio = "HOBBY"
  }else if ($('conocioPlanet').checked){
    conocio = "PLANET"
  }else if ($('conocioPamarillas').checked){
    conocio = "P. AMARILLAS"
  }else if ($('conocioQDQ').checked){
  conocio = "QDQ"
  }else if ($('conocioInternet').checked){
  conocio = "INTERNET"
  }else if ($('conocioOtros').checked){
    conocio = "OTROS"
    if ($('conocioOtrosTexto').value ==""){
      alert('Por favor, indica de qué otra forma nos conoció.').
      $('conocioOtrosTexto').focus();
      return false
    }else{
      conocio += ", "+$('conocioOtrosTexto').value;
    }
  }
  
  url = '?accion=profesional&razonSocial='+$('razonSocial').value+'&nombreComercial='+$('nombreComercial').value+'&cif='+$('cif').value+'&direccion='+$('direccion').value+'&cp='+$('cp').value+'&poblacion='+$('poblacion').value+'&provincia='+$('provincia').value+'&personaContacto='+$('personaContacto').value+'&telefono='+$('telefono').value+'&fax='+$('fax').value+'&email='+$('email').value+'&tiendaAbierta='+tiendaAbierta+'&establecimiento='+establecimiento+'&conocio='+conocio+'&consulta='+$('consulta').value+'';
  xmlhttp=new XML();
  if (xmlhttp){
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        $('respuestaProfesionales').innerHTML =xmlhttp.responseText;
        var inputs = ID('form-profesionales').getElementsByTagName('input');
        for (i=0;i<inputs.length;i++){
          if (inputs[i].type == "text")
            inputs[i].value = "";
          else inputs[i].checked = "";
        }
        $('consulta').value = "";
      }
    }
    xmlhttp.open("GET", "/formulario-profesionales.php"+url,true);
    xmlhttp.send(null);
    return false;
  }
}
