var tempX = 0;
var tempY = 0;

var zoom = -10;
var _zoom = -10;

document.onmousemove = getMouseXY;

if (window.addEventListener)
        window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;

function wheel(event){
        var delta = 0;
        if (!event) event = window.event;
        if (event.wheelDelta) {
                delta = event.wheelDelta/120;
                if (window.opera) delta = -delta;
        } else if (event.detail) {
                delta = -event.detail/3;
        }
        if (delta)
                handle(delta);
}

function getMouseXY(e) {
 
    tempX = e.pageX;
    tempY = e.pageY;

    return true;
  
}

function handle(delta) {
	_zoom -= delta;
}

var rotationX = 0;
var rotationY = 0;
var finX = 0;
var finY = 0;

var previousTime = 0;

function drawScene(){

	gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

    perspective(40, innerWidth / innerHeight, 0.1, 100.0);
    loadIdentity();

    mvTranslate([0.0, 0.0, zoom])
	
	mvRotate(rotationX, [0.0, 1.0, 0.0]);
	mvRotate(rotationY, [1.0, 0.0, 0.0]);
		
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
    gl.vertexAttribPointer(vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

    /*gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
    gl.vertexAttribPointer(vertexColorAttribute, triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
*/
	gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, nekoTexture);
    gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);

	gl.bindBuffer(gl.ARRAY_BUFFER, vertexTextureCoordBuffer);
    gl.vertexAttribPointer(textureCoordAttribute, vertexTextureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
	
    setMatrixUniforms();
    gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);
	
	finX = ((tempX / innerWidth) * 360);
	finY = ((tempY / innerHeight) * 360);
	
	rotationX += (finX - rotationX) / 5;
	rotationY += (finY - rotationY) / 5;
	
	zoom += (_zoom - zoom) / 5;
	mvTranslate([0.0, 0.0, zoom]);
	
}

function setPoses(){
	finX = Math.floor(Math.random() * Width);
	finY = Math.floor(Math.random() * Height);
}

 var mvMatrixStack = [];
  function mvPushMatrix(m) {
    if (m) {
      mvMatrixStack.push(m.dup());
      mvMatrix = m.dup();
    } else {
      mvMatrixStack.push(mvMatrix.dup());
    }
  }

  function mvPopMatrix() {
    if (mvMatrixStack.length == 0) {
      throw "Invalid popMatrix!";
    }
    mvMatrix = mvMatrixStack.pop();
    return mvMatrix;
  }
  
 function mvRotate(ang, v) {
    var arad = ang * Math.PI / 180.0;
    var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
    multMatrix(m);
  }

