//
// requires prototype.js to work 
//

//
// generates ids for various components on the page
//
function get_param(id){
	var param = new Object()
	param.editid  = 'EDIT-FORM-'   + id
	param.areaid  = 'TEXT-AREA-'   + id
	param.saveid  = 'SAVE-BUTTON-' + id
	param.tagid   = 'MAIN-TAG-'    + id
	param.textid  = 'MAIN-TEXT-'   + id
	return param
}

//
// cancels  editor
//
function cancel(id){
	var p = get_param(id)

	Element.remove( p.editid )
	Element.show( p.tagid )
}

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

	var box    = '<textarea id="' + p.areaid + '" name="' + p.areaid + '" rows="' + rownum + '" cols="50">' +  text + '</textarea>'
	var save   = '<input id="' + p.saveid + '" type="button" value=" Save " />'
	var cancel = '<a href="javascript:cancel(\'' + id + '\')">Cancel</a>'
	var widget = '<div id="' + p.editid + '">' + box + '<br>' + save + ' or ' + cancel + '</div>';
	
	return widget
}


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

	// hide the main tag 
	Element.hide( p.tagid );

	// create edit box and display a temporary loading message inside it
	var widget = make_editbox(id, rownum, 'Loading...')
	new Insertion.After(p.tagid , widget)

	//
	// make an ajax connection to fetch the content 
	//
	var url     = '/get_text/' 
	var params  = 'oid=' + id 
	var area    = $( p.areaid )
	var success = function(t){ area.value = t.responseText  }
	var failure = function(t){ area.value = 'Sorry, get operation failed'  }
	var ajax    = new Ajax.Request(url, {method:'post', postBody:params, onSuccess:success, onFailure:failure})

	//
	// assign save event to the submit button
	//
	Event.observe( p.saveid, 'click',   function(){ save(id) }, false)
}

// saving the contents of the tag editor
function save(id){

	var p = get_param(id)

	// fetch the content of the text area
	var text = escape( $F(p.areaid) )

	// remove the edit widget
	Element.remove( p.editid )
	
	// display the main tag with a temporary message
	var msg = $(p.textid)
	Element.addClassName(msg, 'saving') // lets also temporarily change the CSS class during the save
	msg.innerHTML = 'Saving entry number ' + id
	
	// show the main tag
	Element.show( p.tagid );

	// make the ajax connection
	var success = function(t){ msg.innerHTML = t.responseText; Element.removeClassName(msg, 'saving'); }
	var failure = function(t){ msg.innerHTML = 'Sorry, the update failed...'; }
	
	var url  = '/save_text/';
	var params = 'oid=' + id + '&text=' + text
	var myAjax = new Ajax.Request(url, {method:'post', postBody:params, onSuccess:success, onFailure:failure});
	
}

