/*
 *  Copyright 2015 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Singleton class to handle actions on surveys.
 * @private
 */
 Ext.define('Ametys.plugins.survey.SurveyActions', {
 	singleton: true,
 	
 	/**
 	 * @private
 	 * @property {String} _mode Can be 'new or 'edit'.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _editDialogBox The dialog box for creating/editing a survey.
 	 */
 	 
	/**
	 * @private
	 * @property {Ext.form.Panel} _editFormPanel The form panel of the create/edit dialog box.
	 */
 	 
	/**
	 * @private
	 * @property {Boolean} _editInitialized Indicates if the create/edit dialog box is initialized.
	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _copyDialogBox The dialog box for copying a survey.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _copyFormPanel The form panel of the copy dialog box.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Boolean} _copyInitialized Indicates if the copy dialog box is initialized.
 	 */
 	
 	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _reinitDialogBox The dialog box for reinitializing a survey.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _reinitFormPanel The form panel of the reinit dialog box.
 	 */
 	 
 	/**
 	  * @private
 	  * @property {Boolean} _reinitInitialized Indicates if the reinit dialog box is initialized.
 	  */
 	
 	/**
 	 * Creates a new survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	add: function(controller)
 	{
 		var tool = Ametys.tool.ToolsManager.getTool('uitool-survey');
 		this._lang = tool != null ? tool.getCurrentLanguage() : null;
 		
 		this._mode = 'new';
 		this._editDelayedInitialize();
 		
 		this._editInitForm();
 	},
 	
 	/**
 	 * Edits a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	edit: function(controller)
 	{
 		var tool = Ametys.tool.ToolsManager.getTool('uitool-survey');
 		this._lang = tool != null ? tool.getCurrentLanguage() : null;
 		
		this._mode = 'edit';
 		this._editDelayedInitialize();
 		
 		this._editInitForm(controller.getMatchingTargets()[0]);
 	},
 	
 	/**
 	 * Removes a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	remove: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		Ametys.Msg.confirm("{{i18n PLUGINS_SURVEY_DELETE_SURVEY_LABEL}}",
 				"{{i18n PLUGINS_SURVEY_DELETE_SURVEY_CONFIRM}}",
 				Ext.bind(this._doRemove, this, [target], 1),
 				this
 		);
 	},
 	
 	/**
 	 * Duplicates a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	copy: function(controller)
 	{
 		var tool = Ametys.tool.ToolsManager.getTool('uitool-survey');
 		this._lang = tool != null ? tool.getCurrentLanguage() : null;
 		
 		this._copyDelayedInitialize();
 		
 		this._copyInitForm(controller.getMatchingTargets()[0]);
 	},
 	
 	/**
 	 * Validates a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 * @param {Boolean} state True is the button is toggled, false otherwise
 	 */
 	validate: function(controller, state)
 	{
 		var target = controller.getMatchingTargets()[0];
 		if (state)
 		{
 			// The controller was not pressed and is now
 			Ametys.Msg.confirm("{{i18n PLUGINS_SURVEY_VALIDATE_SURVEY_LABEL}}",
	 				"{{i18n PLUGINS_SURVEY_VALIDATE_SURVEY_CONFIRM}}",
	 				Ext.bind(this._doValidate, this, [target], 1),
	 				this
 			);
 		}
 		else
 		{
 			// The controller was pressed, and is not anymore, but we want to let it toggled and do nothing.
 			controller.toggle(true);
 		}
 	},
 	
 	/**
 	 * Reinitializes a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	reinit: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		Ametys.cms.survey.SurveyDAO.isOnline([target.getParameters().id], this._reinitThen, {scope: this});
 	},
 	
 	
 	/**
 	 * Show a dialog box for reinit action after retrieving the online status.
 	 * @param {Object} response The server response
 	 * @param {Array} args The server arguments
 	 * @param {Array} params The callback parameters
 	 */
 	_reinitThen: function(response, args, params)
 	{
 		var isOnline = response.isOnline == 'true';
 		var isValid = response.isValid == 'true';
 		var id = params[0];
 		
 		if (!isOnline)
 		{
 			var msg = isValid ? "{{i18n PLUGINS_SURVEY_REINIT_SURVEY_CONFIRM}}" : "{{i18n PLUGINS_SURVEY_REINIT_SURVEY_CONFIRM_2}}";
 			Ametys.Msg.confirm("{{i18n PLUGINS_SURVEY_REINIT_SURVEY_LABEL}}",
	 				msg,
	 				Ext.bind(this._doReinit, this, [id, true], 1),
	 				this
 			); 
 		}
 		else
 		{
 			this._reinitDelayedInitialize();
 			this._reinitDialogBox.show();
 			this._reinitInitForm(id);
 		}
 	},
 	
 	/**
 	 * Opens the preview tool for a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	preview: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0],
 			subtarget = target.getSubtargets()[0],
 			subsubtarget,
 			id = target.getParameters().id,
 			pageId,
 			questionId;
 			
 		if (subtarget)
 		{
 			pageId = subtarget.getParameters().id;
 			subsubtarget = subtarget.getSubtargets()[0];
 		}
 		if (subsubtarget)
 		{
 			questionId = subsubtarget.getParameters().id;
 		}
 		
 		var params = {
			id: id,
			pageId: pageId,
			questionId: questionId
		};
		
 		Ametys.tool.ToolsManager.openTool('uitool-survey-preview', params);
 	},
 	
 	/**
 	 * Sets a redirection page to a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 * @param {Boolean} state The new press-state of the button
 	 */
 	redirect: function(controller, state)
 	{
 		var target = controller.getMatchingTargets()[0];
 		if (!state)
 		{
 			// The controller was pressed and is no more, remove redirection
 			Ametys.cms.survey.SurveyDAO.setRedirection([target.getParameters().id, '']);
 		}
 		else
 		{
 			// The controller was not pressed, and is now, unpressed it and set a redirection page
 			controller.toggle(false);
 			
			var tool = Ametys.tool.ToolsManager.getTool('uitool-survey');
	 		this._lang = tool != null ? tool.getCurrentLanguage() : null;
 		
			Ametys.web.helper.ChoosePage.open ({
				title: "{{i18n PLUGINS_SURVEY_REDIRECTION_DIALOG_TITLE}}",
				helpMessage: "{{i18n PLUGINS_SURVEY_REDIRECTION_DIALOG_DESCRIPTION}}",
				siteContext: Ametys.getAppParameter('siteName'),
				sitemapContext: this._lang || Ametys.web.helper.ContextToolbar.SITEMAP_CONTEXT_ALL,
				defaultSitemapName: this._lang || Ametys.getAppParameter('user').locale,
				multiple: false,
				allowCreation: false,
				callback: Ext.bind(this._doRedirect, this, [target.getParameters().id], 1)
			});
 		}
 	},
 	
 	/**
 	 * Opens the limit access tool for a given survey.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	openLimitAccessTool:  function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		var params = {
			id: target.getParameters().id
		};
		
 		Ametys.tool.ToolsManager.openTool('uitool-survey-access', params);
 	},
 	
 	/**
 	 * Prints and opens a given survey
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	print: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		var previewTool = Ametys.tool.ToolsManager.getTool('uitool-survey-preview$' + target.getParameters().id);
 		
 		if (previewTool)
 		{
 			var iFrameDom = Ext.getDom(previewTool.getIframeId());
    		iFrameDom.contentWindow.print();
 		}
 	},
    
    /**
     * Exports to XLS a given survey sessions.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    exportXls: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        
        var args = {
            'id': target.getParameters().id
        };
        Ametys.openWindow(Ametys.getPluginDirectPrefix('survey') + '/survey/sessions.xls', args);
    },
    
    /**
     * Exports to XLS a summary of given survey sessions.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    summaryExportXls: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        
        var args = {
            'id': target.getParameters().id
        };
        Ametys.openWindow(Ametys.getPluginDirectPrefix('survey') + '/survey/summary/sessions.xls', args);
    },
 	
 	/**
 	 * Exports a given survey to HTML.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	export2Html: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		
 		Ametys.data.ServerComm.send({
 			plugin: 'survey',
 			url: 'survey/codehtml.xml',
 			parameters: {
 				id: target.getParameters().id
 			},
 			priority: Ametys.data.ServerComm.PRIORITY_MAJOR,
 			callback: {
 				handler: this._export2HtmlCb,
 				scope: this
 			},
 			errorMessage: {
 				msg: "{{i18n PLUGINS_SURVEY_EDIT_SURVEY_ERROR}}"
 			}
 		});
 	},
 	
 	/**
     * Initializes the dialog box to create or edit a survey. 
     * @private
     */
 	_editDelayedInitialize: function()
 	{
 		if (!this._editInitialized)
		{
			this._editFormPanel = this._createEditFormPanel();
			
			this._editDialogBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_DIALOG_TITLE}}",
	            iconCls: 'ametysicon-list24',
	            
	            width: 550,
		        scrollable: false,
	            
	            items: [this._editFormPanel],
	            
	            closeAction: 'hide',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            
	            selectDefaultFocus: true,
	            defaultFocus: 'label',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_OK}}",
	                handler: Ext.bind(this._editValidate, this)
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_CANCEL}}",
	                handler: Ext.bind(this._editCancel, this)
	            }]    
			});
			
			this._editInitialized = true;
		}
 	},
 	
 	/**
 	 * Creates the form panel of the create/edit dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createEditFormPanel: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'textfield',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 120,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	itemId: 'label',
		        	name: 'label',
		        	fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_LABEL_DESC}}",
	                allowBlank: false,
	                maxLength: 20
		        },
		        {
		        	name: 'title',
	                fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_TITLE}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_TITLE_DESC}}"
		        },
		        {
                    xtype: 'edition.file',
                    name: 'picture',
                    allowSources: [Ametys.form.widget.File.External.SOURCE, Ametys.cms.widget.File.Resource.SOURCE],
                    filter: Ametys.form.widget.File.IMAGE_FILTER,
                    fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_PICTURE_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_PICTURE_DESC}}"
                },
                {
                    xtype: 'textfield',
                    name: 'picture-alternative',
                    fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_PICTURE_ALT_LABEL}}",
                    ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_PICTURE_ALT_DESC}}"
                },
		        {
		        	xtype: 'textarea',
		        	name: 'description',
	                fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_DESCRIPTION}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_DESCRIPTION_DESC}}",
	                height: 140
		        },
		        {
		        	xtype: 'textarea',
		        	name: 'endingMessage',
	                fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_ENDING_MESSAGE}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_ENDING_MESSAGE_DESC}}",
	                height: 140
		        }
	        ]
        	
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * @private
 	 * Initializes the create/edit form with some optional values.
 	 * @param {Ametys.message.MessageTarget} [target] The target to edit
 	 */
	_editInitForm: function(target)
 	{
 		var form = this._editFormPanel.getForm();
		form.reset();
 		
 		if (this._mode === "new") 
        {
 			form.findField('id').setValue('');
		    form.findField('label').setValue("{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_LABEL_DEFAULT}}");
		    form.findField('label').clearInvalid();
		    form.findField('title').setValue('');
		    form.findField('description').setValue('');
		    form.findField('endingMessage').setValue('');
		    form.findField('picture-alternative').setValue();
		    form.findField('picture').setValue();
		    this._editDialogBox.show();
        }
 		else
 		{
 			form.findField('id').setValue(target.getParameters().id);
 			
 			Ametys.cms.survey.SurveyDAO.getSurvey([target.getParameters().id], this._editSetValues, {scope: this});
 		}
 	},
 	
 	/**
 	 * Fill the create/edit form with some values.
 	 * @param {Object} data The survey.
 	 * @private
 	 */
 	_editSetValues: function(data)
 	{
 		var form = this._editFormPanel.getForm();
 		
	    form.findField('title').setValue(data.title);
	    form.findField('label').setValue(data.label);
	    form.findField('description').setValue(data.description);
	    form.findField('endingMessage').setValue(data.endingMessage);
	    
	    form.findField('picture-alternative').setValue(data.pictureAlternative);
	    
	    if (!Ext.Object.isEmpty(data.picture))
    	{
	    	data.picture.id = 'untouched';
		    form.findField('picture').setValue(data.picture);
    	}
	    else
	    {
	    	form.findField('picture').setValue();
	    }
	    
	    this._editDialogBox.show();
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'ok' button of the create/edit dialog box
 	 */
    _editValidate: function()
    {
        var form = this._editFormPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
 		
 		if (this._mode == 'new')
 		{
 			var params = [values, Ametys.getAppParameters().siteName, this._lang];
 			Ametys.cms.survey.SurveyDAO.createSurvey(params, this._editValidateCb, {scope: this} );
 		}
 		else
 		{
 			var params = [values, Ametys.getAppParameters().siteName, this._lang];
 			Ametys.cms.survey.SurveyDAO.editSurvey(params, this._editValidateCb, {scope: this} );
 		}
    },
    
    /**
     * Callback function called after creation or edition process
     * @param {Object} response The text response provided by the {@link Ametys.data.ServerComm}
 	 * @param {Object} args The callback arguments
 	 * @private
     */
    _editValidateCb: function(response, args)
    {
    	if (!response['error'])
    	{
    		this._editDialogBox.close();
    	}
    },
 	
 	/**
     * @private
     * Callback for the "cancel" button of the create/edit dialog. Close the create/edit dialog.
     */
    _editCancel: function()
    {
        this._editDialogBox.close();
    },
    
    /**
     * Initializes the copy dialog box. 
     * @private
     */
 	_copyDelayedInitialize: function()
 	{
 		if (!this._copyInitialized)
		{
			this._copyFormPanel = this._createCopyFormPanel();
			
			this._copyDialogBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_COPY_DIALOG_TITLE}}",
	            icon: Ametys.getPluginResourcesPrefix('survey') + "/img/survey/copy_survey_16.png",
	            
	            width: 550,
		        scrollable: false,
	            
	            items: [this._copyFormPanel],
	            
	            closeAction: 'hide',
	            
	            defaultFocus: 'label',
	            selectDefaultFocus: true,
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_OK}}",
	                handler: Ext.bind(this._copyValidate, this)
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_CANCEL}}",
	                handler: Ext.bind(this._copyCancel, this)
	            }]    
			});
			
			this._copyInitialized = true;
		}
 	},
 	
 	/**
 	 * Creates the form panel of the copy dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createCopyFormPanel: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'textfield',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 120,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	itemId: 'label',
		        	name: 'label',
		        	fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_LABEL}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_LABEL_DESC}}",
	                allowBlank: false,
	                maxLength: 20
		        },
		        {
		        	name: 'title',
	                fieldLabel: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_TITLE}}",
	                ametysDescription: "{{i18n PLUGINS_SURVEY_DIALOG_SURVEY_TITLE_DESC}}"
		        }
	        ]
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * @private
 	 * Initializes the copy form with some optional values.
 	 * @param {Ametys.message.MessageTarget} target The target to copy and paste
 	 */
	_copyInitForm: function(target)
 	{
 		var form = this._copyFormPanel.getForm();
		form.reset();
		Ametys.cms.survey.SurveyDAO.getSurvey([target.getParameters().id], this._copySetValues, {scope: this});
 	},
 	
 	/**
 	 * Fill the copy form with some values.
 	 * @param {Object} data The survey.
 	 * @private
 	 */
 	_copySetValues: function(data)
 	{
 		var form = this._copyFormPanel.getForm();
 		
	    form.findField('id').setValue(data.id);
	    form.findField('title').setValue(data.title);
	    form.findField('label').setValue(data.label);

	    this._copyDialogBox.show();
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'ok' button of the copy dialog box
 	 */
    _copyValidate: function()
    {
        var form = this._copyFormPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
		var params = [values.id, values.label, values.title];
		Ametys.cms.survey.SurveyDAO.copySurvey(params, this._copyValidateCb, {scope: this} );
    },
    
    /**
     * Callback function called after copy process
     * @param {Object} response The text response provided by the {@link Ametys.data.ServerComm}
 	 * @param {Object} args The callback arguments
 	 * @private
     */
    _copyValidateCb: function(response, args)
    {
    	if (!response['error'])
    	{
    		this._copyDialogBox.close();
    	}
    },
 	
 	/**
     * @private
     * Callback for the "cancel" button of the copy dialog. Close the copy dialog.
     */
    _copyCancel: function()
    {
        this._copyDialogBox.close();
    },
    
    /**
     * Initializes the dialog box to reinit a survey. 
     * @private
     */
 	_reinitDelayedInitialize: function()
 	{
 		if (!this._reinitInitialized)
		{
			this._reinitFormPanel = this._createReinitFormPanel();
			
			this._reinitDialogBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_REINIT_SURVEY_LABEL}}",
	            iconCls: 'ametysicon-arrows130',
	            
	            width: 510,
	            height: 220,
		        scrollable: false,
	            
	            items: [this._reinitFormPanel],
	            
	            closeAction: 'hide',
	            
	            defaultFocus: 'invalidate-false',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_OK}}",
	                handler: Ext.bind(this._reinitValidate, this)
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_CANCEL}}",
	                handler: Ext.bind(this._reinitCancel, this)
	            }]    
			});
			
			this._reinitInitialized = true;
		}
 	},
 	
 	/**
 	 * Creates the form panel of the reinit dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createReinitFormPanel: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'radio',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 120,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: true,
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	xtype: 'component',
		        	html: "{{i18n PLUGINS_SURVEY_REINIT_BUZY}}"
		        },
		        {
		        	name: 'invalidate',
		        	itemId: 'invalidate-false',
		        	hideLabel: true,
		        	cls: 'checkbox',
		        	boxLabel: "{{i18n PLUGINS_SURVEY_REINIT_BUZY_CHOICE_1}}",
	                inputValue: "false",
	                checked: true,
	                style: {
		        		paddingLeft: '20px'
		        	}
		        },
		        {
		        	name: 'invalidate',
		        	itemId: 'invalidate-true',
		        	hideLabel: true,
		        	cls: 'checkbox',
	                boxLabel: "{{i18n PLUGINS_SURVEY_REINIT_BUZY_CHOICE_2}}",
	                inputValue: "true",
	                style: {
		        		paddingLeft: '20px'
		        	}
		        }
	        ]
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * @private
 	 * Initializes the reinit form with some values.
 	 * @param {String} id The survey id
 	 */
	_reinitInitForm: function(id)
 	{
 		var form = this._reinitFormPanel.getForm();
		form.reset();
 		
		form.findField('id').setValue(id);
		form.findField('invalidate').setValue(true);
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'ok' button of the reinit dialog box
 	 */
    _reinitValidate: function()
    {
        var form = this._reinitFormPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
        this._reinitDialogBox.close();
		this._doReinit('yes', values.id, values.invalidate == 'true');
    },

 	/**
     * @private
     * Callback for the "cancel" button of the reinit dialog. Close the reinit dialog.
     */
    _reinitCancel: function()
    {
        this._reinitDialogBox.close();
    },
 	 	
 	/**
 	 * @private
 	 * The action to perform when the user clicks on a button from the removing message box.
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {Ametys.message.MessageTarget} target The target to remove.
 	 */
 	_doRemove: function(btn, target)
 	{
	 	if (btn == 'yes')
	    {
	        if (target == null)
	        {
	            return;
	        }
	        
	        Ametys.cms.survey.SurveyDAO.deleteSurvey([target.getParameters().id]);
	    }
 	},
 	
 	/**
 	 * @private
 	 * The action to perform when the user clicks on a button from the validating message box.
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {Ametys.message.MessageTarget} target The target to validate.
 	 */
 	_doValidate: function(btn, target)
 	{
	 	if (btn == 'yes')
	    {
	        if (target == null)
	        {
	            return;
	        }
	        
	        Ametys.cms.survey.SurveyDAO.validateSurvey([target.getParameters().id]);
	    }
 	},
 	
 	/**
 	 * @private
 	 * The action to perform when the user clicks on a button from the reinitializing message box.
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {String} id The id of the survey to validate.
 	 * @param {Boolean} invalidate True to invalidate the survey
 	 */
 	_doReinit: function(btn, id, invalidate)
 	{
	 	if (btn == 'yes')
	    {
	        Ametys.cms.survey.SurveyDAO.reinitSurvey([id, invalidate]);
	    }
 	},
 	
 	/**
 	 * @private
 	 * The action to perform when the user clicks on the OK button from the ChoosePageHelper.
 	 * Sets a redirection page to the survey.
 	 * @param {String} pageId The page selected with the ChoosePageHelper.
 	 * @param {String} surveyId The survey to edit.
 	 */
 	_doRedirect: function(pageId, surveyId)
 	{
 		if (pageId)
 		{
			Ametys.cms.survey.SurveyDAO.setRedirection([surveyId, pageId]);
 		}
 	},
 	
 	/**
 	 * Shows the HTML code of a given survey in a dialog box.
 	 * @param {Object} response The xml http response
 	 * @private
 	 */
 	_export2HtmlCb: function(response)
 	{
 		var xmlChildren = Ext.dom.Query.select('xml/*', response);
 		
 		var html = "";
 		for (var i = 0; i < xmlChildren.length; i++) {
 			html += xmlChildren[i].outerHTML;
 		}
 		if (!this._export2htmlInitialized)
		{
			this._export2HtmlDialogBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_EXPORT_HTML_LABEL}}",
	            iconCls: 'ametysicon-html25',
	            
	            width: 570,
	            height: 550,
		        scrollable: false,
		        layout: {
		            type: 'vbox',
		            align: 'stretch' 
		        },
	            
	            items: [
		            {
		            	xtype: 'component',
		            	html: "{{i18n PLUGINS_SURVEY_EXPORT_HTML_HINT}}"
		            },
		            {
		            	xtype: 'textarea',
		            	name: 'code',
		            	itemId: 'code',
		            	hideLabel: true,
						readOnly: true,
						flex: 1
		            }
	            ],
	            
	            closeAction: 'hide',
	            defaultFocus: 'code',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_OK}}",
	                handler: function() { this._export2HtmlDialogBox.close();},
	                scope: this
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_DIALOG_BUTTON_CANCEL}}",
	                handler: function() { this._export2HtmlDialogBox.close();},
	                scope: this
	            }]    
			});
			
			this._export2htmlInitialized = true;
		}
		
		this._export2HtmlDialogBox.down("[name=code]").setValue(html);
		this._export2HtmlDialogBox.show();
 	},
 	
 	
 	/**
 	 * Sends an email inviting the granted users who did not answered yet the survey to do it.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	sendInvitations: function(controller)
 	{
 		var target = controller.getMatchingTargets()[0];
 		var surveyId = target.getParameters().id;
 		
 		this._invitationsDelayedInitialize();
 		this._invitationsDialogBox.show();
 		this._initInvitationsForm(surveyId);
 	},
 	
    /**
 	 * Initializes the dialog box for inviting users. 
 	 * @private
 	 */
 	_invitationsDelayedInitialize: function()
 	{
 		if (!this._invitationsInitialized)
		{
			this._invitationsFormPanel = this._createInvitationsFormPanel();
			
			this._invitationsDialogBox = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_SURVEY_SEND_MAIL_TITLE}}",
	            iconCls: "ametysicon-envelope64",
	            
	            width: 450,
		        scrollable: false,
	            
	            items: [this._invitationsFormPanel],
	            
	            defaultFocus: 'message',
	            closeAction: 'hide',
	            
	            referenceHolder: true,
	            defaultButton: 'validate',
	            
	            buttons: [{
	            	reference: 'validate',
	                text: "{{i18n PLUGINS_SURVEY_SEND_MAIL_BUTTON_OK}}",
	                handler: Ext.bind(this._validateInvitations, this)
	            }, {
	                text: "{{i18n PLUGINS_SURVEY_SEND_MAIL_BUTTON_CANCEL}}",
	                handler: Ext.bind(this._cancelInvitations, this)
	            }]    
			});
			
			this._invitationsInitialized = true;
		}
 	},
 	
 	/**
 	 * Creates the form panel of the invitation dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createInvitationsFormPanel: function()
 	{
 		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'component',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 70,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: false,
	        
	        items: [
		        {
	                html: "{{i18n PLUGINS_SURVEY_SEND_MAIL_HINT}}",
	                cls: 'a-text'
		        },
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	xtype: 'textarea',
                	name: 'message',
                	itemId: 'message',
                	hideLabel: true,
		        	fieldLabel: "{{i18n PLUGINS_SURVEY_SEND_MAIL_MESSAGE}}",
                	ametysDescription: "{{i18n PLUGINS_SURVEY_SEND_MAIL_MESSAGE_DESC}}",
                	height: 180,
                	allowBlank: false,
                	value: "{{i18n PLUGINS_SURVEY_SEND_MAIL_MESSAGE_DEFAULT}}"
		        },
		        {
		        	id: 'survey-invitation-mail-note',
		        	html: "{{i18n PLUGINS_SURVEY_SEND_MAIL_NOTE}}",
		        	cls: 'a-text'
		        }
	        ]
 		});
 		
 		return formPanel;
 	},
 	
    /**
 	 * Initializes the invitations form.
 	 * @param {String} surveyId The id of the survey
 	 * @private
 	 */
 	_initInvitationsForm: function(surveyId)
 	{
 		var form = this._invitationsFormPanel.getForm();
 		form.findField('id').setValue(surveyId);
	    form.findField('message').setValue("{{i18n PLUGINS_SURVEY_SEND_MAIL_MESSAGE_DEFAULT}}");
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'ok' button of the invitation dialog box.
 	 */
 	_validateInvitations: function()
    {
        var form = this._invitationsFormPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
		var params = [values.id, values.message, Ametys.getAppParameter("siteName")];
		Ametys.cms.survey.SurveyDAO.sendInvitations(params, this._validateInvitationsCb, {scope: this} );
    },
    
    /**
     * @private
     * Callback function after the invitations emails were sent.
     * @param {Object} response The response
     */
    _validateInvitationsCb: function(response)
    {
		Ametys.Msg.show({
	        title: "{{i18n PLUGINS_SURVEY_SEND_MAIL_LABEL}}",
	        msg: "{{i18n PLUGINS_SURVEY_SEND_MAIL_SUCCESS}}",
	        buttons: Ext.Msg.OK,
	        icon: Ext.MessageBox.INFO
	    });
	    this._invitationsDialogBox.close();
    },
 	
 	/**
     * @private
     * Callback for the "cancel" button of the invitation dialog box. Close it.
     */
 	_cancelInvitations: function()
    {
        this._invitationsDialogBox.close();
    }
 	
 });