AccelerometerAssistant.prototype.Step = 0;
AccelerometerAssistant.prototype.Polling = false;
AccelerometerAssistant.prototype.RequestCall = undefined;
AccelerometerAssistant.prototype.RequestCallTurnOn = undefined;
AccelerometerAssistant.prototype.RequestCallTurnOff = undefined;

AccelerometerAssistant.prototype.nextImage = 
{
	1: "images/rotation1.png",
	2: "images/rotation2.png",
	3: "images/rotation3.png",
	4: "images/rotation4.png",
};


AccelerometerAssistant.prototype.angles = 
	[0, 0, Math.PI /2, Math.PI, Math.PI * 3 / 2, 0 ];

function AccelerometerAssistant()
{
	this.commandMenuItems = new Array();
	this.commandMenuModel = {
			visible:true,
			items: [{ }] 
    };
}

AccelerometerAssistant.prototype.handleCommand = function(event) {
	if(event.type == Mojo.Event.command) {
		if (event.command == Mojo.Menu.helpCmd) {
			Event.stop(event);
			var openParams = {
				target: 'http://help.palm.com/device_info/index.html'
			};
			this.controller.serviceRequest('palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					id: 'com.palm.app.help',
					params: openParams
				}
			});
		}else if (typeof this[event.command] == "function") {
			this[event.command](event);
		}
	} else if (event.type == Mojo.Event.commandEnable && 
		 (event.command == Mojo.Menu.helpCmd)) {
		event.stopPropagation();
	}
}

/************************************************************************
 * Do initial setup
 ************************************************************************/
AccelerometerAssistant.prototype.setup = function()
{
	this.controller.get('canvas').hide();
	this.controller.get('noncanvas').show();

	this.appMenuModel = {
		visible: true,
		items: [Mojo.Menu.editItem, Mojo.Menu.helpItem]
	};
	this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);
	this.commandMenuModel = {
			visible:true,
			items: [{ }] 
    }; 
	   
  
	var cmdmenuItemSkip = new Object();
    cmdmenuItemSkip.label = $L("Skip");
    cmdmenuItemSkip.command = "handleSkip";
    this.commandMenuItems.push(cmdmenuItemSkip);
	var cmdmenuItem1 = new Object();
    this.commandMenuItems.push(cmdmenuItem1);
	var cmdmenuItem2 = new Object();
    this.commandMenuItems.push(cmdmenuItem2);
	
	this.commandMenuModel.items = this.commandMenuItems;

	
    this.controller.setupWidget(Mojo.Menu.commandMenu, {}, this.commandMenuModel);
	this.controller.get('Start').observe(Mojo.Event.tap, this.handleStart.bindAsEventListener(this));
	//this.controller.get('Skip').observe(Mojo.Event.tap, this.handleSkip.bindAsEventListener(this));
	//this.controller.get('DidntRotate').observe(Mojo.Event.tap, this.handleDidntRotate.bindAsEventListener(this));

	//this.controller.get('DidntRotate').hide();

}

AccelerometerAssistant.prototype.handleStart = function()
{
	this.Step++;

	//this.turnAccelerometerOn();

	this.controller.get('image').hide();
	//this.controller.get('StartSkip').hide( );
	this.controller.get('Start').hide( );
	//this.controller.get('Skip').hide( );
	//this.controller.get('DidntRotateDiv').show( );
	//this.controller.get('DidntRotate').show( );
	if(this.commandMenuItems.length>0)
		this.commandMenuItems.pop();
		
	var cmdmenuItemDidntRotate = new Object();
    cmdmenuItemDidntRotate.label = $L("Didn't Rotate");
    cmdmenuItemDidntRotate.command = "handleDidntRotate";
    this.commandMenuItems.push(cmdmenuItemDidntRotate);
	this.commandMenuModel.items = this.commandMenuItems;
	this.controller.modelChanged(this.commandMenuModel);
	
	this.controller.get('canvas').show();
	this.controller.get('noncanvas').hide();

	this.canvasNext();
}

AccelerometerAssistant.prototype.handleSkip = function()
{
	this.controller.stageController.pushScene("complete", $L("Screen Tests"), $L("The screen tests are complete.") );
}

AccelerometerAssistant.prototype.AccelerometerGetData = function(data)
{
	//console.log("Accelerometer: AccelerometerGetData=" + Object.toJSON(data));

	if (this.Polling)
	{
		if (data == undefined || data.success === "true")
		{
			this.RequestCall = new Mojo.Service.Request('palm://com.palm.crotest', {
												method: 'Accelerometer',
												parameters: {"command": "getdata"},
												onSuccess: this.AccelerometerGotData.bind(this),
												onFailure: function() {
														console.log("Accelerometer: Failed to turn accelerometer on");
													}
												});
		}
	}
}

AccelerometerAssistant.prototype.handleDidntRotate = function()
{
	Logging.log( "Accelerometer", "Test " + this.Step + " failed" );
	this.Step++;
	this.angle = this.angles[ this.Step ];
	this.NextTest();
}

AccelerometerAssistant.prototype.NextTest = function(data)
{
	//this.controller.get('DidntRotate').show();

	// If we are passed the rotation tests then the instructions go in the instruction div, otherwise
	// they go on the canvas so we can rotate them accordingly
	if (this.Step > 4)
	{
		/*if (this.Step === 5)
		{
			this.controller.get('titleDiv').update( $L("Orientation") );
			//this.controller.get('instructions').update( $L("Lay the device face-up.  It should vibrate once.") );
			this.controller.get('image').show();
			this.controller.get('image').src = "images/orientationUp.png";
			this.controller.get('instructions').update( $L("Lay the device face-up. It should vibrate once.<br><br>Did the phone vibrate?") );
		}
		else if (this.Step === 6)
		{
			//this.controller.get('instructions').update( $L("Lay the device face-down.  It should vibrate once.") );
			this.controller.get('image').src = "images/orientationDown.png";
			this.controller.get('instructions').update( $L("Lay the device face-down. It should vibrate once.<br><br>Did the phone vibrate?") );
		}
		else if (this.Step === 7)
		{*/
			//this.turnAccelerometerOff();
			this.handleSkip();
			return;
	//	}

	//	this.controller.get('DidntRotate').update( $L("No") );

		this.controller.get('canvas').hide();
		this.controller.get('noncanvas').show();
	}
	else
	{
		this.canvasNext();
	}
}

AccelerometerAssistant.prototype.AccelerometerGotData = function(data)
{
	if (data.success !== "true")
		console.log("Accelerometer: Something went wrong!");

	//console.log("Accelerometer: AccelerometerGotData=" + Object.toJSON(data));
	//console.log("Accelerometer: Step=" + this.Step + ", data.T=" + data.T);

	var rotated = false;

	if ((this.Step == 1) && (data.T ===3)) // Right
	{
		rotated = true;
	}
	else if ((this.Step == 2) && (data.T === 5)) // Down
	{
		rotated = true;
	}
	else if ((this.Step == 3) && (data.T === 4)) // Left
	{
		rotated = true;
	}
	else if ((this.Step == 4) && (data.T === 6)) // Up
	{
		rotated = true;
	}
	else if ((this.Step == 5) && (data.T === 2)) // Face up
	{
		rotated = true;
	}
	else if ((this.Step == 6) && (data.T === 1)) // Face down
	{
		rotated = true;
	}

	if (rotated)
	{
		Logging.log( "Accelerometer", "Test " + this.Step + " success" );
		this.Step++;
		Vibrate.vibrate();
		//this.controller.get('DidntRotate').hide();

		this.angle = this.angles[ this.Step ];

		this.controller.get('noncanvas').hide();
		this.controller.get('canvas').show();
		this.canvasSuccess(  );

		setTimeout( this.NextTest.bind(this), 2000 );
	}

	if (this.Polling)
	{
		// wait 1 second and try again
		setTimeout( this.AccelerometerGetData.bind(this), 500);
	}

}

AccelerometerAssistant.prototype.turnAccelerometerOff = function()
{
	this.Polling = false;
  	this.RequestCallTurnOff = new Mojo.Service.Request('palm://com.palm.crotest', {
					                    method: 'Accelerometer',
					                    parameters: {"command": "off"},
										onSuccess: function() {
												console.log("Accelerometer: Successfully turned accelerometer off");
											},
										onFailure: function() {
												console.log("Accelerometer: Failed to turn accelerometer on");
											}
					                	});
}


AccelerometerAssistant.prototype.turnAccelerometerOn = function()
{
	this.Polling = true;
  	this.RequestCallTurnOn = new Mojo.Service.Request('palm://com.palm.crotest', {
					                    method: 'Accelerometer',
					                    parameters: {"command": "on"},
										onSuccess: this.AccelerometerGetData.bind(this),
										onFailure: function() {
												console.log("Accelerometer: Failed to turn accelerometer on");
											}
					                	});
}

AccelerometerAssistant.prototype.initializeScreen = function()
{	
	this.Step = 0;
	//this.controller.get('instructions').update( $L("Before testing rotation, please hold the phone upright.") );
	this.controller.get('instructions').update( $L("Before testing rotation, please hold the phone upright. Tap the Start button when you are ready to begin.") );
	//this.controller.get('StartSkip').show();
	this.controller.get('Start').show();
	//this.controller.get('Skip').show();
	//this.controller.get('DidntRotateDiv').hide();
	//this.controller.get('DidntRotate').hide();
	//reset the command menu buttons
	var length = this.commandMenuItems.length;
	for (var i = 0; i < length; i++) {
		this.commandMenuItems.pop();
	}
	var cmdmenuItemSkip = new Object();
    cmdmenuItemSkip.label = $L("Skip");
    cmdmenuItemSkip.command = "handleSkip";
    this.commandMenuItems.push(cmdmenuItemSkip);
	var cmdmenuItem1 = new Object();
    this.commandMenuItems.push(cmdmenuItem1);
	var cmdmenuItem2 = new Object();
    this.commandMenuItems.push(cmdmenuItem2);
	
	this.commandMenuModel.items = this.commandMenuItems;
	this.controller.modelChanged(this.commandMenuModel);
	
	this.controller.get('canvas').hide();
	this.controller.get('noncanvas').show();
	this.controller.get('image').show();
	this.controller.get('image').src = "images/uprightPhone.png";
	this.controller.get('titleDiv').update( $L("Rotation") );
}

AccelerometerAssistant.prototype.activate = function()
{
	//console.log( "Accelerometer: activate called" );
	this.initializeScreen();
}

AccelerometerAssistant.prototype.cleanup = function()
{
	//console.log( "Accelerometer: cleanup called" );
}

AccelerometerAssistant.prototype.deactivate = function()
{
	//console.log( "Accelerometer: deactivate called" );
	//this.turnAccelerometerOff();
	this.initializeScreen();
}

// Draws the next set of instructions on the canvas
AccelerometerAssistant.prototype.canvasNext = function( ) 
{
	var img = new Image();
	var devInfo = Mojo.Environment.DeviceInfo;
	img.onload = function()
	{
		var canvas = this.controller.get('canvasObj');
		var context = canvas.getContext("2d");
		context.fillStyle = "#e4e4e2";
		if (devInfo && devInfo.modelName) {
			if (devInfo.modelName === "Prē") 
				context.fillRect(0, 0, 320, 320);
			else 
				context.fillRect(0, 0, 320, 280);
		}
		
		context.save();
		if (devInfo && devInfo.modelName) {
			if (devInfo.modelName === "Prē") 
				context.translate(160, 160);
			else 
				context.translate(140, 140);
		}
		
		context.rotate(this.angle || 0);
		console.log("this.angle:"+ this.angle);
		context.font = "16px sans-serif";
		context.fillStyle = "Black";
		context.fillText( $L("Rotate the phone to the right,"), -110, 50, 100);
		context.fillText( $L("as shown above."), -110, 70);

		context.drawImage( img, -45, -120); 

		context.restore();
	}.bind(this);
	
	img.src = this.nextImage[this.Step];

	
}

// Draws the "screen rotated properly" on the canvas
AccelerometerAssistant.prototype.canvasSuccess = function( ) 
{
	var img = new Image();
	var devInfo = Mojo.Environment.DeviceInfo;
	img.onload = function()
	{
		var canvas = this.controller.get('canvasObj');
		var context = canvas.getContext("2d");
		context.fillStyle = "#e4e4e2";
		if (devInfo && devInfo.modelName) {
			if (devInfo.modelName === "Prē") 
				context.fillRect(0, 0, 320, 320);
			else 
				context.fillRect(0, 0, 320, 280);
		}
		context.save();

		if (devInfo && devInfo.modelName) {
			if (devInfo.modelName === "Prē") 
				context.translate(160, 160);
			else 
				context.translate(140, 140);
		}
		context.rotate(this.angle || 0);

		context.font = "15px sans-serif";
		context.fillStyle = "Black";
		
		context.fillText( $L("The screen updated properly."), -110, 50);
		context.drawImage( img, -70, -120 );


		context.restore();
	}.bind(this);

	img.src = "images/BigCheck.png";
}

AccelerometerAssistant.prototype.orientationChanged = function (orientation) {
	
	this.orientation = orientation;
	Mojo.Log.info("orientation" + orientation);
Logging.log( "orientation", "orientationChanged " + this.orientation + " returned" );
	var rotated = false;

	if ((this.Step == 1) && (orientation == 'right')) // Right
	{
		rotated = true;
	}
	else if ((this.Step == 2) && (orientation == 'down')) // Down
	{
		rotated = true;
	}
	else if ((this.Step == 3) && (orientation == 'left')) // Left
	{
		rotated = true;
	}
	else if ((this.Step == 4) && (orientation == 'up')) // Up
	{
		rotated = true;
	}
	/*else if ((this.Step == 5) && (orientation === 'faceUp') || (orientation == 'Face Up') || (orientation == 'faceup') || (orientation === '2') || (orientation == '2')) // Face up
	{
		rotated = true;
	}
	else if ((this.Step == 6) && (orientation == 'faceDown')) // Face down
	{
		rotated = true;
	}*/

	if (rotated)
	{
		Logging.log( "Accelerometer", "Test " + this.Step + " success" );
		this.Step++;
		Vibrate.vibrate();
		//this.controller.get('DidntRotate').hide();

		this.angle = this.angles[ this.Step ];

		this.controller.get('noncanvas').hide();
		this.controller.get('canvas').show();
		this.canvasSuccess(  );

		setTimeout( this.NextTest.bind(this), 2000 );
	}
	
}

