Ext.onReady(function() {
	FR.update = function() {
		var html = '';
		FR.sendWebLinks = window.parent.FR.sendingByEmail.sendLinks;
		FR.filePaths = [];
		Ext.each(window.parent.FR.sendingByEmail.items, function(item) {
			if (item.ownerTree) {
				var icon = 'f.png';
				var filename = item.attributes.pathname;
				var filePath = item.getPath('pathname');
				FR.sendWebLinks = true;
			} else {
				var icon = item.data.icon;
				var filename = item.data.filename;
				var filePath = item.data.path ? item.data.path : window.parent.FR.currentPath+'/'+filename;
				if (item.data.isFolder) {
					FR.sendWebLinks = true;
				} else {
					if (FR.WebLinksForLargerFiles) {
						if (item.data.filesize > FR.WebLinksForLargerFiles) {
							FR.sendWebLinks = true;
						}
					}
				}
			}
			html += '<div style="white-space:nowrap;">';
			html += '<img src="'+URLRoot+'/images/fico/'+icon+'" align="absmiddle" style="margin-bottom:1px;" width="16" height="16" border="0"><span style="margin-left:3px;">'+filename+'</span>';
			if (!item.ownerTree && !item.data.isFolder) {
				html += ' <span style="color:gray;font-size:11px">('+item.data.nice_filesize+')</span>';
			}
			html += '</div>';

			FR.filePaths.push(filePath);
		});
		Ext.get('attachments').update(html);
		Ext.getCmp('weblinks').setValue(FR.sendWebLinks);
	}
	
	var addressHistory = [];
	var addressHistoryStoreData = [];
	var histCookie = Ext.util.Cookies.get("historyAddresses");
	if (histCookie != null) {
		addressHistory = Ext.util.JSON.decode(histCookie);
		var t = [];
		Ext.each(addressHistory, function(item) {if (item.length > 3){t.push([item]);}});
		addressHistoryStoreData = t;
	}
	
	FR.UI.form = new Ext.FormPanel({
		autoHeight: true, border: false,
		defaultType: 'textfield',
		labelAlign: 'right', labelWidth: 90,
		bodyStyle: 'margin-left:5px;margin-top:5px;',
		defaults: {width: 300, labelStyle: 'white-space:nowrap'},
		items: [
			{fieldLabel: FR.T('From'), name: 'from', minLength: 5, value: FR.defaultFrom, allowBlank: false, readOnly: !FR.usersCanEditAddress},
			{fieldLabel: FR.T('To'), id: 'toField', name: 'to', allowBlank: false,
				xtype: 'combo', id: 'toField', emptyText: FR.T('Separate recipients by ,'),
				store: new Ext.data.ArrayStore({
					fields: ['addr'],
					data: addressHistoryStoreData,
					sortInfo: {field: 'addr', direction: 'DESC'}
				}),
				typeAhead: true,
				displayField: 'addr',
				mode: 'local',
				triggerClass: 'x-form-address-trigger',
				onTriggerClick: function(e, btn) {
					if (!FR.chooser) {
						FR.chooser = new UserChooser();
					}
					FR.chooser.show(btn, function(data) {
						if (data.users) {
							Ext.each(data.users, function(user) {
								var s = Ext.getCmp('toField').getValue();
								s += s.length > 0 ? ', ' : '';
								Ext.getCmp('toField').setValue(s+user.name);
							});
						}
						if (data.groups) {
							Ext.each(data.groups, function(group) {
								var s = Ext.getCmp('toField').getValue();
								s += s.length > 0 ? ', ' : '';
								Ext.getCmp('toField').setValue(s+'['+group.name+']');
							});
						}
					});
					FR.chooser.clearChecked();
				}
			},
			{fieldLabel: FR.T('Subject'), name: 'subject', allowBlank: false},
			{fieldLabel: FR.T('Message'), xtype: 'textarea', height: 120, name: 'message'},
			{fieldLabel: FR.T('Attachments'), xtype: "field", value: '', autoCreate: {tag: 'div', children: [
				{tag: 'div', id: 'attachments', 'class': 'x-form-text', style:'overflow:auto;height:62px;', html: 'Loading...'}
			]}},
			{
				boxLabel: FR.T('Send WebLinks instead of attaching the files.'),
				xtype: 'checkbox', name: 'weblinks', id: 'weblinks', value: '1',
				hidden: !(window.parent.User.perms.weblink && window.parent.User.perms.download),
				listeners: {
					'check': function(f, checked) {this.ownerCt.set_weblinks.setVisible(checked);}
				}
			},
			{
				boxLabel: FR.T('Overwrite existing WebLink settings'), hidden: true, ref: 'set_weblinks',
				xtype: 'checkbox', name: 'set_weblinks', id: 'set_weblinks', value: '1',
				listeners: {
					'check': function() {FR.clickWebLinkOption(this)}
				}
			}
		]
    });

	var useBoxLabelForLong = true;
	var extraFormStyle = 'padding-left:10px;';
	if (window.parent.FR.language == 'german') {
		var labelWidth = 215;
		var fieldWidth = 135;
		var useBoxLabelForLong = false;
	} else if (FR.language == 'french') {
		var labelWidth = 240;
		var fieldWidth = 120;
		var useBoxLabelForLong = false;
		extraFormStyle = 'padding-left:5px;';
	} else {
		var labelWidth = 130;
		var fieldWidth = 220;
	}

	FR.UI.webLinksForm = new Ext.FormPanel({
		border: false,
		defaultType: 'textfield',
		labelAlign: 'right', labelWidth: labelWidth,
		bodyStyle: 'padding-top:10px;'+extraFormStyle,
		defaults:{width: fieldWidth, labelStyle: 'white-space:nowrap'},
		items: [
			{fieldLabel: FR.T('Expiration date', 2), name: 'wl_expiry', xtype: 'datefield', id: 'wl_expiry', minValue: new Date(), value: ''},
			{fieldLabel: FR.T('Download limit', 2), name: 'wl_download_limit', width: 50, id: 'wl_download_limit'},
			{fieldLabel: FR.T('Set a password', 2), name: 'el_password', id: 'wl_password', value: '',
				selectOnFocus: true,
				listeners: {
					'focus': function() {
						if (this.getRawValue().length == 0) {
							this.setValue(randomPass(12, true, true, true, true, 2));
							this.getEl().dom.select();
						}
					}
				}
			},
			{
				fieldLabel: useBoxLabelForLong ? null: FR.T('Prompt the visitor to save the file'),
				boxLabel: useBoxLabelForLong ? FR.T('Prompt the visitor to save the file'): null,
				xtype: 'checkbox', name: 'wl_force_save', id: 'wl_force_save', value: '1',
				labelSeparator: ''
			},
			{
				fieldLabel: useBoxLabelForLong ? null: FR.T('Receive e-mail notifications'),
				boxLabel: useBoxLabelForLong ? FR.T('Receive e-mail notifications', 2): null,
				xtype: 'checkbox', name: 'wl_notify', id: 'wl_notify', value: '1'
			}
		]
    });
	
	FR.clickWebLinkOption = function(checkbox) {
		if (!checkbox.checked) {return false;}
		if (!FR.webLinksOptWin) {
			FR.webLinksOptWin = new Ext.Window({
				title: FR.T('Web Link Options'), width: 390, height: 260, resizable: false, draggable: false,
				modal: true, closeAction: 'hide', closable: false, items: FR.UI.webLinksForm, layout: 'fit',
				bbar: [
					{
						text: FR.T('Done'), cls: 'fr-btn-default fr-btn-primary  fr-btn-smaller',
						handler: function(){FR.webLinksOptWin.hide();}
					}
				]
			});
		}
		FR.webLinksOptWin.show();
	}
	new Ext.Viewport({
		layout: 'border', border: false,

		items: [
			{
				region: 'center', layout: 'fit', border: false,
				items: [FR.UI.form], buttonAlign: 'left',
				buttons: [
					{
						cls: 'fr-btn-default fr-btn-primary',
						text: FR.T("Send"),
						handler: function() {
							FR.UI.form.getForm().submit({
								waitMsg: FR.T('Sending e-mail, please wait...'),
								clientValidation: true,
								url: URLRoot+'/?module=email&section=ajax&page=send',
								timeout: 18000,
								params: {
									'filePaths[]': FR.filePaths,
									wl_expiry: Ext.getCmp('wl_expiry').getRawValue(),
									wl_download_limit: Ext.getCmp('wl_download_limit').getValue(),
									wl_password: Ext.getCmp('wl_password').getValue(),
									wl_notify: (Ext.getCmp('wl_notify').getValue() ? 1 : 0),
									wl_force_save: (Ext.getCmp('wl_force_save').getValue() ? 1 : 0)
								},
								success: function(form, action) {
									if (action.result) {
										new Ext.ux.prompt({text: action.result.msg, callback: function() {window.parent.FR.UI.popups.emailFiles.hide();}});

										var recipients = Ext.getCmp('toField').getValue().split(',');
										Ext.each(recipients, function(item) {
											item = Ext.util.Format.trim(item);
											if (addressHistory.indexOf(item) == -1) {addressHistory.push(item);}
										});
										var expiry = new Date();
										expiry.setTime(expiry.getTime()+(90*24*60*60));
										Ext.util.Cookies.set("historyAddresses", Ext.util.JSON.encode(addressHistory), expiry);
									} else {
										new Ext.ux.prompt({text: FR.T('Invalid server reply')});
									}
								},
								failure: function(form, action) {
									if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
										new Ext.ux.prompt({text: FR.T("Please make the appropriate <br>changes to the highlighted fields.")});
									} else if (action.failureType == Ext.form.Action.CONNECT_FAILURE) {
										new Ext.ux.prompt({text: FR.T("Ajax communication failed.")});
									} else if (action.failureType == Ext.form.Action.SERVER_INVALID) {
										if (action.result.msg) {
											new Ext.ux.prompt({text: action.result.msg});
										} else {
											new Ext.ux.prompt({text: FR.T('Unexpected reply from this application\'s server')});
										}
									}
								}
							});
						}
					}
				]
			}
		]
	});
	
	window.parent.Ext.get(window.parent.FR.UI.popups.emailFiles.getLayout().container.body.dom).unmask();
	FR.update();
});