var Commerce = {}

Commerce.FicheProduit = new Class({
  Implements: [Options, Events],
  
  options: {
    pid:          0,
    values:       [],
    stockNumber:  0
  },
  
  initialize: function(option) {
    this.setOptions(option);
    this.pid = this.options.pid;
    this.values = this.options.values;
    this.stockNumber = 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);
    
    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();
      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();
  },

  setStockStars: function() {
    if (this.stockNumber > 0 || this.stockNumber == -1)
      this.stockStars.src = wwwroot + '/media/img/enstock.jpg';
    else if (this.stockNumber <= -2)
      this.stockStars.src = wwwroot + '/media/img/prochainement.jpg';
    else
      this.stockStars.src = wwwroot + '/media/img/epuise.jpg';
  },

  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 = 'Votre panier est vide';
        else {
          formatHTML = '<a href="' + wwwroot + '/commande/panier.html" title="Voir votre panier">';
          formatHTML += ' vous avez ' + nb_article + ' ' + ((nb_article > 1) ? 'articles' : 'article');
          formatHTML += '</a>';	    
        }

        this.cart.innerHTML = formatHTML;
      
        Growl.Bezel({
          title: 'Panier',
          text: 'Le produit a &eacute;t&eacute; ajout&eacute; &agrave; votre panier. Quantit&eacute;: '+this.quantity.value+' produit'+(this.quantity.value>1  ?'s':'')+'',
          image: wwwroot+'/media/module/Commerce/cart-logo.png',
          duration: 2
        });
      
      } 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();
      }
  
      // getResponseCode()
      // getResponseText()
      // getResponseData()
  
      }.bind(this));
  
    remote.call();
    
    }
  }

});


Commerce.Livraison = new Class({
  Implements: [Options, Events],
  
  options: {
     duration: 200,
     wait: false
  },
  
  initialize: function(option) {
    this.countriesList = $('pays_livraison');
    this.regionsList = $('region_livraison');
    
    this.paysLabel = $$('.tab .adresses').getElement('input[name=liv_pays]')[0];
    this.regionsLabel = $$('.tab .adresses').getElement('input[name=liv_reg]')[0];
    this.shippingGridElements = $$('.tab .transport');
    this.priceZone = $$('.tab .zone_droite')[0];
    this.shippingInsertZone = $$('.tab .tab_header2')[0];
    
    this.setOptions(option);
    
    this.setShippingFx();
    
    this.setCountriesListeners();
    this.setRegionsListeners();
    this.setShippingListeners();
  },
  

  
  setShippingFx: function() {
    this.shippingGridElements.each(function(el) {
      el.set('morph', {
         duration:this.options.duration,
         wait:this.options.wait
       });
    }.bind(this));
  },
  
  setRegionsListeners: function() {
    this.regionsList.addEvents({
      'change': function() {
        this.regionsLabel.value = this.regionsList.getElement('option[value='+this.regionsList.value+']').innerHTML;
      	this.getShippingGridElements(this.countriesList.value,this.regionsList.value);
      }.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,this.regionsList.value);
        
      }.bind(this)
    });
  },
  
  setShippingListeners: function() { 
  var val;
  
  //var i=document.getElementsByName("transport")[val].value;
    this.shippingGridElements.each(function(el) {
    var valeur = $('region_livraison').value;
        el.getElement('input[type=radio]').addEvents({
          'change': function() {
			  
			for(val=0;val<document.getElementsByName("test").length;val++){
			  
			  if(document.getElementsByName("transport")[val].checked){
			  if(document.getElementsByName("test")[val].value==1){
				$('departements').style.display = "none";
			    $('region_livraison').value = 96;
			  }
			  if(document.getElementsByName("test")[val].value==0){
				$('departements').style.display = "inline";
				$('region_livraison').value = valeur;
				
			   
			  }
			}
			}
            this.shippingGridElements.each(function(tr){
              tr.removeClass('transport_hover');
            });
            el.addClass('transport_hover');
            this.getHTMLShippingPrices(el.getElement('input[type=radio]').value);
          }.bind(this)
        });
    }.bind(this));
  },
  
  getShippingGridElements: function(countryID, regionID) {
    var tr;
    var td = new Array();
    var input;

    var shippings = new Array();
    
    var remote = new Remote({ name:'commerce' , command:'getShippingByCountry' , params:{ countryID:countryID, regionID:regionID } });
    
    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
            });
			td[4] = new Element('input', {
			  'type' : 'checkbox',
              'name' : 'test',
			  'style' : 'display:none;',
              'value': shipping.importance_dep,
			  });
            
            input.inject(td[0]);
            td[0].inject(tr);
            td[1].inject(tr);
            td[2].inject(tr);
            td[3].inject(tr);
			td[4].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 remote = new Remote({ name:'commerce' , command:'getHTMLShippingPrices' , params:{ shippingID:shippingID } });
    
    remote.addEvent('complete', function(remote) {
      
      if(remote.getResponseCode() == 1)      
        this.priceZone.innerHTML = remote.getResponseData();
          
      // getResponseCode()
      // getResponseText()
      // getResponseData()
      
    }.bind(this));
    
    remote.call();
  }
});

Commerce.ChoixPaiement = new Class({
  Implements: [Options, Events],
  
  options: {
     duration: 200,
     wait: false
   },

displayDepartement : function() {

	alert("bien");
	
	if(isset($('Pas_dep'))){
		$('departements').style.display = "inline";
	}
	else{
		$('departements').style.display = "none";
	}
	
},

   
   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) {
        el.addEvents({
          'change': function() {
            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() {}
 
});
