// ExtJS initialize
Ext.state.Manager.setProvider( new Ext.state.CookieProvider() );
Ext.Ajax.disableCaching = false;
Ext.Ajax.method = "GET";
Ext.QuickTips.init();


iii.shareprice.apps.fixed = {
	layout: {
		north: new Ext.Panel({
			layout: 'column',
			id: 'north',
			region: 'north',
			height: 46,
			border: true,
			margins: '5 5 5 5',
			layoutConfig: {
				columns: 3
			},
			cls: 'b',
			items: [
				new Ext.Panel({
					id: 'logo',
					html: '<a href="./" title="shareprice"><img alt="shareprice.co.uk" src="./img/logos/logo.png"/></a>',
					columnWidth: .33
				}),
				new Ext.Panel({
					id: 'growl',
					html: '&nbsp;',
					columnWidth: .66
				}),
				new Ext.Toolbar( {
					id: 'userbar',
					cls: 'toolbar',
					autoWidth: true,
					items: [
						{
							id: 'status',
							text: 'Login / Register for live prices',	
							disabled: true
						},
						{
							id: 'login',
							text: 'login',
							handler: function ( ) {
								iii.shareprice.apps.fixed.layout.login.show();
							}
						},
						{
							id: 'logout',
							text: 'logout',
							hidden: true,
							handler: function ( ) {
								iii.shareprice.apps.stockexplorer.user.set();
							}
						},
						
						{
							id: 'register',
							text: 'register',
							handler: function ( ) {
								iii.shareprice.apps.stockexplorer.fireEvent( 'content-before-show', [ 'register' ] );
							}
						},
						{
							id: 'help',
							text: 'help',
							handler: function ( ) {
								iii.shareprice.apps.stockexplorer.fireEvent( 'content-before-show', [ 'help' ] );
							}
						},
						{
							id: 'report-a-bug',
							text: 'report a bug ?',
							disabled: true,
							style: 'display: none',
							handler: function ( ) {
								iii.shareprice.apps.fixed.layout.bugreportwindow.show();
							}
						},
						new Ext.Button ( {
							id: 'startstopstreamingbtn',
							disabled: true,
							enableToggle: true,
							text: 'start streaming',
							toggleHandler: function ( btn, toggle ) {
								toggle == true ? iii.shareprice.apps.stockexplorer.fireEvent( 'stream-start' ) : iii.shareprice.apps.stockexplorer.fireEvent( 'stream-stop' );
							}
						} )
					]
				} )
				
			]
		}),
		west: new Ext.Panel( {
			id: 'west',
			region : 'west',
			split: false,
			height: 600,
			width: 250,
			minSize: 200,
			maxSize: 500,
			margins: '0 5 0 5',
			title: '&nbsp;',
			collapsible: true,
			titleCollapse: true,
			stateful: true,
			items: [
				{
					id: 'search-stock-box',
					html: '<table style="width:auto" valign="top"><tr>' +
						'<td><span class="search-stock-input-left">&nbsp;</span></td>' +
						'<td style="width:auto"><input id="search-stock-input" tabindex="1" class="search-stock-input" /></td>' +
						'<td><span class="search-stock-input-right">&nbsp;</span></td>' +
						'</tr></table>'
				},
				new Ext.Panel( {
					id: 'recent',
					layout:'accordion',
					defaults: {
						bodyStyle: 'padding:0px',
						autoScroll: true,
						autoHeight: true
					},
					layoutConfig: {
						animate: true,
						forceFit: true
					},
					fill: true,
					height: '100',
					items: [ {
						id : 'recentSearch',
						title: 'Recent Searches',
						html: '',
						stateful: true,
						stateEvents: [ 'expand', 'collapse' ],
						stateId: 'recent-search-body',
						getState: function ( ) {
							return {
								collapsed: this.collapsed
							};
						}
					} ]
				} ),
				new Ext.Panel( {
					id : 'portfolio',
					layout:'accordion',
					defaults: {
						bodyStyle: 'padding:0px',
						autoScroll: true,
						autoHeight: true
					},
					layoutConfig: {
						animate: true,
						forceFit: true
					},
					fill: true,
					height: '100',
					items: [ {
						id : 'portfolios',
						title: 'Quick Lists',
						html: '<p style="padding: 0.3em 0.5em;">Coming Soon</p>',
						stateful: true,
						stateEvents: [ 'expand', 'collapse' ],
						stateId: 'portfolio-body',
						getState: function ( ) {
							return {
								collapsed: this.collapsed
							};
						}
					} ]
				} )
                            ]
		} ),
		center: new Ext.Panel( {
			id: 'center',
			region : 'center',
			autoScroll: true,
			height: 100,
			minSize: 100,
			margins: '0 5 0 0',
			layout: 'fit',
			stateful: true,
			items: [
				new Ext.TabPanel({
					id: 'inner-center',
					region: 'center',
					deferredRender: false,
					autoScroll: true, 
					margins: '0 4 4 0',
					activeTab: 1,
					height: 500,
					stateful: true,
					stateEvents: [ 'tabchange' ],
					stateId: 'main-view',
					getState: function ( ) {
						return {
							activeTab: this.activeTab.id == 'box_view' ? 1 : 2
						};
					},
					bbar: new Ext.TabPanel( {
						id: 'switch-stock-bar',
						activeTab: 0,
						stateful: true,
						listeners: {
							'tabchange' : {
								fn: function ( panel, active ) {
									if( active.id != 'all' )
										iii.shareprice.apps.stockexplorer.fireEvent( 'stock-before-show-alone', [ active.id ] );
									else
										iii.shareprice.apps.stockexplorer.fireEvent( 'stock-before-hide-alone' );
								}
							}
						},
						items: [ {
							id: 'all',
							title: 'all'
						}]
					} ),
					tbar: new Ext.Panel({
						id: 'view-options',
						layout: 'column',
						autoWidth: true,
						layoutConfig: {
							columns: 4,
							autoWidth: true
						}
					} ),
					items:[
					{
						id: 'select',
						title: 'Select a view:',
						disabled: true,
						items: [ {
							id: 'content',
							html: '&nbsp;'
						} ]
					},
					{
						id:'box_view',
						cls: 'box_view',
				    	title: '',
				    	closable: false,
						autoScroll: true,
						forceFit: true,
				    	items: [
							new Ext.Panel({
								xtype: 'panel',
								id: 'box',
								region: 'center',
								autoScroll: false,
								autoHeight: true,
								forceFit: true,
								stateful: true,
								items: [{
									xtype: 'portal',
									id: 'box_portal',
									region: 'center',
									margins: '35 5 5 0',
									autoScroll: false,
									listeners: {
										drop: {
											fn: function ( obj ) {
												iii.shareprice.apps.stockexplorer.active.portlet( obj.panel.id, obj.column.id, obj.position );
											}
										}
									},
									viewConfig: {
										forceFit: true,
										autoScroll: false
									},
									defaults: {
										autoScroll: false
									},
									items: [
										new Ext.ux.PortalColumn( {
											id: 'portlet-system-left'
										} ),
										new Ext.ux.PortalColumn( {
											id: 'portlet-system-middle'
										} ),
										new Ext.ux.PortalColumn( {
											id: 'portlet-system-right'
										} )
									]
								}]
							})
						]
					},{
						id:'list_view',
				    	cls: 'list_view',
				    	title: '&nbsp;',
				    	closable: false,
				    	autoScroll: true,
				    	items: [
							new Ext.Panel({
								id: 'grid',
								html: '',
								items: [
									new Ext.grid.GridPanel({
										id: 'grid-panel',
										store: new Ext.data.Store({
											reader: new Ext.data.JsonReader({}, Ext.data.Record.create([
											    { name: 'name' },  
											    { name: 'mid', type: 'float' },
												{ name: 'currency' },
												{ name: 'bid', type: 'float' },
												{ name: 'ask', type: 'float' },
												{ name: 'chg_abs', type: 'float' },
												{ name: 'chg_prc', type: 'float' },
												{ name: 'update' },
												{ name: 'high', type: 'float' },
												{ name: 'low', type: 'float' }
											])),
											data: []
										}),
										columns: [
											{header: "Security Name", width: 250, sortable: true, dataIndex: 'name', id: 'name'},
											{header: "Last Price", width: 80, sortable: true, dataIndex: 'mid', id: 'mid',
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											{header: "Cur", width: 28, sortable: true, dataIndex: 'currency', id: 'currency'},
											{header: "Bid", width: 80, sortable: true, dataIndex: 'bid', id: 'bid',
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											{header: "Ask", width: 80, sortable: true, dataIndex: 'ask', id: 'ask'	,
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											{header: "Chg Abs", width: 80, sortable: true, dataIndex: 'chg_abs', id: 'changeactual'		,
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											{header: "Chg %", width: 80, sortable: true, dataIndex: 'chg_prc', id: 'changepercent'},
											{header: "Update", width: 80, sortable: true, dataIndex: 'update', id: 'updatetime'},
											{header: "High", width: 80, sortable: true, dataIndex: 'high', id: 'high',
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											{header: "Low", width: 80, sortable: true, dataIndex: 'low', id: 'low'	,
												renderer: function ( value ) {
													if( typeof value == "string" && value.length < 1 ){
														    return "&#160;";
													}
													return Number( value ).toFixed( 2 );
												}
											},
											 {header: "Volume", width: 80, sortable: true, dataIndex: 'volume', id: 'volume',
											    renderer: function ( value ) {
											      if( typeof value == "string" && value.length < 1 ){
											         return " ";
											           }
											         return value;
											           }
											    }
										],
										viewConfig: {
											forceFit: true,
											autoFill: true,
											emptyText: 'No stocks are here.'
										},
										stripeRows: true,
										autoWidth: true,
										autoHeight: true,

										sm: new Ext.grid.RowSelectionModel( { singleSelect: true } )
									})
								]
							})
						]
					},
					{
						id: 'ground',
						items: [
							{
								id: 'content'
							}
						]
					}]
				})
			]
		} ),
		south: new Ext.Panel( {
			id: 'south',
			region: 'south',
			margins: '0 0 0 0',
			style: 'visibility: hidden; height: 5px; width: 0;overflow: hidden;'
		} ),
		stock: {
			tools: [ {
				id:'refresh',
				handler: function(e, target, panel){
					iii.shareprice.apps.fixed.layout.stock.menu.show( target );
					iii.shareprice.apps.fixed.layout.stock.menu.symbol = panel.id;
				}
			} ],
			menu: new Ext.menu.Menu( {
				items: [ { 
					text: 'close',
					handler: function( button, e ) {
						button.parentMenu.hide();
						iii.shareprice.apps.stockexplorer.fireEvent( 'stock-before-close', [ iii.shareprice.apps.fixed.layout.stock.menu.symbol ] );
					}
				},
				{ 
					text: 'show alone',
					handler: function( button, e ) {
						button.parentMenu.hide();	
						iii.shareprice.apps.stockexplorer.fireEvent( 'stock-before-show-alone', [ iii.shareprice.apps.fixed.layout.stock.menu.symbol ] );
					}
				}
				]
			} ),
			alone: new Ext.Window({
				id: 'alone',
				layout: 'fit',
				width: '80%',
				height: 700,
				closeAction: 'hide',
				plain: true,
				resizable: false,
				draggable: false,
				minimizable: false,
				maximizable: false,
				listeners: {
					'hide': {
						fn: function( ) {
							iii.shareprice.apps.stockexplorer.fireEvent( 'stock-before-hide-alone' ); 
						}
					},
					'show': {
						fn: function ( ) {
							
						}
					}
				},
				items: new Ext.TabPanel({
					autoTabs: true,
					activeTab: 0,
					deferredRender: false,
					border: false,
					defaults: {
						autoScroll: true,
						minSize: 500
					},
					id: 'tabpanel',
					tbar: [
						new Ext.Panel({
							id: 'info'
						})
					],
					items: [ 
					{
						id: 'stock-alone-trade-view',
						cls: 'trades_view',
						title: 'Trades',
						layout: 'fit',
						tbar: [{
							id: 'reload-trade-data',
							xtype: 'button',
							text: 'reload',
							style: 'margin: 5px 10px;',
							handler: function () {                 
							}
						}],
						items: [ {
							id: 'trades'
						} ]
					},
					{
						id: 'stock-alone-chart-view',
						cls: 'chart_view',
						title: 'Chart',
						items: [ {
							id: 'chart'
						} ]
					},
					{
						id: 'stock-alone-news-view',
						cls: 'news_view',
						title: 'News',
						items: [ {
							id: 'news'
						} ]
					},
					{
						id: 'stock-alone-info-view',
						cls: 'info_view',
						title: 'Info',
						items: [ {
							id: 'info'
						} ]
					},
					{
						id: 'stock-alone-discussions-view',
						cls: 'discussions_view',
						title: 'Discussions',
						items: [ {
							id: 'discussions'
						} ]
					},
					{
						id: 'stock-alone-web-search-view',
						cls: 'web_search_view',
						title: 'Web',
						items: [ {
							id: 'web'
						} ]
					} ]
				})
			})			
		},
		streamingAlerter: new Ext.Window( {
			title:'Streaming Data .....',
			layout:'fit',
			width: 380,
			height: 385,
			closeAction: 'hide',
			resizable: false,
			draggable: false,
			plain: false,
			modal: true,
			returnUrl: null,
			buttons: [
				{
					handler: function ( ) {
						iii.shareprice.apps.fixed.layout.streamingAlerter.hide ( );
						iii.shareprice.apps.stockexplorer.fireEvent( 'stream-start' );
					},
					text: 'Start Streaming'
				},
				{
					handler: function ( ) {
						iii.shareprice.apps.stockexplorer.ly.els.userbar.items.get( 'startstopstreamingbtn' ).toggle( false );
						iii.shareprice.apps.fixed.layout.streamingAlerter.hide ( );
					},
					text: 'Stop Streaming'
				}
			],
			html: '<div id="streaming-ad-iframe-outer-content"></div>'
		} ),
		waiter: new Ext.Window( {
			title:'Loading Data .....',
			layout:'fit',
			width: 380,
			autoHeight: true,
			closeAction: 'hide',
			resizable: false,
			draggable: false,
			plain: false,
			modal: true,
			returnUrl: null
		} ),
		bugreportwindow: new Ext.Window( {
			title: 'Bugreport',
			layout: 'fit',
			width: 380,
			height: 250,
			closeAction: 'hide',
			resizable: false,
			draggable: false,
			plain: false,
			modal: true,
			returnUrl: null,
			items: new Ext.FormPanel({
				labelWidth: 1,
				frame: true,
				defaults: {
					labelSeperator: ''
				},
				id: 'fpBugreport',
				height: 300,
				xtype: 'form',
				onSubmit: $lambda(),
				items: [
					{
						width: 340,
						height: 100,
						xtype: 'textarea',
						id: 'text',
						name: 'reporttext',
						allowBlank: false,
						labelSeparator: '&nbsp;',
						labelStyle: 'display: none;'
					},
					new Ext.form.TextField({
						width: 340,
                        name       : 'email',
                        fieldLabel : 'Email-Address',
                        allowBlank : false,
                        vtype      : 'email',
						labelSeparator: '&nbsp;',
						labelStyle: 'display: block;'
                     })
				],
				buttons: [{
					text: 'Submit',
					type: 'submit',
					handler: function ( window ) {
						iii.shareprice.apps.fixed.layout.bugreportwindow.hide();
		            	iii.shareprice.apps.fixed.layout.bugreportwindow.findById('fpBugreport').getForm().submit({
		            		url: iii.shareprice.apps.config.get( 'serviceUrl' ) + 'service/json/client/user/login' ,
							method: 'POST',
							waitMsg:'Sending on ...',
							success: function( form, action ) {					
								pageTracker._setVar('Registered User');
								iii.shareprice.apps.fixed.layout.bugreportwindow.hide();
							},
							failure: function( form, action ) {
								if( action.result )
									var msg = action.result['msg'];
								if(!msg){
									msg = 'incorrect data';
								}											
								Ext.MessageBox.alert( 'Report', msg );
							}
						});
		        	}
				},{
					text: 'Cancel',
					handler: function ( ) {
		            	iii.shareprice.apps.fixed.layout.bugreportwindow.hide();
		        	}
				}]
			})
		} ),
		login: new Ext.Window({
			title:'Login',
			layout:'fit',
			width:430,
			height:150,
			closeAction: 'hide',
			draggable: false,
			plain: false,
			modal: true,
			returnUrl: null,
			resizable: false,
			defaultButton: 'fpLoginSubmitBtn',
			keys: {
				key: Ext.EventObject.ENTER,
				fn: function ( ) {
					iii.shareprice.apps.fixed.layout.login.buttons[ 0 ].initialConfig.handler( iii.shareprice.apps.fixed.layout.login );
					return false;
				}
			},
			items: new Ext.FormPanel({
						labelWidth: 75,
						frame:true,
						bodyStyle:'padding:5px 5px 0',
						defaults: {width: 270},
						defaultType: 'textfield',
						id: 'fpLogin',
						width: 500,
						height: 300,
						xtype: 'form',
						onSubmit: $lambda( false ),
						items: [{
								id: 'name',
								fieldLabel: 'Username',
								name: 'username',
								allowBlank:false
							}, 
							new Ext.form.TextField({
								fieldLabel: 'Password',
								name: 'password',
								inputType: 'password'
							})
						]
					}),
			buttons: [{
				id: 'fpLoginSubmitBtn',
				text: 'Login',
				type: 'submit',
				handler: function ( window ) {
					iii.shareprice.apps.fixed.layout.login.hide();
	            	iii.shareprice.apps.fixed.layout.login.findById('fpLogin').getForm().submit( {
	            		url: iii.shareprice.apps.config.get( 'serviceUrl' ) + 'service/json/client/user/login?',
						method: 'POST',
						waitMsg:'Login on ...',
						success: function( form, action ) {
							iii.shareprice.apps.stockexplorer.user.set( action.form.findField('name').getValue(), Ext.decode( action.response.responseText ) )								
							iii.shareprice.apps.fixed.layout.login.hide();
						},
						failure: function( form, action ) {
							if( action.result ) {
								var msg = action.result['msg'];
							}
							if(!msg){
								msg = 'incorrect username/password!';
							}											
							Ext.MessageBox.alert( 'Login', msg );
						}
					});
	        	}
			},{
				text: 'Cancel',
				handler: function ( ) {
	            	iii.shareprice.apps.fixed.layout.login.hide();
	        	}
			}, {
				text: 'Fogotten Password',
					handler: function(){
						iii.shareprice.apps.fixed.layout.login.hide();
						iii.shareprice.apps.fixed.layout.forgottenPassword.show();
					}
			},
			{
				text: 'Resend Confirmation',
				handler: function(){
					iii.shareprice.apps.fixed.layout.login.hide();
					iii.shareprice.apps.fixed.layout.resendConfirmation.show();
				}
			}
			]
		}),
		forgottenPassword: new Ext.Window({
			title:'Forgotten password',
			layout:'fit',
			width:380,
			height:120,
			closeAction:'hide',
			modal:true,
			resizable: false,
			draggable: false,
			plain: false,
			returnUrl :null,
			defaultButton: 'forgottenPassword_Send',
			items: new Ext.FormPanel({
				labelWidth: 75,
				frame: true,
				bodyStyle:'padding:5px 5px 0',
				defaults: {
					width: 230
				},
				defaultType: 'textfield',
				id: 'fpForgottenPassword',
				width: 500,
				height: 200,
				xtype: 'form',
				onSubmit: $lambda( false ),
				items: [ {
					fieldLabel: 'Email',
					name: 'email',
					vtype: 'email',
					allowBlank: false
				} ]
			}),
			buttons: [ {
				text: 'Send',
				type: 'submit',
				id: 'forgottenPassword_Send',
				handler: function ( btn ) {
					btn.ownerCt.findById( 'fpForgottenPassword' ).getForm( ).submit({
						url: iii.shareprice.apps.config.get( 'serviceUrl' ) + 'service/json/client/user/forgottenPassword',
						method: 'POST',
						waitMsg:'Sending ...',
						success: function( form, action ) {
							Ext.MessageBox.alert(
								'Done',
								'A password reset email is currently winging its way to you. Please follow the instructions within the email to complete your password reset.',
								function ( ) {
									iii.shareprice.apps.fixed.layout.forgottenPassword.hide();
								}
							);
						},
						failure: function (  ) {
							Ext.MessageBox.alert(
								'Message',
								'Password Reset Request Failed!',
								function ( ) {
								iii.shareprice.apps.fixed.layout.forgottenPassword.hide();
								}
							);
						}
					});
				}
			},{
				text: 'Cancel',
				handler: function(){
					iii.shareprice.apps.fixed.layout.forgottenPassword.hide();
				}
			}]
		}),
		resendConfirmation: new Ext.Window( {
			title:'Resend Confirmation Email',
			layout:'fit',
			width:380,
			height:120,
			closeAction:'hide',
			modal:true,
			plain: false,
			defaultButton: 'resendConfirmation_Send',
			items: new Ext.FormPanel({
				labelWidth: 75, // label settings here cascade unless overridden
				frame:true,
				bodyStyle:'padding:5px 5px 0',
				defaults: {width: 230},
				defaultType: 'textfield',
				id: 'fpResendConfirmation',
				width:500,
				height:200,
				xtype: 'form',
				onSubmit: Ext.emptyFn,
				items: [{
					fieldLabel: 'Email',
					name: 'email',
					allowBlank:false
				} ]
			}),
			buttons: [{
				text: 'Send',
				type: 'submit',
				id: 'resendConfirmation_Send',
				handler: function( btn ){
					btn.ownerCt.findById( 'fpResendConfirmation' ).getForm().submit({
						url: iii.shareprice.apps.config.get( 'serviceUrl' ) + '/service/json/client/user/resendConfirmation',
						method: 'POST',
						waitMsg:'Sending ...',
						success: function(form,action) {
							Ext.MessageBox.alert('Done', 'Your registration confirmation email has been resent.', function ( ) {
								iii.shareprice.apps.fixed.layout.resendConfirmation.hide();
							});
						},
						failure: function(form,action) {
							var msg = action.result['message'];
							if( !msg ) {
								msg = 'Resend Confirmation Request Failed!';
							}											
							Ext.MessageBox.alert('Message', msg );
						}
					});
				}
			},{
				text: 'Cancel',
				handler: function(){
					iii.shareprice.apps.fixed.layout.resendConfirmation.hide();
				}
			} ]
		} ),
		passwordReset: new Ext.Window({
			title:'Password reset',
			layout:'fit',
			width:450,
			height:200,
			closeAction:'hide',
			plain: false,
			modal:true,
			items: new Ext.FormPanel({
				labelWidth: 140, // label settings here cascade unless overridden
				frame:true,
				bodyStyle:'padding:5px 5px 0',
				defaults: {
					width: 230,
					inputType: 'password'
				},
				id: 'fpLogin',
				xtype: 'form',
				items: [
					{
                                            Label: 'New password must be at least 8 characters with at least one lower case letter, one uppercase letter and a number.',
                                            name: 'first',
                                            allowBlank:false
                                        },
					new Ext.ux.PasswordField({
						fieldLabel: 'New Password',
							name: 'password',
							id: 'password',
							showCapsWarning: false,
							showStrengthMeter: true,
							vtype: 'passwordStrength',
							vtypeText: 'Must be a least 8 characters with at least one lower case letter, one uppercase letter and a number'
					} ),
					new Ext.form.TextField({
						fieldLabel: 'Re-type New Password',
						name: 'passwordConfirm',
						inputType: 'password',
						initialPassField: 'password',
						vtype: 'passwordCompare',
						vtypeText: 'Passwords do not match'
					} )
				]
			} ),
			buttons: [{
				text: 'Send',
				type: 'submit',
				handler: function ( btn ) {
					btn.ownerCt.findById( 'fpResendConfirmation' ).getForm().submit({
						url: iii.shareprice.apps.config.get( 'serviceUrl' ) + '/service/json/client/user/passwordReset?resetCode='+ iii.shareprice.apps.fixed.layout.passwordReset.resetCode,
						method: 'POST',
						waitMsg:'Submitting ...',
						success: function( form, action ) {
							Ext.MessageBox.alert('Done', 'Your password has been reset',function(){
								iii.shareprice.apps.fixed.layout.passwordReset.hide();
							});
						},
						failure: function() {
							Ext.MessageBox.alert('Message', 'Password Reset Failed!');
						}
					});
				}
			},{
				text: 'Cancel',
				handler: function(){
					iii.shareprice.apps.fixed.layout.passwordReset.hide();
				}
			}]
		} ),
		register: function ( ) {
			var wiz = new Ext.ux.Wiz ( {
	        	title : 'shareprice.co.uk',
				height: 500,
				enableMask: true,
				resizable: false,
				stateful: false,
				listeners: {
					'show': {
						fn: function ( ) {
							iii.shareprice.apps.stockexplorer.fireEvent( 'registration-begin' , arguments );
						}
					},
					'close': {
						fn: function ( ) {
							iii.shareprice.apps.stockexplorer.fireEvent( 'registration-close', arguments );
						}
					},
					'finish': {
						fn: function( wizard, data ) {
							iii.shareprice.apps.stockexplorer.fireEvent( 'registration-finish', data, wizard ); 
						}
					}
				},
	        	headerConfig : {
	            	title : 'User Registration'    
	        	},
	        	cardPanelConfig : {
	            	defaults : {
	                	baseCls    : 'x-small-editor',
						margins: '40 0 40 0',
	                	bodyStyle  : 'padding:40px 15px 40px 20px;background-color: #F6F6F6;',
	                	border     : false,
						autoScroll: true
	            	}
	        	},   
	        	cards : [
					new Ext.ux.Wiz.Card({
						id: 'welcome',
                		title : 'Welcome',
                		items : [{
                    		border    : false,
                    		bodyStyle : 'background:none;',
                    		html      : 'Under the terms of any website offering live London Stock ' +
							  'Exchange data, <br/>your access to live / streaming market data ' +
							  'requires you to register some details with us;<br/> validate your ' +
							  'email; and then log-in each time you use the site..<br/><br/>' +
							  'The following steps will take just a moment to complete.'   
                		}]  
            		}),
					new Ext.ux.Wiz.Card({
						id: 'user',
                		title        : 'Enter a Username and Password',
                		monitorValid : true,
                		defaults     : {
                    		labelStyle : 'font-size:11px',
							style: 'width:300px'
                		},
                		items : [
							{
	                        	border    : false,
	                        	bodyStyle : 'background:none;padding-bottom:30px;',
	                        	html      : 'Please choose a user name and password -<br/>they are case ' +
								  'sensitive.<br/><br/>' +
								  'Your user name may be used as an identifier in future services ' +
								  'such as bulletin boards - so you may wish to use an anonymous ' +
								  'nickname rather than, say, your surname.<br/><br/>'								
	                    	},
                    		new Ext.form.TextField({
                        		name       : 'username',
                        		fieldLabel : 'Username',
                        		allowBlank : false,
                        		validator  : function(v){
                            		var t = /^[a-zA-Z_.\- ]+$/;
                            		return t.test(v);
                        		}
                    		}),
							new Ext.ux.PasswordField({
								id: 'password',
								name       : 'password',
                        		fieldLabel : 'Password',
								showCapsWarning: true,
								fieldClass: null,
								showStrengthMeter: true,
								pwStrengthMeterCls: 'x-form-password-strengthMeter',
								pwStrengthMeterFocusCls: 'x-form-password-strengthMeter-focus',
								pwStrengthScoreBarCls:'x-form-password-scoreBar'
							}),
							new Ext.form.TextField( {
								allowBlank : false,
								name: 'password_repeat',
								fieldLabel: 'Re-type your password',
								vtype: 'password',
								inputType: 'password',
								initialPassField: 'password',
								invalidText: 'passwords do notch match.'
							} )
						]    
            		}),
					
	            	new Ext.ux.Wiz.Card({
						id: 'personal',
	                	title        : 'About you',
	                	monitorValid : true,
	                	defaults     : {
	                    	labelStyle : 'font-size:11px',
							style: 'width:300px'
	                	},
	                	items : [
							
							new Ext.form.ComboBox( {
								name: 'title',
								fieldLabel: 'Title',
								allowBlank: false,
								emptyText: 'Select a title',
								store: [ 'Dr', 'Lady', 'Lord', 'Miss', 'Mr', 'Mrs', 'Ms', 'Prof', 'Revd' ]
							} ),
	                    	new Ext.form.TextField({
	                        	name       : 'firstname',
	                        	fieldLabel : 'Firstname',
	                        	allowBlank : false,
	                        	validator  : function( v ){
	                            	var t = /^[a-zA-Z_\- ]+$/;
	                            	return t.test(v);
	                        	}
	                    	}),
	                    	new Ext.form.TextField({
	                        	name       : 'surname',
	                        	fieldLabel : 'Surname',
	                        	allowBlank : false,
	                        	validator  : function(v){
	                            	var t = /^[a-zA-Z_\- ]+$/;
	                            	return t.test(v);
	                        	}
	                    	}),
							new Ext.form.DateField( {
								name       : 'birthday',
	                        	fieldLabel : 'DOB (dd/mm/yyyy)',
								format: 'd/m/Y',
								allowBlank : false
							} ),
							new Ext.form.RadioGroup( {
								fieldLabel: 'Gender',
								width: 300,
								vertical: false,
								blankText: 'Error',
								autoHeight: true,
								defaultType: 'radio',
								defaults: {
									scroll: false
								},
								items: [
									{
										checked: true,
										name: 'gender',
										inputValue: 0,
										boxLabel: 'Male',
										autoShow: true
									},
									{
										name: 'gender',
										inputValue: 1,
										boxLabel: 'Female',
										autoShow: true
									}
								]
							} )
	                	]    
	            	}),
					new Ext.ux.Wiz.Card({
							id: 'email',
			                title : 'Your email address',
			                monitorValid : true,
			                defaults : {
			                   	labelStyle : 'font-size:11px',
								style: 'width:300px'
			                },
			                items : [
								{
	                        		border    : false,
	                        		bodyStyle : 'background:none;padding-bottom:30px;',
	                        		html      : '' +
									  'You are required to validate your email address by responding to' +
									  'an automated message sent to the address you specify below. This' +
									  'address should remain valid throughout your use of our service ,' +
									  'or can be changed at a later date via your profile.' +
									  'An unreachable email address may invalidate your access to' +
									  'shareprice.co.uk<br/><br/>' +
									  '(please add a further email field and validation - ie. the two' +
									  'fields must match, to ensure the user doesn\'t mistype their' +
									  'email address<br/>'
	                    		},
			                    new Ext.form.TextField({
									id: 'email-address',
			                        name       : 'email',
			                        fieldLabel : 'Email-Address',
			                        allowBlank : false,
			                        vtype      : 'email'
			                     }),
								new Ext.form.TextField( {
									name: 'email_repeat',
									allowBlank : false,
									fieldLabel: 'Re-type your email-address',
									vtype: 'email',
									inputType: 'text',
									initialPassField: 'email-address',
									invalidText: 'emails do notch match.'
								} )
							]
						}),
					new Ext.ux.Wiz.Card({
						id: 'contact',
	                	title : 'Contact details',
	                	monitorValid : true,
	                	defaults : {
	                    	labelStyle : 'font-size: 11px;',
							style: 'width: 300px;'
	                	},
	                	items : [
							
							new Ext.form.TextField({
		                       	name       : 'address_line1',
		                       	fieldLabel : 'Address line 1',
		                       	allowBlank : false,
		                       	validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
		                       	name       : 'address_line2',
		                       	fieldLabel : 'Address line 2',
		                       	validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.+\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
		                       	name       : 'address_line3',
		                       	fieldLabel : 'Address line 3',
		                       	validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.+\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
		                       	name       : 'address_line4',
		                       	fieldLabel : 'Address line 4',
		                       	validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.+\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
		                       	name       : 'town',
		                       	fieldLabel : 'Town',
		                       	allowBlank: false,
								validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.+\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
		                       	name       : 'county',
		                       	fieldLabel : 'County',
								allowBlank: false,
		                       	validator  : function(v){
		                           	var t = /^[a-zA-Z0-9_.+\- ]+$/;
		                           	return t.test(v);
		                       	}
		                    }),
							new Ext.form.TextField({
	                        	name       : 'postcode',
	                        	fieldLabel : 'Postcode',
	                        	allowBlank : false,
	                        	validator  : function(v){
	                            	var t = /^[a-zA-Z0-9_.+\- ]+$/;
	                            	return t.test(v);
	                        	}
	                    	}),
							new Ext.form.ComboBox( {
								name: 'country',
								fieldLabel: 'Country',
								allowBlank: false,
								store: [ 'United Kingdom' ]
							} ),
							new Ext.form.TextField({
		                       name       : 'phone',
		                       fieldLabel : 'Telephone',
		                       allowBlank : false,
		                       validator  : function(v){
		                            var t = /^[0-9_\-+.\\\/ ]+$/;
		                           return t.test(v);
		                       }
		                   })
	                	]
	            	}),
					new Ext.ux.Wiz.Card( {
						id: 'conditions',
						title: 'Site conditions and privacy',
						monitorValid : true,
	                	defaults : {
	                    	labelStyle: 'display:none;'
	                	},
						items: [
							{
	                        	border    : false,
	                        	bodyStyle : 'padding-bottom: 40px;padding-top: 10px;height: 160px;',
								cls: 'cf',
								autoScroll: true,
	                        	html: '<b>Site terms and conditions</b><br/>Donec lorem pede, tempus et, placerat non, ultrices at, tellus. Duis dignissim urna vitae justo. Phasellus nibh. Cras pellentesque elementum felis? Suspendisse eleifend condimentum ligula. In justo! Aliquam lobortis massa at nisl. Proin tempus dictum urna. Donec commodo dictum lorem. Suspendisse hendrerit. Nulla eget dui vel odio lobortis consectetuer. Ut vehicula vulputate urna. Vestibulum egestas urna ac orci. Curabitur nec odio. Mauris varius turpis quis dui. Phasellus adipiscing massa id purus. Pellentesque blandit, velit sed sagittis iaculis, massa sem facilisis velit, at pulvinar elit velit eget quam! Integer ipsum magna, faucibus sit amet; consequat vitae, volutpat sit amet, justo. Proin ut dui sed pede tristique eleifend. Aliquam iaculis. Praesent imperdiet egestas massa. Praesent at nibh ac turpis blandit rutrum. Praesent mattis molestie sem! Ut faucibus. Maecenas convallis elit et velit. Vivamus ligula mauris, dapibus et, malesuada vehicula, interdum dapibus, est. Sed bibendum, dui vel consequat elementum, arcu ligula tincidunt pede, ut suscipit urna purus et felis. Nam porta viverra nulla. Integer lobortis. Donec massa diam, ornare a, laoreet nec, vulputate sit amet, ligula. Sed eget urna. Sed enim purus, sollicitudin sed, semper luctus, egestas et; ipsum. Morbi ut odio. Nulla feugiat consequat quam. Suspendisse potenti. Aliquam ultricies euismod nunc. Pellentesque commodo, nisi sed auctor luctus, diam lacus placerat velit, quis porta lectus felis ut pede. Mauris imperdiet porttitor risus? Sed magna. Maecenas eu neque. Nullam porttitor est et neque. Quisque lobortis, sem quis faucibus laoreet, nisi orci convallis tortor, a volutpat velit eros sit amet nulla. Nam gravida mollis nunc. Suspendisse potenti. Nulla ornare tellus ac sem? Aliquam et felis eget orci varius suscipit. Donec tortor nisl, pharetra non, porta nec, lobortis in, quam. Quisque vel risus vitae lorem luctus cursus. Pellentesque at nisl in mi mattis fermentum. Sed eu eros quis nibh venenatis viverra. Praesent sed magna ut mauris congue bibendum? Integer a turpis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus porta quam quis tortor. Cras gravida. Phasellus porttitor lacinia nulla. Phasellus adipiscing condimentum elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum justo nunc, dapibus lobortis, sodales nec, gravida vitae, quam. Suspendisse in est? Donec cursus? Phasellus pede! Morbi turpis. Fusce ac justo. Nulla vel ante a sapien auctor venenatis. Nulla volutpat tincidunt felis. Suspendisse potenti. Donec facilisis erat sit amet lorem. Vestibulum libero tellus, vulputate vel, egestas vitae, elementum id; magna. Nulla convallis. Nunc interdum dapibus turpis? Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean aliquam metus ac nisi. Nunc egestas, mauris sed consequat sodales, dolor est cursus enim, eu adipiscing nulla mi vitae tortor. Fusce vestibulum, enim ut sodales porttitor, est urna porta eros, vitae auctor ante justo at purus! Donec quis eros vitae nibh dictum pretium. Maecenas fermentum. Fusce porta quam eget mi consectetuer mattis. Nullam eget lacus ac nunc congue commodo. Fusce eu diam eget sapien hendrerit convallis. Sed sodales nulla a eros. Vivamus congue nisi vitae diam. Mauris euismod enim vel est! Etiam lacus felis, ultricies eu, sodales non, tempus quis; massa. Proin auctor lacus in tellus. Mauris tellus enim, posuere non, malesuada quis, ullamcorper rutrum, dui. Quisque arcu velit; eleifend at, auctor eu, lobortis accumsan, massa. Praesent nec nunc. Suspendisse at est sed risus dapibus aliquet. Donec vulputate. Nam luctus massa sit amet velit. Vivamus faucibus pellentesque est. Sed cursus aliquet leo! Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce nibh leo, condimentum non, ultrices a, pellentesque non, sapien? Mauris faucibus, erat facilisis vehicula interdum, enim elit rutrum nunc, vitae bibendum arcu mauris sed felis. Integer elit mi; aliquet in, accumsan vel'
	                    	},
							new Ext.form.Checkbox( {
								allowBlank : false,
								
								name: 'general_site_conditions',
								boxLabel: "I have read and agree to shareprice.co.uk Terms & Conditions",
								fieldLabel: '',
								validationEvent: 'change',
								labelSeparator: '&nbsp;',
								style: 'margin-left: -100px;',
								invalidText: 'Error',
								autoShow: true,
								autoScroll: false
							} ),
							new Ext.form.Checkbox( {
								autoShow: true,
								name: 'email_conditions',
								style: 'margin-left: -100px;',
								boxLabel: "I agree to receiving no more than one email newsletter a week",
								fieldLabel: '',
								labelSeparator: '&nbsp;',
								invalidText: 'Error',
								checked: true,
								autoScroll: false
							} )
						]
					} ),
	            	new Ext.ux.Wiz.Card({
						listeners: {
							show: {
								fn: function ( ) {
									wiz.nextButton.disable();
									var data =  wiz.getWizardData();
									var date = data.personal.birthday.split( '/' );
									switch( data.personal.title ) {
										case 'Dr': 
											data.personal.title = 1;
										break;
										case 'Lady':
											data.personal.title = 2;
										break;
										case 'Lord':
											data.personal.title = 3;
										break;
										case 'Miss':
											data.personal.title = 4;
										break;
										case 'Mr': 
											data.personal.title = 5;
										break;
										case 'Mrs':
											data.personal.title = 6;
										break;
										case 'Ms':
											data.personal.title = 7;
										break;
										case 'Prof':
											data.personal.title = 8;
										break;
										case 'Revd':
											data.personal.title = 9;
										break;
									};

									var postData = {
										'USERNAME': data.user.username,
										'USERPASSWORD': data.user.password,
										'USERPASSWORD2': data.user.password_repeat,
										'TITLEID': data.personal.title,
										'FIRSTNAME': data.personal.firstname,
										'LASTNAME': data.personal.surname,
										'GENDER': data.personal.gender,
										'ADDRESS_LINE_1': data.contact.address_line1,
										'ADDRESS_LINE_2': data.contact.address_line2,
										'ADDRESS_LINE_3': data.contact.address_line3,
										'ADDRESS_LINE_4': data.contact.address_line4,
										'ADDRESS_TOWN': data.contact.town,
										'ADDRESS_COUNTY': data.contact.county,
										'ADDRESS_POSTCODE': data.contact.postcode,
										'ADDRESS_COUNTRY_CODE': 'UK',
										'PHONE_NO': data.contact.phone,
										'EMAIL': data.email.email,
										'DOB_DAY': date[0],
										'DOB_MONTH': date[1],
										'DOB_YEAR': date[2],
										'TC_AGREE': 1
									};
									var self = this;
									self.findById( 'wiz-finished' ).el.dom.set( 'html', 'Register...' );
									iii.shareprice.apps.stockexplorer.request.send( {
										method: 'POST',
										url: iii.shareprice.apps.config.get( 'serviceUrl' ) + "service/json/client/user/registration",
										params: postData,
										success: function ( data ) {
											data = data || {
												success: false,
												message: 'There was an error in your registration. try again.'
											};
											if( data.success ) {
												data.message = 'Registration is submited. Check your Email.';
												wiz.nextButton.enable();
											} else {
												wiz.nextButton.disable();
											}
											self.findById( 'wiz-finished' ).el.dom.set( 'html', data.message );
										}
									} );
								}
							}
						},
	                	title: 'Finished!',
						enableMask: true,
	                	items : [{
							id: 'wiz-finished',
	                    	border    : false,
	                    	bodyStyle : 'background:none;',
	                    	html      : 'Thank you for registration. Your data has been collected... '
	                	}]
	            	})
	        	]
			});
			wiz.show();
			return wiz;
		}
	},
	tpl: {
		loading: "loading...",
		portlet: {
			title: new Ext.XTemplate(
			    '<tpl for="descriptor">{displayname}</tpl>'
			),
			content: new Ext.XTemplate("<div class=\"symbol symbol-{code}_GB\"><div style=\"height:70px;overflow: hidden;\">" +
						"<ul class=\"w_33 cf\">" +
							"<li class=\"calc-change-procent f_r\"><span class=\"{cls} big symbol-calc-changepercent\">{performancepct}%</span>Currency {currency}</li>" +
							"<li class=\"calc-change-number f_r\"><span class=\"{cls} big symbol-calc-changeactual\">{performance}</span>Volume <span class=\"symbol-val-totalvolume i\">{totalvolume_f}</span></li>" +
							"<li class=\"lastprice\"><span class=\"big logo-{cls} symbol-val-lastprice\">{price} </span><span class=\"small grey\"><span class=\"symbol-val-mid\">{mid} <i>(mid)</i></span>as of <span class=\"symbol-val-lastpricetime i\">{pricedtm_time}</span></span></li>" +
						"</ul>" +
					"</div>" + 
					"<div style=\"height:30px;\">" + 
						"<ul class=\"w_25 cf\">" +
							"<li><span class=\"strong\">Bid - Offer</span><span class=\"symbol-val-bid i\">{bid} - {ask}</span></li>" +
							"<li><span class=\"strong\">Prev close</span><span class=\"symbol-val-prevclosingprice i\">{close}</span></li>" +
							"<li><span class=\"strong\">Open</span><span class=\"i\">{open}</li>" +
							"<li><span class=\"strong\">Day range</span><span class=\"symbol-val-low i\">{low}</span> - <span class=\"symbol-val-high i\">{high}</span></li>" +
						"</ul>" +
					"</div></div>")
		},
		list: {
			title: new Ext.XTemplate(
			    '<tpl for="descriptor">{displayname}</tpl>'
			)
		},
		btn: {
			title: "{exchangecode}"
		},
		alone: {
			title: new Ext.XTemplate(
			    '<tpl for="descriptor">{displayname}</tpl>'
			),
			chart: "{chart}",
			info: new Ext.XTemplate( '<tpl for="descriptor">' +
				'<h2>{nameofficial}</h2>' +
				'<table width="100%"><tbody>'+
					'<tr>' +
						'<td>Company</td><td>{bestcompanyname}</td>' +
					'</tr>'+
				'</tbody></table>' +
			 '</tpl>' )
		},
		help: {
			title: "Help",
			content: new Ext.TabPanel( {
				activeTab: 0,
				autoHeight: true,
				autoWidth: true,
				plain:true,
				defaults: {
					autoScroll: true,
					autoHeight: true,
					autoWidth: true
				},
				items:[ {
					title: 'Video Tutorial',
					autoLoad: {
						url: 'sites/help-video.html'
					}
				},	{
						title: 'FAQ',
						autoLoad: {
							url: 'sites/help-faq.html'/*,
							params: 'foo=bar&wtf=1'*/
						}
					} ]
			} )
		}
	}
};








iii.shareprice.apps.fixed.layout.stock.trade = { };
iii.shareprice.apps.fixed.layout.stock.trade.store = new Ext.data.Store({
	reader: new Ext.data.JsonReader({}, Ext.data.Record.create([
		{ name: 'addendum' },
		{ name: 'volume', type: 'float' },
		{ name: 'price', type: 'float' },
		{ name: 'pricedatetime', mapping: 'fprice_datetime' }
	])),
	data: []
});
iii.shareprice.apps.fixed.layout.stock.trade.load = function ( id ) {
	iii.shareprice.apps.fixed.layout.stock.trade.grid.loadMask.enable();
	iii.shareprice.apps.fixed.layout.stock.trade.grid.loadMask.show();
	iii.shareprice.apps.stockexplorer.request.send( {
		url: iii.shareprice.apps.config.get( 'serviceUrl' ) + 'service/json/securities/trades/code/' + id.toUpperCase() + "?format=1",
		success: function ( data ) {
			data = data || {};
			iii.shareprice.apps.stockexplorer.stocks.get( id.toUpperCase() ).up( {
				trades: data[ id.toUpperCase() ].trades
			} );
			iii.shareprice.apps.fixed.layout.stock.trade.store.loadData( data[ id.toUpperCase()  ].trades );
			iii.shareprice.apps.fixed.layout.stock.trade.grid.loadMask.hide();
			iii.shareprice.apps.fixed.layout.stock.trade.grid.loadMask.disable();
		}
	} );
};
iii.shareprice.apps.fixed.layout.stock.trade.grid = new Ext.grid.GridPanel( {
	id: 'grid-panel',
	store: iii.shareprice.apps.fixed.layout.stock.trade.store,
	loadMask: true,
	frame: false,
	columns: [
		{header: "Trade Price", width: 40, sortable: true, dataIndex: 'price',
			renderer: function ( value ) {
				if( typeof value == "string" && value.length < 1 ){
					return "&#160;";
				}
				return Number( value ).toFixed( 2 );
			}
		},
		{
			header: "Time",
			width: 80,
			sortable: true,
			dataIndex: 'pricedatetime',
			renderer: function ( value ) {
				if( typeof value == "string" && value.length < 1 ){
					return "&#160;";
				}
				var date = ( new Date ( value ) );
				return date.format( 'H:i:s' );
			}
		},
		{header: "Number Traded", width: 70, sortable: true, dataIndex: 'volume' },
		{header: "Trade Type", sortable: true, dataIndex: 'addendum' }
	],
	viewConfig: {
		forceFit: true,
		autoFill: true,
		emptyText: 'No trade data available.'
	},
	autoHeight: false,
	sm: new Ext.grid.RowSelectionModel( { singleSelect: true } )
});

iii.shareprice.apps.fixed.layout.stock.discussion = { };
iii.shareprice.apps.fixed.layout.stock.discussion.store= new Ext.data.JsonStore( {
	baseParams: {
		'url': iii.shareprice.apps.config.get( 'iiiDiscussionUrl' )
//		,'sort': 'post'
//		,'dir': 'DESC'
	},
	root: 'messages',
	totalProperty: 'totalcount',
	remoteSort: true,
	fields: [
		'subject', 'author', 'date_time', 'message'
	],
	url: iii.shareprice.apps.config.get( 'proxy' )
} );


iii.shareprice.apps.fixed.layout.stock.discussion.chatstore = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({ url: iii.shareprice.apps.config.get( 'bossQueryUrl' ) }),
	totalProperty: 'totalcount',
	reader: new Ext.data.JsonReader( {
	id: 'uuid'
	}, ['title', 'description', 'link', 'uuid', {
		name: 'date',
		mapping: 'pubdate',
		type: 'date'
	}, 'feed']
	)
} );
/*
iii.shareprice.apps.fixed.layout.stock.discussion.advfnstore = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({ url: iii.shareprice.apps.config.get( 'bossQueryUrl' ) }),
	totalProperty: 'totalcount',
	reader: new Ext.data.JsonReader( {
	}, ['title', 'description', 'permalink', 'uuid', {
		name: 'date',
		mapping: 'pubdate',
		type: 'date'
	}, 'feed']
	)
} );
*/
iii.shareprice.apps.fixed.layout.stock.discussion.load = function ( symbol ) {
	var s = symbol.toUpperCase();
	if( s.length == 2 ) {
		s += "-";
	}
	iii.shareprice.apps.fixed.layout.stock.discussion.store.baseParams = {
		'url': iii.shareprice.apps.config.get( 'iiiDiscussionUrl' ),
		'code' : 'cotn:' + s.replace('.','-')  + '.L',
		'sort': 'post',
		'dir': 'DESC'
	};
	iii.shareprice.apps.fixed.layout.stock.discussion.store.url = iii.shareprice.apps.config.get( 'proxy' );
	iii.shareprice.apps.fixed.layout.stock.discussion.store.proxy.conn.url = 	iii.shareprice.apps.fixed.layout.stock.discussion.store.url;
	iii.shareprice.apps.fixed.layout.stock.discussion.store.load( {
		params: {
			start: 0,
			end: 25
		}
	} );
	iii.shareprice.apps.stockexplorer.request.send( {
		url: iii.shareprice.apps.config.get( 'feedServiceUrl' ) + encodeURIComponent ( iii.shareprice.apps.config.get( 'lseChatUrl' ) + symbol.toUpperCase() ) ,
		success: function ( returns ) {
			data = returns.topics || [];
			iii.shareprice.apps.fixed.layout.stock.discussion.chatstore.loadData( data );
		}
	} );
	/*
	iii.shareprice.apps.stockexplorer.request.send( {
		url: iii.shareprice.apps.config.get( 'feedServiceUrl' ) + encodeURIComponent ( iii.shareprice.apps.config.get( 'advfnTickerUrl' ) + symbol.toUpperCase() ) ,
		success: function ( returns ) {
			data = returns.topics || [];
			iii.shareprice.apps.fixed.layout.stock.discussion.advfnstore.loadData( data );
			iii.shareprice.apps.fixed.layout.stock.discussion.advfnstore.sort('date', 'DESC')
		}
	} );
	*/
};

iii.shareprice.apps.fixed.layout.stock.discussion.grid = new Ext.Panel({
	autoWidth: true,
	autoHeight: false,
	title: 'Bulletin board postings on this company from around the web',
	autoScroll: true,
	border: false,
	frame: false,
	tbar: [
			{
				id: 'alone-view-discussion-btn',
				xtype: 'button',
				text: '&nbsp;<img src="./img/icons/iii.gif" style="margin-top: 0.2em;" />&nbsp;',
				disabled: true,
				handler: function ( btn ) {
					btn.disable();
					Ext.getCmp( 'alone-view-chat-btn' ).enable();
					//Ext.getCmp( 'alone-view-advfn-btn' ).enable();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'iiidiscussions' ).show();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.getBottomToolbar().show();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'stockchat' ).hide();
					//iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'advfndiscussions' ).hide();
				}
			}/*,
			{
				id: 'alone-view-advfn-btn',
				xtype: 'button',
				text: '&nbsp;<img src="./img/icons/advfn.png" style="margin-top: 0.2em;" />&nbsp;',
				handler: function ( btn ) {
					Ext.getCmp( 'alone-view-discussion-btn' ).enable();
					Ext.getCmp( 'alone-view-chat-btn' ).enable();
					btn.disable();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'iiidiscussions' ).hide();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.getBottomToolbar().hide();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'stockchat' ).hide();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'advfndiscussions' ).show();
				}
			}*/,
			{
				id: 'alone-view-chat-btn',
				xtype: 'button',
				text: '&nbsp;<img src="./img/icons/lse.gif" height=16 width=16 style="margin-top: 0.2em;" />&nbsp;',
				handler: function ( btn ) {
					Ext.getCmp( 'alone-view-discussion-btn' ).enable();
					//Ext.getCmp( 'alone-view-advfn-btn' ).enable();
					btn.disable();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'iiidiscussions' ).hide();
					//iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'advfndiscussions' ).hide();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.getBottomToolbar().hide();
					iii.shareprice.apps.fixed.layout.stock.discussion.grid.items.get( 'stockchat' ).show();
				}
			}
	],
	items: [
		new Ext.DataView( {
			id: 'iiidiscussions',
			store: iii.shareprice.apps.fixed.layout.stock.discussion.store,
			itemSelector: '.entry',
			tpl: new Ext.XTemplate(
			'<tpl for=".">' +
				'<div class="entry">' +
					'<div class="entry-title">{subject}</div>' +
					'<div class="excerpt">' +
						'<p>{message}</p>' +
					'</div>' +
					'<h4>Datetime: {date_time}<br/>User: {author}</h4>' +
				'</div>' +
			'</tpl>' )
		} ),
		new Ext.DataView({
			store: iii.shareprice.apps.fixed.layout.stock.discussion.chatstore,
			hidden: true,
			id: 'stockchat',
			itemSelector: '.entry',
			deferEmptyText: true,
			emptyText: 'No Chats for this stock are here.',
			tpl: new Ext.XTemplate(
			'<tpl for=".">' +
				'<div class="entry">' +
					'<a rel="bookmark" href="{link}" class="entry-title" target="_blank">{title}</a>' +
					'<div class="excerpt">' +
						'<p>{description}</p>' +
					'</div>' +
					'<h4><a href="{link}" class="view-post" target="_blank">Visit Message &raquo;</a><br/>From: {date:date("F j, Y  H:i")}</h4>' +
				'</div>' +
			'</tpl>' )
		})/*,
		new Ext.DataView({
			store: iii.shareprice.apps.fixed.layout.stock.discussion.advfnstore,
			hidden: true,
			id: 'advfndiscussions',
			itemSelector: '.entry',
			deferEmptyText: true,
			emptyText: 'No Chats for this stock are here.',
			tpl: new Ext.XTemplate(
				'<tpl for=".">' +
					'<div class="entry">' +
						'<a rel="bookmark" href="{permalink}" class="entry-title" target="_blank">{title}</a>' +
						'<div class="excerpt">' +
							'<p>{description}</p>' +
						'</div>' +
						'<h4><a href="{permalink}" class="view-post" target="_blank">Visit Message &raquo;</a><br/>From: {date:date("F j, Y  H:i")}</h4>' +
					'</div>' +
				'</tpl>' )
			})*/
	],
	viewConfig: {
		forceFit: true,
		autoFill: true
	},
	bbar: new Ext.PagingToolbar({
		pageSize: 25,
		store: iii.shareprice.apps.fixed.layout.stock.discussion.store,
		displayInfo: true,
		displayMsg: 'Displaying topics {0} - {1} of {2}',
		emptyMsg: "No topics to display"
	})
});
iii.shareprice.apps.fixed.layout.stock.discussion.store.on( 'beforeload', function ( ) {
	if( iii.shareprice.apps.fixed.layout.stock.discussion.loadMask )
		iii.shareprice.apps.fixed.layout.stock.discussion.loadMask.destroy();
	iii.shareprice.apps.fixed.layout.stock.discussion.loadMask = new Ext.LoadMask (
		$( iii.shareprice.apps.fixed.layout.stock.discussion.grid.id ),
		{
			msg: "Please wait..."
		}
	);
	iii.shareprice.apps.fixed.layout.stock.discussion.loadMask.show();
} );

iii.shareprice.apps.fixed.layout.stock.discussion.store.on( 'load', function ( ) {
	iii.shareprice.apps.fixed.layout.stock.discussion.loadMask.hide();
} );



iii.shareprice.apps.fixed.layout.stock.web = { };
iii.shareprice.apps.fixed.layout.stock.web.store = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({ url: iii.shareprice.apps.config.get( 'bossQueryUrl' ) }),
	reader: new Ext.data.JsonReader({
		root: 'results',
		totalProperty: 'total',
		id: 'id'
	}, ['title', 'abstract', 'url', 'clickurl', 'size', 'date', 'dispurl' ]
	)
});

iii.shareprice.apps.fixed.layout.stock.web.grid = new Ext.Panel({
	autoWidth: true,
	autoHeight: false,
	frame: false,
	title: 'YAHOO SEARCH',
	autoScroll: true,
	border: false,
	items: new Ext.DataView({
		store: iii.shareprice.apps.fixed.layout.stock.web.store,
		itemSelector: '.entry',
		tpl: new Ext.XTemplate(
		'<tpl for=".">' +
			'<div class="entry">' +
				'<a rel="bookmark" href="{clickurl}" class="entry-title" target="_blank">{title}</a>' +
				'<div class="excerpt">' +
					'<p>{abstract}</p>' +
					'{dispurl}' +
				'</div>' +
				'<h4><a href="{clickurl}" class="view-post" target="_blank">Visit Web Site &raquo;</a><br/>Last Updated: {date:date("F j, Y")}</h4>' +
			'</div>' +
		'</tpl>' )
	}),
	viewConfig: {
		forceFit: true,
		autoFill: true,
		emptyText: 'No search results for this stock are here.'
	},
	bbar: new Ext.PagingToolbar({
		pageSize: 30,
		store: iii.shareprice.apps.fixed.layout.stock.web.store,
		displayInfo: true,
		displayMsg: '{0} - {1} of {2}',
		emptyMsg: "No Results"	
	})
});
iii.shareprice.apps.fixed.layout.stock.web.load = function ( id ) {
	iii.shareprice.apps.fixed.layout.stock.web.store.baseParams = {
		'format': 'json',
		q: encodeURIComponent( id ),
		stype: 'web'
	};
	iii.shareprice.apps.fixed.layout.stock.web.store.load( { params: {
		start: 0,
		limit: 30
	} } );
};

iii.shareprice.apps.fixed.layout.stock.web.store.on( 'beforeload', function ( ) {
	if( iii.shareprice.apps.fixed.layout.stock.web.loadMask )
		iii.shareprice.apps.fixed.layout.stock.web.loadMask.destroy();
	iii.shareprice.apps.fixed.layout.stock.web.loadMask = new Ext.LoadMask (
		$( iii.shareprice.apps.fixed.layout.stock.web.grid.id ),
		{
			msg: "Please wait..."
		}
	);
	iii.shareprice.apps.fixed.layout.stock.web.loadMask.show();
} );

iii.shareprice.apps.fixed.layout.stock.web.store.on( 'load', function ( ) {
	iii.shareprice.apps.fixed.layout.stock.web.loadMask.hide();
} );


iii.shareprice.apps.fixed.layout.stock.news	 = { };
iii.shareprice.apps.fixed.layout.stock.news.store = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({ url: iii.shareprice.apps.config.get( 'bossQueryUrl' ) }),
	reader: new Ext.data.JsonReader( {
	}, ['title', 'description', 'link', 'uuid',	{
			name: 'date',
			mapping: 'pubdate',
			type: 'date'
		}, 'feed']
	)
} );

iii.shareprice.apps.fixed.layout.stock.news.grid = new Ext.Panel( {
	autoWidth: true,
	autoHeight: false,
	frame: false,
	title: 'News',
	autoScroll: true,
	border: false,
	items: 
		new Ext.DataView({
			store: iii.shareprice.apps.fixed.layout.stock.news.store,
			id: 'iiinews',
			itemSelector: '.entry',
			deferEmptyText: true,
			emptyText: 'No News for this stock are here.',
			tpl: new Ext.XTemplate(
			'<tpl for=".">' +
				'<div class="entry">' +
					'<a rel="bookmark" href="{link}" class="entry-title" target="_blank">{title}</a>' +
					'<div class="excerpt">' +
						'<p>{description}</p>' +
					'</div>' +
					'<h4><a href="{link}" class="view-post" target="_blank">Visit Message &raquo;</a><br/>From: {date:date("F j, Y  H:i")}</h4>' +
				'</div>' +
			'</tpl>' )
		}),
	viewConfig: {
		forceFit: true,
		autoFill: true
	}
});

iii.shareprice.apps.fixed.layout.stock.news.load = function ( symbol, exchangecode ) {
	if( iii.shareprice.apps.fixed.layout.stock.news.loadMask )
		iii.shareprice.apps.fixed.layout.stock.news.loadMask.destroy();
	iii.shareprice.apps.fixed.layout.stock.news.loadMask = new Ext.LoadMask (
		$( iii.shareprice.apps.fixed.layout.stock.news.grid.id ),
		{
			msg: "Please wait..."
		}
	);
	iii.shareprice.apps.fixed.layout.stock.news.loadMask.show();
	
	var s = symbol.toUpperCase();
	s = s.replace( /\./g, '-' );
	if( s.length == 2 ) {
		s += "-";
	};
	iii.shareprice.apps.stockexplorer.request.send( {
		url: iii.shareprice.apps.config.get( 'feedServiceUrl' ) + encodeURIComponent (  iii.shareprice.apps.config.get( 'iiiNewsUrl' ).substitute(  {
			symbol: s
		} ) ) ,
		success: function ( returns ) {
			data = returns.topics || [];
			iii.shareprice.apps.stockexplorer.stocks.get( exchangecode.toUpperCase() ).up( {
				news: data
			} );
			iii.shareprice.apps.fixed.layout.stock.news.store.loadData( data );
			iii.shareprice.apps.fixed.layout.stock.news.loadMask.hide();
		}
	} );
};



iii.shareprice.apps.fixed.layout.twitter = {};

iii.shareprice.apps.fixed.layout.twitter.store = new Ext.data.JsonStore( {
	fields: [
		'in_reply_to_status_id', { 
			name: 'created_at',
			convert: function ( value ) {
				var date = Date.parseDate( value, "D M d H:i:s O Y" );
				return date.format( "Y-m-d H:i:s" );
			}	 
		}, 'favorited', 'in_reply_to_user_id', 'text', 'source', 'id', 'user', 'truncated'
	]
} );
iii.shareprice.apps.fixed.layout.twitter.grid = new Ext.Panel({
	autoWidth: true,
	autoHeight: true,
	frame: false,
	autoScroll: true,
	border: false,
	layout:'accordion',
	defaults: {
		bodyStyle: 'padding:0px',
		autoScroll: true,
		autoHeight: true
	},
	layoutConfig: {
		animate: true,
		forceFit: true
	},
	fill: true,
	height: '100',
	items: [ {
		stateful: true,
		stateEvents: [ 'expand', 'collapse' ],
		stateId: 'twitter-body',
		getState: function ( ) {
			return {
				collapsed: this.collapsed
			};
		},
		title: 'Service Updates',
		id: 'twitter-content',
		items: 
		new Ext.DataView({
			title: 'Twitter',
			store: iii.shareprice.apps.fixed.layout.twitter.store,
			itemSelector: '.entry',
			deferEmptyText: true,
			tpl: new Ext.XTemplate(
				'<tpl for=".">' +
					'<div class="entry">' +
						'<p>{text}</p>' +
						'<h4>From: {created_at}</h4>' +
					'</div>' +
				'</tpl>'
			)
		})
	} ],
	viewConfig: {
		forceFit: true,
		autoFill: true
	}
});

iii.shareprice.apps.fixed.layout.twitter.load = function ( ) {
	if( iii.shareprice.apps.fixed.layout.twitter.loadMask )
		iii.shareprice.apps.fixed.layout.twitter.loadMask.destroy();
	iii.shareprice.apps.fixed.layout.twitter.loadMask = new Ext.LoadMask (
		$( iii.shareprice.apps.fixed.layout.twitter.grid.items.get('twitter-content').id ),
		{
			msg: "Loading Twitter..."
		}
	);
	iii.shareprice.apps.fixed.layout.twitter.loadMask.show();
	new Element( 'script', {
		'type': 'text/javascript',
		'src': iii.shareprice.apps.config.get( 'twitterUrl' ) + "&callback=foo"
	} ).inject( document.head );
};

iii.shareprice.apps.fixed.layout.twitter.loadData = function ( data ) {
	iii.shareprice.apps.fixed.layout.twitter.store.loadData( data );
};

window.foo = iii.shareprice.apps.fixed.layout.twitter.loadData;

iii.shareprice.apps.fixed.layout.twitter.store.on( 'load', function ( ) {
	if( iii.shareprice.apps.fixed.layout.twitter.loadMask )
		iii.shareprice.apps.fixed.layout.twitter.loadMask.hide();
} );


iii.shareprice.apps.fixed.layout.leftad = {};

iii.shareprice.apps.fixed.layout.leftad.panel =  new Ext.Panel( {
					id : 'left_ad_panel',
					layout:'fit',
					defaults: {
						bodyStyle: 'padding:0px',
						autoScroll: true,
						autoHeight: true
					},
					layoutConfig: {
						animate: false,
						forceFit: true
					},
					fill: true,
					height: '300',
					items: [ {
						id : 'left_ad_panel_1',
						title: 'Sponsor',
                				stateful: false,
                                                preventBodyReset: true,
                                                closable:false,
                                                items: [{
                                                afterRender: function(){
                                                    var random = Math.round(0 + ((99999999999 - 0) * Math.random()));
                                                    var html = "<iframe id='left_ad_panel_1' name='left_ad_panel_1' src='http://openmkt.iii.co.uk/www/delivery/afr.php?n=4&amp;zoneid=30&amp;target=_blank&amp;cb="+random+"' framespacing='0' frameborder='no' scrolling='no' width='200' height='200'>"
                                                    + "<a href='http://openmkt.iii.co.uk/www/delivery/ck.php?n=4&amp;cb="+random+"' target='_blank'>"
                                                    + "<img src='http://openmkt.iii.co.uk/www/delivery/avw.php?zoneid=30&amp;cb="+random+"&amp;n=$id' border='0' alt='' />"
                                                    + "</a>"
                                                    + "</iframe>";
                                                    this.body.update(html);
                                                }
                                                }]
					} ]
				} )


