
/********************** Persistance Object Information and Functions *************/

function PObject(name,defaults,onload){
	if (!name){
		name=window.location.pathname;
		var pos = name.lastIndexOf("/");
		if (pos != -1) name = name.substring(pos+1);
	}
	this.$name = name;
	this.$init(name, defaults, onload);
}

PObject.prototype.save = function(lifetimeInDays){
	var s ="";
	for(var name in this){
		if (name.charAt(0) == "$") continue;
		var value = this[name];
		var type = typeof value;
		if (type == "object" || type == "function") continue;
		if (s.length > 0) s += "&";
		s += name + ':' + encodeURIComponent(value);
	}
	this.$save(s, lifetimeInDays);
};

PObject.prototype.forget = function(){
	for (var name in this){
		if (name.charAt(0) == '$') continue;
		var value = this[name];
		var type = typeof value;
		if (type == "function" || type == "object") continue;
		delete this[name];
	}
	this.$save("",0);
};

PObject.prototype.$parse = function(s, defaults){
	if (!s){
		if (defaults) for(var name in defaults) this[name] = defaults[name];
		return;
	}
	var props = s.split('&');
	for(var i=0; i<props.length; i++){
		var p = props[i];
		var a = p.split(':');
		this[a[0]] = decodeURIComponent(a[1]);
	}
};

var isIE = navigator.appName == "Microsoft Internet Explorer";

if (isIE){
	PObject.prototype.$init = function(name, defaults, onload){
		var div = document.createElement("div");
		this.$div = div;
		div.id = "PObject" + name;
		div.style.display = "none";
		div.style.behavior = "url('#default#userData')";
		document.body.appendChild(div);
		div.load(name);
		var data = div.getAttribute("data");
		this.$parse(data, defaults);
		if(onload){
			var pobj = this;
			setTimeout(function(){ onload(pobj, name);}, 0);
		}
	}
	PObject.prototype.$save = function(s, lifetimeInDays) {
		if (lifetimeInDays){
			var now = (new Date()).getTime();
			var expires = now + lifetimeInDays * 24 * 60 * 60 * 1000;
			this.$div.expires = (new Date(expires)).toUTCString();
		}
		this.$div.setAttribute("data", s);
		this.$div.save(this.$name);
	};
}else {
	PObject.prototype.$init = function(name, defaults, onload) {
		var allcookies = document.cookie;
		var data = null;
		var start = allcookies.indexOf(name + '=');
		if (start != -1){
			start += name.length +1 ;
			var end = allcookies.indexOf(';', start);
			if (end == -1) end = allcookies.length;
			data = allcookies.substring(start, end);
		}
		this.$parse(data, defaults);
		if (onload){
			var pobj = this;
			setTimeout(function() { onload(pobj, name);}, 0);
		}
	};
	PObject.prototype.$save = function(s, lifetimeInDays) {
		var cookie = this.$name + '=' + s;
		if (lifetimeInDays != null){
			cookie += "; max-age=" + (lifetimeInDays*24*60*60);
		}
		document.cookie = cookie;
	};
}


