(function() {
	// globals
	MyApp.Utils = {};


	// utility functions
	MyApp.Utils.getUrlParameter = function(name) {
		name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
		var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
		var results = regex.exec(location.search);
		return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
	};

	MyApp.Utils.removeURLParameter = function(url, parameter) {
		//prefer to use l.search if you have a location/link object
		var urlparts = url.split('?');
		if (urlparts.length >= 2) {

			var prefix = encodeURIComponent(parameter) + '=';
			var pars = urlparts[1].split(/[&;]/g);

			//reverse iteration as may be destructive
			for (var i = pars.length; i-- > 0;) {
				//idiom for string.startsWith
				if (pars[i].lastIndexOf(prefix, 0) !== -1) {
					pars.splice(i, 1);
				}
			}

			return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
		}
		return url;
	};


	// app functions
	MyApp.renderShell = function() {
		document.title = i18next.t('vanillaJS');

		var d = $.Deferred();

		//preload this template, so we can be sure the dom in rendered when we resolve
		ejs.preloadTemplate('/templates/main.ejs')
		.then(function(templateUrl) {
			$('.js-main-content').html(ejs.rr(templateUrl));
			d.resolve();
		});
		return d;
	};

	MyApp.renderHomePage = function() {
		$('.js-page-container').html(ejs.rr('/templates/home.ejs'));
	};

	MyApp.renderTextPage = function() {
		$('.js-page-container').html(ejs.rr('/templates/sometext.ejs', {
			texts: [
				{
					id: 100,
					description: 'Some text with id 100'
				},
				{
					id: 200,
					description: 'Some other text with id 200. Click it!'
				}
			]
		}));
	};

	MyApp.renderAboutPage = function() {
		$('.js-page-container').html(ejs.rr('/templates/about.ejs'));
	};

	// events
	$(document).on('click', '.js-link', function(ev) {
		var el = $(ev.currentTarget);
		var linkId = el.attr('data-id');
		PNotify.success('The text you clicked had id ' + linkId + '. Maybe next time I will do something with this id.');
	});


	// app startup

	// set language
	i18next
	.use(i18nextBrowserLanguageDetector)
	.init({
		lng: MyApp.config.lang,
		detection: {
			order: ['querystring', 'cookie', 'navigator'],
			lookupQuerystring: 'lang',
			lookupCookie: 'current-language',
			caches: ['cookie'],
			cookieMinutes: 5256000
		},
		fallbackLng: 'en',
		resources: {
			en: {
				translation: {
					'vanillaJS': 'vanillaJS seed project',
					'awesome': 'This is an awesome app!'
				}
			},
			it: {
				translation: {
					'vanillaJS': 'progetto di esempio vanillaJS',
					'awesome': 'Questa app è fantastica!'
				}
			},
			de: {
				translation: {
					'vanillaJS': 'vanillaJS Beispiel Projekt',
					'awesome': 'Coole app.'
				}
			}
		}
	})
	.then(function() {
		// language initialized
		// if there is a lang query string parameter, remove it and reload: we save the language in a cookie so the url stays nice
		if (MyApp.Utils.getUrlParameter('lang')) {
			var newUrl = MyApp.Utils.removeURLParameter(window.location.toString(), 'lang');
			//removeURLParameter does not return the hash. add it back if there is one.
			newUrl = newUrl + window.location.hash;
			window.location = newUrl;
		}

		// render main shell
		MyApp.renderShell()
		.then(function() {
		//setup routing
			page('/', MyApp.renderHomePage);
			page('/about', MyApp.renderAboutPage);
			page('/text', MyApp.renderTextPage);

			page({
				hashbang: true
			});
		});
	});

})();
