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

var PrefsAcctAssistant = Class.create({ 
	initialize: function(acctid, domain, name, login, folderid, icon, isCrud) {
		this.acctId = acctid;
		this.acctName = name;
		this.acctDomain = domain;
		this.acctLogin = login;
		this.acctFolderId = folderid;
		this.acctIcon = icon;
		this.acctIsCrud = isCrud;
	},
	
	getCalendarsForSyncAccountCallback: function(response) {
		//Mojo.Log.info('prefs-acct-assistant: getCalendarsForSyncAccount' + Object.toJSON(response));
		// Inject the color style for each calendar here
		if (response.calendars.size() == 0) {
			this.controller.get('pav_calendars_list').hide();
			this.controller.get('pav_no_calendars_msg').show();
		} else {
			var defaultCalId = getPrefsManager().getDefaultCalendar();
			this.controller.get('pav_no_calendars_msg').hide();
			this.controller.get('pav_calendars_list').show();
			response.calendars.each(function(cal){
				cal.displayDisabled = false;
				cal.hideExcludeTb = 'none';
				if (defaultCalId == cal.id) {
					// Append (Default Calendar) to the name
					var newName = cal.name + $L(' (Default Calendar)');
					cal.name = newName;
					// 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;
			}, this);
		}
		this.calsModel.items = response.calendars;
		//Mojo.Log.info('prefs-acct-assistant: getCalendarsForSyncAccount' + Object.toJSON(response));
		this.controller.modelChanged(this.calsModel);
	},
	
	renderLocalColorPicker: function() {
		var localObj = {};
		// Retrieve the color associated to the Local calendar
		localObj.colorStyle = "cal-color-" + this.localCal.color; // Do NOT Localize
		localObj.colorLabel = this.colorPicker.getColorLabel(this.localCal.color);
		// Render the color
		var localHtml = Mojo.View.render({object: localObj, template:'prefs-acct/prefs-acct-local'});
		this.controller.get('pav-local-color-picker').update(localHtml);
	},
	
	localColorPickerCallback: function(color) {
		if (this.localCal.color != color && color != undefined) {
			// Color Chip
			var localColorChip = this.controller.get('pav-local-color-chip');
			localColorChip.removeClassName("cal-color-" + this.localCal.color);
			this.localCal.color = color;
			localColorChip.addClassName("cal-color-" + this.localCal.color);
			// Color Label
			this.controller.get('pav-local-color-label').update(this.colorPicker.getColorLabel(this.localCal.color));
			this.dirty = true;
		}
	},
	
	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;
		}
	},
	
	setup: function() {
		//Mojo.Log.info("prefs-acct-assistant: setup: domain: ");
		this.dirty = false;
		
		// Render the header
		var headerObj = {};
		if (this.acctDomain == "local") {
			if (this.acctLogin == undefined || this.acctLogin == "")
				headerObj.login = $L("On Phone");
			else
				headerObj.login = this.acctLogin;
		} else if (this.acctDomain == 'eas') {
				// For EAS accounts, remove the domain name from the login
        if (this.acctLogin.indexOf('\\') > 0) {
          headerObj.login = this.acctLogin.gsub(/.*\\/, '');
        } else {
					headerObj.login = this.acctLogin;
				}
		} else {
			headerObj.login = this.acctLogin;
		}
		headerObj.serviceIcon = this.acctIcon;
		var headerHtml = Mojo.View.render({object: headerObj, template:'prefs-acct/prefs-acct-header'});
		this.controller.get('pav_header_div').update(headerHtml);
		
		if (this.acctDomain == "local") {
			// Since the Local account isn't a sync account and it only represents a single
			// calendar, build the view manually here
			this.controller.get('pav_non_local_div').hide();
			this.localCal = getCalendarsManager().getLocalCalendar();
			//Mojo.Log.info('LOCAL CAL %j', this.localCal);
			this.colorPicker = new ColorPicker(this.controller.get('pav-local-color-picker'),
											  this.localCal.color,
											  this.localColorPickerCallback.bind(this),
												this.controller);
			// Need to call this a second time so that the color label is rendered.
			// Color label is dependent on this.colorPicker being defined
			this.renderLocalColorPicker();
			
		} else {
			this.controller.get('pav_local_div').hide();
			this.controller.get('pav_no_calendars_msg').hide();
			
			// For non-Local accounts get the calendars associated with the account
			this.controller.setupWidget('pav_calendars_list', this.calListAttrs, 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'});
			
			this.getCalendarSyncAccountsRequest = getCalendarService().getCalendarsForSyncAccount(this.acctId, this.getCalendarsForSyncAccountCallback.bind(this), this.controller);
		
			// Remove Account and Change Login Settings buttons are only visible in non-local accounts
			if (this.acctIsCrud == true) {
				// If this is a Crud account hide Remove Account and Change Login Settings
				this.controller.get("pav_purge_acct_btn").hide();
				this.controller.get("pav_edit_login_btn").hide();
			} else {
				this.setupDeleteButton();
			}	
		}
	},
	
	setupDeleteButton:function(){
		this.deleteButtonModel = {
				buttonLabel:$L("Remove Account"),
				disabled:false,
				buttonClass: "negative"
			}
		this.controller.setupWidget("pav_purge_acct_btn", {type: Mojo.Widget.activityButton}, this.deleteButtonModel )
		this.deleteButton = this.controller.get("pav_purge_acct_btn");
		this.deleteButton.show();
		// Do NOT setup event observer here, should be done in activate()
	},	
	setCalendarsCallback: function(response) {
		//Mojo.Log.info('prefs-acct-assistant: setCalendarsCallback');
	},
	
	cleanup: function() {
		if (this.dirty) {
			if (this.acctDomain == "local") {
				this.calendars = [{id: this.localCal.id, color: this.localCal.color, excludeFromAll: this.localCal.excludeFromAll}];
			} else {
				// Find the dirty calendars and only add the dirty ones to the array
				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));
		}
	},
	
	handleEditLoginBtnTap: function() {
		if (this.acctDomain == 'eas') {
			var args = {
         appId: "com.palm.app.email",
         name: "create"
     	};
			
			var params = {
				edit: true,
				id: this.acctId,
				type: "calendar", 
				title: $L("Change login settings"), 
				protocol: "EAS"
			};
			
			this.controller.stageController.pushScene(args, params);
		} else {
			this.controller.stageController.pushScene("accountlogin", 
																								this.acctId, 
																								this.acctLogin,
																								0 /*acctTypeId*/,
																								this.acctIcon /*acctIcon*/, 
																								this.acctName, 
																								undefined /*sceneToReturnTo*/);
		}
	},
	
	activate: function(results) {
		if (this.acctDomain == 'local') {
			this.colorPicker.activate();
		} else {
			this.acctsListSelectionHandler = this.handleAcctsListSelection.bind(this);
			this.controller.get('pav_calendars_list').observe(Mojo.Event.listTap, this.acctsListSelectionHandler);
			this.editLoginBtnTapHandler = this.handleEditLoginBtnTap.bindAsEventListener(this);
			if (this.acctIsCrud == false) {
				this.controller.get('pav_edit_login_btn').observe(Mojo.Event.tap, this.editLoginBtnTapHandler);
				this.purgeBtnTapHandler = this.showPurgeCalendarsConfirmation.bindAsEventListener(this);
				this.deleteButton.observe(Mojo.Event.tap, this.purgeBtnTapHandler);
			}
			this.listPropertyChangeHandler = this.handleListPropertyChange.bindAsEventListener(this);
			this.controller.listen('pav_calendars_list', Mojo.Event.propertyChange, this.listPropertyChangeHandler);
		}
	},
	
	deactivate: function() {
		if (this.acctDomain == 'local') {
			this.colorPicker.deactivate();
		} else {
			this.controller.get('pav_calendars_list').stopObserving(Mojo.Event.listTap, this.acctsListSelectionHandler);
			if (this.acctIsCrud == false) {
				this.controller.get('pav_edit_login_btn').stopObserving(Mojo.Event.tap, this.editLoginBtnTapHandler);
				this.deleteButton.stopObserving(Mojo.Event.tap, this.purgeBtnTapHandler);
			}
			this.controller.stopListening('pav_calendars_list', Mojo.Event.propertyChange, this.listPropertyChangeHandler);
		}
	},
	
	// *** EVENT HANDLERS ***
	handleListPropertyChange: function(event) {
		//Mojo.Log.info("handleListPropertyChange %j", event);
		if (event.property == "displayInAll") {
			event.model.dirty = true;
		}

		this.dirty = true;
	},
	
	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
			}
		}
	},
	
	handleCommand: function(event) {
		if(event.type == Mojo.Event.command) {
			if (event.command == 'purge') {
				Event.stop(event);
				this.showPurgeCalendarsConfirmation();
				
			}
		}
	},
	
	showPurgeCalendarsConfirmation: function(){
    //Mojo.Log.info("prefs-acct-assistant: showPurgeCalendarsConfirmation");
    this.controller.showDialog({
        template: 'shared/confirm-purgeaccount',
        assistant: new PurgeAccountConfirmDialogAssistant(this),
    });
  },
	
	removeServiceCallback: function() {
		
		this.controller.stageController.popScenesTo('prefs');
	},
	
	
	yesToPurgeAccountConfirm: function() {
		
		// Go ahead and purge those calendars
		// Call service to delete calendars from this account
		
		this.deleteButton.mojo.activate();
		//this.deleteButtonModel.buttonLabel = $L("Removing Account...");
		this.deleteButtonModel.disabled = true;
		this.controller.modelChanged(this.deleteButtonModel);
		
		//stop observing list taps	
		this.controller.get('pav_calendars_list').stopObserving(Mojo.Event.listTap, this.acctsListSelectionHandler);

		//stop observing the edit login button tap

		this.controller.get('pav_edit_login_btn').stopObserving(Mojo.Event.tap, this.editLoginBtnTapHandler);
		
		getAccountsService().removeService(this.controller, this.acctId, this.removeServiceCallback.bind(this));
		
	},
		
	
	noToPurgeAccountConfirm: function() {
//		Mojo.Log.info("prefs-acct-assistant: noToPurgeAccountConfirm");
		// Don't do anything if the user wants to keep his calendars
		
		// Remove the spinner from the Remove Account button since we are not removing
		// the account
		this.deleteButton.mojo.deactivate();
	},
	
	calListAttrs : {
		itemTemplate: 'prefs-acct/prefs-acct-calendar',
	},
	
	calsModel : {
		items: [],
	}
});
