﻿function Panier() {

  this.refreshPanier = function() {
    new Request.JSON({ url: "/Panier.ashx?Action=NbArticles",
      onComplete: function($data) {
        $("Panier").innerHTML = "Panier : " + $data.nbArticles;
      }
    }).send();
  }

  this.ajouter = function($event, $id) {
    var $button = $event.target ? $event.target : $event.srcElement;
    $button.value = "Ajouté";
    $button.style.color = "gray";
    $button.disabled = true;

    var $morph = new Fx.Morph("Panier");
    $morph.start({color: "#ffff00"});

    new Request.JSON({ url: "/Panier.ashx?Action=AjouterArticle&Id=" + $id,
      onComplete: this.responseAjouter.bind(this)
    }).send();
  }

  this.responseAjouter = function($response) {
    if ($response.Ok) {
      this.refreshPanier();
    }
    else
      alert($response.Message);
  }

  this.supprimer = function($id) {
    if (!confirm("Êtes-vous sûr de vouloir enlever cet article du panier ?"))
      return;
    new Request.JSON({ url: "/Panier.ashx?Action=SupprimerArticle&Id=" + $id,
      onComplete: function($response) {
        if ($response.Ok)
          window.location = "Panier.aspx";
        else
          alert($response.Message);
      }
    }).send();
  }

  this.changeQuantite = function($event, $id, $taille) {
    var $el = $event.target ? $event.target : $event.srcElement;
    new Request.JSON({ url: "/Panier.ashx?Action=ChangeQuantite&Article=" + $id + "&Taille=" + $taille + "&Quantite=" + $el.value,
      onComplete: function($response) {
        $("totalHt" + $id).innerHTML = $response.TotalHtArticle + " &euro;";
        $("totalHt").innerHTML = $response.TotalHt + " &euro;";
      }
    }).send();
  }

  this.save = function($id) {
    if (!confirm("Êtes-vous sûr de vouloir passer commande des articles de votre panier ?"))
      return;
    var $patientez = new Patientez();
    new Request.JSON({ url: "/Panier.ashx?Action=Save",
      onComplete: function($response) {
        $patientez.fermer();
        if ($response.Ok) {
          alert("Votre commande a bien été enregistrée, un mail de confirmation vous a été expédié");
          window.location = "/";
        }
        else
          alert($response.Message);
      }
    }).send();
  }

  this.refreshPanier();
  
}