   var camera, scene, renderer;
    var effect, controls;
    var element, container;
var bigX = 410, bigZ = 320, width  = 150;
    var clock = new THREE.Clock();

var myLoc = function(x,z){
    this.x = x
    this.z = z;
};

var mesh;
var txt = document.getElementById("text");

var myArray= new Array(8);
for (var i = 0; i < 8; i++) {
  myArray[i] = new Array(16);
}

for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 8; j++) {
      myArray[i][j] = new myLoc(bigX - j * width, bigZ - i*width);
    }
}




    init();
    animate();

    function init() {
      renderer = new THREE.WebGLRenderer();
      element = renderer.domElement;
      container = document.getElementById('ThreeJS');
      container.appendChild(element);

      effect = new THREE.StereoEffect(renderer);

      scene = new THREE.Scene();

//       camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
//       camera.position.set(0, 10, 0);
//       scene.add(camera);

    var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
    var VIEW_ANGLE = 70, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
    camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
	scene.add(camera);
	camera.position.set(0,900,1000);
    //camera.lookAt(scene.position);	
    camera.lookAt(0.2,399.5,999.22);	
    
    
    
      controls = new THREE.OrbitControls(camera, element);
      controls.rotateUp(Math.PI / 4);
      controls.target.set(
       0.19766,399.5,999.159
      );
      controls.noZoom = true;
      controls.noPan = true;

      function setOrientationControls(e) {
        if (!e.alpha) {
          return;
        }

        controls = new THREE.DeviceOrientationControls(camera, true);
        controls.connect();
        controls.update();

        element.addEventListener('click', fullscreen, false);

        window.removeEventListener('deviceorientation', setOrientationControls, true);
      }
      window.addEventListener('deviceorientation', setOrientationControls, true);


     // LIGHT
	var light = new THREE.PointLight(0xffffff);
	light.position.set(-100,200,100);
	scene.add(light);
	// FLOOR
	var floorTexture = new THREE.ImageUtils.loadTexture( 'images/chess.png' );
	floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping; 
	floorTexture.repeat.set( 1, 1 );
	var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
	var floorGeometry = new THREE.PlaneGeometry(1100, 1100, 10, 10);
	var floor = new THREE.Mesh(floorGeometry, floorMaterial);
	floor.position.y = -0.5;
	floor.rotation.x = Math.PI / 2;
	scene.add(floor);
	// SKYBOX/FOG
	var skyBoxGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
	var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x9999ff, side: THREE.BackSide } );
	var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
	// scene.add(skyBox);
	scene.fog = new THREE.FogExp2( 0x9999ff, 0.00025 );
	
    
    var jsonLoader = new THREE.JSONLoader();
	jsonLoader.load( "model/king.js", addModelToScene );
    
    
    

      window.addEventListener('resize', resize, false);
      setTimeout(resize, 1);
      
      
    
    }

    function resize() {
      var width = container.offsetWidth;
      var height = container.offsetHeight;

      camera.aspect = width / height;
      camera.updateProjectionMatrix();

      renderer.setSize(width, height);
      effect.setSize(width, height);
    }

    function update(dt) {
      resize();

      camera.updateProjectionMatrix();
      //var point = new THREE.Vector3(0,0,-1);
      //console.log(point.applyMatrix4(camera.matrixWorld));
      controls.update(dt);
    }

    function render(dt) {
      effect.render(scene, camera);
    }

    function animate(t) {
      requestAnimationFrame(animate);

      update(clock.getDelta());
      render(clock.getDelta());
    }

    function fullscreen() {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      }
    }
    
    
  function addModelToScene( geometry, materials ) 
{
	var material = new THREE.MeshFaceMaterial( materials );
	mesh = new THREE.Mesh( geometry, material );
	mesh.scale.set(30,20,30);
	scene.add( mesh );
    mesh.position = new THREE.Vector3(bigX, 0, bigZ);
    
      mesh.position.z = bigZ;
      mesh.position.x = bigX;
}  
    
    
    
    

/////////////////////////////////////////////////////////////////graphics finined here 
//
//shaking 
/*
window.onload = function() {

    //create a new instance of shake.js.
    var myShakeEvent = new Shake({
        threshold: 5
    });

    // start listening to device motion
    myShakeEvent.start();

    // register a shake event
    window.addEventListener('shake', shakeEventDidOccur, false);

    //shake event callback
    function shakeEventDidOccur () {

        //put your own code here etc.
        alert('Shake!');
    }
};
*/

  function __log(e, data) {
    //log.innerHTML += "\n" + e + " " + (data || '');
    console.log(e + " " + (data || ''));
  }

  var audio_context;
  var recorder;

  function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
    __log('Media stream created.');

    // Uncomment if you want the audio to feedback directly
    //input.connect(audio_context.destination);
    //__log('Input connected to audio context destination.');
    
    recorder = new Recorder(input);
    __log('Recorder initialised.');
  }

  function startRecording() {
    recorder && recorder.record();
    //console.log("start");
    //button.disabled = true;
    //button.nextElementSibling.disabled = false;
    __log('Recording...');
  }

  function stopRecording() {
    recorder && recorder.stop();
    //button.disabled = true;
    //button.previousElementSibling.disabled = false;
    __log('Stopped recording.');
    //console.log("stop");
    // create WAV download link using audio data blob
    createDownloadLink();
    
    
    
    
    recorder.clear();
  }



function myMove(query){


    if (query.indexOf("forward") !=-1) {
        mesh.position.z -= width;
    }
    else if(query.indexOf("back") !=-1){
         mesh.position.z += width;
    }
    else if(query.indexOf("left") !=-1){
        mesh.position.x -= width;
    }
    else if(query.indexOf("right") !=-1){
        mesh.position.x += width;
    }


}



  function createDownloadLink() {
    recorder && recorder.exportWAV(function(blob) {
      var url = URL.createObjectURL(blob);
      var li = document.createElement('li');
      var au = document.createElement('audio');
      var hf = document.createElement('a');
      
      au.controls = true;
      au.src = url;
      hf.href = url;
      hf.download = new Date().toISOString() + '.wav';
      hf.innerHTML = hf.download;
      li.appendChild(au);
      li.appendChild(hf);
      //recordingslist.appendChild(li);

      var data = new FormData();
      /*jQuery.each(jQuery('#file')[0].files, function(i, file) {
        data.append('file-'+i, file);
      });*/
      //data.append('file-0', hf.download)
      data.append("file", blob);
      //alert(hf.download);
      jQuery.ajax({
        url: 'http://hacksc20152.azurewebsites.net/api/Speech/SpeechToChessMove',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
            //alert(data);

            __log(data);


            var json = JSON.parse(data);
            var query=json.query;
            __log(query);
            myMove(query);
            // alert(obj);
            
            
            
            
        }
      });
    });
    //upoad the file here
  }

var flag=false;

  window.onload = function init() {
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
      window.URL = window.URL || window.webkitURL;
      
      audio_context = new AudioContext;
      __log('Audio context set up.');
      __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
    } catch (e) {
      alert('No web audio support in this browser!');
    }
    
    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      __log('No live audio input: ' + e);
    });
    
    
    
        //create a new instance of shake.js.
    var myShakeEvent = new Shake({
        threshold: 3
    });

    // start listening to device motion
    myShakeEvent.start();

    // register a shake event
    window.addEventListener('shake', shakeEventDidOccur, false);

    //shake event callback
    function shakeEventDidOccur () {

        //put your own code here etc.
        //alert('Shake!');
        
        if(!flag){
            startRecording();
            txt.innerHTML = "Rec";

        }else{
            stopRecording();
            txt.innerHTML = "Standby";

        }flag=!flag;
        
    }
    
    window.onkeyup = function(e) {
    var key = e.keyCode ? e.keyCode : e.which;

        if (key == 32) {
                //alert('Shake!');
        
            if(!flag){
                startRecording();
                txt.innerHTML = "Rec";

            }else{
                stopRecording();
                txt.innerHTML = "Standby";

  
            }flag=!flag;
        }
    }
    
  };