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

var PrefsOptionsAssistant = Class.create({ 
	initialize: function(accountModel) {
		this.acctsModel = accountModel;
	
	},
	
	
	calendarCategory:function(modelItem) {
		return modelItem.category;
	},	
	setup: function() {
		this.number = Math.random();
		
		this.calList =[];
		this.calsModel = {listTitle: $L('Accounts'), items:this.calList};
		this.controller.setupWidget('pav_calendars_list', 
									{
										itemTemplate: 'prefs-options/prefs-options-calendar',
										dividerTemplate: 'prefs-options/divider',
										dividerFunction: this.calendarCategory,
									},
									this.calsModel);
		
		this.colorPicker = new ColorPicker(	null,
											'blue',
											this.colorPickerCallback.bind(this),
											this.controller);
											
		this.controller.setupWidget('pav-cal-exclude-tb', {modelProperty : 'displayInAll', disabledProperty: 'displayDisabled'});
			
		
			if (this.acctsModel != null) {
				this.queryCalendarsForAccounts(this.acctsModel);
			}
			else{
				//first get the accounts list and then 
				//get the call get calendars
				getAccountsService().getAllAccountsForCalendarService(this.getCalendarAccountsCallback.bind(this), this.controller);
				
			}
	},
	getCalendarAccountsCallback: function(response) {
		//Mojo.Log.info('prefs-assistant: getCalendarSyncAccountsCallback');
	
		for(i=0;i<response.list.length;i++)
		{
				// NOTE: Account names to be localized are located in javascripts/accountLocalizations.js
				response.list[i].accountDisplayName = $L(response.list[i].accountDisplayName);
		}
		acctsModel={items:response.list};
		this.queryCalendarsForAccounts(acctsModel);
	},
	
	queryCalendarsForAccounts:function(acctsModel){
		var acctList =[];
		acctsModel.items.each(function(acct){
					acctList.push(acct.accountId);
				});
				
		getCalendarService().getCalendarsForAccountList(acctList, this.getCalendarListCallBack.bind(this), this.controller);
	},
	
	getCalendarListCallBack:function(response){
	
		this.calsModel.items =[];
		var defaultCalId = getPrefsManager().getDefaultCalendar();		
		var accounts =response.result;
		if(accounts.size()>0)
		{
			
			for(j=0;j<accounts.size();j++)
			{
				var account =accounts[j];
				var index=account.displayName.indexOf('@', 0);
				if(index>0)
					account.displayName = account.displayName.substring(0,index);
				if(account.source == "Palm Profile")
				{
					account.source = $L("Palm Profile");
				}
				var category = account.source+" "+account.displayName;
			
				var calendars =account.calendars;
				if (calendars.size() > 0) {
					for (i = 0; i < calendars.size(); i++) 
					{
						var cal = calendars[i];
						cal.displayDisabled = false;
						cal.hideExcludeTb = 'none';
						if(cal.syncSource == "Local")
						{
							cal.name = $L("Palm Profile");
						}
						if (defaultCalId == cal.id) {
							// Append (Default Calendar) to the name
							var newName = cal.name + $L(' (Default Calendar)');
							cal.name = newName;
						}
						if(defaultCalId==cal.id || cal.syncSource == "Local" )
						{
							// Disable the Display In All checkbox, since we do not
							// allow the user to exclude the default calendar from the "All
							// Calendars view"
							cal.displayDisabled = true;
							cal.showExcludeTb = 'none';
							cal.hideExcludeTb = 'inline-block';
							cal.disableExcludeTb = 'disabled';
						}
				
						cal.colorStyle = 'cal-color-' + cal.color;	// Do NOT Localize
						cal.colorLabel = this.colorPicker.getColorLabel(cal.color);
						cal.displayInAll = !cal.excludeFromAll;
						cal.category =category;
						cal.noCalStyle="display:none";
						this.calsModel.items.push(cal);
					}
				}
				else
				{
					//need to add message saying no calendars in this account
					var cal ={};
					cal.category=category;
					cal.calStyle="display:none";
					this.calsModel.items.push(cal);
				}
			}
		}
		
		
		this.controller.modelChanged(this.calsModel);
	},
	
	colorPickerCallback: function(color) {
		
		if (this.selectedCal.color != color && color != undefined) {
			this.selectedCal.color = color;
			this.selectedCal.colorStyle = 'cal-color-' + this.selectedCal.color;
			this.selectedCal.colorLabel = this.colorPicker.getColorLabel(this.selectedCal.color);
			this.controller.modelChanged(this.calsModel);
			this.selectedCal.dirty = true;
			this.selectedCal = undefined;
			this.dirty = true;
		}
	},

	cleanup: function() {
		
		this.calendars = [];
		this.calsModel.items.each(function(cal){
					if (cal.dirty) {
						this.calendars.push({id: cal.id, color: cal.color, excludeFromAll: !cal.displayInAll});
					}
				}, this);
		getCalendarService().setCalendars(this.calendars, this.setCalendarsCallback.bind(this));
	},	

   setCalendarsCallback:function(response){
   
   },
	
	activate: function(results) {
	
			this.acctsListSelectionHandler = this.handleAcctsListSelection.bind(this);
			this.controller.get('pav_calendars_list').observe(Mojo.Event.listTap, this.acctsListSelectionHandler);

			this.listPropertyChangeHandler = this.handleListPropertyChange.bindAsEventListener(this);
			this.controller.listen('pav_calendars_list', Mojo.Event.propertyChange, this.listPropertyChangeHandler);

	},
	
	deactivate: function() {
			
			this.controller.get('pav_calendars_list').stopObserving(Mojo.Event.listTap, this.acctsListSelectionHandler);
			this.controller.stopListening('pav_calendars_list', Mojo.Event.propertyChange, this.listPropertyChangeHandler);


	},
	
		
	handleAcctsListSelection: function(event) {
		
		var id = event.item.id;
		
		// Check to see if the hit was in the color picker or the checkbox
		var target = event.originalEvent.target;
		// Figure out what was hit
		while (target && !target.hasClassName('palm-row')) {
			target = target.up();
		}
		
		// Find the calendar in the list
		this.selectedCal = this.calsModel.items.find(function(cal){
			return cal.id == id;
		});
		
		if (this.selectedCal != null && this.selectedCal != undefined) {
			// Default the color picker to the selected calendar's color
			if (target.id == "pav_cal_color") {
				this.colorPicker.setSelectedColor(this.selectedCal.color);
			 	this.colorPicker.handleColorPickerClick(event);
			} else if (target.id == "pav_exclude_tb") {
				// Do Nothing
			}
		}
	},
	
	handleListPropertyChange: function(event) {
	
		//Mojo.Log.info("handleListPropertyChange %j", event);
		if (event.property == "displayInAll") {
			event.model.dirty = true;
		}

		this.dirty = true;
	}

});
