extensibleForms = new Array;

function extensibleFormAddCol(text, width, title) {
	this.cols.push(new Array(text, width, title));
}

function extensibleFormAddReplacement(search, replace) {
	this.replacements.push(new Array(search, replace));
}

function extensibleFormDisplay(init) {
	document.write('<table border="0" cellspacing="0" cellpadding="0" id="extensibleform_'+this.id+'">');
	writetitles = false;
	for(x in this.cols) {
		if(this.cols[x][2] != '') {
			writetitles = true;
		}
		if(this.cols[x][1] != '') {
			document.write('<col width="'+this.cols[x][1]+'">');
		} else {
			document.write('<col>');
		}
	}
	if(writetitles) {
		document.write('<tr>');
		for(x in this.cols) {
			document.write('<th>'+this.cols[x][2]+'</th>');
		}
		document.write('</tr>');
		this.baserow = 1;
	}
	
	document.write('<tr>');
	document.write('<td colspan="'+this.cols.length+'" align="center"><button id="extensibleform_'+this.id+'_addbutton" type="button" onClick="extensibleFormAddRow('+this.id+');">&nbsp;&nbsp;+&nbsp;&nbsp;</button>&nbsp;<button id="extensibleform_'+this.id+'_delbutton" type="button" onClick="extensibleFormDelRow('+this.id+');">&nbsp;&nbsp;-&nbsp;&nbsp;</button></td>');
	document.write('</tr>');
	document.write('</table>');
	document.close();
	
	this.table = document.getElementById('extensibleform_'+this.id);
	this.addbutton = document.getElementById('extensibleform_'+this.id+'_addbutton');
	this.delbutton = document.getElementById('extensibleform_'+this.id+'_delbutton');
	
	this.delbutton.disabled = true;
	
	if(init > 0) {
		for(i = 0; i < init; i++) {
			extensibleFormAddRow(this.id);
		}
	}
}

function extensibleFormAddRow(formid) {
	form = extensibleForms[formid];
	if(form) {
		table = form.table;
		row = table.insertRow(form.numrows + form.baserow);
		
		for(x in form.cols) {
			regEx = new RegExp('ROW_ID', 'g');
			text = form.cols[x][0].replace(regEx, form.numrows);
			for(y in form.replacements) {
				regEx = new RegExp(form.replacements[y][0], 'g');
				text = text.replace(regEx, form.replacements[y][1][form.numrows] ? form.replacements[y][1][form.numrows] : '');
			}
			cell = row.insertCell(x);
			cell.innerHTML = text;
		}
		
		form.numrows++;
		
		if(form.numrows == 2) form.delbutton.disabled = false;
	}
}

function extensibleFormDelRow(formid) {
	form = extensibleForms[formid];
	if(form) {
		table = form.table;
		form.numrows--;
		row = table.deleteRow(form.numrows + form.baserow);
		if(form.numrows == 1) form.delbutton.disabled = true;
	}
}

function extensibleForm() {
	this.cols = new Array();
	this.replacements = new Array();
	
	this.numrows = 0;
	this.baserow = 0;
	
	extensibleForms.push(this);
	this.id = extensibleForms.length-1;
	
	this.addCol = extensibleFormAddCol;
	this.display = extensibleFormDisplay;
	this.addReplacement = extensibleFormAddReplacement;
}