//
// requires MochiKit to work 
//

//
// generates the custom ids for the various DOM elements
//
function get_param(id){
	var p = new Object()
	p.areaid  = 'TEXT-AREA-'   + id
	p.saveid  = 'SAVE-BUTTON-' + id
	p.tagid   = 'MAIN-TAG-'    + id
	p.textid  = 'MAIN-TEXT-'   + id
	p.tdid    = 'MAIN-TD-'     + id
	p.wid     = 'WIDGET-'      + id
	return p
}

//
// cancels editing
//
function cancel(id){
	var p = get_param(id)
	showElement( p.tagid )
	removeElement (p.wid )
}

//
// creates a textarea widget
//
function make_editbox(id, rows, text){
	var p = get_param(id)

	var area = TEXTAREA( { 'id':p.areaid, 'rows':rows, 'cols':'50' }, text )
	var save = INPUT( { 'id':p.saveid, 'type':'button', value:'Save' } )
	var br   = BR( null )
	var link = A( { 'href':'javascript:cancel(\'' + id + '\')' }, 'Cancel' )
	var widget = DIV( { 'id':p.wid }, area, br, save, ' or ', link)
	return widget
}

//
// main editing function
//
function edit(id, rows){
	
	var p = get_param(id)

	// hide the main tag 
	hideElement( p.tagid )

	// create edit box and display a temporary loading message inside it
	var editbox = make_editbox(id, rows, 'Loading...')
	appendChildNodes( p.tdid, editbox)

	// add onclick event to the save button
	connect( p.saveid, 'onclick', function() { save(id) } )

	// create ajax connection
	var ajax = doSimpleXMLHttpRequest( '/get_text/', { 'oid': id  } )

	// add functions for sucess and error
	ajax.addCallbacks(
		function(t){ var obj = $( p.areaid ); obj.value = t.responseText }, 
		function(t){ var obj = $( p.areaid ); obj.value = 'Sorry, get operation failed'  }
	)

}

//
// submits the content of the textarea to the server
//
function save(id){
	var p = get_param(id)
	
	// save the text from the textarea
	var value = $( p.areaid ).value
	
	//remove edit widget
	removeElement ( p.wid )

	// show main tag
	showElement( p.tagid )

	// display temporary text with different styling
	var text = $( p.textid )
	addElementClass(text, 'saving')
	text.innerHTML = 'Saving entry number ' + id
	
	var ajax = doSimpleXMLHttpRequest( '/save_text/', { 'oid': id, 'text':value  } )
	
	ajax.addCallbacks(
		function(t){ text.innerHTML = t.responseText; removeElementClass(text, 'saving') }, 
		function(t){ text.innerHTML = 'Sorry, the update failed...';   }
	)
	
}

