/**
 * Base CG object
 * 
 * Provides a set of constants and utility functions in addition
 * to a namespace for all shared CG libraries.
 * 
 * @requires jQuery
 */

/**
 * Check object dependancies and throw an error if they aren't met
 * 
 * @param String|Array obj The name of an object, or array of objects, to check
 * @param String lib The name of the script that requires these objects
 * @param Function handler Optional callback to call instead of throwing an error
 * @return void
 */
function require(obj, lib, handler) {
	if(Object.prototype.toString.call(obj) !== '[object Array]') {
		obj = [obj];
	}
	
	if(typeof(lib) === 'function') {
		handler = lib;
		lib = undefined;
	}
	
	var badnews = [], len = obj.length, i, msg;
	
	for(i = 0; i < len; i++) {
		try {
			if(eval('typeof(' + obj[i] + ') === \'undefined\'')) {
				throw 'Bad voodoo';
			}
		} catch(e) {
			badnews.push(obj[i]);
		}
	}
	
	if(badnews.length) {
		if(typeof(handler) === 'function') {
			handler();
		} else {
			msg = lib ? 
				lib + ' requires ' + badnews.join(' and ') + ' to be loaded' : 
				badnews.join(' and ') + ' ' + (badnews.length > 1 ? 'are' : 'is') + ' required to be loaded';
			alert(msg);
			throw {name: 'CGDependencyException', message: msg};
		}
	}
}

require('jQuery', 'CG');
require('console', function() {
	window.console = {
		log: function() {},
		warn: function() {},
		info: function() {}
	};
});

(function($) {
	
	/**
	 * Global CG namespace
	 * 
	 * @type Object
	 */
	CG = $.extend(true, typeof(CG) === 'undefined' ? {} : CG, {

		/**
		 * Stores configurable options for shared code.  To set an option for some
		 * other library (CG.FriendManager for example) define a CG.FriendManager object
		 * with those options before the CG.FriendManager script is loaded.
		 * 
		 * @type Object
		 */
		options: typeof(CG) === 'undefined' ? {} : CG.options || {},
		
		/**
		 * Lists all CG Games and various properties of those games
		 * 
		 * @type Object
		 * @todo Would love to pull this out of this file and into some centralized service
		 */
		GAMES: {
			18: {name: 'Warstorm', link: 'http://apps.facebook.com/warstorm', hasBulletins: true, description: 'Fight evil in this fantasy game!'},
			15: {name: 'Ponzi Inc', link: 'http://apps.facebook.com/ponzi_inc', hasBulletins: true, description: 'Be the tycoon of your own company!'}
		},
		
		/**
		 * CakePHP debug level
		 * 
		 * @type Int
		 */
		DEBUG: 2,
		
		/**
		 * Global events
		 */
		events: {
			
			/**
			 * Startup event fires on document.ready
			 * 
			 * Defined in event.js. stupid...
			 */
			startup: (function() {
				
				$(document).ready(function() {
					require('CG.Event', 'CG');
					CG.events.startup.fire();
				});
				
				return null;
			})()
		}		
	});
})(jQuery);
