﻿/**
 * @projectDescription Master file for Nike Playmaker. Loads in other JS files as necessary based on the current page
 * @dependencies MooTools v1.11
 * 
 * @author Den Odell dennis.odell@akqa.com
 */


/**
 * @classDescription Playmaker namespace to encapsulate all scripts
 */
var Playmaker = new Hash({
	hasLoaded: false,
			
	/**
	 * Site-wide settings
	 */
	Settings: new Hash({
		googleAPIkey: '',
		locale: ''
	}),
	
	/**
	 * Series of switches to determine current section loaded
	 */
	Section: new Hash({
		isCalendar: false,
		isHome: false,
		isFixture: false,
		isFixtureBeingCreated: false,
		isFixtureEditable: false,
		isPlayerManagement: false,
		isProfileLocation: false,
		isImportContacts: false,
		isAccountManagement: false
	}),
	
	init: function() {
		window.addEvent('domready', this.onDomReady.bind(this));
		window.addEvent('load', this.onLoad.bind(this));
	},
	
	/**
	 * Finds which JavaScript files to load, then loads them all in order
	 */
	onDomReady: function() {
		this.populateSettings();
		this.setSectionByPageId(this.getPageId());
		this.loadPrimaryScripts();
	},
	
	/**
	 * Loads less important JavaScript files
	 */
	onLoad: function() {
		this.loadSecondaryScripts({
			onload: function() {
				Playmaker.hasLoaded = true;
			}
		});
	}
});

Playmaker.Page = {}
Playmaker.Widgets = {}

Playmaker.extend({	
	/**
	 * Populates Playmaker.Settings with Google API key and locale values from query string of playmaker.js script src value
	 */
	populateSettings: function() {
		$ES('script')
		.filter(function(script) {
			return (script.src && script.src.match(/playmaker\.js(\?.*)?$/))
		})
		.each(function(script) {
		    var path = script.src.replace(/playmaker\.js(\?.*)?$/,'');
		    var queryString = script.src.replace(path + 'playmaker.js?', '').split('&');
			for (var queryStringIndex = 0; queryStringIndex < queryString.length; queryStringIndex++) {
				if (queryString[queryStringIndex].contains('googleAPIKey')) {
					this.Settings.set('googleAPIkey', queryString[queryStringIndex].split('=')[1]);
				} else if (queryString[queryStringIndex].contains('locale')) {
					this.Settings.set('locale', queryString[queryStringIndex].split('=')[1]);
				}
			}
	    }.bind(this));
	},
	
	/**
	 * Gets the value of the 'id' attribute of the <body> tag
	 */
	getPageId: function() {
		return $E('body').get('id');
	},
	
	/**
	 * Sets Playmaker.Section based on the value of the input string
	 * 
	 * @param {String} pageId
	 */
	setSectionByPageId: function(pageId) {
		switch (pageId) {
			case 'calendar-month-page':
			case 'calendar-list-page':
			case 'calendar-week-page':
				Playmaker.Section.set('isCalendar', true);
				break;
				
			case 'create-game-page':
				Playmaker.Section.set('isFixture', true);
				Playmaker.Section.set('isFixtureBeingCreated', true);
				Playmaker.Section.set('isFixtureEditable', true);
				break;
				
			case 'edit-game-page':
				Playmaker.Section.set('isFixture', true);
				Playmaker.Section.set('isFixtureEditable', true);
				break;
				
			case 'view-game-page':
			case 'view-game-invitation-page':
				Playmaker.Section.set('isFixture', true);
				break;
				
			case 'home-page':
				Playmaker.Section.set('isHome', true);
				break;
				
			case 'players-page':
				Playmaker.Section.set('isPlayerManagement', true);
				break;
				
			case 'location-page':
				Playmaker.Section.set('isProfileLocation', true);
				break;
	
			case 'edit-profile-page':
			case 'registration-page':
				Playmaker.Section.set('isAccountManagement', true);
				break;
				
			case 'import-page':
				Playmaker.Section.set('isImportContacts', true);
				break;
				
			default:
				break;
		}
	},
	
	/**
	 * Establishes which components to load based on the values set in Playmaker.Section
	 */
	getComponentsBySection: function() {
		var componentList = new Array();
        
        componentList.include({
            script: 'playmaker.mandatory',
            onload: function(){
                Playmaker.Mandatory.init();
            }
        });
			
		if (Playmaker.Section.get('isCalendar')) {
			componentList.include({
				script: 'playmaker.page.calendar',
				onload: function(){
					Playmaker.Page.Calendar.init();
				}
			});
		}
		
		if (Playmaker.Section.get('isFixture')) {
			componentList.include({
				script: 'playmaker.providers'
			});
			componentList.include({
				script: 'playmaker.widgets'
			});
			componentList.include({
				script: 'playmaker.widgets.dateselector'
			});
			if (Playmaker.Section.get('isFixtureEditable')) {
				componentList.include({
					script: 'playmaker.page.game.editable',
					onload: function() {
						//Playmaker.Game.Editable.init();
					}
				});
			} else {
				componentList.include({
					script: 'playmaker.page.game.viewable',
					onload: function(){
						//Playmaker.Game.Viewable.init();
					}
				});
			}
		}
		
		if (Playmaker.Section.get('isPlayerManagement')) {
			componentList.include({
				script: 'playmaker.page.players',
				onload: function(){
					Playmaker.Players.init();
				}
			});
		}
		
		if (Playmaker.Section.get('isImportContacts')) {
			componentList.include({
				script: 'playmaker.page.importcontacts',
				onload: function(){
					Playmaker.Page.ImportContacts.init();
				}
			});
		}
		
		if (Playmaker.Section.get('isProfileLocation')) {
			componentList.include({
				script: 'playmaker.page.loc',
				onload: function(){
					Playmaker.Page.Loc.init();
				}
			});
		}
		
		if (!Playmaker.Section.get('isHome')) {
			componentList.include({
				script: 'playmaker.banner',
				onload: function(){
					Playmaker.Banner.init();
				}
			});
		}

		return componentList;
	}
});


Playmaker.extend({
	/**
	 * Loads important JavaScript files
	 */
	loadPrimaryScripts: function() {
		Document.Scripts.add('/playmaker/library/js/' + Playmaker.Settings.locale + '/playmaker.locale.js', {
			onload: function(){
				var intervalLocale = window.setInterval(function() {
					if (Playmaker.Locale) {// We really need this script to have loaded before we continue
						window.clearInterval(intervalLocale);
						Document.Scripts.add('/playmaker/library/js/playmaker.ui.js', {
							onload: function(){
								var intervalUI = window.setInterval(function() {
									if (Playmaker.UI) {// We really need this script to have loaded before we continue
										window.clearInterval(intervalUI);
										Playmaker.UI.init();
										this.getComponentsBySection().each(function(component) {
											Document.Scripts.add('/playmaker/library/js/' + component.script + '.js', {
												check: (component.object),
												onload: function(){
													if (component.onload) {
														component.onload()
													}
													
												}
											});
										});
									}
								}.bind(this), 50);
							}.bind(this),
							check: function(){return Playmaker.UI}
						});
					}
				}.bind(this), 50);
			}.bind(this),
			check: function(){return Playmaker.Locale}
		});
	},
	
	/**
	 * Loads less important JavaScript files
	 */
	loadSecondaryScripts: function(options) {
		if ($('tout')) Document.Scripts.add('/playmaker/library/js/playmaker.survey.js');
        if (navigator.vendor && navigator.vendor.indexOf('Apple') > -1) {
            new Element('link',{
                'type': 'text/css',
                'rel': 'stylesheet',
                'href': '/playmaker/library/css/screen/safari/common.css',
                'media': 'screen'
            }).injectInside($E('head'));
        }
		Document.Scripts.add('/playmaker/library/js/playmaker.tracking.js', {
			onload: (typeof(options.onload) == 'function' ? options.onload : function(){}),
			check: function() {
				return Playmaker.Tracking;
			}
		});
	}
});

Playmaker.init();