var Commerce = {}

Commerce.FicheProduit = new Class({
  Implements: [Options, Events],
  
  options: {
    pid:          0,
    values:       [],
    stockNumber:  0,
    initialStock : 0
  },
  
  initialize: function(option) {
  
    this.setOptions(option);
    
    this.pid = this.options.pid;
    this.values = this.options.values;
    this.stockNumber = this.initialStock = this.options.stockNumber;
    this.cart = $('nb_article');
    this.more = $('img_more');
    this.less = $('img_less');
    this.quantity = $('quantite');
    this.stockStars = $('stock_img');
  
    this.criteriasLists = $$('.critere-liste');
    
    this.price = $('oldprice');     
    this.promotionalPrice = $('price');
    this.cartButton = $('bouton_ajouteraupanier');

    this.setCriteriasListsListeners();
    this.setCartButtonListener();
    this.setQuantifierListener();

    this.isCorrectQuantity();
  },

  setCriteriasListsListeners: function() {
    this.eventCriteriaChange = this.setNewPrice.bind(this); // Passage en référence obligatoire à cause du bind

    this.criteriasLists.each(function(list) {
      list.addEvent('change', this.eventCriteriaChange);    
    }.bind(this));

  },

  setQuantifierListener: function() {
    this.eventMoreClick = this.moreQuantity.bind(this); // Passage en référence obligatoire à cause du bind
    this.eventLessClick = this.lessQuantity.bind(this); // Passage en référence obligatoire à cause du bind
    this.eventQuantityChange = this.isCorrectQuantity.bind(this); // Passage en référence obligatoire à cause du bind

    this.more.addEvent('click', this.eventMoreClick);
    this.less.addEvent('click', this.eventLessClick);
    this.quantity.addEvent('change', this.eventQuantityChange);
  },

  setCartButtonListener: function() {
    this.eventCartButtonClick = this.addToCart.bind(this); // Passage en référence obligatoire à cause du bind
    this.cartButton.addEvent('click', this.eventCartButtonClick);
  },

  addTransactionListeners: function() {
    this.cartButton.addEvent('click', this.eventCartButtonClick);
    this.more.addEvent('click', this.eventMoreClick);
    this.less.addEvent('click', this.eventLessClick);
    this.quantity.disabled = false;
    this.cartButton.setStyles({
      'opacity': 1,
      'cursor' : 'pointer'
    });
    if (this.quantity.value <= 0)
      this.quantity.value = 1;    
  },

  removeTransactionListeners: function() {
    this.cartButton.removeEvent('click', this.eventCartButtonClick);
    this.more.removeEvent('click', this.eventMoreClick);
    this.less.removeEvent('click', this.eventLessClick);
    this.quantity.disabled = true;
    this.cartButton.setStyles({
      'opacity': 0.5,
      'cursor' : 'default'
    });
    this.quantity.value = 0;
  },

  /**
   * Vérifie la suffisance du stock
   *
   * @return true|false true si le stock est suffisant, false sinon
   */
  hasSufficientStock: function() {
  
    var quantity = parseInt(this.quantity.value);
    
    if(this.stockNumber == 0)
      return false;

    return (this.stockNumber >= quantity || this.stockNumber == -1);
    
  },

  isCorrectQuantity: function() {
  
    var quantity = parseInt(this.quantity.value);
    
    if (!this.hasSufficientStock()) {
    
      if (this.stockNumber == 0 || this.stockNumber == -2 || this.promotionalPrice.innerHTML == '') {
        this.removeTransactionListeners();
        this.quantity.value = 0;
        //alert('Désolé, le stock pour ce produit est actuellement épuisé.');
      } else {
        this.quantity.value = this.stockNumber;
        alert(
          'Nous n\'avons pas suffisament de stock pour satisfaire votre demande.'
         +'Nous vous avons indiqué dans le champs quantité la quantité maximale que nous pouvons vous fournir ('+ this.quantity.value +').'
        );
      }
      
      return false;
      
    } else
      this.addTransactionListeners();

    if (quantity <= 0)
      return false;
 
    return true;
    
  },
  
  moreQuantity: function() {
    this.quantity.value++;
    return this.isCorrectQuantity();
       
  },

  lessQuantity: function() {
      if (this.quantity.value > 0) this.quantity.value--;
      return this.isCorrectQuantity(); 
  },

  setNewPrice: function() {
  
    this.values = new Array();
    
    this.criteriasLists.each(function(list) {
      this.values.push(list.value);
    }.bind(this));
    
    var quantity = parseInt(this.quantity.value);   
    var remote = new Remote({ name:'commerce', command:'getProductValuesInfo', params:{pid: this.pid, values: this.values, actualQuantity: quantity} });   

    remote.addEvent('complete', function(remote) {
    
      var response = remote.getResponseCode();
      var result = remote.getResponseData();

      this.result = result;
      this.response = response;

      if (response == 1 || response == 2) {

        if (this.price)
          this.price.innerHTML = result.price+' <small>T.T.C.</small>';
          
        if(this.promotionalPrice)
          this.promotionalPrice.innerHTML = result.promotionalPrice+' <small>T.T.C.</small>';

        this.stockNumber = result.stockNumber;
        
      } else if (response == 3) {
      
        if (this.price)
          this.price.innerHTML = '';
          
        if(this.promotionalPrice)
          this.promotionalPrice.innerHTML = '';
        
        this.stockNumber = 0;
        
      }
      
      /*
      if(this.initialStock>0 && this.stockNumber==-1)
        this.stockNumber = this.initialStock;
      */	

      if(typeof result.visual == 'object' && result.visual.upname)
        $('visual').src = wwwroot+'/'+result.visual.path;
      
      this.setStockStars(response);
      this.isCorrectQuantity();
      
    }.bind(this));
    
    remote.call();
  },

  setStockStars: function(stockCode) {  
    
    if(stockCode && stockCode == 3) {
    
      $('stock_img').set('html', '<span class="valStock">Non disponible avec ce(s) critère(s)</span>');
    
    } else if (this.stockNumber == -1) {
    
      //this.stockStars.src = wwwroot + '/media/img/enstock.jpg';
      $('stock_img').set('html', 'En stock');
      
    } else if (this.stockNumber > 0) {
    
      //this.stockStars.src = wwwroot + '/media/img/enstock.jpg';
      $('stock_img').set('html', '<span class="valStock">'+this.stockNumber+'</span> <b>pièce(s)</b>');
      
    } else if (this.stockNumber <= -2) {
    
      //this.stockStars.src = wwwroot + '/media/img/prochainement.jpg';
      $('stock_img').set('html', '<span class="valStock">En cours de réapprovisionnement</span>');
      
    } else {
    
      //this.stockStars.src = wwwroot + '/media/img/epuise.jpg';
      html  = '<span class="valStock">Stock actuellement epuisé.</span>';
      
      //if(this.result.connected == true) {
      /*
        html += '<br/>';
        html += '<a class="followProduct radius-3px" href="'+wwwroot+'/alerte-produit/'+this.pid+'/'+this.result.sid+'/index.html">';
        html += 'M\'avertir par mail dès que disponible !';
        html += '</a>';
      */
      //}
      
      $('stock_img').set('html', html);
      
    }
    
  },

  addToCart: function() {    
    var formatHTML;
     
    // verification du stock disponible et de ce que l'on a déjà ajouté au panier
    if (this.isCorrectQuantity()) {
      // on lance l'appel ajax pour ajouter au panier
      var remote = new Remote({ name:'commerce' , command:'addProductToCart' , params:{ product_id:this.pid, values_ids:this.values , quantity:this.quantity.value } });
  
      remote.addEvent('complete', function(remote) {
  
      if(remote.getResponseCode() == 1) {
         
        var nb_article = remote.getResponseData();

        if (nb_article == 0) {
          formatHTML = '';
          this.cart.setStyle('display','none');
        } else {
          formatHTML = nb_article;	    
          this.cart.setStyle('display','block');
        }

        this.cart.innerHTML = formatHTML;
      
        uid1 = UniqueID();
	    uid2 = UniqueID();
      
        Growl.Bezel({
          title: 'Panier',
          text: ''
            +'Le produit a &eacute;t&eacute; ajout&eacute; au panier. '
            +'Quantit&eacute;: '+this.quantity.value+' produit'+(this.quantity.value>1  ?'s':'')
            +'<br/><a href="javascript:void(0)" id="'+uid1+'" class="growlButton">Voir panier</a>'
            +'<a href="javascript:void(0)" id="'+uid2+'" class="growlButton">Continuer mes achats</a>'
          +'',
          image: wwwroot+'/media/module/Commerce/cart-logo.png',
          duration: 2,
          autoClose : false
        });
        
        $(uid1).addEvent('mouseup', function() { window.document.location = wwwroot+'/commande/panier.html'; });
        $(uid2).addEvent('mouseup', function() { window.document.location = wwwroot+'/'; });
        
      } else {
      
        var text = remote.getResponseText();
        this.stockNumber = remote.getResponseData();        
        if (text.trim() == 'already_on_cart') {
        
          this.removeTransactionListeners();
          alert('Vous avez déjà commandé la quantité maximale pour ce produit');
          this.quantity.value = 0;
          
        } else      {
        
          this.isCorrectQuantity();
        
        } 
          
      }
  
      }.bind(this));
  
      remote.call();
    
    }
  }

});


Commerce.Livraison = new Class({
  Implements: [Options, Events],
  
  options: {
     duration: 200,
     wait: false
  },
  
  initialize: function(option) {
    this.countriesList = $('pays_livraison');
    this.paysLabel = $$('.tab .adresses').getElement('input[name=liv_pays]')[1];
    this.shippingGridElements = $$('.tab .transport');
    this.priceZone = $$('.tab .zone_droite')[0];
    this.shippingInsertZone = $$('.tab .tab_header2')[0];
   
    this.gift = $('gift');
    this.shippingID = '';
    
    this.giftdetail = $('gift_message').value;
    if(!this.gift.checked){
      $$('.giftInformation')[0].setStyle('display', 'none');
    }
        
    this.setOptions(option);
    
    this.setShippingFx();
    
    this.setCountriesListeners();
    this.setShippingListeners();

    this.isGift();
  },

  isGift: function() {
    this.gift.addEvents({
     'click': function() {
       // On ne traite l'information que dans le cas où la checkbox est cochée
       var is_gift = 1;
       
       if(!this.gift.checked){
         is_gift = 0;
         $$('.giftInformation')[0].setStyle('display', 'none');
       }
       else {
         $$('.giftInformation')[0].setStyle('display', '');
       }
         

       var shipping = this.shippingID;
       var remote = new Remote({ name:'commerce' , command:'isAGift', params:{ shippingID:shipping, countryID:$('pays_livraison').value, gift:is_gift } });

       remote.addEvent('complete', function(remote) {
         if(remote.getResponseCode() == 1)
           this.priceZone.innerHTML = remote.getResponseData();
       }.bind(this));
       remote.call();

     }.bind(this)
    });
  },
  
  setShippingFx: function() {
    this.shippingGridElements.each(function(el) {
      el.set('morph', {
         duration:this.options.duration,
         wait:this.options.wait
       });
    }.bind(this));
  },
  
  setCountriesListeners: function() {
    this.countriesList.addEvents({
      'change': function() {
        this.paysLabel.value = this.countriesList.getElement('option[value='+this.countriesList.value+']').innerHTML;
        this.getShippingGridElements(this.countriesList.value);
      }.bind(this)
    });
  },
  
  setShippingListeners: function() {
    this.shippingGridElements.each(function(el) {
        el.getElement('input[type=radio]').addEvents({
          'change': function() {
            this.shippingGridElements.each(function(tr){
              tr.removeClass('transport_hover');
            });
            el.addClass('transport_hover');
            this.getHTMLShippingPrices(el.getElement('input[type=radio]').value);
            this.shippingID = el.getElement('input[type=radio]').value;
            $('gift').fireEvent('click');
          }.bind(this)
        });
        el.addEvent('click', function(){
        	el.getElement('input[type=radio]').set('checked','checked');
        });
    }.bind(this));
  },
  
  getShippingGridElements: function(countryID) {
    var tr;
    var td = new Array();
    var input;

    var shippings = new Array();
    var remote = new Remote({ name:'commerce' , command:'getShippingByCountry' , params:{ countryID:countryID } });
    this.shippingID = '';
    $('gift').fireEvent('click');
    
    remote.addEvent('complete', function(remote) {
      if(remote.getResponseCode() == 1) {
        shippings = remote.getResponseData();
        
        this.shippingGridElements.dispose();
        $each(shippings, function(shipping, n) {

            tr = new Element('tr', {
              'class' : 'transport'
            });
            
            input = new Element('input', {
              'type' : 'radio',
              'name' : 'transport',
              'value': shipping.trid
            });
            
            td[0] = new Element('td');
            td[1] = new Element('td', {
              'html' : shipping.libelle
            });
            td[2] = new Element('td', {
              'html' : shipping.dateLivraison + ' (' + shipping.description +')'
            });
            td[3] = new Element('td', {
              'html' : shipping.prixFormate
            });
            
            input.inject(td[0]);
            td[0].inject(tr);
            td[1].inject(tr);
            td[2].inject(tr);
            td[3].inject(tr);
            
            tr.inject(this.shippingInsertZone, 'after');                        
        }.bind(this));
        // On scanne à nouveau la zone des lignes tr
        this.shippingGridElements = $$('.tab .transport');
        this.setShippingListeners();
        
      }
    }.bind(this));
    
    remote.call();   
  },
  
  getHTMLShippingPrices: function(shippingID) {
  
    var is_gift = 1;
    if(!this.gift.checked)
      is_gift = 0;
  
    var remote = new Remote({ name:'commerce' , command:'getHTMLShippingPrices' , params:{ shippingID:shippingID, countryID:this.countriesList.value, gift:is_gift } });
    
    remote.addEvent('complete', function(remote) {
      
      if(remote.getResponseCode() == 1) {     
      
        this.priceZone.innerHTML = remote.getResponseData();
        
        livFormHide = $('livFormHide');
        f = false;
        
        if(livFormHide) {
          if(parseInt(livFormHide.value) == 1) {
            //$$('#livraisonForm input, #livraisonForm textarea').setProperty('disabled','disabled').setStyle('opacity', 0.5);
            $$('.livraisonForm').setStyle('display', 'none');
            f = true;
          }
        }
        
        if(!f) {
          //$$('#livraisonForm input, #livraisonForm textarea').setProperty('disabled','').setStyle('opacity', 1);
          $$('.livraisonForm').setStyle('display', '');
        }
        
      }

    }.bind(this));
    
    remote.call();
  }
});

Commerce.ChoixPaiement = new Class({
  Implements: [Options, Events],
  
  options: {
     duration: 200,
     wait: false
   },
   
   initialize: function(options) {
    this.payments = $$('.tab .paiement').getElements('input[name=paiement]');
    this.payments = $$('.paiement_input');
    this.paymentLines = $$('.tab .paiement');
    this.paymentDescriptions = $('payment_descriptions').getElements('span');
    
    this.setOptions(options);
    
    // this.setShippingFx(); @todo A developper ultérieurement : effet FX
    
    this.setPaymentListeners();
  },
  
  setShippingFx: function() {
    this.paymentLines.each(function(el) {
      el.set('morph', {
         duration:this.options.duration,
         wait:this.options.wait
       });
    }.bind(this));
  },
  
  setPaymentListeners: function() {
    this.payments.each(function(el) {
        D(el.getParent());
        el.getParent().addEvent('click', function(){
        	el.set('checked','checked');
        	this.showDescription(el.value);
        }.bind(this));
    }.bind(this));
  },
  
  showDescription: function(id) {
    this.paymentDescriptions.each(function(el) {
      el.setStyle('display' , 'none');
    });
    $('payment_description_' + id).setStyle('display' , '');
  }
});

  /*
  setNewPrice: function() {
    this.values = new Array();
    
    this.criteriasLists.each(function(list) {
      this.values.push(list.value);
    }.bind(this));
    
    var quantity = parseInt(this.quantity.value);   
    var remote = new Remote({ name:'commerce', command:'getProductValuesInfo', params:{pid: this.pid, values: this.values, actualQuantity: quantity} });   

    remote.addEvent('complete', function(remote) {
      var response = remote.getResponseCode();
      if (response == 1 || response == 2) {
        var result = remote.getResponseData();
        if (this.price != null)
          this.price.innerHTML = result.price;
        this.promotionalPrice.innerHTML = result.promotionalPrice;
        this.stockNumber = result.stockNumber;
      } else if (response == 3) {
        if (this.price != null)
          this.price.innerHTML = '';
        this.promotionalPrice.innerHTML = '';
        this.stockNumber = 0;
      }
      this.setStockStars();
      this.isCorrectQuantity();
    }.bind(this));
    
    remote.call();
  },
  */
  
var Catalogue = {};

Catalogue.FicheProduit = new Class({
  
   Implements: [Options, Events]
  
  ,criteriasLists : [] 
  ,values  : []
  ,eventCriteriaChange : function(){}
  
  ,initialize : function(options) {
  
    this.setOptions(options);
    this.pid = this.options.pid;
    this.values = this.options.values;
    this.stockNumber = 0;
    this.cart = new Element('div');
    this.more = new Element('img');
    this.less = new Element('img');
    this.quantity = new Element('div');
    this.stockStars = new Element('img');
    this.criteriasLists = $$('.critere-liste');
    this.setCriteriasListsListeners();
    this.promotionalPrice = $('price');
    this.cartButton = new Element('img');
  
  }
  
 ,setCriteriasListsListeners: function() {
 
    this.eventCriteriaChange = this.setNewPrice.bind(this); // Passage en référence obligatoire à cause du bind

    this.criteriasLists.each(function(list) {
      list.addEvent('change', this.eventCriteriaChange.bind(this));    
    }.bind(this));
    
  } 
  
 ,setNewPrice : function() { Commerce.FicheProduit.prototype.setNewPrice.bind(this)(); }
 ,setStockStars : function() {}
 ,isCorrectQuantity : function() {}
 
});