// Create the application
GSI.Application.create("CommandCenter");

/** Debug Mode @type Boolean */
CommandCenter.debugMode = false;

/** Deployment Options */
CommandCenter.deployments = {
	current: "local",
	getCurrent: function()
	{
		return CommandCenter.deployments[ CommandCenter.deployments.current ];
	},
	local: { rootPath: "/", classPath: "/common/", libPath: "/lib/" },
	jive: { rootPath: "/gsi/", classPath: "/gsi/common/", libPath: "/gsi/lib/" }
};

/** Server Variable */
CommandCenter.baseURL = {
	
	getBase: function()
	{
		var bURL = location.href;
		if(bURL.search("jive")>0)
		{
			bURL = "qa";
		}
		else if(bURL.search("gsiccorp")>0)
		{
			bURL = "qa";
		}
		else
		{
			bURL = "live";
		}
		
		switch(bURL)
		{
			case "qa" : return "http://dsp.tst01.gspt.net";
			break;
			case "live" : return "http://www.dickssportinggoods.com";
			break;
			default : return "http://www.dickssportinggoods.com";
			break;
		}
		
	}
	
}
// Set the root url for all loading
CommandCenter.rootPath = CommandCenter.deployments.getCurrent().rootPath;
// Set the lib url for loading libraries
CommandCenter.libPath = CommandCenter.deployments.getCurrent().libPath;
// Set the classpath for the API includes
GSI.NameSpace._classPath = CommandCenter.deployments.getCurrent().classPath;

// Set the app requirements
CommandCenter.requiredClasses =
[
	"GSI.Position"    ,"GSI.Dimensions","GSI.LightBox","GSI.TabManager" ,"GSI.Date",
	"GSI.SelectBox"   ,"GSI.Geography" ,"GSI.Accordion"      ,"GSI.Network"        ,
	"GSI.CalendarData","GSI.Calendar"  ,"GSI.CalendarControl","GSI.Scrolling"      ,
	"GSI.Scrollbar"   ,"GSI.Uploader"  ,"GSI.MethodChain"    ,"GSI.CommentTemplate",
	"GSI.Location"    ,"GSI.Window"    ,"GSI.Mouse"          ,"GSI.Verifier"
];

/** Load the scripts using document.write for debugging */
GSI.loadScripts( CommandCenter.requiredClasses, GSI.NameSpace._classPath );
GSI.loadScripts( ["GSI.Application.DSP.CMMCommandCenter.CalendarBase.js"], "javascript/" );

/** MiniCalendar reference @type GSI.Calendar */
CommandCenter.miniCalendar = undefined;
/** MiniCalendarControl reference @type GSI.CalendarControl */
CommandCenter.miniCalendarCtl = undefined;
/** Reference to the current page. Set var currentPage="value" before the GSI include @type String */
CommandCenter.currentPage = undefined;
/** Reference to the page we are leaving in SportSpace. @type String */
CommandCenter.currentSpaceId = undefined;
/** The user's current role key @type String */
CommandCenter.userRoleKey = undefined;

/** URL and Page config object @type Object */
CommandCenter.urls = {
	guest:
	{
		index:
		{
			defaultPage: "landingPage",
			pages:
			{
				landingPage: {name: "landingPage",url: "pages/landingPage.html",className: "LandingPage",auth: false,redirectIfLoggedIn: "dashboard.html"},
				logOut: {name: "logOut",url: "pages/logOut.html",className: "LogOut",auth: true},
				viewPublicPage: {name: "viewPublicPage",url: "pages/viewPublicPage.html",className: "ViewPublicPage",auth: false},
				corporatePublicPage: {name:"corporatePublicPage",url:"pages/corporatePublicPage.html",className:"CorporatePublicPage",auth:false},
				resetPassword: {name: "resetPassword",url: "pages/resetPassword.html",className: "ResetPassword",auth: false,redirectIfLoggedIn: "dashboard.html"},
				resetPasswordConfirmation: {name: "resetPasswordConfirmation",url: "pages/resetPasswordConfirmation.html",className: "ResetPasswordConfirmation",auth: false,redirectIfLoggedIn: "dashboard.html"},
				equipmentKit: {name: "equipmentKit",url: "pages/equipmentKit.html",className: "EquipmentKit",auth: false},
				packetCoupon: {name: "packetCoupon",url: "pages/packetCoupon.html",className: "PacketCoupon",auth: false},
				eventsActivities: {name: "eventsActivities",url: "pages/eventsActivities.html",className: "EventsActivities",auth: false},
				informationRequest: {name: "informationRequest",url: "pages/information_request_form.html",className: "InformationRequest",auth: false},
				completeInvitation: {name: "completeInvitation",url: "pages/profile_setup.html",className: "ProfileSetup",auth: false},
				editLeague: {name: "editLeague",url: "pages/edit_league.html",className: "EditLeague",auth: false},
				infoThanks: {name : "infoThanks", url : "pages/information_request_form_confirmation.html", className : "InfoThanks", auth : false},
				noLeague: {name : "noLeague", url : "pages/no_league.html", className : "NoLeague", auth : false},
				cysOverview: {name : "cyoOverview", url : "pages/landingPage.html", className : "cyoOverview", auth : false},				
				cysLearnMore: {name : "cysLearnMore", url : "pages/cysLearnMore.html", className : "cysLearnMore", auth : false},				
				cysTeamPacket: {name : "cysTeamPacket", url : "pages/cysTeamPacket.html", className : "cysTeamPacket", auth : false},				
				cysCoachEquipKit: {name : "cysCoachEquipKit", url : "pages/cysCoachEquipKit.html", className : "cysCoachEquipKit", auth : false},				
				cysInStore: {name : "cysInStore", url : "pages/cysInStore.html", className : "cysInStore", auth : false},				
				
		
				leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}
			}
		},
		terms_and_conditions:
		{
			defaultPage: "termsAndConditions",
			pages:
			{
				termsAndConditions: {name: "termsAndConditions", url: "pages/termsAndConditions.html",className:"TermsAndConditions",auth:false }
			}
		}
	},
	player:
	{
		dashboardplayer:
		{
			defaultPage: "lockerRoom",
			pages:
			{
				lockerRoom: {name: "playersLockerRoom",url: "pages/sportPlayersLockerRoom.html",className: "playersLockerRoom",auth: true,requireSpace: true },
				logOut: {name: "logOut",url: "pages/logOut.html",className: "LogOut",auth: true},
				equipmentKit: {name: "equipmentKit",url: "pages/equipmentKit.html",className: "EquipmentKit",auth: false},
				packetCoupon: {name: "packetCoupon",url: "pages/packetCoupon.html",className: "PacketCoupon",auth: false},
				eventsActivities: {name: "eventsActivities",url: "pages/eventsActivities.html",className: "EventsActivities",auth: false},
				leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}


			}
		}
	},

	coach:
	{
		dashboardcoach:
		{
			defaultPage: "coachsOffice",
			pages:
			{
				coachsOffice: {name: "coachsOffice",url: "pages/sportCoachsOffice.html",className: "sportSpaceCoachsOffice",auth: true,requireSpace: true },
				logOut: {name: "logOut",url: "pages/logOut.html",className: "LogOut",auth: true},
				noSpace: {name: "noSpace",url: "pages/no_league.html",className: "NoSpace",auth: true},
				resetPassword: {name: "resetPassword",url: "pages/resetPassword.html",className: "ResetPassword",auth: false,redirectIfLoggedIn: "dashboardcoach.html"},
				resetPasswordConfirmation: {name: "resetPasswordConfirmation",url: "pages/resetPasswordConfirmation.html",className: "ResetPasswordConfirmation",auth: false,redirectIfLoggedIn: "dashboardcoach.html"},
				equipmentKit: {name: "equipmentKit",url: "pages/equipmentKit.html",className: "EquipmentKit",auth: false},
				packetCoupon: {name: "packetCoupon",url: "pages/packetCoupon.html",className: "PacketCoupon",auth: false},
				eventsActivities: {name: "eventsActivities",url: "pages/eventsActivities.html",className: "EventsActivities",auth: false},
				createTeams: {name: "createTeams",url: "pages/createTeams.html",className: "CreateTeams",auth: true},
				editTeam: {name: "editTeam",url: "pages/edit_team.html",className: "EditTeam",auth: true},
				createNewTeam: {name: "createNewTeam",url: "pages/createNewTeam.html",className: "CreateNewTeam",auth: true},
				createNewSeason: {name: "createNewSeason",url: "pages/createTeams.html",className: "CreateTeams",auth: true, onLoad: { methodName: "setFormType", parameters: ["copy"] }
				},
				viewInvitations: {name: "viewInvitations",url: "pages/view_invitations.html",className: "ViewInvitations",auth: true},
				editProfile: {name: "editProfile",url: "pages/profile_edit.html",className: "EditProfile",auth: true, requireSpace: true },
				createMoreTeams: {name: "editTeams",url: "pages/createTeams.html",className: "CreateTeams",auth: true,onLoad: { methodName: "setFormType", parameters: ["createTeam"] }
				},
				leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}
			}
		}
	},
	leagueOrganizer:
	{
		dashboardleagueOrganizer:
		{
			defaultPage: "lockerRoom",
			pages:
			{
				lockerRoom: {name: "lockerRoom",url: "pages/sportSpaceLocker.html",className: "sportSpaceLocker",auth: true,requireSpace: true},
				logOut: {name: "logOut",url: "pages/logOut.html",className: "LogOut",auth: true},
				resetPassword: {name: "resetPassword",url: "pages/resetPassword.html",className: "ResetPassword",auth: false,redirectIfLoggedIn: "dashboardleagueOrganizer.html"},
				resetPasswordConfirmation: {name: "resetPasswordConfirmation",url: "pages/resetPasswordConfirmation.html",className: "ResetPasswordConfirmation",auth: false,redirectIfLoggedIn: "dashboard.html"},
				equipmentKit: {name: "equipmentKit",url: "pages/equipmentKit.html",className: "EquipmentKit",auth: false},
				packetCoupon: {name: "packetCoupon",url: "pages/packetCoupon.html",className: "PacketCoupon",auth: false},
				eventsActivities: {name: "eventsActivities",url: "pages/eventsActivities.html",className: "EventsActivities",auth: false},
				editProfile: {name: "editProfile",url: "pages/profile_edit.html",className: "EditProfile",auth: true, requireSpace: true },
				createLeague: {name: "createLeague",url: "pages/profile_setup_step2.html",className: "CreateLeagues"},
				createNewSeason: {name: "createNewSeason",url: "pages/profile_setup_step2.html",className: "CreateLeagues",auth: true, requireSpace: true, onLoad: { methodName: "setFormType", parameters: ["new"] }
				},
					editLeague: {name: "editLeague",url: "pages/edit_league.html",className: "EditLeague",auth: true},
					leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}

			}
		}
	},
	communityMarketingManager:
	{
		dashboard:
		{
			defaultPage: "teamSpaceTab",
			pages:
			{
				teamSpaceTab: { name: "teamSpaceTab", url: "pages/teamSpaceTab.html", className: "TeamSpaceTab", auth: true, requireSpace: true },
				cmmTab: { name: "cmmTab", url: "pages/cmmTab.html", className: "CMMTab", auth: true, requireSpace: true },
				editPublicPage: {
					name: "editPublicPage", url: "pages/editPublicPage.html", className: "EditPublicPage", auth:true, requireSpace:true,
					onLoad: { methodName: "setFormType", parameters: ["edit"] }
				},
				setupPublicPage: {
					name: "setupPublicPage", url: "pages/editPublicPage.html", className: "EditPublicPage", auth:true, requireSpace:true,
					onLoad: { methodName: "setFormType", parameters: ["setup"] }
				},
				viewPublicPage: { name: "viewPublicPage", url: "pages/viewPublicPage.html", className: "ViewPublicPage", auth: true, requireSpace: true },
				leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}
			}
		}
	},
	corporateAdmin:
	{
		dashboardcorporateAdmin:
		{
			defaultPage: "adminTab",
			pages:
			{
				adminTab: { name: "adminTab",url:"pages/adminTab.html",className: "AdminTab",auth: true,requireSpace: true},
				cmmTab: { name: "cmmTab", url:"pages/corporateAdmin-cmmTab.html",className:"CMMTab", auth:true, requireSpace:true },
				editPublicPage: {
					name: "editPublicPage", url:"pages/corporateAdmin-editPublicPage.html", className:"CorpAdminPublicPageForm", auth:true, requireSpace:true,
					onLoad: { methodName: "setFormType", parameters: ["edit"] }
				},
				setupPublicPage: {
					name: "setupPublicPage", url:"pages/corporateAdmin-editPublicPage.html", className:"CorpAdminPublicPageForm", auth:true, requireSpace:true,
					onLoad: { methodName: "setFormType", parameters: ["setup"] }
				},
				leavingSportSpace: {name : "leavingSportSpace", url : "pages/leaving.html", className : "LeavingSportSpace", auth : false}
			}
		}
	}
};

/** Form config object @type Object */
CommandCenter.forms =
{
	emailUpdatesForm: {
		url: "components/emailUpdatesForm.html",
		elementId: "emailUpdatesFormDiv",
		className: "EmailUpdatesForm",
		noLightBox: true
	},
	eventForm: {
		url: "components/eventForm.html",
		elementId: "eventFormDiv",
		className: "EventForm"
	},
	blogPostForm: {
		url: "components/blogPostForm.html",
		elementId: "blogPostFormDiv",
		className: "BlogPostForm"
	},
	dailyEvents: {
		url: "components/dailyEvents.html",
		elementId: "dailyEventsDiv",
		className: "DailyEventsForm"
	},
	sendInvite: {
		url: "components/sendAnInvitation.html",
		elementId: "sendInvitationDiv",
		className: "SendInviteForm"
	},

	sendInviteConfirmation: {
		url: "components/invitationConfirmation.html",
		elementId: "inviteConfirmationDiv",
		className: "InvitationConfirmationForm"
	},

	messageForm: {
		url: "components/messageForm.html",
		elementId: "messageFormDiv",
		className: "MessageForm"
	},

	kbFolderForm: {
		url: "components/kbFolderForm.html",
		elementId: "kbFolderFormDiv",
		className: "KBFolderForm"
	},

	kbFileForm: {
		url: "components/kbFileForm.html",
		elementId: "kbFileFormDiv",
		className: "KBFileForm"
	},

	forgotPassword: {
		url: "components/forgotPassword.html",
		elementId: "forgotPasswordDiv",
		className: "ForgotPassword",
		noLightBox: true
	},

	forgotPasswordConfirmation: {
		url: "components/forgotPasswordConfirmation.html",
		elementId: "forgotPasswordConfirmationDiv",
		className: "ForgotPasswordConfirmation",
		noLightBox: true
	},

	//Added by BH
	cmmForm: {
		url: "components/contactCMMForm.html",
		elementId: "cmmFormDiv",
		className: "cmmForm"
	},
	sshForm: {
		url: "components/ssHelpForm.html",
		elementId: "sshFormDiv",
		className: "sshForm"
	},
	deactivateForm: {
		url: "components/deactivateTeamForm.html",
		elementId: "deactivateFormDiv",
		className: "DeactivateForm"
	},
	editTeamForm: {
		url: "components/editTeamForm.html",
		elementId: "editFormDiv",
		className: "EditTeamForm"
	},
	createTeamForm: {
		url: "components/createTeamForm.html",
		elementId: "createFormDiv",
		className: "CreateTeamForm"
	},
	messageThreadForm: {
		url: "components/messageThreadForm.html",
		elementId: "messageThreadFormDiv",
		className: "MessageThreadForm"
	},
	leagueGameForm: {
		url: "components/leagueGameForm.html",
		elementId: "gameFormDiv",
		className: "LeagueGameForm"
	},
	teamGameForm: {
		url: "components/teamGameForm.html",
		elementId: "gameFormDiv",
		className: "TeamGameForm"
	},
	editPlayerForm: {
		url: "components/editPlayerForm.html",
		elementId: "editFormDiv",
		className: "EditPlayerForm"
	},
	deletePlayerForm: {
		url: "components/deletePlayer.html",
		elementId: "deactivateFormDiv",
		className: "DeletePlayerForm"
	},
	declineInvitationForm: {
		url: "components/declineInvitation.html",
		elementId: "declineInviteFormDiv",
		className: "DeclineInvitationForm"
	},
	createPlayerForm: {
		url: "components/createPlayerForm.html",
		elementId: "createFormDiv",
		className: "CreatePlayerForm"
	},
	archiveMessageForm: {
		url: "components/archiveMessage.html",
		elementId: "archiveDiv",
		className: "ArchiveMessage",
		noLightBox: true
	},
	seasonHasEndedForm: {
		url: "components/seasonHasEndedPrompts.html",
		elementId: "seasonEndDiv",
		className: "SeasonEndedPromt"
	},
	seasonArchivedMessage: {
		url: "components/seasonArchivedMessage.html",
		elementId: "seasonArchivedFormDiv",
		className: "SeasonArchivedMessage"
	},
	getActivityReportForm: {
		url: "components/getActivityReport.html",
		elementId: "activityReportFormDiv",
		className: "GetActivityReportForm"
	},
	congratulationsForm: {
		url: "components/congrats.html",
		elementId: "congratsDiv",
		className: "Congratulations"
	},
	seasonExtended: {
		url: "components/congrats_extended.html",
		elementId: "congratsExtendDiv",
		className: "Congratulations"
	}
};

/** Element ids for referencing via $ @type Object */
CommandCenter.elementId =
{
/************************************************/
/* General */
	connectionObserver: "connectionObserver",
	loaderMessage: "mouseLoader",
	pageLoader: "pageLoader",
	welcomeText: "welcomeText",

/************************************************/
/* Teamspace Tab: */

// Container Divs
	blogPostFormDiv: "blogPostFormDiv",
	eventFormDiv: "eventFormDiv",
	editEventDiv: "editEventDiv",
	sendInviteDiv: "sendInvitationDiv",
	sendInviteConfirmationDiv: "inviteConfirmationDiv",
	dailyEventsDiv: "dailyEventsDiv",
	folderContentsDiv: "folderContentsDiv",
	errorMessagesDiv: "errorMessagesDiv",
	messageFormDiv: "messageFormDiv",


// Status Message
	statusMessage: "statusMessage",
	statusMessageText: "statusMessageText",

// Mini Calendar
	miniCalendarContainer: "miniCalendarDiv",
	miniCalendarBackground: "miniCalendarBackground",
	miniCalendarControl: "miniCalendarCtl",
	miniCalendar: "miniCalendar",

// Loaders
	mainCalendarLoader: "mainCalendarLoader",
	teamSpaceActivitiesLoader: "teamSpaceActivitiesLoader",
	blogsLoader: "blogsLoader",

/************************************************/
/* CMM Tab: */

// Container Divs
	createMessageDiv: "createMessageDiv",
	createFolderDiv: "createFolderDiv",
	cmmTemplate: "cmmTemplate",
// Loaders
	messageBoardLoader: "messageBoardLoader",
	knowledgeBaseLoader: "knowledgeBaseLoader"
};
/************************************************/


/** URLs of the pages to load in via ajax */
CommandCenter.ajaxUrl =
{
	header: "components/header.html",
	footer: "components/footer.html",
	footerLinks: "components/footerLinks.html",
	createCMM: "components/createCMM.html",
	publicPageCalendar: "components/publicPageCalendar.html",
	teamCalendar: "components/teamCalendar.html",
	leagueCalendar: "components/leagueCalendar.html",
	publicPageBlog: "components/publicPageBlog.html",
	signIn: "components/signIn.html",
	testConnection: "/gsi/cmm-command.jspa",
	sendInvite: "components/sendAnInvitation.html",
	inviteConfirmation: "components/invitationConfirmation.html",
	mainCalendar: "components/mainCalendar.html",
	teamSpaceActivities: "components/activities.html",
	blogs: "components/blogs.html",
	messageBoard: "components/messageBoard.html",
	messageBoardOrg: "components/messageBoardLeagueOrg.html",
	messageBoardCoach: "components/messageBoardCoach.html",
	teamMessages: "components/messageBoardPlayer.html",
	knowledgeBase: "components/knowledgeBase.html",
	createMessage: "components/createAMessage.html",
	createFolder: "components/createAFolder.html",
	dailyEvents: "components/dailyEvents.html",
	dailyEventsPlayers: "components/dailyEventsPlayers.html",
	folderContents: "components/folderContentsDiv.html",
	googleMapsRouting: "http://maps.google.com/maps?f=q&hl=en&q=",
	printableCalendar: "components/printableCalendar.html",
	activitesReport: "components/activityReport.html",
	leagueSchedule: "components/leagueSchedule.html",
	teamSchedule: "components/teamSchedule.html",
	teamScheduleCoach: "components/teamScheduleCoach.html",
	teamRoster: "components/teamRoster.html",
	leagueTeams: "components/leagueTeams.html",
	//Zparse Templates
	cmmTemplate: "templates/cmmTemplate.zptm"
};

/** Initialize the application */
CommandCenter.initialize = function()
{
//	Hide the debug window if not debugging
	var debugEl = GSI.Debug.element();
//  Add links to debug window
//tag, elId, cssClass, inner, parentEl, childrenArr
	var debugLinks = GSI.$e('div',false,'debugLinks',false,document.body, [
		GSI.$e('div','debug-title','debugTitle','Debug:'),
		GSI.$e('div','debug-clear','debugLink','Clear'),
		GSI.$e('div','debug-toggle','debugLink','Hide')
	]);
	$("debug-clear").observe('click',GSI.Debug.cls.bind(GSI.Debug));
	$("debug-toggle").observe('click',function(){
		var el = GSI.Debug.element();
		$('debug-toggle').update( el.visible() ? 'Show' : 'Hide' );
		el.toggle();
	});
	if( !this.debugMode ) { debugEl.hide(); debugLinks.hide(); }

//	Create the element to show error messages
	this.createErrorMessageContainer();
	var chain = new GSI.MethodChain();
	chain.add( this.loadComponent.bind(this, this.ajaxUrl.header, $("header"), chain.callNext.bind(chain)) );
	chain.add( this.loadComponent.bind(this, this.ajaxUrl.footerLinks, $("footerLinks"), chain.callNext.bind(chain)) );
	chain.add( this.loadComponent.bind(this, this.ajaxUrl.footer, $("footer"), chain.callNext.bind(chain)) );
	chain.add( this.loadApplicationData.bind(this, chain.callNext.bind(chain) ) );
	chain.add( this.loadCurrentPage.bind(this,false) );
	chain.callNext();

	GSI.nowOrLater( this.sportSpaceHelp.bind(this), function() {
		var ret = window && window.document && $("sportSpaceHelp") !== null;
		return ret;
	}, 100 );
};

/** Hide the KB File form */
CommandCenter.hideKBFileForm = function()
{
	this.hideForm( "kbFileForm" );
}

/** Load the current page */
CommandCenter.loadCurrentPage = function( next )
{
	var ds = JiveDataExchange.dataStore;

// 	If the user is authenticated, but the profile data has not been loaded
//	Load the profile data, and return to this process from the start
	if( ds.applicationData.userAuthenticated && !ds.profileData )
	{
		this.loadProfileData( this.loadCurrentPage.bind( this, "setProfile" ) );
		return;
	}


// We have loaded the profile data
	if( next && next == "setProfile" )
	{
		this.userRoleKey = JiveDataExchange.dataStore.profileData.userRole.userRoleKey;
		if( this.userRoleKey !== "communityMarketingManager" )
		{
			GSI.loadStyleSheet( "../include/style-" + this.userRoleKey + ".css", true );
		}
	}


// Get the template (pageName) and parameters for the request
	var pageName = GSI.Location.getPageName().split(".html").join("");
	var params = GSI.Location.getParameters();

//	Get the URL config for the requested document
	var roleSet = this.urls[ "guest" ];
	if( this.userRoleKey ) { roleSet = Object.extend( roleSet, this.urls[ this.userRoleKey ] ); }
	var conf = roleSet[ pageName ];
	if( conf == undefined ) { this.getPage( "index" ); return; }

//	Get the page config for the requested document / page combo
	this.currentPage = params.p || conf.defaultPage;
	var page = conf.pages[ this.currentPage ];
	if( page == undefined ) { this.getPage( "index" ); return;}

	var url = page.url;
	var userAuth = JiveDataExchange.dataStore.applicationData.userAuthenticated;

// If we have an incomplete profile, we are redirected to the appropriate page
	if( page.name !== "logOut" && this.checkProfileIncomplete( pageName ) ) { return; }

//	If the page requires authentication and they are not logged in, redirect
	if( page.auth && !userAuth == true ) { this.authRequired(); return; }

//	If they are logged in and the page should redirect to their dashboard
	if( page.redirectIfLoggedIn && userAuth == true ) {
		var newPage = "dashboard";
		if( this.userRoleKey !== "communityMarketingManager" ) { newPage += this.userRoleKey; }
		this.getPage( newPage );
		return;
	}

//  If the page requires "space" to be set, do it now and callback to this method
	if( page.requireSpace && this.currentSpaceId == undefined )
	{
		this.setCurrentSpace( false, this.loadCurrentPage.bind(this, true ) );
		return;
	}

	this.loadComponent( url, $( this.elementId.pageLoader ), this.loadCurrentPage_complete.bind(this) );
};

/** Get a page
 * @param {String} template			The name of the template (url) to retrieve
 * @param {String} page					The page name
 * @param {Object} params				The parameters for the request
 * @param {Boolean} newWindow 	Open the page in a new window
 */
CommandCenter.getPage = function( template, page, params, newWindow )
{
//	Set the base url for the new document location
	var url = GSI.Location.getCurrentFolder() + "/" + template + ".html";
	var qs = "";

//	Add the page name and parameters to the querystring
	if( params == undefined || params == false ) params = {};
	if( params.p ) { throw "params for getPage must not contain a value for 'p'"; }
	if( page ) params.p = page;
	if( params ) qs = $H( params ).toQueryString();
	if( qs !== "" ) url += "?" + qs;
	var getUrl = location.protocol + "//" + location.hostname + ( parseInt(location.port) !== 80 ? ":" + location.port : "" ) + url;

//	Change the location
	if( newWindow ) return window.open( getUrl );
	location.href = getUrl;
	return true;
};

/** Show a form
 * @param {String} formId				The id of the form to load (see this.forms above)
 * @param {Element} parentEl		The element to append the form element into
 * @param {Object} options			Any options for the form
 * @param {Function} callback		The method to call after form is ready
 */
CommandCenter.showForm = function( formId, parentEl, options, callback )
{

//	Preparations...
	var form = this.forms[ formId ];
	var selfCaller = CommandCenter.showForm.bind( CommandCenter, formId, parentEl, options, callback );
	parentEl = $(parentEl);

	if( !form ) { throw( "Could not find config for form with id [" + formId + "]" ); }
	if( parentEl == null ) { throw( "Could not show form within parent element, element not found within the DOM" ); }

//	Var references...
	var el = $( form.elementId );
	var url = form.url;

// First pass - if the element doesn't exist for the form, create it and load the component via AJAX
// The callback for loadcomponent will make a second run through this method and continue past this check
	if( el == null || $( el.parentNode ) == null || $( el.parentNode ) !== parentEl )
	{
		if( el !== null ) { el.remove(); }
		form.ready = false;
		if( CommandCenter[form.className]) { delete CommandCenter[form.className]; }

		GSI.Debug.writeLine("ShowForm: Creating container...");
	//	We will create the element
		el = GSI.$e( "div", form.elementId, false, false );
		el.hide();
		parentEl.appendChild(el);
		this.loadComponent( url, el, selfCaller );
		return;
	}
	GSI.Debug.writeLine("ShowForm: Container Ready.");
	var instance = CommandCenter[form.className];
	el.addClassName( this.userRoleKey );
	el.hide();
	try {
		["top","left","bottom","right","opacity"].each( function(el,s){ delete el.style[s]; }.bind(null,el) );
	} catch(e) {}

// Check to see if the form has been initialized
	if( form.ready === undefined || form.ready == false || [undefined,null].include(instance) )
	{
		GSI.Debug.writeLine("ShowForm: Initializing class...");
		GSI.nowOrLater(
			function( form,callback ) {
				CommandCenter[ form.className ].initialize();
				form.ready = true;
				callback();
			}.bind(this,form,selfCaller),
			function( form ) {
				var ret = ( CommandCenter[ form.className ] !== undefined &&
					typeof (CommandCenter[ form.className ].initialize) == 'function' );
				return ret;
			}.bind(this,form),
			50
		);
		return;
	}


	GSI.Debug.writeLine("ShowForm: Class Ready.");

// If we have a custom show function, call it
	el.show();
	if( !form.noLightBox ) { this.showLightBox( el ); }
	if( typeof (instance.show) == 'function' ) { instance.show(); }
	GSI.Debug.writeLine("ShowForm: Element Shown.");

//	If there is a formtype within the options, call the form "setFormType" method
	if( typeof (instance.setFormType) == 'function' && options.formType ) {
		GSI.Debug.writeLine("ShowForm: SetFormType called ["+options.formType+"]");
		instance.setFormType( options.formType, options.data );
	}

// Execute the callback method
	if( typeof callback == "function" )	{
		GSI.nowOrLater( function(callback) {
				GSI.Debug.writeLine("ShowForm: Callback Called.");
				callback();
			}.bind(this,callback),
			function( form, instance, el ) {
				return ( form.ready && el.visible() && !el.empty() );
			}.bind( this,form,instance,el ),
			10
		);
	}

	var getYScroll = function() {
		var v1 = 0;
		var v2 = 0;
		var v3 = 0;
		try { v1 = parseInt( window.pageYOffset || 0 ); } catch(e) {v1=0;}
		try { v2 = parseInt( document.documentElement.scrollTop || 0 ); } catch(e) {v2=0;}
		try { v3 = parseInt( document.body.scrollTop || 0 ); } catch(e) {v3=0;}
		return [v1,v2,v3].sortBy(function(s){return s;}).reverse()[0];
	}
	var getXScroll = function() {
		var x1 = 0;
		var x2 = 0;
		var x3 = 0;
		try { x1 = parseInt( window.pageXOffset || 0 ); } catch(e) { x1=0;}
		try { x2 = parseInt( document.documentElement.scrollLeft || 0 ); } catch(e) {x2=0;}
		try { x3 = parseInt( document.body.scrollLeft || 0 ); } catch(e) {x3=0;}
		return [x1,x2,x3].sortBy(function(s){return s;}).reverse()[0];
	}



//	Animate scrolling to bring the form into view
	var sPos = Position.cumulativeOffset(el);
	window.scrollTo( sPos[0], sPos[1]);
}

/**
 * Hide a form
 */
CommandCenter.hideForm = function( formId )
{
//	Preparations...
	var form = this.forms[ formId ];
	if( !form ) throw( "Could not find config for form with id [" + formId + "]" );

//	Get a reference to the form instance
	var instance = this[form.className];

//	Hide everything
	if( instance.hide )	instance.hide();
	if( !form.noLightBox ) this.hideLightBox();
	$( form.elementId ).hide();
}

/**
 * Handle the result of a form submission
 * @param {Object} result		The result of the form submission
 * @param {Element} form		The form
 * @param {Data} data				The eval'ed JSON
 * @return True if OK to proceed, False if not
 * @type Boolean
 */
CommandCenter.handleFormResult = function( result, form, data )
{

	GSI.Debug.writeLine("HandleFormResult: " + (form ? form.id : "unknown form" ));
	GSI.Debug.traceObject({ result: result,form: form,data: data });
	GSI.Debug.writeLine("----------------");

//	Check for General Exceptions
	if( result != true || !data || data.parseError)
	{

		alert( "We are currently experiencing problems with this service, please try again later." );
		return false;
	}

//	Page errors or Form errors
	if( data.pageErrors || data.formErrors )
	{
		this.showErrorMessages( data );
		return false;
	}

//	Everything's good to go, return true
	return true;
}



/** Authorization required for this user, redirect to login page */
CommandCenter.authRequired = function()
{
	this.getPage("index");
}

/** Event for completion of current page load */
CommandCenter.loadCurrentPage_complete = function()
{
	var pageName = GSI.Location.getPageName().split(".html").join("");
	var params = GSI.Location.getParameters();

	var roleSet = this.urls[ "guest" ];
	if( this.userRoleKey ) roleSet = Object.extend( roleSet, this.urls[ this.userRoleKey ] );
	var conf = roleSet[ pageName ];
	if( conf == undefined ) return;

	var page = conf.pages[ this.currentPage ];
	if( page == undefined ) return;

//	If there is a page onload method, call it
	if( page.onLoad !== undefined )
	{
/*
		setTimeout( function()
		{
		//	Get the instance of the page class from the configuration
			var instance = CommandCenter[ page.className ];
		//	Call the method on the instance within its own scope
			instance[ page.onLoad.methodName ].apply( instance, (page.onLoad.parameters || []) );
		}, 500 );
*/
		GSI.nowOrLater( function(page) {
			var instance = CommandCenter[ page.className ];
			instance[ page.onLoad.methodName ].apply( instance, (page.onLoad.parameters || []) );
		}.bind(this,page), function(page) {
			var instance = CommandCenter[ page.className ];
			if( [undefined,null].include(instance) ) { return false; }
			var method = instance[ page.onLoad.methodName ];
			return ( typeof method == 'function' );
		}.bind(this,page), 50 );
	}
}

//________________________________________________________________
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//	Profile Data, Location Data and Application Data / Generics
//________________________________________________________________
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ

	/** Set the user's "space" */
	CommandCenter.setCurrentSpace = function( spaceId, callback )
	{
		GSI.Debug.writeLine("Setting space to: " + spaceId );
		this.currentSpaceId = spaceId;
		JiveDataExchange.loadData( "userSpace", spaceId ? {spaceId: spaceId} : {}, callback );
	}

	/** Load the profile data from Jive */
	CommandCenter.loadProfileData = function( callback )
	{
		GSI.Debug.writeLine("loading profile data");
		JiveDataExchange.loadData( "profileData", {}, callback );
	}

	/** Load the application data from Jive */
	CommandCenter.loadApplicationData = function( callback )
	{
		GSI.Debug.writeLine("loading application data");
		JiveDataExchange.loadData( "applicationData", {}, callback );
	}

	/** Load the location data from Jive */
	CommandCenter.loadLocationData = function( callback )
	{
		GSI.Debug.writeLine("loading location data");
		JiveDataExchange.loadData( "eventLocations", {}, callback );
	}

	/** Load the league data from Jive */
	CommandCenter.loadLeagueData = function( callback )
	{
		GSI.Debug.writeLine("loading league data");
		JiveDataExchange.loadData( "organizerLeagues", {}, callback );
	}

	/** Load the team data from Jive */
	CommandCenter.loadTeamData = function( callback )
	{
		GSI.Debug.writeLine("loading team data");
		JiveDataExchange.loadData( "viewTeam", {}, callback );
	}

	/** Set the welcome message */
	CommandCenter.setWelcomeMessage = function()
	{
		var profileData = JiveDataExchange.dataStore.profileData;
		$(this.elementId.welcomeText).update( profileData.firstName ? "Welcome back, " + profileData.firstName + "!" : "Welcome back!" );
	}


//________________________________________________________________
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//	Connection Manager
//________________________________________________________________
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ

	/** Observe the client connection for stop/resume */
	CommandCenter.observeConnection = function()
	{
	//	Create a connection manager and observe stop and resume every 10 seconds
		this.connectMan = new GSI.Network.ConnectionManager( this.ajaxUrl.testConnection, 10000 );
		this.connectMan.onConnectionStop.observe( "CMMCommandCenter", this.connection_stop, this );
		this.connectMan.onConnectionResume.observe( "CMMCommandCenter", this.connection_resume, this );

	//	Create the observer element and keep it centered to the top of the window
		var el = GSI.$e("div", this.elementId.connectionObserver, false, false, document.body );
		GSI.Position.keepTop( el );
		GSI.Position.hCenterWindow( el );
		el.hide();
	}

	/** Event handler for connection stop */
	CommandCenter.connection_stop = function()
	{
		var el = $(this.elementId.connectionObserver);
		el.addClassName("stopped");
		el.removeClassName("resumed");
		el.update("You have lost the connection to our servers, please wait until this message disappears.<br>Meanwhile, please check your connection for problems.");
		el.show();
	}

	/** Event handler for connection resume */
	CommandCenter.connection_resume = function()
	{
		var el = $(this.elementId.connectionObserver);
		el.removeClassName("stopped");
		el.addClassName("resumed");
		el.update("Connection OK. Please continue.");
		setTimeout( function(el) { el.hide(); }.bind(this,el), 500 );
	}

//________________________________________________________________
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//	General Functionality UI
//________________________________________________________________
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
	/** Return the template text from within the commented innerHTML of an element
	* @param {Element} el		The element to use for templating
	* @return The string to use for template evaluation
	* @type String
	*/
	CommandCenter.templatize = function(el)
	{
		el = $(el);
		var content = el.innerText || el.textContent || el.innerHTML;
		return content.split("<!--").join("").split("-->").join("");
	}

  /** Process the template specified by tempEl using data specified and update container
	* @param {Element} tempEl			The element containing the template
	* @param {Object} data				The data to use in parsing
	* @param {Element} container	The container element to update with the result. optional
	* @return the processed template string
	* @type String
	*/
	CommandCenter.processTemplate = function( tempEl, data, container )
	{

		var zParser = new ZParse( Implementation );
		GSI.Debug.writeLine("Parsing template...");
		var succ = zParser.parse( this.templatize( tempEl ) );

		if( !succ ) GSI.Debug.writeLine( "Could not parse the template in " + tempEl.id );
		var val = zParser.process( data );
		if( container ) container.update( val );
		GSI.Debug.writeLine("Parsing complete.");
		return val;
	}

	/** Create an element to display the error messages
	 * @type Element
 	 */
	CommandCenter.createErrorMessageContainer = function( )
	{
		var el,display,closer;
		if( $( this.elementId.errorMessagesDiv ) == null )
		{
			el = GSI.$e( "div", this.elementId.errorMessagesDiv, false, false );
			display = GSI.$e( "div", false, "display", false, el );
			el["displayDiv"] = display;
			closer = GSI.$e( "div", false, "close button", "Close Errors", el );
			Element.observe( closer, "click", this.hideErrorMessages.bind( this ) );
			GSI.Position.hCenterWindow( el );
			GSI.Position.keepTop( el );
			el.hide();
			document.body.appendChild(el);
		}
		return el || $( this.elementId.errorMessagesDiv );
	}

	/**
	 * Create an element to display error messages
	 * @param {Object} data		The eval'ed JSON object containing error codes
	 * @return An element with the error messages
	 * @type {Element}
	 */
	CommandCenter.createErrorMessageElement = function( data )
	{
		if( data && data.length ) data = { pageErrors: data };

	//	Create the container element
		var errorDiv = GSI.$e( "div", false, "formErrors" );

	//	Get the page errors and field errors
		var pageErrors = data.pageErrors || [];
		var fieldErrors = data.fieldErrors || [];
		var i,len,e,message;

	//	Has page errors
		if( pageErrors.length > 0 )
		{
			var pageErrorsDiv = GSI.$e( "div", false, "pageErrors", false, errorDiv );
			for( i=0,len=pageErrors.length; i<len; i++ )
			{
				e = pageErrors[i];
				message = e.message || e;
				GSI.$e( "div", false, "pageError", message, pageErrorsDiv );
			}
		}

	//	Has field errors
		if( fieldErrors.length > 0 )
		{
			var fieldErrorsDiv = GSI.$e( "div", false, "fieldErrors", false, errorDiv );
			for( i=0,len=fieldErrors.length; i<len; i++ )
			{
				e = fieldErrors[i];
				message = e.message || e;
				GSI.$e( "div", false, "fieldError", message, fieldErrorsDiv );
			}
		}

		return errorDiv;
	}

	/** Show error messages
	 * @param {Object} data		The data that contains the error messages
	 */
	CommandCenter.showErrorMessages = function( data )
	{
	//	Create the messages element
		var messagesEl = this.createErrorMessageElement( data );
		var el = $(this.elementId.errorMessagesDiv);

	//	Update the display and add the messages
		display = el.displayDiv;
		display.update("");
		display.appendChild( messagesEl );

	//	Show the element
		el.show();
		if( el.timeout ) clearTimeout(el.timeout);
		el.timeout = setTimeout( function(el){ el.hide() }.bind( this, el ), 10000 );
	}

	/** Hide error messages */
	CommandCenter.hideErrorMessages = function( )
	{
		$( this.elementId.errorMessagesDiv ).hide();
	}

	/** Show an error when we cannot load necessary data */
	CommandCenter.showDataError = function( result, storeId )
	{
		this.hideLoader("Error loading data");
		this.showErrorMessages( [ "Could not access the servers, please try again later" ], [result.message || result] );
	}

	/** Load a component into an element
	 * @param {String} url 				The url of the component to load
	 * @param {Element} element		The element to hold the component
	 * @param {Function} callback	The onSuccess callback
	 * @param {Object} options		Special object
	 * @return The Ajax Updater object
	 * @type Ajax.updater
	 */
	CommandCenter.loadComponent = function( url, element, callback, options )
	{

		var updater = new Ajax.Updater( element, url, {
			method: "get",
			parameters: ( options && options.params ) ? options.params : {},
			evalScripts: true,
			onSuccess: function(callback) { setTimeout( callback, 0 ); }.bind(this,callback || function(){} )
		});
	}

	CommandCenter.loaderBuffer = { count: 0 };

	/** Show a loading message
	 * @param {String} message - the message to display
	 */
	CommandCenter.showLoader = function( message )
	{
		this.loaderBuffer.count += 1;

		var div = $(CommandCenter.elementId.loaderMessage);

		if( !div )
		{
			div = GSI.$e("div", this.elementId.loaderMessage, false, false, document.body );
			loaderDiv = GSI.$e("div", "mouseLoader-image", false, '<img src="images/mouseLoader.gif" >', div );
			messageDiv = GSI.$e("div", "mouseLoader-message", false, false, div);

			div.loaderDiv = loaderDiv;
			div.messageDiv = messageDiv;

			div.setStyle( {zIndex: 5000, position: "absolute"} );
			messageDiv.innerHTML = "Loading";
			GSI.Mouse.onMove.observe( "commandCenter", this.loader_mouseMove, this );
		}

		div.messageDiv.innerHTML = message;
		div.show();

	}

	/** Mouse move event for the loader */
	CommandCenter.loader_mouseMove = function( pos )
	{
		var div = $(CommandCenter.elementId.loaderMessage);
		if( div == null ) return;
		div.setStyle({
			top: pos.yPos + "px",
			left: pos.xPos + 15 + "px"
		});

	}

	/** Hide the loading message */
	CommandCenter.hideLoader = function( message )
	{
		this.loaderBuffer.count -= 1;
		if( this.loaderBuffer.count > 0 ) return;

		var div = $(CommandCenter.elementId.loaderMessage); if( div == null ) return;
		if( message ) div.messageDiv.update( message );
		setTimeout( function(){
			var div = $(CommandCenter.elementId.loaderMessage);
			if( !div ) return;
			div.hide();
		}, 700 );
	}

	/** Show the lightbox for an element
	 * @param {Element} element 	The element to highlight
	 * @param {Number} opacity		The opacity for the lightbox
	 */
	CommandCenter.showLightBox = function( element, opacity )
	{
		GSI.LightBox.create({
			maxOpacity: opacity || 0.4,
			dataElement: element
		});
	}

	/** Hide the lightbox */
	CommandCenter.hideLightBox = function()
	{
		GSI.LightBox.close( );
	}

//________________________________________________________________
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//	Mini Calendar
//________________________________________________________________
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ

	/** Show the mini calendar
	 * @param {Element} container		The element to append the calendar to
	 * @param {Function} callback		The callback method for onclick
	 * @param {Object} context			The context, or scope - for the callback
	 * @return A reference to the calendar container element
	 * @type Element
	 */
	CommandCenter.showMiniCalendar = function( container, callback, context )
	{
		var calEl = this.createMiniCalendar();

		container.appendChild( calEl );
		this.miniCalendar.onItemClick.observe("teamSpaceMiniCal", callback, context);
		calEl.show();

		return calEl;
	}

	/** Hide the mini calendar */
	CommandCenter.hideMiniCalendar = function( )
	{
		var calEl = this.createMiniCalendar();
		calEl.hide();
		document.body.appendChild(calEl);

	}

	/** Create the mini calendar or return a reference if already created
	 * @return A reference to the mini calendar's container element
	 * @type Element
	 */
	CommandCenter.createMiniCalendar = function( )
	{
	// If the element has already been created, return it
		if( this.miniCalendar !== undefined ) {
			var calEl = $( this.elementId.miniCalendarContainer);
			if( calEl !== null ) { return calEl; }
			delete this.miniCalendar;
		}

	//	Create the container
		container = GSI.$e( "div", this.elementId.miniCalendarContainer, false, false, document.body );
	//	Create an IFrame for IE's form element fix
		container.innerHTML = '<iframe src="javascript:\'<html></html>\'" style="width:100%;height:100%;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);-moz-opacity:0" scrolling="no" frameborder="0" width="100%" height="100%"/>';

	//	Create the background element and set the class for iepngfix.htc behavior
		var bgEl = GSI.$e( "div", this.elementId.miniCalendarBackground, false, false, container);
		Element.addClassName( bgEl, "backgroundPNG" );

	//	Create the calendar and cal control elements
		var ctlEl = GSI.$e( "div", this.elementId.miniCalendarControl, false, false, container );
		var calEl = GSI.$e( "div", this.elementId.miniCalendar, false, false, container );

	//	Create the mini calendar
		this.miniCalendar = new GSI.Calendar("miniCalendar1");
		this.miniCalendar.weekDayNames = ["S","M","T","W","T","F","S"];
		this.miniCalendar.create( calEl );

	//	Create the calendar control
		this.miniCalendarCtl = new GSI.CalendarControl();
		this.miniCalendarCtl.prevTemplate = new Template('<div class="calendarCtl_prev"></div>');
		this.miniCalendarCtl.nextTemplate = new Template('<div class="calendarCtl_next"></div>');
		this.miniCalendarCtl.create( this.miniCalendar, "miniCalendarCtl1", ctlEl, new Date().getMonth(), new Date().getFullYear() );

	//	Add the event listeners
		this.miniCalendar.onItemMouseOver.observe("teamSpaceMiniCal", this.weekDay_onMouseOver, this );
		this.miniCalendar.onItemMouseOut.observe("teamSpaceMiniCal", this.weekDay_onMouseOut, this );

		return container;
	}

	/** MouseOver event for mini calendar @see GSI.Calendar */
	CommandCenter.weekDay_onMouseOver = function( evt, el, cal, date )
	{
		if( el.hasClassName("prevMonth") || el.hasClassName("nextMonth") ) return;
		$(el).addClassName("over");
	}

	/** MouseOut event for mini calendar @see GSI.Calendar */
	CommandCenter.weekDay_onMouseOut = function( evt, el, cal, date )
	{
		if( el.hasClassName("prevMonth") || el.hasClassName("nextMonth") ) return;
		$(el).removeClassName("over");
	}

//________________________________________________________________
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
//	Locations and Addresses
//________________________________________________________________
//////////////////////////////////////////////////////////////////
//ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ

	/** Show directions to an address
	 * @param {String} name		Name for the address
	 * @param {String} addr1	Address Line 1
	 * @param {String} addr2	Address Line 2
	 * @param {String} city		City
	 * @param {String} state	State
	 * @param {String} zip		ZipCode
	 */
	CommandCenter.showDirectionsTo = function( addr1, addr2, city, state, zip )
	{
		var address = ( addr1 || "" ) + " " + ( addr2 || "" ) + ", " + ( city && state ? city + ", " + state : "," ) + " " + ( zip || "" );
		var url = this.ajaxUrl.googleMapsRouting + encodeURI( address );

		try
		{
			window.open( url );
		}
		catch(e)
		{
			alert("Could not open directions. Please disable any popup blockers for this site and try again.");
		}
	}

	/** Show the "Daily Events" form
	 * @param {Date} date		The date to show events for
	 */
	CommandCenter.showDailyEvents = function( date, parent, setEventType )
	{
		
		if(setEventType != undefined){
			this.setEventType = setEventType;
			getDT = date.split('/');
			
			var checkMonth = getDT[0];
			
			if(checkMonth == 0)
			{
				checkMonth = 12;
			}
			else
			{
				checkMonth = checkMonth-1;
			}
				
			JiveDataExchange.loadData("announcementCalendar",{month:checkMonth,year:getDT[2]},this.showDailyEventsPlayer.bind(this,date, parent, setEventType))
		return;}
		else{this.setEventType = false};
		this.showForm( "dailyEvents", parent || $("mainCalendar-calendarContainer"), null, function(d,t) {
				this.DailyEventsForm.loadDayData( d, t );
		}.bind(this,date,setEventType) );
	}
	CommandCenter.showDailyEventsPlayer = function( date, parent, setEventType )
	{
		this.showForm( "dailyEvents", parent || $("mainCalendar-calendarContainer"), null, function(d,t) {
				this.DailyEventsForm.loadDayDataAnncouncement( d, t );
		}.bind(this,date,setEventType) );
		
	}
	

	/** Hide the "Daily Events" form */
	CommandCenter.hideDailyEvents = function( )
	{
		this.hideForm( "dailyEvents" );
	}

/** Refresh the list of event locations */
	CommandCenter.refreshEventLocations = function( callback )
	{
		JiveDataExchange.loadData( "eventLocations", {}, callback );
	}

/** Sign in has been successful */
	CommandCenter.signInSuccess = function( data )
	{
		this.loadProfileData( this.signInSuccess_profileComplete.bind( this, data ) );
	}

/**
 * Check to see if the profile is incomplete.
 * @param pageName {String} the name of the page being requested
 */
	CommandCenter.checkProfileIncomplete = function( pageName, postSignIn )
	{
		var profileData = JiveDataExchange.dataStore.profileData;
	// Check to see if we have profile data and user role, if not, resume normally
		if( !profileData || !profileData.userRole ) { return false; }

		var role = profileData.userRole.userRoleKey || "guest";
		var c = profileData.profileIncomplete || false;

	// If the profile is not incomplete, proceed normally
		if( !c ) { return false; }

	// mapping of role to array values
	// Array values are [0]=template,[1]=page
		var icData =
		{
			communityMarketingManager: ["dashboard","setupPublicPage"],
			corporateAdmin: ["dashboardcorporateAdmin","setupPublicPage"],
			coach: ["dashboardcoach","createNewTeam",{invitationCode:"false"}],
			leagueOrganizer: ["dashboardleagueOrganizer","createLeague"]
		};

	// If the profile is incomplete, go to the page needed to view it
	// If we do not have values within our icData for this user role, continue normally
		var values = icData[role];
		if( values === undefined ) { return false; }

	// Get the template(t), page(p), params(u)
		var t = values[0];
		var p = values[1];
		var u = values[2];

	//	We are already on the page to be viewed for profile incomplete
		if( t == pageName && this.currentPage && this.currentPage == p ) { return false; }

	//	Get the page required for incomplete profile for this user role
		this.getPage( t, p , u);
		return true;
	}

/** Loaded profile data, check roles etc */
	CommandCenter.signInSuccess_profileComplete = function( data )
	{
		var profileData = JiveDataExchange.dataStore.profileData;
		var role = profileData.userRole.userRoleKey;

	// If the profile is incomplete, a call to getPage has already occurred
		if( this.checkProfileIncomplete() ) { return; }

	//	Get the template for the user's dashboard
		var roleDash = "dashboard";
		if( role !== "communityMarketingManager" ) { roleDash += role; }

	//	Load the dashboard for the user
		this.getPage( roleDash );
	}

	CommandCenter.viewPublicPage = function()
	{
		var ds = JiveDataExchange.dataStore;
		if( ds.applicationData.userAuthenticated && this.userRoleKey && this.userRoleKey == "corporateAdmin" ) {
			this.getPage("index","corporatePublicPage",false, true);
			return;
		}
		this.getPage("index","viewPublicPage",false,true);
	}

	CommandCenter.sportSpaceHelp = function()
	{
		if( !$("sportSpaceHelp") ) { return; }
		Event.observe($("sportSpaceHelp"),"click",this.showHelp.bind(this));
	}

	CommandCenter.showHelp = function()
	{
		this.showForm( "sshForm", document.body, null, this.positionHelp.bind(this), true );
	}

	CommandCenter.positionHelp = function()
	{
		var e = $("sshFormDiv");
		if( e == undefined || e == null ) {
			GSI.nowOrLater( this.positionHelp.bind(this), function(e) {
				return ![undefined,null].include(e);
			}.bind(this,e), 50 );
//			setTimeout( this.positionHelp.bind(this), 50 );
		}
		var hw = parseInt( GSI.Dimensions.getBodySize().height );
		var he = parseInt( GSI.Dimensions.getElementSize(e).height );
		if( isNaN(parseInt(he)) || he < 120  ) { setTimeout( this.positionHelp.bind(this), 50 ); }
		var newTop = (hw-he-35)+"px";
		e.setStyle({top: newTop});
		e.setStyle({top: newTop});
	}
	CommandCenter.hideHelp = function()
	{
		this.hideForm("sshForm");
	}

/** Leaving Sport Space Redirect */
	CommandCenter.leavingSportSpace = function(url)
	{	
		
		var userAuth = JiveDataExchange.dataStore.applicationData.userAuthenticated;
		if(userAuth == true)
		{
			var newPage = "dashboard";
			if( this.userRoleKey !== "communityMarketingManager" ) { newPage += this.userRoleKey; }
			this.getPage(newPage,"leavingSportSpace",{newURL:url,leavingPage:newPage}) ;
			return;

		}
		else
		{
			this.getPage("index","leavingSportSpace",{newURL:url,leavingPage:"index"});
		}
		return;
	}

/** Show the Email Updates Form */
	CommandCenter.showEmailUpdatesForm = function()
	{
		this.showForm( "emailUpdatesForm", $("hdrRight") );
	}
