IntervalUI.js 9.19 KB
/**
 * Project   : AMDA-NG
 * Name      : IntervalUI.js
 * @class 	 amdaUI.IntervalUI
 * @extends  Ext.container.Container
 * @brief    common component to select interval
 * @author 	 Benjamin
 * @version  $Id: IntervalUI.js 2077 2014-02-11 11:33:36Z elena $
 * @todo Validations
 *****************************************************************************
 * FT Id     :   Date   : Name - Description
 ******************************************************************************
 */

/**
config:
- durationLimit: The maximum value of the duration days field (9999 by default).
*/
Ext.define('amdaUI.IntervalUI', {
    extend: 'Ext.container.Container',
    alias: 'widget.intervalSelector',
    activeField : null,

	constructor: function(config) {
		this.init(config);
		this.callParent(arguments);
	},

	/**
	Set the start and stop date, and update the duration field.
	- startDate: A Extjs Date object representing the new start time.
	- stopDate: A Extjs Date object representing the new stop time.
	- return: None.
	*/
	setInterval: function(startDate, stopDate) {
		// get the search form
		var form = this.findParentByType('form').getForm();
		// get start field
		var startField = form.findField('startDate');
		// get stop field
		var stopField = form.findField('stopDate');

		if (startField != null)
			startField.setValue(startDate);

		if (stopField != null)
			stopField.setValue(stopDate);

		this.updateDuration();
	},

	/**
	Set the limits values of both startField and stopField date fields.
	*/
	setLimits: function(minValue, maxValue) {
		var form = this.findParentByType('form').getForm();
		var startField = form.findField('startDate');
		var stopField = form.findField('stopDate');

		if (startField != null) {
			startField.setMinValue(minValue);
			startField.setMaxValue(maxValue);
		}

		if (stopField != null) {
			stopField.setMinValue(minValue);
			stopField.setMaxValue(maxValue);
		}

		this.updateDuration();
	},

	/**
	Get the start time field value.
	- return: A Extjs Date object representing the start time (null if the date is not valid).
	*/
	getStartTime: function() {
		// get the search form
		var form = this.findParentByType('form').getForm();
		// get start field
		var startField = form.findField('startDate');

		return startField.getValue();
	},

	/**
		Get the stop time field value.
		- return: A Extjs Date object representing the stop time (null if the date is not valid).
	*/
	getStopTime : function()
	{
		// get the search form
        var form = this.findParentByType('form').getForm();
        // get stop field
        var stopField = form.findField('stopDate');

        return stopField.getValue();
	},

	/*
		#### Private methods from here ####
	*/

    updateDuration: function() {
        // get the search form
        var form = this.findParentByType('form').getForm();
        // get start value
        var start = this.getStartTime();
        // get stop value
        var stop = this.getStopTime();
        // if duration computable
        if (stop != null && start != null) {

            // compute offset
            var zoneOffset = stop.getTimezoneOffset() - start.getTimezoneOffset();
            // compute duration
            var diff = stop - start - zoneOffset*60000;

            var durationDays = Math.floor(diff/86400000);
            // set all duration values
            form.findField('durationDay').setValue(Ext.String.leftPad(durationDays, ('' + this.durationLimit).length, '0'));
            form.findField('durationHour').setValue(Ext.String.leftPad(Math.floor(diff/3600000 % 24),2,'0'));
            form.findField('durationMin').setValue(Ext.String.leftPad(Math.floor(diff/60000 % 60),2,'0'));
            form.findField('durationSec').setValue(Ext.String.leftPad(Math.floor(diff/1000 % 60),2,'0'));

            if (durationDays > this.durationLimit) {
                form.findField('durationDay').markInvalid('Maximum interval is ' + this.durationLimit + ' days!');
            }
        }

    },

    isValidDuration: function(){
        // get the time form
        var form = this.findParentByType('form').getForm();
        // get global validation status for duration fields
        return (
                form.findField('durationDay').isValid() && form.findField('durationHour').isValid()
                && form.findField('durationMin').isValid() && form.findField('durationSec').isValid()
        );// return true if all duration fields are Valid false otherwise
    },

    updateStop: function() {
        // get the time form
        var form = this.findParentByType('form').getForm();
        // get duration value
        var duration =  parseInt(form.findField('durationDay').getValue(),10)*86400 +
        parseInt(form.findField('durationHour').getValue(),10)*3600 +
        parseInt(form.findField('durationMin').getValue(),10)*60  +
        parseInt(form.findField('durationSec').getValue(),10);
        // get start value
        var start = form.findField('startDate').getValue();
        // compute stop value
        var stop = Ext.Date.add(start,Ext.Date.SECOND,duration);
        // set stop value into form
        form.findField('stopDate').setValue(stop);

    },

	onChangeStartField : function(field, newValue, oldValue)
	{
        if (field.isValid())  {
        // get the search form
            var form = this.findParentByType('form').getForm();
            // set to the stop datefield the newValue as minValue
            form.findField('stopDate').setMinValue(newValue);
            // if it's a user modification
            if (oldValue != null && this.activeField == 'start')  {
                // launch the update of duration fields
                this.updateDuration();
            }
    }
	},

	onChangeStopField: function(field, newValue, oldValue) {
        if (field.isValid() && oldValue != null  && this.activeField == 'stop') {
            // launch the update of duration fields
            this.updateDuration();
        }
    },

	getDateField : function(fieldName,fieldText,fieldId,onChangeField)
	{
		return {
			layout: {type: 'hbox', align: 'middle'},
            items: [
                {
					xtype: 'datefield',
					name: fieldName,
					emptyText: 'YYYY/MM/DD hh:mm:ss',
					format: 'Y/m/d H:i:s',
					enforceMaxLength: true,
					maxLength: 19,
					fieldLabel: fieldText,
                    labelAlign: 'left',
					labelWidth: 60,
                    listeners: {
                        change: onChangeField,
                        focus: function(field) {
                            this.activeField = fieldId;
                        },
                        scope : this
                    }
                }
            ]
        };
	},

	getStartField : function()
	{
		return this.getDateField('startDate','Start Time','start', this.onChangeStartField);
	},

	getStopField : function()
	{
		return this.getDateField('stopDate','Stop Time','stop',this.onChangeStopField);
	},

	getDurationField : function()
	{
            return {
            layout: {type: 'hbox', align: 'middle'},
            margin: 0,
            defaults: {
                xtype: 'textfield',
                labelAlign: 'left',
                width: 35,
                margin: '0 5 0 0',
                allowBlank: false, maxLength:2, enforceMaxLength : true,
                hideTrigger: true,
                regex: /^[0-9]([0-9])*$/i,
                listeners: {
                    change: function(field, newValue, oldValue){
                        if (this.isValidDuration() && oldValue != null && this.activeField == 'duration')  {
                            // launch the update of stop datefield
                            this.updateStop();
                        }
                    },
                    focus: function(field) {
                        this.activeField = 'duration';
                    },
                    render: function(c) {
                        Ext.create('Ext.tip.ToolTip', {
                            target: c.getEl(),
                            html: c.tip
                        });
                    },
                    scope : this
                }
            },
            items:[
                // { xtype: 'displayfield', labelWidth: 60, labelAlign: 'right', },
                { name: 'durationDay', tip: 'Days', fieldLabel: 'Duration', labelWidth: 60, emptyText: 'Days', width: 100, maxLength: ('' + this.durationLimit).length},
                { name: 'durationHour', tip: 'Hours', emptyText: 'Hrs'},
                { name: 'durationMin', tip: 'Minutes', emptyText: 'Mins'},
                { name: 'durationSec', tip: 'Seconds', emptyText: 'Secs'}
            ]
        };
	},

    init : function(config) {
		this.durationLimit = config.durationLimit == null ? 9999 : config.durationLimit; // Set duration limit to 9999 by default

        var me = this;

        var myConf = {
                    border: false,
                    plain: true,
                    flex: 1,
                    layout: 'anchor',
                    defaults: { margin: '0 0 5 0', xtype : 'container'},

                    items: [
                            me.getStartField(),
                            me.getStopField(),
                            me.getDurationField()
                        ]
        };
        Ext.apply (this , Ext.apply (arguments, myConf));
	}
});