Object.extend(CatalogController,
{
    _tree: null,
    _prices: null,
    _meta: null,
    _units: null,
    _minimumOrder: 1,
    _orderIncrement: 1,
    _timer: null,
    _pictures: null,
    _zooms: null,
    _pictureIndex: 0,
    _thumbIndex: 0,
    
    init: function(tree)
    {
        this._tree = tree;
        
        if($('filterForm'))
        {
            $A($('filterForm').getElementsByTagName('input')).each(function(i){
                i = $(i);
                
                if(i.type == 'text')
                    i.observe('keypress', this._delayCountFilter.bind(this));
                else if(i.type == 'checkbox' || i.type == 'radio')
                    i.observe('change', this._delayCountFilter.bind(this));
            }.bind(this));
            $A($('filterForm').getElementsByTagName('select')).each(function(i){
                if(i.options.length == 2)
                    $(i).disable();
                $(i).observe('change', this._delayCountFilter.bind(this));
            }.bind(this));
        }

				if($('helpBox') != null)
            new Dialog.Box('helpBox');
    },
    
    initProduct: function(prices, meta, units, pictures, zooms)
    {
        this._pictures = pictures;
        this._zooms = zooms;
        for(var i = 0; i < pictures.length && i < 4; i++) {
          $('pt_'+i).down().src = pictures[i];
          $('pt_'+i).observe('click', this._setPicture.bind(this, i));
        }
        if(pictures.length) {
          this._pictureIndex = 0;
          this._thumbIndex = 0;
          $('pt_0').up().addClassName('selected');
          $('prev-thumb').observe('click', this._previousPicture.bind(this));
          $('next-thumb').observe('click', this._nextPicture.bind(this));
          $('prev-thumb').up().addClassName('off');
          $('product-picture-img').observe('click', this._zoomPicture.bind(this));
          if(this._hasZoom(0)) { $('icon-zoom').show(); }
        }
        
        if(prices.length <= 0)
            return;
        this._prices = prices;
        this._meta = meta;
        this._units = units;
        
        this._minimumOrder = parseInt(this._meta.minimumOrder);
        this._orderIncrement = parseInt(this._meta.orderIncrement);
        
        $('product-qty').value = this._minimumOrder;
        this.displayPrice();
    },
    
    countFilter: function()
    {
        this._timer = null;
        var f = this._getFilters();
        var q = ($('q'))?$F('q'):null;
        this.countResults(this._tree, f.toJSON(), q, function(r, j){ $('filterCount').update(j.out); } );
    },
    
    countCompatibles: function(from)
    {
        if(from != 'product')
            $('compatibility_'+from+'_loader').show();
        var q = ($('q'))?$F('q'):null;
        this._countCompatibles(this._tree, q, $F('compatibility_brand'), $F('compatibility_range'), $F('compatibility_product'), from, function(r, j)
        {
            j = this._getJSON(r, j);
            if(j == null)
                return;
            $('filterCount').update(j.out.count);
            switch(from)
            {
                case 'brand':
                var cr = $('compatibility_range');
                cr.selectedIndex = 0;
                cr.options.length = 1;
                $A(j.out.data).each(function(d){
                    cr.options[cr.options.length] = new Option(d.name, d.id);
                });
                if(j.out.data.length)
                	cr.disabled = false;
                else
                	cr.disabled = true;	
                var cp = $('compatibility_product');
                cp.selectedIndex = 0;
                cp.options.length = 1;
                cp.disabled = true;
                
                $('compatibility_brand_loader').hide();
                break;
                case 'range':
                var cp = $('compatibility_product');
                cp.selectedIndex = 0;
                cp.options.length = 1;
                $A(j.out.data).each(function(d){
                    cp.options[cp.options.length] = new Option(d.name, d.id);
                });
                if(j.out.data.length)
                	cp.disabled = false;
                else
                	cp.disabled = true;	
                $('compatibility_range_loader').hide();
                break;
                case 'product':
                break;
            }
        }.bind(this));
    },
    
    applyFilter: function(base, sort, dir)
    {
        var get = true;
        if($('compatibilityForm'))
        {
            get = ($('compatibility_brand').selectedIndex == 0 && $('compatibility_range').selectedIndex == 0 && $('compatibility_product').selectedIndex == 0);
            if(get)
                document.location = base;
            else
            {
                $('resultPage').value = base.gsub('^.*(\\?|&)p=', '');
                if(sort) {
                  $('sortKey').value = sort;
                  $('sortDir').value = dir;
                }
                $('compatibilityForm').submit();
            }
        }
        else
        {
            var f = this._getFilters();
            get = f.size() == 0
            if(get)
                document.location = base;
            else
            {
                $('resultPage').value = base.gsub('^.*(\\?|&)p=', '');
                if(sort) {
                  $('sortKey').value = sort;
                  $('sortDir').value = dir;
                }
                $('filterForm').submit();
            }
        }
        
    },
    
    _delayCountFilter: function()
    {
        if(this._timer)
            clearTimeout(this._timer);
        this._timer = setTimeout(this.countFilter.bind(this), 300);
    },
    
    _getFilters: function()
    {
        var inputs = $A($('filterList').getElementsByTagName('input'));
        var selects = $A($('filterList').getElementsByTagName('select'));
        var f = $H();
        
        inputs.each(function(input)
        {
            if(input.type == 'hidden')
                return;
            if(input.type == 'radio' || input.type == 'checkbox')
            {
                if(input.checked)
                    f.set(input.id, {value: input.value, operator: '='});
            }
            else
            {
                var v = input.value.replace(/^\s+|\s+$/, '');
                if(v.length <= 0)
                    return;
                f.set(input.id, {value: v, operator: '='});
            }
        });
        selects.each(function(select)
        {
            if(select.selectedIndex < 0 || select.options.length == 2)
                return;
            if(select.id.match(/-operator$/))
            {
                var s = select.id.replace(/-operator$/, '');
                var v = f.get(s);
                if(v == null)
                    return;
                v.operator = select.options[select.selectedIndex].value;
                f.set(s, v);
            }
            else
            {
                var v = $A();
                $A(select.options).each(function(option){ if(option.selected && option.value.length > 0){ v.push(option.value); }});
                if(v.length > 0)
                    f.set(select.id, {value: v, operator: '='});
            }
        });
        
        return f;
    },
    
    compare: function(url)
    {
        var cmpv = '?_=_';
        var checkCount = 0;
        $A($('product-list').getElementsByTagName('input')).each(function(inp)
        {
            if(inp.type == 'text')
                return;
            if(inp.checked)
            {
                cmpv += "&p[]="+inp.value;
                checkCount++;
            }
        });
        if(checkCount < 2)
            return;
        document.location = url + cmpv;
    },
    
    checkValue: function()
    {
        if(this._timer)
            clearTimeout(this._timer);
        this._timer = setTimeout(this._checkValue.bind(this), 125);
    },
    
    _checkValue: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return false;
        }
        if(v < this._minimumOrder || v%this._orderIncrement != 0)
        {
            $('product-qty').setStyle({backgroundColor: 'red'});
            return false;
        }
        else
        {
            $('product-qty').setStyle({backgroundColor: ''});
            this.displayPrice();
            return true;
        }
    },
    
    nextIncrement: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return;
        }
        v = Math.floor(v/this._orderIncrement)*this._orderIncrement;
        v += this._orderIncrement;
        if(v < this._minimumOrder)
            v =  this._minimumOrder;
        $('product-qty').value = v;
        $('product-qty').setStyle({backgroundColor: ''});
        this.displayPrice();
    },
    
    previousIncrement: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return;
        }
        v = Math.floor(v/this._orderIncrement)*this._orderIncrement;
        v -= this._orderIncrement;
        if(v < this._minimumOrder)
            v =  this._minimumOrder;
        $('product-qty').value = v;
        $('product-qty').setStyle({backgroundColor: ''});
        this.displayPrice();
    },
    
    displayPrice: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return;
        }
        var cp = null;
        var i = 0;
        while(i < this._prices.length && this._prices[i].level <= (v*this._meta.displayCoef))
            i++;
            
        var t = parseInt(this._meta.taxes);
        cp = Math.round((parseInt(this._prices[i-1].price)+t)*EcommerceController._vat*EcommerceController._currencyRate);

        v = Math.round((v*this._meta.displayCoef)*(cp/this._meta.baseToSaleCoef));
        var vv = (v/100).toString();
        if(v%100 == 0)
            vv += '.00';
        else if(v%10 == 0)
            vv += '0';
        $('current-price').update(vv);
        
        vv = (cp/100).toString();
        if(cp%100 == 0)
            vv += '.00';
        else if(cp%10 == 0)
            vv += '0';
        $('current-salesprice').update(vv);
        
        cp = Math.round((this._meta.displayCoef)*(cp/this._meta.baseToSaleCoef));
        vv = (cp/100).toString();
        if(cp%100 == 0)
            vv += '.00';
        else if(cp%10 == 0)
            vv += '0';
        $('current-displayprice').update(vv);

				// prochain dégressif
				if (this._prices.length > 1) {
					var p = null;
					if(this._prices[i])
						p = this._prices[i];
					else
						p = this._prices[i-1];
					
					var lvl = Math.round(p.level/this._meta.displayCoef);
					var pu = Math.round((parseInt(p.price)+t)*EcommerceController._vat*EcommerceController._currencyRate);
					pu = Math.round((this._meta.displayCoef)*(pu/this._meta.baseToSaleCoef));
					puu = (pu/100).toString();
	        if(cp%100 == 0)
	            puu += '.00';
	        else if(cp%10 == 0)
	            puu += '0';

					$('next-displaylevel').update(lvl);
	        $('next-displayprice').update(puu);
				}
    },
    
    addToCart: function(pid)
    {
        if(this._checkValue())
            EcommerceController.addToCart(pid);
    },
    
    _nextPicture: function(event)
    {
      Event.stop(event);
      
      if(this._pictureIndex == this._pictures.length - 1) {
        return;
      }
      $('pt_'+this._thumbIndex).up().removeClassName('selected');
      this._pictureIndex++;
      if(this._thumbIndex < 3) {
        this._thumbIndex++;
      } else {
        for(var i = 3, j = 0; i >= 0; i--, j++) {
          $('pt_'+i).down().src = this._pictures[this._pictureIndex-j];
        }
      }
      $('pt_'+this._thumbIndex).up().addClassName('selected');      

      $('product-picture-img').src = this._pictures[this._pictureIndex];
      if(this._hasZoom(this._pictureIndex)) { $('icon-zoom').show(); } else { $('icon-zoom').hide(); }
      
      if(this._pictureIndex == this._pictures.length - 1) {
        $('next-thumb').up().addClassName('off');
      } else {
        $('next-thumb').up().removeClassName('off');
      }
      if(this._pictureIndex == 0) {
        $('prev-thumb').up().addClassName('off');
      } else {
        $('prev-thumb').up().removeClassName('off');
      }
    },
    
    _hasZoom: function(idx) {
      var zoom = this._pictures[idx].replace('product_', 'zoom_');
      if(!this._zooms.length) { return false; }
      for(var i = 0; i < this._zooms.length; i++) {
        if(zoom == this._zooms[i]) return true;
      }
      return false;
    },

    _previousPicture: function(event)
    {
      Event.stop(event);
      
      if(this._pictureIndex == 0) {
        return;
      }
      $('pt_'+this._thumbIndex).up().removeClassName('selected');
      this._pictureIndex--;
      if(this._thumbIndex > 0) {
        this._thumbIndex--;
      } else {
        for(var i = 0; i < 4; i++) {
          $('pt_'+i).down().src = this._pictures[this._pictureIndex+i];
        }
      }
      $('pt_'+this._thumbIndex).up().addClassName('selected');      

      $('product-picture-img').src = this._pictures[this._pictureIndex];
      if(this._hasZoom(this._pictureIndex)) { $('icon-zoom').show(); } else { $('icon-zoom').hide(); }
      
      if(this._pictureIndex == this._pictures.length - 1) {
        $('next-thumb').up().addClassName('off');
      } else {
        $('next-thumb').up().removeClassName('off');
      }
      if(this._pictureIndex == 0) {
        $('prev-thumb').up().addClassName('off');
      } else {
        $('prev-thumb').up().removeClassName('off');
      }
    },
    
    _setPicture: function(index, event) {
      Event.stop(event);
      $('pt_'+this._thumbIndex).up().removeClassName('selected');
      this._pictureIndex += index-this._thumbIndex;
      this._thumbIndex = index;
      $('pt_'+this._thumbIndex).up().addClassName('selected');
      
      $('product-picture-img').src = this._pictures[this._pictureIndex];
      if(this._hasZoom(this._pictureIndex)) { $('icon-zoom').show(); } else { $('icon-zoom').hide(); }
      
      if(this._pictureIndex == this._pictures.length - 1) {
        $('next-thumb').up().addClassName('off');
      } else {
        $('next-thumb').up().removeClassName('off');
      }
      if(this._pictureIndex == 0) {
        $('prev-thumb').up().addClassName('off');
      } else {
        $('prev-thumb').up().removeClassName('off');
      }
    },
    
    _zoomPicture: function(event) {
      Event.stop(event);
      if(!this._hasZoom(this._pictureIndex)) { return; }
      
      var h = '<img src="'+this._pictures[this._pictureIndex].replace(/product_/,'zoom_')+'" width="700" height="700">';
      Modalbox.show(h, {title: "Zoom", width: 760});
    },
    
    addToFavs: function(pid, logged)
    {
        var pids = $A();
        if(pid)
        {
            pids.push(pid);
        }
        else
        {
            $A($('product-list').getElementsByTagName('input')).each(function(inp)
            {
                if(inp.type == 'text')
                    return;
                if(inp.checked)
                {
                    pids.push(inp.value);
                    inp.checked = false;
                }
            });
        }
        if(logged)
        {
            
            this._addToFavs(pids.toJSON(),function(r,j)
            {
                j = this._getJSON(r, j);
                if(j && !j.failed)
                {
                    if($('addToFav'))
                    {
                        $('addToFav').hide();
                        $('isFav').show();
                    }
                }
            }.bind(this));
        }
        else
        {
            document.location = '/'+Globule.currentLanguage+'/clients/login.phtml?from='+ encodeURIComponent('/'+Globule.currentLanguage+'/clients/favourites.phtml?a=add&p='+pids.toString());
        }
    }
});

