// Generic functions for cookie manipulation
// courtesy of www.quirksmode.com/
function setCookie(name, value, days, context, domain) {
	var cookieStr;
	var expires;
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		expires = "";
	}
	if (context) {
	} else {
		context ="/";
	}
	cookieStr = name + "=" + value + expires + "; path=" + context;
	if (domain) {
		cookieStr += "; domain=" + domain;
	}
	document.cookie = cookieStr;
	// debug variable here
	var newCookieList = document.cookie;
	// how to print?
	// myLog('cookie='+newCookieList);
}

function readCookie(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;
}

// Erase a cookie by setting the timeout to imediate
function eraseCookie(name, context, domain) {
	setCookie(name, "", -1, context, domain);
}
//==========================================================================

// This function will clean all cookies that are likely to cause problem because the structure
// of the website changed. If these cookies are left the website behaviour becomes unpredictable
function cleanOldCookies() {
	var value = readCookie('language');
	eraseCookie('language', '/site/');
	if (value) {
		setCookie('language', value, 120);
	}
}

// Check if the user has a persistent language preference
// If it has use it to send it to the english or french home page
// Otherwise redirect based on the Accept-Language preference
function redirect(defLang) {
	var value = readCookie('language');
	if (value == "en") {
		cleanOldCookies();
		setCookie('language', value, 120);
		window.location = "/en/home/index.html";
	} else if (value == "fr") {
		cleanOldCookies();
		setCookie('language', value, 120);
		window.location = "/fr/home/index.html";
	} else {
		// force the cookie
		setCookie('language', defLang, 120);
		window.location = "/"+defLang+"/home/index.html";
	}
}


