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

var RepeatAssistant = Class.create({
	initialize: function(targetEvent,callback,oldEvent,setEventCallback,editSceneController,callBackAfterUpdate,longTargetId) {
		//Mojo.Log.info("repeat-assistant:initialize");
		this.targetEvent = targetEvent;
		this.targetCallBack =callback;
		this.oldEvent=oldEvent;
		this.recurrenceRule = getRecurrenceRule();
		this.setEventCallback=setEventCallback;
		this.editSceneController =editSceneController;
		this.callBackAfterUpdate =callBackAfterUpdate;
		this.targetId = longTargetId;
	},

	freqs: [
		{name: $L('Daily'), units: $L('day(s)')},
		{name: $L('Weekly'), units: $L('week(s)')},
		{name: $L('Monthly on (by date)'), units: $L('month(s)')},
		{name: $L('Monthly on (by week)'), units: $L('month(s)')},
		{name: $L('Yearly on (by month)...)'), units: $L('year(s)')},
	],
	
	
	
	buildRepeatInfo: function(response) {
		//Mojo.Log.info("repeat-assistant:buildRepeatInfo: ");
		
		start =new Date(this.targetEvent.startTimestamp);
		end = new Date(this.targetEvent.endValidity);
		
		var templateModel = {};
		templateModel.start = Mojo.Format.formatDate(start, {date: "long"});
		templateModel.end = Mojo.Format.formatDate(end, {date: "long"});
		templateModel.count = response.count;
		
		var template = $L("1#This event starts on #{start} and ends on #{end} and it occurs 1 time.|101<#This event starts on #{start} and ends on #{end} and it occurs #{count} times.|#This event starts on #{start} and ends on #{end} and there are more than 100 occurrences left.");
  		
		var info = Mojo.Format.formatChoice(response.count, template, templateModel);
		
		var text = Mojo.View.render({object: {info: info}, template: "datetime/info"});
	  	this.controller.get('edit_repeat_info').update(text);	
		
	},
	
	updateRepeatInfo: function(info) {
		
		var button = Mojo.View.render({object: {info: info}, template: "datetime/info"});
		this.controller.get('edit_repeat_info').update(button);
	},
	
	setupRepeatSettings: function(transition) {
		
		
		if (transition == false) {
			switch (this.repeatFreqIndex) {
				case 2:
					if (this.controller.get('repeat_weekly').visible() == false) {
						this.controller.get('repeat_weekly').show(); 
					
					}
					break;
					
				default:
					if (this.controller.get('repeat_weekly').visible() == true)
						this.controller.get('repeat_weekly').hide();
					break;
			}
		}
		else {
			switch (this.repeatFreqIndex) {
				case 2:
				{
					if (this.controller.get('repeat_weekly').visible() == false) 
						this.slideDown(this.controller.get('repeat_weekly'), 0.4);
				}
				break;
					
				default:
					if (this.controller.get('repeat_weekly').visible() == true)
						this.slideUp(this.controller.get('repeat_weekly'), 0.4);
					break;
			}
		}
		if(this.repeatFreqIndex==2)
		{
			var date = new Date(this.targetEvent.startTimestamp);
			var day = this.recurrenceRule.dayMap[date.getDay()];
			if (!this.targetEvent.rruleModel.byday || this.targetEvent.rruleModel.byday.length == 0) {
				 this.checkBoxCheck(day, day);	
			} else {
				
				this.targetEvent.rruleModel.byday.each(function(thing){
					
					this.checkBoxCheck(thing, day);				
				},this);
			}
			
		}
	},
	checkBoxCheck:function(lday,day){
		this.weekday.each(function(thing){
			
			if(thing.day == lday){
				thing.model.value=true;
			}
			if(thing.day == day){
				thing.model.disabled=true;
			}
			this.controller.modelChanged(thing.model);
	
		},this);
	},
	
	setupDate: function(dateDiv, date) {
		
		var theDate = new Date(date);
			
		var y = Mojo.Format.formatDate(theDate, "yyyy");
		var m = Mojo.Format.formatDate(theDate, "MMM").toUpperCase();
		var d = Mojo.Format.formatDate(theDate, "dd");
		var button = Mojo.View.render({object: {label: $L("Date"), year: y, month: m, day: d},
										template: "datetime/datePicker"});
		dateDiv.insert(button);
		var items = dateDiv.childElements();
		button = items[items.size() - 1];
//		button.observe('click', this.handleDate.bind(this));
	},
	
	setUpCustomRepeat:function(){
		//Mojo.Log.info('setUpCustomRepeat %j',this.targetEvent.rruleModel);
		//set up repeat frequency
		if(this.targetEvent.rruleModel.frequency=='DAILY')
		  	this.repeatFreqIndex=1;
		else if(this.targetEvent.rruleModel.frequency=='WEEKLY')
		 	this.repeatFreqIndex=2;
		else if(this.targetEvent.rruleModel.frequency=='MONTHLY')
		{
			var theDate = new Date(this.targetEvent.startTimestamp);
		    var checkday = getDOWCount(this.targetEvent.startTimestamp).toString();
			checkday += this.recurrenceRule.dayMap[theDate.getDay()];
			if ((this.targetEvent.rruleModel.byday) &&
				(this.targetEvent.rruleModel.byday.length > 0) &&
				(this.targetEvent.rruleModel.byday[0] == checkday ))
			 	this.repeatFreqIndex = 4;
			else
			 	this.repeatFreqIndex = 3;
		}
		else if(this.targetEvent.rruleModel.frequency=='YEARLY')
		  	this.repeatFreqIndex=5;
		else
		  	this.repeatFreqIndex=1;
		
	},
	
	updateRepeatFromModel:function(){
		//Mojo.Log.info("repeat-assistant:updateRepeatModel");
		this.updateInterval();
		
		if (this.targetEvent.isRecurringForever == true) {
			this.repeatForeverChecked = true;
			this.foreverCheckboxModel.value = true;
		} else {
			this.repeatForeverChecked = false;
			this.foreverCheckboxModel.value = false;
		}
		
		this.controller.modelChanged(this.foreverCheckboxModel);
		var endTime;
		if (this.targetEvent.endValidity && this.targetEvent.endValidity != "" &&
			this.targetEvent.rrule &&
			this.targetEvent.rrule != "" &&
			this.targetEvent.endValidity != AppAssistant.long_max_value &&
			!this.targetEvent.isRecurringForever ) {
			endTime = new Date(this.targetEvent.endValidity);
		}
		else 
			endTime = new Date(this.targetEvent.endTimestamp);
		
		this.defaultendValidity =endTime;
		
		this.endDateModel = {
			date: endTime
		};
		
		if (this.repeatForeverChecked != true) {
			if (this.targetEvent.endValidity != "" && this.targetEvent.rrule &&
				this.targetEvent.rrule !="" && (this.targetEvent.endValidity >= this.targetEvent.endTimestamp)) {
				this.endDateModel.date = new Date(this.targetEvent.endValidity);
			}
		}
		
		this.controller.setupWidget('untilDate',{label:" "}, this.endDateModel);
		this.controller.listen('untilDate', Mojo.Event.propertyChange,this.endDateUpdate.bindAsEventListener(this));			

		this.setupRepeatSettings(false);
		this.updateRecurUntil(false);
	},
	
	renderWeeklyRepeatDays: function() {
		//Mojo.Log.info("repeat-assistant: renderWeeklyRepeatDays");
		var html = "";
		
		// Set up the array of day names based on the start of the week
		var date = new Date();
		var dayValue = getPrefs().startOfWeek-1;
		var days = [];
		
		date.moveToDayOfWeek(dayValue);
		
		var model = {};
		
		for (i = 0; i < 7; i++) {
			model.dayId = this.weekday[dayValue].day;
			//Mojo.Log.info('*************dayid is:'+model.dayId);
			model.dayText = Mojo.Format.formatDate(date, "EEEE").slice(0, 2);
			
			html += Mojo.View.render({object: model, template: 'repeat/repeat-day-checkbox'});
			date.addDays(1);
			if (dayValue == 6)
				dayValue = 0;
			else
				dayValue++;
		}	
	
		this.controller.get('repeat_weekly_days').update(html);
		
		// Set up the checkbox widgets
		this.weekday.each(function(thing){
			
			this.controller.setupWidget(thing.day,this.attributes,thing.model);
			this.controller.listen(thing.day, Mojo.Event.propertyChange, this.handleWeekTap.bindAsEventListener(this));
		},this);
	},
	
	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.updateRecurrence();
		if(this.checktargetEventDirty())		
			this.saveEvent(true);
				
	},	
	
	setup: function() {
		//Mojo.Log.info("repeat-assistant:setup");
		this.appMenuModel= { visible:true, 
					label:$L('Calendar'), 
					items: [ Mojo.Menu.editItem,
							{label:$L('Preferences & Accounts'), command:Mojo.Menu.prefsCmd, disabled: true},
							{label:$L('Help'), command:Mojo.Menu.helpCmd, disabled:false}]
		  		   }
		
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, this.appMenuModel);

		
		
		this.repeatView = this.controller.get('repeat_view');
		this.header = this.controller.get('edit_header');
		
		this.blurStage = this.blurStageBound.bind(this);
		this.controller.listen(this.controller.document, Mojo.Event.deactivate, this.blurStage);
		
		this.header.update(Mojo.View.render({template: 'repeat/header', object: this.targetEvent}));

		this.service = getCalendarService();
		this.requests = [];	
		
		this.foreverCheckboxModel = {
			value: false
		};
		
		this.weekday= [
			{
				day: 'SU', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'MO', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'TU', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'WE', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'TH', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'FR', // Do NOT Localize this id
				model: {
					value: false
				}
			},{
				day: 'SA', // Do NOT Localize this id
				model: {
					value: false
				}
			}
		]
		
		this.setUpCustomRepeat();	
		
		// Setup Forever checkbox
		this.foreverCheckboxModel.value = this.targetEvent.isRecurringForever;
		this.controller.get('dtl_forever_cb').observe(Mojo.Event.propertyChange, this.handleForeverTap.bindAsEventListener(this));
		this.controller.get('dtl_checkbox_div').observe(Mojo.Event.tap, this.handleForeverTap.bindAsEventListener(this));
		this.foreverattributes = {
			modelProperty: 'value'
		}
		this.controller.setupWidget('dtl_forever_cb',this.foreverattributes,this.foreverCheckboxModel);
		
		// Customize the monthly freq options based on the date.
		var date = new Date(this.targetEvent.startTimestamp);
		
		var templateModel = {};
		templateModel.day = Mojo.Format.formatDate(date, "d");		
		var template = $L("1#Monthly on the 1st|2#Monthly on the 2nd|3#Monthly on the 3rd|21#Monthly on the 21st|22#Monthly on the 22nd|23#Monthly on the 23rd|31#Monthly on the 31st|#Monthly on the #{day}th");		
		this.freqs[2].name= Mojo.Format.formatChoice(templateModel.day, template, templateModel);
		
		
		
		templateModel = {};
		templateModel.dayOfWeek = Mojo.Format.formatDate(date, "EEEE");
		templateModel.dowCount = getDOWCount(this.targetEvent.startTimestamp);
		var template = $L("1#Monthly on the 1st #{dayOfWeek}|2#Monthly on the 2nd #{dayOfWeek}|3#Monthly on the 3rd #{dayOfWeek}|#Monthly on the #{dowCount}th #{dayOfWeek}");	
		this.freqs[3].name = Mojo.Format.formatChoice(templateModel.dowCount, template, templateModel);
		
		
		templateModel = {};		
		templateModel.month = Mojo.Format.formatDate(date, "MMMM");
		templateModel.day = Mojo.Format.formatDate(date, "d");
		var template = $L("1#Yearly on #{month} 1st|2#Yearly on #{month} 2nd|3#Yearly on #{month} 3rd|21#Yearly on #{month} 21st|22#Yearly on #{month} 22nd|23#Yearly on #{month} 23rd|31#Yearly on #{month} 31st|#Yearly on #{month} #{day}th");	
		this.freqs[4].name = Mojo.Format.formatChoice(templateModel.day, template, templateModel);
		
		var button = Mojo.View.render({object: {text: this.freqs[this.repeatFreqIndex-1].name,
									buttonId: 'freqButton'}, template: "edit/popupButton"});
		this.controller.get('repeat_freq').insert(button);
		this.controller.get('repeat_freq').observe('click', this.handleRepeatFreq.bind(this));		

		this.renderWeeklyRepeatDays();
		
		this.integerModel = {
			value: 1,
		};
		//Mojo.Log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!before setting up interval picker");
        this.controller.setupWidget('intervalPicker', {label:" ",modelProperty:'value',min: 1, max: 99}, this.integerModel);
		this.controller.listen('intervalPicker', Mojo.Event.propertyChange,this.intervalConstruct.bindAsEventListener(this));
		
		this.controller.get('repeat_interval').update(Mojo.View.render({
			template: 'repeat/repeat-interval',
			object: {
				units: this.freqs[this.repeatFreqIndex-1].units,
				//value: this.targetEvent.rruleModel.interval
				}
		}));
	   
		
		this.updateRepeatFromModel();
		
		//we are doing this to find out if the event is dirty and need to check
		//before attempting to save it
		if(this.targetEvent.rruleModel)
			this.oldByday = this.targetEvent.rruleModel.byday;
			this.oldEndValidity = this.targetEvent.endValidity;		
		
		this.attributes = {
			modelProperty:'value'
		}
			
		
	},
	
	
	intervalConstruct:function(event){
		//Mojo.Log.info("in interval construct");
		this.targetEvent.rruleModel.interval = event.value;
		this.constructRecurrenceString();
		
	},
	
	updateInterval:function(){
		//Mojo.Log.info("repeat-assistant:updateInterval");
		if (this.targetEvent.rruleModel.interval && this.targetEvent.rruleModel.interval != 0) {
			this.integerModel.value = this.targetEvent.rruleModel.interval;
			this.controller.modelChanged(this.integerModel);
		} else {
			this.integerModel.value = 1;
			this.controller.modelChanged(this.integerModel);
			this.targetEvent.rruleModel.interval = 1;
		}
	},
	
	endDateUpdate: function(event) {
		this.recurConstruct(new Date(event.value),true);
	},
	
	recurConstruct:function(time,setdefaultEndValidity){
		//Mojo.Log.info('entered date call back'+time);
		//we need to set the end validity to the exact time as 
		//each event
		var endtimestamp = new Date(this.targetEvent.endTimestamp);
		time.setHours(endtimestamp.getHours());
		time.setMinutes(endtimestamp.getMinutes());
		time.setSeconds(endtimestamp.getSeconds());
		
		if (setdefaultEndValidity) {
			this.defaultendValidity = time;
		}
		
		this.targetEvent.endValidity= time.getTime();
		this.targetEvent.rruleModel.until= this.recurrenceRule.calculateRecurTime(this.targetEvent.endValidity);
		//calculate the number of occurences from start date
		this.constructRecurrenceString();
		
	},
	
	constructRecurrenceString:function(){
		//Mojo.Log.info("repeat-assistant: constructRecurrentString");
		
		if(this.repeatForeverChecked) {
			var text = Mojo.View.render({object: {info: $L("This event repeats forever.")}, template: "datetime/info"});
    		this.controller.get('edit_repeat_info').update(text);
		} else if(this.targetEvent.endValidity < this.targetEvent.endTimestamp) {
			var text = Mojo.View.render({object: {info: $L('There are no more occurrences of this event.')}, template: "datetime/info"});
			this.controller.get('edit_repeat_info').update(text);
		} else {
			this.updateRecurrence();
			this.recurrenceRule.constructRRuleFromModel(this.targetEvent);
			this.service.getOccurenceCount(this.targetEvent.startTimestamp, this.targetEvent.rrule,this.targetEvent.endValidity,this.buildRepeatInfo.bind(this), this.controller);
		}
	},
	
	handleForeverTap: function() {
		Mojo.Log.info('repeat-assistant: handleForeverTap');
    	if(this.repeatForeverChecked)
			this.repeatForeverChecked = false;
		else
			this.repeatForeverChecked = true;
		this.updateRecurUntil(true);
	},
		
	handleWeekTap: function() {
		//Mojo.Log.info('repeat-assistant: handleWeekTap');
    	this.constructRecurrenceString();
	},
	
	updateRecurUntil: function(transition) {
		//Mojo.Log.info("repeat-assistant: updaterecuruntil");
		if (transition == false) {
			if (this.repeatForeverChecked == false) {
				this.controller.get('repeat_until_row').show();
				this.foreverCheckboxModel.value = false;
				this.controller.modelChanged(this.foreverCheckboxModel);
				this.controller.get('foreverdiv').removeClassName('last');
				
			} else {
				this.controller.get('repeat_until_row').hide();
				this.foreverCheckboxModel.value = true;
				this.controller.modelChanged(this.foreverCheckboxModel);
				this.controller.get('foreverdiv').addClassName('last');
			}
		} else {
			if (this.repeatForeverChecked == false) {
				this.slideDown(this.controller.get('repeat_until_row'), 0.4);
			
				this.foreverCheckboxModel.value = false;
				this.controller.modelChanged(this.foreverCheckboxModel);
				this.controller.get('foreverdiv').removeClassName('last');
					
			} else {
				this.slideUp(this.controller.get('repeat_until_row'), 0.4);
				
				this.foreverCheckboxModel.value = true;
				this.controller.modelChanged(this.foreverCheckboxModel);
				this.controller.get('foreverdiv').addClassName('last');

			}
		}
		this.updateEndvalidity();
		
	},
	
	updateRecurrence:function(){
		//Mojo.Log.info("repeat-assistant:UpdateRecurrence");
		var num=0;
		
		var date = new Date(this.targetEvent.startTimestamp);
		var until= this.targetEvent.rruleModel.until;
		var interval=this.targetEvent.rruleModel.interval;
		this.targetEvent.rruleModel = Object.clone(recurrence_model);
			
		switch(this.repeatFreqIndex)
		{
			case 1:
			this.targetEvent.rruleModel.frequency = 'DAILY';	// Do NOT Localize
			break;
			
			case 2:
			this.targetEvent.rruleModel.frequency ='WEEKLY'; // Do NOT Localize

			this.targetEvent.rruleModel.byday = [];
			this.weekday.each(function(thing){
				if(thing.model.value == true)
					this.targetEvent.rruleModel.byday.push(thing.day);
			},this);
			break;
			
			case 3:
			this.targetEvent.rruleModel.frequency ='MONTHLY'; // Do NOT Localize
			this.targetEvent.rruleModel.bymonthday = [];
			this.targetEvent.rruleModel.bymonthday.push(date.toString("d")); 			
			break;
			
			case 4:
			this.targetEvent.rruleModel.frequency ='MONTHLY'; // Do NOT Localize
			nth = getDOWCount(this.targetEvent.startTimestamp);
			this.targetEvent.rruleModel.byday = [];
			var date = new Date(this.targetEvent.startTimestamp);
			var byday=this.recurrenceRule.dayMap[date.getDay()];
			
			this.targetEvent.rruleModel.byday.push(nth + byday);
			break;
			
			case 5:
			// TODO: Mojo.Format.formatDate returns LOCALIZED month name, will this screw up the recurrence?
			this.targetEvent.rruleModel.frequency ='YEARLY'; // Do NOT Localize
			break;
			
		}
		if(interval>1)
			this.targetEvent.rruleModel.interval =interval;
			
		if (this.repeatForeverChecked) {
			this.targetEvent.rruleModel.count = -1;
			this.targetEvent.rruleModel.until="";
		
		}
		else {
			this.targetEvent.rruleModel.until = until;
			this.targetEvent.rruleModel.count = 0;
		}
		   
	},
	saveEvent: function(inCardMode) {
    	
		//we need to do this because sometimes after returning to previous view and
		//coming back here, the forever changes are not reflected in the targetevent
		
		this.targetEvent.isRecurringForever=this.repeatForeverChecked;
		
		//we will also need to assign a default subject name if there is none
		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');
		}
		//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);
			
		var callback = (inCardMode) ?this.renderSetEvent.bind(this):this.setEventCallback;	
		this.requests.push(this.service.setEvent(
			this.targetEvent, callback, this.editSceneController));
		
		//we do this so that we can make sure we dont do multiple
		//saves on an event that is already saved.
		this.oldEvent=Object.clone(this.targetEvent);
		this.targetCallBack(null,this.oldEvent);
		this.targetEvent.dirty=false;
		this.targetEvent.pendingSave = true;
		if (!inCardMode) {
			if(this.callBackAfterUpdate!=undefined)
				this.callBackAfterUpdate(this.targetId);
			this.controller.stageController.popScene("repeat");
		}

	},
  
    renderSetEvent:function(response){
   		//this will only be called in the case of
		//minimized card mode.
		//if we are exiting the scene by back gesture,
		//we have already popped the scene.
		
   		this.targetEvent.id = response.id;
    },
  
	checktargetEventDirty:function(){
		//construct rrule
		if(this.targetEvent.rruleModel)
		{
			this.recurrenceRule.constructRRuleFromModel(this.targetEvent);
		}
		if (this.service.isEventDirty(this.oldEvent, this.targetEvent))
			return true;
		else 
			return false;
	},
  
  handleCommand:function(event)
  {
  	if (event.command == Mojo.Menu.helpCmd) {
		getAppManagerService().launchHelp(this.controller);
	}
	//Mojo.Log.info("entered into handle command");
	else 
		if (event.type == Mojo.Event.back) {
			this.updateRecurrence();
			if (this.targetEvent.endValidity < this.targetEvent.endTimestamp) {
				Event.stop(event);
				this.defaultendValidity = new Date(this.targetEvent.endTimestamp);
				var end = Mojo.Format.formatDate(this.defaultendValidity, {
					date: "long"
				});
				if (this.oldEndValidity && this.oldEndValidity >= this.targetEvent.endTimestamp) 
					this.defaultendValidity = new Date(this.oldEndValidity);
				
				this.controller.showDialog({
					template: 'repeat/recurrenceEndWarning',
					assistant: new RecurrenceEndWarning(this),
					preventCancel: true,
					end: end
				});
			}
			else 
				if (this.checktargetEventDirty()) {
					//Mojo.Log.info("entered into event back and is dirty");
					var date = new Date();
					
					Event.stop(event);
					
					this.saveEvent();
				}
		}
  	
  },

	cleanup: function() {
		
		this.controller.get('repeat_freq').stopObserving();
		this.weekday.each(function(thing){
			this.controller.get(thing.day).stopObserving(Mojo.Event.propertyChange);
			thing.model.value=false;
		}, this);
	},

	activate: function() {
	},
	
	deactivate: function() {
		//Mojo.Log.info("repeat-assistant:deactivate");
		this.controller.stopListening(this.controller.document, Mojo.Event.deactivate, this.blurStage);

	},

	handleRepeatFreq: function(e){
		
		
			this.controller.popupSubmenu({onChoose:this.freqChoose, placeNear:e.target,
			toggleCmd:this.repeatFreqIndex,
			    items: [
				    {label: this.freqs[0].name, command: 1}, 
				    {label: this.freqs[1].name, command: 2}, 
				    {label: this.freqs[2].name, command: 3}, 
				    {label: this.freqs[3].name, command: 4}, 
				    {label: this.freqs[4].name, command: 5}, 
				]});
			
		
	},
	
	freqChoose: function(val) {
		value=parseInt(val);
		if (val != undefined && this.repeatFreqIndex != value) {
			var button = Mojo.View.render({
				object: {
					text: this.freqs[value-1].name,
					buttonId: 'freqButton'
				},
				template: "edit/popupButton"
			});
			this.controller.get('repeat_freq').update(button);
			
			this.repeatFreqIndex = value;
			
			this.setupRepeatSettings(true);
			
			
			//update the repeatuntil and reset it to forever
			
			this.updateEndvalidity();
		
			
			this.controller.get('repeat_interval').update(Mojo.View.render({
			template: 'repeat/repeat-interval',
			object: {
				units: this.freqs[this.repeatFreqIndex-1].units,
			}
		}));
		this.updateInterval();

			
		}
	},
	
	updateEndvalidity:function(){
		
		if (this.repeatForeverChecked) {
			this.targetEvent.endValidity =AppAssistant.long_max_value;
			this.targetEvent.rruleModel.until="";
			this.constructRecurrenceString();
		} else {
			var time;
			if (this.targetEvent.endValidity && this.targetEvent.endValidity != "" &&
			this.targetEvent.rrule &&
			this.targetEvent.rrule != "" &&
			this.targetEvent.endValidity != AppAssistant.long_max_value) {
				time = this.targetEvent.endValidity;
				
			}
			else {
				time = this.defaultendValidity.getTime();
			}
				
				
			this.endDateModel.date = new Date(time);
			this.controller.modelChanged(this.endDateModel);
			this.recurConstruct(new Date(time),false);
		}
	},
	
	slideDown: function(div, duration) {
		div.show();
 		var divDimensions = div.getDimensions();
       	div.style.height='0px';
		Mojo.Animation.animateStyle(div, 'height', 'bezier', {from: 0, to: divDimensions.height, duration: duration, curve: 'ease-in-out', 
											        onComplete:function(el, cancelled){
											                if(!cancelled) {
											                    div.style.height='';
											                }
											            }
		});
	},
	
	slideUp: function(div, duration) {
 		var divDimensions = div.getDimensions();
       	div.show();
		Mojo.Animation.animateStyle(div, 'height', 'bezier', {from: divDimensions.height, to: 0, duration: duration, curve: 'ease-in-out', 
                       onComplete:function(el, cancelled){
                                if(!cancelled) {
                                    div.style.height='';
                                    div.hide();
                                }
                            }
        });
	},
	handleRecurrenceWarningOk:function(){
		this.endDateModel.date = this.defaultendValidity;
	    this.controller.modelChanged(this.endDateModel);
		this.recurConstruct(this.defaultendValidity,false);
		
	}
	
});




/*
	Small controller class used for the recurring date time picker check.
*/
var RecurrenceEndWarning = Class.create({
	
	initialize: function(sceneAssistant) {
		this.sceneAssistant = sceneAssistant;
	},
	
	setup : function(widget) {
	
		this.widget =widget;
		this.sceneAssistant.controller.get('OK').addEventListener(Mojo.Event.tap, this.handleOK.bindAsEventListener(this));
		
		
	},

	handleOK:function(event){
		
		Event.stop(event);
		this.sceneAssistant.handleRecurrenceWarningOk();
		this.widget.mojo.close();
	},

	
});