
// Coded By Brendan Davey
// copyright 2009
//------------------------------------ 

// -------------------------------- MAIN FUNCTION ------------------------------------------------ //


Ext.onReady(function(){
	
	Ext.QuickTips.init();
    //------------------------------ MENU WITH ALL THE GOODNESS ----------------------------------  
	// Create the MAIN toolbar.
	var tb_main = new Ext.Toolbar();

    tb_main.add(
    	'->',
    	{ 
        text: '<b>Settings</b>',
        tooltip: { text: 'Configure how you want the Racing Zone to work', title: 'Racing Zone Settings', autoHide: true },
        icon: 'images/icon_settings.png',
        cls: 'x-btn-text-icon',
        menu: {	id: 'Settings Menu',
        		items:
	    	    [{
					text: '<b>Show:</b>',
					canActivate: false
				},
					new Ext.menu.CheckItem({ text: 'Place Prices', checked: global.show_place, checkHandler: handle_showplace }),
		   			new Ext.menu.CheckItem({ text: 'Win Prices', checked: global.show_win, checkHandler: handle_showwin }),
				    new Ext.menu.CheckItem({ text: 'Scratchings', checked: global.show_scratchings, checkHandler: handle_scratchings }),
			   		new Ext.menu.CheckItem({ text: 'Form as Graph (req Fast PC)', checked: global.show_fgraph, checkHandler: handle_showfgraph }),
			   	    {
			   		text: 'Race Column(s):',
	        		tooltip: { text: 'Show or Hide Race Columns', title: 'Race Columns', autoHide: true },
	    			menu: runner_cols_menu
        		    },
				'-',
				{
	    			text: '<b>Refreshing:</b>',
	    			canActivate: false
	    		},{
	    			text: 'Auto Refresh Period',
	        		tooltip: { text: 'Select how oftern you wish to have information automatically refreshed', title: 'Refresh Settings', autoHide: true },
	    			menu: refresh_menu
		    	},
		    		new Ext.menu.CheckItem({ text: 'Auto Next OPEN Race', checked: global.Race_Autoload, checkHandler: handle_autonextrace }),
		    	'-',
		    	{
	    			text: '<b>Betfair Advantage (ADV%):</b>',
	    			canActivate: false
	    		},
	    			new Ext.menu.CheckItem({ text: 'Show', checked: global.show_advantage, checkHandler: handle_advantage }),
	    		{
	    		  	text: 'Comparison',
	        		tooltip: { text: 'Select the Tote you wish to compare with Betfair', title: 'Betfair Advantage Selection', autoHide: true },
	       		 	menu: advantage_menu
	    		},{
	    		  	text: 'Show ADV% column when',
	        		tooltip: { text: 'Select the conditions for showing the BF advantage column', title: 'Betfair Advantage Selection', autoHide: true },
	       		 	menu: advantage_pool_menu
	    		},
	    		'-',
	    		{
	    		    text: '<b>BF Commission Rate</b>',
	    		    tooltip: { text: 'Will show the Betfair prices less the commission rate you choose, this helps for comparing prices', title: 'BF Commission Selection', autoHide: true },
	    		    menu: commission_menu
		    	}]
        	}
    	},
    	"-",
	    {   text: '<b>Auto Refresh<b>',
		    tooltip: { title: 'Auto Refresh', text: 'Automatically refresh data for the current selected race, refresh rate set in settings menu. Auto Refresh will not work if the race status is CLOSED', autoHide: true },
		    cls: 'x-btn-text-icon',
		    icon: 'images/icon_refresh.png',
		    enableToggle: true,
		    pressed: global.auto_refresh,
		    handler: handle_auto_refresh
		},
		"-",
		{ text: '<b>Scratchings</b>', 
			tooltip: { text: 'Scratchings for the date selected.', title: 'Scratchings', autoHide: true }, 
			handler: handle_allscratchings},
		"-",
		{ text: '<b>Results</b>', tooltip: { text: 'Results for the date selected', title: 'Results', autoHide: true }, handler: handle_allresults},
		"-",
		{ text: '<b>Form</b>', tooltip: { text: 'Form for the current race', title: 'Complete Form', autoHide: true }, handler: handle_allform},
		"-",
		{ text: '<b>A-Z Lists</b>', tooltip: { text: 'List everything about a track for a day selected', title: 'A-Z Lists', autoHide: true }, handler: handle_allaz},
		"-",
		{
			 text: '<b>Help</b>',
		     tooltip: { Title: 'Help', text: 'Need help? click here to find out more about each of the data elements in the racing zone.', autoHide: true },
		     icon: 'images/icon_help.png',
		     cls: 'x-btn-text-icon',
		     menu: { id: 'helpmenu', items: [ 
		            new Ext.menu.Item({ text: 'Help Contents', handler: handle_help}), 
					new Ext.menu.Item({ text: 'About', handler: handle_about}) 
		     ]}
	     }
	);
    tb_main.render('main_toolbar');
    
    //the date toolbar
	var tb_date = new Ext.Toolbar();
	
    tb_date.add({
		text:'<b>Race Date:</b>',
		tooltip: { text: 'Select a date, and view events that occured on that day.', title: 'Race Day Selection', autoHide: true },
		cls: 'x-btn-text-icon',
		icon: 'images/icon_calander.png',
		menu: dateMenu  // assign menu by instance
	});
    
    tb_date.render('date_toolbar');
    
    
    
    // The Race codes toolbar.
	var tb_codes = new Ext.Toolbar();
	
    tb_codes.add(
    	 "->",
    	 {text: '<b>Filter:</b>', canActivate: false, enableToggle: false},
    	 {
    	  	id: 'show_gallops',
    	    tooltip: { text: 'Show or hide Gallop races, toggle on/off', title: 'Gallops', autoHide: true },
    	    enableToggle: true,
    	    pressed: global.show_gallops,
    	    icon: 'images/R.png',
    	    iconCls: 'add',
            scale: 'large',
    	    handler: handle_gallops
		 },{
    	  	id: 'show_harness',
    	    tooltip: { text: 'Show or hide harness races, toggle on/off', title: 'Harness', autoHide: true },
    	    enableToggle: true,
    	    pressed: global.show_harness,
    	    icon: 'images/H.png',
    	    iconCls: 'add',
            scale: 'large',
    	    handler: handle_harness
		 },{
    	  	id: 'show_greyhounds',
    	    tooltip: { text: 'Show or hide greyhound races, toggle on/off', title: 'Greyhounds', autoHide: true },
    	    enableToggle: true,
    	    pressed: global.show_greyhounds,
    	    icon: 'images/G.png',
    	    iconCls: 'add',
            scale: 'large',
    	    handler: handle_greyhounds
		 }
	 );
    
    tb_codes.render('date_codes_toolbar');
    
    
    
    // create grids for the markets... round and match view.
	race_date_grid = new Ext.grid.GridPanel({ 
		store: race_date_store, 
		columns: race_date_cols, 
		renderTo: 'race_date_tag',
		height: 191, 
		stripeRows: true, 
		enableColumnHide: false,
	    view: new Ext.grid.GroupingView({
	        forceFit: true,
		    startCollapsed: true,
	        groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Races" : "Race"]})',
	        scrollToTop: Ext.emptyFn
	    })
	});
	
	
	
    runner_grid = new Ext.grid.GridPanel({ 
    	store: runner_store, 
    	cm: runner_cols, 
    	renderTo: 'runner_tag', 
    	stripeRows: true, 
    	autoHeight: true,
    	enableHdMenu: false,
    	enableColumnHide: false,
    	view: new Ext.grid.GridView({
 		 	forceFit: true	
 	    })
    });
    
 
	var viewport = new Ext.Viewport({
        layout: 'vbox',
        layoutConfig: { align: 'stretch' },
        items: [{
            contentEl: 'banner',
            collapsible:true
        },{
        	xtype: 'container',
            layout: 'hbox',
            height: 234,
            layoutConfig: { align: 'stretch' },
            items: [{
            	width: 5,
            	contentEl: 'racebreak1'
            },{
            	width: v_rezx,
                contentEl: 'race_date'
            },{
            	width: 7,
            	contentEl: 'racebreak2'
            },{
                flex: true,           
                items: [{	
                	height: 43, //26
                	contentEl: 'main_toolbar_table'
                },{
                	height: 191, //191
                  	contentEl: 'race_details',
                  	flex: true
                }]
            },{
            	width: 5,
            	contentEl: 'racebreak3'
            }]
        },{ height: 7, contentEl: 'racebreakh1' },
        {
        	xtype: 'container',
        	layout: 'hbox',
        	flex: true,
        	layoutConfig: { align: 'stretch' },
        	items: [{
				width: 5,
				contentEl: 'racebreak4'
			},
	        {
	            flex: true,
	            contentEl: 'race',
	            autoScroll: true
	        },
	        {
				width: 5,
				contentEl: 'racebreak5'
			}]
        },
        { height: 7, contentEl: 'racebreakh2' }
        ]
    });
    
	
	
	race_details_store.on('load', function() {
		
		//get some global stuff, thats handy for runner calcs etc
		global.bf_pool_percentage = parseFloat(race_details_store.getAt(0).get('POOL_BFWINPERC'));
		global.MarketCountry = race_details_store.getAt(0).get('Country');
		global.BFmarket = race_details_store.getAt(0).get('BFmarket');
		global.PlcMarketID = race_details_store.getAt(0).get( "PlcMarketID" );
		global.MarketType = race_details_store.getAt(0).get( "MarketType" );
		global.MarketStatus = race_details_store.getAt(0).get('MarketStatus');	
		global.LastUpdate = race_details_store.getAt(0).get('UPD_TIME');
		global.RaceTime = race_details_store.getAt(0).get('StartTime');
		
		//if we just loaded a closed market, we now need to halt any further refreshes unless they select a new market.
		if (global.MarketStatus == 'CLOSED') global.refresh_halt = true; else global.refresh_halt = false;
		
		// get the locations of some columns we will use below in the runner grid.
		trainer = runner_cols.getIndexById( "Trainer");
		handicap = runner_cols.getIndexById( "Handicap");
		barrier = runner_cols.getIndexById( "Barrier");
		jockey = runner_cols.getIndexById( "Jockey");
		miniform = runner_cols.getIndexById( "MiniForm");

		Ext.get( 'tag_racecode').dom.innerHTML = "<img src='images/type_" + global.MarketType + ".png'>";	
		Ext.get( 'tag_racetrack').dom.innerHTML = race_details_store.getAt(0).get('VenueName');
		Ext.get( 'tag_racenum').dom.innerHTML = "Race " + race_details_store.getAt(0).get('RaceNum');
		Ext.get( 'tag_trackcond').dom.innerHTML = "Condition - <b>" + race_details_store.getAt(0).get('TrackCond') + "</b>";
		Ext.get( 'tag_trackweather').dom.innerHTML = "Weather - <b>" + race_details_store.getAt(0).get('Weather') + "</b>";
		sta = "";
		if (global.MarketStatus == "ACTIVE") sta = "(OPEN)"; 
		if (global.MarketStatus == "ABANDONED") sta = "(ABANDONED)"; 
		if (global.MarketStatus == "CLOSED") sta = "(CLOSED)"; 
		if (global.MarketStatus == "INTERIM") sta = "(INTERIM)"; 
		if (global.MarketStatus == "SUSPENDED") sta = "(RUNNING)"; 
		Ext.get( 'tag_racestatus').dom.innerHTML = sta;
		Ext.get( 'tag_racefield').dom.innerHTML = "Field - <b>" + race_details_store.getAt(0).get('NumRunners') + "</b>";
		Ext.get( 'tag_raceclass').dom.innerHTML = "&nbsp;&nbsp;Class - <b>" + race_details_store.getAt(0).get('EventClass') + "</b>";
		Ext.get( 'tag_racelength').dom.innerHTML = "Distance - <b>" + race_details_store.getAt(0).get('EventLength') + "m</b>";
		Ext.get( 'tag_racename').dom.innerHTML = race_details_store.getAt(0).get('EventName');	
		Ext.get( 'tag_trackcountry').dom.innerHTML = "<span><img src='images/flag_" + global.MarketCountry + ".png'></span>";
		
		t = global.LastUpdate.split(" ");
		Ext.get( 'tag_updatetime').dom.innerHTML = t[1]; 
		Ext.get( 'tag_racetime').dom.innerHTML = global.RaceTime; //with date.
		
		Ext.get( 'tag_poolstabwin').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_STABWIN'),0);
		Ext.get( 'tag_poolstabwinperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_STABWINPERC');
		Ext.get( 'tag_poolstabplace').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_STABPLACE'),0);
		Ext.get( 'tag_poolstabplaceperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_STABPLACEPERC');
	
		Ext.get( 'tag_poolnswwin').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_NSWWIN'),0);
		Ext.get( 'tag_poolnswwinperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_NSWWINPERC');
		Ext.get( 'tag_poolnswplace').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_NSWPLACE'),0);
		Ext.get( 'tag_poolnswplaceperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_NSWPLACEPERC');
		
		Ext.get( 'tag_pooluniwin').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_UNIWIN'),0);
		Ext.get( 'tag_pooluniwinperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_UNIWINPERC');
		Ext.get( 'tag_pooluniplace').dom.innerHTML = "$" + format_number(race_details_store.getAt(0).get('POOL_UNIPLACE'),0);
		Ext.get( 'tag_pooluniplaceperc').dom.innerHTML = race_details_store.getAt(0).get('POOL_UNIPLACEPERC');
		
		
		Ext.get( 'tag_firstfour_pool').dom.innerHTML = "<a title='POOL'>($" + format_number(race_details_store.getAt(0).get('EXPOOL_FirstFour'),0) + ")</a>";
		Ext.get( 'tag_trifecta_pool').dom.innerHTML = "<a title='POOL'>($" + format_number(race_details_store.getAt(0).get('EXPOOL_Trifecta'),0) + ")</a>";
		Ext.get( 'tag_exacta_pool').dom.innerHTML = "<a title='POOL'>($" + format_number(race_details_store.getAt(0).get('EXPOOL_Execta'),0) + ")</a>";
		Ext.get( 'tag_quinella_pool').dom.innerHTML = "<a title='POOL'>($" + format_number(race_details_store.getAt(0).get('EXPOOL_Quinella'),0) + ")</a>";
		
		// We need to change the look of some columns in the runner grid depending on the race code they just selected	 
		switch (global.MarketType)
		{
			case 'G':
			//runner_cols.setHidden(trainer,true);
			runner_cols.setHidden(barrier,true);
			runner_cols.setHidden(handicap,true);
			runner_cols.setHidden(miniform,true);
			runner_cols.setColumnHeader(jockey,"Driver / Trainer");
			runner_cols.setHidden(runner_cols.getIndexById( "StatsOverallRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsHorseRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsTrainerRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsJockeyRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsStallionRank"),true);
			break;
			case 'H':
			//runner_cols.setHidden(trainer,true);
			runner_cols.setHidden(barrier,true);
			runner_cols.setHidden(handicap,true);
			runner_cols.setHidden(miniform,false);
			runner_cols.setColumnHeader(jockey,"Driver / Trainer");
			runner_cols.setHidden(runner_cols.getIndexById( "StatsOverallRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsHorseRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsTrainerRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsJockeyRank"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsStallionRank"),true);
			break;
			case 'R':
			//runner_cols.setHidden(trainer,false);
			runner_cols.setHidden(barrier,!global.show_barrier);
			runner_cols.setHidden(handicap,!global.show_WGT);
			runner_cols.setHidden(miniform,false);
			runner_cols.setColumnHeader(jockey,"Jockey / Trainer");
			runner_cols.setHidden(runner_cols.getIndexById( "StatsOverallRank"),!global.show_fullstats);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsHorseRank"),!global.show_fullstats);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsTrainerRank"),!global.show_fullstats);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsJockeyRank"),!global.show_fullstats);
			runner_cols.setHidden(runner_cols.getIndexById( "StatsStallionRank"),!global.show_fullstats);
			break;
		}
	
		//If the race is closed, show the results and bookie sp, as well as hide graphs etc.
		placed = runner_cols.getIndexById( "Placed" );
		bookiesp = runner_cols.getIndexById( "TABSP" );
		if ((global.MarketStatus == 'CLOSED') || (global.MarketStatus == 'INTERIM')) {
			//If it's ok to show results do it
			runner_cols.setHidden(placed,!global.show_results); 
			Ext.get( 'tag_firstfour').dom.innerHTML = "<a title='ODD'>$" + format_number(race_details_store.getAt(0).get('EXODD_FirstFour'),0) + "</a>";
			Ext.get( 'tag_trifecta').dom.innerHTML = "<a title='ODD'>$" + format_number(race_details_store.getAt(0).get('EXODD_Trifecta'),0) + "</a>";
			Ext.get( 'tag_exacta').dom.innerHTML = "<a title='ODD'>$" + format_number(race_details_store.getAt(0).get('EXODD_Execta'),0) + "</a>";
			Ext.get( 'tag_quinella').dom.innerHTML = "<a title='ODD'>$" + format_number(race_details_store.getAt(0).get('EXODD_Quinella'),0) + "</a>";
			//Show the Bookie price for Gallops in AU.
			if ((global.MarketType == "R") && (global.MarketCountry == "AU")) runner_cols.setHidden(bookiesp,!global.show_booksp); else runner_cols.setHidden(bookiesp,true);
			Ext.get( 'tag_betnow').dom.innerHTML = '';
		} else {
			//don't show the places at all there not there, or bookie sp.
			runner_cols.setHidden(placed,true);
			runner_cols.setHidden(bookiesp,true); 
			//blank the payouts for exotics.
			Ext.get( 'tag_firstfour').dom.innerHTML = "";
			Ext.get( 'tag_trifecta').dom.innerHTML = "";
			Ext.get( 'tag_exacta').dom.innerHTML = "";
			Ext.get( 'tag_quinella').dom.innerHTML = "";
			//market link.
			Ext.get( 'tag_betnow').dom.innerHTML = '<a href="http://www.betfair.com/?mi=' + global.MarketID + '&ex=2" target="_blank"><img src="images/betnow.png"></a>';
		}
		
		//if the current pool is less than the value stored for showing the percentage, show it (if turned on).
		advantage = runner_cols.getIndexById( "Advantage");
		if (global.bf_pool_percentage < global.advantage_percentage) runner_cols.setHidden(advantage,!global.show_advantage);
		else runner_cols.setHidden(advantage,true);
		
		//Show the reduction factors?
		runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_REDUCTION"),!global.show_reductionf); 
		
		//If it's not a BF market, dont show our stuff etc.
		if (global.BFmarket == false) {
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_BACK"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_WAP"),true);
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_LAY"),true);
			Ext.get( 'tag_poolbfwin').dom.innerHTML = '';
			Ext.get( 'tag_poolbfwinperc').dom.innerHTML = '';
			Ext.get( 'tag_poolbfwinlayperc').dom.innerHTML = '';
			Ext.get( 'tag_poolbfplace').dom.innerHTML = '';
			Ext.get( 'tag_poolbfplaceperc').dom.innerHTML = '';
			Ext.get( 'tag_poolbfplacelayperc').dom.innerHTML = '';
			
		} else {
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_BACK"),false);
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_WAP"),!global.show_bfwap);
			runner_cols.setHidden(runner_cols.getIndexById( "BF_WIN_LAY"),!global.show_bflay);
			Ext.get( 'tag_poolbfwin').dom.innerHTML = "BF Wn <b>$" + format_number(race_details_store.getAt(0).get('POOL_BFWIN'),0) + "</b>";
			Ext.get( 'tag_poolbfwinperc').dom.innerHTML = "(" + global.bf_pool_percentage + "%)";
			Ext.get( 'tag_poolbfwinlayperc').dom.innerHTML = "(" + race_details_store.getAt(0).get('POOL_BFWINLAYPERC') + "%)";
			Ext.get( 'tag_poolbfplace').dom.innerHTML = "BF Pl <b>$" + format_number(race_details_store.getAt(0).get('POOL_BFPLACE'),0) + "</b>";
			Ext.get( 'tag_poolbfplaceperc').dom.innerHTML = "(" + race_details_store.getAt(0).get('POOL_BFPLACEPERC') + "%)";
			Ext.get( 'tag_poolbfplacelayperc').dom.innerHTML = "(" + race_details_store.getAt(0).get('POOL_BFPLACELAYPERC') + "%)";
		}
		
		//now load the runners, it's important to get all this stuff first.
		runner_store.reload({params: {marketid: global.MarketID}});
		
		if ((race_details_store.getAt(0).get('ServiceStatus') != "OK" ) && (race_details_store.getAt(0).get('ServiceStatus') != "" )) {
			Ext.get( 'zone_status' ).dom.innerHTML = '<a onClick="handle_svcerror()" ><img src="/images/degsvc.png" border="0" hspace="5" title="Degraded Service - click for more information" alt="Degraded Service" /></a>';
		} else {
			Ext.get( 'zone_status' ).dom.innerHTML = '';
		}
	});
	
	
	
	
	runner_store.on('load', function() {
		// Don't show the scratchings if they dont want them.
		if (!global.show_scratchings) {
			for (loop = 0; loop < runner_store.data.length; loop++) {
				if (runner_store.getAt(loop).get('Scratched')) { 
					runner_store.removeAt(loop);
					loop--; //go back one, before te loop++ of the loop, stay the same number, just in case there are a few in a row :).
				}
			}
		}
	}); 
		
	
	
	race_date_store.on('load', function() {
		//it was an automated reload, this should also occur the first time.
		if (!global.refresh_user) {	
			loop = 0;
			auto = global.Race_Autoload; // if they have automatic next race enabled, will overwrite marketid if it exists.
			//get a new market id, if they want the next race AUTO NEXT RACE, OR the market is blank.
			while (((auto) || (global.MarketID == '')) && (loop < race_date_store.data.length)) {
				// The next OPEN race.
				if (race_date_store.getAt(loop).get('Market_status') == "A") {
					//found it, write to Market id global and set auto to false, they have it.... drop out.
					global.MarketID = race_date_store.getAt(loop).get('MarketID');
					global.RaceNumber = race_date_store.getAt(loop).get('RaceNumber'); //row.get( 'RaceNumber' );
					global.TrackCode = race_date_store.getAt(loop).get('TrackCode'); //row.get( 'TrackCode' );
					
					//race_date_grid.getSelectionModel().selectRow(loop);
		           // view.grid.getSelectionModel().selectRow(last);
		            //view.focusRow(last);
		            
		            
					auto = false;
					global.refresh_halt = false; //regardless of reload state of market, just do it.
				}
				loop++;
			}
			//Nothing Open found, default to first in list.
			if (global.MarketID == '') {
				global.MarketID = race_date_store.getAt(0).get('MarketID');
				global.RaceNumber = race_date_store.getAt(0).get('RaceNumber'); //row.get( 'RaceNumber' );
				global.TrackCode = race_date_store.getAt(0).get('TrackCode'); //row.get( 'TrackCode' );
			}
		}
				
		
		//--------------------------IMPORTANT-----------------------------
		// Refresh the Runner and race details information for that market select above or allready set for manual
		//if the market is not closed its ok to update. If it is closed, then there is no point. HALT! SOS (Save Our Servers)
		//halting is set the last time it was updated.
		if (!global.refresh_halt) {
			race_details_store.reload({params: {marketid: global.MarketID}});
			//the runenrs get loaded at the end of the race_details_store load in the .on func.
		}
		//-----------------------------------------------------------------
	}); 
	
	

	race_date_grid.getSelectionModel().on(
	    	'rowselect', function( model, row_index ) { handle_races_grid_rowselect( model, row_index ); }
	);
	
	
	
	//refresh, no more refreshing until they turn it on.
	refresh('auto');
	//Ext.Msg.show({title: 'Racing Zone Version 2.', width: 400, buttons: '', msg: "<center><br>Welcome to the Betfair Racing Zone v2 (beta).<br /><br />If you require help or would like to provide feedback<br />on this product please email us at <a href='mailto:racingfeedback@betfair.com'>racingfeedback@betfair.com</a><br><br>If you would like to use the older version of the racing zone, please click <a href='/index_v1.html'>here</a></center>"});
});

// ------------------------------------------------------------------------------------------------------------------------------------


function refresh(u) {
	if (u == 'user') global.refresh_user = true; else global.refresh_user = false;
	//build a list of the types of races the user wants as 1-3 digit code.
	types = '';
	if (global.show_gallops) types = types + "R";
	if (global.show_harness) types = types + "H";
	if (global.show_greyhounds) types = types + "G";
	//If they want something, get it.
	if (types.length == 0) types = "A"; 
	//AS PART OF THIS DATE REFRESH IT WILL DO THE OTHER race and runner details, see race_date on load.
	race_date_store.reload({params: {date: global.RaceDate, type: types}});
}



