/*
  Language Picker

Copyright 2009 Palm, Inc.  All rights reserved.

*/
var LanguageAssistant = Class.create({
  	
	supportedLanguages: [], 
	countries: [],
	
	setup: function() {
		
		this.noAction = true;
		this.powerDownMethod = setTimeout(this.powerDownDevice.bind(this), 1000*60*5);
		
		this.getLanguagesList();    
    	
		this.languagesModel = {items:this.supportedLanguages};	   
	   	this.controller.setupWidget('languagesList', 
                  {itemTemplate:'language/language-item', listTemplate:'language/language-container'},
                 	 this.languagesModel); 
		this.selectedLanguage = this.supportedLanguages[0];
		
		this.controller.listen('languagesList', Mojo.Event.listTap, this.showCountries.bind(this));
    	
		saveCurrentState("language");
				
		this.controller.setupWidget('country-drawer', {property:'open'});
		this.controller.setupWidget('country-list', 
						     		{itemTemplate:'language/country-item', listTemplate:'language/country-container'},
									{}
						      	);	
		
		// Listen to ## key presses
		this.controller.listen(this.controller.sceneElement, Mojo.Event.keydown, FirstUseUtil.handleKeyPressEvent.bind(this));
	},
	
	powerDownDevice: function () {
		clearTimeout(this.powerDownMethod);
		if (this.noAction == true) {
			FirstUseUtil.powerDownDevice("User inactivity during firstuse");
		}
	},
	
	handleCommand: function(event) {
		var langController = this;
		if (event.type == Mojo.Event.back) {
			this.languagesModel.items.each(function(item) {	
				if (item.open == true) {
					item.open = false;
					langController.controller.modelChanged(item, langController);
				}
			});
			this.controller.get('languagesList').removeClassName('drawer-open');
			event.preventDefault();
			event.stopPropagation();
		}	
	},
	
	getLanguagesList: function() {
		this.languagesRequest = AppAssistant.accountService.getLanguages(
							this.successLanguageList.bind(this), 
							this.errorLanguageList.bind(this));	
	},
	
	successLanguageList: function (payload) {	
		
		if (!payload.locale) {
			//Wait till we get the list of languages
			return;
		}	
		
		if (this.supportedLanguages.size() > 0) {
			return;
		}	
		
		this.languagesRequest.cancel();
		
		for(var i = 0; i<payload.locale.length; i++) {
			if(this.currentLanguage && this.currentLanguage === payload.locale[i].languageCode) {
        // payload.locale[i].checkImage = "images/check.png";
				payload.locale[i].showImage = "block";
			} 
			payload.locale[i].open = false;
			countriesList = [];
			payload.locale[i].countries.each(function(item) {
				countriesList.push({
						countryName: item.countryName,
						countryCode: item.countryCode,
						checkImage: ''
					});
			});
			payload.locale[i].items = countriesList;
			this.supportedLanguages.push(payload.locale[i]);
		}
		
		// If the languages list size is greater than 4, top align the list
		if (this.supportedLanguages.size() >4) {
			this.controller.get('languagesList').toggleClassName('top-align');
		}
		
		this.controller.modelChanged(this.languagesModel, this);
	},
	
	errorLanguageList: function (payload) {
		Mojo.Log.info("Error Retrieving the languages list %o", $H(payload));	
		//TODO What to do in this case?
	},
	
	showCountries: function(event) {
		
		this.noAction = false;
		clearTimeout(this.powerDownMethod);
		this.previousLanguage = this.selectedLanguage;
		var targetRow = event.originalEvent.target;
				
		if((targetRow.hasClassName('palm-row first selected')) || 
			(targetRow.hasClassName('palm-row last selected')) ||
			(targetRow.hasClassName('palm-row selected'))) {
		
			targetRow = targetRow.down('div');		
		}
		
		if (targetRow.hasClassName('name')) {
			if(event.item) {
				this.setLocale(event.item);
			}
		}
		else if (targetRow.hasClassName('title')) {				
			if (event.item) {
				this.selectedLanguage = event.item;
				var countriesArray = this.selectedLanguage.countries;
				Mojo.Log.info("Size of countries? ---------------------------------- %s", countriesArray.size());
				if (countriesArray.size() == 1) {
					this.setLocaleWithOnlyLanguage();
					return;
				}
				if(this.previousLanguage != this.selectedLanguage) {
					this.closeDrawers();
					this.controller.modelChanged(this.previousLanguage, this);
				}			
				this.selectedLanguage.open = !(this.selectedLanguage.open);
				
				if(this.selectedLanguage.open == true) {
					this.controller.get('languagesList').addClassName('drawer-open');	
				} else {
					this.controller.get('languagesList').removeClassName('drawer-open');
				}
				
				this.controller.modelChanged(this.selectedLanguage, this);	
			}
		}	  
	},
	
	closeDrawers: function() {
		if(this.previousLanguage) {
			this.previousLanguage.open = false;
		}
	},
	
	clearPreviousSelection: function() {
		this.closeDrawers();
		this.languagesModel.items.each(function(item) {
			item.checkImage="";
			
			if(item.items) {
				item.items.each (function (country) {
					country.checkImage="";
				});
			}
		});	
	},
	
	 setLocale: function(selectedValue){
	 	
	 	this.clearPreviousSelection();
		var countryCode = selectedValue.countryCode;
		var languageCode = this.selectedLanguage.languageCode;
			
		this.controller.modelChanged(this.languagesModel, this);
		
		Mojo.Log.info("Set Locale = %s ",languageCode, "_%s", countryCode);
		
		Account.language = languageCode;
		Account.country = countryCode;
		this.countryName = selectedValue.countryName;
		this.loadCustomization();
    },
			
	setLocaleWithOnlyLanguage: function(){
		this.clearPreviousSelection();
		Mojo.Log.info("selected language = %s", this.selectedLanguage.languageCode);
		Mojo.Log.info("selected country = %s", this.selectedLanguage.countries[0].countryCode);
		Account.language = this.selectedLanguage.languageCode;
		Account.country = this.selectedLanguage.countries[0].countryCode;
    
		this.controller.modelChanged(this.languagesModel, this);
		
		Mojo.Log.info("Set Locale = %s", Account.language, "_%s", Account.country);		
		this.countryName = this.selectedLanguage.countries[0].countryName;
		
		this.loadCustomization(this);
    },
	
	
	loadCustomization: function () {
		this.controller.get('languagesList').removeClassName('drawer-open');
		Mojo.Controller.stageController.pushScene('confirmlanguage', this.selectedLanguage.languageName, this.countryName);
	},
	
	deactivate: function() {
		this.noAction = false;
		clearTimeout(this.powerDownMethod);
	},	
	
	cleanup: function () {
		delete this.languagesModel;
	}
	
	
});


