var moodal = new Class({

  Implements: [Options],

  options: {
    // Classe css per identificare tutti i trigger. Cliccando sul trigger si deve aprire il divup
    trigger: null,
    // L'elemento che rappresenta il contenuto di base dei vari divup aperti
    divup: null,
    // Funzione di callback chiamata quando si apre un divup, utile per popolare il divup con i valori di un record estratto dal db
    // la callback si deve aspettare come argomento l'elemento trigger che è stato cliccato per aprire il divup
    callbackOnTrigger: null,
    callbackOnComplete: null
  },

  inFx: null,
  outFx: null,
  inner: null,
  msgDisappearsInSec: 1500,
  container:'\
<div class="generic_dialog_popup" style="top: 239px;"> \
<table class="pop_dialog_table" id="pop_dialog_table" style="width: 532px;"> \
  <tbody> \
    <tr><td class="pop_topleft"/><td class="pop_border"/><td class="pop_topright"/></tr> \
    <tr> \
      <td class="pop_border"/> \
      <td id="pop_content" class="pop_content"> \
        <h2 class="dialog_title"><span></span></h2> \
        <div class="dialog_content"> \
        </div> \
      </td> \
      <td class="pop_border"/> \
    </tr> \
    <tr><td class="pop_bottomleft"/><td class="pop_border"/><td class="pop_bottomright"/></tr> \
  </tbody> \
</table> \
</div> \
  ',


  initialize: function(options) {

    this.setOptions(options);

    // Cambio l'onclick di tutti i trigger in modo che lancino la showModal()
    $$('.' + this.options.trigger).each( function (v, k){

      v.addEvent('click', function(e){

        e.preventDefault();
        this.showModal();

        // Se è stata definita una callback avviamola
        if(this.options.callbackOnTrigger)
          this.options.callbackOnTrigger.run(v, this);

      }.bind(this));
    }, this);


    // Animazione di comparsa del divup
    this.inFx = new Fx.Tween(this.options.divup, {
      duration: 700,
      transition: 'back:out'
    });

    // Animazione di scomparsa del divup
    this.outFx = new Fx.Tween(this.options.divup, {
      duration: 700,
      transition: 'back:out'
    });

    // Travaso il modello nella proprietà della classe
    this.inner = this.options.divup.innerHTML;
  },


  // -------------------------------
  // Fa comparire il divup
  showModal: function() {

    // To set the position of the "window" div at the center of the screen
    var size = document.getElement('body').getSize();
    var toY = 80;
    var toX = (size.x - 600) / 2;

    // Let's set the "window" div on the top of the screen on top of the rest of the content (z-index)
    this.options.divup.setStyles({
      'display': 'block',
      'position': 'absolute',
      'top': toY+'px',
      'left': toX+'px',
      'width': '600px' ,
      'z-index': '1',
      'opacity': '0'
    });

    this.createModal();
    this.inFx.start('opacity', '1');
  },


  // -------------------------------
  // Fa scomparire il divup
  closeModal: function() {
    this.outFx.start('opacity', '0');
  },


  // -------------------------------
  // Serve a creare l'html del divup
  createModal: function(){

    // First of all empty the JS generated content in the "window" div
    // usefull only after the first execution of the method
    this.options.divup.empty();

    // html structure for the 1px rounded corner of the "window" div
    var div1 = new Element('div', {'id': 'moodalDiv1', 'html': this.container});

    div1.inject(this.options.divup);
    this.options.divup.getElement('div.dialog_content').set('html', this.inner);

    // Se nel corpo del divup abbiamo un form trasformiamolo in form ajax
    if(myForm = div1.getElement('form'))
      this.setAjaxForm(myForm);

    // Mount the closeModal on close triggers
    $$('.moodalClose').each( function (v, k){
      v.addEvent('click', function(e){
        if(e)
          e.preventDefault();
        this.closeModal();
      }.bind(this));
    }.bind(this));

  },


  // -------------------------------
  // trasforma un form normale in un form ajax, bloccando il submit normale
  setAjaxForm: function(myForm){

    myForm.set(
      'send',
      {
        onComplete: function(resultStr){
          var result = JSON.decode(resultStr);
          var class = result.ok ? 'success' : 'error';
          result.msg = "<span class=\""+class+"\">"+result.msg+"</span>";

          if(myForm.getElement('.dialog_summary'))
            {
            var msgBox = myForm.getElement('.dialog_summary');
            msgBox.set('html', result.msg);
            msgBox.setStyle('opacity', '1');
            }
          else
            {
            var msgBox = new Element('div', {'class': 'dialog_summary', 'html': result.msg });
            msgBox.addEvent('dblclick', function(){
              msgBox.fade('out');
            });
            msgBox.inject(myForm, 'top');
            }

          // faccio sparire il messaggio di errore dopo 3 secondi
          msgBox.fireEvent('dblclick', null, this.msgDisappearsInSec);
          // Se l'operazione è andata bene dopo aver mostrato il testo chiudiamo il divup
          if(result.ok)
            $$('.moodalClose')[0].fireEvent('click', null, this.msgDisappearsInSec + 500);

          // Se è stata definita una callback avviamola ma con mezzo secondo di ritardo per dare il tempo agli altri fade di chiusura di completarsi
          if(this.options.callbackOnComplete)
            this.options.callbackOnComplete.delay(this.msgDisappearsInSec + 1000, this, result);
        }.bind(this)
      }
    );

    myForm.addEvent('submit', function(e){
      //  Preveniamo il default
      e = new Event(e);
      e.preventDefault();
      e.stop();

      myForm.send();
    });
  }

});
