// InLineEdit

ILE = { 
  // create one or more Tag#Id.Class with content
  // call ILE.create(Tag || "#Id" || ".Class" || any other CSS Selector,options)
options: {
     submitname: 'submit', // name of the submit-button 
     onsubmit: undefined, // function: with which as parameter; string: evaluated
     cancelname: 'cancel', // name of the cancelbutton
     editname: 'edit',  // name of the edit-button
     parameters: {},    // additional parameters
     method: 'put',    // submit-method
     url: undefined,           // url for Ajax-Request
     fieldname: false,  // fieldname of the inlineedit-field
     rows: 3            // rows of the textarea
         },
create: function(which,args) {
          try {
            if(typeof(which) == "string") {
              var m = which.match(/^[^. #]*#([^. ]+)(.*)/);
              
              if(m) {
                  which = m[2] == "" ? [$(m[1])] : $(m[1]).select(m[2]);
              } else {
                  which = $$(which);
              }
            } else if(which.nodeType) {
              which = [$(which)];
            } else if(!which.pop) {
              return;
            }  
          } catch(e) {
            if(console) console.log(which,e);
            return;
          }
          for(var i=0;i<which.length;i++) this.init(which[i],args);
      },
init: function(el,args) {
        el = $(el);
        if(! el.hasClassName("ILE") || el.down(".ILE_field")) return;
        el.ILE = Object.extend(Object.clone(ILE.options),args || {});
        el.ILE.parameters= $H(el.ILE.parameters || {});
        el.ILE.fieldname || (el.ILE.fieldname = $w(el.className)[0]);

        el.ILE.text = el.innerHTML;

        el.ILE.text = el.ILE.text.gsub(/\n/,'').gsub(/<br\s*\/?>/,"\n");
        el.ILE.text = el.ILE.text.gsub(/<h1[^>]*>(.*?)<\/h1>/, function(m) {
          return "#"+m[1]+"#";
        });
				
				el.ILE.text = el.ILE.text.gsub(/<b[^>]*>(.*?)<\/b>/, function(m) {
          return "*"+m[1]+"*";
        });
        el.ILE.text = el.ILE.text.gsub(/<a[^>]+href=(["'])(.*?)\1[^>]*>(.*?)<\/a>/, function(m) {
          return '"'+m[3]+'":'+m[2];
        });

        el.update(
"<span class='ILE_off ILE_field'>"+el.innerHTML+"</span> "+
"<input class='ILE_off ILE_editButton formButtonSmall' type='button' value='"+el.ILE.editname+"' onclick='ILE.edit(\""+el.identify()+"\");'/>"
        );    
      },
edit: function(which) {
        which = $(which);
        if(!which.down('.ILE_field') || which.down('.ILE_form')) return;
        this.show();
        which.select('.ILE_off').each(function(el){el.hide()});
        which.insert({top: "<form class='ILE_form ILE_on' action='#' onsubmit='return false;'>"+
"<textarea class='formText' name='"+which.ILE.fieldname+"' rows='"+which.ILE.rows+"'>"+which.ILE.text+"</textarea>"+
"<span><input type='button' class='formButton' value='"+which.ILE.cancelname+"' onclick='ILE.cancel(\""+which.id+"\");return false;'/>"+
"<input type='button' class='formButton' value='"+which.ILE.submitname+"' onclick='ILE.submit(\""+which.id+"\");return false;'/></span>"+
"</form>" 
        });
        textarea = which.down('textarea');
				textarea.style.height = textarea.scrollHeight+"px";
				textarea.onkeydown = function(){this.style.height=this.scrollHeight+'px'} 
        textarea.focus();
      },
submit: function(which) {
        which = $(which);
        field = which.down('.ILE_field');
        textarea = which.down('textarea');
        textarea.value = textarea.value.escapeHTML();
        if(!field || !textarea) return;
        if(which.ILE.text != textarea.value) {
          if(which.ILE.onsubmit) {
            if(typeof(which.ILE.onsubmit) == "string") rv = eval(which.ILE.onsubmit);
            else if(typeof(which.ILE.onsubmit) == "function") rv = which.ILE.onsubmit(which,textarea);
            if(rv == false) {
              textarea.focus();
              textarea.addClassName("fieldWithErrors");
              return;
            }  
            textarea.removeClassName("fieldWithErrors");
          }
          which.ILE.text = textarea.value;
          var text,truncate_string,send_text;
          if(which.ILE.truncation_length) {
            text = which.ILE.text.substring(0,which.ILE.truncation_length); 
            truncate_string = which.ILE.text.length > which.ILE.truncation_length ? which.ILE.truncate_string : '';
            send_text = which.ILE.text
          } else {
            text = which.ILE.text;
            text = text.gsub(/"(.+?)":([^\s#<]+)/,function(m){
                return "<a href='"+m[2]+"'>"+m[1]+"</a>";
            });
            text = text.gsub(/\n/m,"<br/>");
            text = text.gsub(/\#(.+?)\#/,function(m){
                return "<h1>"+m[1]+"</h1>";
            });
            text = text.gsub(/\*(.+?)\*/,function(m){
                return "<b>"+m[1]+"</b>";
            });
            send_text = text;
            truncate_string = '';
          }

          field.update(text+truncate_string);
          var params = {html_id: which.identify()}
          params[which.ILE.fieldname] = send_text;

          if(which.ILE.url) new Ajax.Request( which.ILE.url, {
            asynchronous:true, evalScripts:true, method: 'put', 
            parameters: params
          });
        } 
        this.cancel(which);
      },
cancel: function(which) {
        which = $(which);
        if(!which.down('.ILE_on')) return;
        which.select('.ILE_off').each(function(el){el.show()});
        which.down('.ILE_on').remove();
      },
hide: function() {
        // hides all ILE-Controls
        $$('.ILE_on').each(function(el){el.remove()});
        $$('.ILE_editButton').each(function(el){el.hide()});
      },
show: function() {
        // shows all ILE-Controls
        $$('.ILE_on').each(function(el){el.remove()});
        $$('.ILE_off').each(function(el){el.show()});
      },
toggle: function() {
        // toggles all ILE-Controls
        eb = Element.down(document.body,'.ILE_editButton');
        if(! eb) return;
        if(eb.getStyle('display') == 'none') ILE.show();
        else ILE.hide();
      }
}


