// Let's you construct a session out of a json one loaded from the server.
// caveat: we made the assumption that we're keeping arrays instead of the explicit
// contents of the server session in this js object.  That's for convenience w/
// the client side js which deals with arrays not csv's.
PServerSession = function(o) {
	this.data = {};
	var d = this.data;
	if (o) {
		var v;
		for (var k in o) {
			v = o[k];
			d[k] = v.split(',');
		}
	}
	this.dirty = false;
}
PServerSession.prototype.toURI = function(prefix) {
	var all = [];
	var d = this.data;
	var v;
	for (var k in d) {
		v = d[k];
		all.push(k + '=' + (v && v.join ? v.join(',') : v));
	}
	return (prefix ? prefix : '') + all.join('&');
}

PServerSession.prototype.setIndicators = function(inds) {
	this.setObjects(inds, "i");
}
PServerSession.prototype.getIndicator = function() {
	var d = this.data;
	return d.i && d.i[d.i.length-1] ? d.i[d.i.length-1] : null;
}
PServerSession.prototype.setPlaces = function(places) {
	this.setObjects(places, "p");
}
PServerSession.prototype.getPlace = function() {
	var d = this.data;
	return d.p && d.p[d.p.length-1] ? d.p[d.p.length-1] : null;
}
PServerSession.prototype.getPlaces = function() {
	return this.getAttribute("p");	
}
PServerSession.prototype.hasPlaces = function() {
	var d = this.data;
	return d.p != null && d.p.length > 0;
}
PServerSession.prototype.isArray = function(o) {
	return o && typeof o === 'object' && o.length != null;
}
PServerSession.prototype.clearIndicators = function() {
	this.data.i = null;
	this.dirty = true;
}
PServerSession.prototype.setOverlaySets = function(sets) {
	this.setObjects(sets, "o");
}
PServerSession.prototype.setObjects = function(objs, prop) {
	var d = this.data;
	if (this.isArray(objs) && objs.length > 0) {
		d[prop] = [];
		var l = objs.length;
		var o;
		if (objs[0].id != null) {
			for (var i=0; i<l; i++) {
				o = objs[i];
				d[prop].push(o.id);
				
				// places kluge
				if (prop == 'p' && o instanceof PPlace) {
					d['place'] = [];
					d['place'].push(o.getLabel());
				}
			}
		} else {
			for (var i=0; i<l; i++) {
				d[prop].push(objs[i]);
			}
		}
	} else {
		d[prop] = objs ? [objs.id] : objs;
		if (prop == 'p' && o instanceof PPlace && o.getLabel) {
			d['place'] = [];
			d['place'].push(o.getLabel());
		}
	}
	this.dirty = true;
}

PServerSession.prototype.getAttribute = function(k) { return this.data[k]; this.dirty = true}

PServerSession.prototype.setAttribute = function(k, v) { this.data[k] = v; }

PServerSession.prototype.isDirty = function() { return this.dirty };

PServerSession.prototype.save = function() { 
	PAsync2.call(this.url + '/' + new Date().getTime() + Math.random() + this.toURI('?'), function() {});
	this.dirty = false;
}; 
