/* $Header$ */

			var loadurl = MOD_BUSDIR_URL+'busdirajax_e.php?type=';
			var baseurl = MOD_BUSDIR_URL+'busdirajax.php?type=';
			
			Ext.onReady(function(){ 
				Ext.QuickTips.init(); // turn on validation errors beside the field globally
				Ext.form.Field.prototype.msgTarget = 'side'; // create simple dynamic form 
				var pp = Ext.urlDecode(window.location.search.substring(1));

				if(pp.action == 'edit'){
					loadurl = MOD_BUSDIR_URL+'busdirajax_e.php?action=edit&type=';
				}

				Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

			/*	var state = Ext.state.Manager.getProvider();
				var start = state.get('startStoreAdmin',0);
				var limit = state.get('limitStoreAdmin',15);
				var q = state.get('qStoreAdmin','');*/

				var businessDataStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : loadurl+'businessData.json',
					root: 'data',
					totalProperty: 'totalcount',
			        idProperty: 'id',
			        params: {'start':0,'q':'', 'limit':15},
			        remoteSort: true,
					fields : ['id','businessName','municipality','naics','established','employees','website','description','phone','action','geoCodeAddr','lat','lng']
				});
				
				var numEmployeeRangeStore = new Ext.data.SimpleStore({
					fields: ['range','label'],
					data: [["1-4",'1 to 4'],
							["5-9",'5 to 9'],
							["10-19",'10 to 19'],
							["20-49",'20 to 49'],
							["50-99",'50 to 99'],
							["100-249",'100 to 249'],
							["250-499",'250 to 499'],
							["500-999",'500 to 999'],
							["1000-4999",'1,000 to 4,999'],
							["5000-9999",'5,000 to 9,999'],
							["10000+",'Over 10,000'],
							["0",'Not Available']]
				});
				
				var structureTypeStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'structure-type.json',
					root: 'result',
					fields : ['type','structure']
				});
				
				var isoStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'iso.json',
					root: 'result',
					fields : ['id','isoreg']
				});
				
				var countryStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'countries.json',
					root: 'result',
					fields : ['id','country']
				});
				
				var yearStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'year.json',
					root: 'result',
					fields : ['year','Year']
				});
				
				var townStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'townDropDown.json',
					root: 'result',
					fields : ['mid','municipality']
				});
				
				var naicsPrimaryStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'naics-primary.json',
					root: 'result',
					fields : ['code','description']
				});
				
				var businessParkStore = new Ext.data.JsonStore({
					autoLoad : true,
					url : baseurl+'businessPark.json',
					root: 'result',
					fields : ['bpid','businessPark']
				});
                
                
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: structureTypeStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: isoStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: countryStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: yearStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: townStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: naicsPrimaryStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: businessParkStore});
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: countryStore});
				
				var form = new Ext.FormPanel({
					cls:'form-style',
					labelWidth: 150,
					frame:false,
					header:false,
					border:false,
					bodyBorder:false,
					bodyStyle:'padding:20px',
					width: 675,
					defaults: {width: 450},
					defaultType: 'textfield', // define form fields
					items: [
						{
							xtype: 'textfield',
							fieldLabel: 'Company Name',
							hiddenName: 'companyName',
							name: 'companyName'
						},
						{
							xtype: 'textfield',
							fieldLabel: 'Street Name',
							hiddenName: 'streetName',
							name: 'streetName'
						},
						{
							xtype: 'textfield',
							fieldLabel: 'City/Town',
							hiddenName: 'city',
							name: 'city'
						},
						{
							xtype: 'textfield',
							fieldLabel: 'Postal Code',
							hiddenName: 'postal',
							name: 'postal'
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							fieldLabel: 'Municipality',
							hiddenName: 'municipality',
							displayField: 'municipality',
							valueField: 'municipality',
							store: townStore,
							typeAhead: true,
							mode: 'local',
							triggerAction:'all',
							emptyText: 'Select municipality...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							fieldLabel: 'Year Established in City',
							hiddenName: 'yearEstInCity',
							displayField: 'Year',
							valueField: 'year',
							store: yearStore,
							typeAhead: true,
							mode: 'local',
							triggerAction:'all',
							emptyText: 'Select Year...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							xtype: 'combo',
							//xtype: 'lovcombo',
							//separator: '~',
							//forceSelection: true,
							fieldLabel: 'Number of Employees',
							hiddenName: 'numEmp',
							displayField: 'label',
							valueField: 'range',
							store: numEmployeeRangeStore,
							typeAhead: true,
							mode: 'local',
							triggerAction:'all',
							emptyText: 'Select Range...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							fieldLabel: 'Country of Ownership',
							hiddenName: 'countryOwn',
							displayField: 'country',
							valueField: 'country',
							store: countryStore,
							typeAhead: true,
							mode: 'local',
							triggerAction:'all',
							emptyText: 'Select Country...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							hiddenName: 'naics',
							fieldLabel: 'NAICS Code',
							displayField: 'description',
							valueField: 'description',
							mode: 'local',
							store: naicsPrimaryStore,
							typeAhead: true,
							triggerAction:'all',
							emptyText: 'Select NAICS code...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							fieldLabel: 'Quality Registration',
							hiddenName: 'isoReg',
							displayField: 'isoreg',
							valueField: 'isoreg',
							store: isoStore,
							typeAhead: true,
							mode: 'local',
							triggerAction:'all',
							emptyText: 'Select Registration...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							hiddenName: 'business_park',
							fieldLabel: 'Business Park',
							displayField: 'businessPark',
							valueField: 'businessPark',
							store: businessParkStore,
							typeAhead: true,
							mode: 'local',
							triggerAction: 'all',
							emptyText: 'Select business park...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						},
						{
							//inputType: 'ComboBox',
							//xtype: 'combo',
							xtype: 'lovcombo',
							separator: '~',
							//forceSelection: true,
							hiddenName: 'structure_type',
							fieldLabel: 'Structure Type',
							displayField: 'structure',
							valueField: 'structure',
							mode: 'local',
							store: structureTypeStore,
							typeAhead: true,
							triggerAction:'all',
							emptyText: 'Select company structure type...'
						/*	listeners: {blur:{
								 fn: function(combo) {
								if (combo.getRawValue() == ''){
								   combo.setValue('');
								}
								 }
							}} */
						}
					],
					buttons: [
						{
						text: 'Search',
						handler: function() {
											var f = form.getForm();
											//var state = Ext.state.Manager.getProvider();
                                            //var query = f.getValues(true).replace(/\=/g,':').replace(/\&/g,'|');
											var query =  'approved:on|listing_approved:on|municipality:'+f.findField('municipality').getValue()+'|'+'business_park:'+f.findField('business_park').getValue()+'|'+'num_employees_in_town:'+f.findField('numEmp').getValue()+'|'+'structure_type:'+f.findField('structure_type').getValue()+'|'+'iso_registrations:'+f.findField('isoReg').getValue()+'|'+'naics_all:'+f.findField('naics').getValue()+'|'+'country_of_ownership:'+f.findField('countryOwn').getValue()+'|'+'year_est_in_city:'+f.findField('yearEstInCity').getValue()+'|'+'company_name:'+f.findField('companyName').getValue()+'|'+'address:'+f.findField('streetName').getValue()+'|'+'city:'+f.findField('city').getValue()+'|'+'postal:'+f.findField('postal').getValue();
											//state.set('qStoreAdmin',query);
											businessDataStore.baseParams.q = query;
											businessDataStore.load({params: {
														q:query,start:0,limit:15
												}});
							}
						},
						{
						text: 'Reset',
						handler: function() {
											var f = form.getForm();
											//var state = Ext.state.Manager.getProvider();
											var query =  '';
											f.reset();
											//state.set('qStoreAdmin',query);
											businessDataStore.baseParams.q = query;
											businessDataStore.load({params: {
														q:query,start:0,limit:15
												}});
							}
						}
					]
				});

				form.render('grid-form');
				
			/*	Ext.PagingToolbar.override({  
				   init : function (grid) {  
				     this.grid = grid;          
				     this.grid.on("beforestatesave", this.saveState, this);      
				     Ext.util.Observable.capture(grid.store, this.onStateChange, this);  
				   },  
				   saveState : function(grid, state) {  
				     state.start = grid.store.lastOptions.params.start;
				     state.q = grid.store.lastOptions.params.start;  
				   },  
				   onStateChange : function(ev, store, records, options) {  
				     if (ev == "load") {this.grid.saveState(); };  
				   }  
				});  */
				
				var expander = new Ext.grid.RowExpander({
					tpl: new Ext.Template(
						'<div style="padding:10px;"><p><b>Year Established:</b> {established}</p>',
						'<p><b>Description</b><br>',
						'{description}</p><br>',
						'<p><b>Phone Number:</b> {phone}</p>',
						'<p><b><a href="/busdir_listing?busid={id}" style="color:#990000; text-decoration:none;" target="_BLANK"><span style="font-family: Arial Black, Arial, sans-serif;">&#187;</span> View More Details</a></b></p></div>'
						)
				});
				
				
				var map = new Ext.ux.GMapPanel({
					title: 'Map',
    				gmapType: 'map',
					zoomLevel: 16,
					/*mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
            		mapControls: ['GSmallMapControl','GMapTypeControl']*/
					height: 500,
					dataStore: businessDataStore,
    				addControl: new GSmallMapControl(),
					defaultCenter: {
    					geoCodeAddr: '57 Erb Street West, Waterloo, Ontario, Canada N2L 6C2',
			            marker: {title: 'Canada\'s Technology Triangle Inc'}
    				}
				});
				
				var grid = new Ext.grid.GridPanel({
					title:'Grid',
					cls:'grid-style',
					id:'search-private-grid',
					frame:false,
					header:false,
					border:false,
					bodyBorder:false,
					store:businessDataStore,
					autoHeight:false,
					width:675,
					height:400,
					hideCollapseTool:true,
					stripeRows:true,
					iconCls:'icon-grid',
					plugins:expander,
					bbar: new Ext.PagingToolbar ({
						pageSize: 15,
						store: businessDataStore,
						displayInfo: true,
				        displayMsg: 'Displaying entries {0} - {1} of {2}',
				        emptyMsg: "No entries to display"
					}),
					columns: [
						expander,
						{header:"Business Name",dataIndex:'businessName',width:175},
						{header:"Municipality",dataIndex:'municipality',width:88},
						{header:"NAICS",dataIndex:'naics',width:270},
						{header:"Employees",dataIndex:'employees',width:65,align:'center'},
					//	{header:"Website Address",dataIndex:'website',width:175},
						{header:"Action",dataIndex:'action',width:50,align:'center'}
					]
				});
				
                new Ext.LoadMask(Ext.getBody(), {msg: 'Please Wait...', store: businessDataStore});
				
				businessDataStore.on('load',function(){
							/*var state = Ext.state.Manager.getProvider();
							var grid = Ext.ComponentMgr.get('search-private-grid');
							this.baseParams.q = state.get('qStoreAdmin','');
							var start = 0;
							var limit = 15;
							var q = '';
							if (typeof grid.getStore().lastOptions.params != 'undefined'){
								start = (!(grid.getStore().lastOptions.params['start'] === null))? grid.getStore().lastOptions.params['start'] : 0;
								limit = (!(grid.getStore().lastOptions.params['limit'] === null))? grid.getStore().lastOptions.params['limit'] : 15;
								q = (!(grid.getStore().lastOptions.params['q'] === null))? grid.getStore().lastOptions.params['q'] : '';
							}*/
							//var start = (!(grid.getStore().lastOptions.params['start'] === null))? grid.getStore().lastOptions.params['start'] : 0;
							//var limit = (!(grid.getStore().lastOptions.params['limit'] === null))? grid.getStore().lastOptions.params['limit'] : 0;
							//var q = (!(grid.getStore().lastOptions.params['q'] === null))? grid.getStore().lastOptions.params['q'] : 0;
							/*state.set('startStoreAdmin',start);
							state.set('limitStoreAdmin',limit);
							state.set('qStoreAdmin',q);*/
							
							if (map.rendered) {
								map.clearMarkers();
								businessDataStore.each(function(rec){
									if (!(rec.data.lat == 0 && rec.data.lng == 0)) {
										var marker = map.addMarker(new GLatLng(rec.data.lat, rec.data.lng), {title: rec.data.businessName});
                                        GEvent.addListener(marker,'click', function() {
                                            window.open('busdir_listing?busid=' + rec.data.id, 'details');
                                        });
									}
								});

								map.setCenter(map.getCenter(), map.getBoundsZoomLevel());
							}
						});
						
				var tabPanel = new Ext.TabPanel( {
					//xtype: 'tabpanel',
					activeTab: 0,
					frame: false,
					//autoHeight: true,
					height:400,
					width:675,
					items: [
						grid,
						map 
					]
				});
				
				function bugfix(){
				    if(Ext.isIE) grid.view.mainHd.setOpacity(100);
				}
                         
				grid.on('mouseover',function(){
				    bugfix();
				});

				grid.on('render',bugfix);
				
				var searchResultsPanel = new Ext.Panel({
					renderTo:'grid',
					title:'Search Results',
					collapsible: false,
					header: true,
					border: false,
					frame: false,
					width: 675,
					autoHeight: true,
					layout: 'fit',
					style: 'font-family:arial; font-size:small; color:#666600;',
					items: tabPanel
				});
			
			}); 
			