/*
 * LSPN
 * Copyright(c) 2008 Color Shift, Inc.
 * Created on January 22, 2008
 * By Mark Hulka
 *
 */
 
Ext.BLANK_IMAGE_URL = 'ext2/resources/images/default/s.gif';
Ext.namespace('LSPN');
Ext.namespace('LSPN.enums');
Ext.namespace('LSPN.stores');

// some globals
var PAGE_LIMIT = 5; // The maximum rows returned in a grid before paging.
var ROOT_URL = '/';
var RPC_URL = ROOT_URL+'LspnService.php';
var RSS_URL = ROOT_URL+'rss.php';
var saved_arcade_event = 0;
var last_tab = 0;
var in_arcade = 0;

Ext.onReady(function(){
	if (!is_logged_in)
	{
		var button = new Ext.Button({
			applyTo: 'join_button',
			style: 'text-align: center; margin:auto;',
		    text: 'Join Now',
		    handler: function(){
		    	window.location.href = 'community/ucp.php?mode=register';
		    }
		});
		
		var button = new Ext.Button({
			applyTo: 'login_button',
			style: 'text-align: center; margin-top: 10px; margin-left:auto; margin-right: auto;',
		    text: 'Log In',
		    handler: function(){
		    	window.location.href = 'community/ucp.php?mode=login&redirect=..'+redirect;
		    }
		});
	}
});

LSPN.MainPage = function(config) 
{
    Ext.apply(this, config);
    this.tabs = null;
    //this.officialTours = null;
    this.event_id = 0;
    this.leaderboardOptionsWin = null;
    this.flightOptionsWin = null;
    this.flightOptions = {
    	game : 'anygame',
		difficulty : -1,
		swing : 0
    }    
    this.leaderboardOptions = {
    	game : 'l2k3',
		difficulty : 1,
		swing : 1
    }
    this.useLeagueId = 0;
    this.leagueCurrentEvents = 0;
    this.userPrefs  = {
    	game: '',
    	skill: '',
    	swing_type: '',
    	matchplay: ''
    }
    this.previousEvents = false;
    this.pointsOptionsWin = null;
    this.currentEventOptionsWin = null;
    this.scheduleGrid = null;
    this.coursesWin = null;
    this.rssOptionsWin = null;
    this.rssOptions = {
    	feed : this.golfRss
    };
    
    this.currentEventOptions = 0;
    this.pointsOptions = 0;
    this.setDefaultCurrentEventOptions();
	//this.setDefaultPointsOptions();
    this.cp = new Ext.state.CookieProvider({
	       path: "/",
	       expires: new Date(new Date().getTime()+((1000*60*60*24)*365*10)), //10 years
	       domain: "lspn.net"
	   });        

	this.getLeaderboardOptions();
	Ext.QuickTips.init();
};

LSPN.MainPage.prototype.initGolfNewsBlock = function()
{
	this.getRssOptions();
	var ds = new Ext.data.Store({
	proxy: new Ext.data.HttpProxy({url: RSS_URL+"?feed="+ this.rssOptions.feed}),
		reader: new Ext.data.XmlReader({
	       record: 'item'
	   }, ['title', 'description', 'pubDate', 'link'])
	});
	ds.load();
	
	ds.on("load", function(ds, records, options){
		var linkNode = ds.reader.xmlData.getElementsByTagName("link");
		var pageLink = linkNode[0].firstChild.nodeValue;
		var titleNode = ds.reader.xmlData.getElementsByTagName("title");
		var pageTitle = titleNode[0].firstChild.nodeValue;
		var imageTitle = titleNode[1].firstChild.nodeValue;
		var descNode = ds.reader.xmlData.getElementsByTagName("description");
		var pageDesc = descNode[0].firstChild.nodeValue;
		
		var header = document.getElementById('golf-news-header');
		header.innerHTML = '<div style="float: left; width: 250px; text-align: center;"><img src="images/icons/rss.png"/></div><div style="float: left; line-height: 2em;"><a href="'+pageLink+'" target="_new">'+pageTitle + '</a><br/>'+pageDesc+'</div>';
		
	});

    // Custom rendering Template for the View
    var resultTpl = new Ext.XTemplate(
        '<tpl for=".">',
        '<div class="search-item">',
            '<p><a href="{link}" style="font-weight: bold; font-size: 90%" target="_new">{title}</a><br/><span style="font-size: 75%; color: #818181">{pubDate}<br/></span><span stye="font-size: 80%;">{description}</span></p><br/>',
        '</div></tpl>'
    );

    var panel = new Ext.Panel({
        applyTo: 'golf-news-panel',
        height:325,
        autoScroll:true,
        loadMask: true,
        bodyStyle: "border: 0px;",

        items: new Ext.DataView({
        	id: 'golf-news-view',
            tpl: resultTpl,
            store: ds,
            itemSelector: 'div.search-item',
            loadingText:'Loading RSS News'
        })
    });
}

LSPN.MainPage.prototype.initLSPNNewsBlock = function()
{
	this.news_panel = new Ext.Panel({
            	renderTo: 'lspn-news-panel',
            	height: 152,
            	autoScroll: true,
            	header: false,
            	bodyStyle: "border: 0px; background: #fff6e0;",
            	autoLoad: ROOT_URL+'news.php'
            });
}

LSPN.MainPage.prototype.initLeagueAboutBlock = function()
{
	this.news_panel = new Ext.Panel({
            	renderTo: 'about-league-panel',
            	height: 152,
            	autoScroll: true,
            	header: false,
            	bodyStyle: "border: 0px; background: #fff6e0;",
            	autoLoad: ROOT_URL+'news.php'
            });
}



LSPN.MainPage.prototype.doLeaderboard = function(grid, rowIndex, colIndex, e)
{
	var tab = this.tabs.getActiveTab();
	this.event_id = tab.event_id;
	
	if (tab)
	{
		this.showFullLeaderboard(this.event_id, tab.tour_name);
	}
}

LSPN.MainPage.prototype.showMyLeaderboard = function(grid, rowIndex, colIndex, e)
{
    var selectionModel = grid.getSelectionModel(); 
    var record = selectionModel.getSelected();  
    this.event_id = record.get('event_id');
    var name = record.get('name');
	this.showFullLeaderboard(this.event_id, name);
}


LSPN.MainPage.prototype.showFullLeaderboard = function(event_id, title)
{
	var method = "getLeaderboard";
	if (this.previousEvents)
		method = "getPreviousLeaderboard";	
		
	this.event_id = event_id;
	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:method})),
		method: "POST",
	    remoteSort: false,
	    baseParams : {event_id: event_id, swing_type: this.leaderboardOptions.swing},
	    sortInfo : {field: 'total_score', direction: "ASC"},
	    reader: new Ext.data.JsonReader({
	    root: 'rows'
	   }, ['difficulty', 'game', 'rank', 'user_id', 'username', 'total_score', 'r1', 'r2', 'r3', 'r4', 'total_strokes', 'penalty', 'current_round', 'current_hole', 'status_str', 'points', 'swing_type'] )
	});
	ds.on("load", function(){
		if (ds.reader.jsonData.flight_view)
		{
			var win = Ext.getCmp("leaderboard-win");
			var title = '<span style="color: #c00; font-weight: bold">***FLIGHT VIEW - </span>' + win.title +'<span style="color: #c00; font-weight: bold"> - FLIGHT VIEW***</span>';
			win.setTitle(title);
		}
	});
	
	ds.load();
	var cm = new Ext.grid.ColumnModel([
				{header: "Pos", width: 50, sortable: false, dataIndex: 'rank'}, 	
		        {header: "Player", width: 150, sortable: true, dataIndex:'username', renderer: showMe}, 
				{header: "Score", width: 50, sortable: true, dataIndex: 'total_score', renderer: renderScore}, 
				{header: "R1", width: 35, sortable: true, dataIndex: 'r1'}, 
				{header: "R2", width: 35, sortable: true, dataIndex: 'r2'}, 
				{header: "R3", width: 35, sortable: true, dataIndex: 'r3'},
				{header: "R4", width: 35, sortable: true, dataIndex: 'r4'},
				{header: "Strokes", width: 50, sortable: true, dataIndex: 'total_strokes'},
				{header: "Penalty", width: 50, sortable: true, dataIndex: 'penalty'},
				{header: "Swing", width: 50, sortable: true, dataIndex: 'swing_type', renderer: renderLeaderboardSwing},
				{header: "Thru", width: 50, sortable: true, renderer: renderThru},
				{header: "Status", width: 100, sortable: true, dataIndex: 'status_str'},
				{header: "Points", width: 50, sortable: true, dataIndex: 'points'}
    ]);	
     
    var grid = new Ext.grid.GridPanel({
            	region: 'north',
            	height: 280,
            	id: 'leaderboard',
            	loadMask: true,
                border:false,
	        	ds : ds,    
 				split: true,
	        	stripeRows: true,
                cm: cm,
                viewConfig: {
                    forceFit:true
                }
            })         
	grid.on('rowclick', this.getStats, this); 
	grid.on('rowdblclick', this.leaderboardShowProfile, this); 
	
	var scorecard = new Ext.Panel({
		            	id: 'scorecard',
		            	title: 'Scorecard',
		            	autoScroll: true,
		            	height: 200,
		            	width: 700
		            });

	var stats = new Ext.Panel({
		            	id: 'stats',
		            	height: 200,
		            	title: 'Stats',
		            	autoScroll: true,
		            	header: false,
		            	width: 700,
		            	autoLoad: '/viewStats.php'
		            });

	stats.render('stats');
	var scoretabs = new Ext.TabPanel({
		    	region: 'center',
		        resizeTabs:true,
		        width: 700,
		        autoShow: true,
		        height: 200,
		        defaults: {autoScroll:true}
	});
	scoretabs.add(scorecard).show();
	scoretabs.add(stats).show();
	scoretabs.activate("scorecard");
	scoretabs.doLayout();
	
    win = new Ext.Window({
    	id: 'leaderboard-win',
        title: title,
        width:740,
        height:480,
        modal: true,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			grid,
		    scoretabs
   		 ]
    });
    
    win.show();	
    scoretabs.doLayout();
}

LSPN.MainPage.prototype.getLeaderboardOptions = function()
{
	this.leaderboardOptions.game = this.cp.get("game") === undefined ? this.leaderboardOptions.game : this.cp.get("game");
	this.leaderboardOptions.difficulty = this.cp.get("difficulty") === undefined ? this.leaderboardOptions.difficulty : this.cp.get("difficulty");
	this.leaderboardOptions.swing = this.cp.get("swing") === undefined ? this.leaderboardOptions.swing : this.cp.get("swing");
}

LSPN.MainPage.prototype.getFlightOptions = function()
{
	this.flightOptions.game = this.cp.get("flgame") === undefined ? this.flightOptions.game : this.cp.get("flgame");
	this.flightOptions.difficulty = this.cp.get("fldifficulty") === undefined ? this.flightOptions.difficulty : this.cp.get("fldifficulty");
	this.flightOptions.swing = this.cp.get("flswing") === undefined ? this.flightOptions.swing : this.cp.get("flswing");
}


LSPN.MainPage.prototype.getRssOptions = function()
{
	this.rssOptions.feed = this.cp.get("feed") === undefined ? this.rssOptions.feed : this.cp.get("feed");
}

LSPN.MainPage.prototype.getCurrentEventOptions = function()
{
    doAjaxRPC('getCurrentEventOptions', {}, createObjectCallback(this, this.setCurrentEventOptions), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.getUserPreferences = function()
{
    doAjaxRPC('getHandicapPrefsForForm', {}, createObjectCallback(this, this.setUserPreferences), createObjectCallback(this, this.failure));	
}


LSPN.MainPage.prototype.getPointsOptions = function()
{
	return;
	this.pointsOptions.game = this.cp.get("game") === undefined ? this.leaderboardOptions.game : this.cp.get("game");
	this.pointsOptions.difficulty = this.cp.get("difficulty") === undefined ? this.leaderboardOptions.difficulty : this.cp.get("difficulty");
	this.pointsOptions.swing = this.cp.get("swing") === undefined ? this.leaderboardOptions.swing : this.cp.get("swing");
}

LSPN.MainPage.prototype.getCourses = function(event_id)
{
    doAjaxRPC('getCourses', {event_id: event_id}, createObjectCallback(this, this.doCoursesWin), createObjectCallback(this, this.failure));	
}


LSPN.MainPage.prototype.setDefaultCurrentEventOptions = function(respObj)
{
	var prefs = 0;
	for (n in LSPN.enums.prefs)
	{
		prefs |= LSPN.enums.prefs[n];
	}
	this.setCurrentEventOptions(prefs, true);
}

LSPN.MainPage.prototype.setCurrentEventOptions = function(respObj, bDoNotOpenWin)
{
	if (respObj.rows)
		this.currentEventOptions = respObj.rows;
	if (!bDoNotOpenWin)
		this.doCurrentEventOptionsWin();
}

LSPN.MainPage.prototype.setUserPreferences = function(respObj)
{
	if (respObj.rows && respObj.rows[0].game != undefined)
	{
		this.userPrefs = respObj.rows[0];
		this.accountForm.form.findField("pref_game").setValue(this.userPrefs.game);
		this.accountForm.form.findField("pref_difficulty").setValue(this.userPrefs.skill);
		this.accountForm.form.findField("pref_swing").setValue(this.userPrefs.swing_type);
		//this.accountForm.form.findField("pref_matchplay").setValue(this.userPrefs.matchplay);
	}
}

LSPN.MainPage.prototype.createLeague = function()
{
   Ext.QuickTips.init();

    this.league_form = new Ext.FormPanel({
        labelWidth: 150, // label settings here cascade unless overridden
        url:'save-form.php',
        bodyStyle: 'padding: 10px; border: 0px; background: #f0f0f0;',
        width: 'auto',
        defaults: {width: 'auto', height: 'auto'},
        defaultType: 'textfield',

        items: [{
                fieldLabel: 'League Name',
                id: 'group_name',
                name: 'group_name',
                allowBlank:false,
                maxLength: 60
            },{
                fieldLabel: 'League Description',
                id: 'group_desc',
                name: 'group_desc',
                maxLength: 255
            },{
                fieldLabel: 'League URL',
                id: 'group_url',
                name: 'group_url',
                maxLength: 255
            }, new Ext.form.ComboBox({
            	fieldLabel: "Difficulty",
            	id :'group_difficulty',
            	name: 'group_difficulty',
		        store: LSPN.stores.difficulty_league,
		        displayField: "name",
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true
		    }), new Ext.form.ComboBox({
            	fieldLabel: "Swing Type",
            	id :'group_swing',
            	name: 'group_swing',
		        store: LSPN.stores.swing,
		        displayField: "name",
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true
		    }), new Ext.form.ComboBox({
            	fieldLabel: "Game",
            	id :'group_game',
            	name: 'group_game',
		        store: LSPN.stores.league_games,
		        displayField: "name",
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true
		    })
        ]
    });
    
    var submit = this.league_form.addButton({
        text: 'Submit',
        handler: this.saveNewLeague,
        scope: this
    });
    
    this.league_form.render('create-league-form');    
}

LSPN.MainPage.prototype.saveNewLeague = function()
{
	var params = {
		group_name : this.league_form.findById('group_name').getValue(),
		group_desc : this.league_form.findById('group_desc').getValue(),
		group_url : this.league_form.findById('group_url').getValue(),
		group_difficulty : getEnumValue(LSPN.enums.difficulty_league, this.league_form.findById('group_difficulty').getValue()),
		group_swing : getEnumValue(LSPN.enums.swing, this.league_form.findById('group_swing').getValue()),
		group_game : getEnumValue(LSPN.enums.league_games, this.league_form.findById('group_game').getValue())
	};
	doAjaxRPC('saveNewLeague', params, createObjectCallback(this, this.leagueComplete), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.leagueComplete = function(respObj)
{
	var league_id = respObj.rows.league_id;
	window.location.href = "/league_admin/?league_id="+league_id;
}

LSPN.MainPage.prototype.showFindMember = function()
{
	var simple = new Ext.FormPanel({
		applyTo: 'find-player-form',
        labelWidth: 0,
        height: 'auto',
        frame:false,
        region: 'center',
        bodyStyle: 'border: 0px; background: #f0f0f0;',
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 35px;',       	
                items:[{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "",
	                labelSeparator: "",
	                id: 'find-member',
	                width: 275,
	                store: new Ext.data.Store({
		        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getMemberList'})),
		        	    method: "POST",
			        	reader: new Ext.data.JsonReader({
			            root: 'rows',
			            id: 'user_id',
			            autoLoad: true
		               }, ['user_id', 'username'] )
		            }),
	                minChars: 2,
	                displayField: 'username',
	                valueField: 'user_id',
	                typeAhead: true,
	                mode: 'remote', 
	                selectOnFocus: true,
	                triggerAction: 'all'
	            }]
        	},
			{
                columnWidth:.2,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 35px;',       	
                items:[{
			 		xtype: 'button',
			        text: 'Go',
			        handler: function(){
			        		window.location.href = "profile.php?user_id="+simple.findById('find-member').value;
			            }
		        }]
       		},
			{
                columnWidth:.3,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 35px;',       	
                items:[{
		        	'html':'<a href="profile.php" style="text-decoration: underline;">Show my tour profile</a>',
		        	'bodyStyle': 'border: 0px; background: #f0f0f0; width: 150px;'
		        }]
       		}]
		}]
	});
}


LSPN.MainPage.prototype.updateCourses = function(combo, newValue, oldValue)
{
	if ((oldValue == 'l2k3') && (newValue == 'l2k3'))
		return;
		
	if (oldValue == 'l2k1' && newValue == 'l2k1')
		return;
		
	var use_store = LSPN.stores.courses;
	if (newValue == 'l2k1')
	{
		use_store = LSPN.stores.courses2k1;
	}
	
    var round_tabs = Ext.getCmp('round-tabs');
    var num_rounds = round_tabs.getTabCount();
    var rounds = {};
    j=0;
    for (var i=0;i<=last_tab;i++)
    {
        var round_tab = Ext.getCmp('round-tab-'+i);
        if (round_tab)
        {
			var round = j+1;
            var rprop = round_tab.items.items[0];
            rprop.customEditors['Course'] = makePropertyComboEditor(use_store, 'name', 'course_id', mainPage, mainPage.changeCourse);
        }
    }
}

LSPN.MainPage.prototype.showArcadeForm = function()
{
	Ext.QuickTips.init();
	
	var gamecombo = new Ext.form.ComboBox({
		                style: 'text-align: left;',
		                fieldLabel: "Game",
		                id: 'arcade-game',
		                labelSeparator: ":",
		                store: LSPN.stores.games,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Game',
		                allowBlank: false
		            });
		            
    gamecombo.on("change", this.updateCourses, this);

	
	this.arcadeForm = new Ext.FormPanel({
		applyTo: 'arcade-form',
        labelWidth: 110,
        height: 190,
        width: 630,
        frame:false,
        region: 'center',
        bodyStyle: 'border: 0px; background: #f0f0f0;',
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[
                	{
                		xtype: 'textfield',
		                fieldLabel: 'Title',
		                id: 'arcade-title',
		                width: 180,
		                allowBlank: false,
		                maxLength: 30
                	},
                	gamecombo,
                	{
                		xtype: 'datefield',
                		id: 'arcade-start-date',
		                style: 'text-align: left;',
		                fieldLabel: "Start Date",
		                labelSeparator: ":",
		                emptyText: 'Select a Date',
		                allowBlank: false,
		                width: 180
		            },
                	{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Duration",
		                id: 'arcade-duration',
		                labelSeparator: ":",
		                store: LSPN.stores.duration,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'How many days?',
		                allowBlank: false
		            },
                	{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'arcade-max-players',
		                fieldLabel: "# Players Allowed",
		                labelSeparator: ":",
		                store: LSPN.stores.max_players,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'How many players?',
		                allowBlank: false
		            },		            
                	{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'arcade-skill',
		                fieldLabel: "Skill Level",
		                labelSeparator: ":",
		                store: LSPN.stores.difficulty,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Level',
		                allowBlank: false
		            }	            
		            
		            
		            
	            ]
        	},
			{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Swing Type",
		                id: 'arcade-swing-type',
		                labelSeparator: ":",
		                store: LSPN.stores.full_swing_types,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Swing Type',
		                allowBlank: false
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Rules",
		                id: 'arcade-rules',
		                labelSeparator: ":",
		                store: LSPN.stores.current_rules,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select the Rules',
		                allowBlank: false
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Allow Putt Assist",
		                id: 'arcade-putt-assist',
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select One',
		                allowBlank: false
		            },{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Chip on Green?",
		                id: 'arcade-chip-green',
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select One',
		                allowBlank: false
		            },		            
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Requalify",
		                id: 'arcade-requal',
		                labelSeparator: ":",
		                store: LSPN.stores.requals,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Allowed to Requalify?',
		                allowBlank: false,
		                tooltip:'The number of times a person is allowed to reset their round should they become disqualified for some reason'
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'arcade-requal-penalty',
		                fieldLabel: "Requalify Penalty",
		                labelSeparator: ":",
		                store: LSPN.stores.requal_penalty,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select the Penalty',
		                allowBlank: false,
		                tooltip:'Number of strokes to be added on each requalify'
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'arcade-requal-multiplier',
		                fieldLabel: "Penalty Multiplier",
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Use a Penalty Multiplier?',
		                allowBlank: false,
		                tooltip:'The number of times requalified * the penalty = total penalty strokes'
		            }		            
	            ]
       		}]
		}]
	});
	
    var round_tabs = new Ext.TabPanel({
        title: 'Rounds',
        enableTabScroll:true,
        width: 630,
        height: 535,
        defaults: {autoScroll:true},
        id: 'round-tabs',
        applyTo: 'round-tabs',
        tbar:[{
            text:'New Round',
            tooltip:'Creates a new round',
            handler: createObjectCallback(this, this.createNewRound)
        },'-',{
            text:'Remove Selected Round',
            tooltip:'Removes the currently selected round',
            handler: createObjectCallback(this, this.deleteRound)
        }]
    });
	
	this.createNewRound();
	
	var button = new Ext.Button({
		applyTo: 'save-button',
		iconCls: 'save',
	   	text: 'Save Arcade Event',
	   	handler: this.checkArcadeEvent,
	   	scope: this
	});	
}

LSPN.MainPage.prototype.showChallengeCreateForm = function()
{
	Ext.QuickTips.init();
	
	var gamecombo = new Ext.form.ComboBox({
		                style: 'text-align: left;',
		                fieldLabel: "Game",
		                id: 'challenge-game',
		                labelSeparator: ":",
		                store: LSPN.stores.games,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Game',
		                allowBlank: false
		            });
		            
    gamecombo.on("change", this.updateCourses, this);

	
	this.challengeEventForm = new Ext.FormPanel({
		applyTo: 'challenge-create-form',
        labelWidth: 110,
        height: 190,
        width: 630,
        frame:false,
        region: 'center',
        bodyStyle: 'border: 0px; background: #f0f0f0;',
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[
                	{
                		xtype: 'textfield',
		                fieldLabel: 'Title',
		                id: 'challenge-title',
		                width: 180,
		                allowBlank: false,
		                maxLength: 30
                	},
                	gamecombo,
                	{
                		xtype: 'datefield',
                		id: 'challenge-start-date',
		                style: 'text-align: left;',
		                fieldLabel: "Start Date",
		                labelSeparator: ":",
		                emptyText: 'Select a Date',
		                allowBlank: false,
		                width: 180
		            },
                	{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Duration",
		                id: 'challenge-duration',
		                labelSeparator: ":",
		                store: LSPN.stores.duration,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'How many days?',
		                allowBlank: false
		            },{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Head-to-head?",
		                id: 'challenge-h2h',
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select One',
		                allowBlank: false
		            },		            
                	{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'challenge-skill',
		                fieldLabel: "Skill Level",
		                labelSeparator: ":",
		                store: LSPN.stores.difficulty,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Level',
		                allowBlank: false
		            }	            
		            
		            
		            
	            ]
        	},
			{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Swing Type",
		                id: 'challenge-swing-type',
		                labelSeparator: ":",
		                store: LSPN.stores.full_swing_types,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select a Swing Type',
		                allowBlank: false
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Rules",
		                id: 'challenge-rules',
		                labelSeparator: ":",
		                store: LSPN.stores.challenge_rules,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select the Rules',
		                allowBlank: false
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Allow Putt Assist",
		                id: 'challenge-putt-assist',
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select One',
		                allowBlank: false
		            },{
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Chip on Green?",
		                id: 'challenge-chip-green',
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select One',
		                allowBlank: false
		            },		            
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                fieldLabel: "Requalify",
		                id: 'challenge-requal',
		                labelSeparator: ":",
		                store: LSPN.stores.requals,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Allowed to Requalify?',
		                allowBlank: false,
		                tooltip:'The number of times a person is allowed to reset their round should they become disqualified for some reason'
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'challenge-requal-penalty',
		                fieldLabel: "Requalify Penalty",
		                labelSeparator: ":",
		                store: LSPN.stores.requal_penalty,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Select the Penalty',
		                allowBlank: false,
		                tooltip:'Number of strokes to be added on each requalify'
		            },
		            {
                		xtype: 'combo',
		                style: 'text-align: left;',
		                id: 'challenge-requal-multiplier',
		                fieldLabel: "Penalty Multiplier",
		                labelSeparator: ":",
		                store: LSPN.stores.yesno,
		                width: 180,
		                displayField: 'name',
		                valueField: 'num',
		                typeAhead: true,
		                mode: 'local', 
		                selectOnFocus: true,
		                triggerAction: 'all',
		                emptyText: 'Use a Penalty Multiplier?',
		                allowBlank: false,
		                tooltip:'The number of times requalified * the penalty = total penalty strokes'
		            }		            
	            ]
       		}]
		}]
	});
	
    var round_tabs = new Ext.TabPanel({
        title: 'Rounds',
        enableTabScroll:true,
        width: 630,
        height: 535,
        defaults: {autoScroll:true},
        id: 'round-tabs',
        applyTo: 'round-tabs'
    });
	
	this.createNewRound();
	
	var button = new Ext.Button({
		applyTo: 'save-button',
		iconCls: 'save',
	   	text: 'Make Challenge',
	   	handler: this.checkChallengeEvent,
	   	scope: this
	});	
}


LSPN.MainPage.prototype.upgrade = function(new_level)
{
	window.location.href="membership.php?action="+new_level;
}

LSPN.MainPage.prototype.tryLevel = function(new_level)
{
	window.location.href="membership.php?try=1&action="+new_level;
}

LSPN.MainPage.prototype.tryCasualPlayer = function()
{
	this.tryLevel("Casual Player");
}

LSPN.MainPage.prototype.tryTourPlayer = function()
{
	this.tryLevel("Tour Player");
}

LSPN.MainPage.prototype.tryTourDirector = function()
{
	this.tryLevel("Tour Director");
}

LSPN.MainPage.prototype.unsubscribe = function()
{
	if (unsubscribe_old)
		window.location.href="membership.php?action=unsubscribe_old";
	else
		window.location.href="membership.php?action=unsubscribe";
}

LSPN.MainPage.prototype.switch_to_yearly = function()
{
	window.location.href="membership.php?action=switch_to_yearly";
}

LSPN.MainPage.prototype.showMyAccountForm = function()
{
	cost = "";
	
	if (my_type < 3)
	{
		if (level == 'Tour Player')
			cost = "";
			
		if (level == "Tour Director")
			cost = "";
	}

	var options = [{ 
	                width: 500,
	                html : '<div class="x-form-item"><label style="width: 300px; " class="x-form-item-label">Membership:</label><div class="x-form-element" style="padding-left: 305px; ">'+level + ' ' + cost+'</div></div>',
	                bodyStyle: 'font-size: 80%; border: 0px;'
	            }];
	            
	if (level != 'Casual Player')                
	{	     
		if (!use_grace_period)
		{       
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label style="width: 300px; " class="x-form-item-label">Last Payment Date:</label><div class="x-form-element" style="padding-left: 305px; ">'+payment_date+'</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		}
		
	    if (my_type == 3 || my_type == 2)
	    {
	    	if (!use_grace_period)
	    	{
				options[options.length] = { 
			                width: 500,
			                html : '<div class="x-form-item"><label style="width: 300px;" class="x-form-item-label">Next Payment Due:</label><div class="x-form-element" style="padding-left: 305px; ">'+payment_due+'</div></div>',
			                bodyStyle: 'font-size: 80%; border: 0px;'
			            };
	    	}
	    	else
	    	{
				options[options.length] = { 
			                width: 500,
			                html : '<div class="x-form-item"><label style="width: 300px;" class="x-form-item-label">Grace Period Ends:</label><div class="x-form-element" style="padding-left: 305px; ">'+payment_due+'</div></div>',
			                bodyStyle: 'font-size: 80%; border: 0px;'
			            };
	    	}
	    }	            
		if (my_type == 1)
		{
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Annivesary:</label><div class="x-form-element" style="padding-left: 305px; ">'+monthly_ann+'</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
			
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Payment Type:</label><div class="x-form-element" style="padding-left: 305px; ">PayPal Subscription</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            		
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Recurring Payment:</label><div class="x-form-element" style="padding-left: 305px; ">'+(recurring == 1 ? "Yes" : "No")+'</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		}
		
		if (my_type == 4)
		{
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Payment Type:</label><div class="x-form-element" style="padding-left: 305px; ">PayPal One-Time Payment</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            		
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Recurring Payment:</label><div class="x-form-element" style="padding-left: 305px; ">No</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label style="width: 300px;" class="x-form-item-label">Next Payment Due:</label><div class="x-form-element" style="padding-left: 305px; ">'+payment_due+'</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            
		}		
		
		if (my_type == 2)
		{
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Payment Type:</label><div class="x-form-element" style="padding-left: 305px; ">Check or Money Order</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
			};
			/*
			if (can_renew)
			{
				options[options.length] = { 
			                width: 500,
			                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Renew Early for 1 year:</label><div class="x-form-element" style="padding-left: 305px; ">Send $19.99 before next payment date</div></div>',
			                bodyStyle: 'font-size: 80%; border: 0px;'
			            };
			}
			
			if (can_regular_renew)
			{
				options[options.length] = { 
			                width: 500,
			                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Renew for 1 year:</label><div class="x-form-element" style="padding-left: 305px; ">$29.99</div></div>',
			                bodyStyle: 'font-size: 80%; border: 0px;'
			            };
			}	*/		
			
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Payment Address:</label><div class="x-form-element" style="padding-left: 305px; ">Color Shift, Inc.<br/>Attn: Dept '+my_user_id+'<br/>7322 S. Rainbow Blvd #128<br/>Las Vegas, NV<br/>89139<br/></div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            
		}

		if (my_type == 3)
		{
			options[options.length] = { 
		                width: 500,
		                html : '<div class="x-form-item"><label for="autopayment" style="width: 300px;" class="x-form-item-label">Payment Type:</label><div class="x-form-element" style="padding-left: 305px; ">ACN Service</div></div>',
		                bodyStyle: 'font-size: 80%; border: 0px;'
		            };
		            
		    if (use_grace_period)
		    {
				options[options.length] = { 
			                width: 500,
			                html : '<div class="x-form-item"><label style="width: 500px;" class="x-form-item-label">Please contact <a href="mailto:helpme@lspn.net?Subject=ACN Service">Mark Hulka</a> as soon as you know which service you like or once you\'ve signed up online.</label></div>',
			                bodyStyle: 'font-size: 80%; border: 0px;'
			            };
		    	
		    }
		}
		
	}

	if (!use_grace_period)
	{       
		if (level == 'Casual Player')                
		{
		    options[options.length] = {
		            	html: '<br/><u>Options</u>',
		            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
		            };
		            		
		    options[options.length] = new Ext.Button({
							iconCls: 'upgrade',
						   	text: 'Upgrade to Tour Player',
						   	handler: function(){
						   		mainPage.upgrade("Tour+Player");
						   	},
						   	scope: this
						});
		    options[options.length] = {
		            	html: '<a href="javascript:mainPage.showTourPlayerDetails()">&raquo;More information</a>',
		            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
		            };
						
		    options[options.length] = new Ext.Button({
							iconCls: 'upgrade',
						   	text: 'Upgrade to Tour Director',
						   	handler: function(){
						   		mainPage.upgrade("Tour+Director");
						   	},
						   	scope: this
						});
						
		    options[options.length] = {
		            	html: '<a href="javascript:mainPage.showTourDirectorDetails()">&raquo;More information</a>',
		            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
		            };
						
		}
		
		if (my_type == 4)
		{
			    if (can_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch_to_yearly',
								   	text: 'Renew Your Yearly Membership for $19.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
					            	html: '<br/>',
					            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
					            };								
								
			    }										            
			    
			    if (can_regular_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch',
								   	text: 'Renew Your Yearly Membership for $29.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
				            	html: '<br/>',
				            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
				            };								
			    }			
		}
		
		if (my_type == 4 && unsubscribe_old == 1)
		{
		    options[options.length] = {
		            	html: 'This unsubscribe button is here for your convenience. You may have already cancelled your old monthly subscription but the button will remain until PayPal notifies us of the end of term.',
		            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
		            };			
			    options[options.length] = new Ext.Button({
								iconCls: 'delete',
							   	text: 'Unsubscribe from Monthly Membership Dues',
							   	handler: this.unsubscribe,
							   	scope: this
							});
			
		}
		
		if (my_type != 4)
		{
			if (level == 'Tour Player')                
			{
			    options[options.length] = {
			            	html: '<br/><u>Options</u>',
			            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
			            };
			            	
			    if (can_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch_to_yearly',
								   	text: 'Switch to a Yearly Membership for $19.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
					            	html: '<br/>',
					            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
					            };								
								
			    }										            
			    
			    if (can_regular_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch',
								   	text: 'Switch to a Yearly Membership for $29.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
				            	html: '<br/>',
				            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
				            };								
			    }										            
			    
			    
			    options[options.length] = new Ext.Button({
								iconCls: 'downgrade',
							   	text: 'Downgrade to Casual Player',
							   	handler: this.unsubscribe,
							   	scope: this
							});
			    options[options.length] = {
			            	html: '<a href="javascript:mainPage.showCasualPlayerDetails()">&raquo;More information (Free)</a>',
			            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
			            };
							
			    options[options.length] = new Ext.Button({
								iconCls: 'upgrade',
							   	text: 'Upgrade to Tour Director',
							   	handler: function(){
							   		mainPage.upgrade("Tour+Director");
							   	},
							   	scope: this
							});
							
			    options[options.length] = {
			            	html: '<a href="javascript:mainPage.showTourDirectorDetails()">&raquo;More information ($4.99/mo)</a>',
			            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
			            };
			}
		
			if (level == 'Tour Director')                
			{
			    options[options.length] = {
			            	html: '<br/><u>Options</u>',
			            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
			            };
			            
			            					    if (can_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch_to_yearly',
								   	text: 'Switch to a Yearly Membership for $19.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
					            	html: '<br/>',
					            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
					            };								
								
			    }										            
			    
			    if (can_regular_renew)
			    {	
				    options[options.length] = new Ext.Button({
									iconCls: 'switch',
								   	text: 'Switch to a Yearly Membership for $29.99',
								   	handler: this.switch_to_yearly,
								   	scope: this
								});
				    options[options.length] = {
				            	html: '<br/>',
				            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
				            };								
			    }	
			    
			    options[options.length] = new Ext.Button({
								iconCls: 'downgrade',
							   	text: 'Downgrade to Casual Player',
							   	handler: this.unsubscribe,
							   	scope: this,
							   	html: 'hello'
							});
			    options[options.length] = {
			            	html: '<a href="javascript:mainPage.showCasualPlayerDetails()">&raquo;More information</a>',
			            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
			            };
							
				if (my_type != 3)
				{		            
				    options[options.length] = new Ext.Button({
									iconCls: 'downgrade',
								   	text: 'Downgrade to Tour Player',
								   	handler: function(){
								   		mainPage.upgrade("Tour+Player");
								   	},
								   	scope: this
								});
								
				    options[options.length] = {
				            	html: '<a href="javascript:mainPage.showTourPlayerDetails()">&raquo;More information</a>',
				            	bodyStyle: 'font-size: 80%; border: 0px; padding: 5 0 15 0;'
				            };
				}
			}
		}
	}	
	
	Ext.QuickTips.init();
	this.accountForm = new Ext.FormPanel({
		applyTo: 'my-account-form',
        labelWidth: 300,
        height: 800,
        frame:false,
        region: 'center',
        bodyStyle: 'border: 0px;',
		items: [{
            xtype:'fieldset',
            title: 'User Preferences',
            autoHeight:true,
            defaults: {width: 210},
            items :[{ 
	                width: 500,
	                html : '<div class="x-form-item"><label style="width: 400px; " class="x-form-item-label">These settings are used for combined handicap and matchplay</label></div>',
	                bodyStyle: 'font-size: 80%; border: 0px;'
	            }, new Ext.form.ComboBox({
            	fieldLabel: "Game",
            	id :'pref_game',
            	name: 'pref_game',
		        store: LSPN.stores.games,
		        displayField: "name",
		        valueField: "num",
		        typeAhead: false,
		        mode: 'local',
		        editable: false,
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true})
		    , new Ext.form.ComboBox({
            	fieldLabel: "Difficulty",
            	id :'pref_difficulty',
            	name: 'pref_difficulty',
		        store: LSPN.stores.difficulty,
		        displayField: "name",
		        valueField: "num",
		        typeAhead: false,
		        editable: false,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true
		    }), new Ext.form.ComboBox({
            	fieldLabel: "Swing Type",
            	id :'pref_swing',
            	name: 'pref_swing',
		        store: LSPN.stores.swing_no_any,
		        displayField: "name",
		        valueField: "num",
		        editable: false,
		        typeAhead: false,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Select one...',
		        selectOnFocus:true
		    }),
                new Ext.Button({
					iconCls: 'save',
				   	text: 'Save Preferences',
				   	handler: this.savePreferences,
				   	scope: this
				})
            ]
        },{
            xtype:'fieldset',
            title: 'User Information',
            autoHeight:true,
            defaults: {width: 210},
            items :[{
            		xtype: 'textfield',
                    fieldLabel: 'Username:',
                    name: 'new_username',
                    id: 'new_username',
                    value: my_username,
                    minLength: 5,
                    disabled: true,
                    maxLength: 20,
                    allowBlank:false,
                    labelSeparator: "",
                    vtype: 'alphanum'
                },{
                	xtype: 'textfield',
                    fieldLabel: 'E-mail address:<br/><span style="color: #515151;">You only need to specify this if you are changing your e-mail address.</span>',
                    name: 'email',
                    id: 'email',
                    vtype:'email',
                    labelSeparator: ""
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Confirm e-mail address:',
                    name: 'email_confirm',
                    id: 'email_confirm',
                    vtype:'email',
                    labelSeparator: ""
                },{
                	xtype: 'textfield',
                    fieldLabel: 'New password:<br/><span style="color: #515151;">Must be between 6 and 20 characters.</span>',
                    name: 'new_password',
                    id: 'new_password',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password'                    
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Confirm new password:<br/><span style="color: #515151;">You only need to confirm your password if you changed it above.</span>',
                    name: 'password_confirm',
                    id: 'password_confirm',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password'                    
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Current Password:<br/><span style="color: #515151;">You must confirm your current password if you wish to change it, alter your e-mail address.</span>',
                    name: 'password',
                    id: 'password',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password',
                    allowBlank: false                 
                },
                new Ext.Button({
					iconCls: 'save',
				   	text: 'Save Account Details',
				   	handler: this.saveAccountDetails,
				   	scope: this
				})
            ]
        },{
            xtype:'fieldset',
            title: 'Membership Information',
            autoHeight:true,
            defaults: {width: 210},
            items :options
        }]
	});
	
}

LSPN.MainPage.prototype.showTestAccountForm = function()
{
	cost = "(Free for Testing)";
	
	var options = [{ 
	                width: 500,
	                html : '<div class="x-form-item"><label style="width: 300px; " class="x-form-item-label">Membership:</label><div class="x-form-element" style="padding-left: 305px; ">'+level + ' ' + cost+'</div></div>',
	                bodyStyle: 'font-size: 80%; border: 0px;'
	            },new Ext.Button({
					iconCls: '',
				   	text: 'Try Casual Player',
				   	handler: this.tryCasualPlayer,
				   	scope: this
				}),
				new Ext.Button({
					iconCls: '',
				   	text: 'Try Tour Player',
				   	handler: this.tryTourPlayer,
				   	scope: this
				}),
				new Ext.Button({
					iconCls: '',
				   	text: 'Try Tour Director',
				   	handler: this.tryTourDirector,
				   	scope: this
				})];
	            	
	Ext.QuickTips.init();
	this.accountForm = new Ext.FormPanel({
		applyTo: 'my-account-form',
        labelWidth: 300,
        height: 800,
        frame:false,
        region: 'center',
        bodyStyle: 'border: 0px;',
		items: [{
            xtype:'fieldset',
            title: 'User Information',
            autoHeight:true,
            defaults: {width: 210},
            items :[{
            		xtype: 'textfield',
                    fieldLabel: 'Username:',
                    name: 'new_username',
                    id: 'new_username',
                    value: my_username,
                    minLength: 5,
                    disabled: true,
                    maxLength: 20,
                    allowBlank:false,
                    labelSeparator: "",
                    vtype: 'alphanum'
                },{
                	xtype: 'textfield',
                    fieldLabel: 'E-mail address:<br/><span style="color: #515151;">You only need to specify this if you are changing your e-mail address.</span>',
                    name: 'email',
                    id: 'email',
                    vtype:'email',
                    labelSeparator: ""
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Confirm e-mail address:',
                    name: 'email_confirm',
                    id: 'email_confirm',
                    vtype:'email',
                    labelSeparator: ""
                },{
                	xtype: 'textfield',
                    fieldLabel: 'New password:<br/><span style="color: #515151;">Must be between 6 and 20 characters.</span>',
                    name: 'new_password',
                    id: 'new_password',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password'                    
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Confirm new password:<br/><span style="color: #515151;">You only need to confirm your password if you changed it above.</span>',
                    name: 'password_confirm',
                    id: 'password_confirm',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password'                    
                },{
                	xtype: 'textfield',
                    fieldLabel: 'Current Password:<br/><span style="color: #515151;">You must confirm your current password if you wish to change it, alter your e-mail address.</span>',
                    name: 'password',
                    id: 'password',
                    labelSeparator: "",
                    minLength: 6,
                    maxLength: 20,
                    inputType: 'password',
                    allowBlank: false                 
                },
                new Ext.Button({
					iconCls: 'save',
				   	text: 'Save Account Details',
				   	handler: this.saveAccountDetails,
				   	scope: this
				})
            ]
        },{
            xtype:'fieldset',
            title: 'Membership Information',
            autoHeight:true,
            defaults: {width: 210},
            items :options
        }]
	});
	
}

LSPN.MainPage.prototype.showTourPlayerDetails = function()
{
	this.showDetails('Tour Player', 'tourplayer.php');
}

LSPN.MainPage.prototype.showCasualPlayerDetails = function()
{
	this.showDetails('Casual Player', 'casualplayer.php');
}

LSPN.MainPage.prototype.showTourDirectorDetails = function()
{
	this.showDetails('Tour Director', 'tourdirector.php');
}

LSPN.MainPage.prototype.showDetails = function(title, url)
{
    win = new Ext.Window({
        layout:'fit',
        width:500,
        title: title+' Membership',
        height:300,
        closeAction:'hide',
        plain: true,
        modal: true,
        items:[new Ext.Panel({height: 200,
        	autoScroll: true,
        	header: false,
        	autoLoad: ROOT_URL+url
        }),{
            text: 'Close',
            handler: function(){
                win.hide();
            }
        }]
    });
    
    win.show();
}


LSPN.MainPage.prototype.saveAccountDetails = function()
{
	if (!this.accountForm.form.isValid())
	{
		Ext.Msg.alert('Errors', 'Please correct items highlighted in red.');    
		return;
	}
	
	var new_email = this.accountForm.findById('email').getValue();
	var email_confirm = this.accountForm.findById('email_confirm').getValue();
	
	this.changedEmail = false;
	bchanges = false;
	if (new_email.length > 0)
	{
		if (new_email != email_confirm)
		{
			Ext.Msg.alert('Errors', 'The email fields do not match');    
			return;
		}
		else
		{
			this.changedEmail = true;
			bchanges = true;
		}
	}

	var new_password = this.accountForm.findById('new_password').getValue();
	var password_confirm = this.accountForm.findById('password_confirm').getValue();
	if (new_password.length > 0)
	{
		if (new_password != password_confirm)
		{
			Ext.Msg.alert('Errors', 'The password fields do not match');    
			return;
		}
		bchanges = true;
	}
	
	var password = this.accountForm.findById('password').getValue();
	var new_username = this.accountForm.findById('new_username').getValue();
	
	if (new_username != my_username)
		bchanges = true;
	
	if (bchanges)
	{
	    var real_params = {
	        new_username: new_username,
	        password: password,
	        new_password: new_password,
	        password_confirm: password_confirm,
	        email: new_email,
	        email_confirm: email_confirm
	    };
	        
	    doAjaxRPC('saveMyAccount', real_params, createObjectCallback(this, this.saveAccountComplete), createObjectCallback(this, this.saveAccountFailure));
	}
	else
	{
		Ext.Msg.alert('Nothing to Save', 'There\'s nothing to save.');    
	}
}

LSPN.MainPage.prototype.savePreferences = function()
{
	var game = this.accountForm.findById('pref_game').getValue();
	var skill = this.accountForm.findById('pref_difficulty').getValue();
	var swing = this.accountForm.findById('pref_swing').getValue();
	
	if (game == '' || (skill == '' && skill != 0) || swing == '')
	{
		Ext.Msg.alert('Errors', 'You must select a preference for game, swing, and difficulty');    
		return;
	}
	
    var real_params = {
        game: game,
        skill: skill,
        swing: swing
    };
        
    doAjaxRPC('setHandicapPrefs', real_params, createObjectCallback(this, this.saveAccountComplete), createObjectCallback(this, this.saveAccountFailure));
}


LSPN.MainPage.prototype.saveAccountComplete = function(respObj)
{
	if (this.changedEmail)
	{
	    Ext.Msg.show({
	       title:'Save Complete',
	       msg: 'The changes were saved successfully, however, because you changed your email address your account has been deactivated until you reactivate your account. An email has been sent with instructions. If you have difficulty please contact the Tour Administrator in the Help Section.',
	       buttons: Ext.Msg.OK,
	       fn: createObjectCallback(this, this.logout),
	       icon: Ext.MessageBox.INFO
	    });
	}
	else
	{
		Ext.Msg.alert('Save Complete', 'The changes were saved successfully');    
	}
}

LSPN.MainPage.prototype.logout = function()
{
	window.location.href = "community/ucp.php?mode=logout&sid="+sid;
}


LSPN.MainPage.prototype.saveAccountFailure = function(errors)
{
    Ext.Msg.alert('Message', errors);    
}

LSPN.MainPage.prototype.createNewRound = function()
{
    var round_tabs = Ext.getCmp('round-tabs');
    var num_rounds = round_tabs.getTabCount();
    var round = num_rounds + 1;
	if (round > 4)
	{
		Ext.Msg.alert('Maxmimum Reached', 'Currently there is a maximum of 4 rounds allowed in an event.');
		return;
	}
    var source = {
        Mulligans:0,
        'Gimme Range': 12,
        'Green Speed':1,
        'Green Hardness':1,        
        Holes:0,
        Tees:0,
        'Grid Allowed':true,
        'Caddie Allowed':true,
        'Pin':3,        
        'Pin Positions (18 Holes, Positions from 0 - 17)':"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
        'Tees - if Custom (18 Holes - B,M,F,J,L)':"b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b",
        'Course ID':"",
        'Course Key':"",
        'Course':'',
        Wind:1,
        Round:round,
        Crowds: 0,
        "Show Tour Objects": false,
        "Joker Front 9 (Spanish Stableford)": 1,
        "Joker Back 9 (Spanish Stableford)": 10
    };
    
    var rprop = mainPage.createRoundPropertyGrid(source);
    round_tabs.add({
        id: 'round-tab-'+last_tab,
        title: 'Round ' + round,
        items: [rprop]
    }).show(); 
    last_tab++;
    round_tabs.doLayout(); 
}

LSPN.MainPage.prototype.createRoundPropertyGrid = function(source)
{
    var rprop = new Ext.grid.PropertyGrid({
        title: 'Round Conditions',
        split: true,
        frame:true,
        width: 630
    });
    
    Ext.apply(rprop.colModel.config[0], {width: 237, header: 'Name'});
    Ext.apply(rprop.colModel.config[1], {width: 237, header: 'Value'});
    
    source['Mulligans'] = getEnumText(LSPN.enums.mulligans, source['Mulligans']);
    source['Wind'] = getEnumText(LSPN.enums.wind, source['Wind']);
    source['Green Speed'] = getEnumText(LSPN.enums.speed, source['Green Speed']);
    source['Green Hardness'] = getEnumText(LSPN.enums.hardness, source['Green Hardness']);
    source['Holes'] = getEnumText(LSPN.enums.holes, source['Holes']);
    source['Crowds'] = getEnumText(LSPN.enums.crowds, source['Crowds']);
    source['Pin'] = getEnumText(LSPN.enums.pins, source['Pin']);
    source['Tees'] = getEnumText(LSPN.enums.tees, source['Tees']);
    source['Gimme Range'] = getEnumText(LSPN.enums.gimme_range, source['Gimme Range']);
    
    rprop.setSource(source);

   rprop.customEditors = {
        'Course' : makePropertyComboEditor(LSPN.stores.courses, 'name', 'course_id', mainPage, mainPage.changeCourse),   
        'Green Speed' : makePropertyComboEditor(LSPN.stores.speed, 'name', 'num'),
        'Green Hardness' : makePropertyComboEditor(LSPN.stores.hardness, 'name', 'num'),
        'Fairway Hardness' : makePropertyComboEditor(LSPN.stores.hardness, 'name', 'num'),
        'Wind' : makePropertyComboEditor(LSPN.stores.wind, 'name', 'num'),
        'Mulligans' : makePropertyComboEditor(LSPN.stores.mulligans, 'name', 'num'),
        'Holes' : makePropertyComboEditor(LSPN.stores.holes, 'name', 'num'),
        'Crowds' : makePropertyComboEditor(LSPN.stores.crowds, 'name', 'num'),
        'Tees' : makePropertyComboEditor(LSPN.stores.tees, 'name', 'num'),
        'Gimme Range' : makePropertyComboEditor(LSPN.stores.gimme_range, 'name', 'num'),
        'Pin' : makePropertyComboEditor(LSPN.stores.pins, 'name', 'num', mainPage, mainPage.setPins)
    };  

	rprop.on("beforeedit",this.beforeRoundEdit, this);
    rprop.on("validateedit",this.validateRoundEdit, this);
    return rprop;
}

function makePropertyComboEditor(store, display, value, onchangeobj, onchangefunc, alt_id)
{
    var combo = new Ext.form.ComboBox({
        store: store,
        displayField: display,
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'Select one...',
        selectOnFocus:true
    });
    
    
    if (onchangeobj)
    {
        combo.on("change", onchangefunc, onchangeobj);
    }
    
    var combo = new Ext.grid.GridEditor(combo); 
    
    return combo
}


LSPN.MainPage.prototype.changeCourse = function(combo, newValue, oldValue)
{
    var record = combo.store.getAt(combo.selectedIndex);
    if (record)
    {
	    var course_id = record.get('course_id');
	    var tabs = Ext.getCmp('round-tabs');
	    var tab = tabs.getActiveTab();
	    var rprop = tab.items.items[0];
	    var record = rprop.propStore.store.getById("Course ID");
	    var record2 = rprop.propStore.store.getById("Course Key");
	    var arr = course_id.split("|");
	    record.set("value", arr[1]);
	    record2.set("value", arr[0]);
	    rprop.propStore.store.commitChanges();
    }
}

LSPN.MainPage.prototype.setPins = function(combo, newValue, oldValue)
{
    var record = combo.store.getAt(combo.selectedIndex);
    var pin = record.get('num');
    var tabs = Ext.getCmp('round-tabs');
    var tab = tabs.getActiveTab();
    var rprop = tab.items.items[0];
    var record = rprop.propStore.store.getById("Pin Positions (18 Holes, Positions from 0 - 17)");
    var pins = [];
    if (pin == 3)
    {
    	 // easy pins 0 - 6
    	 for (i=0;i<18;i++)
    	 {
    	 	pins[i] = 0;
    	 }
    }    
    if (pin == 0)
    {
    	 // easy pins 0 - 6
    	 for (i=0;i<18;i++)
    	 {
    	 	pins[i] = randomnumber(0,5);
    	 }
    }
    if (pin == 1)
    {
    	 // easy pins 0 - 6
    	 for (i=0;i<18;i++)
    	 {
    	 	pins[i] = randomnumber(6,11);
    	 }
    }
    if (pin == 2)
    {
    	 // easy pins 0 - 6
    	 for (i=0;i<18;i++)
    	 {
    	 	pins[i] = randomnumber(12,17);
    	 }
    }
    
    var positions = pins.join(",");
    
    record.set("value", positions);
    rprop.propStore.store.commitChanges();
}

LSPN.MainPage.prototype.showStatsFilter = function()
{
	var seasons_ds = new Ext.data.Store({
        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getSeasonsForPlayer'})),
        	    method: "POST",
                remoteSort: true,
                baseParams: {user_id: g_user_id, league_id: g_league_id},
	            reader: new Ext.data.JsonReader({
	            root: 'rows',
	            totalProperty: 'num_records'
               }, ['season_id', 'name'] )
            });
            
	//seasons_ds.load();
	
	var tours_ds = new Ext.data.Store({
        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getToursForSeasonForPlayer'})),
        	    method: "POST",
                remoteSort: true,
                baseParams: {user_id: g_user_id},
	            reader: new Ext.data.JsonReader({
	            root: 'rows',
	            totalProperty: 'num_records'
               }, ['tour_id', 'name'] )
            });
            
	var events_ds = new Ext.data.Store({
        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getEventsForTourForPlayer'})),
        	    method: "POST",
                remoteSort: true,
                baseParams: {user_id: g_user_id},
	            reader: new Ext.data.JsonReader({
	            root: 'rows',
	            totalProperty: 'num_records'
               }, ['event_id', 'name'] )
            });
            	
	var simple = new Ext.FormPanel({
		applyTo: 'view-stats-form',
        labelWidth: 100,
        height: 160,
        frame:false,
        region: 'center',
        autoScroll:true,
        bodyStyle: 'border: 0px; background: #f0f0f0;',
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "View Stats For",
	                labelSeparator: ":",
	                id: 'view-stats',
	                store: LSPN.stores.view_stats ,
	                width: 180,
	                displayField: 'name',
	                valueField: 'num',
	                typeAhead: true,
	                mode: 'local', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                emptyText: 'Select one...',
	                tooltip:'Use this drop down to select what kind of stats you would like to see',
	                listeners:{
						select:{fn:function(combo, value) {
								if (combo.getValue() == "league")
								{
									se = Ext.getCmp('view-season');
									se.emptyText = 'Not Used';
									seasons_ds.baseParams.user_id = 0;
									se.setRawValue(se.emptyText);

									tour = Ext.getCmp('view-tour');
									tour.emptyText = 'Not Used';
									tours_ds.baseParams.season_id = 0;
									tour.setRawValue(tour.emptyText);
									
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Not Used';
									ev.setRawValue(ev.emptyText);
									events_ds.baseParams.tour_id = 0;
									ev.setRawValue(ev.emptyText);
								}
								
								if (combo.getValue() == "season")
								{
									se = Ext.getCmp('view-season');
									se.emptyText = 'Select a Season...';
									seasons_ds.baseParams.user_id = g_user_id;
									seasons_ds.load();
									se.setRawValue(se.emptyText);

									tour = Ext.getCmp('view-tour');
									tour.emptyText = 'Not Used';
									tours_ds.baseParams.season_id = 0;
									tour.setRawValue(tour.emptyText);
									
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Not Used';
									ev.setRawValue(ev.emptyText);
									events_ds.baseParams.tour_id = 0;
									ev.setRawValue(ev.emptyText);
								}

								if (combo.getValue() == "tour")
								{
									se = Ext.getCmp('view-season');
									se.emptyText = 'Select a Season...';
									seasons_ds.baseParams.user_id = g_user_id;
									seasons_ds.load();
									se.setRawValue(se.emptyText);

									tour = Ext.getCmp('view-tour');
									tour.emptyText = 'Select a Season...';
									tours_ds.baseParams.season_id = 0;
									tour.setRawValue(tour.emptyText);
									
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Not Used';
									ev.setRawValue(ev.emptyText);
									events_ds.baseParams.tour_id = 0;
									ev.setRawValue(ev.emptyText);
								}
								
								if (combo.getValue() == "event")
								{
									se = Ext.getCmp('view-season');
									se.emptyText = 'Select a Season...';
									seasons_ds.baseParams.user_id = g_user_id;
									seasons_ds.load();
									se.setRawValue(se.emptyText);

									tour = Ext.getCmp('view-tour');
									tour.emptyText = 'Select a Season...';
									tours_ds.baseParams.season_id = 0;
									tour.setRawValue(tour.emptyText);
									
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Select a Seaon...';
									ev.setRawValue(ev.emptyText);
									events_ds.baseParams.tour_id = 0;
									ev.setRawValue(ev.emptyText);
								}
								
							}}	
							
					}	                
	            },
	            {
	            	html: '<u>Filters for Career, Season, or Tour stats</u>',
	            	bodyStyle: 'background: #f0f0f0; border: 0px; padding: 5 0 5 0;'
	            },{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Game",
	                labelSeparator: ":",
	                id: 'view-game',
	                store: LSPN.stores.games ,
	                width: 180,
	                displayField: 'name',
	                valueField: 'num',
	                typeAhead: true,
	                mode: 'local', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                emptyText: 'Select one...'
	            },{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Swing",
	                labelSeparator: ":",
	                id: 'view-swing',
	                store: LSPN.stores.stats_swing,
	                width: 180,
	                displayField: 'name',
	                valueField: 'num',
	                typeAhead: true,
	                mode: 'local', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                emptyText: 'Select one...'
	            },{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Difficulty",
	                labelSeparator: ":",
	                id: 'view-skill',
	                store: LSPN.stores.stats_difficulty,
	                width: 180,
	                displayField: 'name',
	                valueField: 'num',
	                typeAhead: true,
	                mode: 'local', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                emptyText: 'Select one...'
	            },{
			 		xtype: 'button',
			        text: 'View Stats',
			        handler: function(){
			        		var type = simple.findById('view-stats').value;
			        		var swing = simple.findById('view-swing').value;
			        		var game = simple.findById('view-game').value;
			        		var skill = simple.findById('view-skill').value;
			        		var season_id = simple.findById('view-season').value;
			        		var tour_id = simple.findById('view-tour').value;
			        		var event_id = simple.findById('view-event').value;
			        		
			        		if (game == "l2k1" && swing == 3)
			        		{
			        			alert("Links 2001 does not support Real Time Swing. Please select another swing type.")
			        			return;
			        		}
			        		if (game == "l2k1" && skill == 3)
			        		{
			        			alert("Links 2001 does not support Elite mode. Please select another difficulty.")
			        			return;
			        		}
			        		window.location.href = "profile.php?league_id="+g_league_id+"&user_id="+g_user_id+"&type="+type+"&swing="+swing+"&game="+game+"&difficulty="+skill+"&season_id="+season_id+"&tour_id="+tour_id+"&event_id="+event_id;
			            }
		        }
	            
	            ]
        	},
			{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; height: 200px;',       	
                items:[{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Season",
	                labelSeparator: ":",
	                id: 'view-season',
	                store: seasons_ds,
	                width: 190,
	                displayField: 'name',
	                valueField: 'season_id',
	                typeAhead: true,
	                mode: 'remote', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                emptyText: 'Select one...',
	                tooltip:'Use this drop down to if you want to see season stats',
	                listeners:{
						select:{fn:function(combo, value) {
								type = Ext.getCmp('view-stats');
								if (type.getValue() == "tour" || type.getValue() == "event")
								{
									tour = Ext.getCmp('view-tour');
									tour.emptyText = 'Select a Tour...';
									tour.setRawValue(tour.emptyText);
									tours_ds.baseParams.season_id = combo.getValue();
									tours_ds.load();
								}
								
								if (type.getValue() == "event")
								{
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Select a Tour...';
									ev.setRawValue(ev.emptyText);
								}
								
							}}	
					}	                
	            },{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Tour",
	                labelSeparator: ":",
	                id: 'view-tour',
	                store: tours_ds,
	                width: 190,
	                displayField: 'name',
	                valueField: 'tour_id',
	                typeAhead: true,
	                mode: 'remote', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                tooltip:'Use this drop down to if you want to see tour stats',
	                emptyText: 'Select a Season...',
	                listeners:{
						select:{fn:function(combo, value) {
								type = Ext.getCmp('view-stats');
								if (type.getValue() == "event")
								{
									ev = Ext.getCmp('view-event');
									ev.emptyText = 'Select an Event...';
									ev.setRawValue(ev.emptyText);
									events_ds.baseParams.tour_id = combo.getValue();
									events_ds.load();
								}							
							}}	
					}	                
	            },{
	                xtype: 'combo',
	                style: 'text-align: left;',
	                fieldLabel: "Event",
	                labelSeparator: ":",
	                id: 'view-event',
	                store: events_ds,
	                width: 190,
	                displayField: 'name',
	                valueField: 'event_id',
	                typeAhead: true,
	                mode: 'remote', 
	                selectOnFocus: true,
	                triggerAction: 'all',
	                tooltip:'Use this drop down to if you want to see stats for a particular event',
	                emptyText: 'Select a Season...'
	            }	            
	            ]
       		}]
		}]
	});
}


LSPN.MainPage.prototype.doLeaderboardOptions = function()
{
	this.getLeaderboardOptions();
	
	var simple = new Ext.FormPanel({
		id: 'leaderboard-options-form',
        labelWidth: 0,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
	    width: 350,
        items: [
        	{xtype:'fieldset',
            title: 'Game',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'Links 2003',
	                name: 'game',
	                value: 'l2k3',
	                checked: (this.leaderboardOptions.game == "l2k3" ? true : false),
	                labelSeparator: ''
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Links 2001',
	                name: 'game',
	                value: 'l2k1',
	                checked: (this.leaderboardOptions.game == "l2k1" ? true : false),
	                labelSeparator: ''
	            }]
       	 	},
        	{xtype:'fieldset',
            title: 'Difficulty',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'Amateur',
	                name: 'difficulty',
	                value: 2,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.difficulty == 2 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Pro',
	                name: 'difficulty',
	                value: 1,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.difficulty == 1 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Champ',
	                name: 'difficulty',
	                value: 0,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.difficulty == 0 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Elite',
	                name: 'difficulty',
	                value: 3,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.difficulty == 3 ? true : false)
	            }]
       	 	},{xtype:'fieldset',
            title: 'Swing Type',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'Classic Swing (C)',
	                name: 'swing',
	                value: 1,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.swing == 1 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'PowerStroke (PS)',
	                name: 'swing',
	                value: 2,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.swing == 2 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Real Time Swing (RTS)',
	                name: 'swing',
	                value: 3,
	                labelSeparator: '',
	                checked: (this.leaderboardOptions.swing == 3 ? true : false)
	            }]
       	 	}]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/config.gif" hspace="5"/></div><div style="float: left; width: 190px; text-align: left; padding: 5px;"><b>Leaderboard Options</b><br/>Use the options below to change how the Leaderboard block is displayed on the main page.</div>'
	})
	
		
    this.leaderboardOptionsWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'Leaderboard Options',
        width:300,
        height:525,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text:'Apply',
                    handler: createObjectCallback(this, this.saveLeaderboardOptions)
                },{
                    text: 'Cancel',
                    handler: createObjectCallback(this, this.closeLeaderboardOptions)
                }]
    });
    
    this.leaderboardOptionsWin.show();	
    
	
}

LSPN.MainPage.prototype.doFlightOptions = function()
{
	this.getFlightOptions();
	
	var simple = new Ext.FormPanel({
		id: 'flight-options-form',
        labelWidth: 0,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
	    width: 350,
        items: [
        	{xtype:'fieldset',
            title: 'Game',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'All Games',
	                name: 'flgame',
	                value: 'anygame',
	                checked: (this.flightOptions.game == "anygame" ? true : false),
	                labelSeparator: ''
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Links 2003',
	                name: 'flgame',
	                value: 'l2k3',
	                checked: (this.flightOptions.game == "l2k3" ? true : false),
	                labelSeparator: ''
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Links 2001',
	                name: 'flgame',
	                value: 'l2k1',
	                checked: (this.flightOptions.game == "l2k1" ? true : false),
	                labelSeparator: ''
	            }]
       	 	},
        	{xtype:'fieldset',
            title: 'Difficulty',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'All Difficulties',
	                name: 'fldifficulty',
	                value: -1,
	                labelSeparator: '',
	                checked: (this.flightOptions.difficulty == -1 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Amateur',
	                name: 'fldifficulty',
	                value: 0,
	                labelSeparator: '',
	                checked: (this.flightOptions.difficulty == 0 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Pro',
	                name: 'fldifficulty',
	                value: 1,
	                labelSeparator: '',
	                checked: (this.flightOptions.difficulty == 1 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Champ',
	                name: 'fldifficulty',
	                value: 2,
	                labelSeparator: '',
	                checked: (this.flightOptions.difficulty == 2 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Elite',
	                name: 'fldifficulty',
	                value: 3,
	                labelSeparator: '',
	                checked: (this.flightOptions.difficulty == 3 ? true : false)
	            }]
       	 	},{xtype:'fieldset',
            title: 'Swing Type',
            autoHeight:true,
            autoWidth: true,
            style: 'text-align: left;',
	            items: [{
	        		xtype: 'radio',
	                boxLabel: 'All Swings',
	                name: 'flswing',
	                value: 0,
	                labelSeparator: '',
	                checked: (this.flightOptions.swing == 0 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Classic Swing (C)',
	                name: 'flswing',
	                value: 1,
	                labelSeparator: '',
	                checked: (this.flightOptions.swing == 1 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'PowerStroke (PS)',
	                name: 'flswing',
	                value: 2,
	                labelSeparator: '',
	                checked: (this.flightOptions.swing == 2 ? true : false)
	            },{
	        		xtype: 'radio',
	                boxLabel: 'Real Time Swing (RTS)',
	                name: 'flswing',
	                value: 3,
	                labelSeparator: '',
	                checked: (this.flightOptions.swing == 3 ? true : false)
	            }]
       	 	}]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/config.gif" hspace="5"/></div><div style="float: left; width: 190px; text-align: left; padding: 5px;"><b>Handicap & Flight Options</b><br/>Use the options below to filter the handicap & flight list.</div>'
	})
	
		
    this.flightOptionsWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'Handicap & Flight Options',
        width:300,
        height:550,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text:'Apply',
                    handler: createObjectCallback(this, this.saveFlightOptions)
                },{
                    text: 'Cancel',
                    handler: createObjectCallback(this, this.closeFlightOptions)
                }]
    });
    
    this.flightOptionsWin.show();	
    
	
}


LSPN.MainPage.prototype.showConditions = function(event_id, bcourses_only)
{
	this.event_id = event_id;
	this.bcourses_only = bcourses_only
	doAjaxRPC('getConditions', {event_id: this.event_id}, createObjectCallback(this, this.doConditions), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.doConditions = function(respObj)
{
	// Custom rendering Template for the View
	
	var tpl = null;
	var title = "Courses & Conditions";
	var message = "Download courses and view conditions for the event. Click on the course name to find out how to obtain it.";
	if (this.bcourses_only == true)
	{
		title = "Courses";
		message = "Click on the course name to find out how to obtain it.";
	    tpl = new Ext.XTemplate(
	     	'<tpl for=".">',
	        '<div class="round">',
	            '<span style="font-weight: bold; font-size: 13px;">Round {#}</br><a href="{course_url}" target="_new">{course} <img src="images/icons/download_small.png" border="0"/></a></span>',
            '</div><br/></tpl>'
	    );
	}
	else
	{
	    tpl = new Ext.XTemplate(
	     	'<tpl for=".">',
	        '<div class="round">',
	            '<span style="font-weight: bold; font-size: 13px;">Round {#}</br><a href="{course_url}" target="_new">{course} <img src="images/icons/download_small.png" border="0"/></a></span><br /><span style="font-size: 12px; color: #a6a6a6;">{weather}</span>',
	            '<p>{tees}, {holes}, {pins}, {gimme_range}, {mulligans}, {grid}, {caddie}, {crowds}<br/>',
	        '</div>',
	        '<tpl if="joker0 &gt; 0">',
	        'Joker hole {joker0}',
	        '</tpl>',
	        '<tpl if="joker1 &gt; 0">',
	        ', Joker hole {joker1}',
	        '</tpl>',
	        '</p><br/></tpl>'
	        
	    );
	}
	
    var simple = new Ext.Panel({
    	id: 'conditions-panel',
        autoScroll:true,
        loadMask: true,
		region: 'center',
		bodyStyle: 'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
		html: tpl.applyTemplate(respObj.rows)
    });
	

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/weather.png" hspace="5"/></div><div style="float: left; width: 450px; text-align: left; padding: 5px;"><b>'+title+'</b><br/>'+message+'</div>'
	});
	

    this.coursesWin = new Ext.Window({
    	headerStyle: 'text-align: left;',
    	bodyStyle: 'text-align: left;',
        title: title,
        width:600,
        height:500,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text: 'Close',
                    handler: createObjectCallback(this, this.closeCoursesWin)
                }]
    });
    
    this.coursesWin.show();	
    
}
	    

	    
LSPN.MainPage.prototype.doRssOptions = function()
{
	this.getRssOptions();
	
	var simple = new Ext.FormPanel({
		id: 'rss-options-form',
        labelWidth: 100,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
	    width: 600,
        items: 
	        [{
	            layout: 'form', 
	            bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',       	
	            items:[{
	        		xtype: 'textfield',
	        		id: 'rss-feed',
	                fieldLabel: 'Feed URL',
	                width: 300,
	                name: 'feed',
	                allowBlank: false,
	                value:this.rssOptions.feed
	       	 	}]
	        }]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 250px; text-align: center;"><img src="images/icons/rss.png" hspace="5"/></div><div style="float: left; width: 250px; text-align: left; padding: 5px;"><b>RSS News Options</b><br/>Customize your RSS Feed.</div>'
	});
	
		
    this.rssOptionsWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'RSS News Options',
        width:600,
        height:250,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text:'Apply',
                    handler: createObjectCallback(this, this.saveRssOptions)
                },{
                    text: 'Cancel',
                    handler: createObjectCallback(this, this.closeRssOptions)
                }]
    });
    
    this.rssOptionsWin.show();	
    
	
}



LSPN.MainPage.prototype.doCurrentEventOptionsWin = function()
{
	var temp;
	
	if (level != "Casual Player")
	{
		temp = [{
	        		xtype: 'checkbox',
	                boxLabel: 'Official Tour',
	                name: 'showevents',
	                value: LSPN.enums.prefs.LSPN,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.LSPN ? true : false),
	                labelSeparator: ''
	            },{
	        		xtype: 'checkbox',
	                boxLabel: 'The Arcade',
	                name: 'showevents',
	                value: LSPN.enums.prefs.ARCADE,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.ARCADE ? true : false),
	                labelSeparator: ''
	            },{
					xtype: 'checkbox',
	                boxLabel: 'My Leagues',
	                name: 'showevents',
	                value: LSPN.enums.prefs.LEAGUE,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.LEAGUE ? true : false),
	                labelSeparator: ''
	            }/*,{
					xtype: 'checkbox',
	                boxLabel: 'Free Events',
	                name: 'showevents',
	                value: LSPN.enums.prefs.FREE,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.FREE ? true : false),
	                labelSeparator: ''
		        }*/];
	}
	else
	{          
		temp = [{
	        		xtype: 'checkbox',
	                boxLabel: 'Official Tour',
	                name: 'showevents',
	                value: LSPN.enums.prefs.LSPN,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.LSPN ? true : false),
	                labelSeparator: ''
	            },{
	        		xtype: 'checkbox',
	                boxLabel: 'The Arcade',
	                name: 'showevents',
	                value: LSPN.enums.prefs.ARCADE,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.ARCADE ? true : false),
	                labelSeparator: ''
	            },{
					xtype: 'checkbox',
	                boxLabel: 'Free Events',
	                name: 'showevents',
	                value: LSPN.enums.prefs.FREE,
	                checked: (this.currentEventOptions & LSPN.enums.prefs.FREE ? true : false),
	                labelSeparator: ''
		        }];
	}
	
	var simple = new Ext.FormPanel({
		id: 'current-event-options-form',
        labelWidth: 0,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
		width: 700,
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',       	
                items:[
		        	{xtype:'fieldset',
		            title: 'Game',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Links 2003',
			                name: 'game',
			                value: LSPN.enums.prefs.L2K3,
			                checked: (this.currentEventOptions & LSPN.enums.prefs.L2K3 ? true : false),
			                labelSeparator: ''
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Links 2001',
			                name: 'game',
			                value: LSPN.enums.prefs.L2K1,
			                checked: (this.currentEventOptions & LSPN.enums.prefs.L2K1 ? true : false),
			                labelSeparator: ''
			            }]
		       	 	},
		        	{xtype:'fieldset',
		            title: 'Difficulty',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Amateur',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.AMATEUR,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.AMATEUR ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Pro',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.PRO,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.PRO ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Champ',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.CHAMP,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CHAMP ? true : false)
		
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Elite',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.ELITE,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.ELITE ? true : false)
			            },{ html:'<div style="border: 0px; background: #f0f0f0; padding: 4px;">&nbsp;</div>',
			            	bodyStyle: 'border: 0px;'
			            }]
		       	 	},
		       	 	{xtype:'fieldset',
		            title: 'Swing Type',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Classic Swing',
			                name: 'swing',
			                value: LSPN.enums.prefs.CLASSIC_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CLASSIC_SWING ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'PowerStroke',
			                name: 'swing',
			                value: LSPN.enums.prefs.PS_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.PS_SWING ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Real Time Swing',
			                name: 'swing',
			                value: LSPN.enums.prefs.RTS_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.RTS_SWING ? true : false)
			            }]
		       	 	}]},
					{
	                columnWidth:.5,
	                layout: 'form',   
	                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',     	
	                items:[		       	 	
			        	{xtype:'fieldset',
			        	columnWidth: .5,
			            title: 'Show Events From',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: temp
			       	 	},
			        	{xtype:'fieldset',
			            title: 'Tees',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: [{
				        		xtype: 'checkbox',
				                boxLabel: 'Back',
				                name: 'tees',
				                value: LSPN.enums.prefs.BACK,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.BACK ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Middle',
				                name: 'tees',
				                value: LSPN.enums.prefs.MIDDLE,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.MIDDLE ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Forward',
				                name: 'tees',
				                value: LSPN.enums.prefs.FORWARD,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.FORWARD ? true : false)
			
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Junior',
				                name: 'tees',
				                value: LSPN.enums.prefs.JUNIOR,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.JUNIOR ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Ladies',
				                name: 'tees',
				                value: LSPN.enums.prefs.LADIES,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.LADIES ? true : false)
				            }]
			       	 	},{xtype:'fieldset',
			            title: 'Holes',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: [{
				        		xtype: 'checkbox',
				                boxLabel: 'All 18',
				                name: 'holes',
				                value: LSPN.enums.prefs.ALL18,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.ALL18 ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Front 9',
				                name: 'holes',
				                value: LSPN.enums.prefs.FRONT9,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.FRONT9 ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Back 9',
				                name: 'holes',
				                value: LSPN.enums.prefs.BACK9,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.BACK9 ? true : false)
				            }]
	       	 			}	       	 	
	       	 		]}
        ]
        	}]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/config.gif" hspace="5"/></div><div style="float: left; width: 550px; text-align: left; padding: 5px;"><b>Current Events Options</b><br/>Use the options below to filter the Current Events Block. These options also affect the list you\'ll see in the game.</div>'
	})
	
		
    this.currentEventOptionsWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'Current Event Options',
        width:700,
        height:525,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text:'Apply',
                    handler: createObjectCallback(this, this.saveCurrentEventOptions)
                },{
                    text: 'Cancel',
                    handler: createObjectCallback(this, this.closeCurrentEventOptions)
                }]
    });
    
    this.currentEventOptionsWin.show();	
}

LSPN.MainPage.prototype.doPointsOptionsWin = function()
{
	/*
	var simple = new Ext.FormPanel({
		id: 'current-event-options-form',
        labelWidth: 0,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
		width: 700,
        items: [{
        	layout: 'column',
        	bodyStyle:'border: 0px;',       	
        	items: [{
                columnWidth:.5,
                layout: 'form', 
                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',       	
                items:[
		        	{xtype:'fieldset',
		            title: 'Game',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Links 2003',
			                name: 'game',
			                value: LSPN.enums.prefs.L2K3,
			                checked: (this.currentEventOptions & LSPN.enums.prefs.L2K3 ? true : false),
			                labelSeparator: ''
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Links 2001',
			                name: 'game',
			                value: LSPN.enums.prefs.L2K1,
			                checked: (this.currentEventOptions & LSPN.enums.prefs.L2K1 ? true : false),
			                labelSeparator: ''
			            }]
		       	 	},
		        	{xtype:'fieldset',
		            title: 'Difficulty',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Amateur',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.AMATEUR,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.AMATEUR ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Pro',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.PRO,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.PRO ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Champ',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.CHAMP,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CHAMP ? true : false)
		
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Elite',
			                name: 'difficulty',
			                value: LSPN.enums.prefs.ELITE,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.ELITE ? true : false)
			            },{ html:'<div style="border: 0px; background: #f0f0f0; padding: 4px;">&nbsp;</div>',
			            	bodyStyle: 'border: 0px;'
			            }]
		       	 	},
		       	 	{xtype:'fieldset',
		            title: 'Swing Type',
		            autoHeight:true,
		            autoWidth: true,
		            style: 'text-align: left;',
			            items: [{
			        		xtype: 'checkbox',
			                boxLabel: 'Classic Swing',
			                name: 'swing',
			                value: LSPN.enums.prefs.CLASSIC_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CLASSIC_SWING ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'PowerStroke',
			                name: 'swing',
			                value: LSPN.enums.prefs.PS_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CLASSIC_SWING ? true : false)
			            },{
			        		xtype: 'checkbox',
			                boxLabel: 'Real Time Swing',
			                name: 'swing',
			                value: LSPN.enums.prefs.RTS_SWING,
			                labelSeparator: '',
			                checked: (this.currentEventOptions & LSPN.enums.prefs.CLASSIC_SWING ? true : false)
			            }]
		       	 	}]},
					{
	                columnWidth:.5,
	                layout: 'form',   
	                bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',     	
	                items:[		       	 	
			        	{xtype:'fieldset',
			        	columnWidth: .5,
			            title: 'Show Events From',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: [{
				        		xtype: 'checkbox',
				                boxLabel: 'Official Tour',
				                name: 'showevents',
				                value: LSPN.enums.prefs.LSPN,
				                checked: (this.currentEventOptions & LSPN.enums.prefs.LSPN ? true : false),
				                labelSeparator: ''
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'The Arcade',
				                name: 'showevents',
				                value: LSPN.enums.prefs.ARCADE,
				                checked: (this.currentEventOptions & LSPN.enums.prefs.ARCADE ? true : false),
				                labelSeparator: ''
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'My League',
				                name: 'showevents',
				                value: LSPN.enums.prefs.LEAGUE,
				                checked: (this.currentEventOptions & LSPN.enums.prefs.LEAGUE ? true : false),
				                labelSeparator: ''
				            }]
			       	 	},
			        	{xtype:'fieldset',
			            title: 'Tees',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: [{
				        		xtype: 'checkbox',
				                boxLabel: 'Back',
				                name: 'tees',
				                value: LSPN.enums.prefs.BACK,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.BACK ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Middle',
				                name: 'tees',
				                value: LSPN.enums.prefs.MIDDLE,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.MIDDLE ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Forward',
				                name: 'tees',
				                value: LSPN.enums.prefs.FORWARD,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.FORWARD ? true : false)
			
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Junior',
				                name: 'tees',
				                value: LSPN.enums.prefs.JUNIOR,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.JUNIOR ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Ladies',
				                name: 'tees',
				                value: LSPN.enums.prefs.LADIES,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.LADIES ? true : false)
				            }]
			       	 	},{xtype:'fieldset',
			            title: 'Holes',
			            autoHeight:true,
			            autoWidth: true,
			            style: 'text-align: left;',
				            items: [{
				        		xtype: 'checkbox',
				                boxLabel: 'All 18',
				                name: 'holes',
				                value: LSPN.enums.prefs.ALL18,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.ALL18 ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Front 9',
				                name: 'holes',
				                value: LSPN.enums.prefs.FRONT9,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.FRONT9 ? true : false)
				            },{
				        		xtype: 'checkbox',
				                boxLabel: 'Back 9',
				                name: 'holes',
				                value: LSPN.enums.prefs.BACK9,
				                labelSeparator: '',
				                checked: (this.currentEventOptions & LSPN.enums.prefs.BACK9 ? true : false)
				            }]
	       	 			}	       	 	
	       	 		]}
        ]
        	}]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/config.gif" hspace="5"/></div><div style="float: left; width: 550px; text-align: left; padding: 5px;"><b>Current Events Options</b><br/>Use the options below to filter the Current Events Block. These options also affect the list you\'ll see in the game.</div>'
	})
	
		
    this.currentEventOptionsWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'Current Event Options',
        width:700,
        height:525,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text:'Apply',
                    handler: createObjectCallback(this, this.saveCurrentEventOptions)
                },{
                    text: 'Cancel',
                    handler: createObjectCallback(this, this.closeCurrentEventOptions)
                }]
    });
    
    this.currentEventOptionsWin.show();	
    */
}


LSPN.MainPage.prototype.doCoursesWin = function(respObj)
{
	var courses = respObj.rows;
	str = "";
	var last_course = null;
	for (i=0;i<courses.length;i++)
	{
		if (last_course != courses[i].name)
		{
			str += '<a href="'+courses[i].URL+'" target="_new">'+courses[i].name+'</a><br/>'
			last_course = courses[i].name;
		}
	}

	var simple = new Ext.FormPanel({
		id: 'courses-options-form',
        labelWidth: 0,
        frame:false,
        region: 'center',
        bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px; border-top: 1px solid white;',
		width: 400,
        items: [{
            layout: 'form', 
            bodyStyle:'padding:5px 5px 0; background: #f0f0f0; border: 0px;',       	
            items:[
            {
            	html: str,
            	bodyStyle: 'padding:5px 5px 0; background: #f0f0f0; border: 0px;'
            }
	        ]
        	}]
		});

	var panel = new Ext.Panel({
		bodyStyle: 'border: 0px; border-bottom: 1px solid #c8c8c8',
		region: 'north',
		height: 74,
		html: '<div style="float: left; width: 80px; text-align: center;"><img src="images/icons/download.png" hspace="5"/></div><div style="float: left; width: 200px; text-align: left; padding: 5px;"><b>Courses</b><br/>Listed below are links to the courses used for this event.</div>'
	})
	
		
    this.coursesWin = new Ext.Window({
    	bodyStyle: 'text-align: left;',
        title: 'Courses',
        width:400,
        height:240,
        shim:false,
        animCollapse:false,
        constrainHeader:true,
        layout: 'border',
        items:[
			panel, simple
   		 ],
   		 buttons: [{
                    text: 'Close',
                    handler: createObjectCallback(this, this.closeCoursesWin)
                }]
    });
    
    this.coursesWin.show();	
}


LSPN.MainPage.prototype.doCurrentEventOptions = function()
{
	this.getCurrentEventOptions(this, this.doCurrentEventOptionsWin);
}

LSPN.MainPage.prototype.closeCoursesWin = function()
{
	this.coursesWin.close();
}


LSPN.MainPage.prototype.saveLeaderboardOptions = function()
{
	var simple = Ext.getCmp('leaderboard-options-form');
	var arr = simple.findByType('radio');
	for (i=0;i<arr.length;i++)
	{
		if (arr[i].getValue())
		{
			this.cp.set(arr[i].name, arr[i].value);
		}
	}
	this.closeLeaderboardOptions();
	this.reloadLeaderboard();
}

LSPN.MainPage.prototype.saveFlightOptions = function()
{
	var simple = Ext.getCmp('flight-options-form');
	var arr = simple.findByType('radio');
	for (i=0;i<arr.length;i++)
	{
		if (arr[i].getValue())
		{
			this.cp.set(arr[i].name, arr[i].value);
		}
	}
	this.closeFlightOptions();
	this.reloadHandicapList();
}

LSPN.MainPage.prototype.closeLeaderboardOptions = function()
{
	this.leaderboardOptionsWin.close();
}	

LSPN.MainPage.prototype.closeFlightOptions = function()
{
	this.flightOptionsWin.close();
}	

LSPN.MainPage.prototype.saveRssOptions = function()
{
	var simple = Ext.getCmp('rss-options-form');
	var rss = document.getElementById('rss-feed');
	this.cp.set('feed', rss.value);
	this.closeRssOptions();
	this.reloadGolfNews();
}

LSPN.MainPage.prototype.closeRssOptions = function()
{
	this.rssOptionsWin.close();
}	

LSPN.MainPage.prototype.saveCurrentEventOptions = function()
{
	var simple = Ext.getCmp('current-event-options-form');
	var arr = simple.findByType('checkbox');
	var prefs = 0;
	for (i=0;i<arr.length;i++)
	{
		if (arr[i].getValue())
		{
			prefs |= arr[i].value;
		}
	}
	
    doAjaxRPC('saveCurrentEventOptions', {prefs: prefs}, createObjectCallback(this, this.reloadCurrentEvents), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.reloadCurrentEvents = function()
{
    var paging = Ext.getCmp('page-current-events');
	paging.doLoad(0);
	this.closeCurrentEventOptions();
}

LSPN.MainPage.prototype.closeCurrentEventOptions = function()
{
	this.currentEventOptionsWin.close();
}	

LSPN.MainPage.prototype.failure = function(o)
{
	if (typeof(o) == "string")
    	Ext.Msg.alert('Message', o);    
    else
    	alert(var_dump(o));
}

LSPN.MainPage.prototype.getStats = function(grid, rowIndex, colIndex, e)
{
    var selectionModel = grid.getSelectionModel(); 
    var record = selectionModel.getSelected();  
    var user_id = record.get('user_id');

    var scorecard = Ext.getCmp('scorecard');
	scorecard.load({
		url: "/viewScorecard.php",
		params: {user_id : user_id,
				 event_id : this.event_id
				}
	});
     
	var stats = Ext.getCmp('stats');
	stats.load({
		url: "/viewStats.php",
		params: {user_id : user_id,
				 event_id : this.event_id,
				 stats_type : 'event_stats'
				}
	});
}

LSPN.MainPage.prototype.initLeaderboardBlock = function()
{
	this.setupLeaderboard();
    //doAjaxRPC('getOfficialTours', {}, createObjectCallback(this, this.setupLeaderboard), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.initCurrentEventsBlock = function()
{
    this.setupCurrentEvents();
}

LSPN.MainPage.prototype.initLeagueCurrentEventsBlock = function()
{
	this.useLeagueId = league_detail_id;
	this.leagueCurrentEvents = 1;
	this.setupCurrentEvents();
}


LSPN.MainPage.prototype.initLastWeeksEventsBlock = function()
{
    this.setupLastWeeksEvents();
}

LSPN.MainPage.prototype.reloadGolfNews = function()
{
	this.getRssOptions();
	var view = Ext.getCmp('golf-news-view');
	view.store.proxy.conn.url = RSS_URL+"?feed="+this.rssOptions.feed;
	view.store.load();
}

LSPN.MainPage.prototype.reloadLeaderboard = function()
{
	this.getLeaderboardOptions();
    for (i=0;i<LSPN.enums.difficulty.length;i++)
    {
    	var skill = LSPN.enums.difficulty[i][0];
		var grid = Ext.getCmp('grid_'+skill);
		var tab = Ext.getCmp('skill_'+skill);

		grid.store.baseParams.swing_type = this.leaderboardOptions.swing;
		grid.store.baseParams.difficulty = skill;
		grid.store.baseParams.game = this.leaderboardOptions.game;
		grid.store.removeAll();
		grid.store.current_index = skill;
		grid.store.load();	
    }
    // hack. For some reason ext isn't rendering the active tab
    var tab = this.tabs.getActiveTab();
    var id = tab.id;
    arr = id.split("_");
    var grid = Ext.getCmp("grid_"+arr[1]);
    grid.view.render();
    
    // switch to the desired tab
    this.tabs.activate("skill_"+this.leaderboardOptions.difficulty);
}

LSPN.MainPage.prototype.reloadHandicapList = function()
{
	this.getFlightOptions();
	var grid = Ext.getCmp('flight-grid');
	grid.store.baseParams.swing_type = this.flightOptions.swing;
	grid.store.baseParams.difficulty = this.flightOptions.difficulty;
	grid.store.baseParams.game = this.flightOptions.game;
	grid.store.removeAll();
	grid.store.load({params:{start:0, limit:25}});	
}


LSPN.MainPage.prototype.setupMyEvents = function()
{
   		var playing_ds = new Ext.data.Store({
	        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getMyEventsPlaying'})),
	        	    method: "POST",
	                remoteSort: true,
	                sortInfo : {field: "end_date", direction: "ASC"},
		            reader: new Ext.data.JsonReader({
		            root: 'rows',
		            totalProperty: 'num_records'
	               }, ['num_requal', 'event_id', 'name', 'start_date', 'end_date', 'status'])
	            });
	            
    	playing_ds.load();
    	
		var playing_cm = new Ext.grid.ColumnModel([
	        {header: "Event", width: 150, sortable: true, dataIndex: 'name'},
	        {header: "End", width: 70, sortable: true, dataIndex: 'end_date'},
	        {header: "Status", width: 95, sortable: false, dataIndex: 'status', renderer: renderMyEventStatus}
	    ]);
    	
        playing_grid = new Ext.grid.GridPanel({
        	id: 'grid_events_playing',
        	title: 'Playing',
        	loadMask: true,
            border:false,
        	ds : playing_ds,                       
            cm: playing_cm,
            stripeRows: true,
            width: 290,
            height: 'auto'
        }) ;   	
    	
    	playing_grid.on('rowdblclick', this.showMyLeaderboard, this);

   		var own_ds = new Ext.data.Store({
	        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getMyEventsOwn'})),
	        	    method: "POST",
	                remoteSort: true,
	                sortInfo : {field: "end_date", direction: "ASC"},
		            reader: new Ext.data.JsonReader({
		            root: 'rows',
		            totalProperty: 'num_records'
	               }, ['num_players', 'max_players', 'num_requal', 'event_id', 'name', 'start_date', 'end_date', 'status'])
	            });
	            
    	own_ds.load();
    	
		var own_cm = new Ext.grid.ColumnModel([
	        {header: "Event", width: 150, sortable: true, dataIndex: 'name'},
	        {header: "End", width: 70, sortable: true, dataIndex: 'end_date'},
	        {header: "Players", width: 70, sortable: true, dataIndex: 'num_players', renderer: renderNumPlayers}
	    ]);
    	
        own_grid = new Ext.grid.GridPanel({
        	id: 'grid_events_own',
        	title: 'Own',
        	loadMask: true,
            border:false,
        	ds : own_ds,                       
            cm: own_cm,
            stripeRows: true,
            width: 290,
            height: 'auto'
        }) ;   	
    	
    	own_grid.on('rowdblclick', this.showMyLeaderboard, this);
    	
	    var tabs = new Ext.TabPanel({
	        renderTo:'main-myevents-tabs',
	        resizeTabs:true,
	        activeTab: 0,
	        minTabWidth: 75,
	        tabWidth:75,
	        enableTabScroll:true,
	        autoWidth: 300,
	        height: 175,
	        defaults: {autoScroll:true},
	        items:[playing_grid, own_grid]
	    });	
	    
	    tabs.doLayout();
	
}

///<summary>
/// Creates the tabs and grids for the leaderboard section on the main page
///<summary>
LSPN.MainPage.prototype.setupLeaderboard = function()
{
	//this.officialTours = respObj.rows;
    this.tabs = new Ext.TabPanel({
        renderTo:this.tabsId,
        resizeTabs:true,
        minTabWidth: 75,
        tabWidth:75,
        enableTabScroll:true,
        autoWidth: 429,
        height: 181,
        defaults: {autoScroll:true}
    });

    var grid;
    for (i=0;i<LSPN.enums.difficulty.length;i++)
    {
    	var skill_num = LSPN.enums.difficulty[i][0];
    	var skill_name = LSPN.enums.difficulty[i][1];

   		var ds = new Ext.data.Store({
	        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getLeaders'})),
	        	    method: "POST",
	                remoteSort: true,
	                baseParams: {difficulty: skill_num, game: this.leaderboardOptions.game, swing_type: this.leaderboardOptions.swing, num_pos: 5},
		            reader: new Ext.data.JsonReader({
		            root: 'rows.leaders',
		            totalProperty: 'num_records'
	               }, ['rank', 'user_id', 'username', 'total_score', 'current_round', 'current_hole'] )
	            });


    	ds.load();
    	
		ds.on("load", function(ds, records, options){
			if (ds.reader.jsonData.rows.event_id)
			{
				var skill_num = ds.reader.jsonData.rows.skill;
				var tab = Ext.getCmp('skill_'+skill_num);
				var obj=document.getElementById("tour_title_"+skill_num);
				if (obj)
				{
					var mod_title = " - " + getEnumText(LSPN.enums.games, ds.reader.jsonData.rows.game);
					
					var swing_arr = LSPN.enums.k3short;
					if (ds.reader.jsonData.rows.game == 'l2k1')
						swing_arr = LSPN.enums.k1short;
						
					var swing_title = "";
					value = getEnumText(swing_arr, ds.reader.jsonData.rows.swing);
					
					swing_title = " - "+value;
					obj.innerHTML = ds.reader.jsonData.rows.name + swing_title + mod_title;
					if (tab)
					{
						tab.event_id = ds.reader.jsonData.rows.event_id;
						tab.tour_name = ds.reader.jsonData.rows.name + swing_title + mod_title;
					}					
					var obj=document.getElementById("tour_date_"+skill_num);
					if (obj)
					{
						obj.innerHTML = ds.reader.jsonData.rows.event_date;
					}
				}
			}
		});
    	
		var cm = new Ext.grid.ColumnModel([
	        {header: "Pos", width: 70, sortable: false, dataIndex: 'rank'},
	        {header: "Player", width: 150, sortable: false, dataIndex: 'username'},
	        {header: "Score", width: 70, sortable: false, dataIndex: 'total_score'},
	        {header: "Round", width: 70, sortable: false, dataIndex: 'current_round'},
	        {header: "Hole", width: 60, sortable: false, dataIndex: 'current_hole'}
	    ]);
    	
        grid = new Ext.grid.GridPanel({
        	id: 'grid_'+skill_num,
        	loadMask: true,
            border:false,
        	ds : ds,                       
            cm: cm,
            stripeRows: true,
            width: 426
        }) ;   	
    	
    	grid.on('dblclick', this.doLeaderboard, this);

    	var tour_name = "";
    	addTab(this.tabs, {
    		id: 'skill_'+skill_num,
	        title: skill_name,
	        tour_name: tour_name,
	        //event_id: /*this.officialTours[this.leaderboardOptions.game][skill_num][0],*/
	        items: [{tag:'p',html:'<p id="'+this.titleId+'"><span id="tour_title_'+skill_num+'"></span><br/><span style="font-size: 90%" id="tour_date_'+skill_num+'"></span></p>', style:'font-size: 90%; border: 0px;'}, grid],
	        closable:false
	    });
	    
    
    }
	addTab(this.tabs, {
		id: 'temp',
        title: 'temp',
        closable:false
    });	
    this.tabs.doLayout();
    this.tabs.activate("skill_"+this.leaderboardOptions.difficulty);
    this.tabs.remove('temp');    
}

LSPN.MainPage.prototype.showSchedule = function(element, tour)
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getSchedule'})),
    	    method: "POST",
    	    sortInfo : {field: "end_date", direction: "ASC"},
            remoteSort: true,
            baseParams: {tour: tour, league_current_events: this.leagueCurrentEvents, use_league_id: this.useLeagueId},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
                'swing_typenew', 'tees', 'holes', 'tour_name', 'event_id', 'tour_id', 'game', 'name', 'rules', 'num_players', 'num_rounds', 'team_mode', 'num_team_members', 
               'difficulty', 'eligibility', 'sportsmanship', 'rank_id', 'num_cuts', 'team_mode', 
               {name: 'end_date', mapping: 'end_date', type: 'date', dateFormat:'Y-m-d'},
               {name: 'start_date', mapping: 'start_date', type: 'date', dateFormat:'Y-m-d'},
               'qualifier', 'private', 'prize', 'expired', 'points', 'max_players', 'sponsor', 'no_putt_assist', 'chip_green', 'cut_round', 'resumes', 'owner_id', 'num_requal', 'requal_penalty',
               'requal_multiplier', 'official', 'owner', 'user_id', 'status', 'requalifies'
            ]            
            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'end_date',
           header: "Dates",
           dataIndex: 'end_date',
           width: 90,
           renderer: renderLast
        },{
           id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Events",
           dataIndex: 'name',
           width: 180,
           renderer: renderScheduleEvent
        },{
           header: "Skill",
           dataIndex: 'difficulty',
           width: 50,
           align: 'left',
           renderer: renderEventsSkill
        },{
           header: "Swing",
           dataIndex: 'swing_typenew',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Rules",
           dataIndex: 'rules',
           width: 50,
           align: 'left',
           renderer: renderRules
        },{
           header: "Tour",
           dataIndex: 'tour_name',
           width: 60,
           align: 'left'
        },{
           header: "Rds",
           dataIndex: 'num_rounds',
           width: 35,
           align: 'left'
        },{
           header: "Players",
           dataIndex: 'num_players',
           width: 70,
           align: 'left',
           renderer: renderNumPlayers
        },{
           header: "Owner",
           dataIndex: 'owner',
           width: 105,
           hidden: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var height = 600;
    if (this.leagueCurrentEvents)
    	height = 300;
    
    
    var grid = new Ext.grid.GridPanel({
        applyTo:element,
        width:630,
        height:height,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        bbar: new Ext.PagingToolbar({
        	id: 'page-schedule-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying events {0} - {1} of {2}',
            emptyMsg: "No events to display"
        })
    });

    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}


LSPN.MainPage.prototype.setupCurrentEvents = function(respObj)
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getCurrentEvents'})),
    	    method: "POST",
    	    sortInfo : {field: "end_date", direction: "ASC"},
            remoteSort: true,
            baseParams: {clubhouse_id: 2, user_id: 2, league_current_events: this.leagueCurrentEvents, use_league_id: this.useLeagueId},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
                'swing_typenew', 'tees', 'holes', 'tour_name', 'event_id', 'tour_id', 'game', 'name', 'rules', 'num_players', 'num_rounds', 'team_mode', 'num_team_members', 
               'difficulty', 'eligibility', 'sportsmanship', 'rank_id', 'num_cuts', 'team_mode', 
               {name: 'end_date', mapping: 'end_date', type: 'date', dateFormat:'Y-m-d'},
               {name: 'start_date', mapping: 'start_date', type: 'date', dateFormat:'Y-m-d'},
               'qualifier', 'private', 'prize', 'expired', 'points', 'max_players', 'sponsor', 'no_putt_assist', 'chip_green', 'cut_round', 'resumes', 'owner_id', 'num_requal', 'requal_penalty',
               'requal_multiplier', 'official', 'owner', 'user_id', 'status', 'requalifies'
            ]            
            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'end_date',
           header: "Dates",
           dataIndex: 'end_date',
           width: 90,
           renderer: renderLast
        },{
           id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Events",
           dataIndex: 'name',
           width: 180,
           renderer: renderEvent
        },{
           header: "Skill",
           dataIndex: 'difficulty',
           width: 50,
           align: 'left',
           renderer: renderEventsSkill
        },{
           header: "Swing",
           dataIndex: 'swing_typenew',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Rules",
           dataIndex: 'rules',
           width: 50,
           align: 'left',
           renderer: renderRules
        },{
           header: "Tour",
           dataIndex: 'tour_name',
           width: 60,
           align: 'left'
        },{
           header: "Rds",
           dataIndex: 'num_rounds',
           width: 35,
           align: 'left'
        },{
           header: "Players",
           dataIndex: 'num_players',
           width: 70,
           align: 'left',
           renderer: renderNumPlayers
        },{
           header: "Owner",
           dataIndex: 'owner',
           width: 105,
           hidden: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var tbar = null;
    if (can_create_arcade)
    {
    	tbar = [
            'Search for event name or owner: ', ' ',
            new Ext.app.SearchField({
                store: ds,
                width:300
            }),
			new Ext.Button({
			    text: 'Create Arcade Event',
			    iconCls: 'add',
			    handler: function(){
			    	window.location.href = '/arcade.php';
			    }
			})
        ];
    }
    else
    {
    	tbar = [
            'Search for event name or owner: ', ' ',
            new Ext.app.SearchField({
                store: ds,
                width:300
            })
        ];
    }
    
    var height = 600;
    if (this.leagueCurrentEvents)
    	height = 300;
    
    var grid = new Ext.grid.GridPanel({
        applyTo:'current-events-grid',
        width:630,
        height:height,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: tbar,
        bbar: new Ext.PagingToolbar({
        	id: 'page-current-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying events {0} - {1} of {2}',
            emptyMsg: "No events to display"
        })
    });

    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}

LSPN.MainPage.prototype.setupLastWeeksEvents = function(respObj)
{
	this.previousEvents = true;
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getLastWeeksEvents'})),
    	    method: "POST",
    	    sortInfo : {field: "end_date", direction: "ASC"},
            remoteSort: true,
            baseParams: {clubhouse_id: 2, user_id: 2},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
                'swing_typenew', 'tees', 'holes', 'tour_name', 'event_id', 'tour_id', 'game', 'name', 'rules', 'num_players', 'num_rounds', 'team_mode', 'num_team_members', 
               'difficulty', 'eligibility', 'sportsmanship', 'rank_id', 'num_cuts', 'team_mode', 
               {name: 'end_date', mapping: 'end_date', type: 'date', dateFormat:'Y-m-d'},
               {name: 'start_date', mapping: 'start_date', type: 'date', dateFormat:'Y-m-d'},
               'qualifier', 'private', 'prize', 'expired', 'points', 'max_players', 'sponsor', 'no_putt_assist', 'chip_green', 'cut_round', 'resumes', 'owner_id', 'num_requal', 'requal_penalty',
               'requal_multiplier', 'official', 'owner', 'user_id', 'status', 'requalifies'
            ]            
            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'end_date',
           header: "Dates",
           dataIndex: 'end_date',
           width: 90,
           renderer: renderLast
        },{
           id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Events",
           dataIndex: 'name',
           width: 180,
           renderer: renderEvent
        },{
           header: "Skill",
           dataIndex: 'difficulty',
           width: 50,
           align: 'left',
           renderer: renderEventsSkill
        },{
           header: "Swing",
           dataIndex: 'swing_typenew',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Rules",
           dataIndex: 'rules',
           width: 50,
           align: 'left',
           renderer: renderRules
        },{
           header: "Tour",
           dataIndex: 'tour_name',
           width: 60,
           align: 'left'
        },{
           header: "Rds",
           dataIndex: 'num_rounds',
           width: 35,
           align: 'left'
        },{
           header: "Players",
           dataIndex: 'num_players',
           width: 70,
           align: 'left',
           renderer: renderNumPlayers
        },{
           header: "Owner",
           dataIndex: 'owner',
           width: 105,
           hidden: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var tbar = null;
	tbar = [
        'Search for event name or owner: ', ' ',
        new Ext.app.SearchField({
            store: ds,
            width:300
        })
    ];
    
    var grid = new Ext.grid.GridPanel({
        applyTo:'current-events-grid',
        width:630,
        height:600,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: tbar,
        bbar: new Ext.PagingToolbar({
        	id: 'page-current-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying events {0} - {1} of {2}',
            emptyMsg: "No events to display"
        })
    });

    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}

LSPN.MainPage.prototype.setupAllEvents = function(respObj)
{
	this.previousEvents = true;
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getAllEvents'})),
    	    method: "POST",
    	    sortInfo : {field: "end_date", direction: "ASC"},
            remoteSort: true,
            baseParams: {league_id: all_league_id},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
                'swing_typenew', 'tees', 'holes', 'tour_name', 'event_id', 'tour_id', 'game', 'name', 'rules', 'num_players', 'num_rounds', 'team_mode', 'num_team_members', 
               'difficulty', 'eligibility', 'sportsmanship', 'rank_id', 'num_cuts', 'team_mode', 
               {name: 'end_date', mapping: 'end_date', type: 'date', dateFormat:'Y-m-d'},
               {name: 'start_date', mapping: 'start_date', type: 'date', dateFormat:'Y-m-d'},
               'qualifier', 'private', 'prize', 'expired', 'points', 'max_players', 'sponsor', 'no_putt_assist', 'chip_green', 'cut_round', 'resumes', 'owner_id', 'num_requal', 'requal_penalty',
               'requal_multiplier', 'official', 'owner', 'user_id', 'status', 'requalifies'
            ]            
            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           id: 'end_date',
           header: "Dates",
           dataIndex: 'end_date',
           width: 90,
           renderer: renderLast
        },{
           id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
           header: "Events",
           dataIndex: 'name',
           width: 180,
           renderer: renderEvent
        },{
           header: "Skill",
           dataIndex: 'difficulty',
           width: 50,
           align: 'left',
           renderer: renderEventsSkill
        },{
           header: "Swing",
           dataIndex: 'swing_typenew',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Rules",
           dataIndex: 'rules',
           width: 50,
           align: 'left',
           renderer: renderRules
        },{
           header: "Tour",
           dataIndex: 'tour_name',
           width: 60,
           align: 'left'
        },{
           header: "Rds",
           dataIndex: 'num_rounds',
           width: 35,
           align: 'left'
        },{
           header: "Players",
           dataIndex: 'num_players',
           width: 70,
           align: 'left',
           renderer: renderNumPlayers
        },{
           header: "Owner",
           dataIndex: 'owner',
           width: 105,
           hidden: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var tbar = null;
	tbar = [
        'Search for event name or owner: ', ' ',
        new Ext.app.SearchField({
            store: ds,
            width:300
        })
    ];
    
    var grid = new Ext.grid.GridPanel({
        applyTo:'current-events-grid',
        width:630,
        height:600,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: tbar,
        bbar: new Ext.PagingToolbar({
        	id: 'page-current-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying events {0} - {1} of {2}',
            emptyMsg: "No events to display"
        })
    });

    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}


LSPN.MainPage.prototype.showAllLeagues = function()
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getLeagueList'})),
    	    method: "POST",
    	    sortInfo : {field: "group_name", direction: "ASC"},
            remoteSort: true,
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
               'username', 'group_id', 'user_id', 'group_name', 'group_desc', 'group_url', 'group_difficulty', 'group_swing', 'group_game']            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           header: "Name",
           dataIndex: 'group_name',
           width: 175,
           renderer: renderDesc
        },{
           header: "Skill",
           dataIndex: 'group_difficulty',
           width: 50,
           align: 'left',
           renderer: renderLeagueSkill
        },{
           header: "Swing",
           dataIndex: 'group_swing',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Game",
           dataIndex: 'group_game',
           width: 75,
           align: 'left',
           renderer: renderGroupGame
        },{
           header: "Owner",
           dataIndex: 'username',
           width: 105,
           renderer: renderUsername
        },{
           header: "Action",
           dataIndex: 'username',
           width: 75,
           renderer: renderActions,
           sortable: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var grid = new Ext.grid.GridPanel({
        applyTo:'league-list-grid',
        width:630,
        height:600,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: [
            'Search for a league: ', ' ',
            new Ext.app.SearchField({
                store: ds,
                width:320
            })
        ],
        bbar: new Ext.PagingToolbar({
        	id: 'page-current-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying events {0} - {1} of {2}',
            emptyMsg: "No events to display"
        })
    });

    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}

LSPN.MainPage.prototype.showMyLeagues = function()
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getMyLeagueList'})),
    	    method: "POST",
    	    sortInfo : {field: "group_name", direction: "ASC"},
            remoteSort: true,
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: [
               'user_pending', 'group_id', 'group_owner', 'group_leader', 'user_id', 'username', 'group_name', 'group_desc', 'group_url', 'group_difficulty', 'group_swing', 'group_game']            
           })
    });
	            
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           header: "Name",
           dataIndex: 'group_name',
           width: 175,
           renderer: renderDesc
        },{
           header: "Position",
           dataIndex: 'user_pending',
           width: 50,
           renderer: renderPosition
        },{
           header: "Skill",
           dataIndex: 'group_difficulty',
           width: 50,
           align: 'left',
           renderer: renderLeagueSkill
        },{
           header: "Swing",
           dataIndex: 'group_swing',
           width: 50,
           align: 'left',
           renderer: renderEventsSwing
        },{
           header: "Game",
           dataIndex: 'group_game',
           width: 75,
           align: 'left',
           renderer: renderGroupGame
        },{
           header: "Action",
           dataIndex: 'group_leader',
           width: 75,
           renderer: renderMyActions,
           sortable: false
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    this.myleaguesgrid = new Ext.grid.GridPanel({
        applyTo:'myleague-list-grid',
        width:630,
        height:200,
        store: ds,
        cm: cm,
        trackMouseOver:false,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        }});

    // render it
    this.myleaguesgrid.render();

    // trigger the data store load
    ds.load();

}

LSPN.MainPage.prototype.askResign = function(league_id)
{
	this.resign_id = league_id;
    Ext.Msg.show({
       title:'Are you sure?',
       msg: 'Are you absolutely positive that you want to resign from this league? You will lose all forum and league privileges.',
       buttons: Ext.Msg.YESNOCANCEL,
       fn: createObjectCallback(this, this.resignMembership),
       icon: Ext.MessageBox.QUESTION
    });
}

LSPN.MainPage.prototype.resignMembership = function(answer)
{
	if (answer != 'yes')
		return;
		
    doAjaxRPC('resignMembership', {league_id: this.resign_id}, createObjectCallback(this, this.resignComplete), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.resignComplete = function()
{
	Ext.Msg.alert('Complete', 'You have been removed from the league');
	this.myleaguesgrid.store.reload();
}

LSPN.MainPage.prototype.askJoin = function(league_id)
{
	this.join_id = league_id;
    Ext.Msg.show({
       title:'Are you sure?',
       msg: 'Are you sure you want to apply to join this league?',
       buttons: Ext.Msg.YESNOCANCEL,
       fn: createObjectCallback(this, this.joinLeague),
       icon: Ext.MessageBox.QUESTION
    });
}

LSPN.MainPage.prototype.joinLeague = function(answer)
{
	if (answer != 'yes')
		return;
		
    doAjaxRPC('joinLeague', {league_id: this.join_id}, createObjectCallback(this, this.joinComplete), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.joinComplete = function()
{
	Ext.Msg.alert('Complete', 'You have applied for membership in the league. A league leader must appove your membership before you can participate in the league.');
	this.myleaguesgrid.store.reload();
}


LSPN.MainPage.prototype.initStrokeStats = function()
{
    doAjaxRPC('getStrokeStats', {type: g_type, user_id: g_user_id, swing: g_swing, skill: g_skill, game: g_game, league_id: g_league_id, season_id: g_season_id, tour_id: g_tour_id, event_id: g_event_id}, createObjectCallback(this, this.setupStrokeStats), createObjectCallback(this, this.failure));	
}

LSPN.MainPage.prototype.createStatsPropertyGrid = function(source, id, is_event)
{
	var prop = null;
	if (!is_event)
	{
	  	prop = new Ext.grid.PropertyGrid({
	  		applyTo: id,
	        title: g_type_str + ' Stats Summary',
	        height: 250,
	        width: 620,
	        source: {}
	    });
	}
	else
	{
	  	prop = new Ext.grid.PropertyGrid({
	  		applyTo: id,
	        title: g_type_str + ' Round Stats',
	        autoHeight: true,
	        width: 620,
	        source: {}
	    });
	}
    Ext.apply(prop.colModel.config[0], {header: 'Stat'});
    Ext.apply(prop.colModel.config[1], {header: 'Value'});
    
    prop.store.sortInfo = null; 
    
    prop.setSource(source);
	
    return prop;
}

LSPN.MainPage.prototype.setupKeyStats = function(stats)
{
	if (g_scoring_avg == undefined)
		return;
		
	this.keyStatScoringAvg(stats);
	this.keyStatPuttsPerRound(stats);
	this.keyStatDrivingDistance(stats);
	this.keyStatParSaves(stats);
	this.keyStatDrivingAccuracy(stats);
	this.keyStatGIR(stats);
}

LSPN.MainPage.prototype.keyStatParSaves = function(stats)
{
	var par_saves = stats["% Par Saves"];
		
	var width = (par_saves * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_par_saves');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_par_saves_text');
	if (obj)
	{
		obj.innerHTML = par_saves;
	}
	

	var width = (g_par_saves * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('tour_par_saves');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('tour_par_saves_text');
	if (obj)
	{
		obj.innerHTML = g_par_saves;
	}
}

LSPN.MainPage.prototype.keyStatDrivingAccuracy = function(stats)
{
	var accuracy = stats["% Drives in Fairway"];
		
	var width = (accuracy * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_accuracy');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_accuracy_text');
	if (obj)
	{
		obj.innerHTML = accuracy;
	}
	

	var width = (g_accuracy * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('tour_accuracy');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('tour_accuracy_text');
	if (obj)
	{
		obj.innerHTML = g_accuracy;
	}
}

LSPN.MainPage.prototype.keyStatGIR = function(stats)
{
	var gir = stats["% GIR"];
		
	var width = (gir * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_gir');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_gir_text');
	if (obj)
	{
		obj.innerHTML = gir;
	}
	

	var width = (g_gir * .01) * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('tour_gir');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('tour_gir_text');
	if (obj)
	{
		obj.innerHTML = g_gir;
	}
}



LSPN.MainPage.prototype.keyStatDrivingDistance = function(stats)
{
	stats["Yards Drove in Fairway"] = stats["Yards Drove in Fairway"].replace(/,/g, '');
	stats["# Drives in Fairway"] = stats["# Drives in Fairway"].replace(/,/g, '');

	var average_drive = (parseInt(stats["Yards Drove in Fairway"])/parseInt(stats["# Drives in Fairway"]));
	average_drive = average_drive.toFixed(2);
	var diff_best = Math.abs(g_distance_best - average_drive);
	var pct = 1;
	if (diff_best == 0)
		pct = 1;
	if (diff_best == g_distance_diff)
		pct = .01;
		
	var diff = g_distance_diff - diff_best;

	if (diff != 0)
		pct = diff / g_distance_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_driving_distance');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_driving_distance_text');
	if (obj)
	{
		obj.innerHTML = average_drive;
	}
	
	
	var diff_best = Math.abs(g_distance_best - g_driving_distance);
	var diff = g_distance_diff - diff_best;
	var pct = 1;
	if (diff != 0)
		pct = diff / g_distance_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;	
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('tour_driving_distance');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('tour_driving_distance_text');
	if (obj)
	{
		obj.innerHTML = g_driving_distance;
	}	
}


LSPN.MainPage.prototype.keyStatScoringAvg = function(stats)
{
	stats["Total Strokes"] = stats["Total Strokes"].replace(/,/g, '');
	stats["Total Rounds Played"] = stats["Total Rounds Played"].replace(/,/g, '');

	var average_score = (parseInt(stats["Total Strokes"])/parseInt(stats["Total Rounds Played"]));
	average_score = average_score.toFixed(2);
	var diff_best = Math.abs(average_score - g_scoring_best);
	var pct = 1;
	if (diff_best == 0)
		pct = 1;
	if (diff_best == g_scoring_diff)
		pct = .01;
		
	var diff = g_scoring_diff - diff_best;

	if (diff != 0)
		pct = diff / g_scoring_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_league_scoring_avg');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_league_scoring_avg_text');
	if (obj)
	{
		obj.innerHTML = average_score;
	}
	
	
	var diff_best = Math.abs(g_scoring_avg - g_scoring_best);
	var diff = g_scoring_diff - diff_best;
	var pct = 1;
	if (diff != 0)
		pct = diff / g_scoring_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;	
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('league_scoring_avg');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('league_scoring_avg_text');
	if (obj)
	{
		obj.innerHTML = g_scoring_avg;
	}	
}

LSPN.MainPage.prototype.keyStatPuttsPerRound = function(stats)
{
	stats["Total Putts"] = stats["Total Putts"].replace(/,/g, '');
	stats["Total Rounds Played"] = stats["Total Rounds Played"].replace(/,/g, '');
	var p1 = parseInt(stats["Total Putts"]);

	var p2 = parseInt(stats["Total Rounds Played"]);
	
	var putts_per_round = p1 / p2;
	
	putts_per_round = putts_per_round.toFixed(2);
	
	var diff_best = Math.abs(putts_per_round - g_putts_best);
	
	var pct = 1;
	if (diff_best == 0)
		pct = 1;
	if (diff_best == g_putts_diff)
		pct = .01;
		
	var diff = g_putts_diff - diff_best;

	if (diff != 0)
		pct = diff / g_putts_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('my_league_putts_per_round');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('my_league_putts_per_round_text');
	if (obj)
	{
		obj.innerHTML = putts_per_round;
	}
	
	var diff_best = Math.abs(g_putts_per_round - g_putts_best);
	var diff = g_putts_diff - diff_best;
	var pct = 1;
	if (diff != 0)
		pct = diff / g_putts_diff;
		
	var width = pct * 245;
	width = (width > 245) ? 245 : width;	
	width = (width < 0) ? 0 : width;

	var obj = document.getElementById('league_putts_per_round');
	if (obj)
	{
		obj.style.width = width;
	}
	var obj = document.getElementById('league_putts_per_round_text');
	if (obj)
	{
		obj.innerHTML = g_putts_per_round;
	}	
}


LSPN.MainPage.prototype.setupStrokeStats = function(respObj)
{
	var prop = null;
	var rpropall = null;
	var has_stats = false;
	
	if (g_type != 'event')
	{
		if (respObj.rows.stroke_stats)
		{
			prop = this.createStatsPropertyGrid(respObj.rows.stroke_stats, 'stroke-stats', false);
			var obj = document.getElementById('key-stats');
			if (obj)
				this.setupKeyStats(respObj.rows.stroke_stats);
			has_stats = true;
		}
	}
	else
	{
		if (respObj.rows[1])
		{
		    var tabs = new Ext.TabPanel({
		        title: 'Rounds',
		        applyTo: 'stroke-stats',
		        enableTabScroll:true,
		        defaults: {autoScroll:true}
		    });
		    
	        var data = respObj.rows;
	        var rprop = [];
	        if (data)
	        {
	            for (var i=0;i<4;i++)
	            {
	                var round = i + 1; 
	                if (data[round])
	                {           	
		                rprop[i] = this.createStatsPropertyGrid(data[round].stroke_stats, 'round-grid-'+round, true);
		
		                tabs.add({
		                    id: 'round-tab-'+round,
		                    title: 'Round ' + round,
		                    iconCls: 'tabs',
		                    items: [rprop[i]]
		                }).show();
		                has_stats = true;
	                }
	            }
	            
	            if (data.accumulated_stats)
	            {
		            var source = data.accumulated_stats.stroke_stats;
		            Ext.apply(source, data.accumulated_stats.computed_stats);
			        rpropall = this.createStatsPropertyGrid(source, 'round-grid-all', true);
			
			        tabs.add({
			            id: 'round-tab-all',
			            title: 'Total',
			            iconCls: 'tabs',
			            items: [rpropall]
			        }).show();
		            tabs.activate("round-tab-1");            
	            }
	        }

		
	        
	        tabs.doLayout();	    
	        for (var i=0;i<4;i++)
	        {
	        	if (rprop[i])
		        	rprop[i].render();
	        }
	        
	        if (rpropall)	
	        	rpropall.render();
	        	        
        }
        

	}

        if (!has_stats)
        {
		    panel = new Ext.Panel({
		        title: 'No Stats',
		        applyTo: 'stroke-stats',
		        enableTabScroll:true,
		        defaults: {autoScroll:true},
		        items: [{html:"No stats have been submitted for these filter settings", 		        bodyStyle: 'border: 0px; padding: 10px;'}]
		        
		    });
        }	
	
}

LSPN.MainPage.prototype.setupLeaguePoints = function()
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getLeagueRoster'})),
    	    method: "POST",
    	    sortInfo : {field: "username", direction: "ASC"},
            remoteSort: true,
            baseParams: {league_current_events: this.leagueCurrentEvents, use_league_id: this.useLeagueId},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: ["username","user_id","total","points"]
           })
    });
    
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           header: "Player",
           dataIndex: 'username',
           width: 90
        },{
           header: "Avg Points",
           dataIndex: 'points',
           width: 100,
           renderer: renderAvgPoints
        },{
           header: "Total Points",
           dataIndex: 'total',
           width: 100,
           align: 'left'
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var grid = new Ext.grid.GridPanel({
        applyTo:'roster-panel',
        width:300,
        height:200,
        store: ds,
        cm: cm,
        stripeRows: true,
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        }
    });

    grid.on('rowdblclick', this.showProfile, this);
    
    // render it
    grid.render();

    // trigger the data store load
    ds.load();

}


LSPN.MainPage.prototype.setupPoints = function()
{
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getPointsList'})),
    	    method: "POST",
    	    sortInfo : {field: "points", direction: "DESC"},
            remoteSort: true,
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: ["username","user_id","total","points","num_events"]
           })
    });
    
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([{
           header: "Player",
           dataIndex: 'username',
           width: 90
        },{
           header: "Avg Points",
           dataIndex: 'points',
           width: 100,
           renderer: renderAvgPoints
        },{
           header: "Total Points",
           dataIndex: 'total',
           width: 100,
           align: 'left'
        },{
           header: "# Events",
           dataIndex: 'num_events',
           width: 50,
           align: 'left'
        }]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var grid = new Ext.grid.GridPanel({
        applyTo:'stats-points-grid',
        width:630,
        height:300,
        store: ds,
        cm: cm,
        stripeRows: true,
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: [
            'Search for player: ', ' ',
            new Ext.app.SearchField({
                store: ds,
                width:320
            })
        ],
        bbar: new Ext.PagingToolbar({
        	id: 'page-current-events',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying players {0} - {1} of {2}',
            emptyMsg: "No players to display"
        })
    });

    grid.on('rowdblclick', this.showProfile, this);
    
    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}

LSPN.MainPage.prototype.showProfile = function(grid, rowIndex, colIndex, e)
{
    var selectionModel = grid.getSelectionModel(); 
    var record = selectionModel.getSelected();  
    var user_id = record.get('user_id');
    var str = "profile.php?user_id="+user_id; 
    if (this.useLeagueId)
    	str += "&league_id="+this.useLeagueId;
    
    str += "&type=career";
    
    if (record.get('swing_type'))
    	str += "&swing="+record.get('swing_type');
    if (record.get('game'))
    	str += "&game="+record.get('game');
    if (record.get('difficulty'))
    	str += "&difficulty="+record.get('difficulty');
    	
	window.location.href = str;
}

LSPN.MainPage.prototype.leaderboardShowProfile = function(grid, rowIndex, colIndex, e)
{
    var selectionModel = grid.getSelectionModel(); 
    var record = selectionModel.getSelected();  
    var type = "event";
    var user_id = record.get('user_id');
    var game = record.get('game_id');    
    var event_id = this.event_id;
    var swing = record.get('swing_type');
	window.location.href = "profile.php?user_id="+user_id+"&type="+type+"&swing="+swing+"&game="+game+"&season_id=0&tour_id=0&event_id="+event_id;
}


function toggleDetails(btn, pressed){
    var grid = Ext.getCmp('current-events-grid');
    var view = grid.getView();
    view.showPreview = pressed;
    view.refresh();
}

function addTab(tabs, config){
	if (tabs && config)
    	tabs.add(config).show();
}

function renderEvent(value, p, record){
    return String.format(
            '<b><a href="javascript:mainPage.showFullLeaderboard({1}, \'{0}\')">{0}</a></b><br/><a href="javascript:mainPage.showConditions({1}, false);">View Courses & Conditions</a>',
            record.data.name, record.data.event_id);
}

function renderDesc(value, p, record){
    return String.format(
            '<b><a href="league_detail.php?league_id={0}" target="_new">{1}</a></b><br/>{2}',
            record.data.group_id, record.data.group_name, record.data.group_desc);
}

function renderMyActions(value, p, record)
{
	str = '';
	if (record.data.group_leader == 1)
		str += '<a href="league_admin/?league_id='+record.data.group_id+'">[Admin]<br/>';

	if (record.data.group_owner == 0)
		str += '<a href="javascript: mainPage.askResign('+record.data.group_id+');">[Resign]<br/>';
		
	return str;
}

function renderActions(value, p, record){
	if (can_join)
		str = '<a href="javascript: mainPage.askJoin('+record.data.group_id+');">[Apply]<br/>';
	else
		str = "None Available";
		
	return str;
}

function renderPosition(value, metadata, record, rowIndex, colIndex, store)
{
	if (value == "1")
		value = '<img src="/ext2/examples/shared/icons/fam/flag_red.png" title="Membership Pending"/>';
	else
	{
	    leader = record.get("group_leader");
	    owner = record.get("group_owner");
	    
	    if (leader == "0" && owner == "0")
			value = '<img src="/ext2/examples/shared/icons/fam/flag_green.png" title="League Member"/>';    
	
	    if (leader == "1" && owner =="0")
			value = '<img src="/ext2/examples/shared/icons/fam/key.png" title="League Leader"/>';    
			
	    if (owner == "1")
			value = '<img src="/ext2/examples/shared/icons/fam/award_star_gold_1.png" title="League Owner"/>';    
	}		
    return value;
    
}



function renderMyEventStatus(value, p, record)
{
	var str = getEnumText(LSPN.enums.leaderboard_status, value);
	if (value == 4 && record.data.num_requal > 0)
	{
		str += '<br/><a href="requalify.php?event_id='+record.data.event_id+'" style="color: #c00">Requalifiy</a>';
	}
	
	return str;
}


function renderGame(value, p, record){
	return getEnumText(LSPN.enums.games, value);
	return value;
}

function renderGroupGame(value, p, record){
	return getEnumText(LSPN.enums.league_games, value);
	return value;
}


function renderUsername(value, p, record){
    return String.format(
            '<b><a href="profile.php?user_id={0}">{1}</a>',
            record.data.user_id, record.data.username);
}


function renderScheduleEvent(value, p, record){
    return String.format(
            '<b>{0}</b><br/><a href="javascript:mainPage.showConditions({1}, true);">View Courses</a>',
            record.data.name, record.data.event_id);
}

function renderLast(value, p, r){
    return String.format('{0}<br/>{1}', r.data['start_date'].dateFormat('D, M j') +' to', value.dateFormat('D, M j'));
}

function renderNumPlayers(value, p, r){
    return String.format('{0}/{1}', value, r.data['max_players']);
}

// ===== skill level =====    
LSPN.enums.difficulty = [
    [2, 'Amateur'],
    [1, 'Pro'],
	[0, 'Champ'],
    [3, 'Elite']
];

LSPN.enums.stats_difficulty = [
    [0, 'Amateur'],
    [1, 'Pro'],
	[2, 'Champ'],
    [3, 'Elite']
];


LSPN.stores.stats_difficulty = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.stats_difficulty
}); 

LSPN.enums.difficulty.order = [
    [2],
    [1],
    [0],
    [3]
];


// ===== leaderboard status =====    
LSPN.enums.leaderboard_status = [
    [0, 'Entered'],
    [1, 'Playing'],
    [2, 'Completed Round'],
    [3, 'Finished Event'],
    [4, 'Disqualified'],
    [5, 'Cut'],
    [6, 'Incomplete'],
    [7, 'Not Playing'],
    [8, 'Requalified'],
    [9, 'Viewing']
];

LSPN.stores.leaderboard_status = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.leaderboard_status
});  


LSPN.stores.difficulty = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.difficulty
}); 

LSPN.enums.swing_types = [
        [1, 'C'],
        [2, 'PS'],
        [3, 'RTS']
];

LSPN.enums.swing_full_names = [
        [4, 'Any Swing'],
		[2, 'Classic Swing'],
        [1, 'PowerStroke'],
        [5, 'Real Time Swing']
];

LSPN.enums.swing_no_any = [
		[2, 'Classic Swing'],
        [1, 'PowerStroke'],
        [5, 'Real Time Swing']
];

LSPN.enums.stats_swing = [
        [1, 'Classic Swing'],
        [2, 'PowerStroke'],
        [3, 'Real Time Swing']
];

LSPN.stores.full_swing_types = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.swing_full_names
});  

LSPN.stores.swing_no_any = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.swing_no_any
});  

LSPN.stores.swing_types = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.swing_types
});  

LSPN.stores.stats_swing = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.stats_swing
});  


LSPN.stores.rules = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.rules
});  

LSPN.enums.rules = [
        [0, 'Stroke'],
        [1, 'Handicap'],
        [2, 'Stroke with Cuts'],
        [3, 'Match Play'],
        [4, 'Classic Stableford'],
        [5, 'British Stableford'],
        [6, 'Spanish Stableford']
];

LSPN.enums.current_rules = [
        [0, 'Stroke'],
        [4, 'Classic Stableford'],
        [5, 'British Stableford'],
        [6, 'Spanish Stableford']
];

LSPN.stores.current_rules = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.current_rules
});  

LSPN.enums.challenge_rules = [
        [0, 'Stroke'],
        [3, 'Match Play'],
        [4, 'Classic Stableford'],
        [5, 'British Stableford'],
        [6, 'Spanish Stableford']
];

LSPN.stores.challenge_rules = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.challenge_rules
});  


LSPN.enums.view_stats = [
        ['career', 'Career'],
        ['season', 'Season'],
        ['tour', 'Tour'],
        ['event', 'Event']
];

LSPN.stores.view_stats = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.view_stats
});  

LSPN.enums.games = [
        ['l2k3', 'Links 2003'],
        ['l2k1', 'Links 2001']
];

LSPN.stores.games = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.games
});  

LSPN.enums.swing = [
        [4, 'Any Swing'],
		[2, 'Classic Swing'],
        [5, 'Real Time Swing'],
        [1, 'PowerStroke']
];


LSPN.stores.swing = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.swing
});

LSPN.enums.challenge_type = [
        [0, 'MatchPlay'],
		[1, 'Best Score']
];

LSPN.stores.challenge_type = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.challenge_type
});

LSPN.enums.duration = [
        [1, 1],
		[2, 2],
        [3, 3],
        [4, 4],
        [5, 5],
        [6, 6],
        [7, 7],
        [8, 8],
        [9, 9],
        [10, 10],
        [11, 11],
        [12, 12],
        [13, 13],
        [14, 14]
];


LSPN.stores.duration = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.duration
});

LSPN.enums.requals = [
		[0, 0],
        [1, 1],
		[2, 2],
        [3, 3],
        [4, 4],
        [5, 5],
        [6, 6],
        [7, 7],
        [8, 8]
];


LSPN.stores.requals = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.requals
});

LSPN.enums.requal_penalty = [
		[0, 0],
        [1, 1],
		[2, 2],
        [3, 3],
        [4, 4],
        [5, 5],
        [6, 6],
        [7, 7],
        [8, 8]
];


LSPN.stores.requal_penalty = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.requal_penalty
});

LSPN.enums.yesno = [
		[0, 'No'],
        [1, 'Yes']
];


LSPN.stores.yesno = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.yesno
});


LSPN.enums.max_players = [
		[2, 2],
        [4, 4],
        [8, 8],
        [16, 16],
        [32, 32],
        [64, 64]
];


LSPN.stores.max_players = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.max_players
});

LSPN.enums.prefs = {
	ALL:0,
	LEAGUE: 1,	
	ARCADE:2,	
	LSPN:4,
	CLASSIC_SWING:8,
	PS_SWING:16,
	RTS_SWING:32,
	AMATEUR:64,
	PRO:128,
	CHAMP:256,
	ELITE:512,
	L2K3:1024,
	L2K1:4096,
	BACK:8192,
	MIDDLE:16384,
	FORWARD:32768,
	JUNIOR:65536,
	LADIES:131072,
	ALL18:262144,
	FRONT9:524288,
	BACK9:1048576,
	FREE:2097152
};

LSPN.enums.difficulty_league = [
    [4, 'Any Level'],
	[2, 'Amateur'],
    [1, 'Pro'],
	[0, 'Champ'],
    [3, 'Elite']
];

LSPN.stores.difficulty_league = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.difficulty_league
}); 

if (is_logged_in)
{
	LSPN.stores.courses = new Ext.data.Store({
	        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getCourseComboList'})),
	        	    method: "POST",
	        	    baseParams: {game: 'l2k3'},
	                remoteSort: true,
		            reader: new Ext.data.JsonReader({
		            root: 'rows'
	               }, ['course_id', 'name'] )
	            });
	

	
	LSPN.stores.courses2k1 = new Ext.data.Store({
	        	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getCourseComboList'})),
	        	    baseParams: {game: 'l2k1'},
	        	    method: "POST",
	                remoteSort: true,
		            reader: new Ext.data.JsonReader({
		            root: 'rows'
	               }, ['course_id', 'name'] )
	            });
	
	
}



LSPN.enums.k3swing = [
        [4, 'Any Swing'],
		[2, 'Classic Swing'],
        [5, 'Real Time Swing'],
        [1, 'PowerStroke']
];


LSPN.stores.k3swing = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.k3swing
});

LSPN.enums.k1swing = [
        [2, 'Any Swing'],
		[1, 'Classic Swing'],
        [3, 'PowerStroke']
];


LSPN.stores.k1swing = new Ext.data.SimpleStore({
    fields: ['num', 'name'],
    data : LSPN.enums.k1swing
});

LSPN.enums.k3short = [
        [2, 'C'],
        [1, 'PS'],
        [5, 'RTS'],
        [4, 'Any']
];

LSPN.enums.k1short = [
        [1, 'C'],
        [2, 'Any'],
        [3, 'PS']
];

LSPN.enums.league_games = [
        ['l2k3', 'Links 2003'],
        ['l2k1', 'Links 2001'],
        ['anygame', 'Links 2001 & 2003']
];

LSPN.stores.league_games = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.league_games
});
/// <summary>
/// Used for stand alone ajax calls
/// </summary>
function doAjaxRPC(method, params, success, failure)
{
    var ajax = new JayRock.RpcConnection({
        url:RPC_URL, 
        rpcMethod:method,
        params: params,
        success: goodRpcRequest,
        failure: badRpcRequest,
        successCB: success,
        failureCB: failure
    });
    ajax.request();
}

/// <summary>
/// RPC Success function
/// </summary>
function goodRpcRequest(resp, conn){
    var o = eval("("+resp.responseText+")");
    if (o.success === undefined)
    {
        alert("Json Service Failed: " + resp.responseText);
        return;
    }
    
    if (o.success)
        conn.successCB(o);
    else
    {
    	if (o.errors)
			conn.failureCB(o.errors);
		else
			conn.failureCB(o);
    }
}

/// <summary>
/// RPC Failure function
/// </summary>
function badRpcRequest(resp, conn){
    var o = eval("("+resp.responseText+")");
    alert(var_dump(o));
}



/// <summary>
/// Makes life much easier when using callback functions in OOP Javascript
/// Works like PHP var_dump function.
/// </summary>

function createObjectCallback(obj, fn)
{
    return function() { fn.apply(obj, arguments); };
}

function renderLeaderboardSkill(value, metadata, record, rowIndex, colIndex, store)
{
    title = getEnumText(LSPN.enums.difficulty, value);
    value = '<img src="images/icons/skill_'+value+'.gif" title="'+title+'"/>';
    return value;
}

function renderEventsSkill(value, metadata, record, rowIndex, colIndex, store)
{
    title = getEnumText(LSPN.enums.difficulty, value);
    
	if (value == 2)
		value = 0;
	else if (value == 0)
		value = 2;
		

    value = '<img src="images/icons/skill_'+value+'.gif" title="'+title+'"/>';
    return value;
}

function renderLeagueSkill(value, metadata, record, rowIndex, colIndex, store)
{
    title = getEnumText(LSPN.enums.difficulty_league, value);
    
	if (value == 2)
		value = 0;
	else if (value == 0)
		value = 2;
		

    value = '<img src="images/icons/skill_'+value+'.gif" title="'+title+'"/>';
    return value;
}

function renderRules(value, metadata, record, rowIndex, colIndex, store)
{
    title = getEnumText(LSPN.enums.rules, value);
    value = '<img src="images/icons/rules_'+value+'.gif" title="'+title+'"/>';
    return value;
}

function renderEventsSwing(value, metadata, record, rowIndex, colIndex, store)
{
	if (value)
	{
		//alert(record.get("game"));
		if (record.get("game") == "l2k1")
		{
			if (value == 3) //l2k1 PS
				value = 1;
			else if (value == 1)
				value = 2;
			else if (value == 2)
				value = 4;
		}		
		
		
		
    	title = getEnumText(LSPN.enums.swing_full_names, value);
    	value = '<img src="/images/icons/swing_'+value+'.gif" title="'+title+'"/>';
	}
    else
    {
    	value = "N/A";
    }	
    return value;
}

function renderLeaderboardSwing(value, metadata, record, rowIndex, colIndex, store)
{
	if (!value)
	{
		value = "N/A";
	}
	else
	{
		// re order swings based on difference between event values and leaderboard values
		if (value == 1)
			value = 2;
		else if (value == 2)
			value = 1;
		else if (value == 3)
			value = 5;

    	title = getEnumText(LSPN.enums.swing_full_names, value);
    	value = '<img src="images/icons/swing_'+value+'.gif" title="'+title+'"/>';
	}
    return value;
}



function renderScore(value, metadata, record, rowIndex, colIndex, store)
{
	if (value == 999)
    	value = "N/A";
    	
    return value;
}

function showMe(value, metadata, record, rowIndex, colIndex, store)
{
	if (record.get("user_id") == my_user_id)
		metadata.css = 'lb_highlighted';
		
	return value;
}

function renderThru(value, metadata, record, rowIndex, colIndex, store)
{
    round = record.get("current_round");
    hole = record.get("current_hole");
    str = "R"+round+"H"+hole;
    return str;
    
}

function renderAvgPoints(value, metadata, record, rowIndex, colIndex, store)
{
	value=Math.round(value*100)/100;
    return value;
    
}

function getEnumValue(enm, text)
{
    return getEnumValueOrText(enm, text, true);
}



function getEnumValueOrText(enm, find, bWantValue)
{
    var val = null;
    for (var i=0;i<enm.length;i++)
    {
        match = enm[i][0];
        ret_val = enm[i][1];
        if (bWantValue)
        {
            match = enm[i][1];
            ret_val = enm[i][0];
        }
            
        if (match == find)
        {
            val = ret_val;
            break;
        }
    }
    return val;
}

function getEnumText(enm, text)
{
    return getEnumValueOrText(enm, text, false);
}

function var_dump(data,addwhitespace,safety,level) {
    var rtrn = '';
    var dt,it,spaces = '';
    if(!level) {level = 1;}
    for(var i=0; i<level; i++) {
       spaces += '   ';
    }//end for i<level
    if(typeof(data) != 'object') {
       dt = data;
       if(typeof(data) == 'string') {
          if(addwhitespace == 'html') {
             dt = dt.replace(/&/g,'&amp;');
             dt = dt.replace(/>/g,'&gt;');
             dt = dt.replace(/</g,'&lt;');
          }//end if addwhitespace == html
          dt = dt.replace(/\"/g,'\"');
          dt = '"' + dt + '"';
       }//end if typeof == string
       if(typeof(data) == 'function' && addwhitespace) {
          dt = new String(dt).replace(/\n/g,"\n"+spaces);
          if(addwhitespace == 'html') {
             dt = dt.replace(/&/g,'&amp;');
             dt = dt.replace(/>/g,'&gt;');
             dt = dt.replace(/</g,'&lt;');
          }//end if addwhitespace == html
       }//end if typeof == function
       if(typeof(data) == 'undefined') {
          dt = 'undefined';
       }//end if typeof == undefined
       if(addwhitespace == 'html') {
          if(typeof(dt) != 'string') {
             dt = new String(dt);
          }//end typeof != string
          dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
       }//end if addwhitespace == html
       return dt;
    }//end if typeof != object && != array
    for (var x in data) {
       if(safety && (level > safety)) {
          dt = '*RECURSION*';
       } else {
          try {
             dt = var_dump(data[x],addwhitespace,safety,level+1);
          } catch (e) {continue;}
       }//end if-else level > safety
       it = var_dump(x,addwhitespace,safety,level+1);
       rtrn += it + ':' + dt + ',';
       if(addwhitespace) {
          rtrn += '\n'+spaces;
       }//end if addwhitespace
    }//end for...in
    if(addwhitespace) {
       rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
    } else {
       rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
    }//end if-else addwhitespace
    if(addwhitespace == 'html') {
       rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
    }//end if addwhitespace == html
    return rtrn;
}//end function var_dump

LSPN.enums.pins = [
		[3, 'Custom'],
        [0, 'Easy'],
        [1, 'Moderate'],
        [2, 'Difficult']
];

LSPN.stores.pins = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.pins
}); 

LSPN.enums.mulligans = [
        [0, 'None'],
        [1, 1],
        [2, 2],
        [3, 3],
        [4, 4],
        [5, 5],
        [10, 10],
        [15, 15],
        [20, 20]
];

LSPN.stores.mulligans = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.mulligans
}); 

LSPN.enums.crowds = [
        [0, 'None'],
        [1, 'Small'],
        [2, 'Medium'],
        [3, 'Large']
];

LSPN.stores.crowds = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.crowds
}); 

// ===== green speed =====
LSPN.enums.speed = [
        [0, 'Slow'],
        [1, 'Medium'],
        [2, 'Fast'],
        [3, 'Slow(Challenging)'],
        [4, 'Medium(Challenging)'],
        [5, 'Fast(Challenging)'],
        [6, 'Course Speed']
];

LSPN.stores.speed = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.speed
}); 

// ===== hardness for greens and fairway =====
LSPN.enums.hardness = [
        [0, 'Soft'],
        [1, 'Medium'],
        [2, 'Firm'],
        [3, 'Soft(Challenging)'],
        [4, 'Medium(Challenging)'],
        [5, 'Firm(Challenging)'],
        [6, 'Course Hardness']
        
];

LSPN.stores.hardness = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.hardness
}); 

// ===== hardness for greens and fairway =====
LSPN.enums.holes = [
        [0, 'All 18'],
        [1, 'Front 9'],
        [2, 'Back 9']
];

LSPN.stores.holes = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.holes
}); 

// ===== hardness for greens and fairway =====
LSPN.enums.gimme_range = [
        [0, 'None'],
        [6, '6 inches'],
        [12, '12 inches'],
        [24, '2 feet'],
        [48, '4 feet']
];

LSPN.stores.gimme_range = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.gimme_range
}); 

// ===== hardness for greens and fairway =====
LSPN.enums.tees = [
        [0, 'Back'],
        [1, 'Middle'],
        [2, 'Front'],
        [3, 'Junior'],
        [4, 'Ladies'],
        [5, 'Custom']
];

LSPN.stores.tees = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.tees
}); 


// ===== wind conditions =====
LSPN.enums.wind = [
        [0, 'None'],
        [1, 'Breezy'],
        [2, 'Windy'],
        [3, 'Gusty']
];

LSPN.stores.wind = new Ext.data.SimpleStore({
        fields: ['num', 'name'],
        data : LSPN.enums.wind
}); 

/// <summary>
/// Addition to TabPanel to remove all tabs from a tab panel
/// </summary>
Ext.TabPanel.prototype.clearTabs = function()
{
    var num_tabs = this.items.items.length;
    var ids = [];    
    for (var i=0;i<num_tabs;i++)
    {
        ids[i] = this.items.items[i].id;
    }  
    for (var i=0;i<ids.length;i++)
        this.remove(ids[i]);
}

/// <summary>
/// Addition to TabPanel to return total tab count
/// </summary>
Ext.TabPanel.prototype.getTabCount = function()
{
    var count = 0;
    if (this.items)
    {   
        if (this.items.items)
            count = this.items.items.length;
    }
    return count;
}

function randomnumber(num1, num2)
{
	num1 = parseInt(num1);
	num2 = parseInt(num2);
	generator = 0;
	if(num1 >= num2)
	{
		alert("Number 2 should be greater than Number 1");
	}
	else
	{
		var generator = Math.random()*(num2-num1);
		generator = Math.round(num1+generator);
	}
	return generator;
}

/// <summary>
/// Verify a property can be edited before allowing a change
/// </summary>
LSPN.MainPage.prototype.beforeRoundEdit = function(e)
{
	var name = e.record.data.name;
    if(name == "Round" ||
    	name == "Course Key" ||
    	name == "Course ID")
        e.cancel = true;
        
}

/// <summary>
/// Validation for editing a round property
/// </summary>
LSPN.MainPage.prototype.validateRoundEdit = function(e)
{
	var name = e.record.data.name;
	if (name == "Pin Positions (18 Holes, Positions from 0 - 17)")
	{
		var arr = e.value.split(",");
		if (arr.length != 18)
		{
			 Ext.Msg.alert('Error', 'Please make sure you have all 18 holes set. Even if the round only requires 9 holes. You can set the holes on the front or back 9 to 0 if only using 9 holes');
			 e.cancel = true;
		}
        if (!checkpins(e.value))
        {
        	Ext.Msg.alert('Error', 'Please check the pin positions. That value must be comprised of numbers 0 - 17 and commas only');  
        	e.cancel = true;
        }   		
	}
	
	if (name == 'Tees - if Custom (18 Holes - B,M,F,J,L)')
	{
		var arr = e.value.split(",");
		if (arr.length != 18)
		{
			 Ext.Msg.alert('Error', 'Please make sure you have all 18 holes set. Even if the round only requires 9 holes. You can set the holes on the front or back 9 to 0 if only using 9 holes');
			 e.cancel = true;
		}
        if (!checktees(e.value))
        {
        	Ext.Msg.alert('Error', 'Please check the custom tees. That value must be comprised of the letters b,m,f,l, or j and commas only');  
        	e.cancel = true;
        }     		
	}   
	
}

function checkpins(pins) {
  var re = /\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2},\d{1,2}/;
  if (pins.match(re)) {
    return true;
  } else {
    return false;
  }
}

function checktees(tees) {
  var re = /(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1},(b|f|m|j|l|B|F|M|J|L){1}$/;
  if (tees.match(re)) {
    return true;
  } else {
    return false;
  }
}

LSPN.MainPage.prototype.deleteRound = function()
{
    var round_tabs = Ext.getCmp('round-tabs');
    var num_rounds = round_tabs.getTabCount();
	if (num_rounds == 1)
	{
		Ext.Msg.alert('Cannot Remove Round', 'There must be at least 1 round for an event.');    
		return;
	}
	
    this.delete_round = null;
    
    if (round_tabs)
    {
        this.delete_round = round_tabs.getActiveTab();
        
    }    
    
    if (!this.delete_round)
    {
        Ext.Msg.alert('Select Round', 'Please select a round tab to delete.');    
        return;
    }
    
    Ext.Msg.show({
       title:'Delete?',
       msg: 'Are you sure you want to delete the selected round? This will reorder the remaining rounds',
       buttons: Ext.Msg.YESNOCANCEL,
       fn: createObjectCallback(this, this.doDeleteRound),
       icon: Ext.MessageBox.QUESTION
    });
}

/// <summary>
/// Does the RPC call to the delete the round from the database
/// </summary>
LSPN.MainPage.prototype.doDeleteRound = function(answer)
{
    if (answer != 'yes')
        return;  
          
 	var round_tabs = Ext.getCmp('round-tabs');
    round_tabs.remove(this.delete_round);

	var current_round = 1;
	    	
	for (var i=0; i<last_tab;i++)
	{
		var obj = Ext.getCmp('round-tab-'+i);
		if (obj)
		{
			obj.setTitle("Round "+current_round);
			current_round++;
			//obj.rendered = false;
		}
	}

//	round_tabs.doLayout();
	//round_tabs.render();
}

LSPN.MainPage.prototype.checkArcadeEvent = function()
{
	if (!this.arcadeForm.form.isValid())
	{
		Ext.Msg.alert('Errors', 'Please correct items highlighted in red.');    
		return;
	}
	
	var title = this.arcadeForm.findById('arcade-title').getValue();
	
	if (title.indexOf("'") > -1 || title.indexOf('"') > -1)
	{
		Ext.Msg.alert('Errors', 'Please do not use apostrophes or quotation marks in the title.');    
		return;
	}
	
	
	var game = this.arcadeForm.findById('arcade-game').getValue();
	var start_date = this.arcadeForm.findById('arcade-start-date').getValue();
	var duration = this.arcadeForm.findById('arcade-duration').getValue();
	var rules = this.arcadeForm.findById('arcade-rules').getValue();
	var max_players = this.arcadeForm.findById('arcade-max-players').getValue();
	var skill = this.arcadeForm.findById('arcade-skill').getValue();
	var swing_type = this.arcadeForm.findById('arcade-swing-type').getValue();
	var putt_assist = this.arcadeForm.findById('arcade-putt-assist').getValue();
	var chip_green = this.arcadeForm.findById('arcade-chip-green').getValue();
	var requal = this.arcadeForm.findById('arcade-requal').getValue();
	var requal_penalty = this.arcadeForm.findById('arcade-requal-penalty').getValue();
	var requal_multiplier = this.arcadeForm.findById('arcade-requal-multiplier').getValue();

	
    var now = new Date();
    now.setDate(now.getDate()-1);
    now.setHours(23);
    now.setMinutes(59);
    now.setSeconds(59);
    if (start_date < now)
    {
    	Ext.Msg.alert('Error', 'The event must occur start at a future date.');    
    	return;
    }
	

	if (game == 'l2k1')
	{
		if (skill == 3)
		{
	    	Ext.Msg.alert('Error', 'The Elite skill level is not supported in Links 2001');    
	    	return;
		}
		
		if (swing_type == 2)
			swing_type = 1
		else if (swing_type == 1)
			swing_type = 3;
		else if (swing_type == 4)
			swing_type = 2;
		else if (swing_type == 5)
		{
	    	Ext.Msg.alert('Error', 'Real Time Swing is not supported in Links 2001');    
	    	return;
		}
	}    
    
	var round_data = this.checkArcadeRounds(rules);
	
	if (!round_data)
		return;
	


   
   
    // we need to convert the params from pretty print
    // to the parameters expected by the RPC
    
    var real_params = {
        name: title,
        game: game,
        start_date: start_date,
        duration: duration,
        rules: rules,
        max_players: max_players,
        difficulty: skill,
        no_putt_assist: !putt_assist,
        chip_green: chip_green,
        num_requal : requal,
        requal_penalty : requal_penalty,
        requal_multiplier : requal_multiplier,
        swing_typenew : swing_type,
        rounds: round_data
    };
    doAjaxRPC('saveArcadeEvent', real_params, createObjectCallback(this, this.saveArcadeComplete), createObjectCallback(this, this.saveArcadeFailure));
    
}

LSPN.MainPage.prototype.checkChallengeEvent = function()
{
	if (!this.challengeEventForm.form.isValid())
	{
		Ext.Msg.alert('Errors', 'Please correct items highlighted in red.');    
		return;
	}
	
	var title = this.challengeEventForm.findById('challenge-title').getValue();
	
	if (title.indexOf("'") > -1 || title.indexOf('"') > -1)
	{
		Ext.Msg.alert('Errors', 'Please do not use apostrophes or quotation marks in the title.');    
		return;
	}
	
	
	var game = this.challengeEventForm.findById('challenge-game').getValue();
	var start_date = this.challengeEventForm.findById('challenge-start-date').getValue();
	var duration = this.challengeEventForm.findById('challenge-duration').getValue();
	var rules = this.challengeEventForm.findById('challenge-rules').getValue();
	var skill = this.challengeEventForm.findById('challenge-skill').getValue();
	var swing_type = this.challengeEventForm.findById('challenge-swing-type').getValue();
	var putt_assist = this.challengeEventForm.findById('challenge-putt-assist').getValue();
	var chip_green = this.challengeEventForm.findById('challenge-chip-green').getValue();
	var requal = this.challengeEventForm.findById('challenge-requal').getValue();
	var requal_penalty = this.challengeEventForm.findById('challenge-requal-penalty').getValue();
	var requal_multiplier = this.challengeEventForm.findById('challenge-requal-multiplier').getValue();
	var h2h = this.challengeEventForm.findById('challenge-h2h').getValue();

    var now = new Date();
    now.setDate(now.getDate()-1);
    now.setHours(23);
    now.setMinutes(59);
    now.setSeconds(59);
    if (start_date < now)
    {
    	Ext.Msg.alert('Error', 'The event must occur start at a future date.');    
    	return;
    }
	

	if (game == 'l2k1')
	{
		if (skill == 3)
		{
	    	Ext.Msg.alert('Error', 'The Elite skill level is not supported in Links 2001');    
	    	return;
		}
		
		if (swing_type == 2)
			swing_type = 1
		else if (swing_type == 1)
			swing_type = 3;
		else if (swing_type == 4)
			swing_type = 2;
		else if (swing_type == 5)
		{
	    	Ext.Msg.alert('Error', 'Real Time Swing is not supported in Links 2001');    
	    	return;
		}
	}    
    
	var round_data = this.checkChallengeRounds(rules);
	
	if (!round_data)
		return;
	


   
   
    // we need to convert the params from pretty print
    // to the parameters expected by the RPC
    
    var real_params = {
        name: title,
        game: game,
        start_date: start_date,
        duration: duration,
        rules: rules,
        difficulty: skill,
        no_putt_assist: !putt_assist,
        chip_green: chip_green,
        num_requal : requal,
        requal_penalty : requal_penalty,
        requal_multiplier : requal_multiplier,
        swing_typenew : swing_type,
        rounds: round_data,
        opponent_id: opponent_id,
        h2h:h2h
    };
    doAjaxRPC('saveChallengeEvent', real_params, createObjectCallback(this, this.saveChallengeComplete), createObjectCallback(this, this.saveArcadeFailure));
    
}


LSPN.MainPage.prototype.saveArcadeComplete = function(respObj)
{
    Ext.Msg.show({
       title:'Save Complete',
       msg: 'The changes were saved successfully',
       buttons: Ext.Msg.OK,
       fn: createObjectCallback(this, this.loadHomePage),
       icon: Ext.MessageBox.INFO
    });
}


LSPN.MainPage.prototype.saveChallengeComplete = function(respObj)
{
    Ext.Msg.show({
       title:'Save Complete',
       msg: 'The changes were saved successfully',
       buttons: Ext.Msg.OK,
       fn: createObjectCallback(this, this.loadMatchPlay),
       icon: Ext.MessageBox.INFO
    });
}

LSPN.MainPage.prototype.loadMatchPlay = function()
{
	window.location.href = "/matchplay.php";
}


LSPN.MainPage.prototype.loadHomePage = function()
{
	window.location.href = "/";
}

LSPN.MainPage.prototype.saveArcadeFailure = function(errors)
{
    Ext.Msg.alert('Message', errors);    
}


LSPN.MainPage.prototype.checkArcadeRounds = function(rules)
{
    var round_tabs = Ext.getCmp('round-tabs');
    var num_rounds = round_tabs.getTabCount();
    var rounds = {};
    j=0;
    for (var i=0;i<=last_tab;i++)
    {
        var round_tab = Ext.getCmp('round-tab-'+i);
        if (round_tab)
        {
        	
			var round = j+1;
            var rprop = round_tab.items.items[0];
            data = rprop.getSource();
            if (data['Course Key'] == '')
            {
            	Ext.Msg.alert('Error', 'Please select a course for round '+round+".");  
            	return null;
            }
            if (!checkpins(data['Pin Positions (18 Holes, Positions from 0 - 17)']))
            {
            	Ext.Msg.alert('Error', 'Please check the pin positions for round '+round+". That value must be comprised of numbers from 0 - 17 and commas only");  
            	return null;
            }            
            
            var f9 = 0;
            var b9 = 0;
            if (parseInt(rules) == 6)
            {
            	var f9 = data['Joker Front 9 (Spanish Stableford)'];
            	var b9 = data['Joker Back 9 (Spanish Stableford)']
            	if (parseInt(f9) < 1 || parseInt(f9) > 9)
            	{
            		Ext.Msg.alert('Error', 'The Joker hole for the Front 9 must be between 1 and 9 on round '+round);  
            		return null;
            	}
            	if (parseInt(b9) < 10 || parseInt(b9) > 18)
            	{
            		Ext.Msg.alert('Error', 'The Joker hole for the Back 9 must be between 10 and 18 on round '+round);  
            		return null;
            	}
            	
            }
			rounds[j] = {};
            rounds[j]["allow_caddie"] = (data['Caddie Allowed'] == true ? 1: 0);            
            rounds[j]["course_key"] = data['Course Key'];
            rounds[j]["crowd_size"] = getEnumValue(LSPN.enums.crowds, data['Crowds']);
            rounds[j]["gimme_range"] = data['Gimme Range'];
            rounds[j]["green_hardness"] = getEnumValue(LSPN.enums.hardness, data['Green Hardness']);            
            rounds[j]["green_speed"] = getEnumValue(LSPN.enums.speed, data['Green Speed']);            
            rounds[j]["allow_grid"] = (data['Grid Allowed'] == true ? 1: 0);
            rounds[j]["holes"] = getEnumValue(LSPN.enums.holes, data['Holes']);
            rounds[j]["mulligans"] = getEnumValue(LSPN.enums.mulligans, data['Mulligans']);
            rounds[j]["pins"] = getEnumValue(LSPN.enums.pins, data['Pin']);
            rounds[j]["pinpos"] = data['Pin Positions (18 Holes, Positions from 0 - 17)'];
            rounds[j]["teepos"] = data['Tees - if Custom (18 Holes - B,M,F,J,L)'];
            rounds[j]["show_objects"] = (data['Show Tour Objects'] == true ? 1: 0);
            rounds[j]["wind_speed"] = getEnumValue(LSPN.enums.wind, data['Wind']);
            rounds[j]["tees"] = getEnumValue(LSPN.enums.tees, data['Tees']);
            rounds[j]["round_num"] = data['Round'];
            rounds[j]["joker_f9"] = f9;
            rounds[j]["joker_b9"] = b9;
            j++;
        }
    }
	return rounds;
}

LSPN.MainPage.prototype.checkChallengeRounds = function(rules)
{
    var round_tabs = Ext.getCmp('round-tabs');
    var num_rounds = round_tabs.getTabCount();
    var rounds = {};
    j=0;
    for (var i=0;i<=last_tab;i++)
    {
        var round_tab = Ext.getCmp('round-tab-'+i);
        if (round_tab)
        {
        	
			var round = j+1;
            var rprop = round_tab.items.items[0];
            data = rprop.getSource();
            if (data['Course Key'] == '')
            {
            	Ext.Msg.alert('Error', 'Please select a course for round '+round+".");  
            	return null;
            }
            if (!checkpins(data['Pin Positions (18 Holes, Positions from 0 - 17)']))
            {
            	Ext.Msg.alert('Error', 'Please check the pin positions for round '+round+". That value must be comprised of numbers from 0 - 17 and commas only");  
            	return null;
            }            
            
            var f9 = 0;
            var b9 = 0;
            if (parseInt(rules) == 6)
            {
            	var f9 = data['Joker Front 9 (Spanish Stableford)'];
            	var b9 = data['Joker Back 9 (Spanish Stableford)']
            	if (parseInt(f9) < 1 || parseInt(f9) > 9)
            	{
            		Ext.Msg.alert('Error', 'The Joker hole for the Front 9 must be between 1 and 9 on round '+round);  
            		return null;
            	}
            	if (parseInt(b9) < 10 || parseInt(b9) > 18)
            	{
            		Ext.Msg.alert('Error', 'The Joker hole for the Back 9 must be between 10 and 18 on round '+round);  
            		return null;
            	}
            	
            }
			rounds[j] = {};
            rounds[j]["allow_caddie"] = (data['Caddie Allowed'] == true ? 1: 0);            
            rounds[j]["course_key"] = data['Course Key'];
            rounds[j]["crowd_size"] = getEnumValue(LSPN.enums.crowds, data['Crowds']);
            rounds[j]["gimme_range"] = data['Gimme Range'];
            rounds[j]["green_hardness"] = getEnumValue(LSPN.enums.hardness, data['Green Hardness']);            
            rounds[j]["green_speed"] = getEnumValue(LSPN.enums.speed, data['Green Speed']);            
            rounds[j]["allow_grid"] = (data['Grid Allowed'] == true ? 1: 0);
            rounds[j]["holes"] = getEnumValue(LSPN.enums.holes, data['Holes']);
            rounds[j]["mulligans"] = getEnumValue(LSPN.enums.mulligans, data['Mulligans']);
            rounds[j]["pins"] = getEnumValue(LSPN.enums.pins, data['Pin']);
            rounds[j]["pinpos"] = data['Pin Positions (18 Holes, Positions from 0 - 17)'];
            rounds[j]["teepos"] = data['Tees - if Custom (18 Holes - B,M,F,J,L)'];
            rounds[j]["show_objects"] = (data['Show Tour Objects'] == true ? 1: 0);
            rounds[j]["wind_speed"] = getEnumValue(LSPN.enums.wind, data['Wind']);
            rounds[j]["tees"] = getEnumValue(LSPN.enums.tees, data['Tees']);
            rounds[j]["round_num"] = data['Round'];
            rounds[j]["joker_f9"] = f9;
            rounds[j]["joker_b9"] = b9;
            j++;
        }
    }
	return rounds;
}



LSPN.MainPage.prototype.membershipButtons = function()
{
	mo_cost = "$2.99";
	yr_cost = "$29.99";
	if (new_level == 'Tour Director')
	{
		mo_cost = "$4.99";
		yr_cost = "$49.99";
	}

	var renew_type = '';
	if (can_regular_renew)
	{
		yr_cost = '$29.99';
		renew_type = '&renew_type=1';
	}
	
	if (can_renew)
	{
		yr_cost = '$19.99';
		renew_type = '&renew_type=2';
	}

	var renew = '';
	if (is_renew)
		renew = '&renew=1';
		
	if (document.getElementById('paypal_monthly_button') != undefined)
	{
		var button = new Ext.Button({
			renderTo: 'paypal_monthly_button',
		    text: 'Use a PayPal Subscription for <b>Monthly</b> Membership Dues ('+mo_cost+')',
		    handler: function(){
		    	window.location.href = 'subscribe.php?period=1&user_id='+my_user_id+'&action=process&level='+new_level;
		    }
		});
	}
	
	if (document.getElementById('paypal_yearly_button') != undefined)
	{	
		var button3 = new Ext.Button({
			renderTo: 'paypal_yearly_button',
		    text: 'Use a one-time PayPal Payment for <b>Yearly</b> Membership Dues ('+yr_cost+')',
		    handler: function(){
		    	window.location.href = 'subscribe.php?period=2&user_id='+my_user_id+'&action=process&level='+new_level+renew+renew_type;
		    }
		});
	}
	
	if (document.getElementById('moneyorder_button') != undefined)
	{	
		var button2 = new Ext.Button({
			renderTo: 'moneyorder_button',
		    text: 'Send a Check or Money for Membership Dues',
		    handler: function(){
		    	window.location.href = 'moneyorder.php?action='+new_level;
		    }
		});
	}
	
	if (document.getElementById('moneyorder_switch_button') != undefined)
	{	
		var button2 = new Ext.Button({
			renderTo: 'moneyorder_switch_button',
		    text: 'Send a Check or Money for Membership Dues',
		    handler: function(){
		    	window.location.href = 'moneyorder_switch.php';
		    }
		});
	}	
	
	if (document.getElementById('acn_button') != undefined)
	{		
		var button3 = new Ext.Button({
			renderTo: 'acn_button',
		    text: 'Find out more about ACN Services',
		    handler: function(){
		    	window.location.href = 'acn.php?action='+new_level;
		    }
		});
	}
}

LSPN.MainPage.prototype.moneyOrderButton = function()
{
	var button = new Ext.Button({
		renderTo: 'do_moneyorder_button',
	    text: 'I am going to send a check or money order. Please start my grace period',
	    handler: function(){
	    	window.location.href = 'moneyorder.php?period=1&action=start&new_level='+new_level;
	    }
	});

}

LSPN.MainPage.prototype.acnOrderButton = function()
{
	var button = new Ext.Button({
		renderTo: 'do_acn_button',
	    text: 'I am going to sign up for ACN service. Please start my grace period',
	    handler: function(){
	    	window.location.href = 'acn.php?action=start&new_level='+new_level;
	    }
	});
}


LSPN.MainPage.prototype.showPayPalMessage = function()
{
	Ext.Msg.alert('PayPal Success', 'It could take up to an hour for PayPal to notify the LSPN that your payment was successful. If you don\'t see the correct membership level noted on this page after an hour, please contact the Tour Administrator');    
}


LSPN.MainPage.prototype.errorMessage = function()
{
	Ext.Msg.alert('An Error Occurred', 'An error occurred. Please try again. If this continues please contact the Tour Administrator.');    
}

LSPN.MainPage.prototype.setupFlights = function()
{
	this.getFlightOptions();
	var ds = new Ext.data.Store({
    	    proxy: new Ext.data.HttpProxy(new JayRock.RpcConnection({url:RPC_URL, rpcMethod:'getFlightList'})),
    	    method: "POST",
    	    sortInfo : {field: "game", direction: "DESC"},
            remoteSort: true,
            baseParams: {difficulty: this.flightOptions.difficulty, swing: this.flightOptions.swing, game: this.flightOptions.game},
            reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'num_records',
			fields: ['user_id', 'username', 'difficulty', 'swing_type', 'game', 'handicap', 'flight']
           })
    });
    
    if (this.useLeagueId)
    {
    	ds.baseParams.league_id = this.useLeagueId;
    }
    
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var cm = new Ext.grid.ColumnModel([
        {header: "User ID", width: 70, sortable: false, dataIndex: 'user_id'},
        {header: "User Name", width: 150, sortable: true, dataIndex: 'username'},
        {header: "Handicap", width: 70, sortable: true, dataIndex: 'handicap', renderer: renderHandicap},
        {header: "Flight", width: 50, sortable: true, dataIndex: 'flight'},
        {header: "Skill", width: 70, sortable: true, dataIndex: 'difficulty', renderer: renderLeaderboardSkill},
        {header: "Swing", width: 70, sortable: true, dataIndex: 'swing_type', renderer: renderLeaderboardSwing},
        {header: "Game", width: 100, sortable: true, dataIndex: 'game', renderer: renderGame}
    ]);

    // by default columns are sortable
    cm.defaultSortable = true;

    var grid = new Ext.grid.GridPanel({
        id:'flight-grid',
        applyTo:'stats-flight-grid',
        width:630,
        height:300,
        store: ds,
        cm: cm,
        stripeRows: true,
        loadMask: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true
        },
        tbar: [
            'Search for player: ', ' ',
            new Ext.app.SearchField({
                store: ds,
                width:320,
                pgid: 'page-flights'
            })
        ],
        bbar: new Ext.PagingToolbar({
        	id: 'page-flights',
            pageSize: 25,
            store: ds,
            displayInfo: true,
            displayMsg: 'Displaying players {0} - {1} of {2}',
            emptyMsg: "No players to display"
        })
    });

    grid.on('rowdblclick', this.showProfile, this);
    
    // render it
    grid.render();

    // trigger the data store load
    ds.load({params:{start:0, limit:25}});

}
    
function renderGame(value, metadata, record, rowIndex, colIndex, store)
{
    value = '<img src="/images/icons/'+value+'.gif"/>';
    return value;
}

function renderHandicap(value, metadata, record, rowIndex, colIndex, store)
{
	if (value > 0)
		value = "+" + value;

    return value;
}