window.onload = function() {

	rows = document.getElementsByTagName('td');
	
	for(i = 0; i < rows.length; i++) {
	
		if(rows[i].className.substr(-9) == 'clickable') {
			
			rows[i].style.cursor = 'pointer';
			rows[i].onclick = function() {
				rid = this.parentNode.className.replace(' altrow', '');
				
				location.href = location.href+'/edit/'+rid
			}
			
		}
	
	}
	
	inlineEdit();

}

StandBy = true;

function inlineEdit() {

	//window.onerror = function() {return true}; //For ie

	var cells = $$('td.editable');

	for(i = 0; i < cells.length; i++) {
			
		cells[i].onclick = function() { return false; };
		
		Element.extend(cells[i])
		
		if(cells[i].down().tagName == 'SPAN') {

			cells[i].down().onclick = function() {

				if(StandBy) {
					
					StandBy = false;
								
					form = document.createElement('form');
					form.method = 'post';
					
					var originalValue = this.firstChild.nodeValue;
					
					inp = document.createElement('input');
					inp.type = 'text';
					inp.style.width = '95%';
					inp.style.position = 'relative';
					inp.value = trim(originalValue);
					
					indent = originalValue.replace(inp.value, '');
					form.action = indent;

					form.appendChild(inp);
					this.parentNode.appendChild(form);
					this.parentNode.removeChild(this);
					
					form.onsubmit = function() {
						
						this.id = 'inlineEditForm';
						this.style.display = 'none';
						
						info = this.parentNode.className.substr(this.parentNode.className.indexOf('tdData')+7).split('-')
						child = this.down();
						
						var item = 'value='+child.value+'&model='+info[0]+'&id='+info[1]+'&field='+info[2];
						
						if(IE)
							item += '&IE=1';
						else
							item += '&IE=0';
						
						new Ajax.Request(HOST+'admin/'+MODEL+'/ajaxEdit',
						{
							method:'post',
							parameters: item,
							onSuccess: function(transport){

								val = document.getElementById('inlineEditForm').action+transport.responseText;
								StandBy = true;		
								
								span = document.createElement('span');
								span.appendChild(document.createTextNode(val));
								document.getElementById('inlineEditForm').parentNode.appendChild(span);
								
								document.getElementById('inlineEditForm').parentNode.removeChild(document.getElementById('inlineEditForm'));
								inlineEdit();
								
								return false;
								
							},
							onFailure: function(){ alert('Error al actualizar.') }
							
						});

						
						return false;
					}
					
				}
			
			}
			
		}
	
	}
	
}

function trim (str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

