function contactTable() {
	this.lastRow = null;
}

contactTable.prototype = {
    'initialize' : function(tbody) {
	    this.addContact = bind(this.addContact, this);
		this.onchange = bind(this.onchange, this);
	    this.tbody = tbody;
		
		var lastRow = getElementsByTagAndClassName('tr', null, this.tbody);
		if(lastRow.length) {
		    lastRow = lastRow[lastRow.length-1];
			if(lastRow.className.search('existing') == -1) {
			    this.lastRow = this.hookRow(lastRow);				
			}
		}
		if(this.lastRow == null)
		    this.addContact();
    },
	
	'addContact' : function() {
	    this.lastRow = this.hookRow(TR(null, 
	             TD({'class':'key'}),//, INPUT({'name':'key', 'class':'radio', 'type':'radio'})),
				 TD(null, INPUT({'name':'contacts.sName:records'})),
				 TD(null, INPUT({'name':'contacts.sPosition:records'})),
				 TD(null, INPUT({'size':'12','name':'contacts.sTelephone:records'})),
				 TD(null, INPUT({'name':'contacts.sEmail:records'})),
				 TD(null, INPUT({'size':'12','name':'contacts.sFax:records'})),
				 TD(null)
//				 TD({'class':'delete'}, INPUT({'class':'radio', 'type':'checkbox', 'value': 'True', 'name':'contacts.delete:records'}))
				));
		this.tbody.appendChild(this.lastRow);
	},
	
	'checkRow' : function(row) {
	    var complete = true,
		    empty = true,
		    data = getElementsByTagAndClassName('td', null, row);
		
	    for(var i=1;i<=4;i++) {
		    var input = data[i].getElementsByTagName('input')[0],
                val = input.value;	
				
		    if(!val) { 
			    complete = false; 
		    } else {
			    empty = false;
			}
			
			if(i==4 && !empty) {
			    var at = val.search('@');
				if(at == -1) { 
				    complete = false;
					break;
				}
				val = val.substr(at+1);
				if(val.search('.') == -1) 
				    complete = false;
				
			}
		}
		if(complete) return 1;
		if(empty) return -1;
		return 0;
		
	},
	'hookRow' : function(row) {
	    var data = getElementsByTagAndClassName('td', null, row);
		
	    for(var i=1;i<=4;i++) {
		    var input = data[i].getElementsByTagName('input')[0];
			input.onchange = this.onchange;
		}
		return row;
		
	},
	
	'onchange' : function() {	    
		if(this.checkRow(this.lastRow) == 1) this.addContact();
    }
	    
}


function hookContacts() {
    var table = getElementsByTagAndClassName('*', 'contact-form');
	if(table.length) {
	    var i = new contactTable;
		i.initialize(table[0]);
    }
	return true;
}

addLoadEvent(hookContacts);
	
		
		
