;(function($){
  o3djs.require('o3djs.util');
  o3djs.require('o3djs.math');
  o3djs.require('o3djs.rendergraph');
  o3djs.require('o3djs.primitives');
  o3djs.require('o3djs.material');
  o3djs.require('o3djs.io');
  o3djs.require('o3djs.picking');
  o3djs.require('o3djs.debug');
  
  $(function(){
    var hc,wc;
    var msie = $.browser.msie;
    var ratio;
    var resized = false;
    var resize = function() {
      var hc2 = $(window).height();
      var wc2 = Math.max($(window).width(),800);
      $("#o3d").height(hc2);
    }
    $(window).resize(resize);
    resize();
    var mouseX, mouseY;
    
    var Particella = function(x, y, z, radius, col) {
      this.dx = 0;
      this.dy = 0;
      this.dz = 0;
      this.dradius = 0;
      this.rifx = 0;
      this.rify = 0;
      this.rifz = 0;
      this.vel = 30;
      this.vibracounter = 0;
      
      this.x = x;
      this.y = y;
      this.z = z;
      this.radius = radius;
      this.radius2 = radius*2;
      this.col = col;
      this.state = 0;
      this.t = null;
    };
    
    Particella.prototype = {
      setRif: function(x, y, z) {
        this.rifx = x;
        this.rify = y;
        this.rifz = z;
      },
      update: function() {
        if(Math.abs(mouseX-this.x)<20 && Math.abs(mouseY-this.y)<20) {
          if(this.state==0) {
            this.state = 1;
            this.dx = this.rifx+Math.random()*200-100;
            this.dy = Math.random()*hc;
            this.dz = 0;//Math.random()*800-400;
            
            this.vel = 30;
          } else if(this.state==1) {
            this.vibracounter = Math.round(Math.random()*20+10);
          }    
        }
        switch(this.state) {
          case 0:
            this.vibraLinea();
            break;
          case 1:
            this.vibraTutto();
            break;      
        }
        this.x += (this.dx-this.x)/this.vel;
        this.y += (this.dy-this.y)/this.vel;
        this.z += (this.dz-this.z)/this.vel;
        this.t.identity();
        this.t.translate(this.x,this.y,this.z);
      },
      vibraLinea: function() {
        if(this.vibracounter==0) {
          this.vel = 20;
          this.dx = this.rifx+Math.random()*20-10;
          this.dy = this.rify+Math.random()*20-10;
          //this.dz = this.rifz+Math.random()*20-10;
          this.vibracounter = Math.round(Math.random()*5+5);    
        }
        this.vibracounter--;
      },
      vibraTutto: function() {
        if(Math.abs(this.dx-this.x)<5 && Math.abs(this.dy-this.y)<5){
          this.state = 0;
          return;
        }
      }
      
    };
    
    var iPhone = navigator.userAgent.search(/iPhone|iPod/)!=-1;
    var numParticelle = (msie || iPhone)?50:100;
    var colori = ["#00FFFF","#FFFF00","#FF00FF"];
    var colori2 = [[0,1,1,1],[1,1,0,1],[1,0,1,1]];
    var materiale = null;
        
    var numColori = colori.length;
    var part = new Array(numParticelle);
    
    
    var creaParticelle = function(t) {
      var g_Primitives = o3djs.primitives;
      var g_Material = o3djs.material;

      materiale = g_Material.createBasicMaterial(g_pack,viewInfo,[1,1,1,1]);

      var x,y = hc/2;
      var s = g_Primitives.createSphere(g_pack,materiale,1,10,10);
      z = 0;//Math.random()*800-400;
      for(var i=0;i<numParticelle;i++) {
        var g_Transform = g_pack.createObject('Transform');
        var g_Transform2 = g_pack.createObject('Transform');
        x = Math.random()*wc;
        part[i] = new Particella(x,y,z, Math.random()*5.5+0.5, colori[Math.round(Math.random()*(numColori-1))]);
        part[i].setRif(x,y,z);
        
        g_Transform2.scale([part[i].radius,part[i].radius,part[i].radius]);
        g_Transform2.createParam("diffuse","ParamFloat4").value = colori2[Math.round(Math.random()*(numColori-1))];
        g_Transform2.addShape(s);

        g_Transform.translate(x,y,z);
        
        g_Transform2.parent = g_Transform;
        
        part[i].t = g_Transform;
        
        g_Transform.parent = t;
        
      }
    }
    
    var init = function() {
      o3djs.util.makeClients(setup);
    }
    
    var g_pack = null,
        g_o3d = null,
        viewInfo = null,
        viewInfoOrto = null,
        g_math = null,
        g_client = null,
        g_Transform = null,
        planeT = null,
        t_tab = null,
        t_ling = null,
        mousemoved = false;
    
    var mousemove = function(event) {
      mouseX = event.x;
      mouseY = hc-event.y;
      mousemoved = true;
    }

    var mousedown = function(event) {
      mouseisdown = true;
    }

    var mouseup = function(event) {
      mouseisdown = false;
    }

    
    var o3dresize = function(event) {
      wc = event.width;
      hc = event.height;
      g_Transform.identity();
      g_Transform.translate(-wc/2,-hc/2,0);
      viewInfo.drawContext.projection = g_math.matrix4.perspective(
         2*Math.atan(hc/(2*800)), // 30 degree fov.
         wc/hc,
         1,                  // Near plane.
         5000);              // Far plane.
      viewInfoOrto.drawContext.projection = g_math.matrix4.orthographic(0,wc,0,hc,1,5000);
      for(var i=0;i<numParticelle;i++) {
        part[i].rifx = Math.random()*wc;
        part[i].rify = hc/2;
        //part[i].rifz = Math.random()*2000-1000;
        part[i].t.identity();
        part[i].t.translate(part[i].rifx,part[i].rify,part[i].rifz);
      }
      planeT.identity();
      planeT.translate(150,hc/2,10);
      t_tab.identity();
      t_tab.translate(0.95*wc-213/2,oy,10);
      //Picking
      tinfo.update();        
    }
    
    var Image = function(url,t,w,h) {
      var mat_plane = o3djs.material.createMaterialFromFile(g_pack,"js/texture-only.shader",viewInfoOrto.zOrderedDrawList);
      
      var plane = o3djs.primitives.createPlane(g_pack,mat_plane,w,h,10,10,[
        [1, 0, 0, 0],
        [0, 0, 1, 0],
        [0,-1, 0, 0],
        [0, 0, 0, 1]
      ]); 
      
      var samplerParam = mat_plane.getParam('texSampler0');
      var g_sampler = g_pack.createObject('Sampler');
      samplerParam.value = g_sampler;

      var loadInfo = o3djs.io.loadTexture(g_pack,
                                    url,
                                    callback,false);

      function callback(texture, exception) {
        if (!exception) {
          g_sampler.texture = texture;
        } else {
          alert(exception);
        }
      }       
      
      t.addShape(plane);
    
    }
    
    var setup = function(clientElements) {
      var o3dElement = clientElements[0];
      g_o3d = o3dElement.o3d; 
      g_client = o3dElement.client;
      hc = g_client.height;
      wc = g_client.width;
      g_client.setEventCallback("mousemove",mousemove);
      g_client.setEventCallback("mousedown",mousedown);
      g_client.setEventCallback("mouseup",mouseup);
      g_client.setEventCallback("resize",o3dresize);
      
      g_math = o3djs.math;
      g_pack = g_client.createPack();
      viewInfo = o3djs.rendergraph.createBasicView(
          g_pack,
          g_client.root,
          g_client.renderGraphRoot);      
      // Set up a simple perspective view.
      ratio = wc/hc;
      viewInfo.drawContext.projection = g_math.matrix4.perspective(
         2*Math.atan(hc/(2*800)), // 30 degree fov.
         ratio,
         1,                  // Near plane.
         5000);              // Far plane.
      
      // Set up our view transformation to look towards the world origin where the
      // cube is located.
      viewInfo.drawContext.view = g_math.matrix4.lookAt([0, 0, 800],  // eye
                                                        [0, 0, 0],  // target
                                                        [0, 1, 0]); // up       
      
      viewInfo.clearBuffer.clearColor = [27/255, 34/255, 9/255, 1]; 
      
      viewInfoOrto = o3djs.rendergraph.createBasicView(
          g_pack,
          g_client.root,
          g_client.renderGraphRoot);      
      
      
      g_TrOrto = g_pack.createObject('Transform');
      viewInfoOrto.drawContext.projection = g_math.matrix4.orthographic(0,wc,0,hc,1,5000);
      viewInfoOrto.drawContext.view = g_math.matrix4.lookAt([0, 0, 800],  // eye
                                                        [0, 0, 0],  // target
                                                        [0, 1, 0]); // up       
      viewInfoOrto.clearBuffer.clearColorFlag = false;
      viewInfoOrto.root.priority = viewInfo.root.priority + 1;
      viewInfoOrto.zOrderedState.getStateParam('CullMode').value = o3dElement.o3d.State.CULL_NONE;
      viewInfoOrto.zOrderedState.getStateParam('ZWriteEnable').value = false;  
      
      g_Transform = g_pack.createObject('Transform');
      g_Transform.translate(-wc/2,-hc/2,0);
      
      planeT = g_pack.createObject('Transform');
      planeT.translate(225,hc/2,10);
      
      new Image("images/logo.png",planeT,150,150);
      
      planeT.parent = g_TrOrto;

      t_tab = g_pack.createObject('Transform');
      t_tab.translate(0.95*wc-213/2,-322/2+37,10);
      
      t_ling = g_pack.createObject('Transform');
      
      new Image("images/etichetta.png",t_ling,44,37);
      t_ling.translate(0,(322-37)/2-1,10);
      
      t_ling.parent = t_tab;
      
      var t_cont = g_pack.createObject('Transform');
      
      new Image("images/backgroundet.png",t_cont,213,285);
      t_cont.translate(0,(285-322)/2,10);
      
      t_cont.parent = t_tab;

      

      t_tab.parent = g_TrOrto;
      
      g_TrOrto.parent = g_client.root;
      
      creaParticelle(g_Transform); 
      
      g_Transform.parent = g_client.root;      
            
      g_client.setRenderCallback(update);
    }
    
    var closed = true;
    var opened = false
    var opening = false;
    var closing = false;
    var dy = null;
    var oy = -322/2+37;
    var tinfo = null;
    var closeTimer = null;
    var mouseisdown = false;
    
    var movetab = function() {
      //verifico se sono sulla linguetta ed è chiusa
      if(mousemoved || mouseisdown) {
        if(closed || opened) {
          var world_ray = o3djs.picking.clientPositionToWorldRay(mouseX,hc-mouseY,viewInfoOrto.drawContext,wc,hc);
          if(!tinfo) {
            tinfo = o3djs.picking.createTransformInfo(g_TrOrto,null);
            tinfo.update();        
          }
          var pickInfo = tinfo.pick(world_ray);
          if(pickInfo && pickInfo.shapeInfo.shape.clientId == t_ling.shapes[0].clientId) {
            if(closed) {
              closed = false;
              opening = true;
              dy = 322/2-10;
            } else {
              g_client.cursor = g_o3d.Cursor.POINTER;
              if(mouseisdown) {
                g_client.cursor = g_o3d.Cursor.DEFAULT;
                opened = false;
                closing = true;
                dy = -322/2+37;
                if(closeTimer) {
                  window.clearTimeout(closeTimer);
                  closeTimer = null;
                }
              }
            }
          } else {
            g_client.cursor = g_o3d.Cursor.DEFAULT;
          }
        };
        mousemoved = false;
      }
      if(opening || closing) {
        var delta = dy-oy;
        oy = oy + delta/10;
        t_tab.identity();
        t_tab.translate(0.95*wc-213/2,oy,5);
        if(delta<0.5 && delta>-0.5) {
          if(opening) {
            opening = false;
            opened = true;
            closeTimer = window.setTimeout(function(){
              opened = false;
              closing = true;
              dy = -322/2+37;
              window.clearTimeout(closeTimer);        
            },8000);
          }
          if(closing) {
            closing = false;
            closed = true;
          }
          tinfo.update();
        }
      }    
    }
    
    var update = function() {
      for(var i=0;i<numParticelle;i++) {
        part[i].update();
      }
      movetab();
    }
    
    var unload = function() {
      if (g_client) {
        g_client.cleanup();
      }
    }

    init();
    $(window).unload(unload);
    var spostaLinea = function() {
      var h = Math.random()*hc;
      for(var i=0;i<numParticelle;i++) {
        part[i].rifx = Math.random()*wc;
        part[i].rify = h;
      }
    }
    window.setInterval(spostaLinea,10000);
  }); 
})(jQuery)

