Object.extend(CatalogController,
{
    _tree: null,
    _prices: null,
    _meta: null,
    _units: null,
    _minimumOrder: 1,
    _orderIncrement: 1,
    _timer: null,
    _pictures: null,
    _pictureIndex: 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));
        }
    },
    
    initProduct: function(prices, meta, units, pictures)
    {
        this._pictures = pictures;
        $('next-picture').observe('click', this._nextPicture.bind(this));
        $('previous-picture').observe('click', this._previousPicture.bind(this));
        this._pictureIndex = 0;
        if(pictures.length > 1)
            $('next-picture').setStyle({visibility: ''});
        
        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);

        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);
    },
    
    addToCart: function(pid)
    {
        if(this._checkValue())
            EcommerceController.addToCart(pid);
    },
    
    _nextPicture: function()
    {
        $('product-picture-img').src = this._pictures[++this._pictureIndex];
        $('previous-picture').setStyle({visibility: ''});
        if(this._pictureIndex == this._pictures.length-1)
            $('next-picture').setStyle({visibility: 'hidden'});
    },
    
    _previousPicture: function()
    {
        $('product-picture-img').src = this._pictures[--this._pictureIndex];
        $('next-picture').setStyle({visibility: ''});
        if(this._pictureIndex == 0)
            $('previous-picture').setStyle({visibility: 'hidden'});
    },
    
    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());
        }
    }
});