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

var EditAssistant = Class.create({
	appMenuModel: { visible:true, 
					label:$L('Calendar'), 
					items: [ Mojo.Menu.editItem,
							{label:$L('Event Location'), items: [{label:$L('Show on map'), command:'map', disabled:false},
	                											 {label:$L('Get Directions'), command:'direction', disabled:false}] 
	                													 				
							},
							{label:$L('Delete event'), command:'deleteEvent', disabled:false},
							{label:$L('Preferences & Accounts'), command:Mojo.Menu.prefsCmd, disabled: true},
							{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}]
				  },
	
	initialize: function(targetId, targetDate, targetAllDay,calendarId,subject,forceCommit,callBackAfterUpdate) {
		this.targetId = targetId;
		this.targetModifiedTime ={start:0,end:0,id:0};
		//Mojo.Log.info('>>>>>>>>>>>>>>>>>>>>>>>>>>>>targetId ,%s',targetId);
		if(targetId)
			this.targetModifiedTime=parseFromId(targetId);
		
		this.targetDate = targetDate;	
		this.targetAllDay = targetAllDay;
		this.recurrenceRule = getRecurrenceRule();	
		if(subject)
			this.eventSubject = subject;
		else
			this.eventSubject = '';
		this.eventCalendarId =calendarId;
		this.forceCommit=forceCommit;
		this.callBackAfterUpdate =callBackAfterUpdate;
		this.formatter = getFormatterService();
		
	},
	
	renderEvent: function(response) {
		// Use the response as the event.
		var event = response;

		// Setup the event.
		this.setupEvent(event);
	},
	
	calSelector: function(e) {
		Event.stop(e);
		//Mojo.Log.info("cal selector tap listened");
    	var listItems = buildCalendarsMenu(false /*includeAll*/, false /*includeReadOnly*/, true /*includeExcludedFromAll*/);
 
	    this.controller.popupSubmenu({
	        onChoose: this.calendarChoose.bind(this),
	    		toggleCmd: this.targetEvent.calendarId.sub('id',''), 
	        // placeNear: e.target,
			  manualPlacement:true,
			  popupClass:"details-cal-selector-popup",
	        items: listItems
	    });
	},
	
	calendarChoose: function(value) {
		if(value=="viewOptions")
		{
				this.controller.stageController.pushScene("prefs-options",this.acctsModel);
				return;
		}
		this.targetEvent.dirty =true;
		if(this.targetEvent && value!=undefined)
			this.updateContentCalendarType(value);
	},
	
	updateContentCalendarType:function(calid){
		if(calid == null)
			calid =getCurrentCal();
			var calMgr = getCalendarsManager();
			
			var calcolor = calMgr.getCalColorStyle("id" + calid);
			var calType = calMgr.getCalAccountName("id"+calid)+"</span>";
			
			var syncSource = calMgr.getCalSyncSource("id"+calid);
			// Special case the local calendar to always show Palm since Palm Profile always
			// gets truncated and looks ugly
			if (syncSource == "Local") 
				calType = $L('Palm')+"</span>";
			
			var button = Mojo.View.render({
				object: {
					text: calType
				},
				template: "edit/popupButton"
			});
			this.controller.get('edit_calendartype').update(button);
			if (this.targetEvent) {
				this.controller.get('edit-details').removeClassName(this.targetEvent.calendarColor);
				this.targetEvent.calendarColor = calcolor;
				this.targetEvent.calendarId = "id" + calid;
			}
			this.controller.get('edit-details').addClassName(calcolor);
			
	},
	updateReadOnly:function(){
		this.controller.get('edit_datetimerow').stopObserving(Mojo.Event.tap,this.edit_infoHandler );
		this.controller.get('edit_repeatrow').stopObserving(Mojo.Event.tap, this.edit_repeatHander);
		this.controller.get('edit_alarmrow').stopObserving(Mojo.Event.tap, this.edit_alarmHandler);	
		this.controller.get('edit_calendartypeParent').stopObserving(Mojo.Event.tap,this.event_calendarTypeHandler );
		
	},
	
	renderGetEvent: function(response) {
    	//Mojo.Log.info("edit-assistant:renderGetEvent");
		//first copy it into an old event variable
		//the reason we are doing this is to avoid unnecessary saves
		//while exiting scenes. we'll compare targetevent against this to see if anything changed.
		//this.oldEvent is updated whenever a setEvent confirmation response comes frmo
		//service because then we the values in the event are already in the activerecord
		this.setUpWidgetListeners();
		this.oldEvent = Object.clone(response);
		
		//we need to do this otherwise while checking against oldevent,
		//the end validity in old event is some long value for never-ending
		//recurrences while in the targetEvent it is deliberately set to
		//"Long.MAX_VALUE"
		if(this.oldEvent.isRecurringForever)
		{
			this.oldEvent.endValidity= "Long.MAX_VALUE";
		}
		
		// Use the response as the event.
		this.targetEvent = response;
		
		if(this.forceCommit && this.targetEvent)
			this.targetEvent.dirty =true;
		
		// Setup the event.
		this.setupEvent();
		this.renderGetEventAttendees();
		
		//this.requests.push(this.service.getEventAttendees(this.targetId,this.renderGetEventAttendees.bind(this),this.controller));
		
	},
	renderGetFailed:function(){
		this.controller.showDialog({
				template: 'shared/invalidEvent_warning',
				assistant: new InvalidEventWarning(this),
				preventCancel: true
			});
	},
	renderGetEventAttendees:function(){
		this.targetEventAttendees={};
		this.targetEventAttendees.attendees = this.targetEvent.attendees;
		this.targetEventAttendees.organizer =this.targetEvent.attendees.organizer;
		console.info("renderGetEventAttendees---"+this.targetEventAttendees.organizer);
		if (this.targetEventAttendees.attendees.size() > 1) {
			//show the div
			//populate the values
			
			this.controller.get('edit_participantrow').show();
			this.controller.get('edit_participants').update(Mojo.View.render({
				template: 'edit/edit_participants',
				object: {
					organizer: this.targetEventAttendees.organizer,
					num: this.targetEventAttendees.attendees.size()
				}
			}));
		}

	},
	
	renderSetEvent: function(response) {
		//Mojo.Log.info("*********************edit-assistant:renderSetEvent: ");
		this.targetEvent.id = response.id;
		this.targetEvent.pendingSave =false;
		if (this.targetEvent.pendingPop) {
			
			this.targetEvent.pendingPop = false;
			this.requests.push(this.service.setEvent(this.targetEvent, this.setEventCallBack, this.controller));
			if(this.callBackAfterUpdate !=undefined)
				this.callBackAfterUpdate(this.targetId);
			this.controller.stageController.popScene("edit");
		}
		
		//if neither of the above cases are true, we just set the id 
		// and do nothing.
		
	},

	deletedEvent: function(response) {
		//Mojo.Log.info("edit-assistant:deletedEvent");
		//this will remove the snooze reminder if any scheduled and
		//will also remove the event from the reminders list
		this.deletedEventHandle();
		
	},
	
	renderEventInfo: function(response) {
		
		this.updateEventInfo(response);
	},
		
	updateCustomLabel:function(){
		//Mojo.Log.info("edit-assistant:custom label");
		var tag;
		var template = new Template("#{freq}");
		var templateModel = {};
		
		if (this.repeatFreqChoice == 5) {
			switch (this.targetEvent.rruleModel.frequency) {
				case 'DAILY':
					templateModel.freq = $L('Custom Daily Repeat');
					break;
					
				case 'WEEKLY':
					templateModel.freq = $L('Custom Weekly Repeat');
					break;
					
				case 'MONTHLY':
					templateModel.freq = $L('Custom Monthly Repeat');
					break;
					
				case 'YEARLY':
					templateModel.freq = $L('Custom Yearly Repeat');
					break;
			}
			this.repeatOptions[this.repeatFreqChoice-1] = template.evaluate(templateModel);
		}
	},	
	
	renderRepeatStrings: function(response) {
		//Mojo.Log.info("edit-assistant:renderRepeatStrings");
		this.repeatOptions = response;
		//we dont want to enable repeat for read only events
		//and exception of a series
		
		if(!this.isReadOnlyEvent && ( !this.targetEvent.parentId || this.targetEvent.parentId<=0))
			this.controller.get('edit_repeatrow').observe(Mojo.Event.tap, this.edit_repeatHander);
		
		//for the custom option alone we see if this is checked currently and if it is we update the label
		this.updateCustomLabel();
		
		this.updateRepeatButton(this.repeatOptions[this.repeatFreqChoice-1],this.repeatFreqChoice);
	},
	
	renderAlarmStrings: function(response) {
		
		this.alarmOptions = response;
		if (!this.isReadOnlyEvent)
			this.controller.get('edit_alarmrow').observe(Mojo.Event.tap, this.edit_alarmHandler);	
		this.updateAlarmButton(this.alarmOptions[this.selectedAlarmOption-1]);
	
	},
	
	updateEventInfo: function(info) {
		Mojo.Log.info("updateEventInfo");
		var stylingClass = "all-day-single";
		if (info.type == stylingClass) {
			this.controller.get('edit_info').addClassName(stylingClass);
		}
		else {
			this.controller.get('edit_info').removeClassName(stylingClass);
		}
		
		var button = Mojo.View.render({object: {text: info.value}, template: "edit/infoButton"});
		//first set the styling for this formatting.
		
		this.controller.get('edit_info').update(button);
	},
		
	updateRepeatButton: function(option,value) {
	    this.repeatFreqChoice = value;
		

		var button = Mojo.View.render({object: {text: option, buttonId: 'repeatButton'}, template: "edit/popupButton"});
		this.controller.get('edit_repeat').update(button);
	},

	updateAlarmButton: function(option) {
	
		
	
		var button = Mojo.View.render({object: {text: option, buttonId: 'alarmButton'}, template: "edit/popupButton"});
		this.controller.get('edit_alarm').update(button);
	},
	
	repeats:['never','daily','weekday','weekly','custom'], //do not localize
	
	
  
    processSetUp:function(){
		//Mojo.Log.info("in Processsetup");
		this.isReadOnlyEvent = getCalendarsManager().isCalendarReadOnly(this.targetEvent.calendarId);
		if (this.isReadOnlyEvent == true) {
			Mojo.Log.info("%%%%%%%%%% this is a read only event");
			this.updateReadOnly();
			this.subjectmodel.disabled=true;
			this.locationmodel.disabled=true;
			this.notemodel.disabled=true; 
		}
		
		// Delete event menu item.  Users can delete new and existing events
		if(!this.isReadOnlyEvent)
			this.appMenuModel.items[2].disabled = false;   
		else
			this.appMenuModel.items[2].disabled = true; 
	
		// Map location menu item
		if (!this.targetEvent.location || this.targetEvent.location == "") {
			this.appMenuModel.items[1].items[0].disabled = true;
			this.appMenuModel.items[1].items[1].disabled = true;
		}
		else {
			this.appMenuModel.items[1].items[0].disabled = false;
			this.appMenuModel.items[1].items[1].disabled = false;
		}
			
		this.controller.modelChanged(this.appMenuModel);	    
    	
		if(this.targetEvent.parentId >0)
			//we should not let change repeat
			this.controller.get('edit_repeatrow').stopObserving(Mojo.Event.tap, this.edit_repeatHander);
		
		if (this.targetEvent.subject) {
			//if(!this.isReadOnlyEvent)
				//this.controller.get('edit_note').mojo.focus();
			
			if(this.eventSubject){
				//this is the case when day scene passed a subject 
				//to the edit details scene
				this.targetEvent.subject=this.eventSubject;
				this.eventSubject =null;
				//this.targetEvent.dirty=true;
			}
			this.subjectmodel.subject=this.targetEvent.subject;			
		}
		else {
			this.subjectmodel.subject = "";
			if(this.targetEvent.id>0)
				this.controller.get('edit_subject_field').mojo.focus();		
		}
		if (this.targetEvent.location) 
			this.locationmodel.location = this.targetEvent.location;
		else 
			this.locationmodel.location = "";
		if (this.targetEvent.note) 
			//this.notemodel.note = this.targetEvent.note;
			this.editnotediv.mojo.value = this.targetEvent.note;
		else 
			//this.notemodel.note = "";
			this.editnotediv.mojo.value = '';
		
		this.controller.modelChanged(this.locationmodel);
		this.controller.modelChanged(this.subjectmodel);
		this.controller.modelChanged(this.notemodel);
		
		if (this.targetEvent.alarm == undefined)
			this.targetEvent.alarm = "none";
		
		this.updateCalendarTypeInfo(this.targetEvent.calendarId);
	},
	
	setupEvent: function() {
	
		Mojo.Log.info("edit-assistant:setupEvent");
		this.updateFromRecurrenceModel();
		this.processSetUp();
		
		var date;
		
		if (this.targetModifiedTime.start == 0 || this.targetModifiedTime.end == 0) {
			//this is just in case we do not get the parsed start and end from the eventid 
			//passed to this scene
			startt = new Date(this.targetEvent.startTimestamp);
			if (this.targetDate) 
				date = this.targetDate;
			else 
				date = getCurrentDateTime();
			date.setHours(startt.getHours());
			date.setMinutes(startt.getMinutes());
			date.setSeconds(startt.getSeconds());
			this.targetModifiedTime.start = date.getTime();
			this.targetModifiedTime.end = this.targetModifiedTime.start + (this.targetEvent.endTimestamp - this.targetEvent.startTimestamp);
			this.targetEvent.alldayReservedStartTimestamp = this.targetModifiedTime.start;
			this.targetEvent.alldayReservedEndTimestamp = this.targetModifiedTime.end;
		}		
		
		this.renderEventInfo(this.formatter.getDateFormatted(this.targetModifiedTime.start, this.targetModifiedTime.end, this.targetEvent.allDay, getTimeFormat()))	;
	
		this.renderRepeatStrings(this.formatter.getRepeatStrings(this.repeats));
		if (this.targetEvent.allDay) {
			this.alarms = this.alarmType.alarmsAllday;
		}
		else 
			this.alarms = this.alarmType.alarmsTimed;
	
		this.alarms.list.each(function(thing){
			if(thing==this.targetEvent.alarm){
				this.selectedAlarmOption=this.alarms.list.indexOf(thing)+1;
			}
		},this);
				
		if (!this.selectedAlarmOption && this.targetEvent.alarm && this.targetEvent.alarm != "") {
			
			this.selectedAlarmOption = 1;
			//push the custom element to the first entry on array
			this.alarms.list.unshift(this.targetEvent.alarm);
		}		
		this.renderAlarmStrings(this.formatter.getAlarmStrings(this.alarms.list));	
		this.updateContentCalendarType(this.targetEvent.calendarId.sub('id',''));
	},
	updateCalendarTypeInfo:function(calendarId){
		if (calendarId) {
			Mojo.Log.info("*************"+calendarId);
			calid = calendarId.sub('id', '');
			calendarColor = getCalendarsManager().getCalColorStyle(calid);
			
			this.controller.get('edit-details').addClassName(calendarColor);
		}
	},
	
	
	blurStageBound:function(){
		//Mojo.Log.info("&&&&&&&&&&&&&&&&&&&&&&&&entered here into blur stage");
		//this will send a Mojo.propertychanged on fields
		//which have changed
		this.controller.commitChanges();
		
		// update selections in the recurrence field
		//into our recurence model
		this.updateRecurrenceModel();
		
		if (this.checktargetEventDirty()){
			
				Mojo.Log.info("saving the current event");
				this.saveEvent(0, true);	

		}
	},		
	setup: function() {
		
		var subjecthinttext=$L('Event name');
		this.alarmType= {
			alarmsTimed: {
				list: [	 'none', // Do NOT Localize
						 '-PT0M', //DO NOT Localize
						 '-PT5M', // Do Not Localize
						 '-PT10M', //Do not localize
						 '-PT15M', // Do NOT Localize
						 '-PT30M', // Do NOT Localize
						 '-PT1H', // Do NOT Localize
						 '-P1D' // Do NOT Localize
						]
						},
			alarmsAllday: {
				list: [ 'none', // Do NOT Localize
						'-PT0M',// DO NOT Localize
	 					'-P1D', // Do NOT Localize
	 					'-P2D', // Do NOT Localize
	 					'-P3D', // Do NOT Localize
	 					'-P1W', // Do NOT Localize
					 ]
					}
		};
		
		//Mojo.Log.info("edit-assistant:setup");		
		this.editview = $('edit_view');
		
		this.blurStage = this.blurStageBound.bind(this);

		//we hide this div initially since we do not k now if the participants list
		//is populated already
		this.controller.get('edit_participantrow').hide();
	
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, this.appMenuModel);
		
		this.service = getCalendarService();
		this.requests = [];
        
        //for date/time div
	 	var button = Mojo.View.render({object: {text: ("")}, template: "edit/infoButton"});
		this.controller.get('edit_info').insert(button);
		this.edit_infoHandler = this.handleEditInfo.bind(this);
		
		//for participants div
		var button = Mojo.View.render({object: {text: ("")}, template: "edit/edit_participants"});
		this.controller.get('edit_participants').insert(button);
		this.edit_participantHandler = this.handleEditParticipants.bind(this);
		
		//for calendar picker
		var button=Mojo.View.render({object:{buttonId:'typeButton'},template: "edit/popupButton"});
		this.controller.get('edit_calendartype').insert(button);
		this.event_calendarTypeHandler= this.calSelector.bindAsEventListener(this);
		
		this.edit_repeatHander=this.handleEditRepeat.bind(this);
		this.edit_alarmHandler = this.handleEditAlarm.bind(this);
		
		var subject = (this.eventSubject)?this.eventSubject:'';
		//for subject
		var tfAttrs1 = {
			modelProperty: 'subject',
			hintText: subjecthinttext,
			focus: false,
			multiline:true,
			textFieldName: 'edit_subject_area',
			acceptBack:true,
			runTextLinker:true
		};
		 this.subjectmodel = {
      		'subject' : subject,
   		 };
		this.controller.setupWidget('edit_subject_field', tfAttrs1, this.subjectmodel);

		//for location
		var tfAttrs2 = {
			modelProperty: 'location',
			hintText: $L('Event location'),
			acceptBack:true,
			runTextLinker:true
	
		};
		 this.locationmodel = {
      		'location' : '',
   		 };
		this.controller.setupWidget('edit_location_field', tfAttrs2, this.locationmodel);
		
		//for notes
		/*var tfAttrs3 = {
			modelProperty: 'note',
			hintText: $L('Event notes'),
			multiline: true,
			acceptBack:true
		};
		 this.notemodel = {
      		'note' : '',
   		 };
		this.controller.setupWidget('edit_note', tfAttrs3, this.notemodel);*/
		this.notemodel ={hintText: $L('Event notes')};
		this.editnotediv = this.controller.get('edit_note');
		this.controller.setupWidget('edit_note', {multiline: true, emoticons: true,runTextLinker: true},this.notemodel );
	
		
		// If the targetId is not 0, get the event's details by calling the service.
		// Otherwise create a new create and set the event's default values.
		if (this.targetId != 0) {
			this.controller.setInitialFocusedElement(null);
			if (this.service.getEvent) {
				this.requests.push(this.service.getEvent(this.targetId, this.renderGetEvent.bind(this), this.renderGetFailed.bind(this),this.controller));
			}
		} 
		else {
			// Create a new event.
			var event = new CalendarEvent();
		
			subjecthinttext =$L('Event name');
			// If a targetDate was supplied, use that.			
			// Otherwise use the current date as the default date/time.
			var start;
			if (this.targetDate != 0) {
				start = new Date(this.targetDate);
				
				// Clear the minutes, seconds, and ms's.
				start.set({	minute: 0, second: 0, millisecond: 0 });
			} else {
				// Use the current date and time maintained by the calendar... Users will
				// most likely want to create events on the day they are currently looking
				// at (and not just today)
				start = getCurrentDateTime();
				
				if (start.getMinutes() > 30) {
					start.set({	minute: 30, second: 0, millisecond: 0 });
				} else {
					start.set({	minute: 0, second: 0, millisecond: 0 });
				}
			}
					
			// Set the start time and end time.
			event.startTimestamp = start.getTime();
			event.endTimestamp =  start.addMinutes(getPrefs().defaultEventDuration).getTime();
			event.endValidity = 0;
			
			//save start and end time in case the user toggles allday off again
			event.alldayReservedStartTimestamp = event.startTimestamp;
			event.alldayReservedEndTimestamp = event.endTimestamp;
					
			if (this.targetAllDay == true) {
				event.allDay = true;
				var alldayTime = new Date(event.startTimestamp);
			
				//set event's start to 00:00:00	
				alldayTime.set({	hour: 0, minute: 0, second: 0, millisecond: 0 });
				event.startTimestamp = alldayTime.getTime();
				this.targetModifiedTime.start = alldayTime.getTime();
				
				//set end to 23:59:59
				alldayTime.set({	hour: 23, minute: 59, second: 59, millisecond: 0 });
				event.endTimestamp = alldayTime.getTime();
				this.targetModifiedTime.end = alldayTime.getTime();			
			}
			else 
				event.allDay = false;
			
			if (event.allDay == false) {
				// Only set the default alarm setting for timed events
				event.alarm = getPrefs().defaultEventReminder;
			}else{			
				event.alarm =getPrefs().defaultAllDayEventReminder;			
			}
			
			// Create an event in the currently selected calendar.  If
			// ALL calendars are displayed then we create an event in the 
			// default calendar (specified by a preference)
			if (getCurrentCal() == 'all') {
				// Create an event in the calendar specified by the defaultCalId preference
				var defaultCalId = getPrefsManager().getDefaultCalendar();
				
				event.calendarId = 'id'+defaultCalId;
				
			} else {
				// If a specific calendar is being displayed, create an
				// event in that calendar
				event.calendarId = 'id'+getCurrentCal();
								
			}
			event.subject = this.eventSubject;
			this.updateCalendarTypeInfo(event.calendarId);
			event.parentId = 0;
			
			// Set the event.
			this.targetEvent = event;
		
			this.targetEvent.rruleModel = Object.clone(recurrence_model);
			
			this.setUpWidgetListeners();
			
			//we do this because even if nothing is changed in the
			//edit scene, if there was a subject passed from day scene
			//we have to save the event
			
		
		}
		//we use this for call back while doing setEvent from datetime scene and
		//custom repeat scenes
		this.setEventCallback = this.renderSetEvent.bind(this);
		
		if(this.forceCommit && this.targetEvent)
			this.targetEvent.dirty =true;
		if (this.eventCalendarId) {
			this.updateContentCalendarType(this.eventCalendarId.sub('id',''));
		}
	 },
	 
	 setUpWidgetListeners: function(){
	 	
	 
		this.controller.get('edit_datetimerow').observe(Mojo.Event.tap,this.edit_infoHandler );
	
		this.controller.get('edit_participantrow').observe(Mojo.Event.tap,this.edit_participantHandler );
		
		this.controller.get('edit_calendartypeParent').observe(Mojo.Event.tap,this.event_calendarTypeHandler );
		
		this.controller.get('edit_subject_field').observe(Mojo.Event.propertyChange, this.subjectChanged.bind(this));
		
		this.controller.get('edit_location_field').observe(Mojo.Event.propertyChange, this.locationChanged.bind(this));
		
		this.controller.get('edit_note').observe(Mojo.Event.propertyChange, this.noteChanged.bind(this));
	
	 },
	 handleCommand: function(event) {
		if(event.type == Mojo.Event.command) {
			if(event.command == 'deleteEvent') {
				Event.stop(event);
				this.deletedeventId = this.targetEvent.id;
				this.handleDelete(event);
			} else if (event.command == Mojo.Menu.prefsCmd) {
				Event.stop(event);
				this.controller.stageController.pushScene('prefs');
			}else if(event.command =='copy'){
				//@todo
			}else if(event.command == Mojo.Menu.helpCmd){
				getAppManagerService().launchHelp(this.controller);
			} else if(event.command == 'map'){
				getAppManagerService().launchMaps(this.controller,this.targetEvent.location,false);
			}else if(event.command == 'direction'){
				getAppManagerService().launchMaps(this.controller,this.targetEvent.location,true);								
			}
		}
		else if(event.type == Mojo.Event.commandEnable && event.command == Mojo.Menu.prefsCmd) {
			// Enable prefs menuitem for this scene.
			Event.stop(event);
		}else if(event.type == Mojo.Event.back){
			//Mojo.Log.info("***************Got event back in the app");
			// Sanity check the settings here... If any are invalid, we stop the Back
			// command
			if (this.targetEvent.dirty != true) {
				//this is the case when nothing
				//was changed in the view. 
				//Mojo.Log.info("nothing changed ......")
	
					
				return;
			}
			else 		
				this.handleSave(event);							
		}
	},
	
	noteChanged: function(e) {
		this.targetEvent.dirty =true;
		
			 if(e.value!=null)
			this.targetEvent.note = e.value;
		else
			this.targetEvent.note = "";
		
	},
	
    
	subjectChanged: function(e) {
		
		this.targetEvent.dirty =true;
			 if(e.value!=null)
			this.targetEvent.subject = e.value;
		else
			this.targetEvent.subject = "";
		
	},
	
	locationChanged: function(e) {
		this.targetEvent.dirty =true;
		Mojo.Log.info("edit-assistant:locationChanged");
		
		 if (e.value != null && e.value!="") {
		 	this.targetEvent.location = e.value;
		 	this.appMenuModel.items[1].items[0].disabled = false;
			this.appMenuModel.items[1].items[1].disabled = false;
			
		 }
		 else {
		 	this.targetEvent.location = "";
			this.appMenuModel.items[1].items[0].disabled=true;
			this.appMenuModel.items[1].items[1].disabled=true;
			
		 }
		 this.controller.modelChanged(this.appMenuModel);
		 
			
	},
  
  saveEvent: function(parentId,inCardMode){
  		
		//Mojo.Log.info("edit-assistant:saveEvent");
		if(this.targetEvent.subject=="" || this.targetEvent.subject==null) {
			if(this.targetEvent.id > 0)
				this.targetEvent.subject =$L("Event name");
			else
			   	this.targetEvent.subject =$L("New event");
		}
		if (parentId > 0) {
			//this is the case where we are trying to make an exception
			
			this.targetEvent.parentId =parentId;
			this.targetEvent.id=-1;
			this.targetEvent.rrule='';
			this.targetEvent.exdates= '';
			this.targetEvent.rruleModel = null;
				
			//we also need to assign the start and end time stamp to 
			//targetModifiedTime because we want an exception in the current date
			this.targetEvent.startTimestamp=this.targetModifiedTime.start;
			this.targetEvent.endTimestamp=this.targetModifiedTime.end;
			this.targetEvent.originalstartTimestamp =this.targetEvent.startTimestamp;
			this.targetEvent.endValidity =0;
		}
		else if(parentId <=0 && this.targetEvent.isRecurringForever==true)
			//we need to do this because if the end validity returned from the 
			//service is a long value, it seems to get truncated when retuned to 
			//JS layer and hence while setting it back 
			this.targetEvent.endValidity = "Long.MAX_VALUE"; 
			
			//instead of adding the exdates separately here
			//we append this while constructing the rrule string
			//inside this.recurrenceRule.constructRRuleFromModel
		
			//if(this.targetEvent.exdates)
				//this.recurrenceRule.addExdateToRRule(this.targetEvent);
		
		if (this.targetEvent.pendingSave) {
			//var eventToSave = Object.clone(this.targetEvent);
			//this.service.setupPendingSave(eventToSave);
			//we need to wait for the response to come back
			//so don't pop the scene yet
			this.targetEvent.pendingSave =false;
			this.targetEvent.pendingPop =true;
		}
		else {
			   
				//var callBack =(inCardMode)?this.renderSetEvent.bind(this,createdException):this.setEventCallBack;
				this.requests.push(this.service.setEvent(this.targetEvent, this.setEventCallback, this.controller));
				if(this.callBackAfterUpdate!=undefined)
					this.callBackAfterUpdate(this.targetId);
				//we set old Event because we want to make sure we don't save twice
				//when coming back from card mode to stage mode or when going back to edit details
				
				this.oldEvent = Object.clone(this.targetEvent);
				//only pop the scene if we are not in card mode
				if(!inCardMode)
					this.controller.stageController.popScene("edit");
		}
		
	},

	cleanup: function() {
	if (!this.isReadOnlyEvent == true) {
		this.controller.get('edit_datetimerow').stopObserving(Mojo.Event.tap, this.edit_infoHandler);
		this.controller.get('edit_repeatrow').stopObserving(Mojo.Event.tap, this.edit_repeatHander);
		this.controller.get('edit_alarmrow').stopObserving(Mojo.Event.tap, this.edit_alarmHandler);
		this.controller.get('edit_calendartypeParent').stopObserving(Mojo.Event.tap, this.event_calendarTypeHandler);
		}
	
	   this.controller.get('edit_participantrow').stopObserving(Mojo.Event.tap,this.edit_participantHandler);	
	},
  
	activate: function() {
		
		this.controller.listen(this.controller.document, Mojo.Event.deactivate, this.blurStage);
		if (this.targetEvent != undefined) {
			this.setupEvent();
		}
	},

	deactivate: function() {
		this.controller.stopListening(this.controller.document, Mojo.Event.deactivate, this.blurStage);
	},
	/*
	//Not relevant anymore - cleanup
	updateEventModel: function() {
		
		
		var editFields = $$('#edit_view input');
    	editFields.each(function(f) {
      		f.blur();
    	});
		
		//this.targetEvent.note = this.controller.get('note').value;
	
	},*/
	
	updateRecurrenceModel:function(){
		if (this.targetEvent.rruleModel) {
			//Mojo.Log.info('updateRecurrenceModel %s',this.repeatFreqChoice);
			
			if (this.repeatFreqChoice != 5)//we dont want to clean the model for custom case
				this.targetEvent.rruleModel = Object.clone(recurrence_model);
			
			switch (this.repeatFreqChoice) {
				case 1:
					this.targetEvent.rruleModel.frequency = '';
					this.targetEvent.endValidity=0;
					
					break;
					
				case 2:
					this.targetEvent.rruleModel.frequency = 'DAILY';								// Do NOT Localize
					this.targetEvent.rruleModel.interval = 0;
					this.targetEvent.rruleModel.count = -1;
					break;
					
				case 3:
					this.targetEvent.rruleModel.frequency = 'WEEKLY';							// Do NOT Localize
					this.targetEvent.rruleModel.byday = ['MO','TU','WE','TH','FR'];						// Do NOT Localize
					this.targetEvent.rruleModel.count = -1;
					break;
					
				case 4:
					var date = new Date(this.targetEvent.startTimestamp);
					this.targetEvent.rruleModel.frequency = 'WEEKLY';							// Do NOT Localize
					this.targetEvent.rruleModel.byday = [];	
					this.targetEvent.rruleModel.byday.push(this.recurrenceRule.dayMap[date.getDay()]);
					this.targetEvent.rruleModel.count = -1;
					break;
					
			}
			
		}	
		
	},
	
	// NOTE to Localizers: Do NOT localize any strings in this method...
	updateFromRecurrenceModel:function(){
	if (this.targetEvent.rruleModel) {
	//no repeat case
	if (!this.targetEvent.rruleModel.frequency || this.targetEvent.rruleModel.frequency == '' || (this.targetEvent.rruleModel.count && this.targetEvent.rruleModel.count == 1))
			this.repeatFreqChoice = 1;
	//daily case,weekly every, every weekday cases
	else if(this.targetEvent.rruleModel.frequency && this.targetEvent.rruleModel.frequency != '' &&
		       (!this.targetEvent.rruleModel.interval || this.targetEvent.rruleModel.interval == 1) &&
		       (this.targetEvent.isRecurringForever==true ))
	{
			if (this.targetEvent.rruleModel.frequency == 'DAILY') {
				this.repeatFreqChoice = 2;
				this.targetEvent.endValidity = AppAssistant.long_max_value;
			}
			else {
				if (this.targetEvent.rruleModel.frequency == 'WEEKLY' && this.recurrenceRule.arraysEqual(this.targetEvent.rruleModel.byday, ['MO','TU','WE','TH','FR']) &&
				    (this.targetEvent.rruleModel.interval == 1 || !this.targetEvent.rruleModel.interval)) {
					this.repeatFreqChoice = 3;
					this.targetEvent.endValidity = AppAssistant.long_max_value;
					
				}
				else if (this.targetEvent.rruleModel.frequency == 'WEEKLY' &&
					(this.targetEvent.rruleModel.interval == 1 || !this.targetEvent.rruleModel.interval) &&
					(this.targetEvent.rruleModel.byday && this.targetEvent.rruleModel.byday.length == 1) &&
					(this.targetEvent.rruleModel.byday[0] == "MO" ||
					this.targetEvent.rruleModel.byday[0] == "TU" ||
					this.targetEvent.rruleModel.byday[0] == "WE" ||
					this.targetEvent.rruleModel.byday[0] == "TH" ||
					this.targetEvent.rruleModel.byday[0] == "FR" ||
					this.targetEvent.rruleModel.byday[0] == "SA" ||
					this.targetEvent.rruleModel.byday[0] == "SU")) {
						this.repeatFreqChoice = 4;
						this.targetEvent.endValidity = AppAssistant.long_max_value;
						
				}
				else
					this.repeatFreqChoice = 5;		
			}
		}
		else 
			this.repeatFreqChoice = 5;
			
		}		
		else this.repeatFreqChoice = 1; //no repeat
	

	},
	
	checktargetEventDirty:function(){
		if (this.cancelNewEvent)
			return false;
			
		//construct rrule
		if(this.targetEvent.rruleModel)
		{
			this.recurrenceRule.constructRRuleFromModel(this.targetEvent);
		
		}
		// If the old event doesn't exist we are trying to save a new event, so it is "dirty"
		if (this.oldEvent == undefined || this.service.isEventDirty(this.oldEvent, this.targetEvent))
			return true;
		else 
			return false;
	},
  	
	handleSave: function(e){
		//Mojo.Log.info("edit-assistant:handleSave");

		//this.updateEventModel();
		this.updateRecurrenceModel();
		
		if (this.checktargetEventDirty()) {
			//Mojo.Log.info("************************event is dirty");
			Event.stop(e);
			
			if (!this.targetEvent.rrule || this.targetEvent.rrule == '' || 
			    !this.oldEvent || !this.oldEvent.rrule || 
			    this.oldEvent.rrule == '' || this.targetEvent.onlyRepeatChanged ==true || 
			    this.oldEvent.calendarId !=this.targetEvent.calendarId)
			{
				this.saveEvent(null);
				//Mojo.Log.info('no rrule');
			}
			else{
				//Mojo.Log.info('there is an rrule');
				//e.preventDefault();
				
				this.doRecurrenceDialog();
			}	
			
		}
		else
			Mojo.Log.info('>>>>>>>>>>>>>>>>event not dirty');

	},
	
	doRecurrenceDialog: function() {
		
		startdate= new Date(this.targetEvent.startTimestamp);
		start = Mojo.Format.formatDate(startdate, {date: "long"});
		this.controller.showDialog({
			template: 'shared/recurrence-warning',
			assistant: new RecurrenceWarning(this,this.targetEvent.id),
			start:start
			
		});
	},
	
	handleEditInfo: function(e){	
		//this.updateEventModel();
		this.updateRecurrenceModel();
		this.controller.stageController.pushScene('datetime', this.targetEvent,this.targetModifiedTime,this.resettargetEvent.bind(this),this.oldEvent,this.setEventCallback,this.controller,this.callBackAfterUpdate,this.targetId);
		
	},	
	handleEditRepeat: function(e){
		Mojo.Log.info("edit-assistant:handleEditRepeat");
			var items=[];
			for (var i=0;i<this.repeatOptions.size();i++)
			{
				items.push({
					label: this.repeatOptions[i],
					command: i +1
				});
				
			}
				this.controller.popupSubmenu({
				onChoose: this.repeatChoose,
				toggleCmd:this.repeatFreqChoice,
				items: items,
				placeNear: this.controller.get('repeat-icon')
			});
		
	},
	
	setRepeatPreset: function(freq) {
		this.repeatFreq = freq;
		this.targetEvent.repeatInterval	= 1;
		this.targetEvent.repeatHasEnd	= false;
		this.targetEvent.repeatEndDate	= 0;
		
		if (freq == "weekly") {
			var date = new Date(this.targetEvent.startTimestamp);
			var dow = date.getDay();
			
			this.targetEvent.repeatWeeklySun	= (dow == 0);
			this.targetEvent.repeatWeeklyMon	= (dow == 1);
			this.targetEvent.repeatWeeklyTue	= (dow == 2);
			this.targetEvent.repeatWeeklyWed	= (dow == 3);
			this.targetEvent.repeatWeeklyThu	= (dow == 4);
			this.targetEvent.repeatWeeklyFri	= (dow == 5);
			this.targetEvent.repeatWeeklySat	= (dow == 6);
		}
	},

	repeatChoose: function(val) {
		//Mojo.Log.info("edit-assistant:repeatChoose");
	
		value = parseInt(val);
		if (val != undefined && (value != this.repeatFreqChoice) ){			
			this.targetEvent.onlyRepeatChanged = true;
			if (this.repeatFreqChoice == 5) {
				// Reset the recurrence model to default settings
				this.targetEvent.rruleModel = Object.clone(recurrence_model);
				// Reset the Custom menu item to default "Custom"
				this.repeatOptions[this.repeatOptions.size()-1] = $L("Custom");
			}else if(this.repeatFreqChoice==1 && value==5)
				this.targetEvent.isRecurringForever =true;
			this.repeatFreqChoice = value;
			this.targetEvent.dirty =true;	
			
			if (!this.targetEvent.rruleModel)
				this.targetEvent.rruleModel = Object.clone(recurrence_model);
			
			if (value == 1) {
				//we need to clear out recurrence stuff as there is no repeat
				this.targetEvent.rruleModel = Object.clone(recurrence_model);
				this.targetEvent.rrule = "";
				this.targetEvent.endValidity = 0;
			} else if (value!=5)
				this.targetEvent.endValidity = AppAssistant.long_max_value;
			this.updateRepeatButton(this.repeatOptions[value-1],value);
		}
			
		if (value == 5) {
			//this.updateEventModel();
			this.updateRecurrenceModel();
			//Mojo.Log.info('pushing the repeat scene');
			this.controller.stageController.pushScene('repeat', this.targetEvent,this.resettargetEvent.bind(this),this.oldEvent,this.setEventCallback,this.controller,this.callBackAfterUpdate,this.targetId);
		} 	
				

	},

	handleEditAlarm: function(e){
		Mojo.Log.info("edit-assistant:handleEditAlarm");
		var items=[];
			for (var i=0;i<this.alarms.list.size();i++)
			{
				items.push({
					label: this.alarmOptions[i],
					command: i +1
				});
				
			}
				this.controller.popupSubmenu({
				onChoose: this.alarmChoose,
				toggleCmd:this.selectedAlarmOption,
				items: items,
				placeNear: this.controller.get('alarm-bell-icon')
				
			});
			
		//}
	},

	alarmChoose: function(val) {
		
		var value = parseInt(val);
		this.selectedAlarmOption = value;
		if (val != undefined) {
			if (value == 999) {
				//this.updateEventModel();
				
				// When selecting the Custom option,
				// set the alarm to the first option (something other than none)
				// if the current alarm is 'none'.
				if (this.targetEvent.alarm == "none") 
					this.targetEvent.alarm = this.alarms.list[0];
				
				this.controller.stageController.pushScene('alarm', this.targetEvent);
			}
			else {
				this.targetEvent.dirty =true;
				this.targetEvent.alarm = this.alarms.list[value-1];
				this.updateAlarmButton(this.alarmOptions[value-1]);		
			
			}
		}
	},
	recurrenceCancel:function(){
		this.targetEvent = Object.clone(this.oldEvent);
		this.targetEvent.dirty =false;
		this.activate();
		//this.controller.stageController.popScene();
	},
	
	handleEditParticipants:function(e){
		this.controller.stageController.pushScene('participants',this.targetEventAttendees,this.targetEvent);
	},

	
	handleDelete: function(e) {
	 this.doDialog();
	},
	
	doDialog: function() {
		// If the user is trying to delete a new event (cancelling the new event) 
		// [new event's parentId equals 0]
		// or
		// if the event is NOT a recurring event, show the standard delete warning
		if ((!this.targetEvent.rrule || this.targetEvent.rrule == "") && this.targetEvent.parentId <=0){
			this.controller.showDialog({
				template: 'shared/confirm-deleteevent',
				assistant: new DeleteEventConfirmDialogAssistant(this, this.targetEvent, this.targetModifiedTime.start),
				preventCancel: true
			});
		}
		// If the event is a recurring event, show the warning allowing users to
		// delete the series, the single event, or cancel
		else {
			
			this.controller.showDialog({
				template: 'shared/confirm-deleterecurringevent',
				assistant: new DeleteEventConfirmDialogAssistant(this, this.targetEvent, this.targetModifiedTime.start),
				preventCancel: true
			});
		}
	},

	resettargetEvent:function(targetEvent,oldEvent){
		if (targetEvent != null) {
			
			this.targetEvent = targetEvent;
		}
		if (oldEvent != null) {
			this.oldEvent = oldEvent;
		}
		
	},
	
	deletedEventHandle: function(){
		
		if(this.targetId)
			getReminderManager().removeReminder(this.targetId);
		else
		  getReminderManager().removeReminder(this.deletedeventId);
		
		if(this.callBackAfterUpdate!=undefined)
			this.callBackAfterUpdate(this.targetId);
		
		this.controller.stageController.popScene();
		
	},
});