/*
LangPrefCookie.js

Methods for setting, unsetting, getting a/the language preference cookie and managing the lang_pref drop-down

Assuming that we will only need to use one of these per domain, the default cookie consumed by the server is 'prefer-language'.
It should merely contain a 2 letter language code.

When managing the drop-down to set it to the current cookie value, we will be looking for an element with this id: cboLangPrefCookie
*/

// for now we will go with a session cookie... if we want to make it persistent, then change this to the number of days
var days = undefined;
var def_ckname = "prefer-language";

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;
}

function setLangPrefCombo(ckname){
	if (! ckname){ ckname = def_ckname; }
	var ck = readCookie(ckname);

	// if the value is empty, we are done
	if (! ck){ return; }
	
	// we are going to look by default for this control
	var combo = document.getElementById('cboLangPrefCookie');
	
	// if the combo cannot be identified, we are done
	if (! combo){ return; }
	
	for (var x=0; x < combo.options.length; x++){
		if (combo.options[x].value == ck){
			combo.options[x].selected = 'selected';
			break;
		}
	}
}

function setLangPrefCookie(lang, path, ckname){
	if (! path){ path = '/'; }
	if (! ckname){ ckname = def_ckname; }
	if (! lang){
		days = -1;
	}

	// lang could simply be the drop-down control itself
	// in that case we want to get the selected language
	if (typeof lang == 'object'){ lang = lang.options[lang.selectedIndex].value; }

	var expires = '';
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days *24*60*60*1000));
		expires = "; expires=" + date.toGMTString();
	}
	else { var expires = ""; }
	document.cookie = ckname + "=" + lang + expires + "; path=" + path;

	window.location.reload();
}