Ext.namespace('Zarafa.plugins.delayeddelivery');

/**
 * @class Zarafa.plugins.delayeddelivery.DelayDeliveryPlugin
 * @extends Zarafa.core.Plugin
 *
 * This class integrates Delay Delivery plugin in existing system.
 * It allows user to Scheduled Mail that will be send in future.
 */
Zarafa.plugins.delayeddelivery.DelayDeliveryPlugin = Ext.extend(Zarafa.core.Plugin, {

	/**
	 * Called after constructor.
	 * Registers insertion points in Content toolbar.
	 * @protected
	 */
	initPlugin : function ()
	{
		Zarafa.plugins.delayeddelivery.DelayDeliveryPlugin.superclass.initPlugin.apply(this, arguments);
		Zarafa.core.data.SharedComponentType.addProperty('common.dialog.delayeddelivery');
		this.registerInsertionPoint('context.mail.mailcreatecontentpanel.toolbar.aftersendbutton', this.createNewDelayDeliveryButton, this);
	},

	/**
	 * Bid for the type of shared component and the given record.
	 * @param {Zarafa.core.data.SharedComponentType} type Type of component a context can bid for.
	 * @param {Ext.data.Record} record Optionally passed record.
	 * @returns {Number}
	 */
	bidSharedComponent : function (type, record)
	{
		var bid = -1;
		switch (type) {
			case Zarafa.core.data.SharedComponentType['common.dialog.delayeddelivery']:
				bid = 1;
				break;
		}
		return bid;
	},

	/**
	 * Will return the reference to the shared component.
	 * Based on the type of component requested a component is returned.
	 * @param {Zarafa.core.data.SharedComponentType} type Type of component a context can bid for.
	 * @param {Ext.data.Record} record Optionally passed record.
	 * @return {Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel} Component
	 */
	getSharedComponent : function (type, record)
	{
		return Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel;
	},

	/**
	 * Prepare new button in mail create toolbar
	 * @return {Ext.Button} Button instance
	 * @private
	 */
	createNewDelayDeliveryButton : function ()
	{
		return [{
			xtype : 'button',
			text : _('Send Later'),
			tooltip : {
				title : _('Send Later'),
				text : _('Schedule your mail to be sent on a specific time.')
			},
			iconCls : 'icon_delaydelivery',
			handler : this.showDelayDeliveryContentPanel,
			listeners : {
				afterrender : this.onAfterRender,
				scope : this
			},
			scope : this
		}];
	},

	/**
	 * Event handler set click event listener on {@link Ext.Button sendButton} of
	 * {@link Zarafa.mail.dialogs.MailCreateToolbar mailCreateToolbar}
	 * @param {Ext.Button} sendLaterButton The button which was render
	 */
	onAfterRender : function (sendLaterButton)
	{
		var mailToolBar = sendLaterButton.ownerCt;
		var sendButton = mailToolBar.sendButton;
		sendButton.on('click', this.onSend, mailToolBar);
	},

	/**
	 * Event handler which is called when the user click the {@link Ext.Button sendButton}
	 * This will set null into deferred_send_time in Zarafa.core.data.IPMRecord} record.
	 */
	onSend : function ()
	{
		// If the mail is scheduled mail(in outbox) and user try to directly send it this will not send
		// Because of it has 'deferred_send_time' ,So by setting null into 'deferred_send_time' we can send the mail
		this.record.set('deferred_send_time', null);
	},

	/**
	 * Event handler open {@link Zarafa.plugins.delayeddelivery.dialogs.delayeddeliveryContentPanel ContentPanel} for
	 * set DEFERRED_SEND_TIME property  in new created mail base on enter Date and Time
	 * @param {Ext.Button} btn The button which was clicked
	 */
	showDelayDeliveryContentPanel : function (btn)
	{
		var record = btn.ownerCt.record;
		Zarafa.core.data.UIFactory.openLayerComponent(Zarafa.core.data.SharedComponentType['common.dialog.delayeddelivery'], record, {
			manager : Ext.WindowMgr,
			modal : true,
			resizable : false,
			scope : this
		});
	}
});

Zarafa.onReady(function () {
	container.registerPlugin(new Zarafa.core.PluginMetaData({
		name : 'delayeddelivery',
		displayName : _('Delayed Delivery Plugin'),
		pluginConstructor : Zarafa.plugins.delayeddelivery.DelayDeliveryPlugin
	}));
});
Ext.namespace('Zarafa.plugins.delayeddelivery.data');

/**
 * @class Zarafa.plugins.delayeddelivery.data.DelayDeliveryRecordFields
 * Array of {@link Ext.data.Field field} configurations for the
 * {@link Zarafa.plugins.delayeddelivery.data.DelayDeliveryRecordFields} object.
 */
Zarafa.plugins.delayeddelivery.data.DelayDeliveryRecordFields = [{
	name : 'deferred_send_time',
	type : 'date',
	dateFormat : 'timestamp',
	defaultValue : null
}];

Zarafa.core.data.RecordFactory.addFieldToMessageClass('IPM', Zarafa.plugins.delayeddelivery.data.DelayDeliveryRecordFields);
Ext.namespace('Zarafa.plugins.delayeddelivery.dialogs');

/**
 * @class Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel
 * @extends Zarafa.core.ui.ContentPanel
 * @xtype zarafa.delayeddeliverycontentpanel
 *
 * The content panel which use to get Date and Time
 */
Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel = Ext.extend(Zarafa.core.ui.ContentPanel, {

	/**
	 * @cfg {Zarafa.mail.MailRecord} record The mail which
	 * is being update by this panel.
	 */
	record : null,

	/**
	 * @cfg {Date} deferredSendTime which is date object of selected date and time for mail
	 */
	deferredSendTime : undefined,

	/**
	 * @constructor
	 * @param {Object} config Configuration object
	 */
	constructor : function (config)
	{
		config = config || {};

		config = Ext.apply(config, {
			xtype : 'zarafa.delayeddeliverycontentpanel',
			width : 300,
			height : 250,
			title : _('Schedule mail to be sent out') + '...',
			layout : 'fit',
			items : [{
				xtype : 'zarafa.delayeddeliverypanel',
				ref : 'delayDeliveryPanel',
				buttonAlign : 'left',
				buttons : [{
					text : _('Send'),
					cls : 'zarafa-action',
					iconCls : 'icon_delaydelivery_dialog',
					ref : '../sendButton',
					disabled : true,
					handler : this.onSend,
					scope : this
				}, '->', {
					xtype : 'spacer'
				}, {
					text : _('Cancel'),
					handler : this.onCancel,
					scope : this
				}]
			}]
		});

		Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel.superclass.constructor.call(this, config);
	},

	/**
	 * Function is use to set disabled value of "send" {@link Ext.Button button}.
	 * @param {Boolean} value is true/false
	 */
	setDisabled : function (value)
	{
		this.delayDeliveryPanel.sendButton.setDisabled(value);
	},

	/**
	 * Event handler which is called when the user clicks the "Cancel" {@link Ext.Button button}
	 * @private
	 */
	onCancel : function ()
	{
		this.close();
	},

	/**
	 * Event handler which is called when the user clicks the "send" {@link Ext.Button button}
	 * Add Event listeners on saverecord and completequeue events.
	 * This will {@link Zarafa.core.ui.MessageContentPanel#sendRecord send} the given record.
	 */
	onSend : function ()
	{
		var mailCreateTab = container.getTabPanel().getActiveTab();
		this.deferredSendTime = this.delayDeliveryPanel.getMailDateTime();

		//Add listener on saverecord event for set deferred_send_time in record
		mailCreateTab.un('saverecord', this.onSaveRecord, this);
		mailCreateTab.on('saverecord', this.onSaveRecord, this);

		//Add listener on completequeue event
		mailCreateTab.sendValidationQueue.un('completequeue', this.onCompleteQueue.createDelegate(this, [mailCreateTab, this.record]), this);
		mailCreateTab.sendValidationQueue.on('completequeue', this.onCompleteQueue.createDelegate(this, [mailCreateTab, this.record]), this);
		this.close();

		//send record
		mailCreateTab.sendRecord();
	},

	/**
	 * Event handler remove event listener on saverecord if record contain validation error
	 * @param {Zarafa.mailcreatecontentpanel} dialog
	 * @param {Zarafa.core.data.IPMRecord} record The record which is going to be send
	 */
	onCompleteQueue : function (dialog, record)
	{
		if (Ext.isEmpty(record.get('deferred_send_time'))) {
			dialog.un('saverecord', this.onSaveRecord, this);
			dialog.showInfoMask = true;
		}
		dialog.sendValidationQueue.un('completequeue', this.onCompleteQueue, this);
	},

	/**
	 * Event handler set deferred_send_time in Zarafa.core.data.IPMRecord} record and
	 * Call {@link Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel#showNotification} for display notification
	 * @param {Zarafa.mailcreatecontentpanel} dialog
	 * @param {Zarafa.core.data.IPMRecord} record The record which is going to be send
	 */
	onSaveRecord : function (dialog, record)
	{
		if (dialog.isSending === true && dialog.showInfoMask === true) {
			dialog.record.set('deferred_send_time', this.deferredSendTime);
			dialog.showInfoMask = false;
			this.showNotification();
			dialog.un('saverecord', this.onSaveRecord, this);
		}
	},

	/**
	 * Function is use to show {@link Zarafa.core.ui.notifier.Notifier notification} and
	 * Set {@link Ext.util.DelayedTask notificationTimer} for remove notification.
	 */
	showNotification : function ()
	{
		var category = 'info.saved';
		var title = 'Scheduled Items';
		var notification = container.getNotifier().notify(category, title, this.sendLaterMessage(), {
			persistent : true,
			listeners : {
				click : this.onNotifierClick,
				scope : this
			}
		});
		this.notificationTimer = new Ext.util.DelayedTask(this.clearNotification.createDelegate(this, [notification], this));
		this.notificationTimer.delay(5000);
	},

	/**
	 * Function is create message that will display in {@link Zarafa.core.ui.notifier.Notifier notification}
	 * Message content deferred send time of mail and close button.
	 * @returns {String} message that will display in notification
	 */
	sendLaterMessage : function ()
	{
		var messageDateTime = this.deferredSendTime.format('d/m/y H:i');
		var upperMessage = _('Your message will be sent at ');
		var lowerMessage = _('Go to your <b>Outbox</b> to edit your email.');

		// return html string which show message and close button
		return String.format("{0}<b>{1}.</b> <br>{2}", upperMessage, messageDateTime, lowerMessage);
	},

	/**
	 * Function is use to Remove {@link Zarafa.core.ui.notifier.Notifier notification}
	 * @param {Zarafa.core.ui.notifier.Notifier} notification
	 */
	clearNotification : function (notification)
	{
		var category = 'info.saved';
		container.getNotifier().notify(category, null, null, {
			reference : notification,
			destroy : true
		});
		this.notificationTimer.cancel();
	},

	/**
	 * Event handler which is fired when the user clicked on the {@link Zarafa.core.ui.notifier.Notifier notification}.
	 * This will remove the notification.
	 * @param {Zarafa.core.ui.notifier.Notifier} notification
	 * @private
	 */
	onNotifierClick : function (notification)
	{
		this.clearNotification(notification);
	}
});

Ext.reg('zarafa.delayeddeliverycontentpanel', Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryContentPanel);
Ext.namespace('Zarafa.plugins.delayeddelivery.dialogs');

/**
 * @class Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryPanel
 * @extends Ext.Panel
 * @xtype zarafa.delayeddeliverypanel
 *
 * Panel for users to set the deferred_send_time on a given {@link Zarafa.mail.MailRecord record}
 */
Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryPanel = Ext.extend(Ext.Panel, {

	/**
	 * @cfg {Date} scheduledMailDateTime which is date object of selected date and time for mail
	 */
	scheduledMailDateTime : undefined,
	/**
	 * @constructor
	 * @param config Configuration structure
	 */
	constructor : function (config)
	{
		config = config || {};

		config = Ext.applyIf(config, {
			xtype : 'zarafa.delayeddeliverypanel',
			border : false,
			bodyStyle : 'padding: 15px; background-color: inherit;',
			defaults : {
				style : {
					margin : '0px 0px 10px 5px'
				}
			},
			items : [{
				xtype : 'zarafa.delayeddeliveryspinnerfield',
				value : _('hour(s)'),
				listeners : {
					focus : this.onFieldFocus,
					change : this.onFieldChange,
					scope : this
				}
			},{
				xtype : 'zarafa.delayeddeliveryspinnerfield',
				value : _('day(s)'),
				listeners : {
					focus : this.onFieldFocus,
					change : this.onFieldChange,
					scope : this
				}
			},{
				xtype : 'zarafa.delayeddeliveryspinnerfield',
				value : _('month(s)'),
				listeners : {
					focus : this.onFieldFocus,
					change : this.onFieldChange,
					scope : this
				}
			},{
				xtype : 'displayfield',
				value : _('at a specific time'),
				style : 'marginLeft : 10%;'
			},{
				xtype : 'zarafa.delayeddeliverydatetimefield',
				ref : 'delayDeliveryDateTimeField',
				listeners : {
					focus : this.onFieldFocus,
					change : this.onFieldChange,
					scope : this
				}
			},{
				xtype : 'displayfield',
				ref : 'timeInfofield'
			}],
			listeners : {
				afterrender : this.setDefaultValue
			}
		});
		Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryPanel.superclass.constructor.call(this, config);
	},

	/**
	 * Event handler which is called when the {@link Zarafa.plugins.delayeddelivery.DelayDeliveryDateTimeField delayDeliveryDateTimeField} or
	 * {@link Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField delayDeliverySpinnerField} field receives input focus,
	 * this will call {@link #createMessage} for updating the message value
	 * @param {Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField / DelayDeliveryDateTimeField} field The field which fired the event
	 */
	onFieldFocus : function (field)
	{
		this.createMessage(field.getDateTime());
	},

	/**
	 * Event handler which is called when the {@link Zarafa.plugins.delayeddelivery.DelayDeliveryDateTimeField delayDeliveryDateTimeField} or
	 * {@link Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField delayDeliverySpinnerField} value has changed,
	 * this will call {@link #createMessage} for updating the message value
	 * @param {Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField / DelayDeliveryDateTimeField} field The field which fired the event
	 * @param {Date} dateTime The date and time which is specified by user.
	 */
	onFieldChange : function (field, dateTime)
	{
		this.createMessage(dateTime);
	},

	/**
	 * Function is use to create message and display message.
	 * this will call {@link #getMessageDate} and {@link #showMessage} for getting the message value and display message
	 * @param {Date} value which is selected date and time
	 */
	createMessage : function (value)
	{
		var dateTime = new Date(value);
		this.scheduledMailDateTime = dateTime;
		var message = this.getMessageDate(dateTime);
		this.showMessage(message);
	},

	/**
	 * Function check date and create appropriate message using the date.
	 * @param {Date} dateTime The date and time which is specified by user.
	 * @returns {string} message which is display when record will be send.
	 */
	getMessageDate : function (dateTime)
	{
		var message = '';
		this.ownerCt.setDisabled(true);
		if (isNaN(dateTime.getTime())) {
			return message;
		}
		else if (this.isPastDate(dateTime)) {

			//If user select past time then return sorry message and disable send button.
			message = _('Sorry,the time you entered is in past. Please reschedule your mail');
			this.delayDeliveryDateTimeField.addClass('delayeddelivery_datetimefield_color');
			return message;
		} else {

			//Create appropriate message related to date and time
			var date = '';
			var time = dateTime.format('H:i');
			if (this.isTodayDate(dateTime)) {
				date = _('today  at ');
			} else if (this.isTomorrowDate(dateTime)) {
				date = _('tomorrow  at ');
			} else if (this.isDayInCurrentWeek(dateTime)) {
				date = String.format(_('{0} at '), dateTime.format('l '));
			} else {
				date = String.format(_('at {0}'), dateTime.format('F jS Y ,'));
			}
			message = String.format(_('Your email will be sent {0}{1}'), date, time);
			this.ownerCt.setDisabled(false);
			this.delayDeliveryDateTimeField.removeClass('delayeddelivery_datetimefield_color')
			return message;
		}
	},

	/**
	 * Function check whether specified date and time is in past or not.
	 * @param {Date} mailDateTime Specified date and time.
	 * @returns {boolean} true if date and time is in past
	 */
	isPastDate : function (mailDateTime)
	{
		var currentDateTime = new Date().getTime();
		var mailDate = mailDateTime.getTime();
		return mailDate < (currentDateTime - 3000);
	},

	/**
	 * Function check whether specified date is today's date or not.
	 * @param {Date} mailDateTime Specified date and time.
	 * @returns {boolean} true if date is today's date
	 */
	isTodayDate : function (mailDateTime)
	{
		var todayDate = new Date().clearTime(true);
		var mailDate = new Date(mailDateTime).clearTime(true);
		return todayDate.getTime() === mailDate.getTime();
	},

	/**
	 * Function check whether specified date is tomorrow's date or not.
	 * @param {Date} mailDateTime Specified date and time.
	 * @returns {boolean} true if date is tomorrow's date
	 */
	isTomorrowDate : function (mailDateTime)
	{
		var date = new Date().clearTime(true);
		var mailDate = new Date(mailDateTime).clearTime(true);
		var tomorrowDateTime = new Date(date.add(Date.DAY, 1));
		return tomorrowDateTime.getTime() === mailDate.getTime();
	},

	/**
	 * Function check whether specified date is in current week or not.
	 * @param {Date} mailDateTime Specified date and time.
	 * @returns {boolean} true if date is in current week else false
	 */
	isDayInCurrentWeek : function (mailDateTime)
	{
		currentDateTime = new Date();
		var first = currentDateTime.getDate() - currentDateTime.getDay();
		var last = first + 7;
		var firstDayOfWeek = new Date(currentDateTime.setDate(first));
		var lastDayOfWeek = new Date(currentDateTime.setDate(last));
		var mailDate = new Date(mailDateTime).clearTime(true);
		return mailDate.between(firstDayOfWeek, lastDayOfWeek);
	},

	/**
	 * Function display message when user select the date.
	 * Message content when your mail will be send.
	 * @param {String} message Message string created using specified date.
	 */
	showMessage : function (message)
	{
		this.timeInfofield.setValue(message);
	},

	/**
	 * Function set default value in {@link Zarafa.plugins.delayeddelivery.DelayDeliveryDateTimeField delayDeliveryDateTimeField}
	 * If record has deferred_send_time then set this date and time otherwise set current date and time
	 */
	setDefaultValue : function ()
	{
		var deferredSendTime = this.ownerCt.record.get('deferred_send_time');
		if (Ext.isEmpty(deferredSendTime)) {
			this.delayDeliveryDateTimeField.setValue(new Date());
		} else {
			this.delayDeliveryDateTimeField.setValue(deferredSendTime);
		}
		var initialDateTime = this.delayDeliveryDateTimeField.getDateTime()
		this.createMessage(initialDateTime);
	},

	/**
	 * Function return date and time which is selected by user.
	 * @returns {Date} The date object
	 */
	getMailDateTime : function ()
	{
		return this.scheduledMailDateTime;
	}
});

Ext.reg('zarafa.delayeddeliverypanel', Zarafa.plugins.delayeddelivery.dialogs.DelayDeliveryPanel);
Ext.namespace('Zarafa.plugins.delayeddelivery.ui');

/**
 * @class Zarafa.plugins.delayeddelivery.ui.DelayDeliveryDateTimeField
 * @extends Zarafa.common.ui.CompositeField
 * @xtype zarafa.delayeddeliverydatetimefield
 *
 * This class can be used to construct a {@link Ext.form.Field field}
 * which contains a {@link Ext.form.Radio} and a {@link Zarafa.common.ui.DateTimeField}
 */
Zarafa.plugins.delayeddelivery.ui.DelayDeliveryDateTimeField = Ext.extend(Zarafa.common.ui.CompositeField, {

	/**
	 * @constructor
	 * @param config Configuration structure
	 */
	constructor : function (config)
	{
		config = config || {};

		Ext.apply(this, config);
		config = Ext.applyIf(config, {
			items : [{
				xtype : 'radio',
				boxLabel : ' ',
				ref : 'sendLaterRadio',
				name : 'sendLaterRadio',
				listeners : {
					check : this.onRadioCheck,
					scope : this
				}
			},{
				xtype : 'zarafa.datetimefield',
				ref : 'dateTimeField',
				minValue : new Date,
				width : 200,
				listeners : {
					change : this.onDateTimeChange,
					afterrender : this.initEvent,
					scope : this
				}
			}]
		});
		Zarafa.plugins.delayeddelivery.ui.DelayDeliveryDateTimeField.superclass.constructor.call(this, config);
	},

	/**
	 * Event handler which is called when {@link Zarafa.common.ui.DateTimeField dateTimeField} has receives input value,
	 * If the input value is number then call the {@link Zarafa.common.ui.DateTimeField doDateChange} function.
	 * @param {Zarafa.common.ui.DateTimeField} field The field which fired the event
	 * @param {Ext.EventObject} e The event object which fired the event
	 */
	onKeyUp : function (field, e)
	{
		var keyCode = e.getCharCode();
		if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) {
			var oldValue = field.startValue;
			var newValue = field.getValue();
			this.dateTimeField.doDateChange(newValue,oldValue);
		}
	},

	/**
	 * Event handler which is called when the {@link Ext.form.Radio radioButton} is checked,
	 * and firing the {@link #focus} event.
	 * @param {Ext.form.Radio} field The field which fired the event
	 * @param {Boolean} checked true if field checked
	 */
	onRadioCheck : function (field, checked)
	{
		if (checked === true) {
			this.fireEvent('focus', this);
		}
	},

	/**
	 * Event handler which is called when the {@link Zarafa.common.ui.DateTimeField dateTimeField} receives input focus,
	 * Set true in {@link Ext.form.Radio radioButton} and
	 * Firing the {@link #focus} event.
	 * @param {Zarafa.common.ui.DateTimeField} field The field which fired the event
	 */
	onDateTimeFocus : function (field)
	{
		this.sendLaterRadio.setValue(true);
		this.fireEvent('focus', this);
	},


	/**
	 * Event handler which is called when the date has been changed,
	 * and firing the {@link #change} event.
	 * @param {Zarafa.common.ui.DateTimeField} field The field which has fired the event
	 * @param {Date} newValue The new Date inside the DateTimeField
	 * @param {Date} oldValue The old Date from the DateTimeField
	 * @private
	 */
	onDateTimeChange : function(field,newValue,oldValue)
	{

		var dateTime = this.getDateTime();
		this.fireEvent('change', this, dateTime);
	},

	/**
	 * Function is use to add listener on keyup and focus event
	 * and remove listener on change event of {@link Ext.form.DateField dateField} and a {@link Ext.ux.form.Spinner spinner}
	 */
	initEvent : function ()
	{
		var timeField = this.dateTimeField.timeField;
		var dateField = this.dateTimeField.dateField;
		timeField.enableKeyEvents = true;
		dateField.enableKeyEvents = true;
		timeField.initEvents();
		dateField.initEvents();

		// Add listener on keyup event
		timeField.on('keyup', this.onKeyUp, this);
		dateField.on('keyup', this.onKeyUp, this);

		// Add listener on focus event
		timeField.on('focus', this.onDateTimeFocus, this);
		dateField.on('focus', this.onDateTimeFocus, this);

		// Remove listener on change event
		timeField.un('change', this.dateTimeField.onTimeChange, this.dateTimeField);
		dateField.un('change', this.dateTimeField.onDateChange, this.dateTimeField);
	},

	/**
	 * Function return the {@link Zarafa.common.ui.DateTimeField dateTimeField} value
	 * @return {Date} The date object
	 */
	getDateTime : function ()
	{
		return this.dateTimeField.getValue();
	},

	/**
	 * Function set true in {@link Ext.form.Radio radioButton} and
	 * set value in {@link Zarafa.common.ui.DateTimeField dateTimeField}
	 * @param {Date} value The date object
	 */
	setValue : function (value)
	{
		this.sendLaterRadio.setValue(true);
		this.dateTimeField.setValue(value);
	},

	/**
	 * Function add css class to the  {@link Zarafa.common.ui.DateTimeField dateTimeField}
	 * @param {String} cls CSS class name
	 */
	addClass : function (cls)
	{
		this.dateTimeField.timeField.addClass(cls);
		this.dateTimeField.dateField.addClass(cls);
	},

	/**
	 * Function remove css class to the  {@link Zarafa.common.ui.DateTimeField dateTimeField}
	 * @param {String} cls CSS class name
	 */
	removeClass : function (cls)
	{
		this.dateTimeField.timeField.removeClass(cls);
		this.dateTimeField.dateField.removeClass(cls);
	}

});

Ext.reg('zarafa.delayeddeliverydatetimefield', Zarafa.plugins.delayeddelivery.ui.DelayDeliveryDateTimeField);
Ext.namespace('Zarafa.plugins.delayeddelivery.ui');

/**
 * @class Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField
 * @extends Zarafa.common.ui.CompositeField
 * @xtype zarafa.delayeddeliveryspinnerfield
 *
 * This class can be used to construct a {@link Ext.form.Field field}
 * which contains a {@link Zarafa.common.ui.SpinnerField},{@link Ext.form.Radio} and {@link Ext.form.DisplayField}
 */
Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField = Ext.extend(Zarafa.common.ui.CompositeField, {

	/**
	 * @cfg {String} value The value which is inputValue of {@link Ext.form.Radio} and value for {@link Ext.form.DisplayField}
	 */
	value : undefined,

	/**
	 * @constructor
	 * @param config Configuration structure
	 */
	constructor : function (config)
	{
		config = config || {};

		Ext.apply(this, config);
		config = Ext.applyIf(config, {
			items : [{
				xtype : 'radio',
				boxLabel : 'in',
				ref : 'sendLaterRadio',
				name : 'sendLaterRadio',
				inputValue : this.value,
				listeners : {
					check : this.onRadioCheck,
					scope : this
				}
			},{
				xtype : 'zarafa.spinnerfield',
				ref : 'spinnerField',
				defaultValue : 1,
				minValue : 1,
				maxValue : 999,
				incrementValue : 1,
				enableKeyEvents : true,
				width : 45,
				plugins : ['zarafa.numberspinner'],
				listeners : {
					spin : this.onValueChange,
					keyup : this.onValueChange,
					focus : this.onFocus,
					scope : this
				}
			},{
				xtype : 'displayfield',
				value : this.value
			}]
		});
		Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField.superclass.constructor.call(this, config);
	},

	/**
	 * Event handler which is called when the {@link Ext.form.Radio radioButton} is checked,
	 * and firing the {@link #focus} event.
	 * @param {Ext.form.Radio} field The field which fired the event
	 * @param {Boolean} checked true if field checked
	 */
	onRadioCheck : function (field, checked)
	{
		if (checked === true) {
			this.fireEvent('focus', this);
		}
	},

	/**
	 * Event handler which is called when the {@link Zarafa.common.ui.SpinnerField spinnerField} receives input focus,
	 * Set true in {@link Ext.form.Radio radioButton} and
	 * Firing the {@link #focus} event.
	 * @param {Zarafa.common.ui.SpinnerField} field The field which fired the event
	 */
	onFocus : function (field)
	{
		this.sendLaterRadio.setValue(true);
		this.fireEvent('focus', this);
	},

	/**
	 * Event handler which is called when the {@link Zarafa.common.ui.SpinnerField spinnerField} value change,
	 * and firing the {@link #change} event.
	 * @param {Zarafa.common.ui.SpinnerField} field The field which fired the event
	 */
	onValueChange : function (field)
	{
		var dateTime = this.getDateTime();
		this.fireEvent('change', this, dateTime);
	},

	/**
	 * Function create date and time using {@link Zarafa.common.ui.SpinnerField spinnerField} value
	 * @returns {Date} Date object
	 */
	getDateTime : function ()
	{
		var spinnerType = this.sendLaterRadio.getGroupValue();
		var spinnerValue = this.spinnerField.getValue();
		var currentDate = new Date();
		switch (spinnerType) {
			case 'hour(s)':
				return currentDate.add(Date.HOUR, spinnerValue);
				break;
			case 'day(s)':
				return currentDate.add(Date.DAY, spinnerValue);
				break;
			case 'month(s)':
				return currentDate.add(Date.MONTH, spinnerValue);
				break;
			default :
				return currentDate;
		}
	}
});

Ext.reg('zarafa.delayeddeliveryspinnerfield', Zarafa.plugins.delayeddelivery.ui.DelayDeliverySpinnerField);
