// this file is here so it can correctly handle the language parameter

(function() {
	if (typeof(window.MyApp) === 'undefined') {
		window.MyApp = {};
	}
	if (typeof(window.MyApp.config) === 'undefined') {
		window.MyApp.config = {};
	}

	var languageCookieName = 'current-language';
	var validLanguages = ['de', 'it', 'en', 'rm'];

	var 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, ' '));
	};

	var setCookie = function(name, value, days) {
		var expires = '';
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = '; expires=' + date.toUTCString();
		}
		document.cookie = name + '=' + (value || '') + expires + '; path=/';
	};

	var getCookie = function(name) {
		var nameEQ = name + '=';
		var ca = document.cookie.split(';');
		for (var i = 0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {c = c.substring(1, c.length);}
			if (c.indexOf(nameEQ) == 0) {return c.substring(nameEQ.length, c.length);}
		}
		return null;
	};

	var delCookie = function(name) {
		document.cookie = name + '=; Max-Age=-99999999;';
	};

	var 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;
	};


	// try to get the language:
	// first check if there is a lang query string parameter
	var langQ = getUrlParameter('lang');
	var selectedLang = validLanguages[0];
	if (langQ && validLanguages.indexOf(langQ) >= 0) {
		selectedLang = langQ;
		setCookie(languageCookieName, langQ);

		//reload the page without the lang parameter. we use the cookie now.
		var newUrl = 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;
		return;
	}

	var langC = getCookie(languageCookieName);
	if (langC && validLanguages.indexOf(langC) >= 0) { //get the language from the cookie
		selectedLang = langC;
	} else { //get the language from the browser
		var langN = window.navigator.userLanguage || window.navigator.language;

		if (langN && validLanguages.indexOf(langN) >= 0) {
			selectedLang = langN;
		}
	}

	//export selected lang to app
	MyApp.config.lang = selectedLang;

})();
