/* javascript compressor */
	Ext.namespace("MY", "MY.joomla");

Ext.lib.Dom.getViewportWidth=function(){
	if(Ext.isIE){
		return Ext.isStrict ? document.documentElement.clientWidth :
			document.body.clientWidth;
    }else{
		return document && document.documentElement ? document.documentElement.scrollWidth :
			self.innerWidth;
	}
};

MY.joomla.Connector = function(){
	this.siteurl= this.cleanUrl('http://wickedgreedy.com');
	this.ajaxurl= this.cleanUrl('http://wickedgreedy.com/index2.php');
	this.option= 'com_fbpool';
	this.readyStack = [];
	this.sections=null;
	this.user=null;
	this.events = {
		'ready':true,
		'logout':true
	};
};

Ext.extend( MY.joomla.Connector, Ext.util.Observable, {
	cleanUrl: function(url){
		var regex = /^http\:\/\/www/;
		if( regex.test(window.location.href) && !regex.test(url)){
			url = url.replace(/http\:\/\//, "http://www.");
		}else if( regex.test(url) && !regex.test(window.location.href)){
			url = url.replace( /http\:\/\/www/, "http://");
		}
		return url;
	},
	initialize: function( view, task ){
		this.request( {view:view,task:task,format:'raw',output:'json'},{
			callback: function(opts,success,xhr){
				if( success ){
					this.data = Ext.util.JSON.decode(xhr.responseText);
					if( this.data.sections ){
						this.sections = this.data.sections;
					}
					if( this.data.user ){
						this.user = this.data.user;
					}
				}
				this.ready = true;
				this.fireEvent('ready');
			},
			scope: this
		});
	},
	getParams: function( view, task, output, format, config ){
		var params = {
			no_html: 1,
			option: 'com_fbpool',
			view: view,
			task: task,
			format: format || 'raw',
			output: output || 'json'
		};
		Ext.apply( params, config );
		return params;
	},
	getConnection: function(params){
		var config = {
			url: this.ajaxurl,
			method: 'POST',
			extraParams: Ext.apply( {no_html: 1, option: this.option}, params || {} )
		};
		var conn = new Ext.data.Connection(config);
		conn.on('requestcomplete', this.checkResponse, this);
		return conn;
	},
	request: function(params, options){
		options = (!options || typeof options == "boolean") ? {} : options;
		var c = this.getConnection();
		options.params = params;
		c.request(options);
	},
	onReady: function( fn, scope ){
		if( this.ready ){
			var f=fn.createDelegate(scope);
			f();
			return;
		}
		this.on('ready',fn,scope);
		return;
	},
	
	checkResponse : function(conn,response,options){
		if(response.responseText.indexOf('<script>') == 0 ){
			if( this.ajaxurl.indexOf('index3.php') ){
				this.fireEvent('logout');
				this.loginBox();
				this.lastReq = {
					conn: conn,
					response: response,
					options: options
				};
				return false;
			}
		}
		return true;
	},
	
	loginBox: function(){
		if( !this.loginDlg ){
			this.loginDlg = new Ext.Window({
				title:'Please Login',
				resizable:false,
				constrain:true,
				constrainHeader:true,
				minimizable : false,
				maximizable : false,
				stateful: false,
				modal: true,
				closeAction: 'hide',
				shim : true,
				buttonAlign:"center",
				width:300,
				height:210,
				footer:true,
				minHeight: 80,
				plain:true,
				closable:true
			});
			this.loginDlg.addButton({
				text: 'Login',
				handler: this.doLogin,
				scope: this
			});
			this.formPanel = new Ext.form.FormPanel({
				url : this.siteurl + '/administrator/index.php',
				method : 'POST',
				baseParams: {'submit':1},
				border: false,
				bodyStyle: "background: transparent;"
			});
			this.formPanel.add(
				new Ext.form.TextField({
					name: 'usrname',
					fieldLabel: 'Username'
				}),
				new Ext.form.TextField({
					name: 'pass',
					fieldLabel: 'Password',
					inputType: 'password'
				})
			);
			this.loginDlg.render(document.body);
			var d = this.loginDlg.body.createChild({
				tag:'div',
				style: 'padding:10px;line-height:1.4em;',
				cls: 'x-form-item',
				children:[
					{tag:'p',html:'Your session has expired.<br />'},
					{tag:'p',html:'Please login again.<br /><br />'}
				]
			});
			this.formPanel.render(d);
			
		}
		this.loginDlg.show();
		
	},
	doLogin: function(){
		var p = Ext.apply(this.formPanel.getForm().getValues(),{
			submit: 1
		});
		Ext.Ajax.request({
			params: p,
			url: this.formPanel.getForm().url,
			success: function( response, options){
				if( response.responseText.indexOf('<script>') == 0 ){
					this.formPanel.getForm().reset();
					this.loginDlg.hide();
					this.lastReq.conn.request(this.lastReq.options);
				}
			},
			scope: this
		});
	}
	
});
MY.IdGenerator = function(){
	var id = 0;
	return {
		generate: function(){
			id++;
			return id;
		}
	}
}();
MY.id = MY.IdGenerator.generate.createDelegate( MY.IdGenerator );
MY.JsonReader = Ext.extend( Ext.data.JsonReader,{
	read : function( res ){
		if( !res.responseText || /^\s*</.test(res.responseText) ){
			throw {message:'Bad JSON Message Returned'};
		}
		return MY.JsonReader.superclass.read.call(this,res);
	}
});
MY.joomla.TextEditor = function(){
	this.id = MY.id();
	this.formDiv = false;
	this.editorView = 'editor';
	this.option = MY.Joomla.option;
	this.autoLoad = true;
	this.rendered = false;
	this.ready = false;
	MY.joomla.TextEditor.superclass.constructor.call(this);
	this.editorurl = '';
	this.templates = {
		input: new Ext.Template('<input type="hidden" name="{name}" id="{id}" />'),
		loading: new Ext.Template('<div class="my-circle-loading"><span>',
			'LOADING', '</span></div>' ),
		iframe: new Ext.Template(
			'<iframe style="display: block; z-index: 2;" scrolling="no" frameborder="0" ',
			'src="{editorUrl}" id="{editorId}" name="{editorName}" class="mycontentEditFrame">',
			'</iframe>')
	};
	this.inputs = [];
	var args = arguments;
	
	if( args.length == 1 && args[0] instanceof Array ){
		args = args[0];
	}
	this.map = {};
	for(i=0;i<args.length;i++){
		var t = (typeof args[i]).toLowerCase();
		var input = false;
		switch( t ){
		case 'string':
			input = {};
			input.name = args[i];
			input.value = '';
			input.label = 'Description';
			break;
		case 'object':
			input = args[i];
			break;
		}
		if( input ){
			this.map[input.name] = this.inputs.length;
			this.inputs.push(input);
		}
	}
	this.addEvents({
		'load': true,
		'hide': true,
		'show': true,
		'savecomplete': true
	});
	this.on('savecomplete', this.updateValues, this );
};
Ext.extend( MY.joomla.TextEditor, Ext.util.Observable, {
	render: function(el){
		if( this.rendered == true ){
			return;
		}
		this.templates.input.compile();
		this.templates.iframe.compile();
		this.templates.loading.compile();
		this.inputEls = {};
		this.map = {};
		for( var i=0; i<this.inputs.length; i++ ){
			this.map[this.inputs[i].name] = i;
			this.inputEls[this.inputs[i].name] = Ext.get( this.templates.input.append(el, {
				name: this.inputs[i].name,
				id: 'my_joomla_input_'+this.inputs[i].name+'_id_'+this.id,
				value: this.inputs[i].value
			}));
		}
		this.loading = Ext.get(this.templates.loading.append(el));
		this.iframe = Ext.get(this.templates.iframe.append(el, {
			editorUrl: this.editorUrl,
			editorName: this.getIframeName(),
			editorId: this.getIframeId()
		}));
		this.loading.setVisibilityMode( Ext.Element.DISPLAY );
		this.iframe.setVisibilityMode( Ext.Element.DISPLAY );
		this.iframe.on('load', this.show, this );
		this.iframe.on('load', this.registerWithIframe, this );
		this.rendered = true;
		this.setupForm();
		if( this.autoLoad ){
			this.setupform.submit();
		}
	},
	registerWithIframe: function(){
		var w = this.getIframeWindow();
		if( w && w.Controller ){
			this.ready=true;
			this.fireEvent('load');
			w.Controller.registerTextEditor( this );
		}
	},
	unloading: function(){
		this.ready = false;
		this.hide();
	},
	
	onReady: function(fn){
		console.log('onReady: ',this.ready);
		if( !this.ready ){
			this.on('load',fn);
			return;
		}
		fn();
	},
	
	hideEditor: function(n){
		this.onReady( function(name){
			var el = this.inputEls[name];
			var id = ( el && el.dom ) ? el.dom.id : '';
			var w = this.getIframeWindow();
			if( w && w.Controller ){
				w.Controller.hide(id);
			}
		}.createDelegate(this,[n]) );
	},
	
	showEditor: function(n){
		this.onReady( function(name){
			var el = this.inputEls[name];
			var id = ( el && el.dom ) ? el.dom.id : '';
			var w = this.getIframeWindow();
			if( w && w.Controller ){
				w.Controller.show(id);
			}
		}.createDelegate(this,[n]) );
	},
	
	changeLabel: function(name, l){
		var el = this.inputEls[name];
		var i = ( el && el.dom ) ? el.dom.id : '';
		this.onReady(function(id,label){
			console.log('changeLabel', id, label);
			var w = this.getIframeWindow();
			if( w && w.Controller ){
				w.Controller.changeLabel(id,label);
			}
		}.createDelegate(this,[i,l]) );
	},

	show: function(){
		if( !this.rendered ){
			return false;
		}
		this.loading.hide();
		this.iframe.show();
	},
	hide: function(){
		if( !this.rendered ){
			return;
		}
		this.iframe.hide();
		this.loading.show();
	},
	apply: function(){
		this.doSave('apply');
	},
	save: function(){
		this.doSave('save');
	},
	doSave: function(saveType){
		this.saving = true;
		this.getIframeWindow().Controller[saveType]( function(){
			this.saving = false;
			this.fireEvent('savecomplete');
		}, this );
	},
	get: function(key){
		return this.inputEls[key].getValue();
	},
	updateValues: function(){
		for( var i = 0; i < this.inputs.length; i++ ){
			this.inputs[i].value = this.inputEls[this.inputs[i].name].value;
		}
	},
	update: function(values){
		this.updateValues();
		if( values ){
			for( i in values ){
				this.inputs[this.map[i]].value = values[i];
			}
		}
		this.setupForm();
		this.setupform.submit();
	},
	
	setupForm: function(){
		this.fireEvent('load');
		if( !this.setupform ){
		this.setupform = Ext.DomHelper.append(document.body, {
				tag: 'form',
				style: 'display: none',
				target: this.getIframeName(),
				action: 'http://wickedgreedy.com/index2.php',
				method: 'post'
			});
		}
		Ext.fly(this.setupform).update('');
		Ext.DomHelper.append( this.setupform,{
			tag: 'input', type: 'hidden', name: 'no_html', value: '1'
		});
		Ext.DomHelper.append( this.setupform,{
			tag: 'input', type: 'hidden', name: 'option', value: this.option
		});
		Ext.DomHelper.append( this.setupform,{
			tag: 'input', type: 'hidden', name: 'view', value: this.editorView
		});
		Ext.DomHelper.append( this.setupform,{
			tag: 'input', type: 'hidden', name: 'iframename', value: this.getIframeId()
		});
		for( var i = 0; i < this.inputs.length; i++ ){
			Ext.DomHelper.append( this.setupform, {
				tag: 'input', type: 'hidden', name: 'name'+i, value: this.inputEls[this.inputs[i].name].dom.id
			});
			Ext.DomHelper.append( this.setupform, {
				tag: 'input', type: 'hidden', name: 'label'+i, value: this.inputs[i].label || 'Editor '+i
			});
			Ext.DomHelper.append( this.setupform, {
				tag: 'textarea', 
				name: this.inputEls[this.inputs[i].name].dom.id, 
				html: this.inputs[i].value || ''
			});
		}
	},
	getIframeName: function(){
		return 'my_joomla_iframe_name_'+this.id;
	},
	getIframeId: function(){
		return 'my_joomla_iframe_id_'+this.id;
	},
	getIframeWindow: function(){
		return parent.frames[this.getIframeName()];
	}
});
MY.joomla.TextEditor.create = function(el,args){
	var te = new MY.joomla.TextEditor(args);
	te.render(el);
	return te;
};
MY.Joomla = new MY.joomla.Connector();
MY.Joomla.evalFormConfigs = function( configs, options ){
	options = options || {};
	var model = options.model || 'default';
	var ret = [];
	for( var i = 0; i < configs.length; i++ ){
		var c = configs[i];
		if( Ext.type(c) == 'array' ){
			ret[ret.length] = MY.Joomla.evalFormConfigs(c,options);
		}else{
			if( c.xtype == 'combo' ){
				c.store = new Ext.data.JsonStore({
					url: MY.Joomla.ajaxurl,
					root: 'items',
					baseParams: Ext.apply(
						MY.Joomla.getParams(model,'getComboOptions'),{
							'property':c.name
						}
					),
					fields: ['value','text']
				});
				c.hiddenName=c.name;
				if( !c.editable ){
					c.editable = false;
				}
				c.listeners = {
					'show': function(){
						this.store.load();
					}
				};
				c.triggerAction='all';
				c.name=c.name+'-combo-display';
				c.displayField = 'text';
				c.valueField = 'value';
				c.forceSelection = true;
			}
			ret[ret.length]=c;
		}
	}
	return ret;
};
Ext.QuickTips.init();Ext.namespace("SB.square");
SB.square.Record = Ext.data.Record.create([
	{name: 'id'},
	{name: 'name'},
	{name: 'email'},
	{name: 'x'},
	{name: 'y'},
	{name: 'paid'},
	{name: 'note'}
]);
SB.square.Reader = function(){
	return new MY.JsonReader({
		id: 'id',
		root: 'items',
		totalProperty: 'count'
	}, SB.square.Record );
};
SB.square.Dialog = function(){
	SB.square.Dialog.superclass.constructor.call(this);
	this.addEvents({
		'save': true,
		'gridcomplete':true
	});
};
Ext.extend( SB.square.Dialog, Ext.util.Observable,{
	open: function(record, from){
		
		this.record = record;
		this.getWindow().show();
		this.getForm().loadRecord(record);
		this.getWindow().center();
		if( !SB.Env.isAdmin ){
			var f = this.getForm().findField('paid');
			f.container.up('div.x-form-item').hide();
		}
		if( record.get('id')== 0 ){
			this.deleteBtn.hide();
			this.saveBtn.setText('Make Donation!');
		}else{
			this.deleteBtn.show();
			this.saveBtn.setText('Save');
		}
	},
	getForm: function(){
		return this.getFormPanel().getForm();
	},
	getWindow: function(){
		if( this.window ){
			return this.window;
		}
		this.window = new Ext.Window({
			modal: true,
			width: 300,
			height: 210,
			closeAction: 'hide',
			title: 'Make Donation',
			layout: 'fit',
			items: [
				this.getFormPanel()
			],
			buttons: [{
				id: 'sb-dlg-save',
				text: 'Make Donation!',
				handler: this.getForm().submit,
				scope: this.getForm()
			},{
				id: 'sb-dlg-delete',
				text: 'Delete',
				handler: this.deleteRecord,
				scope: this
			},{
				text: 'Cancel',
				handler: this.close,
				scope: this
			}]
		});
		this.deleteBtn = Ext.getCmp('sb-dlg-delete');
		this.saveBtn = Ext.getCmp('sb-dlg-save');
		return this.window;
	},
	close: function(){
		this.getWindow().hide();
	},
	deleteRecord: function(){
		if( this.record.get(id) != 0 ){
			MY.Joomla.request( Ext.apply(
				MY.Joomla.getParams('squares','deleteItem'),{
					id: this.record.get('id')
				}),{
				success: function(){
					this.fireEvent('save');
					this.close();
				},
				scope: this
			});
		}
	},
	onSubmit: function( form, action){
		this.fireEvent('save');
		if( action.result.reloadNumbers ){
			this.fireEvent('gridcomplete');
		}
		this.close();
	},
	onFail: function( form, action ){
		var result = action.result;
		if( result.errors && result.errors['x'] ){
			alert('Uh-oh! Someone else must have just taken that box, I\'ll reload the page for you so you can try to get another one.');
			this.fireEvent('save');
			this.close();
		}
	},
	getFormPanel: function(){
		if( this.formPanel ){ return this.formPanel; }
		var noteHeight = SB.Env.isAdmin ? 50 : 60;
		this.formPanel = new Ext.form.FormPanel({
			xtype: 'form',
			baseCls: 'x-plain',
			url: MY.Joomla.ajaxurl,
			baseParams: MY.Joomla.getParams('squares','saveItem'),
			defaultType: 'textfield',
			bodyStyle: 'padding: 10px',
			reader: new SB.square.Reader(),
			labelWidth: 60,
			items: [{
				anchor: '100%',
				name: 'name',
				fieldLabel: 'Name'
			},{
				anchor: '100%',
				name: 'email',
				fieldLabel: 'Email'
			},{
				anchor: '100%',
				height: noteHeight,
				xtype: 'textarea',
				name: 'note',
				fieldLabel: 'Note'
			},{
				xtype: 'checkbox',
				name: 'paid',
				inputValue: 1,
				fieldLabel: 'Paid?'
			},{
				xtype: 'hidden',
				name: 'x'
			},{
				xtype: 'hidden',
				name: 'y'
			},{
				xtype: 'hidden',
				name: 'pool',
				value: 1
			},{
				xtype: 'hidden',
				name: 'id'
			}]
		});
		this.formPanel.getForm().on('actioncomplete', this.onSubmit, this);
		this.formPanel.getForm().on('actionfailed', this.onFail, this );
		return this.formPanel;
	}
});

SB.Env = {
	isAdmin: false};

SB.Pool = Ext.extend( Ext.Component, {
	
	initComponent: function(){
		SB.Pool.superclass.initComponent.call(this);
		var reader = new SB.square.Reader();
		var conn = MY.Joomla.getConnection(
			MY.Joomla.getParams('squares','getList')
		);
		var proxy = new Ext.data.HttpProxy(conn);
		this.loadEnvironment();
		this.store = new Ext.data.Store({
			proxy: proxy,
			reader: reader,
			remoteSort: true
		});
		this.squareDlg = new SB.square.Dialog();
		this.squareDlg.on('gridcomplete', this.onGridComplete, this );
		this.squareDlg.on('save', this.refresh, this);
		this.store.on('beforeload',this.loading,this);
		this.store.on('load', this.stopLoading, this);
		this.store.on('load', this.updateSquares, this );
		//this.on('render', this.refresh, this);
		Ext.QuickTips.init();
		if( SB.Env.isAdmin ){
			Ext.fly(document.body).addClass('sb-admin');
		}
	},
	
	loadEnvironment: function(win){
		var params = Ext.apply(MY.Joomla.getParams('pool','initPool'),{
			sendEmails: win ? 1 : 0
		});
		MY.Joomla.request( params, {
			success: function( response ){
				
				this.poolCfg = Ext.decode(response.responseText);
				this.loadNumbers();
				this.setTopHeading(this.poolCfg['xLabel']);
				this.setLeftHeading(this.poolCfg['yLabel']);
				this.refreshTask();
				if( win ){
					win.close();
				}
			},
			scope: this
		});
	},
	
	onGridComplete: function(){
		if( this.timeout ){
			clearTimeout( this.timeout );
		}
		var  win = new Ext.Window({
			width: 200,
			height: 100,
			closable: false,
			plain: true,
			bodyStyle: 'padding: 10px;',
			modal: true,
			title: 'Generating Numbers...',
			html: [
				'<p>All right! The pool is filled up. ',
				'Hold on a minute while we send everyone ',
				'an email!</p>'
			].join('')
		});
		win.show();
		win.center();
		this.loadEnvironment(win);
	},
	
	test: function(){
		if( this.timeout ){
			clearTimeout( this.timeout );
			MY.Joomla.request(MY.Joomla.getParams('pool','test'),{
				success: function(response){
					this.refreshTask();
				},
				scope: this
			});
		}
	},
	
	delayRefreshTask: function(){
		this.timeout = this.refreshTask.defer(10000,this);
	},
	
	refreshTask: function(){
		this._refresh();
		this.delayRefreshTask();
	},
	
	loading: function(){
		if( this.table ){
			this.table.addClass('sb-loading');
		}
	},
	stopLoading: function(){
		if( this.table ){
			this.table.removeClass('sb-loading');
		}
	},
	
	updateSquares: function(){
		var updated = {};
		for(var i=0; i<10;i++){
			updated[i]={};
		}
		
		this.store.each( function(record){
			var x = record.get('x');
			var y = record.get('y');
			if( x > 9 || y > 9 ){
				return;
			}
			var cell = this.cells[y][x];
			this.fillSquare(cell, record);
			updated[y][x]=true;
		}, this);
		for(var i = 0; i<10; i++){
			for(var j =0; j<10; j++){
				if( !updated[i][j] ){
					this.emptySquare(this.cells[i][j],i,j);
				}
			}
		}
	},
	
	emptySquare: function(cell,y,x){
		cell.update('&nbsp;');
		cell.removeClass('sb-unpaid');
		cell.removeClass('sb-paid');
		cell.replaceClass('sb-full-cell','sb-empty-cell');
		cell.hoverClass = 'sb-empty-cell-hover';
	},
	
	fillSquare: function(cell, record){
		cell.replaceClass('sb-empty-cell','sb-full-cell');
		var html = '<strong>'+record.get('name')+'</strong>';
		if( record.get('paid') == 0 ){
			cell.removeClass('sb-paid');
			cell.addClass('sb-unpaid');
		}else{
			cell.removeClass('sb-unpaid');
			cell.addClass('sb-paid');
		}
		cell.update(html);
		cell.hoverClass='';
	},
	onCellClick: function(x,y){
		if( !this.store ){
			return;
		}
		var found = false;
		this.store.each( function(r){
			if( r.get('x') == x && r.get('y') == y ){
				found = r;
				return false;
			}
		}, this);
		if( !found ){
			this.buyCell(y,x);
		}
		else if( SB.Env.isAdmin ){
			this.squareDlg.open(found, this.cells[y][x]);
		}
	},
	buyCell: function(y,x){
		var record = new SB.square.Record({
			x: x,
			y: y,
			id:0,
			paid:0,
			name: '',
			email:'',
			note:''
		});
		this.cells[y,x];
		this.squareDlg.open(record, this.cells[y],[x] );
	},
	
	loadNumbers: function(){
		
		for(var i=0; i<10; i++){
			this.labels['x'][i].update(this.poolCfg['xAxis'][i]);
			this.labels['y'][i].update(this.poolCfg['yAxis'][i]);
		}
		
		if( this.poolCfg['xAxis'][0] == '?'){
			return;
		}
		
		var str = [
			'<table cellspacing="0" cellpadding="2">',
				'<tr><th style="padding-right: 4px;font-weight:bold;">',
				this.poolCfg.xLabel,':</th>',
				'<td>{0}</td></tr>',
				'<tr><th style="padding-right: 4px;font-weight:bold;">',
				this.poolCfg.yLabel,':</th>',
				'<td>{1}</td></tr>',
			'</table>'
		].join('');
		
		for(var y=0; y<10; y++ ){
			for( var x=0; x<10; x++){
				Ext.QuickTips.register({
					target: this.cells[y][x],
					text: String.format(str,this.poolCfg.xAxis[x],this.poolCfg.yAxis[y])
				});
			}
		}
	},
	
	_refresh: function(){
		this.store.load();
	},
	
	refresh: function(){
		this._refresh();
		if( this.timeout ){
			clearTimeout( this.timeout );
			this.delayRefreshTask();
		}
	},
	
	onRender: function(ct,position){
		SB.Pool.superclass.onRender.call(this,ct,position);
		this.drawTable();
		if( SB.Env.isAdmin ){
			this.drawAdminToolbar();
		}
		//this.loadNumbers();
	},
	
	setTopHeading: function(str){
		this.topheading.update('<span>'+str+'</span>');
	},
	setLeftHeading: function(str){
		var word = str.split('');
		this.leftheading.update('<span>'+word.join('<br />')+'</span>');
	},
	
	drawTable: function(){
		if( this.table ){
			return false;
		}
		width = this.printable ? ' style="width: 680px" ' : "";
		var tpl = [
			'<table class="sb-table" cellpadding="0" ',width,' cellspacing="0">',
				'<tbody>',
					'<tr>',
						'<td class="sb-corner">&nbsp;</td>',
						'<td>&nbsp;</td>',
						'<td valign="middle" colspan="10" id="sb-heading-top" class="sb-heading-top sb-heading"></span>AFC</span></td>',
					'</tr>',
					'<tr>',
						'<td colspan="2">&nbsp;</td>'];
		for( var i = 0; i < 10; i++ ){
			var cls = ['sb-label','sb-label-top'];
			tpl[tpl.length] = ['<td id="sb-label-x-'+i+'" class="'+cls.join(' ')+'">?</td>'].join('');
		}
		tpl[tpl.length] = '</tr>';
		for( var i = 0; i < 10; i++ ){
			var leftHeading = '';
			if( i==0 ){
				leftHeading = '<td valign="middle" id="sb-heading-left" class="sb-heading-left sb-heading" rowspan="10">NFC</td>';
			}
			var cls = ['sb-label','sb-label-left'];
			var label = ['<td valign="middle" id="sb-label-y-', i,'" class="'+cls.join(' ')+'">?</td>'].join('');
			var row = [];
			for( var j = 0; j < 10; j++ ){
				var cls = ['sb-cell'];
				cls[cls.length]='r'+(i%2)+'c'+(j%2);
				if( i==9){
					cls[cls.length]='y-last';
				}
				if( j==9){
					cls[cls.length]='x-last';
				}
				var id='sb-cell-y'+i+'-x'+j;
				row[row.length] = [
					'<td valign="middle" id="',id,'"class="', cls.join(' '), '">&nbsp;</td>'
				].join('');
			}
			tpl[tpl.length] = ['<tr>', leftHeading, label, row.join(''), '</tr>'].join('');
		}
		tpl[tpl.length] = '</tbody></table>';
						
		this.cells = [];
		var ct = this.container;
		
		var T = new Ext.Template(tpl);
		this.table = T.append(ct,{});
		if( !this.printable ){
			Ext.DomHelper.insertBefore(this.table, [
				'<div style="text-align:center; padding: 2px; font-weight: bold;">',
				'<a href="http://wickedgreedy.com',
				'/index2.php?option=com_fbpool&',
				'Itemid=36&printable=true">Printable Version</a>',
				'</div>'
			].join('') );
		}
		this.table = Ext.get(this.table);
		
		var cellOverFn = function(e){
			if( !e.within(this,true) && this.hoverClass ){
				this.addClass(this.hoverClass);
			}
		};
		var cellOutFn = function(e){
			if( !e.within(this,true) && this.hoverClass ){
				this.removeClass(this.hoverClass);
			}
		};
		
		this.leftheading=Ext.get('sb-heading-left');
		this.topheading=Ext.get('sb-heading-top');
		
		this.labels = {};
		this.labels['x']=[];
		this.labels['y']=[];
		
		for( var y = 0; y < 10; y++ ){
			this.labels['y'][y] = Ext.get('sb-label-y-'+y);
			for(var x = 0; x < 10; x++){
				if( y==0 ){
					this.labels['x'][x]=Ext.get('sb-label-x-'+x);
				}
				if( x==0 ){
					this.cells[y]=[];
				}
				this.cells[y][x] = Ext.get('sb-cell-y'+y+'-x'+x);
				this.cells[y][x].hoverClass = '';
				this.cells[y][x].on('mouseover', cellOverFn);
				this.cells[y][x].on('mouseout', cellOutFn);
				this.cells[y][x].on('click', this.onCellClick.createDelegate(this,[x,y]) );
			}
		}
		this.setLeftHeading('NFC');
		this.updateCSS.defer(100,this);
		return true;
	},
	
	drawAdminToolbar : function(){
		var div = Ext.DomHelper.insertBefore(this.table,{
			tag: 'div',
			style: 'border: 1px solid #aaa; border-bottom-width: 0px; width: 90%; margin: 0px auto;'
		});
		new Ext.Toolbar({
			renderTo: div,
			items: [{
				text: 'List Unpaid Emails',
				scope: this,
				handler: this.listUnpaidEmails
			},{
				text : 'Show Stats',
				scope: this,
				handler:this.showStats
			}]
		});
	},
	
	listUnpaidEmails : function(){
		var emails = [];
		this.store.each( function(r){
			if( r.get('paid')!=1 ){
				var e = r.get('email');
					
				if( emails.indexOf( e ) == -1 ){
					emails[emails.length] = e;
				}
			}
		});
		var html = emails.join("<br />");
		var link = "<a href='mailto:mark.fabrizio@gmail.com?bcc="+emails.join(',')+"'>Send Email</a>";
		html = link+"<br /><br />"+html;
		this.infoWindow( html, 'Unpaid Emails');
	},
	
	showStats : function(){
		var paid=0,unpaid=0;
		this.store.each( function(r){
			if( r.get('paid')==1){
				paid++;
			}else{
				unpaid++;
			}
		});
		var html = "Unpaid : $"+(unpaid*5)+"<br />";
		html += "Paid : $"+(paid*5)+"<br /><br />";
		
		var count = this.store.getCount();
		var remain = 100 - count;
		html += remain+" squares still avaialable<br />";
		html += count+" squares have been filled<br /><br />";
		
		var outstanding = (unpaid+remain)*5;
		html += "$"+outstanding+" total owed to this pool";
		
		this.infoWindow(html, "Stats");
		
	},
	
	infoWindow : function( html, title ){
		new Ext.Window({
			width: 320,
			height: 250,
			bodyStyle: 'padding: 10px; font-size: 1.2em; background-color: #fff',
			autoScroll: true,
			title: title || "Info",
			html: html
		}).show();
	},
	
	updateCSS: function(){
		// perform necessary h/w adjustments
		var cell_w = this.cells[0][0].getComputedWidth();
		var heading_w = this.leftheading.getComputedWidth();
		if( !this.stylesheet ){
		
			var css = [
				'.sb-cell{',
					'height: ', cell_w, 'px;',
				'}',
				'.sb-heading-top{',
					'height: ', heading_w, 'px;',
				'}'
			];
			css = css.join('');
			Ext.util.CSS.createStyleSheet(css, 'sb-stylesheet');
		}
		else{
			
			this.updateRule('.sb-cell', 'height', cell_w+'px');
			this.updateRule('.sb-heading-top', 'height', heading_w+'px');
			
		}
	}
});
