var inplace_editor_edit_hint = 'Click to edit...';

function createInplaceEditor(field, update_path, 
          highlightcolor,
          highlightendcolor, 
          cols, 
          rows,
          okButton,
          cancelLink,
          submitOnBlur
          )
{
   fillIfEmpty($(field));

// === defaults:
  if (highlightcolor == "" || highlightcolor == undefined) {highlightcolor = "#FFFF99"}
  if (highlightendcolor == "" || highlightendcolor == undefined) {highlightendcolor = "#FFFFFF"}
  if (cols < 1 || cols == undefined) {cols = 10}
  if (rows < 1 || rows == undefined) {rows = 1}
  if (okButton == undefined) {okButton = false}
  if (cancelLink == undefined) {cancelLink = false}
  if (submitOnBlur == undefined) {submitOnBlur = true}
// =============
  
  new Ajax.InPlaceEditor(field, update_path, { 
     ajaxOptions: {
        method: 'post' // u can have 'put' if u like
     },
     highlightcolor: highlightcolor, 
     highlightendcolor: highlightendcolor,
//     okButton: false,
//     cancelLink: false,
//     submitOnBlur: true,     
     okButton: okButton,
     cancelLink: cancelLink,
     submitOnBlur: submitOnBlur,     
     cols: cols,
     rows: rows,
     callback: function(form) {
        input_field = form.elements[0];
        
        // This is to ensure we don't save the edit hint if
        // the user accidentally clicked an empty field
        if(input_field.value == inplace_editor_edit_hint)
          input_field.value = '';
        
        return Form.serialize(form);                   
      },
     onComplete: function(transport, element)
     { 
       fillIfEmpty(element);
       
       if(transport.statusText != "Internal Server Error")
           onEditorSuccess(); // cb
       
       new Effect.Highlight(element, {
           startcolor: this.options.highlightcolor,
           endcolor: this.options.highlightendcolor
       });
     },
     onFailure: function(element, transport) {
       onEditorFailure(transport.responseText); // cb
     }
   });
}

function fillIfEmpty(element)
{
  if(element.innerHTML == '')
    element.innerHTML = inplace_editor_edit_hint;  
}

function onEditorSuccess()
{
  $('error').innerHTML = '';
  $('notice').innerHTML = 'Model was successfully updated.';
}

function onEditorFailure(response)
{
  response = response.evalJSON();
  
  var lines = new Array();
 
  for(var i = 0; i < response.length; i++)
    lines.push(response[i][0] + ' ' + response[i][1]);
          
  $('notice').innerHTML = '';
  $('error').innerHTML = 'Error: ' + lines.join('. ')
}

