//adds some handy features when saving the form
//validate if there's a JS side validate method
//show 'loader' image while saving
//disable button while saving
//fire off TinyMCE save methods
//then continue on to submitting the form
function panelSave(form) {

  try {
    if (!validate(form)){
      return false;
    }
  } catch (e) {
    //alert(e.name + ": " + e.message);
    //do nothing in case 'validate' isn't defined as a JS function
  }

  form_name = form.id; //either new_something_or_other - or edit_something_or_other_109
  if (form_name.indexOf('new') == 0) {
    //it's a new_something_or other
    model = form_name.substr( form_name.indexOf('_',0)+1 , form_name.length-1);
  } else {
    //it's edit_something_or_other_109
    model = form_name.substr( form_name.indexOf('_',0)+1 , form_name.length-1);
    model = model.substr( 0, model.lastIndexOf('_'));
  }
  button_id = model + "_submit";

  //disable and rename the submit button - whatever it's called.
  //should be using form.select('[type="submit"]') but that has bugs in IE6/7
  sub_button = form.select('.disableable')[0]
  if (sub_button) {
    sub_button.disable();
    sub_button.value = sub_button.readAttribute('off_value');
    sub_button.id = button_id
  } else {
    alert("Please add class=disableable to the submit button here");
  }

  //show loader image
  $('loader').show();

  //process the form and then save
  tinyMCE.triggerSave(false, false);

  return true;
}


//once the panel is loaded - observe the close button for a click.
document.observe('lightview:loaded', function(event) {
  document.getElementsByClassName("lv_Button lv_Close")[0].observe('click', function(event){
    //before closing the panel, unload all tinyMCE controls
    try {
      for(id in tinyMCE.editors){
        //alert("calling removal for "+id+".");
        tinyMCE.execCommand('mceRemoveControl', false, id);
      }
    } catch (err) {}
  });
});
