Ext.onReady(function() {
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
		path: location.pathname.match(/.*\//),
		expires: new Date(new Date().getTime()+(1000*60*60*24*30))
	}));
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Ext.QuickTips.init();
	
	var grid = new Ext.grid.GridPanel({
		store: new Ext.data.JsonStore({
			fields: [
				{name: 'pattern'},
				{name: 'replacement'},
				{name: 'subject'}
			],
			data: Ext.state.Manager.get('regexes', []),
			save: function() {
				var record = [];
				this.each(function(r) {
					record.push(r.data);
				});
				Ext.state.Manager.set('regexes', record);
			},
			listeners: {
				add: function() {this.save();},
				remove: function() {this.save();}
			}
		}),
		columns: [
			{
				id: 'pattern',
				header: __('Pattern'),
				sortable: true,
				dataIndex: 'pattern',
				renderer: 'htmlEncode'
			}, {
				header: __('Replacement'),
				sortable: true,
				dataIndex: 'replacement',
				renderer: 'htmlEncode'
			}, {
				header: __('Subject'),
				sortable: true,
				dataIndex: 'subject',
				renderer: 'htmlEncode'
			}
		],
		autoExpandColumn: 'pattern',
		stripeRows: true,
		border: false,
		tbar: [
			{
				text: __('Remove'),
				ref: '../removeBtn',
				iconCls: 'remove',
				disabled: true,
				handler: function() {
					grid.getSelectionModel().each(function(r) {
						grid.getStore().remove(r);
					});
					grid.getSelectionModel().selectFirstRow();
				}
			}
		]
	});

	var loadWindow = new Ext.Window({
		title: __('Load'),
		width: 640,
		height: 480,
		layout: 'fit',
		closeAction: 'hide',
		modal: true,
		items: grid,
		buttons: [
			{
				text: __('Load'),
				ref: '../loadBtn',
				disabled: true,
				handler: function() {
					loadWindow.loadRegex();
				}
			}
		],
		loadRegex: function() {
			Ext.getCmp('regex').getForm().setValues(grid.getSelectionModel().getSelected().data);
			this.hide();
		}
	});
	
	grid.on('rowdblclick', function() {
		loadWindow.loadRegex();
	});
	
	grid.getSelectionModel().on('selectionchange', function(sm) {
		grid.removeBtn.setDisabled(sm.getCount() < 1);
		loadWindow.loadBtn.setDisabled(sm.getCount() != 1);
	});
	
	var viewport = new Ext.Viewport({
		layout: 'border',
		items: [
			new Ext.BoxComponent({
				region: 'north',
				height: 32,
				el: 'header'
			}), {
				region: 'west',
				margins: '0 0 5 5',
				cmargins: '0 5 5 5',
				title: __('Sidebar'),
				split: true,
				width: 250,
				collapsible: true,
				defaults: {
					border: false,
					bodyStyle: 'padding: 5px'
				},
				items: [
					new Ext.form.FormPanel({
						title: __('Settings'),
						id: 'setting',
						iconCls: 'setting',
						labelWidth: 65,
						items: [
							{
								xtype: 'checkboxgroup',
								fieldLabel: __('Flags'),
								id: 'flags',
								columns: 1,
								items: [
									{name: 'preg_pattern_order', boxLabel: 'PREG_PATTERN_ORDER'},
									{name: 'preg_set_order', boxLabel: 'PREG_SET_ORDER'},
									{name: 'preg_offset_capture', boxLabel: 'PREG_OFFSET_CAPTURE'}
								]
							}, {
								xtype: 'numberfield',
								id: 'offset',
								fieldLabel: __('Offset'),
								allowDecimals: false,
								allowNegative: false,
								style: {
									marginBottom: '1em'
								}
							}, {
								xtype: 'label',
								text: __('These options affect only $matches.')
							}
						]
					}), {
						title: __('PHP manual'),
						iconCls: 'manual',
						contentEl: 'manual'
					}, {
						title: __('About'),
						iconCls: 'about',
						contentEl: 'about'
					}
				]
			}, {
				region: 'center',
				margins: '0 5 5 0',
				border: false,
				layout: 'border',
				items: [
					new Ext.form.FormPanel({
						region: 'north',
						title: __('Regex'),
						id: 'regex',
						iconCls: 'regex',
						split: true,
						height: 200,
						layout: {
							type: 'vbox',
							align: 'stretch'
						},
						bodyStyle: 'padding: 5px',
						defaults: {
							plugins: [Ext.ux.FieldLabeler]
						},
						items: [
							{
								xtype: 'textfield',
								fieldLabel: __('Pattern'),
								id: 'pattern',
								value: ''
							}, {
								xtype: 'textfield',
								fieldLabel: __('Replacement'),
								id: 'replacement'
							}, {
								xtype: 'textarea',
								fieldLabel: __('Subject'),
								id: 'subject',
								flex: 1
							}
						],
						tbar: [
							{
								text: __('Save'),
								id: 'saveBtn',
								iconCls: 'save',
								disabled: true,
								handler: function() {
									var store = grid.getStore();
									store.add(new store.recordType(Ext.getCmp('regex').getForm().getValues()));
								}
							}, {
								text: __('Load'),
								iconCls: 'load',
								handler: function() {
									loadWindow.show();
								}
							}, {
								text: __('Clear'),
								id: 'clearBtn',
								iconCls: 'clear',
								disabled: true,
								handler: function() {
									Ext.getCmp('regex').getForm().reset();
								}
							}, {
								text: __('Copy'),
								iconCls: 'copy',
								handler: function() {
									var func = String.format(
										"preg_replace('{0}', '{1}', $subject)",
										Ext.getCmp('pattern').getValue().replace("'", "\\'"),
										Ext.getCmp('replacement').getValue().replace("'", "\\'")
									);
									Ext.Msg.alert(__('Copy this'), func);
								}
							}, '->', {
								xtype: 'tbtext',
								id: 'loadIcon',
								text: __('Loading...'),
								cls: 'busy',
								hidden: true
							}
						]
					}), {
						region: 'center',
						layout: 'anchor',
						defaults: {
							bodyStyle: 'padding: 5px',
							border: false,
							autoScroll: true,
							anchor: '100% 50%'
						},
						items: [
							{
								title: __('Match result'),
								id: 'match-result',
								iconCls: 'match-result'
							}, {
								title: __('Replace result'),
								id: 'replace-result',
								iconCls: 'replace-result'
							}
						]
					}, {
						region: 'east',
						title: '$matches (preg_match_all)',
						id: 'matches',
						iconCls: 'matches',
						width: 300,
						bodyStyle: 'padding: 5px',
						collapsible: true,
						split: true,
						autoScroll: true
					}
				]
			}
		]
	});
	
	var cache = 'pattern=&replacement=&subject=&offset=';
	var busy = false;
	Ext.TaskMgr.start({
		run: function() {
			var regexForm = Ext.getCmp('regex').getForm().getValues(true);
			if (regexForm == 'pattern=&replacement=&subject=') {
				Ext.getCmp('saveBtn').disable();
				Ext.getCmp('clearBtn').disable();
			} else {
				Ext.getCmp('saveBtn').enable();
				Ext.getCmp('clearBtn').enable();
			}
			
			var data = regexForm + '&' + Ext.getCmp('setting').getForm().getValues(true);
			if (!busy && cache != data) {
				busy = true;
				Ext.getCmp('loadIcon').show();
				RegexChecker.getInfo(Ext.urlDecode(data), function (result) {
					cache = data;
					busy = false;
					Ext.getCmp('match-result').body.update('<pre>' + result.match + '</pre>');
					Ext.getCmp('replace-result').body.update('<pre>' + result.result + '</pre>');
					Ext.getCmp('matches').body.update('<pre>' + result.matches + '</pre>');
					if (result.error != false) {
						Ext.getCmp('pattern').markInvalid(result.error);
					} else {
						Ext.getCmp('pattern').clearInvalid();
					}
					Ext.getCmp('loadIcon').hide();
				});
			}
		},
		interval: 800
	});
	
	setTimeout(function() {
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({remove: true});
	}, 500);
});
