/*
* Used by My Meedan page to edit profile fields in-place.
*/

/**
* Sets up a field as editable
*/
function makeEditable(id, textInput){
	Event.observe(id+"_button", 'click', function(){edit($(id),textInput)}, false);
}

/**
* When Update button is pressed, field becomes editable: the field is shown in an input box, prepopulated with the field's
* current value, with a Save and Cancel button.
*/
function edit(obj, textInput){
	Element.hide(obj);
	
	//Hide update button
	var editButton = document.getElementById(obj.id+"_button");
	Element.hide(editButton);
	
	var input;
	if (textInput){
		//Text input field
		input = '<div id="'+obj.id+'_editor"><input type="text" id="'+obj.id+'_edit" name="'+obj.id+'" value="'+obj.innerHTML+'" autocomplete="off" size="'+default_input_size+'"/>';	
	} else {
		//Textarea input field
		input = '<div id="'+obj.id+'_editor"><textarea id="'+obj.id+'_edit" name="'+obj.id+'" rows="4" cols="'+default_input_size+'" class="input textarea">'+obj.innerHTML+'</textarea>';
	}
	
	//Save and Cancel buttons
	var button	 = '<div><input id="'+obj.id+'_save" type="button" value="'+button_save+'" class="button" /> '+text_or+' <input id="'+obj.id+'_cancel" type="button" value="'+button_cancel+'" class="button"/></div></div>';
	new Insertion.After(obj, input+button);	
	Event.observe(obj.id+'_save', 'click', function(){saveChanges(obj)}, false);
	Event.observe(obj.id+'_cancel', 'click', function(){cleanUp(obj)}, false);
}

/**
* Submitting a profile field update. 
*/
function saveChanges(obj){
	var new_content	=  $F(obj.id+'_edit');
	
	obj.innerHTML	= "Saving...";
	cleanUp(obj, true);

	var success	= function(t){editComplete(t, obj);}
	var failure	= function(t){editFailed(t, obj);}
  	var url = 'service.php';
	var pars = 'type=profile&action=edit_profile_field&id='+obj.id+'&content='+new_content;
	var myAjax = new Ajax.Request(url, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

/**
* Resetting the field by taking it back to its non-editable format. 
*/
function cleanUp(obj, keepEditable){
	Element.remove(obj.id+'_editor');
	Element.show(obj);
	
	//Show update button
	var editButton = document.getElementById(obj.id+"_button");
	Element.show(editButton);
}

/**
* After updating a field, reload the profile info section. 
*/
function editComplete(t, obj){
	document.getElementById("profile_summary").innerHTML = t.responseText;
	makeProfileEditable();
}

/**
* Error handling if updating a field fails. 
*/
function editFailed(t, obj){
	obj.innerHTML	= 'Sorry, the update failed.';
	cleanUp(obj);
}
