Ext.BLANK_IMAGE_URL = 'http://extjs.cachefly.net/ext-3.3.1/resources/images/default/s.gif';
Ext.namespace('CRM');

Ext.apply(CRM, {
	appName: 'ASGA',
	copyright: 'Copyright &copy; 2001-2012 ASGA Chicago. Web design by TRR Partners, Ltd. powered by the <a href="http://www.sencha.com" target="_blank">ExtJs Framework</a>',
	termsOfUse: '', // 'Use of this website indicates acceptance of the {0} <a href="#" title="Terms of Use">Terms of Use</a> {1}',
	
	isPhone: false, // can't determine til onReady
	
	/**
	* Format a date as Month Day, Year (e.g. Dec 23, 2006)
	* @public
	*/
	renderDate: function (val) {
		return val ? val.dateFormat('F j, Y') : '';
	},

	/**
	* Format a datetime as mm/dd/yyy hh:mm AM/PM (e.g. 12/23/2006 09:30 AM)
	* @public
	*/
	renderDateTime: function (val) {
		return val ? val.dateFormat('F j Y g:i A') : '';
		//return val ? val.dateFormat('m/d/Y g:i A') : '';
	},
	
	CalendarStore: Ext.extend(Ext.data.Store, {
		constructor: function (config) {
			config = Ext.applyIf(config || {}, {
				storeId: 'calendarStore',
				root: 'calendars',
				idProperty: Ext.ensible.cal.CalendarMappings.CalendarId.mapping || 'id',
				proxy: new Ext.data.MemoryProxy(),
				autoLoad: true,
				fields: Ext.ensible.cal.CalendarRecord.prototype.fields.getRange(),
				sortInfo: {
					field: Ext.ensible.cal.CalendarMappings.Title.name,
					direction: 'ASC'
				}
			});
			this.reader = new Ext.data.JsonReader(config);
			CRM.CalendarStore.superclass.constructor.call(this, config);
		}
	}),
	MemoryEventStore: Ext.extend(Ext.data.Store, {
		constructor: function (config) {
			config = Ext.applyIf(config || {}, {
				storeId: 'eventStore',
				root: 'evts',
				proxy: new Ext.data.MemoryProxy(),
				writer: new Ext.data.DataWriter(),
				fields: Ext.ensible.cal.EventRecord.prototype.fields.getRange(),
				idProperty: Ext.ensible.cal.EventMappings.EventId.mapping || 'id'
			});
			this.reader = new Ext.data.JsonReader(config);
			CRM.MemoryEventStore.superclass.constructor.call(this, config);
		},

		// In real implementations the store is responsible for committing records
		// after a remote transaction has returned success = true. Since we never do
		// a real transaction, we never get any of the normal store callbacks telling
		// us that an edit occurred. This simple hack works around that for the purposes
		// of the local samples, but should NEVER actually be done in real code.
		afterEdit: function (rec) {
			rec.commit();
		},

		listeners: {
			// Since MemoryProxy has no "create" implementation, added events
			// get stuck as phantoms without an EventId. The calendar does not support
			// batching transactions and expects records to be non-phantoms, so for
			// the purpose of local samples we can hack that into place. In real remote
			// scenarios this is handled automatically by the store, and so you should
			// NEVER actually do something like this.
			'add': function (store, rec) {
				var r = rec[0];
				r.data[Ext.ensible.cal.EventMappings.EventId.name] = r.id;
				r.phantom = false;
				r.commit();
			}
		}
	}),
	content: {
		forms: {url: './php/eventForms.php', path: './Content/Forms/'},
		newsletters: {url: './php/newsletters.php', path: './Content/Newsletters/'},
		safety: {
			items: ['Lightning', 'Sun', 'Hydration', 'Tips For Pace Of Play', 'Tips For Slow Play'],
			path: './Content/Tips/'
		}
	}
});

Ext.apply(CRM, {
	data: {
		board: [
			{id: 'President', name: 'Chris Coyne', email: 'cmec52@comcast.net'},
			{id: 'Membership Chair', name:  'Kathi Maraffino', email: 'golfer_121@hotmail.com'},
			{id: 'Golf Chair', name: 'Bill Forcade', email: 'billforcade@sbcglobal.net'},
			{id: 'Social co-Chair', name: 'Penny Link', email: 'plink2742@gmail.com'},
			{id: 'Social co-Chair', name: 'Joanne Graske', email: 'graske3141@comcast.net'},
			{id: 'Secretary', name:  'Nancy Hill', email:'nncy408@yahoo.com'},
			{id: 'Communications', name: 'Ken Kusumoto', email: 'no9642@yahoo.com'},
			{id: 'Treasurer', name: 'Michael Daugherty', email: 'mdaugherty@hotmail.com'},
			{id: 'Newsletter Editor', name: 'Jane Leary', email: 'jsleary@gmail.com'},
			{id: 'Legal Counsel', name: 'Bill Forcade', email: 'billforcade@sbcglobal.net'},
			{id: 'Past President', name: 'Nancy Pierz', email: 'npierz@comcast.net'},
			{id: 'Webmaster', name: 'Tim Ryan', email: 'tryan@dls.net'}
		]
	}
});

App = function () {
	return {
		init: function () {
			//CRM.isPhone = Ext.fly(document.body).getWidth() <= 480;
			CRM.isPhone = /android|iphone/i.test(navigator.userAgent) && !(/ipad/i.test(navigator.userAgent));
			

			Ext.get('requiresJS').remove();  //remove the 'JavaScript required' message
			Ext.get('loading').remove();  //remove the loading icon
			
			//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

			this.calendarStore = new CRM.CalendarStore({
				data: eventTypes
			});
			this.eventStore = new CRM.MemoryEventStore({
				data: eventList
			});

			var viewport = new Ext.Viewport({
				id: 'viewport',
				layout: 'border',
				items: [
					new Ext.BoxComponent({
						id: 'header', region: 'north',
						height: 75,
						autoEl: {
							cls: 'mainTitle',
							html: '<div class="golftees"><h1 style="padding-top:20px">' +
									'<span style="color:blue;background-color:#ffff99;padding:5px 10px;">American Singles Golf Association - Chicago Chapter</span>' +
								'</h1></div>'
						}
					}),
					new Ext.BoxComponent({
						id: 'footer', region: 'south',
						height: 20,
						autoEl: {
							cls: 'copyright',
							html: CRM.copyright // String.format(CRM.termsOfUse, CRM.appName, CRM.copyright)
						}
					}), {
						id: 'west-panel', region: 'west',
						//: 'Want to know more?',
						width: 160, minSize: 125, maxSize: 160,
						split: true, collapsible: true,
						margins: '0 0 0 5',
						layout: {
							type: 'accordion',
							animate: true
						},
						items: [{
							title: 'About Us',
							border: false,
							items: [
								new Ext.BoxComponent({
									autoEl: {
										html: '<img width="160" src="./resources/images/asga_chicago_logo.jpg" />'
									}
								}), {
								bodyCssClass: 'aboutUs',
								html: '<p><a id="aboutUs" href="#">What is ASGA?</a></p>' +
									'<p><a id="membership" href="#">Membership - Join/Renew</a></p>' +
									'<p><a id="board" href="#">2012 Board Members</a></p>' +
									'<p><a href="http://www.cdga.org/login.asp?cmd=myreg" target="_blank">CDGA Member Login</a></p>' +
									'<p><a href="http://www.singlesgolf.com" target="_blank">ASGA National site</a></p>'
							}]
						}]
					},
					new Ext.TabPanel({  // center
						id: 'calendar',
						region: 'center',
						deferredRender: true,
						activeTab: 0,  // first tab initially active
						items: [{
							bodyCssClass: 'tabNews',
							title: 'Latest News',
							autoScroll: true,
							autoLoad: {
								url: './Content/LatestNews.html', 
								scope:this,
								callback: function() {
									Ext.get('lnkEventList').on('click', this.showListWindow);
								}
							}							
						}, {
							xtype: 'extensible.calendarpanel',
							title: 'Calendar',
							eventStore: this.eventStore,
							calendarStore: this.calendarStore,
							border: false,
							id: 'app-calendar',
							//readOnly: true,
							showDayView: false,
							showTime: false,
							activeItem: 2, // 0=1week view, 1=2week view, 2=month
							monthViewCfg: {
								showHeader: true,
								showWeekLinks: true,
								enableContextMenus:false
							},
							weekViewCfg: {
								viewStartHour: 8, viewEndHour: 24, scrollStartHour:10, showHourSeparator: false,  hourHeight:36
							},
							// Once this component inits it will set a reference to itself as an application
							// member property for easy reference in other functions within App.
							initComponent: function () {
								CRM.calendarPanel = this;
								this.constructor.prototype.initComponent.apply(this, arguments);
							},
							listeners: {
								'dayclick': function() {return false;}, //suppress the AddEvent functionality on cell click
								'eventclick': {
									fn: function (vw, rec, el) {
										this.showEventWindow(rec);
										return false;
									},
									scope: this
								}
							}
						}, {
							title: 'Newsletters',
							bodyCssClass: 'tabNewsletters',
							autoScroll: true,
							listeners: {
								activate: function (pnl) {
									if (CRM.content.newsletters.load) {
										return;  //load first time only
									}
									var store = new Ext.data.JsonStore({
										url: CRM.content.newsletters.url,
										root: 'files',
										fields: ['name', { name: 'size', type: 'float' }/*, { name: 'lastmod', type: 'date', dateFormat: 'timestamp'}*/],
										sortInfo: {field: 'name', direction: 'DESC'},
										listeners: {
											load: function(store, recs) {
												var path = CRM.content.newsletters.path;

												//template needs the actual data object from each record
												var getData = function(recs) {
													var r = [], rec, ts;
													for (var i=0, len=recs.length; i<len; i++) {
														rec = recs[i].data;
														ts = rec['name'].replace('Newsletter_', '').replace('.pdf', '');
														rec['date'] = new Date(ts.substr(0, 4) + '/' + ts.substr(4,2) + '/01').format('F Y');
														r.push(rec);
													}
													return r;
												};

												CRM.content.newsletters.load = true;
												pnl.body.update(
													'<h1>ASGA Newsletters (PDF format)</h1><br />' +
													new Ext.XTemplate(
													'<ul>' +
														'<tpl for=".">' +
															'<li><a href="' + path + '{name}" target="_blank">{date}</a></li>' +
														'</tpl>' +
													'</ul>').apply(getData(store.data.items)));
											}
										}
									});
									store.load();
								}
							}
						}, {
							title: 'Photos',
							xtype: 'iframepanel',
							defaultSrc: 'http://asgachicago.shutterfly.com'
						}, {
							title: 'Helpful Tips',
							bodyCssClass: 'tabSafety',
							html: '<h1>Helpful tips and safety info (PDF format)</h1><br />' +
								new Ext.XTemplate(
									'<ul>' +
										'<tpl for=".">' +
											'<li><a href="' + CRM.content.safety.path + '{.}.pdf" target="_blank">{.}</a></li>' +
										'</tpl>' +
									'</ul>').apply(CRM.content.safety.items)
						}, {
							title: 'Event Organizers',
							bodyCssClass: 'tabNewsletters',
							autoScroll: true,
							listeners: {
								activate: function (pnl) {
									if (CRM.content.forms.load) {
										return;  //load first time only
									}
									var store = new Ext.data.JsonStore({
										url: CRM.content.forms.url,
										root: 'files',
										fields: ['name', { name: 'size', type: 'float' }/*, { name: 'lastmod', type: 'date', dateFormat: 'timestamp'}*/],
										sortInfo: {field: 'name', direction: 'DESC'},
										listeners: {
											load: function(store, recs) {
												var path = CRM.content.forms.path;

												//template needs the actual data object from each record
												var getData = function(recs) {
													var r = [];
													for (var i=0, len=recs.length; i<len; i++) {
														r.push(recs[i].data);
													}
													return r;
												};

												CRM.content.forms.load = true;
												pnl.body.update(
													'<h1>Helpful forms for Event Organizers</h1><br />' +
													new Ext.XTemplate(
													'<ul>' +
														'<tpl for=".">' +
															'<li><a href="' + path + '{name}" target="_blank">{name}</a></li>' +
														'</tpl>' +
													'</ul>').apply(getData(store.data.items)));
											}
										}
									});
									store.load();
								}
							}
						}]
					})]
			});

			Ext.get('aboutUs').on('click', function () {
				var win = Ext.getCmp('winAboutUs');
				if (!win) {
					win = new Ext.Window({
						id: 'winAboutUs',
						title: 'About the ASGA',
						layout: 'fit',
						width: 800, height: 500,
						closable: false, closeAction: 'hide',
						autoScroll: true,
						bodyCssClass: 'winPopup',
						autoLoad: './Content/AboutUs.html',
						buttons: [{
							text: 'Close',
							handler: function () {
								win.hide();
							}
						}]
					});
				}
				win.show(this);
			});

			Ext.get('membership').on('click', function () {
				var win = Ext.getCmp('winMembership');

				if (!win) {
					win = new Ext.Window({
						id: 'winMembership',
						title: 'Membership Info',
						layout: 'fit',
						width: 800, height: 500,
						closable: false, closeAction: 'hide',
						autoScroll: true,
						bodyCssClass: 'winPopup',
						autoLoad: './Content/Membership.html',
						buttons: [{
							text: 'Close',
							handler: function () {
								win.hide();
							}
						}]
					});
				}
				win.show(this);
			});

			Ext.get('board').on('click', function () {
					var win = Ext.getCmp('winBoard');

					if (!win) {
						win = new Ext.Window({
							id: 'winBoard',
							title: 'ASGA Board Members',
							layout: 'fit',
							width: 800,	height: 500,
							closable: false, closeAction: 'hide',
							autoScroll: true,
							bodyCssClass: 'winPopup',
							html: new Ext.XTemplate(
									'<ul><tpl for="."><li><span style="font-weight:bold">{id}</span>&nbsp;&nbsp;<span class="name"><a href="mailto:{email}">{name}</a></span></li></tpl></ul>'
								).apply(CRM.data.board),
							buttons: [{
								text: 'Close',
								handler: function () {
									win.hide();
								}
							}]
						});
					}
					win.show(this);
				});
		},

		showEventWindow: function(rec) {
			var win = Ext.getCmp('winEvent');

			if (!win) {
				win = new Ext.Window({
					id: 'winEvent',
					title: 'Event',
					layout: 'fit',
					width: 800,	height: 500,
					closable: false, closeAction: 'hide',
					autoScroll: true,
					bodyCssClass: 'winPopup event',
					buttons: [{
						text: 'Print',
						handler: function () {
						 var html = new Ext.XTemplate(
						      '<!DOCTYPE>',
						      '<html>',
						        '<head>',
						          '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
						          '<title>Print Event</title>',
						        '</head>',
						        '<body>{data}</body>',
						      '</html>'
						    ).apply({data:this.findParentByType('window').body.dom.innerHTML});

						    //open up a new printing window, write to it, print it and close
						    var w = window.open('', 'printevent');

						    w.document.write(html);
						    w.document.close();
						    w.print();
   							w.close();
						}
					}, {
						text: 'Close',
						handler: function () {
							win.hide();
						}
					}]
				});
			}
			var tpl = new Ext.XTemplate(
				'<div class="title">{Title}</div>',
				'<div class="location">{Location}<br />{LocAddr}<br />{LocPhone}',
					'{[values.URL ? ("<br /><a href=\'" + (values.URL.substr(0,4) == "http" ? "" : "http://") + values.URL + "\'" + "target=\'_blank\'>" + values.URL + "</a>") : ""]}',
				'</div>',

				'<tpl if="CalendarId==1">',  //golf events
					'<div class="when">{[values.StartDt.dateFormat("F j, Y")]} -- First Tee Time: {[values.StartDt.dateFormat("g:i A")]}</div>',
				'</tpl>',
				'<tpl if="CalendarId!=1">',	//non-golf events
					'<div class="when">{[CRM.renderDateTime(values.StartDt)]} - {[CRM.renderDateTime(values.EndDt)]}</div>',
				'</tpl>',

				'<p class="cost">Price: {[values.Cost==-1 || values.Cost=="undefined" ? "TBD" : "$" + values.Cost]}',
				'<tpl if="CostGuest">',
					' / ${CostGuest} (Guest)',
				'</tpl>',
				'</p>',
				'<tpl if="CostWalk!=-1 && CostWalk!=null">',
					'<p class="cost">Price-Walking: {[values.CostWalk==-1 || values.CostWalk=="undefined" ? "TBD" : "$" + values.CostWalk]}',
					'<tpl if="CostGuestWalk">',
						' / ${CostGuestWalk} (Guest)',
					'</tpl>',
					'</p>',
				'</tpl>',
				'<tpl if="Max">',
					'<p class="max">Maximum: {Max} people</p>',
				'</tpl>',
				'<tpl if="MembersOnly">',
					'<p style="color:red; font-weight:bold">Members Only event</p>',
				'</tpl>',

				'<p class="contact">',
					'{[this.doRSVP(values.RSVP)]}{Contact}',
					'{[values.Email ? " - <a target=\'_blank\' href=\'mailto:" + values.Email + "?Subject=ASGA-" + values.Title + "\'>" + values.Email + "</a>" : ""]}',
					'{[values.Phone ? " - " + values.Phone : ""]}',
				'</p>',
				'<div class="desc">{Notes}</div>',
				'<tpl if="CalendarId==1">',  //golf events
					'<div class="disclaimer">{[Ext.fly("disclaimer").dom.innerHTML]}</div>',
				'</tpl>',
				{
					doRSVP: function(d) {
						return d ? '<span class="rsvp">RSVP/Signup by ' + CRM.renderDate(d) + ' to: </span>' : '';
					}
				}

					);
			win.show();
			win.update(tpl.apply(rec.data));
		},

		showListWindow: function() {
			var tpl, win = Ext.getCmp('winList');

			if (!win) {
				tpl = new Ext.XTemplate(
					'<tpl><div>Please check the calendar for complete event details.</div><br /><br />',
					'<tpl for=".">',
						'<tpl if="CalendarId==1">',  //golf events
							'<div class="item">',
							'<div class="title">{Title}</div>',
							'<div>{[values.StartDt.dateFormat("F j, Y")]} -- First Tee Time: {[values.StartDt.dateFormat("g:i A")]}</div>',
							'<div style="float:left;width:40%;">{Location}<br />{[values.LocAddr.replace("," ,"<br />")]}<br />{LocPhone}</div>',
							'<div style="float:left">',
								'{[values.Cost==-1 || values.Cost=="undefined" ? "Cost: TBD" : "Member: $" + values.Cost]}',
								'<tpl if="CostGuest">',
									' / Guest: ${CostGuest}',
								'</tpl>',
								'<tpl if="CostWalk!=-1 && CostWalk!=null">',
									' -- Walking -- Member: {[values.CostWalk==-1 || values.CostWalk=="undefined" ? "TBD" : "$" + values.CostWalk]}',
									'<tpl if="CostGuestWalk">',
										' / Guest: ${CostGuestWalk}',
									'</tpl>',
								'</tpl>',
								'<tpl if="MembersOnly">',
									'<br /><span style="color:red; font-weight:bold">Members Only event</span>',
								'</tpl>',
								'<br />',
								'{[this.doRSVP(values.RSVP)]}{Contact}',
								'<br />{[values.Email ? values.Email : ""]}',
								'{[values.Phone ? " - " + values.Phone : ""]}',
							'</div>',
							'<div style="clear:both;margin:0 20px;border-top:solid 1px gray;height:10px">&nbsp;</div>',
							'</div>',
						'</tpl>',
					'</tpl></tpl>',
					{
						doRSVP: function(d) {
							return d ? '<span>Signup by ' + CRM.renderDate(d) + ' to: </span>' : '';
						}
					}
				);

				App.eventStore.sort('StartDt', 'ASC');
				App.eventStore.filterBy(function(rec, id) {
					return !(rec.get('StartDt') < new Date());
				});
				//alert('width: ' + Ext.getCmp('viewport').getWidth() + ', height: ' + Ext.getCmp('viewport').getHeight());
				
				win = new Ext.Window({
					id: 'winList',
					title: '2011 golf events',
					layout: 'fit',
					width: CRM.isPhone ? 340 : 800,
					height: 500,
					closable: false, closeAction: 'hide',
					autoScroll: true,
					bodyCssClass: 'winPopup event',
					x: CRM.isPhome ? 10 : undefined,
					y: CRM.isPhone ? 10 : undefined,
					buttons: [{
						text: 'Print',
						handler: function () {
						 var html = new Ext.XTemplate(
						      '<!DOCTYPE>',
						      '<html>',
						        '<head>',
						          '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
						          '<title>Print Event</title>',
						        '</head>',
						        '<body>{data}</body>',
						      '</html>'
						    ).apply({data:this.findParentByType('window').body.dom.innerHTML});

						    //open up a new printing window, write to it, print it and close
						    var w = window.open('', 'printevent');

						    w.document.write(html);
						    w.document.close();
						    w.print();
   							w.close();
						}
					}, {
						text: 'Close',
						handler: function () {
							win.hide();
						}
					}],
					items: new Ext.DataView({
						store:App.eventStore,
						tpl: tpl,
						itemSelector:'div.item'
					})
				});
			}

			win.show();
		}
	};
}();

Ext.onReady(App.init, App);
