//
// State.js - Mantenimiento del estado
//
// $Id: state.js 1.5 2008/10/14 13:39:39 jordinas Exp $
//
// Joan Ordinas - <jordinas@EscolaDelTreball.ORG>
//

// Cookie - Objetos persistentes en base a cookies
function Cookie(sName, sScope, nExpires, sDomain) {
	var j, i = document.cookie.indexOf(sName+"_=");
	// uso '_' para distinguir de otras propiedades, que sí se guardan
	this._name = sName;
	this._scope = sScope;
	this._expires = nExpires;
	// domain está por implementar...
	if (i == -1) {	// no se ha recibido la galleta
		this.inicio = new Date().getTime();
	} else {
		i = document.cookie.indexOf("=", i)+1;
		j = document.cookie.indexOf(";", i);
		if (j == -1) j = document.cookie.length;
		var aPair, aVariables = document.cookie.substring(i, j).split("&");
		for (i in aVariables) {
			aPair = aVariables[i].split("=");
			switch (aPair[0]) {
				case "N":
					this[aPair[1]] = Number(unescape(aPair[2]));
					break;
				case "S":
					this[aPair[1]] = unescape(aPair[2]);
					break;
				case "B":
					this[aPair[1]] = (aPair[2] === "1");
					break;
				default:
					break;
			}
			// por ahora solo se soportan los 3 tipos primitivos básicos
		}
	}
}

Cookie.prototype.save = function () {
	function expireDate(nSeconds) {
		if (!nSeconds) return "";
		var nMilliseconds = (new Date().getTime())+nSeconds*1000;
		return "; expires="+new Date(nMilliseconds).toGMTString();
	}
	var aState = [ ], i = 0;
	for (var p in this) {
		if (p.charAt(0) == "_") continue;	// propiedad privada
		switch (typeof this[p]) {
			case "number":
				aState[i++] = "N="+p+"="+escape(this[p]);
				break;
			case "string":
				aState[i++] = "S="+p+"="+escape(this[p]);
				break;
			case "boolean":
				aState[i++] = "B="+p+"="+(this[p] ? "1" : "0");
				break;
		}
	}
	var sCookie =
		this._name+"_="+aState.join("&")+
		expireDate(this._expires)+
		"; path="+(this._scope || "/")+
		";";
	document.cookie = sCookie;
}

Cookie.prototype.expire = function () {
	this._expires = -7777;
	this.save();
}

// Diccionario de propiedades de perfil y sesión
//	State.Profile.language		-- idioma
//	State.Profile.lastPage		-- última pŕgina visitada
//	State.Session.active		-- sesión activa?
//	State.Session.currentPage	-- página actual
//	State.Session.mail			-- mensaje de mail mostrado?
//	State.Session.printer		-- mensaje de printer mostrado?
//	...

function _State(sLang) {
	// asume: util_Initialize();
	this.Session = new Cookie("Session", "/");
	this.Profile = new Cookie("Profile", "/", 60*60*24*15);// 15 dias
	this.Session.currentPage = location.href;
	if (sLang) {
		this.Profile.language = sLang;
	}
}

/* OBSOLET 
_State.prototype.gotoLast = function () {
	if (!this.Session.active
		&& this.Profile.lastPage
		&& this.Profile.lastPage !== location.href)
	{
		var ok = confirm(g_msg_last);
		if (ok) {
			location.href = this.Profile.lastPage;
		}
	}
}
*/

_State.prototype.save = function () {
	this.Profile.lastPage = this.Session.currentPage;
	delete this.Session.currentPage
	this.Session.active = true;
	this.Session.save();
	this.Profile.save();
}

// Para trocear url-encoded strings
function parseQueryString(sQuery) {
	if (!sQuery) return null;
	if (sQuery.charAt(0) === "?") sQuery = sQuery.substr(1);
	if (!sQuery) return null;
	var oDictionary = new Object();
	var aVariables = sQuery.split("&");
	for (var i in aVariables) {
		var aPair = aVariables[i].split("=", 2);
		oDictionary[unescape(aPair[0])] = unescape(aPair[1]);
	}
	return oDictionary;
}

