/* Copyright 2009 Palm, Inc.  All rights reserved. */

var ErrorAssistant = Class.create({
	
    initialize: function(error)
	{
		Mojo.Log.error("ERROR", error);
		this._error = error;
	},
	
    setup: function()
	{
		this.controller.document.body.removeClassName("prefs");
		switch (this._error)
		{
			case 'offline':
				this._selectError('network');
				
				// If the network is down, we wait for it to come up, then switch to the main scene.
				var self = this;
				Weave.Services.ConnectionManager.waitForOnline(function()
				{
					self.controller.stageController.popScenesTo(null);
					self.controller.stageController.pushScene('main');
				});
				ConnectionWidget.connect({ type: 'data'}, this.controller.stageController);
				break;
				
			case 'invalidtoken':
				// If we receive a bad authentication token we must inform the system
				var self = this;
				Weave.Services.AccountServices.notifyAuthenticationFailure(function()
				{
					self._selectError('badauth');
				});
				break;
				
			case 'appunavailable':
				this._selectError('appunavailable');
				break;
			case 'dplfailed':
				this._selectError('dplfailed');
				break;
				
			default:
				this._selectError('error');
				break;
		}
		
		this._showHelp = this._showHelp.bind(this);
		this._showHelpDplFailed = this._showHelpDplFailed.bind(this);
		
		// Menus
		Weave.Utilities.AppMenu.useDefault(this);
    },

	activate: function()
	{
		this.controller.get('show_help').addEventListener(Mojo.Event.tap, this._showHelp);
		this.controller.get('show_dplfailed_help').addEventListener(Mojo.Event.tap, this._showHelpDplFailed);
	},
	
	deactivate: function()
	{
		this.controller.get('show_help').removeEventListener(Mojo.Event.tap, this._showHelp);
		this.controller.get('show_dplfailed_help').removeEventListener(Mojo.Event.tap, this._showHelpDplFailed);
	},
	
	handleCommand: function(event)
	{
		if (event.type == Mojo.Event.back && this._error != 'appunavailable')
		{
			// We cannot escape this screen - let users go back
			// Event.stop(event);
		}
	},
	
	_showHelp: function() 
	{
		Weave.Services.ApplicationManager.openApplication('com.palm.app.help', 
		{
			target: 'no-network'
		});
	},
	
	_showHelpDplFailed: function() 
	{
		Weave.Services.ApplicationManager.openApplication('com.palm.app.help', 
		{
			target: 'http://help.palm.com/app_catalog/appcatalog_download_error.html'
		});
	},
	
	_errorScreens: [ 'network', 'error', 'badauth', 'appunavailable','dplfailed' ],
	
	_selectError: function(error)
	{
		for (var i = 0; i < this._errorScreens.length; i++)
		{
			var e = this._errorScreens[i];
			this.controller.get(e).style.display = (e == error ? 'block' : 'none');
		}
	}
});