// Javascript para: http://www.injiniero.es/
//
// Me encantaría que reutilizaras este código
// Y me haría feliz que nombraras la fuente si lo haces.
// Gracias.
//
var numBg = 19;
var lastBg = 0;
var newBg = 0;
var imgloaded = false;
var updateTime = 600000;
var updateSolTime = 1800000;
var updatedTierra;
var eagleTime = 1000;
var sun;
var sitios = new Array();
var nsitios;
var orbitado = 1;
var luna = 'sitio-1';
var universoW;
var universoH;
var universo;
var ucentro;
var csun;
var eagleId = 0;
var showData = false;  // debug

function random(min,num){
  return Math.floor(Math.random()*num+min);
}

function distancia(p1, p2) {
  return Math.floor(Math.sqrt((Math.pow(p1.top-p2.top,2))+(Math.pow(p1.left-p2.left,2))));
}

function coord(top, left) {
  this.top = top;
  this.left = left;
}

function sitio(id, ang){
  this.s = document.getElementById(id);
  this.id = id;
  this.stop = false;
  this.ang = ang;
  this.pc = 0.5;
  this.coord = new coord(0,0);
  this.centro = new coord(ucentro.top,random(ucentro.left,csun*this.pc));
  if (this.id == luna) {
    this.c = 5.49;
  }
  else {
    this.c = sun.left - this.centro.left;
  }
  var amax = Math.sqrt(Math.pow(this.centro.top,2)+Math.pow(this.c,2));
  var wmax = universoW - this.centro.left;
  amax = amax < wmax ? amax : wmax;
  if (this.id == luna) {
    this.a = 100;
    this.cte = 80;
  }
  else {
    this.a = random(this.c*1.1,amax-this.c*1.1);
    this.cte = this.a/4;
  }
  this.b = Math.sqrt(Math.pow(this.a,2) - Math.pow(this.c,2));
  this.lastTime = 0;

  if (showData) {
    this.element = document.createElement('div');
    this.element.style.cssText = 'position:absolute;top:'+(this.centro.top + parseInt(this.id.substr(this.id.length-1))*20)+'px;left:'+this.centro.left+'px;background-color:#fff;font-size:0.8em;';
    this.element.innerHTML = this.id.substr(this.id.length-1)+' t:'+this.centro.top+' l:'+this.centro.left;
    universo.appendChild(this.element);

    this.data = document.createElement('div');
    this.data.style.cssText = 'position:absolute;top:0px;left:82px;background-color:#fff;font-size:0.8em;';
    this.s.appendChild(this.data);

    this.vel = document.createElement('div');
    this.vel.style.cssText = 'position:absolute;top:-15px;left:0px;background-color:#fff;font-size:0.8em;';
    this.vel.id = 'v'+this.id;
    this.vel.className = 'vel';
    this.s.appendChild(this.vel);
  }

  this.mueve = function() {
    var v;
    if (this.id == luna) {
      v = Math.sqrt(2 * this.cte * (1/distancia(sitios[orbitado].coord,this.coord) - 1/(2*this.a)));
      this.centro.top = sitios[orbitado].coord.top;
      this.centro.left = sitios[orbitado].coord.left;
    }
    else {
      v = Math.sqrt(2 * this.cte * (1/distancia(sun,this.coord) - 1/(2*this.a)));
    }
    if (v<0.08 || isNaN(v)) {
      v = 0.1;
    };
    var now = new Date().getTime();
    var t = this.lastTime == 0 ? 0 : (now - this.lastTime) / 1000;
    var da = v * t;
    this.ang += da;
    if (this.ang > Math.PI*2) {
      this.ang = this.ang-Math.PI*2;
    }
    if (showData) {
      var data = '<pre>'+
        'id: '+this.id+'<br/>'+
        'coord: ('+this.coord.top+','+this.coord.left+')<br/>'+
        'centro: ('+this.centro.top+','+this.centro.left+')<br/>'+
        'ang: '+this.ang+'<br/>'+
        'cte: '+this.cte+'<br/>'+
        'c: '+this.c+'<br/>'+
        'a: '+this.a+'<br/>'+
        'b: '+this.b+'<br/>'+
        'e: '+(this.c/this.a)+'<br/>';

      this.vel.innerHTML = 'v: '+v;
      this.data.innerHTML = data;
    }
    this.coord.left = Math.floor(this.centro.left + this.a * Math.cos(this.ang));
    this.coord.top = Math.floor(this.centro.top + this.b * Math.sin(this.ang));
    if (this.id == luna) {
      this.s.style.top = this.coord.top-20+'px';
      this.s.style.left = this.coord.left-20+'px';
      for (var s = 1;s<nsitios;s++) {
        if (s == orbitado) {
          continue;
        }
        if (Math.abs(distancia(this.coord,sitios[s].coord) - distancia(this.coord,sitios[orbitado].coord)) < 1 && (s == 1 || Math.random() < 0.3) ) {
          var vdi = new coord(this.coord.top - sitios[s].coord.top,this.coord.left - sitios[s].coord.left);
          var newAng = Math.acos(Math.abs(vdi.left) / Math.sqrt(Math.pow(vdi.left,2)+Math.pow(vdi.top,2)));
          if (vdi.left < 0 && vdi.top >= 0) { // 2º cuadrante
            newAng = Math.PI - newAng;
          }
          else if (vdi.left < 0 && vdi.top < 0) { // 3er. cuadrante
            newAng = Math.PI + newAng;
          }
          else if (vdi.left >= 0 && vdi.top < 0) { // 4º cuadrante
            newAng = Math.PI * 2 - newAng;
          }
          this.ang = newAng;
          orbitado = s;
          break;
        }
      }
    }
    else {
      this.s.style.top = this.coord.top-40+'px';
      this.s.style.left = this.coord.left-40+'px';
    }
    this.lastTime = new Date().getTime();

    if (!this.stop) setTimeout(this.mueve, 70);
  }.bind(this);

  setTimeout(this.mueve, 10000);
}

function setupUniverso() {
  universoW = $("#universo-wrapper").innerWidth()-80;
  universoH = $("#universo-wrapper").innerHeight()-80;
  ucentro = new coord(Math.floor(universoH/2),Math.floor(universoW/2));
  universo = document.getElementById('universo');
  universo.style.width = universoW+'px';
  universo.style.height = universoH+'px';
  sun = new coord(ucentro.top-40,Math.round(universoW*0.8)+40);
  $("#sun").css({'top': sun.top,'left':sun.left-80});
  $("#sun").fadeIn(5000);
  csun = sun.left - ucentro.left;

  if (showData) {
    ocentro = document.createElement('div');
    ocentro.style.cssText = 'position:absolute;top:'+ucentro.top+'px;left:'+ucentro.left+'px;z-index:450;background-color:#fff;font-size:0.8em;';
    ocentro.innerHTML = 't:'+ucentro.top+' l:'+ucentro.left+' h:'+universoH+' w:'+universoW;
    universo.appendChild(ocentro);
  }

  $(".sitio").each(function() {
    ang = Math.random()*Math.PI*2;
    sitios[sitios.length] = new sitio($(this).attr('id'), ang);
  });
  nsitios = sitios.length;
  for (i in sitios) {
    sitios[i].coord.left = Math.floor(sitios[i].centro.left + sitios[i].a * Math.cos(sitios[i].ang));
    sitios[i].coord.top = Math.floor(sitios[i].centro.top + sitios[i].b * Math.sin(sitios[i].ang));
  };
  // Recalcula la luna
  sitios[0].centro.top = sitios[orbitado].coord.top;
  sitios[0].centro.left = sitios[orbitado].coord.left;
  sitios[0].coord.left = Math.floor(sitios[0].centro.left + sitios[0].a * Math.cos(sitios[0].ang));
  sitios[0].coord.top = Math.floor(sitios[0].centro.top + sitios[0].b * Math.sin(sitios[0].ang));

  var id;
  for (i in sitios) {
    id = sitios[i].id;
    if (id == luna) {
      $('#'+id).animate({top: sitios[i].coord.top-20, left: sitios[i].coord.left-20},3000);
    }
    else {
      $('#'+id).animate({top: sitios[i].coord.top-40, left: sitios[i].coord.left-40},3000);
    }
  };
  setTimeout('eagleDrop()',eagleTime);
}

function updateTierra() {
  var r = new Date().getTime();
  $("#sitio-2 img").attr("src",'tierra.php?cual='+r).fadeOut(1000).fadeIn(1000);
  setTimeout("updateTierra()",updateTime);
}

function updateSol() {
  var d = new Date();
  var m = d.getMinutes().toString();
  if (m.length < 2) {
    m = '0'+m;
  }
  var hm = parseInt((d.getHours()).toString() + m);

  var sol;
  if ((hm >= 700 && hm < 1000) || (hm >= 1600 && hm < 1900)) {
    sol = 'sol_rojo.gif';
  }
  else if (hm >= 1000 && hm < 1600) {
    sol = 'sol_amarillo.gif';
  }
  else if (hm >= 1900 || (hm >= 0 && hm < 100)) {
    sol = 'sol_azul.gif';
  }
  else {
    sol = 'sol_verde.gif';
  }

  sol = 'img/'+sol;
  var ant;
  ant = $("#sun img").attr("src");
  if (sol != ant) {
    $("#sun img").attr("src",sol).fadeOut(500).fadeIn(6000);
  }
  setTimeout("updateSol()",updateSolTime);
}

function eagleDrop() {
  var r = Math.random();
  var lado;
  var source;
  var zona1;
  var zona2;
  var eagleVel = random(3000,3000);
  if (r < 0.02) {
    if (r < 0.01) {
      source = 'i';
      zona1 = 0.75;
      zona2 = 0;
    }
    else {
      source= 'd';
      zona1 = 0;
      zona2 = 0.75;
    }
    var  eagle = document.createElement('img');
    eagle.id = "eagle"+eagleId;
    eagleId++;
    if (eagleId > 1000) eagleId = 0;
    eagle.style.cssText = 'position:absolute;top: -100px;left:'+random(universoW*zona1,universoW*0.25)+'px;height:20px;width:20px;z-index:1000;';
    eagle.src = 'img/eagle'+source+'.gif';
    eagleWidth = random(80,80);
    universo.appendChild(eagle);
    $("#"+eagle.id).animate({top: universoH + 90, left: random(universoW*zona2,universoW*0.25), width: eagleWidth, height: eagleWidth*0.75},eagleVel,'easeInExpo',function() {
      universo.removeChild(eagle);
      eagle = null;
    });
  }
  setTimeout('eagleDrop()',eagleTime);
}

function updateVisitas() {
  var r = new Date().getTime();
  $.ajax({
    url: "getVdatos.php",
    dataType: "text",
    data: {dummy: r},
    success: function(html) {
      var datos = html.split(",");
      var maximo = 0;
      for (var i=0; i<7;i++) {
        datos[i] = parseInt(datos[i]);
        if (datos[i] > maximo) {
          maximo = datos[i];
        }
      };
      $("#v-Lu").html('<p>'+datos[0]+'</p>').animate({height: Math.floor(datos[0]*55/maximo)},1000);
      $("#v-Ma").html('<p>'+datos[1]+'</p>').animate({height: Math.floor(datos[1]*55/maximo)},1000);
      $("#v-Mi").html('<p>'+datos[2]+'</p>').animate({height: Math.floor(datos[2]*55/maximo)},1000);
      $("#v-Ju").html('<p>'+datos[3]+'</p>').animate({height: Math.floor(datos[3]*55/maximo)},1000);
      $("#v-Vi").html('<p>'+datos[4]+'</p>').animate({height: Math.floor(datos[4]*55/maximo)},1000);
      $("#v-Sa").html('<p>'+datos[5]+'</p>').animate({height: Math.floor(datos[5]*55/maximo)},1000);
      $("#v-Do").html('<p>'+datos[6]+'</p>').animate({height: Math.floor(datos[6]*55/maximo)},1000);
      $("#v-Bo").html('<p>'+datos[7]+'</p>').animate({height: 45},1000);
      $("#v-visitas").html('Visitas: '+datos[8]+', Únicas: '+datos[9]).slideDown(1000);
    }
  });
}

function checkTimer() {
  if (!imgloaded) {
    changeBg();
  }
  setTimeout("checkTimer()",47000);
}

function changeBg(){
  while (newBg == lastBg) {
    newBg = random(1,19);
  }
  lastBg = newBg;
  var cero = '';
  if (newBg < 10) {
    cero = '0';
  }
  var src = 'img/bg/mariposa-'+cero+newBg+'.jpg';
  $("#background").fadeOut(1000, function(){
    imgloaded = false;
    $("#background").attr("src",src);
  });
}

function setBackground() {
  $("#background").redim();
  $("#background").center();
  $("#universo-wrapper").redim();
  $("#universo-wrapper").center();
  $("#background").load(function() {
    imgloaded = true;
    $("#background").fadeIn(1000, function(){
      setTimeout("changeBg()", 30000);
    });
  });
}

function setCorners() {
  $(".corner").show(3000);
}

function setPage() {
  setBackground();
  setCorners();
}

jQuery.fn.center = function() {
  this.css("position","absolute");
  this.css("top",($(window).height() - this.outerHeight()) / 2);
  this.css("left",($(window).width() - this.outerWidth()) / 2);
  return this;
}

jQuery.fn.redim = function() {
  this.css("height",$(window).innerHeight() * 0.90);
  this.css("width",$(window).innerWidth() * 0.90);
  return this;
}

$(document).ready( function(){
  setPage();
  $("#yo").hover(
    function() {
      $(this).fadeTo(3000,0);
      $("#otroyo").fadeIn(3000);
    },
    function() {
      $(this).fadeTo(3000,1);
      $("#otroyo").fadeOut(3000);
  });
  $("#original").hide();
  $("#title-wish").hide();
  $("#title-ojala").show();
  $("#trad").show();
  $("#wish").width($("#wish").width()).css("right", -5-$("#wish").width()).fadeIn(3000).fadeTo(500,0.8).toggle(function(){
    $(this).animate({right: 0},3000, function(){
      $("#abrir-wish").hide();
      $("#cerrar-wish").show();
    });
  },function(){
    $(this).animate({right: -5-$(this).width()},3000, function(){
      $("#abrir-wish").show();
      $("#cerrar-wish").hide();
    });
  });
  $("#title-ojala").hide();
  $("#trad").hide();
  $("#original").show();
  $("#title-wish").show();
  $("#wish-content").hover(
    function() {
      $("#original").hide();
      $("#title-wish").hide();
      $("#title-ojala").show();
      $("#trad").show();
    },
    function() {
      $("#title-ojala").hide();
      $("#trad").hide();
      $("#original").show();
      $("#title-wish").show();
  });
  $("#texto-condena").hide();
  $("#title-condena").hide();
  $("#title-poema").show();
  $("#poema-trad").show();
  $("#condena").width($("#condena").width()).css("left", -5-$("#condena").width()).fadeIn(3000).fadeTo(500,0.8).toggle(function(){
    $(this).animate({left: 0},3000, function(){
      $("#abrir-condena").hide();
      $("#cerrar-condena").show();
    });
  },function(){
    $(this).animate({left: -5-$(this).width()},3000, function(){
      $("#abrir-condena").show();
      $("#cerrar-condena").hide();
    });
  });
  $("#title-poema").hide();
  $("#poema-trad").hide();
  $("#texto-condena").show();
  $("#title-condena").show();
  $("#condena-content").hover(
    function() {
      $("#texto-condena").hide();
      $("#title-condena").hide();
      $("#title-poema").show();
      $("#poema-trad").show();
    },
    function() {
      $("#title-poema").hide();
      $("#poema-trad").hide();
      $("#texto-condena").show();
      $("#title-condena").show();
  });
  $(".sitio").show(3000);
  $("#t-creditos").bind('marquee', function() {
    closing = false;
    var ob = $(this);
    ob.show();
    var ph = $("#creditos").height();
    var oh = ob.height();
    ob.css({ top: ph });
    ob.animate({ top: -oh }, 90000, 'linear', function() {
      closing = true;
      $("#creditos").slideUp(2000,function(){
        $("#copyright").slideDown(1000);
        ob.css({ top: ph });
        ob.hide();
        $(".lemming").remove();
      });
    });
  });
  $("#copyright").click(function() {
    $(this).fadeOut('fast');
    $("#creditos").center().slideDown(2000,function() {
      $(this).fadeTo(200,0.9);
      $("#t-creditos").trigger('marquee');
      Lemmings();
    });
  });
  $("#musica-on").click(function() {
    $(this).slideUp(1000, function() {
      $("#musica-off").slideDown(1000);
      $("#musica").animate({right: -5-$("#musica").width()},3000);
      document.getElementById('fmp256').playpause(0);
    });
  });
  $("#musica").show().css("right",-5-$("#musica").width());
  $("#musica-off").click(function() {
    $(this).slideUp(1000, function() {
      $("#musica-on").slideDown(1000);
      $("#musica").animate({right: 0},3000);
      document.getElementById('fmp256').playpause(1);
    });
  });
  $("#visitas").show().css("left",-15-$("#visitas").width());
  $("#visitas-img").toggle(function() {
    $("#visitas").animate({left: 0},3000,function(){
      updateVisitas();
    });
  },function(){
    $("#visitas").animate({left: -15-$("#visitas").width()},3000);
    $("#v-Lu").animate({height: 0},1000).html('');
    $("#v-Ma").animate({height: 0},1000).html('');
    $("#v-Mi").animate({height: 0},1000).html('');
    $("#v-Ju").animate({height: 0},1000).html('');
    $("#v-Vi").animate({height: 0},1000).html('');
    $("#v-Sa").animate({height: 0},1000).html('');
    $("#v-Do").animate({height: 0},1000).html('');
    $("#v-Bo").animate({height: 0},1000).html('');
    $("#v-visitas").slideUp(1000).html('');
  });
  setTimeout("checkTimer()",1000);
  setTimeout("updateTierra()",updateTime);
  setTimeout("updateSol()",updateSolTime);
  preloadLemmings();
  setupUniverso();
});

$(window).resize( function(){
  setBackground();
});

