/**
 * Cloud 9
 * staalebk
 */

 THREE.Cloud = function (old) {

   THREE.Object3D.call( this );

   this.type = 'Cloud';

    var getCloudGeometry = function(x,y){
          var cloud = new THREE.BoxGeometry( x, 10,y);
          cloud.mergeVertices();
          var modifier = new THREE.SubdivisionModifier(1);
          modifier.modify(cloud);

          /* Move the vertices a bit randomly if they are at the top or bottom */
          for ( var i = 0, il = cloud.vertices.length; i < il; i ++ ) {
            var face = cloud.vertices[i];
            if(face.y < -3){
              face.setY(face.y*((Math.random()*3)+1));
            } else if(face.y > 3) {
              face.setY(face.y*((Math.random()*3)+1));
            }
          }
          return cloud;
      }

     this.cloudmaterialWF = new THREE.MeshBasicMaterial({
       color: 0x79A397,
       ambient: 0x79A397,
       emissive: 0x79A397,
       shading: THREE.FlatShading,
       wireframeLinewidth: 1.3,
       wireframe: true
     });
     
     this.cloudmaterial = new THREE.MeshLambertMaterial({
       ambient: 0x999999,
       color: 0xE4E4E4,
       emissive: 0x222222,
       shading: THREE.FlatShading
     });

   if (old)
   {
    this.cube = old.cube.clone();
    this.cube2 = old.cube2.clone();
    this.cube3 = old.cube3.clone();
   } else
   {
     
     

     var cloud = getCloudGeometry(120, 70);
     var cloud2 = getCloudGeometry(120,120);
     var cloud3 = getCloudGeometry(80,30);



   
     this.cube = new THREE.Mesh(cloud, this.cloudmaterial);
     this.cube2 = new THREE.Mesh(cloud2, this.cloudmaterial);
     this.cube3 = new THREE.Mesh(cloud3, this.cloudmaterial);
     this.cube.castShadow = true;
     this.cube2.castShadow = true;
     this.cube3.castShadow = true;
     this.cube2.rotation.y = Math.PI*Math.random();
     this.cube2.translateZ(100);
     this.cube3.translateX(80);
     this.cube3.translateZ(80);
  }

   this.add(this.cube);
   this.add(this.cube2);
   this.add(this.cube3);


   this.setWireFrame = function(doit)
   {
    if (doit)
    {
      this.cube.material = this.cloudmaterialWF;
      this.cube2.material = this.cloudmaterialWF;
      this.cube3.material = this.cloudmaterialWF;
    } else
    {
      this.cube.material = this.cloudmaterial;
      this.cube2.material = this.cloudmaterial;
      this.cube3.material = this.cloudmaterial;
    }
   }

   this.animate = function(n)
   {
    if (n>0.0001)
    {
      this.cube.visible = true;
      this.cube2.visible = true;
      this.cube3.visible = true;
      this.cube.scale.set(n,n,n);
      this.cube2.scale.set(n,n,n);
      this.cube3.scale.set(n,n,n);
    } else
    {
      this.cube.visible = false;
      this.cube2.visible = false;
      this.cube3.visible = false;
    }
   }

 };

 THREE.Cloud.prototype = Object.create( THREE.Object3D.prototype);
 THREE.Cloud.prototype.constructor = THREE.Cloud;
