[ Index ]
 

Code source de PRADO 3.0.6

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/framework/Web/Javascripts/effects/ -> controls.js (source)

   1  // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
   2  //           (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
   3  //           (c) 2005 Jon Tirsen (http://www.tirsen.com)
   4  // Contributors:
   5  //  Richard Livsey
   6  //  Rahul Bhargava
   7  //  Rob Wills
   8  // 
   9  // See scriptaculous.js for full license.
  10  
  11  // Autocompleter.Base handles all the autocompletion functionality 
  12  // that's independent of the data source for autocompletion. This
  13  // includes drawing the autocompletion menu, observing keyboard
  14  // and mouse events, and similar.
  15  //
  16  // Specific autocompleters need to provide, at the very least, 
  17  // a getUpdatedChoices function that will be invoked every time
  18  // the text inside the monitored textbox changes. This method 
  19  // should get the text for which to provide autocompletion by
  20  // invoking this.getToken(), NOT by directly accessing
  21  // this.element.value. This is to allow incremental tokenized
  22  // autocompletion. Specific auto-completion logic (AJAX, etc)
  23  // belongs in getUpdatedChoices.
  24  //
  25  // Tokenized incremental autocompletion is enabled automatically
  26  // when an autocompleter is instantiated with the 'tokens' option
  27  // in the options parameter, e.g.:
  28  // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
  29  // will incrementally autocomplete with a comma as the token.
  30  // Additionally, ',' in the above example can be replaced with
  31  // a token array, e.g. { tokens: [',', '\n'] } which
  32  // enables autocompletion on multiple tokens. This is most 
  33  // useful when one of the tokens is \n (a newline), as it 
  34  // allows smart autocompletion after linebreaks.
  35  
  36  if(typeof Effect == 'undefined')
  37    throw("controls.js requires including script.aculo.us' effects.js library");
  38  
  39  var Autocompleter = {}
  40  Autocompleter.Base = function() {};
  41  Autocompleter.Base.prototype = {
  42    baseInitialize: function(element, update, options) {
  43      this.element     = $(element); 
  44      this.update      = $(update);  
  45      this.hasFocus    = false; 
  46      this.changed     = false; 
  47      this.active      = false; 
  48      this.index       = 0;     
  49      this.entryCount  = 0;
  50  
  51      if (this.setOptions)
  52        this.setOptions(options);
  53      else
  54        this.options = options || {};
  55  
  56      this.options.paramName    = this.options.paramName || this.element.name;
  57      this.options.tokens       = this.options.tokens || [];
  58      this.options.frequency    = this.options.frequency || 0.4;
  59      this.options.minChars     = this.options.minChars || 1;
  60      this.options.onShow       = this.options.onShow || 
  61      function(element, update){ 
  62        if(!update.style.position || update.style.position=='absolute') {
  63          update.style.position = 'absolute';
  64          Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
  65        }
  66        Effect.Appear(update,{duration:0.15});
  67      };
  68      this.options.onHide = this.options.onHide || 
  69      function(element, update){ new Effect.Fade(update,{duration:0.15}) };
  70  
  71      if (typeof(this.options.tokens) == 'string') 
  72        this.options.tokens = new Array(this.options.tokens);
  73  
  74      this.observer = null;
  75      
  76      this.element.setAttribute('autocomplete','off');
  77  
  78      Element.hide(this.update);
  79  
  80      Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
  81      Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
  82    },
  83  
  84    show: function() {
  85      if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
  86      if(!this.iefix && 
  87        (navigator.appVersion.indexOf('MSIE')>0) &&
  88        (navigator.userAgent.indexOf('Opera')<0) &&
  89        (Element.getStyle(this.update, 'position')=='absolute')) {
  90        new Insertion.After(this.update, 
  91         '<iframe id="' + this.update.id + '_iefix" '+
  92         'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
  93         'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
  94        this.iefix = $(this.update.id+'_iefix');
  95      }
  96      if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  97    },
  98    
  99    fixIEOverlapping: function() {
 100      Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
 101      this.iefix.style.zIndex = 1;
 102      this.update.style.zIndex = 2;
 103      Element.show(this.iefix);
 104    },
 105  
 106    hide: function() {
 107      this.stopIndicator();
 108      if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
 109      if(this.iefix) Element.hide(this.iefix);
 110    },
 111  
 112    startIndicator: function() {
 113      if(this.options.indicator) Element.show(this.options.indicator);
 114    },
 115  
 116    stopIndicator: function() {
 117      if(this.options.indicator) Element.hide(this.options.indicator);
 118    },
 119  
 120    onKeyPress: function(event) {
 121      if(this.active)
 122        switch(event.keyCode) {
 123         case Event.KEY_TAB:
 124         case Event.KEY_RETURN:
 125           this.selectEntry();
 126           Event.stop(event);
 127         case Event.KEY_ESC:
 128           this.hide();
 129           this.active = false;
 130           Event.stop(event);
 131           return;
 132         case Event.KEY_LEFT:
 133         case Event.KEY_RIGHT:
 134           return;
 135         case Event.KEY_UP:
 136           this.markPrevious();
 137           this.render();
 138           if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
 139           return;
 140         case Event.KEY_DOWN:
 141           this.markNext();
 142           this.render();
 143           if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
 144           return;
 145        }
 146       else 
 147         if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
 148           (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;
 149  
 150      this.changed = true;
 151      this.hasFocus = true;
 152  
 153      if(this.observer) clearTimeout(this.observer);
 154        this.observer = 
 155          setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
 156    },
 157  
 158    activate: function() {
 159      this.changed = false;
 160      this.hasFocus = true;
 161      this.getUpdatedChoices();
 162    },
 163  
 164    onHover: function(event) {
 165      var element = Event.findElement(event, 'LI');
 166      if(this.index != element.autocompleteIndex) 
 167      {
 168          this.index = element.autocompleteIndex;
 169          this.render();
 170      }
 171      Event.stop(event);
 172    },
 173    
 174    onClick: function(event) {
 175      var element = Event.findElement(event, 'LI');
 176      this.index = element.autocompleteIndex;
 177      this.selectEntry();
 178      this.hide();
 179    },
 180    
 181    onBlur: function(event) {
 182      // needed to make click events working
 183      setTimeout(this.hide.bind(this), 250);
 184      this.hasFocus = false;
 185      this.active = false;     
 186    }, 
 187    
 188    render: function() {
 189      if(this.entryCount > 0) {
 190        for (var i = 0; i < this.entryCount; i++)
 191          this.index==i ? 
 192            Element.addClassName(this.getEntry(i),"selected") : 
 193            Element.removeClassName(this.getEntry(i),"selected");
 194          
 195        if(this.hasFocus) { 
 196          this.show();
 197          this.active = true;
 198        }
 199      } else {
 200        this.active = false;
 201        this.hide();
 202      }
 203    },
 204    
 205    markPrevious: function() {
 206      if(this.index > 0) this.index--
 207        else this.index = this.entryCount-1;
 208      this.getEntry(this.index).scrollIntoView(true);
 209    },
 210    
 211    markNext: function() {
 212      if(this.index < this.entryCount-1) this.index++
 213        else this.index = 0;
 214      this.getEntry(this.index).scrollIntoView(false);
 215    },
 216    
 217    getEntry: function(index) {
 218      return this.update.firstChild.childNodes[index];
 219    },
 220    
 221    getCurrentEntry: function() {
 222      return this.getEntry(this.index);
 223    },
 224    
 225    selectEntry: function() {
 226      this.active = false;
 227      this.updateElement(this.getCurrentEntry());
 228    },
 229  
 230    updateElement: function(selectedElement) {
 231      if (this.options.updateElement) {
 232        this.options.updateElement(selectedElement);
 233        return;
 234      }
 235      var value = '';
 236      if (this.options.select) {
 237        var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
 238        if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
 239      } else
 240        value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
 241      
 242      var lastTokenPos = this.findLastToken();
 243      if (lastTokenPos != -1) {
 244        var newValue = this.element.value.substr(0, lastTokenPos + 1);
 245        var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
 246        if (whitespace)
 247          newValue += whitespace[0];
 248        this.element.value = newValue + value;
 249      } else {
 250        this.element.value = value;
 251      }
 252      this.element.focus();
 253      
 254      if (this.options.afterUpdateElement)
 255        this.options.afterUpdateElement(this.element, selectedElement);
 256    },
 257  
 258    updateChoices: function(choices) {
 259      if(!this.changed && this.hasFocus) {
 260        this.update.innerHTML = choices;
 261        Element.cleanWhitespace(this.update);
 262        Element.cleanWhitespace(this.update.firstChild);
 263  
 264        if(this.update.firstChild && this.update.firstChild.childNodes) {
 265          this.entryCount = 
 266            this.update.firstChild.childNodes.length;
 267          for (var i = 0; i < this.entryCount; i++) {
 268            var entry = this.getEntry(i);
 269            entry.autocompleteIndex = i;
 270            this.addObservers(entry);
 271          }
 272        } else { 
 273          this.entryCount = 0;
 274        }
 275  
 276        this.stopIndicator();
 277  
 278        this.index = 0;
 279        this.render();
 280      }
 281    },
 282  
 283    addObservers: function(element) {
 284      Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
 285      Event.observe(element, "click", this.onClick.bindAsEventListener(this));
 286    },
 287  
 288    onObserverEvent: function() {
 289      this.changed = false;   
 290      if(this.getToken().length>=this.options.minChars) {
 291        this.startIndicator();
 292        this.getUpdatedChoices();
 293      } else {
 294        this.active = false;
 295        this.hide();
 296      }
 297    },
 298  
 299    getToken: function() {
 300      var tokenPos = this.findLastToken();
 301      if (tokenPos != -1)
 302        var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
 303      else
 304        var ret = this.element.value;
 305  
 306      return /\n/.test(ret) ? '' : ret;
 307    },
 308  
 309    findLastToken: function() {
 310      var lastTokenPos = -1;
 311  
 312      for (var i=0; i<this.options.tokens.length; i++) {
 313        var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
 314        if (thisTokenPos > lastTokenPos)
 315          lastTokenPos = thisTokenPos;
 316      }
 317      return lastTokenPos;
 318    }
 319  }
 320  
 321  Ajax.Autocompleter = Class.create();
 322  Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
 323    initialize: function(element, update, url, options) {
 324      this.baseInitialize(element, update, options);
 325      this.options.asynchronous  = true;
 326      this.options.onComplete    = this.onComplete.bind(this);
 327      this.options.defaultParams = this.options.parameters || null;
 328      this.url                   = url;
 329    },
 330  
 331    getUpdatedChoices: function() {
 332      entry = encodeURIComponent(this.options.paramName) + '=' + 
 333        encodeURIComponent(this.getToken());
 334  
 335      this.options.parameters = this.options.callback ?
 336        this.options.callback(this.element, entry) : entry;
 337  
 338      if(this.options.defaultParams) 
 339        this.options.parameters += '&' + this.options.defaultParams;
 340  
 341      new Ajax.Request(this.url, this.options);
 342    },
 343  
 344    onComplete: function(request) {
 345      this.updateChoices(request.responseText);
 346    }
 347  
 348  });
 349  
 350  // The local array autocompleter. Used when you'd prefer to
 351  // inject an array of autocompletion options into the page, rather
 352  // than sending out Ajax queries, which can be quite slow sometimes.
 353  //
 354  // The constructor takes four parameters. The first two are, as usual,
 355  // the id of the monitored textbox, and id of the autocompletion menu.
 356  // The third is the array you want to autocomplete from, and the fourth
 357  // is the options block.
 358  //
 359  // Extra local autocompletion options:
 360  // - choices - How many autocompletion choices to offer
 361  //
 362  // - partialSearch - If false, the autocompleter will match entered
 363  //                    text only at the beginning of strings in the 
 364  //                    autocomplete array. Defaults to true, which will
 365  //                    match text at the beginning of any *word* in the
 366  //                    strings in the autocomplete array. If you want to
 367  //                    search anywhere in the string, additionally set
 368  //                    the option fullSearch to true (default: off).
 369  //
 370  // - fullSsearch - Search anywhere in autocomplete array strings.
 371  //
 372  // - partialChars - How many characters to enter before triggering
 373  //                   a partial match (unlike minChars, which defines
 374  //                   how many characters are required to do any match
 375  //                   at all). Defaults to 2.
 376  //
 377  // - ignoreCase - Whether to ignore case when autocompleting.
 378  //                 Defaults to true.
 379  //
 380  // It's possible to pass in a custom function as the 'selector' 
 381  // option, if you prefer to write your own autocompletion logic.
 382  // In that case, the other options above will not apply unless
 383  // you support them.
 384  
 385  Autocompleter.Local = Class.create();
 386  Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
 387    initialize: function(element, update, array, options) {
 388      this.baseInitialize(element, update, options);
 389      this.options.array = array;
 390    },
 391  
 392    getUpdatedChoices: function() {
 393      this.updateChoices(this.options.selector(this));
 394    },
 395  
 396    setOptions: function(options) {
 397      this.options = Object.extend({
 398        choices: 10,
 399        partialSearch: true,
 400        partialChars: 2,
 401        ignoreCase: true,
 402        fullSearch: false,
 403        selector: function(instance) {
 404          var ret       = []; // Beginning matches
 405          var partial   = []; // Inside matches
 406          var entry     = instance.getToken();
 407          var count     = 0;
 408  
 409          for (var i = 0; i < instance.options.array.length &&  
 410            ret.length < instance.options.choices ; i++) { 
 411  
 412            var elem = instance.options.array[i];
 413            var foundPos = instance.options.ignoreCase ? 
 414              elem.toLowerCase().indexOf(entry.toLowerCase()) : 
 415              elem.indexOf(entry);
 416  
 417            while (foundPos != -1) {
 418              if (foundPos == 0 && elem.length != entry.length) { 
 419                ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
 420                  elem.substr(entry.length) + "</li>");
 421                break;
 422              } else if (entry.length >= instance.options.partialChars && 
 423                instance.options.partialSearch && foundPos != -1) {
 424                if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
 425                  partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
 426                    elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
 427                    foundPos + entry.length) + "</li>");
 428                  break;
 429                }
 430              }
 431  
 432              foundPos = instance.options.ignoreCase ? 
 433                elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
 434                elem.indexOf(entry, foundPos + 1);
 435  
 436            }
 437          }
 438          if (partial.length)
 439            ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
 440          return "<ul>" + ret.join('') + "</ul>";
 441        }
 442      }, options || {});
 443    }
 444  });
 445  
 446  // AJAX in-place editor
 447  //
 448  // see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
 449  
 450  // Use this if you notice weird scrolling problems on some browsers,
 451  // the DOM might be a bit confused when this gets called so do this
 452  // waits 1 ms (with setTimeout) until it does the activation
 453  Field.scrollFreeActivate = function(field) {
 454    setTimeout(function() {
 455      Field.activate(field);
 456    }, 1);
 457  }
 458  
 459  Ajax.InPlaceEditor = Class.create();
 460  Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
 461  Ajax.InPlaceEditor.prototype = {
 462    initialize: function(element, url, options) {
 463      this.url = url;
 464      this.element = $(element);
 465  
 466      this.options = Object.extend({
 467        okButton: true,
 468        okText: "ok",
 469        cancelLink: true,
 470        cancelText: "cancel",
 471        savingText: "Saving...",
 472        clickToEditText: "Click to edit",
 473        okText: "ok",
 474        rows: 1,
 475        onComplete: function(transport, element) {
 476          new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
 477        },
 478        onFailure: function(transport) {
 479          alert("Error communicating with the server: " + transport.responseText.stripTags());
 480        },
 481        callback: function(form) {
 482          return Form.serialize(form);
 483        },
 484        handleLineBreaks: true,
 485        loadingText: 'Loading...',
 486        savingClassName: 'inplaceeditor-saving',
 487        loadingClassName: 'inplaceeditor-loading',
 488        formClassName: 'inplaceeditor-form',
 489        highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
 490        highlightendcolor: "#FFFFFF",
 491        externalControl: null,
 492        submitOnBlur: false,
 493        ajaxOptions: {},
 494        evalScripts: false
 495      }, options || {});
 496  
 497      if(!this.options.formId && this.element.id) {
 498        this.options.formId = this.element.id + "-inplaceeditor";
 499        if ($(this.options.formId)) {
 500          // there's already a form with that name, don't specify an id
 501          this.options.formId = null;
 502        }
 503      }
 504      
 505      if (this.options.externalControl) {
 506        this.options.externalControl = $(this.options.externalControl);
 507      }
 508      
 509      this.originalBackground = Element.getStyle(this.element, 'background-color');
 510      if (!this.originalBackground) {
 511        this.originalBackground = "transparent";
 512      }
 513      
 514      this.element.title = this.options.clickToEditText;
 515      
 516      this.onclickListener = this.enterEditMode.bindAsEventListener(this);
 517      this.mouseoverListener = this.enterHover.bindAsEventListener(this);
 518      this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
 519      Event.observe(this.element, 'click', this.onclickListener);
 520      Event.observe(this.element, 'mouseover', this.mouseoverListener);
 521      Event.observe(this.element, 'mouseout', this.mouseoutListener);
 522      if (this.options.externalControl) {
 523        Event.observe(this.options.externalControl, 'click', this.onclickListener);
 524        Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
 525        Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
 526      }
 527    },
 528    enterEditMode: function(evt) {
 529      if (this.saving) return;
 530      if (this.editing) return;
 531      this.editing = true;
 532      this.onEnterEditMode();
 533      if (this.options.externalControl) {
 534        Element.hide(this.options.externalControl);
 535      }
 536      Element.hide(this.element);
 537      this.createForm();
 538      this.element.parentNode.insertBefore(this.form, this.element);
 539      if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
 540      // stop the event to avoid a page refresh in Safari
 541      if (evt) {
 542        Event.stop(evt);
 543      }
 544      return false;
 545    },
 546    createForm: function() {
 547      this.form = document.createElement("form");
 548      this.form.id = this.options.formId;
 549      Element.addClassName(this.form, this.options.formClassName)
 550      this.form.onsubmit = this.onSubmit.bind(this);
 551  
 552      this.createEditField();
 553  
 554      if (this.options.textarea) {
 555        var br = document.createElement("br");
 556        this.form.appendChild(br);
 557      }
 558  
 559      if (this.options.okButton) {
 560        okButton = document.createElement("input");
 561        okButton.type = "submit";
 562        okButton.value = this.options.okText;
 563        okButton.className = 'editor_ok_button';
 564        this.form.appendChild(okButton);
 565      }
 566  
 567      if (this.options.cancelLink) {
 568        cancelLink = document.createElement("a");
 569        cancelLink.href = "#";
 570        cancelLink.appendChild(document.createTextNode(this.options.cancelText));
 571        cancelLink.onclick = this.onclickCancel.bind(this);
 572        cancelLink.className = 'editor_cancel';      
 573        this.form.appendChild(cancelLink);
 574      }
 575    },
 576    hasHTMLLineBreaks: function(string) {
 577      if (!this.options.handleLineBreaks) return false;
 578      return string.match(/<br/i) || string.match(/<p>/i);
 579    },
 580    convertHTMLLineBreaks: function(string) {
 581      return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
 582    },
 583    createEditField: function() {
 584      var text;
 585      if(this.options.loadTextURL) {
 586        text = this.options.loadingText;
 587      } else {
 588        text = this.getText();
 589      }
 590  
 591      var obj = this;
 592      
 593      if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
 594        this.options.textarea = false;
 595        var textField = document.createElement("input");
 596        textField.obj = this;
 597        textField.type = "text";
 598        textField.name = "value";
 599        textField.value = text;
 600        textField.style.backgroundColor = this.options.highlightcolor;
 601        textField.className = 'editor_field';
 602        var size = this.options.size || this.options.cols || 0;
 603        if (size != 0) textField.size = size;
 604        if (this.options.submitOnBlur)
 605          textField.onblur = this.onSubmit.bind(this);
 606        this.editField = textField;
 607      } else {
 608        this.options.textarea = true;
 609        var textArea = document.createElement("textarea");
 610        textArea.obj = this;
 611        textArea.name = "value";
 612        textArea.value = this.convertHTMLLineBreaks(text);
 613        textArea.rows = this.options.rows;
 614        textArea.cols = this.options.cols || 40;
 615        textArea.className = 'editor_field';      
 616        if (this.options.submitOnBlur)
 617          textArea.onblur = this.onSubmit.bind(this);
 618        this.editField = textArea;
 619      }
 620      
 621      if(this.options.loadTextURL) {
 622        this.loadExternalText();
 623      }
 624      this.form.appendChild(this.editField);
 625    },
 626    getText: function() {
 627      return this.element.innerHTML;
 628    },
 629    loadExternalText: function() {
 630      Element.addClassName(this.form, this.options.loadingClassName);
 631      this.editField.disabled = true;
 632      new Ajax.Request(
 633        this.options.loadTextURL,
 634        Object.extend({
 635          asynchronous: true,
 636          onComplete: this.onLoadedExternalText.bind(this)
 637        }, this.options.ajaxOptions)
 638      );
 639    },
 640    onLoadedExternalText: function(transport) {
 641      Element.removeClassName(this.form, this.options.loadingClassName);
 642      this.editField.disabled = false;
 643      this.editField.value = transport.responseText.stripTags();
 644      Field.scrollFreeActivate(this.editField);
 645    },
 646    onclickCancel: function() {
 647      this.onComplete();
 648      this.leaveEditMode();
 649      return false;
 650    },
 651    onFailure: function(transport) {
 652      this.options.onFailure(transport);
 653      if (this.oldInnerHTML) {
 654        this.element.innerHTML = this.oldInnerHTML;
 655        this.oldInnerHTML = null;
 656      }
 657      return false;
 658    },
 659    onSubmit: function() {
 660      // onLoading resets these so we need to save them away for the Ajax call
 661      var form = this.form;
 662      var value = this.editField.value;
 663      
 664      // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
 665      // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
 666      // to be displayed indefinitely
 667      this.onLoading();
 668      
 669      if (this.options.evalScripts) {
 670        new Ajax.Request(
 671          this.url, Object.extend({
 672            parameters: this.options.callback(form, value),
 673            onComplete: this.onComplete.bind(this),
 674            onFailure: this.onFailure.bind(this),
 675            asynchronous:true, 
 676            evalScripts:true
 677          }, this.options.ajaxOptions));
 678      } else  {
 679        new Ajax.Updater(
 680          { success: this.element,
 681            // don't update on failure (this could be an option)
 682            failure: null }, 
 683          this.url, Object.extend({
 684            parameters: this.options.callback(form, value),
 685            onComplete: this.onComplete.bind(this),
 686            onFailure: this.onFailure.bind(this)
 687          }, this.options.ajaxOptions));
 688      }
 689      // stop the event to avoid a page refresh in Safari
 690      if (arguments.length > 1) {
 691        Event.stop(arguments[0]);
 692      }
 693      return false;
 694    },
 695    onLoading: function() {
 696      this.saving = true;
 697      this.removeForm();
 698      this.leaveHover();
 699      this.showSaving();
 700    },
 701    showSaving: function() {
 702      this.oldInnerHTML = this.element.innerHTML;
 703      this.element.innerHTML = this.options.savingText;
 704      Element.addClassName(this.element, this.options.savingClassName);
 705      this.element.style.backgroundColor = this.originalBackground;
 706      Element.show(this.element);
 707    },
 708    removeForm: function() {
 709      if(this.form) {
 710        if (this.form.parentNode) Element.remove(this.form);
 711        this.form = null;
 712      }
 713    },
 714    enterHover: function() {
 715      if (this.saving) return;
 716      this.element.style.backgroundColor = this.options.highlightcolor;
 717      if (this.effect) {
 718        this.effect.cancel();
 719      }
 720      Element.addClassName(this.element, this.options.hoverClassName)
 721    },
 722    leaveHover: function() {
 723      if (this.options.backgroundColor) {
 724        this.element.style.backgroundColor = this.oldBackground;
 725      }
 726      Element.removeClassName(this.element, this.options.hoverClassName)
 727      if (this.saving) return;
 728      this.effect = new Effect.Highlight(this.element, {
 729        startcolor: this.options.highlightcolor,
 730        endcolor: this.options.highlightendcolor,
 731        restorecolor: this.originalBackground
 732      });
 733    },
 734    leaveEditMode: function() {
 735      Element.removeClassName(this.element, this.options.savingClassName);
 736      this.removeForm();
 737      this.leaveHover();
 738      this.element.style.backgroundColor = this.originalBackground;
 739      Element.show(this.element);
 740      if (this.options.externalControl) {
 741        Element.show(this.options.externalControl);
 742      }
 743      this.editing = false;
 744      this.saving = false;
 745      this.oldInnerHTML = null;
 746      this.onLeaveEditMode();
 747    },
 748    onComplete: function(transport) {
 749      this.leaveEditMode();
 750      this.options.onComplete.bind(this)(transport, this.element);
 751    },
 752    onEnterEditMode: function() {},
 753    onLeaveEditMode: function() {},
 754    dispose: function() {
 755      if (this.oldInnerHTML) {
 756        this.element.innerHTML = this.oldInnerHTML;
 757      }
 758      this.leaveEditMode();
 759      Event.stopObserving(this.element, 'click', this.onclickListener);
 760      Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
 761      Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
 762      if (this.options.externalControl) {
 763        Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
 764        Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
 765        Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
 766      }
 767    }
 768  };
 769  
 770  Ajax.InPlaceCollectionEditor = Class.create();
 771  Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
 772  Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
 773    createEditField: function() {
 774      if (!this.cached_selectTag) {
 775        var selectTag = document.createElement("select");
 776        var collection = this.options.collection || [];
 777        var optionTag;
 778        collection.each(function(e,i) {
 779          optionTag = document.createElement("option");
 780          optionTag.value = (e instanceof Array) ? e[0] : e;
 781          if(this.options.value==optionTag.value) optionTag.selected = true;
 782          optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
 783          selectTag.appendChild(optionTag);
 784        }.bind(this));
 785        this.cached_selectTag = selectTag;
 786      }
 787  
 788      this.editField = this.cached_selectTag;
 789      if(this.options.loadTextURL) this.loadExternalText();
 790      this.form.appendChild(this.editField);
 791      this.options.callback = function(form, value) {
 792        return "value=" + encodeURIComponent(value);
 793      }
 794    }
 795  });
 796  
 797  // Delayed observer, like Form.Element.Observer, 
 798  // but waits for delay after last key input
 799  // Ideal for live-search fields
 800  
 801  Form.Element.DelayedObserver = Class.create();
 802  Form.Element.DelayedObserver.prototype = {
 803    initialize: function(element, delay, callback) {
 804      this.delay     = delay || 0.5;
 805      this.element   = $(element);
 806      this.callback  = callback;
 807      this.timer     = null;
 808      this.lastValue = $F(this.element); 
 809      Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
 810    },
 811    delayedListener: function(event) {
 812      if(this.lastValue == $F(this.element)) return;
 813      if(this.timer) clearTimeout(this.timer);
 814      this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
 815      this.lastValue = $F(this.element);
 816    },
 817    onTimerEvent: function() {
 818      this.timer = null;
 819      this.callback(this.element, $F(this.element));
 820    }
 821  };


Généré le : Sun Feb 25 21:07:04 2007 par Balluche grâce à PHPXref 0.7