iii.shareprice.apps.ly = new Class ( {
	Implements: Events,
	cookie: 'layout',
	initialize: function( superclass ) {
		this.superclass = superclass;
	},
	render: function ( ) {
		var self = this;
		this.superclass.fireEvent( 'layout-start-render' );
		
		this.View = new Ext.Viewport( {
			layout : 'border',
			stateful: true,	
			items : [
				iii.shareprice.apps.fixed.layout.north,
				iii.shareprice.apps.fixed.layout.west, 
				iii.shareprice.apps.fixed.layout.center,
				iii.shareprice.apps.fixed.layout.south
			]
		} );
		iii.shareprice.apps.fixed.layout.center.items.items[ 0 ].on( 'tabchange', function ( ) {
			self.stock.hide.run( [], self );
		} );
		
		iii.shareprice.apps.fixed.layout.center.on( 'resize', function ( ) {
			self.superclass.fireEvent( 'layout-resize', arguments );
		} );
		var searchStockInput = $('search-stock-input');
		
		var wasStreaming = false;
		searchStockInput.addEvent( 'focus', function ( ) {
			if ( self.superclass.stream.isStreaming ) {
				wasStreaming = true;
//				self.superclass.fireEvent( 'stream-stop' );
			} else {
				wasStreaming = false;
			}
		} ).addEvent( 'blur', function ( ) {
			if( wasStreaming == true ) {
//				self.superclass.fireEvent( 'stream-start' );
			}
		} );
		
		this.View.findById( 'center' ).findById( 'list_view' ).findById( 'grid' ).findById( 'grid-panel' ).on( 'rowdblclick', function( obj, key ) {
			var symbol = obj.store.data.keys[ key ];
			self.superclass.fireEvent( 'stock-before-show-alone', [ symbol ] );
		} );
		var ctl0_content_ctl1_search_store = new Ext.data.JsonStore({url: iii.shareprice.apps.config.get( 'serviceUrl' ) +'service/json/securities/search?exchange=LSE,@GB,NASDAQ,NYSE,@US&typeid=1,7,9,13',
			root: 'results',
			fields: ['idnotation','name', 'nameshort','nameofficial', 'securitytypeid', 'subsecuritytypeid', 'branchid', 'exchangeid', 'lsesector', 'sectorid', 'lsesubsector',
			'bestcompanyname', 'urlsafename', 'company', 'sid', 'homecode', 'symbol', 'homesymbol', 'isin', 'type', 'sedolcode', 'nsin', 'homesin', 'idosi', 'idinstrument', 'id', 'key', 'code', 'exchange',
			'idnotation', 'exchangecode', 'displayname']
		} );
		
		
		var ctl0_content_ctl1_search = new Ext.form.ComboBox({
			store: ctl0_content_ctl1_search_store,
			displayField: 'name',
			typeAhead: false,
			loadingText:'Searching...',
			hideTrigger: true,
			minChars: 2,
			queryDelay: 100,
			minListWidth: 450,
			width: 210,
			tpl: '<tpl for="."><div class="x-combo-list-item">{displayname}</div></tpl>',
			applyTo: 'search-stock-input',
			onSelect: function ( record ) { 
				record.data  = $merge( {
					descriptor: {
						name: record.data.name,
						nameshort: record.data.nameshort,
						nameofficial: record.data.nameofficial,
						company: record.data.company,
						displayname: record.data.displayname
					}
				}, record.data );
				var returns = self.superclass.stocks.include( record.data );
				self.superclass.fireEvent( 'stock-search', [ returns.data , record ] );
				self.superclass.fireEvent( 'stock-before-add', [ returns.data, record ] );
				ctl0_content_ctl1_search.list.hide();
			}
		} );
	
		this.superclass.addEvent( 'stock-before-add', function ( stock ) {	
			self.stock.add.run( arguments, self );
		} );
		
		this.superclass.addEvent( 'stock-update', function ( stock ) {
			self.stock.update.run( [ stock.data ], self );
		} );
		
		this.superclass.addEvent( 'stock-before-close', function ( symbol ) {
			self.stock.remove.run( arguments, self );
		} );
		
		this.superclass.addEvent( 'layout-resize', function ( ) {
			self.stock.aloneResize.run( [], self );
		} );
		
		this.superclass.addEvent( 'stock-before-show-alone', function ( symbol ) {
			self.stock.aloneResize.run( [], self );
			self.els.stock.toolbar.activate( symbol );
			self.stock.show.run( [ symbol ], self );
		} );
		this.superclass.addEvent( 'stock-before-hide-alone', function ( ) {
			self.stock.hide.run( [ ], self );
			self.els.stock.toolbar.activate( 'all' );
		} );
		
		this.superclass.addEvent( 'content-before-show', function ( site ) {
			self.content( site );
		} );
		this.superclass.addEvent( 'content-set-title', function ( title ) {
			self.stock.title.run( [ title ] , self );
		} );
		
		this.superclass.addEvent( 'stream-stop', function ( ) {
			self.els.userbar.items.get( 'startstopstreamingbtn' ).setText( 'start streaming' );
		} );
		this.superclass.addEvent( 'stream-start', function ( ) {
			self.els.userbar.items.get( 'startstopstreamingbtn' ).setText( 'stop streaming' );
		} );
		
		this.els = {
			stock: {
				topbar: {
				},
				toolbar: this.View.findById( 'center' ).findById( 'inner-center' ).getBottomToolbar(),
				store: this.View.findById( 'center' ).findById( 'list_view' ).findById( 'grid' ).findById( 'grid-panel' ).getStore(),
				portal: this.View.findById( 'center' ).findById( 'box_view' ).findById( 'box' ).findById( 'box_portal' ),
				portalLeft: this.View.findById( 'center' ).findById( 'box_view' ).findById( 'box' ).findById( 'box_portal' ).findById( 'portlet-system-left' ),
				portalMiddle: this.View.findById( 'center' ).findById( 'box_view' ).findById( 'box' ).findById( 'box_portal' ).findById( 'portlet-system-middle' ),
				portalRight: this.View.findById( 'center' ).findById( 'box_view' ).findById( 'box' ).findById( 'box_portal' ).findById( 'portlet-system-right' ),
				grid: this.View.findById( 'center' ).findById( 'list_view' ).findById( 'grid' ).findById( 'grid-panel' ),
				alone: {
					chart: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'chart' ),
					trades: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'trades' ),
					news: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'news' ),
					info: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'info' ),
					discussions: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'discussions' ),
					web: iii.shareprice.apps.fixed.layout.stock.alone.findById( 'tabpanel' ).findById( 'web' )
				}
			},
			sidebar: {
				recent: this.View.findById( 'west' ).findById( 'recent' ).findById( 'recentSearch' ),
				portfolio: this.View.findById( 'west' ).findById( 'portfolio' ).findById( 'portfolios' )
			},
			centerTabPanel: this.View.findById( 'center' ).findById( 'inner-center' ),
			content: this.View.findById( 'center' ).findById( 'inner-center' ).findById( 'ground' ),
			userbar:  this.View.findById( 'north' ).findById( 'userbar' )
		};
		

		this.superclass.addEvent( 'user-login', function ( name ) { 
			self.els.userbar.items.get('login').hide();
			self.els.userbar.items.get('register').hide();
			self.els.userbar.items.get('logout').show();
			self.els.userbar.items.get( 'startstopstreamingbtn' ).enable();
			self.els.userbar.items.get( 'report-a-bug' ).enable();
			self.els.userbar.items.get('status').setText( 'hello '+ name );
		} );
		this.superclass.addEvent( 'user-logout', function ( ) {
			self.els.userbar.items.get('login').show();
			self.els.userbar.items.get('register').show();
			self.els.userbar.items.get('logout').hide();
			self.els.userbar.items.get( 'report-a-bug' ).disable();
			self.els.userbar.items.get('status').setText( 'hello nobody' );
			var streamingBtn = self.els.userbar.items.get( 'startstopstreamingbtn' );
			if( streamingBtn.pressed ) {
				streamingBtn.toggle();
			}
			streamingBtn.disable();
		} );

        self.add( 
            self.els.stock.alone.trades,
            iii.shareprice.apps.fixed.layout.stock.trade.grid
        );
        self.add( 
            self.els.stock.alone.discussions,
            iii.shareprice.apps.fixed.layout.stock.discussion.grid
        );
        self.add( 
            self.els.stock.alone.web,
            iii.shareprice.apps.fixed.layout.stock.web.grid
        );
		self.add( 
            self.els.stock.alone.news,
            iii.shareprice.apps.fixed.layout.stock.news.grid
        );
		self.add( 
			this.View.findById( 'west' ),
			iii.shareprice.apps.fixed.layout.twitter.grid
		);

		self.add(
			this.View.findById( 'west' ),
  			iii.shareprice.apps.fixed.layout.leftad.panel
		);

		self.add( 
			this.View.findById( 'west' ),
			{
				html: ''
			}
		);
		
		
		iii.shareprice.apps.fixed.layout.twitter.load();

		this.superclass.fireEvent( 'layout-end-render' );
		this.superclass.fireEvent( 'layout-ready' );
	
	},
	add: function( com, els ) {
		if( !com || !com.fireEvent )
			return;
		com.fireEvent( 'beforeadd' );
		if( $type( els ) == 'array' ) {
			els.each( function( el ) {
				com.add( el );
			} );
		} else {
			com.add( els );
		}
		com.doLayout();
		return this;
	},
	empty: function( com ) {
		if( com.items )
			com.items.each( function( e ) {
				com.remove( e );
			} );
	},
	save: function ( ) {
		
	},
	load: function ( ) {
		
	},
	recent: function( el ) {
		this.empty( this.els.sidebar.recent );
		this.add( this.els.sidebar.recent, {
			contentEl: el
		} );
	},
	content: function ( id ) {
		this.stock.hide.run( [], this );
		if( this.actions[ id ] )
			this.actions[ id ].run( [id], this );
		else {
			this.els.centerTabPanel.activate( 'ground' );
			this.empty( this.els.content );
			var ele = $type( iii.shareprice.apps.fixed.tpl[ id ].content ) == "string" ? { html: iii.shareprice.apps.fixed.tpl[ id ].content } : iii.shareprice.apps.fixed.tpl[ id ].content
			this.add( this.els.content, ele );
		}
		
	},
	portfolio: function ( el ) {
		this.empty( this.els.sidebar.portfolio );
		this.add( this.els.sidebar.portfolio, {
			contentEl: el
		} );
	},
	stocksloading: [],
	stocks: [],
	stock: {
		title: function ( textEl ) {
			textEl = $type( textEl ) == 'element' ? {
				contentEl: textEl
			} : {
				html: textEl
			};
			this.empty( this.els.stock.topbar );
			this.add( this.els.stock.topbar, textEl );
			return this;
		},
		add: function ( stock, pos, columnid ) {
			if( !stock )
				return;
			var id = stock;
			var self = this;
			if( $type( stock ) == 'object'  ) {
				id = stock.id;
			}
			if( $type( stock ) == 'array' ) {
				pos = pos || {};
				columnid = columnid || {};
				var loadingids = [];
				stock.each( function ( id ) {
					if( self.stocksloading.contains( id ) || !id || self.stocks.contains( id ) ) {
						$try( function ( ) {
							$( id ).highlight('#ddf');
						} );
					} else {
						self.stocksloading.include( id );
						loadingids.include( id );
						self.superclass.preloader.add( 'Loading ' + id + " ....", id );
					}
				} );
				this.superclass.stock.datas( loadingids, function ( stock, id ) {
					self.superclass.preloader.remove( id || stock.get( 'id' ) );
					self.stock.render.run( [stock.data, pos[id], columnid[id]], self );
					self.stocksloading = self.stocksloading.erase( id );
				} );
			} else {
				if( self.stocksloading.contains( id ) || !id || self.stocks.contains( id ) ) {
					$try( function ( ) {
						$( id ).highlight('#ddf');
					} );
				} else {
					self.superclass.preloader.add( 'Loading ' + id + " ....", id );
					self.stocksloading.include( id );
					this.superclass.stock.data( id, function ( stock ) {
						self.superclass.preloader.remove( id );
						self.stock.render.run( [ stock.data, pos, columnid], self );
						self.stocksloading = self.stocksloading.erase( id );
					} );
				}
				
			}
			this.superclass.fireEvent( 'stock-add-loading', [ stock, pos, columnid ] );
			return this;
		},
		render: function ( data, pos, columnid ) {
			if( !data )
				return false;
			var self = this;
			if( $type( pos ) != 'string' )
				pos = 0;
			if( $type( columnid ) != 'string' || !columnid ) {
				var l = self.els.stock.portalLeft.items.length;
				var m = self.els.stock.portalMiddle.items.length;
				var r = self.els.stock.portalRight.items.length;
				if( this.els.stock.portal.getInnerWidth() >= 1216 ) {
					if( l >= m && l != 0 ) {
						if( m >= r && m != 0 ) {
							columnid = 'portlet-system-right';
						} else {
							columnid = 'portlet-system-middle';
						}
					} else {
						columnid = 'portlet-system-left';
					}
				} else {
					if( l >= m && l != 0 ) {
						columnid = 'portlet-system-middle';
					} else {
						columnid = 'portlet-system-left';
					}
				}
			}
			
			var portletElement = new Element( 'div', {
				'class': 'x-portlet-content'
			} ).set( 'html', iii.shareprice.apps.fixed.tpl.portlet.content.apply( data ) );
			var portlet =	new Ext.ux.Portlet( {
				xtype: 'portlet',
				cls: 'x-portlet',
				style: 'margin: 8px; max-width: 97%;',
				id: data.id,
				height: 150,
				title: iii.shareprice.apps.fixed.tpl.portlet.title.apply( data ),
				contentEl: portletElement,
				tools: iii.shareprice.apps.fixed.layout.stock.tools
			} );
			portlet.setPosition( pos );
			self.els.stock.store.add( new Ext.data.Record( {
				'name' : iii.shareprice.apps.fixed.tpl.list.title.apply( data ),  
				'mid' : Number( data.mid ),
				'currency': data.currency,
				'bid' : Number( data.bid ),
				'ask' : Number( data.ask ),
				'chg_abs' :Number( data.performance ),
				'chg_prc' : Number( data.performancepct ),
				'update' : data.pricedtm_time,
				'high' : Number( data.high ),
				'low' : Number( data.low ),
				'volume': data.totalvolume_f
				}, data.id
			) );
	
			self.add(
				self.els.stock.portal.findById( columnid ),
				portlet
			);
			self.add(
				self.els.stock.toolbar,
				{
				title: iii.shareprice.apps.fixed.tpl.btn.title.substitute( data ),
				id: data.id
				}
			);
			
			self.stocks.include( data.id );
			self.stocktopbar();
			
			self.superclass.fireEvent( 'stock-add', [ $merge( 
			{
				pos: pos,
				column: columnid
			},
			data), data ] );
			
		},
		empty: function ( ) {
			var self = this;
			this.stocks.each( function ( id ) {
				self.stock.remove.run( [ id ], self );
			} );
			return this;
		},
		remove: function ( id ) {
			this.els.stock.store.remove( this.els.stock.store.getById( id ), true );
			this.stocks = this.stocks.erase( id );
			this.stocksloading = this.stocksloading.erase( id );
			this.els.stock.portalLeft.remove( this.els.stock.portalLeft.findById( id ), true );
			this.els.stock.portalMiddle.remove( this.els.stock.portalMiddle.findById( id ), true );
			this.els.stock.portalRight.remove( this.els.stock.portalRight.findById( id ), true );
			this.els.stock.toolbar.remove( this.els.stock.toolbar.findById( id ) );
			$try( function ( ) {
				$( id ).destroy();
			} );
			this.stocktopbar();
			this.superclass.fireEvent( 'stock-remove', [ id ] );
			return this;
		},
		show: function ( id ) {
			if( !id )
				return;
			var self = this;
			var stock = self.superclass.stocks.get( id ).data;
			this.superclass.fixed.layout.stock.alone.show( );

			var tabpanel = this.superclass.fixed.layout.stock.alone.items.get( 'tabpanel' );
			if( $type( tabpanel.events.tabchange ) == 'object' )
				tabpanel.events.tabchange.clearListeners ( );

			tabpanel.on( 'tabchange', function ( tabpan ) {
				switch( tabpan.activeTab.id ) {
					case 'stock-alone-trade-view' :
						var btn = Ext.getCmp( 'reload-trade-data' );
						btn.setHandler( function ( ) {
							iii.shareprice.apps.fixed.layout.stock.trade.load( stock.id );
						} );
						self.add( 
							self.els.stock.alone.info,
							{
								html: iii.shareprice.apps.fixed.tpl.alone.info.apply( stock )
							}
						);
						iii.shareprice.apps.fixed.layout.stock.trade.load( stock.id.toLowerCase() );
					break;
					case 'stock-alone-chart-view' :
						self.empty( self.els.stock.alone.chart );
						var container = new Element ( 'div' );
						stock.chart = new Swiff( iii.shareprice.apps.config.get( 'serviceUrl' ).replace( '/index.php/', '' ) + '/advanced/amstock.swf', {
							id: 'chart' + stock.id,
							width: '100%',
							height: 500,
							container: container,
							params: {
								wmode: 'transparent',
								quality: 'high',
								bgcolor: "#FFFFFF"
							},
							vars: {
								key: '116-a7c1558387abb9e96b59b8bdbab3e660',
								settings_file: iii.shareprice.apps.config.get( 'serviceUrl' ) + 'quote/amchartsettings?format=xml&id=' + stock.key,
								preloader_color: '#999999'
							}
						} );
						
						$try ( function ( ) {
							stock.chart = container.get( 'html' );
						},function ( ) {
							stock.chart = container.xml || container.outerHTML;
						}, function ( ) {
							stock.chart = stock.chart.toElement().xml || stock.chart.toElement().outerHTML;
						}, function ( ) {
							stock.chart = "Can not showing the chart";
						} );
						stock.chart = stock.chart.replace( /FlashVars\" VALUE\=\"\"/gi, function ( ) {
							return "FlashVars\" VALUE=\"key=116-a7c1558387abb9e96b59b8bdbab3e660&preloader_color=#999999&settings_file=" + encodeURIComponent( iii.shareprice.apps.config.get( 'serviceUrl' ) + 'quote/amchartsettings?format=xml&id=' + stock.key ) + "\"";
						} );
						self.add( 
							self.els.stock.alone.chart,
							{
								html: String( iii.shareprice.apps.fixed.tpl.alone.chart ).substitute( stock )
 							}
						);
					break;
					case 'stock-alone-news-view' :
						iii.shareprice.apps.fixed.layout.stock.news.load( stock.code.toLowerCase(), stock.exchangecode );
					break;
					case 'stock-alone-info-view' :
						self.empty( self.els.stock.alone.info );
						self.add( 
							self.els.stock.alone.info,
							{
								html: iii.shareprice.apps.fixed.tpl.alone.info.apply( stock )
 							}
						);
					break;
					case 'stock-alone-discussions-view' :
						iii.shareprice.apps.fixed.layout.stock.discussion.load( stock.code );
					break;
					default :
						iii.shareprice.apps.fixed.layout.stock.web.load( stock.descriptor.friendlyname || stock.name );
					break;
				}
			} );
			tabpanel.fireEvent( 'tabchange', tabpanel );

			iii.shareprice.apps.fixed.layout.stock.alone.setTitle( iii.shareprice.apps.fixed.tpl.alone.title.apply( stock ) );
		},
		hide: function ( ) {
			var self = this;
			$try( function( ) {
				self.superclass.fixed.layout.stock.alone.hide( );
			} );
		},
		aloneResize: function ( ) {
			var s = this.View.findById( 'center' ).getSize();
			
			iii.shareprice.apps.fixed.layout.stock.alone.setSize( {
				width: s.width-2,
				height: s.height-65
			} );
			var p = this.View.findById( 'center' ).getPosition();
			iii.shareprice.apps.fixed.layout.stock.alone.setPosition( p[0], p[1]+25 );
			var height = s.height - 170;
			
			iii.shareprice.apps.fixed.layout.stock.news.grid.setHeight( height + 35 );
			iii.shareprice.apps.fixed.layout.stock.trade.grid.setHeight( height + 20 );
			iii.shareprice.apps.fixed.layout.stock.web.grid.setHeight( height );
			iii.shareprice.apps.fixed.layout.stock.discussion.grid.setHeight( height - 20 );
		},
		update: function ( data ) {
                        this.els.stock.store.suspendEvents()
			var record = this.els.stock.store.data.get( data.id );
			if( record ) {
				record.beginEdit();
				record.set( 'name', iii.shareprice.apps.fixed.tpl.list.title.apply( data ) );
                                record.set( 'mid', Number( data.mid ) );
				record.set( 'bid', data.bid_f );
				record.set( 'ask', data.ask_f );
				record.set( 'chg_abs', data.performance_f );
				record.set( 'chg_prc', data.performancepct_f );
				record.set( 'update', data.pricedtm_time );
				record.set( 'high', data.high_f );
				record.set( 'low', data.low_f );
				record.set( 'volume', data.totalvolume_f );
				record.endEdit();
				record.commit();
			};

			var boxelement = $ ( data.id );
			if( boxelement ) {
				var boxcontent = boxelement.getElement( '.x-portlet-content' );

                                var a = iii.shareprice.apps.fixed.tpl.portlet.content.apply( data )

                                if( boxcontent )
					boxcontent.set( 'html', iii.shareprice.apps.fixed.tpl.portlet.content.apply( data ) );
				boxelement.highlight( data.color );
			}
                        this.els.stock.store.resumeEvents()
                        this.els.stock.grid.getView().refresh(false);
			var recordelement = $( 'list_view' ).getElements( '.x-grid3-row' )[ this.els.stock.store.findInsertIndex( record ) ];
			if( recordelement )
				recordelement.highlight( data.color );
		}
	},
	stocktopbar: function ( ) {
	},
	actions: {
		register: function ( ) {
			return window.location.replace('/?page=register');
			//return iii.shareprice.apps.fixed.layout.register();
		}
	}
} );
