var Reservations = new Class({

  initialize: function($id) {
    this.id = $id;
    MooTools.lang.setLanguage("fr-FR");
    this.date = (new Date()).format("%x");
    var $form = $("calForm" + this.id);
    var $this = this;
    if ($form) {
      $form.addEvent("submit", function($event) {
        $event.stop();
        this.set("send", { onComplete: $this.ajouterHandler.bind($this) });
        this.send();
      });
    }
  },

  changeDate: function($date) {
    this.date = $date;
    var $pannel = $("calMois" + this.id);
    var $div = new Element("div", { text: "chargement ...", "class": "ajax" });
    $pannel.adopt($div);
    $div.position({ position: "center", relativeTo: $pannel });
    $pannel.load("sys.cal.ajax.asp?ACTION=HTML_CALENDRIER&ID=" + this.id + "&DEBUT=" + $date);
  },

  refresh: function() {
    this.changeDate(this.date);
  },

  select: function($date) {
    $("o_calreserv_du").value = $date;
  },

  ajouterHandler: function($response) {
    $response = JSON.decode($response);
    if ($response.ok) {
      alert("Votre demande de réservation a bien été prise en compte");
      $("calForm" + this.id).reset();
      this.refresh();
    }
    else
      alert($response.message);
  }

});

var ReservationsSemaine = new Class({

  Extends: Reservations,

  changeDate: function($date) {
    this.parent($date);
    new Request.JSON({
      url: "sys.cal.ajax.asp?ACTION=GET_SEMAINES&ID=" + this.id + "&DEBUT=" + $date,
      onSuccess: this.refreshDates.bind(this)
    }).send();
  },

  refreshDates: function($semaines) {
    this.refreshSelectDates($("o_calreserv_du"), $semaines);
    this.refreshSelectDates($("o_calreserv_au"), $semaines);
  },

  refreshSelectDates: function($select, $semaines) {
    $select.options.length = $semaines.length + 1;
    var $option = document.createElement("option");
    $option.value = "";
    $option.text = "";
    $select.options[0] = $option;
    for (var $i = 0; $i < $semaines.length; $i++) {
      $option = document.createElement("option");
      $option.value = $semaines[$i].date;
      $option.text = $semaines[$i].libelle;
      $select.options[$i + 1] = $option;
    }
  },

  select: function($date) {
    new Request.JSON({
      url: "sys.cal.ajax.asp?ACTION=DEBUT_SEMAINE&ID=" + this.id + "&DATE=" + $date,
      onSuccess: function($json) {
        $("o_calreserv_du").value = $json.date;
      }
    }).send();
  }

});
