// TODO replicate custom attributes functionality from php version

function ListBuilder(liT,pfx){
	this.menuPfx = pfx + 'menu';
	this.itemPfx = pfx + 'item';
	this.liT = liT;
	
	
	this.type = 'list';
	this.mC = '';
};

ListBuilder.prototype.init = function(c){
	this.container = c;
};

ListBuilder.prototype.setTemplate = function(t){
	this.liT = t;
};


ListBuilder.prototype.clear = function(pId){
	//this.container.getElementsByTagName('ul')[0].innerHTML = '';
	this.container.innerHTML = '';
};

ListBuilder.prototype.createUl = function(pId){
	if (!pId) pId = 0;
	p = pId > 0 ? this.findItem(pId) : this.container;
	var ul = p.appendChild(document.createElement('ul'));
	if (pId == 0 && this.mC) ul.className = this.mC;
	ul.id = this.menuPfx + pId;
	return ul;
};

// if data is a string, assume it is html and a static li (like the php one's createStaticLi method)
ListBuilder.prototype.createLi = function(pId, id, data, c, atts){
	var p = this.findMenu(pId);
	if (!p) p = this.createUl(pId);
	var li = p.appendChild(document.createElement('li'));
	li.id = this.itemPfx + id;
	if (c) li.className = c;
	if (atts && typeof atts === 'object'){
		for (i in atts) li.setAttribute(i, atts[i]);
	}
	li.innerHTML = (typeof data === 'string') ? data : this.parseText(this.liT,id,data);
	return li;
};


// tags for building regex- NOTE: regexp special chars must be *double escaped*
ListBuilder.prototype.tags = {
	sTag : "\\{\\{",
	eTag : "\\}\\}",
	sCond : "\\(\\(\\(",
	eCond : "\\)\\)\\)",
	alt : "\\(\\?\\)",
	sep : "\\(\\:\\)"
}


ListBuilder.prototype.parseText = function(t,id,data){
	// parse for conditionals
	var regExp = new RegExp(this.tags.sCond + "([^(?:" + this.tags.alt + ")]*)" + this.tags.alt + "(.*?)" + this.tags.sep + "(.*?)" + this.tags.eCond, "g");
	t = String(t).replace(regExp,function(s,c,t,f){with(data) return eval(c) ? t : f;});
	
	// parse for id
	t = t.replace(new RegExp(this.tags.sTag + 'id' + this.tags.eTag, "g"),id);

	// parse for variables
	for (i in data){
		regExp = new RegExp(this.tags.sTag + i + this.tags.eTag, "g");
		t = t.replace(regExp,data[i]);
	}
	return t;	
};

ListBuilder.prototype.deleteUl = function(id){
	// TODO
};
ListBuilder.prototype.deleteLi = function(id){
	// TODO
};

ListBuilder.prototype.findItem = function(id){
	return document.getElementById(this.itemPfx + id);
};
ListBuilder.prototype.findMenu = function(id){
	return document.getElementById(this.menuPfx + id);
};
