/*
  Preferences - Language Picker

Copyright 2009 Palm, Inc.  All rights reserved.

*/

var LanguagepickerAssistant = Class.create({
	
	initialize: function(currentRegion, currentLocale) {
		this.resourcePath = "/usr/palm/applications/com.palm.app.languagepicker/resources/";
	   
		this.currentLocale = currentLocale;
		this.currentLanguage = '';
		this.countryCode = '';
		
		this.currentLangObj = {};
		this.locale = 'en_us';
		
		this.currentRegion = currentRegion;
		
		if(this.currentLocale)	{
			this.currentLanguage = this.currentLocale.languageCode.toLowerCase();
			this.countryCode = this.currentLocale.countryCode.toLowerCase();
			this.currentLangObj.countryCode = this.countryCode;
			this.locale = this.currentLanguage + '_' + this.countryCode;
		}
		else 
			this.getCurrentLocale();
			
		this.getLanguagesList();					
	},
		  			
	setup: function() {
		
    	this.languagesModel = {items:this.supportedLanguages};
										   
	   	this.controller.setupWidget('languagesList', 
                  {itemTemplate:'languagepicker/language-item', listTemplate:'languagepicker/language-container'},
                 	 this.languagesModel); 
		
    	$('languagesList').observe(Mojo.Event.listTap, this.showCountries.bindAsEventListener(this));
		
		this.controller.setupWidget('country-drawer', {property:'open'});
		this.controller.setupWidget('country-list', 
						     		{itemTemplate:'languagepicker/country-item'},
									{}
						      	);	
		
		//App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
	        items: [Mojo.Menu.editItem,{label:$L('Help'), command:Mojo.Menu.helpCmd}
	            ]
	        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);					
		
		this.stringTable = Mojo.Locale.readStringTable("strings.json", this.locale, this.resourcePath);			
	},
	
	cleanup: function() {
		this.supportedLanguages.splice(0);
		this.controller.modelChanged(this.languagesModel);
	},
	
	supportedLanguages: [],
	countries: [],
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if(event.command == Mojo.Menu.helpCmd) {
				new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/language/index.html'}}});
			}
		}
	},
	getLanguagesList: function() {
		this.langRequest = new Mojo.Service.Request("palm://com.palm.systemservice", {
			method: 'getPreferenceValues',
			parameters: {"key":"locale"},
			onSuccess: function(payload) {
					if(!payload.locale)
						return;
					
					for(var i = 0; i<payload.locale.length; i++) {
						countriesList = [];
						if (this.currentLanguage && this.currentLanguage === payload.locale[i].languageCode) {
							payload.locale[i].checkmark = "checkmark";
							this.currentLangObj.languageName = payload.locale[i].languageName;
						}
						for(var j = 0; j< payload.locale[i].countries.length; j++) {
							if(this.countryCode == payload.locale[i].countries[j].countryCode && this.currentLanguage === payload.locale[i].languageCode) {
								this.currentLangObj.countryName = payload.locale[i].countries[j].countryName;
								countriesList.push({
									countryName: payload.locale[i].countries[j].countryName,
									countryCode: payload.locale[i].countries[j].countryCode,						
									checkmark: "checkmark"
								});
							}
							else {
								countriesList.push({
									countryName: payload.locale[i].countries[j].countryName,
									countryCode: payload.locale[i].countries[j].countryCode,						
								});
							}
						}							
						
						payload.locale[i].items = countriesList;
						this.supportedLanguages.push(payload.locale[i]);
						this.controller.modelChanged(this.languagesModel, this);
					}		
			}.bind(this),
			onFailure: function(payload) {
							
			}
		});
	},
	
	/*
	 * Make a mojo service call to get the current locale settings.
	 */	
	getCurrentLocale: function() {
		//Make a mojo service call to get the current locale
		this.currlocaleReq = new Mojo.Service.Request("palm://com.palm.systemservice/", {
		method: 'getPreferences', 
		parameters: {"keys":["locale"]},
		onSuccess: function(payload) {
          
			if(payload.locale) {
				this.currentLanguage = payload.locale.languageCode.toLowerCase();
				this.countryCode = payload.locale.countryCode.toLowerCase();
				this.currentLangObj.countryCode = this.countryCode;
				this.locale = this.currentLanguage + '_' + this.countryCode;
				this.stringTable = Mojo.Locale.readStringTable("strings.json", this.locale, this.resourcePath);	
			}
			this.getLanguagesList();			
        }.bind(this),
		onFailure: function(payload) {
			this.locale = 'en_us';
			this.stringTable = Mojo.Locale.readStringTable("strings.json", this.locale, this.resourcePath);
			this.getLanguagesList();
		}.bind(this),
		});		
	},
	
	
	/*
	 * Show the avilable countries for the selected language.
	 */	
	showCountries: function(event) {
		
		var targetRow = event.originalEvent.target;
		
		
		if (!event.item.countries) {
			
			if(event.item) {
				this.selectedCountry = event.item;
				this.getUserConfirmation(true);				
			}
		}
		else if (event.item.countries) {
								
			if (event.item) {
				this.selectedLanguage = event.item;
				var countriesArray = this.selectedLanguage.countries;
				
				if (countriesArray.size() == 1) {
					this.closeDrawer();
					this.getUserConfirmation(false);					
					return;
				}		
				this.toggleSelection(this.selectedLanguage);
			}
		}	  
	 
	},
	
	toggleSelection: function(nowSelected) {
		this.languagesModel.items.each(function(item) {
			if(nowSelected.languageCode == item.languageCode) {
				nowSelected.open = !nowSelected.open;
			} else {
				item.open = false;
			}
		});
		this.controller.modelChanged(this.languagesModel, this);		
	},
	
	closeDrawer: function() {
		this.languagesModel.items.each(function(item) {
			item.open = false;
		});
		this.controller.modelChanged(this.languagesModel, this);		
	},
	
	clearPreviousSelection: function() {
		this.languagesModel.items.each(function(item) {
			item.checkImage="";
			
			if(item.items) {
				item.items.each (function (country) {
					country.checkImage="";
				});
			}
		});	
	},
	
	/*
	 * Sets the Locale.
	 */	
	 setLocale: function(){
      
	   if(!this.selectedLanguage)
	   	return;	
								
		var countryCode = this.selectedCountry.countryCode;
		var languageCode = this.selectedLanguage.languageCode;
		
		Mojo.Controller.stageController.pushScene('progress',this.$L('Changing Language'));
		this.setDefaultTimeFormat();
		this.setLocalePreference.bind(this,languageCode,countryCode).delay(2);	
			
    },
	
	/*
	 * Sets the Locale. This is called when the language doesn't have more than one region.
	 */
	setLocaleWithOnlyLanguage: function(){
		
		 if(!this.selectedLanguage)
	   		return;	
			
		var languageCode = this.selectedLanguage.languageCode;
		var countryCode = this.selectedLanguage.countries[0].countryCode;
		
		if(languageCode === this.currentLanguage && countryCode === this.countryCode)
			return;
			
		Mojo.Controller.stageController.pushScene('progress',this.$L('Changing Language'));
		this.setDefaultTimeFormat();	
		this.setLocalePreference.bind(this,languageCode,countryCode).delay(2);				
    },	
	
	setLocalePreference: function(languageCode, countryCode ) {
		//Set the x_palm_smartkey to turn it off for non english locale
		/*var smartkey = (languageCode+'_'+countryCode == "en_us") ? true : false;
		this.controller.serviceRequest("palm://com.palm.systemservice", {
			method: 'setPreferences',
			parameters: {x_palm_smartkey:smartkey}			
		});*/
		
		
		//Mojo Service Call to set/change the locale and wait for the response.
		this.setLocaleReq1 = new Mojo.Service.Request("palm://com.palm.systemservice", {
			method: 'setPreferences',
			parameters: {"locale":{"languageCode":languageCode,"countryCode":countryCode}},
			
		});
	},
	
	makeChanges: function(callLocaleWithCountry) {			
		if(callLocaleWithCountry)
			this.setLocale();
		else 
			this.setLocaleWithOnlyLanguage();		
	},
	
	revertChanges: function() {
		this.stringTable = Mojo.Locale.readStringTable("strings.json", this.locale, this.resourcePath);
	},
	
	setDefaultTimeFormat: function() {
		var format = 'HH12';
		if(this.isAmPmDefault(this.selectedLanguage.languageCode,this.currentRegion.countryCode))
			format = 'HH12';
		else
			format = 'HH24';
			
		this.controller.serviceRequest('palm://com.palm.systemservice', {
			method: 'setPreferences',
			parameters: {"timeFormat":format}, 			
		});
	},
	
	isAmPmDefault: function(languageCode, countryCode) {
		var formats = Mojo.Locale.readStringTable(languageCode + '_' + countryCode + '.json', '', Mojo.Locale.formatsPath);
		if (!formats || Mojo.Locale._objectIsEmpty(formats)) {
			// Fall back to using just the country code to look up formats
			formats = Mojo.Locale.readStringTable(countryCode + '.json', '', Mojo.Locale.formatsPath);
		}
		return formats && formats.is12HourDefault;
	},
	
	getUserConfirmation: function(callLocaleWithCountry) {
		
		var labelInCurrentLang;
		var labelInNewLang;
		
		var newLocale;
		if(callLocaleWithCountry) {
			if (this.selectedLanguage.languageCode.toLowerCase() === this.currentLanguage && this.selectedCountry.countryCode.toLowerCase() === this.countryCode) {
				return;
			}
			labelInCurrentLang = this.$L("Use #{languageName} (#{countryName})").interpolate(this.currentLangObj);
			newLocale =  this.selectedLanguage.languageCode + '_' + this.selectedCountry.countryCode;
		}
		else {
			if(this.selectedLanguage.languageCode.toLowerCase() === this.currentLanguage && this.selectedLanguage.countries[0].countryCode.toLowerCase() === this.countryCode)
				return;
			labelInCurrentLang = this.$L("Use #{languageName}").interpolate(this.currentLangObj);;			
			newLocale =  this.selectedLanguage.languageCode + '_' + this.selectedLanguage.countries[0].countryCode;
		}		
		
		this.stringTable = Mojo.Locale.readStringTable("strings.json", newLocale, this.resourcePath);
		
		if(callLocaleWithCountry) {
			labelInNewLang = this.$L("Use #{languageName}").interpolate(this.selectedLanguage);
			labelInNewLang += this.$L(" (#{countryName})").interpolate(this.selectedCountry);
		}
		else {
			labelInNewLang = this.$L("Use #{languageName}").interpolate(this.selectedLanguage);
		}
		
		 this.controller.showAlertDialog({
	    onChoose: function(value) {
			if(value === "true") {
				this.makeChanges(callLocaleWithCountry);
			}
			else {
				this.revertChanges();
			}
		},
	    title: this.$L("Change language"),
		preventCancel:true,
	    message: this.$L("Are you sure you want to change your device language to #{languageName}? This will restart the phone.").interpolate(this.selectedLanguage),
	    choices:[
        {label:labelInNewLang, value:"true", type:'affirmative'},  
        {label:labelInCurrentLang, value:"false"}           
	    ]
	  });
	},
	
	$L: function(str){
		return Mojo.Locale.localizeString(str, this.stringTable);
	},
	
});



