Ext.onReady(function() {
	Ext.QuickTips.init();
	var useBoxLabelForLong = true;
	var extraFormStyle = 'padding-left:10px;';
	if (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.form = new Ext.FormPanel({
		border: false, autoScroll: true,
		defaultType: 'textfield',
		labelAlign: 'right', labelWidth: labelWidth,
		bodyStyle: 'padding-top:10px;'+extraFormStyle, buttonAlign: 'left',
		defaults: {labelStyle: 'white-space:nowrap'},
		buttons: [
			{
				id: 'saveBtn', width: 'auto',
				text: FR.T('Save changes'), cls: 'fr-btn-default fr-btn-primary fr-btn-smaller',
				handler: function(){FR.SaveChanges();}
			},
			{
				cls: 'fr-btn-default fr-btn-smaller', width: 'auto',
				text: FR.T('Cancel'),
				handler: function(){Ext.getCmp('tabPanel').getLayout().setActiveItem(0);}
			}
		],
		items: [
			{
	            fieldLabel: FR.T('Expiration date'), width: fieldWidth,
				name: 'expiry', xtype: 'datefield', id: 'expiry', minValue: new Date()
	        },
			{
	            xtype: 'numberfield', fieldLabel: FR.T('Download limit'), width: fieldWidth,
				name: 'download_limit', id: 'download_limit', width: 50, allowDecimals: false, allowNegative: false, autoStripChars: true
	        },
			{
	            fieldLabel: FR.T('Set a password'),
				name: 'password', id: 'password',
				selectOnFocus: true, width: fieldWidth,
				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: 'force_save', id: 'force_save', value: '1',
				labelSeparator: '', listeners: {
					render: function() {
						Ext.QuickTips.register({
							target: this.wrap.dom.lastChild,
							text: FR.T('Force the file to download, instead of having the browser open it.')
						}) ;
					}
				}
			},
			{
				fieldLabel: useBoxLabelForLong ? null: FR.T('Allow visitors to upload files'),
				boxLabel: useBoxLabelForLong ? FR.T('Allow visitors to upload files'): null,
				xtype: 'checkbox', name: 'allow_uploads', id: 'allow_uploads', value: '1',
				labelSeparator: ''
	        },
			{
				fieldLabel: useBoxLabelForLong ? null: FR.T('Receive e-mail notifications'),
				boxLabel: useBoxLabelForLong ? FR.T('Receive e-mail notifications'): null,
				xtype: 'checkbox', name: 'notify', id: 'notify', value: '1',
				labelSeparator: ''
	        },
			{
				fieldLabel: useBoxLabelForLong ? null: FR.T('Add download terms and conditions'),
				boxLabel: useBoxLabelForLong ? FR.T('Add download terms and conditions'): null,
				xtype: 'checkbox', name: 'terms', id: 'terms', value: '1', labelSeparator: '',
				listeners: {
					render: function() {
						Ext.QuickTips.register({
							target: this.wrap.dom.lastChild,
							text: FR.T('Force the visitors to accept your written terms before being able to download files.')
						}) ;
					},
					'check': function(el, checked) {
						if (checked) {
							Ext.getCmp('tabPanel').getLayout().setActiveItem(2);
						} else {
							Ext.getCmp('tabPanel').getLayout().setActiveItem(1);
						}
					}
				}
			}
		]
    });
	FR.viewport = new Ext.Viewport({
		layout: 'border', border: false,
		items: [
			{
				region: 'center', border: false, layout: 'fit',
				items: {
					activeItem: 0, border: false, id: 'tabPanel', layout: 'card',
					items: [
						{
							layout: 'fit',
							items: [
								{
									xtype: 'form', border: false,
									defaultType: 'textfield',
									bodyStyle: 'padding-top:35px;padding-left:10px;padding-bottom:20px;',
									items: [
										{
											xtype: 'component',
											autoEl: {html: '<div class="x-form-item">'+FR.T('Link address')+':</div>'}
										},
										{
											xtype: 'compositefield', hideLabel: true,
											items: [
												{
													xtype: 'textfield',
													id: 'LinkURLField', width: 330,
													style: 'font-size:14px;', height:32,
													selectOnFocus: true
												},
												{
													id: 'openBtn', xtype: 'button', style:'margin:0px;color: white',
													iconCls: 'fa fa-external-link fa-fw', cls: 'fr-btn-primary',
													handler: function(){
														window.open(Ext.getCmp('LinkURLField').getValue());
													}
												}
											]
										}
									],
									tbar: [
										{
											text: FR.T('Options'), iconCls: 'fa fa-fw fa-cog',
											handler: function() {
												Ext.getCmp('tabPanel').getLayout().setActiveItem(1);
											}
										},
										'->',
										{
											id: 'removeBtn',
											text: FR.T('Remove Web Link'), iconCls: 'fa fa-fw fa-remove colorRed',
											handler: function() {
												var url = URLRoot+'/?module=weblinks&section=ajax&page=update&action=remove';
												FR.loadMask.show();
												Ext.Ajax.request({
													url: url,
													method: 'post',
													params: {
														path: window.parent.FR.WebLinking.path
													},
													success: function(req){
														FR.loadMask.hide();
														try {
															var rs = Ext.util.JSON.decode(req.responseText);
														} catch (er){return false;}
														if (rs.success) {
															with (window.parent) {
																if (FR.WebLinking.item) {
																	if (FR.WebLinking.itemType == 'folder') {
																		if (FR.WebLinking.item.attributes.custom) {
																			FR.WebLinking.item.attributes.custom.weblink = 0;
																		}
																		FR.UI.tree.updateIcon(FR.WebLinking.item);
																	} else {
																		FR.WebLinking.item.data.hasWebLink = 0;
																		FR.UI.gridPanel.getView().refresh();
																	}
																}
																FR.UI.popups.webLink.hide();
															}
														} else {
															new Ext.ux.prompt({text: rs.msg});
														}
													}
												});
											}
										}
									], buttonAlign: 'left',
									buttons: [
										{
											id: 'shareBtn', cls: 'fr-btn-default fr-btn-primary',
											text: FR.T('Share'),
											menu: {
												items: [
													{
														text: FR.T('LinkedIn'), iconCls: 'fa fa-fw fa-linkedin',
														handler: function() {
															window.open(
																'http://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(Ext.getCmp('LinkURLField').getValue())+'&title='+encodeURIComponent(FR.WebLinkInfo.filename)+'&source='+encodeURIComponent(window.parent.Settings.title),
																Ext.isIE?'_blank':'linkedin-share-dialog',
																'width=570,height=430'
															);
														}
													},
													{
														text: FR.T('Twitter'), iconCls: 'fa fa-fw fa-twitter',
														handler: function() {
															window.open(
																'https://twitter.com/share?text='+encodeURIComponent(Ext.getCmp('LinkURLField').getValue()),
																Ext.isIE?'_blank':'twitter-share-dialog',
																'width=570,height=350'
															);
														}
													},
													{
														text: FR.T('Google+'), iconCls: 'fa fa-fw fa-google-plus',
														handler: function() {
															window.open(
																'https://plus.google.com/share?url='+encodeURIComponent(Ext.getCmp('LinkURLField').getValue()),
																Ext.isIE?'_blank':'google-share-dialog',
																'width=626,height=436'
															);
														}
													},
													{
														text: FR.T('Facebook'), iconCls: 'fa fa-fw fa-facebook',
														handler: function() {
															window.open(
																'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(Ext.getCmp('LinkURLField').getValue()),
																Ext.isIE?'_blank':'facebook-share-dialog',
																'width=626,height=436'
															);
														}
													},
													'-',
													{
														id: 'QRCBtn',
														text: FR.T('QR Code'), iconCls: 'fa fa-fw fa-qrcode',
														handler: function(){
															FR.showQRCode(Ext.getCmp('LinkURLField').getValue());
														}
													},
													{xtype: 'tbseparator', hidden: !FR.userCanEmail},
													{
														id: 'emailBtn', hidden: !FR.userCanEmail,
														text: FR.T('E-mail'),  iconCls: 'fa fa-fw fa-envelope-o',
														handler: function(){
															FR.emailLink(Ext.getCmp('LinkURLField').getValue());
														}
													}
												]
											}
										},
										'->',
										{
											id: 'linkTypeOpt',
											text: FR.T('Link type'),
											menu: {
												defaults: {
													xtype: 'menucheckitem',
													group: 'linktype', checkHandler: function(item, checked) {
														if (checked) {
															Ext.getCmp('linkTypeOpt').setText(item.text);
															if (item.value == 'short') {
																if (!FR.WebLinkInfo.short_url) {
																	FR.getShort();
																} else {
																	Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.short_url);
																}
															}  else if (item.value == 'gallery') {
																Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.url+'&mode=gallery');
															} else if (item.value == 'playlist') {
																Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.url+'&mode=playlist');
															} else if (item.value == 'rss') {
																Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.url+'&mode=rss');
															} else {
																Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.url);
															}
															Ext.getCmp('LinkURLField').getEl().highlight("dc143c", {attr: 'border-color', easing: 'easeIn', endColor: 'C1C1C1', duration: 1});
														}
													}
												},
												items: [
													{id: 'linkTypeRegular', text: FR.T('Simple Folder'), value: 'regular'},
													{id: 'linkTypeShort', text: FR.T('Short Link'), value: 'short', hidden: FR.disableShortURL},
													{text: FR.T('Image Gallery'), value: 'gallery'},
													{text: FR.T('Audio Playlist'), value: 'playlist'},
													{text: FR.T('RSS Feed'), value: 'rss'}
												]
											}
										},
										{
											id: 'shortLinkToggle',
											hidden: FR.disableShortURL,
											text: FR.T('Short Link'),
											enableToggle: true,
											toggleHandler: function (item, pressed) {
												if (pressed) {
													if (!FR.WebLinkInfo.short_url) {
														FR.getShort();
													} else {
														Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.short_url);
													}
												} else {
													Ext.getCmp('LinkURLField').setValue(FR.WebLinkInfo.url);
												}
												Ext.getCmp('LinkURLField').getEl().highlight("dc143c", {
													attr: 'border-color',
													easing: 'easeIn',
													endColor: 'C1C1C1',
													duration: 1
												});
											}
										}
									]
								}
							]
						},
						{
							layout: 'fit',
							items: FR.UI.form
						},
						{
							title: FR.T('Download Terms'), hidden: true,
							border: false, bodyStyle: 'padding:1px',
							items: {hideLabel: true, xtype: 'htmleditor', id: 'dterms', enableFont: false, height:140, width: 384},
							buttonAlign: 'left',
							buttons: [{
								id: 'saveBtn2', cls: 'fr-btn-default fr-btn-primary  fr-btn-smaller',
								text: FR.T('Done'),
								handler: function(){Ext.getCmp('tabPanel').getLayout().setActiveItem(1);}
							}]
						}
					]
				}
			}
		]
	});
	FR.SaveChanges = function() {
		FR.loadMask.show();
		FR.UI.form.getForm().submit({
			clientValidation: true,
			url: URLRoot+'/?module=weblinks&section=ajax&page=update&action=edit',
			params: {
				path: window.parent.FR.WebLinking.path,
				download_terms: Ext.getCmp('dterms').getValue()
			},
			success: function(form, action) {
				FR.loadMask.hide();
				Ext.getCmp('tabPanel').getLayout().setActiveItem(0);
				window.parent.FR.UI.feedback(action.result.msg);
			},
			failure: function(form, action) {
				FR.loadMask.hide();
				switch (action.failureType) {
					case Ext.form.Action.CLIENT_INVALID:
						new Ext.ux.prompt({text: FR.T("Please make the appropriate <br>changes to the highlighted fields.")});break;
					case Ext.form.Action.CONNECT_FAILURE:
						new Ext.ux.prompt({text: FR.T("Ajax communication failed.")});break;
					case Ext.form.Action.SERVER_INVALID:
						new Ext.ux.prompt({text: action.result.msg});
				}
			}
		});
	}
	FR.getInfo = function () {
		window.parent.Ext.get(window.parent.FR.UI.popups.webLink.getLayout().container.body.dom).mask(FR.T('Loading data...'));
		var url = URLRoot+'/?module=weblinks&section=ajax&page=load'+(FR.email ? '&email=1' : '');
		var pars = 'path='+encodeURIComponent(window.parent.FR.WebLinking.path);
		Ext.Ajax.request({
			url: url, 
			method: 'post',
			params: pars,
			success: function(req){
				window.parent.Ext.get(window.parent.FR.UI.popups.webLink.getLayout().container.body.dom).unmask();
				try {
					var rs = Ext.util.JSON.decode(req.responseText);
				} catch (er){
					FR.UI.form.getForm().reset();
					Ext.getCmp('LinkURLField').setValue('');
					return false;
				}
				Ext.getCmp('allow_uploads').setVisible((FR.userCanUpload && rs.isdir));
				Ext.getCmp('linkTypeOpt').setVisible(rs.isdir);
				Ext.getCmp('download_limit').setVisible(!rs.isdir);
				Ext.getCmp('shortLinkToggle').setVisible((!rs.isdir && !FR.disableShortURL));
				Ext.getCmp('shortLinkToggle').toggle((rs.linkInfo && rs.linkInfo.short_url), true);
				//FR.viewport.doLayout();
				if (rs.linkInfo) {
					FR.WebLinkInfo = rs.linkInfo;
					FR.WebLinkInfo.isdir = rs.isdir;
					Ext.getCmp('expiry').setValue(rs.linkInfo.expiry2);
					Ext.getCmp('download_limit').setValue(rs.linkInfo.download_limit);
					Ext.getCmp('password').setValue(rs.linkInfo.password);
					Ext.getCmp('LinkURLField').setValue(rs.linkInfo.short_url ? rs.linkInfo.short_url : rs.linkInfo.url);

					Ext.getCmp('dterms').setValue(rs.linkInfo.download_terms);
					Ext.getCmp('terms').setValue(rs.linkInfo.download_terms !== null);
					if (rs.isdir) {
						if (rs.linkInfo.short_url) {
							Ext.getCmp('linkTypeShort').setChecked(true);
						} else {
							Ext.getCmp('linkTypeRegular').setChecked(true);
						}
					}
					Ext.getCmp('force_save').setValue((rs.linkInfo.force_save == '1'));
					Ext.getCmp('allow_uploads').setValue((rs.linkInfo.allow_uploads == '1'));
					Ext.getCmp('notify').setValue((rs.linkInfo.notify == '1'));
					Ext.getCmp('tabPanel').getLayout().setActiveItem(0);
					with (window.parent) {
						if (FR.WebLinking.item) {
							if (FR.WebLinking.itemType == 'folder') {
								if (!FR.WebLinking.item.attributes.custom) {FR.WebLinking.item.attributes.custom = {};}
								FR.WebLinking.item.attributes.custom.weblink = 1;
								FR.UI.tree.updateIcon(FR.WebLinking.item);
							} else {
								FR.WebLinking.item.data.hasWebLink = 1;
								FR.UI.gridPanel.getView().refresh();
							}
						}
					}
				} else {
					FR.UI.form.getForm().reset();
					Ext.getCmp('LinkURLField').setValue('');
				}
			}
		});
	}
	FR.update = function() {
		if (FR.QRWindow) {FR.QRWindow.hide();}
		this.getInfo();
	}
	FR.getShort = function() {
		Ext.getCmp('LinkURLField').setValue(FR.T('Loading...'));
		var url = URLRoot+'/?module=weblinks&section=ajax&page=get_short';
		Ext.Ajax.request({
			url: url,
			method: 'post',
			params: {linkId: FR.WebLinkInfo.id},
			success: function(req){
				try {
					var rs = Ext.util.JSON.decode(req.responseText);
				} catch (er){return false;}
				if (rs.success) {
					FR.WebLinkInfo.short_url = rs.url;
					Ext.getCmp('LinkURLField').setValue(rs.url);
				} else {
					Ext.getCmp('LinkURLField').setValue(rs.error);
				}
			}
		});
	}
	FR.emailLink = function(url) {
		with (window.parent) {
			FR.UI.popups.webLink.hide();
			FR.actions.emailFiles([FR.WebLinking.item], true);
		}
	}

	FR.showQRCode = function (URL) {
		if (!FR.QRWindow) {
			FR.QRWindow = new window.parent.Ext.Window({
				title: FR.T('QR Code'), closeAction: 'hide', draggable: false,
				layout: 'border', width: 270, height: 270, modal: true, hideBorders: true, resizable: false,
				items: [
					{
						region: 'north', bodyStyle: 'padding:3px;text-align:center;', height: 35,
						html: FR.T('Scan this QR code with your mobile device.')
					},
					{
						region: 'center',
						html: '<div style="text-align:center;"><div style="display:inline-block;background-image:url(images/fileman/interface/thumbnail_loading.gif);background-position: center center;background-repeat:no-repeat;width:148px;height:148px;" id="qrwrap"><img src="'+URLRoot +'/?module=fileman&section=utils&page=qrcode&data='+encodeURIComponent(URL)+'" width="148" height="148" border="0" alt="" /></div></div>'
					}
				]
			});
		}
		FR.QRWindow.show();
	}
	window.parent.Ext.get(window.parent.FR.UI.popups.webLink.getLayout().container.body.dom).unmask();
	FR.loadMask = new Ext.LoadMask(Ext.getCmp('tabPanel').el, {msg: window.parent.FR.T('Loading...')});
	FR.getInfo();
});