/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author paulirish / http://paulirish.com/
 *
 * Modified from default:
 * - Added this.clickMove, which differentiates between mouse-looking and
 *   click-to-move.
 * - Changed camera movement in this.update() to respect wall collisions
 * - Changed this.update() to use this.noFly to disallow going up/down with R/F
 */

THREE.FirstPersonControls = function ( object, domElement ) {

	this.object = object;
	this.target = new THREE.Vector3( 0, 0, 0 );

	this.domElement = ( domElement !== undefined ) ? domElement : document;

	this.movementSpeed = 1.0;
	this.lookSpeed = 0.005;

	this.noFly = false;
	this.lookVertical = true;
	this.autoForward = false;
	// this.invertVertical = false;

	this.activeLook = true;
	this.clickMove = false;

	this.heightSpeed = false;
	this.heightCoef = 1.0;
	this.heightMin = 0.0;

	this.constrainVertical = false;
	this.verticalMin = 0;
	this.verticalMax = Math.PI;

	this.autoSpeedFactor = 0.0;

	this.mouseX = 0;
	this.mouseY = 0;

	this.lat = 0;
	this.lon = 0;
	this.phi = 0;
	this.theta = 0;

	this.moveForward = false;
	this.moveBackward = false;
	this.moveLeft = false;
	this.moveRight = false;
	this.freeze = false;

	this.mouseDragOn = false;

	if ( this.domElement === document ) {

		this.viewHalfX = window.innerWidth / 2;
		this.viewHalfY = window.innerHeight / 2;

	} else {

		this.viewHalfX = this.domElement.offsetWidth / 2;
		this.viewHalfY = this.domElement.offsetHeight / 2;
		this.domElement.setAttribute( 'tabindex', -1 );

	}

	this.onMouseDown = function ( event ) {

		if ( this.domElement !== document ) {

			this.domElement.focus();

		}
		////////////////
		
		
		var vector = new THREE.Vector3(
        renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * 2 - 1,
        - renderer.devicePixelRatio * (event.pageY - this.offsetTop) / this.height * 2 + 1,
        0.5
    );
    projector.unprojectVector(vector, cam);

    var raycaster = new THREE.Raycaster(
        cam.position,
        vector.sub( cam.position ).normalize()
    );
   var intersects = raycaster.intersectObjects(paintings);
		//console.log(intersects);
		if(intersects.length !== 0) {
			//intersects[0].object.material.color.set(0xaaeeee);
			this.temp = intersects[ 0 ].object.material.color.getHexString();
            this.name = intersects[ 0 ].object.name;
			console.log(intersects[0]);
			//$( ".text" ).empty();
            $( ".popup" ).html( "<div class='text'><p>This is the color <strong>#" + this.temp + "</strong> and the name assigned in Blender is <strong>" + this.name  + "</strong></p></div>" );
            $(".popup").show();
			//cam.position = intersects[0].object.position.clone();
			cam.position.x = intersects[0].object.position.x  - 4;
			cam.position.z = intersects[0].object.position.z  - 4;
			cam.rotation.x = intersects[0].object.roration.x;
			cam.rotation.y = intersects[0].object.roration.y;
			cam.rotation.z = intersects[0].object.roration.z;
			//console.log(intersects[0].point);
			//gal.moveBackward = true;
			
		}
	/*	
    if (intersects.length) { //alert(1);
        //cam.position = intersects[0].point;
		cam.position = intersects[0].object.position.clone();
        // Alternatively, cam.position = intersects[0].object.position.clone();
    }
	*/
	
	////////////////////
		event.preventDefault();
		event.stopPropagation();

		if ( this.clickMove ) {

			switch ( event.button ) {

				case 0: this.moveForward = true; break;
				case 2: this.moveBackward = true; break;

			}

		}

		this.mouseDragOn = true;
		
		
		/*$(this.domElement).bind("mousemove", function(event) {
			console.log('hello')
			if ( this.domElement === document ) {
	
				this.mouseX = event.pageX - this.viewHalfX;
				this.mouseY = event.pageY - this.viewHalfY;
	
			} else {
	
				this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
				this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
	
			}
		});
		
		this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );*/
		
	};

	this.onMouseUp = function ( event ) {

		event.preventDefault();
		event.stopPropagation();

		if ( this.clickMove ) {

			switch ( event.button ) {

				case 0: this.moveForward = false; break;
				case 2: this.moveBackward = false; break;

			}

		}

		this.mouseDragOn = false;
		
		/*this.domElement.removeEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
		if ( this.domElement === document ) {

			this.mouseX = 0;
			this.mouseY = 0;

		} else {

			this.mouseX = 0;
			this.mouseY = 0;

		}*/

	};

	this.onMouseMove = function ( event ) {
		console.log(event.pageX);
		if ( this.domElement === document ) {

			this.mouseX = event.pageX - this.viewHalfX;
			this.mouseY = event.pageY - this.viewHalfY;

		} else {

			this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
			this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;

		}

	};

	this.onKeyDown = function ( event ) {

		switch( event.keyCode ) {

			case 38: /*up*/
			case 87: /*W*/ this.moveForward = true; break;

			case 37: /*left*/ this.rotateLeft = true; break;
			case 65: /*A*/ this.moveLeft = true; break;

			case 40: /*down*/
			case 83: /*S*/ this.moveBackward = true; break;

			case 39: /*right*/ this.rotateRight = true; break;
			case 68: /*D*/ this.moveRight = true; break;

			case 82: /*R*/ this.moveUp = true; break;
			case 70: /*F*/ this.moveDown = true; break;

			case 81: /*Q*/ this.freeze = !this.freeze; break;

		}

	};

	this.onKeyUp = function ( event ) {

		switch( event.keyCode ) {

			case 38: /*up*/
			case 87: /*W*/ this.moveForward = false; break;

			case 37: /*left*/ this.rotateLeft = false; break;
			case 65: /*A*/ this.moveLeft = false; break;

			case 40: /*down*/
			case 83: /*S*/ this.moveBackward = false; break;

			case 39: /*right*/ this.rotateRight = false; break;
			case 68: /*D*/ this.moveRight = false; break;

			case 82: /*R*/ this.moveUp = false; break;
			case 70: /*F*/ this.moveDown = false; break;

		}

	};

	this.update = function( delta ) {
		var actualMoveSpeed = 0;
		
		if ( this.freeze ) {
			
			return;
			
		} else {

			if ( this.heightSpeed ) {

				var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
				var heightDelta = y - this.heightMin;

				this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );

			} else {

				this.autoSpeedFactor = 0.0;

			}

			actualMoveSpeed = delta * this.movementSpeed;

			if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) {
				this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
				//MovingCube.position = this.object.position;
				if (checkWallCollision(this.object.position)) {console.log('hit');
					this.object.translateZ( actualMoveSpeed + this.autoSpeedFactor );
				}
			}
			if ( this.moveBackward ) {
				this.object.translateZ( actualMoveSpeed );
				if (checkWallCollision(this.object.position)) {
					this.object.translateZ( - actualMoveSpeed );
				}
			}

			if ( this.moveLeft ) {
				//this.mouseX = -10;
				this.object.translateX( - actualMoveSpeed );
				if (checkWallCollision(this.object.position)) {
					//this.object.translateX( actualMoveSpeed );
				}
			}
			if ( this.moveRight ) {
				//this.mouseX = 10;
				this.object.translateX( actualMoveSpeed );
				if (checkWallCollision(this.object.position)) {
					this.object.translateX( - actualMoveSpeed );
				}
			}
			
			if ( this.rotateLeft ) {
				this.mouseX = -50;
				//this.object.translateX( - actualMoveSpeed );
				if (checkWallCollision(this.object.position)) {
					//this.object.translateX( actualMoveSpeed );
				}
			}
			if ( this.rotateRight ) {
				this.mouseX = 50;
				//this.object.translateX( actualMoveSpeed );
				if (checkWallCollision(this.object.position)) {
					this.object.translateX( - actualMoveSpeed );
				}
			}
			
			if (!this.noFly) {
				if ( this.moveUp ) {
					this.object.translateY( actualMoveSpeed );
					if (checkWallCollision(this.object.position)) {
						this.object.translateY( - actualMoveSpeed );
					}
				}
				if ( this.moveDown ) {
					this.object.translateY( - actualMoveSpeed );
					if (checkWallCollision(this.object.position)) {
						this.object.translateY( actualMoveSpeed );
					}
				}
			}

			var actualLookSpeed = delta * this.lookSpeed;

			if ( !this.activeLook ) {

				actualLookSpeed = 0;

			}

			this.lon += this.mouseX * actualLookSpeed;
			if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;

			this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
			this.phi = ( 90 - this.lat ) * Math.PI / 180;
			this.theta = this.lon * Math.PI / 180;

			var targetPosition = this.target,
				position = this.object.position;

			targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
			targetPosition.y = position.y + 100 * Math.cos( this.phi );
			targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
			

		}

		var verticalLookRatio = 1;

		if ( this.constrainVertical ) {

			verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );

		}

		this.lon += this.mouseX * actualLookSpeed;
		if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;

		this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
		this.phi = ( 90 - this.lat ) * Math.PI / 180;

		this.theta = this.lon * Math.PI / 180;

		if ( this.constrainVertical ) {

			this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );

		}

		var targetPosition = this.target,
			position = this.object.position;

		targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
		targetPosition.y = position.y + 100 * Math.cos( this.phi );
		targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );

		this.object.lookAt( targetPosition );
		this.mouseX = 0;   // to stop from continously rotating

	};


	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	//this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
	//this.domElement.addEventListener( 'dragstart', ( this.onMouseMove ) );
	this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
	this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
	this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
	this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
	
	/*$(document).on("dragstart", function(event) {
		console.log('hello')
	});*/
	var isDragging = false;
	var thisDomElement = this.domElement;
	var thisElem = this;
	var initX, initY;
	$(document).mousedown(function(event) {
		isDragging = true;
		initX = event.pageX;
		initY = event.pageY;
	}).mousemove(function(event) {
		if(isDragging === true)
		{
			if ( thisDomElement === document ) {

				thisElem.mouseX = (initX - event.pageX)*10;// - thisElem.viewHalfX;
				thisElem.mouseY = (initY - event.pageY)*10;// - thisElem.viewHalfY;
				initX = event.pageX;
				initY = event.pageY;
	
			} else {
				
				thisElem.mouseX = event.pageX - thisDomElement.offsetLeft - thisElem.viewHalfX;
				thisElem.mouseY = event.pageY - thisDomElement.offsetTop - thisElem.viewHalfY;
	
			}
		}
	}).mouseup(function() {
		isDragging = false;
		thisElem.mouseX = 0;
		thisElem.mouseY = 0;
	});

	function bind( scope, fn ) {

		return function () {

			fn.apply( scope, arguments );

		};

	};

};