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

var MainAssistant = Class.create({
	
	initialize : function() 
	{
		Mojo.Log.info("MainAssistant.initialize");
		/*
		var curr = new Date();
		console.log("@@@@@@@@@@@@@@@@@@@ init diff: " + (curr.getTime() - timer.getTime()));
		console.log("@@@@@@@@@@@@@@@@@@@ init total: " + (curr.getTime() - total.getTime()));
		timer = new Date();
		*/
	},

	setup: function() 
	{
		/*
		var curr = new Date();
		console.log("@@@@@@@@@@@@@@@@@@@ setup diff: " + (curr.getTime() - timer.getTime()));
		console.log("@@@@@@@@@@@@@@@@@@@ setup total: " + (curr.getTime() - total.getTime()));
		timer = new Date();
		*/
		Mojo.Log.info("MainAssistant.setup");
		
		this._gotoApp = this._gotoApp.bindAsEventListener(this);
		this._gotoTag = this._gotoTag.bindAsEventListener(this);
		this._gotoTagCloud = this._gotoTagCloud.bindAsEventListener(this);
		this._gotoTopRated = this._gotoTopRated.bindAsEventListener(this);
		this._gotoMostRecent = this._gotoMostRecent.bindAsEventListener(this);
		this._gotoFreeApps = this._gotoFreeApps.bindAsEventListener(this);
		this._gotoSearch = this._gotoSearch.bindAsEventListener(this);
		this._searchKey = this._searchKey.bindAsEventListener(this);
		this._gotoExploreTags = this._gotoExploreTags.bindAsEventListener(this);
		this._focusSearch = this._focusSearch.bindAsEventListener(this);
		
		this._searchModel = { value: '' };
	    this.controller.setupWidget(
			'in-fa-ma-search-text', 
			{
				hintText: $L('Search...'),
				focus: false,
				enterSubmits: true,
				multiline: false,
				modifierState: Mojo.Widget.steModeSentenceCase,
				focusMode: Mojo.Widget.focusInsertMode,
				requiresEnterKey: true,
				changeOnKeyPress: true,
			}, 
			this._searchModel
		);
		
		// Set up the attributes and model for the popular apps list widget
		this.controller.setupWidget(
			'dv-fa-ma-popularappslist',
			{
				itemTemplate: 'main/main-app',
				itemsCallback: this._featuredItemsCallback.bind(this),
				formatters: {
					dummy: this._formatFeaturedItem.bind(this),
				},
				onItemRendered: this._renderFeaturedItem.bind(this),
			},
			{}
		);
	
		// scrolling for palm apps list
		this.controller.setupWidget(
			'dv-fa-ma-popularappslist-scroller', 
			{}, 
			{
				mode: "horizontal"
			}
		);
		
		// Set up a command menu
		this.controller.setupWidget(Mojo.Menu.commandMenu, 
		{
			menuClass: 'no-fade', 
		}, {
			items: [
				{},
				{},
				{
	                label: $L('My Apps'),
	                command: 'myapps',
					icon: 'bag'
	            },
			],
		});
		           
		// Two things need to complete to remove the shim
		//this._shimcount = 0;
		
		// get notified when installed applications change
		Catalog.AppDownloadMngr.attach(this);
		
		// Menus
		Weave.Utilities.AppMenu.useDefault(this);
	},
	
	ready: function()
	{
		/*
		var curr = new Date();
		console.log("@@@@@@@@@@@@@@@@@@@ ready diff: " + (curr.getTime() - timer.getTime()));
		console.log("@@@@@@@@@@@@@@@@@@@ ready total: " + (curr.getTime() - total.getTime()));
		timer = new Date();
		*/
		// Look for a credit card in the background to save time later
		
		
		
	},
	
	cleanup: function() 
	{
		Catalog.AppDownloadMngr.detach(this);
		Mojo.Log.info("MainAssistant.cleanup");
	},

	activate: function() 
	{
		/*
		var curr = new Date();
		console.log("@@@@@@@@@@@@@@@@@@@ activate diff: " + (curr.getTime() - timer.getTime()));
		console.log("@@@@@@@@@@@@@@@@@@@ activate total: " + (curr.getTime() - total.getTime()));
		timer = new Date();
		*/
		
		Mojo.Log.info("MainAssistant.activate");
		
		this.controller.get('in-fa-ma-search-text').addEventListener(Mojo.Event.propertyChange, this._searchKey);
		this.controller.get('dv-fa-ma-popularappslist').addEventListener(Mojo.Event.listTap, this._gotoApp);

		this.controller.get('dv-fa-ma-tag-explore').addEventListener(Mojo.Event.tap, this._gotoExploreTags);
		this.controller.get('dv-fa-ma-tag-mostrecent').addEventListener(Mojo.Event.tap, this._gotoMostRecent);
		this.controller.get('dv-fa-ma-tag-toprated').addEventListener(Mojo.Event.tap, this._gotoTopRated);
		this.controller.get('search-button').addEventListener(Mojo.Event.tap, this._gotoSearch);
		
		this._searchModel.value = '';
		this.controller.modelChanged(this._searchModel);
		this.controller.get('search-button').style.visibility = 'hidden'; // Because changing the model doesnt fire any propertyChange events
		
		this.controller.document.addEventListener(Mojo.Event.tap, this._focusSearch);
		this.controller.get('in-fa-ma-search-text').mojo.focus();
	},

	deactivate: function() 
	{
		Mojo.Log.info("MainAssistant.deactivate");
		
		this.controller.get('in-fa-ma-search-text').removeEventListener(Mojo.Event.propertyChange, this._gotoSearch);
		this.controller.get('dv-fa-ma-popularappslist').removeEventListener(Mojo.Event.listTap, this._gotoApp);
		this.controller.get('dv-fa-ma-tag-explore').removeEventListener(Mojo.Event.tap, this._gotoExploreTags);
		this.controller.get('dv-fa-ma-tag-mostrecent').removeEventListener(Mojo.Event.tap, this._gotoMostRecent);
		this.controller.get('dv-fa-ma-tag-toprated').removeEventListener(Mojo.Event.tap, this._gotoTopRated);
		this.controller.get('search-button').removeEventListener('mouseup', this._gotoSearch);
		this.controller.document.removeEventListener(Mojo.Event.tap, this._focusSearch);
	},
	
	_featuredItemsCallback: function(widget, offset, count)
	{
		var self = this;
		Weave.Services.ApplicationServer.getFeaturedApplications(function(status, apps, papps, releaseStatus, country)
		{
			self.controller.get('popularapps-loader').style.display = "none";
			self.controller.get('dv-fa-ma-popularappslist-scroller').style.display = 'block';
			/*
			if (--self._shimcount == 0) 
			{
				Mojo.Log.info("turning off scrim");
				self.controller.get('splash-scrim').style.display = 'none';
			}
			*/
			
			if (status) 
			{
				myProfile.activationCountry = country
				Mojo.Log.info("Main-Assistant: Activation country %s", myProfile.activationCountry);
				
				// show beta banner if needed
				var disclaimerDiv = self.controller.get('palm-disclaimer');
				if (releaseStatus == "final" && disclaimerDiv.hasClassName("beta"))
				{
					disclaimerDiv.removeClassName("beta");
				}
				else if (releaseStatus == "beta" && !disclaimerDiv.hasClassName("beta"))
				{
					disclaimerDiv.addClassName("beta");
				}
		
				self.controller.get('dv-fa-ma-popularappslist').mojo.noticeUpdatedItems(0, papps);
			}
			else
			{
				// Error
				Utilities.Errors.displayError(apps);
			}
			
			if(myProfile.isEmbargoed === undefined){
			Weave.Services.PaymentServer.getEmbargoedEmailExtensions(function(status, response)
			{
				
				Mojo.Log.info("getEmbargoedCountryList %j myprofileEmail:%s", response, myProfile.email);
				if (status) {
					AppAssistant.embargoedList = response.OutGetEmbargoedEmailExtensions.embargoedEmailExtensions;
					if(myProfile.email)
					{
						var ext = myProfile.email.substring(myProfile.email.lastIndexOf(".") + 1); 
						myProfile.isEmbargoed = AppAssistant.embargoedList.indexOf(ext) != -1;
						Mojo.Log.info("Main Assistant isEmbargoed%s", myProfile.isEmbargoed);
					} 
				}
			});
			if (myProfile.validCC === undefined)
			{
				Weave.Services.PaymentServer.verifyPaymentSetup(function(status, response)
				{
					if (status && response.OutGetCCPaymentInfos.ccPaymentInfos.length > 0)
					{
						myProfile.validCC = response;
					}
				});
			}
		}
		});
	},
	
	_formatFeaturedItem: function(dummy, model)
	{
		model.formattedAverageRating = ('' + (Math.round(model.averageRating * 2) / 2)).replace(/\./, '');
		if (this._getApplicationInstalledState(model) == 'update')
		{
			model.formattedUpdateAvailable = 'has-update';
		}
		else
		{
			model.formattedUpdateAvailable = '';
		}
	},
	
	_renderFeaturedItem: function(widget, model, node)
	{
		new LazyLoadImage(model.appIcon, node.querySelector('.app-picture'));
	},

	_gotoApp: function(event) 
	{
		this.controller.stageController.pushScene("details", event.item.id, event.item.publicApplicationId);
	},
	
	_gotoExploreTags: function(event)
	{
		this.controller.stageController.pushScene("browse", undefined, false); 
	},
	
	_gotoTag: function(event)
	{
		this.controller.stageController.pushScene("search", 'tag', event.item.name);
	},
	
	_gotoTagCloud: function(event)
	{
		this.controller.stageController.pushScene("tagcloud");
	},
	
	_gotoTopRated: function(event)
	{
		this.controller.stageController.pushScene("search", "sort", "by_rating");
	},
	
	_gotoMostRecent: function(event)
	{
		this.controller.stageController.pushScene("search", "sort", "by_date");
	},
	
	_gotoFreeApps: function(event)
	{
		this.controller.stageController.pushScene("search", "sort", "PRICE_DESC");
	},

	_gotoSearch: function(event) 
	{
		this.controller.stageController.pushScene("search", "query", this.controller.get('in-fa-ma-search-text').mojo.getValue());
	},
	
	_searchKey: function(event)
	{
		if (event.originalEvent.type == 'keyup' && event.originalEvent.keyCode == Mojo.Char.enter) 
		{
			this.controller.stageController.pushScene("search", "query", event.value);
		}
		else if (event.value == '')
		{
			this.controller.get('search-button').style.visibility = 'hidden';
		}
		else
		{
			this.controller.get('search-button').style.visibility = 'visible';
		}
	},
	
	// observer method for notifications from AppDownloadMngr
	// called when apps installed on the system change 
	updateInstalledApps: function()
	{
		Mojo.Log.info("MainAssistant.updateInstalledApps");
		var mojo = this.controller.get('dv-fa-ma-popularappslist').mojo;
		if (mojo) 
		{
			var range = mojo.getLoadedItemRange();
			mojo.noticeUpdatedItems(range.offset, mojo.getItems(range.offset, range.limit));
		}
	},
	
	_getApplicationInstalledState: function(summary)
	{
		var app = Catalog.AppDownloadMngr.getInstalledApp(summary.publicApplicationId);
		if (app)
		{
			Mojo.Log.info("versions: installed %s download %s", app.installedVersion, summary.appVersion);
			if (Utilities.VersionCheck.compare(app.installedVersion, summary.appVersion) != -1)
			{
				return 'installed';
			}
			else
			{
				return 'update';
			}
		}
		return 'notinstalled';
	},
	
	handleCommand: function(event)
	{
		if (event.type == Mojo.Event.command && event.command == 'myapps') 
		{
			this.controller.stageController.pushScene("myapps"); 
		}
	},
	
	_focusSearch: function(event)
	{
		this.controller.get('in-fa-ma-search-text').mojo.focus.defer();
	}
})
