(function(){

	var $;
	var $$;
	var JS_BASE = '/javascripts';

	var app = window.HiDevWeb = window.HiDevWeb && window.HiDevWeb.config ?  window.HiDevWeb : { config : { hostName : 'hidev.it' } };

	app.config.base = ('https:' == document.location.protocol ? 'https://' : 'http://') + app.config.hostName;

	window.onHyperDriveReady = function(){
		$$ = window.HyperDrive;
		$$.app = app;
		$ = $$.$;

		//Init HyperDrive
		$$.init({
			appName:'HiDevWeb',
			jsBase : JS_BASE,
			refreshJs : app.config.isLocal,
			rootElementId:'hidev-root'
		}, function onHyperDriveInit(){
			$$.debug('HyperDrive inited');

			//Load Google Analytics
			var _gaq = window._gaq = window._gaq || [];
			_gaq.push(['_setAccount', 'UA-26418593-1']);
			_gaq.push(['_setDomainName', 'hyperdev.it']);
			_gaq.push(['_setAllowLinker', true]);
			_gaq.push(['_trackPageview']);

			$$.injectScriptAdvanced(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', function(){
				$$.debug('Google Analytics loaded');
			});

			$$.injectScriptAdvanced('libs/less-1.2.2.min', function(){
				$$.debug('Less loaded');
			});

			//Load the API library
			$$.injectScriptAdvanced('hidev.api', function onApiClassLoaded(){
				$$.debug('HiDevApi loaded');
				app.api = new $$.classes.HiDevApi();
				app.api.configGet(function(err, response){
					if(err) {
						$$.trace('Failed to load config');
					}
					else {
						$$.debug('Config loaded', app.config);
						app.config = $.extend(app.config, response);

						$(function(){
							$$.debug('DOM ready, loading components');

							//load the HiDevPages widget
							$$.injectScriptAdvanced(['hidev.floaters', 'hidev.header', 'hidev.menu', 'hidev.pages'], function onPagesClassLoaded(){
								$$.debug('HiDevPages loaded');

								$.extend(app, {
									floaters : new $$.classes.HiDevFloaters(),
									header : new $$.classes.HiDevHeader(),
									menu : new $$.classes.HiDevMenu(),
									pages : new $$.classes.HiDevPages()
								});

								$$.addPageComponent(app.floaters);
								$$.addPageComponent(app.header);
								$$.addPageComponent(app.pages);

								$('body').keydown(function(e){
									if($.inArray(e.which, [35, 36, 38, 40])!==-1) {
										app.pages.$element.trigger(e);
									}
								});
							});

						});
					}
				});
			});


		});
	};

	//load HyperDrive
	var a = document.createElement("script");
	a.async = true;
	a.src = app.config.base + JS_BASE + '/hyperdrive/hyperdrive.js' + (app.config.isLocal ? '?_=' + Date.now() : ''); //FIXME: ONLY ADD RANDOM IF LOCAL
	document.getElementsByTagName('head')[0].appendChild(a);

})();
