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

var RegionpickerAssistant = Class.create({
	
	initialize: function(currentRegion,currentLocale) {
		this.currentRegion = currentRegion;
		this.currentLocale = currentLocale;
		this.getCountryList();
	},
	
	setup: function() {
		this.regions = [];
		this.regionsModel = {items:this.regions};
							   
	   	this.controller.setupWidget('regionList', 
                  {itemTemplate:'regionpicker/region-item',listTemplate:'languagepicker/language-container',filterFunction: this.filterCountry.bind(this),},this.regionsModel); 
		
    	$('regionList').observe(Mojo.Event.listTap, this.showConfirmationDialog.bindAsEventListener(this));
					
		//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);
		
	},
	
	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'}}});
			}
		}
	},
	
	getCountryList: function() {
		this.langRequest = new Mojo.Service.Request("palm://com.palm.systemservice", {
			method: 'getPreferenceValues',
			parameters: {"key":"region"},
			onSuccess: function(payload) {
					if(!payload.region)
						return;
					
					for(var i = 0; i<payload.region.length; i++) {
						var obj = {};
						obj.countryCode = payload.region[i].countryCode;
						obj.countryName = $L(payload.region[i].countryName);
						obj.countryOrigName = payload.region[i].countryName;
						obj.shortCountryName = $L("Short " + payload.region[i].countryName);
						
						if(obj.shortCountryName === ("Short " + payload.region[i].countryName))
							obj.shortCountryName = payload.region[i].shortCountryName;
							
						if(this.currentRegion && this.currentRegion.countryCode === payload.region[i].countryCode) {
							obj.checkmark = "checkmark";											
						}
						
						this.regions.push(obj);
					}					
					this.regions.sort(this.compareCountry.bind(this));
					this.controller.modelChanged(this.regionsModel, this);
			}.bind(this),
			onFailure: function(payload) {
							
			}
		});
	},
	
	compareCountry: function(a,b) {
		var nameA = a.countryName.toLowerCase();
		var nameB = b.countryName.toLowerCase();
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
	},
	
		
	showConfirmationDialog: function(event) {
		
		if(!event)
			return;
		
		if(this.currentRegion.countryCode === event.item.countryCode)
			return;
				
		this.selectedCountry = event.item;
		var countryNameLabel = $L("Use #{shortCountryName}").interpolate(this.selectedCountry);
		this.controller.showAlertDialog({
	    onChoose: function(value) {
			if(value === "true") {
				this.makeChanges();
			}			
		},
	    title: $L("Change Country"),
		preventCancel:true,
	    message: $L("Are you sure you want to change your device country to #{countryName}? This will restart the phone.").interpolate(this.selectedCountry),
	    choices:[
        {label:countryNameLabel, value:"true", type:'affirmative'},  
        {label:$L('Cancel'), value:"false"}           
	    ]
	  });
	},
	
	makeChanges: function() {
		Mojo.Controller.stageController.pushScene('progress',$L('Changing Country'));
		this.setDefaultTimeFormat();
		this.setRegionalPreference.bind(this).delay(2);
	},
	
	setDefaultTimeFormat: function() {
		var format = 'HH12';
		if(this.isAmPmDefault(this.currentLocale.languageCode, this.selectedCountry.countryCode))
			format = 'HH12';
		else
			format = 'HH24';
			
		var request = new Mojo.Service.Request('palm://com.palm.systemservice', {
			method: 'setPreferences',
			parameters: {"timeFormat":format}, 			
		});
	},
	
	setRegionalPreference: function() {
		this.controller.serviceRequest("palm://com.palm.systemservice", {
			method: 'setPreferences',
			parameters: {"region":{"countryCode":this.selectedCountry.countryCode, "countryName": this.selectedCountry.countryOrigName}},
			
		});		
	},
	
	filterCountry: function(filterString, listWidget, offset, count) {
		var matching, lowerFilter;
		if (filterString) {
			lowerFilter = filterString.toLocaleLowerCase();
			function matchesName (regional) {
				return regional.countryName.toLocaleLowerCase().startsWith(lowerFilter);
			}
			matching = this.regions.findAll(matchesName);
		} else {
			matching = this.regions;
		}
		this.regionsModel.items = matching;
		listWidget.mojo.noticeUpdatedItems(0, matching);			
		listWidget.mojo.setLength(matching.length);
		listWidget.mojo.setCount(matching.length);
	},
	
	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;
	},
	
});

