var skin_href = false;
var base_href = '';
var IE = !!(Browser.Engine.trident);
var IE8 = !!(Browser.Engine.trident && (Browser.Engine.version >= 5) && navigator.appVersion.match(/MSIE.8.[0-9]/));
var IE7 = !!(Browser.Engine.trident && (5 == Browser.Engine.version) && !navigator.appVersion.match(/MSIE.8.[0-9]/));
var IE6 = !!(Browser.Engine.trident && (Browser.Engine.version < 5));
var IE67 = !!(IE6 || IE7);

var OptionsDefault, OptionsConfiguration, OptionCurrentStock, OptionImgWidth;

if('object' != $type(window.Lang))
    var Lang = JSON.decode('{"common":{"product_vote_alert":"","product_stock_select":"","product_stock_download_error":""},"voting":{"vote_n":""},"basket":{"address_request_error":""}}');

window.addEvent('domready', function() {
    HrefParser.check();

    $$('input[name=nojs]').set('value', 0);

    $$('.gotourl').addEvent('change', function(e) {
        new Event(e).stop();
        if(this.value.length)
            window.location.href = this.value;
    });

    $$('.bottest').destroy();

    $$('.clickhide').each(function(el) {
        el.addEvent('click', function(e) {
            $(this).fade(0);
        });
    });

    $$('#box_producers_select').each(function(el) {
        var href = window.location.pathname;
        if(el.getElements('option').get('value').contains(href))
            el.set('value', href);
    });

    $$('input.fadingtext').each(function(el) {
        if(0 == el.value.length) return;

        if( !$chk(el.form._fadingtext) )
            el.form._fadingtext = [ ];

        el.form._fadingtext.push(el);

        el._value = el.value;
        el.addEvent('focus', function(e) {
            if(this.value == this._value)
                this.value = '';
        })

        el.addEvent('blur', function(e) {
            if('' == this.value)
                this.value = this._value;
        });

        $(el.form).addEvent('submit', function(e) {
            new Event(e).stop();
            this._fadingtext.each(function(el) {
                el.fireEvent('focus', null);
            });
            this.submit();
        });
    });

    $$('span.votestars').each(function(el) {
        if($chk(el.get('id')) > 0)
            new ProductVoter(el);
    });

    $$('button.resetsubmit').each(function(el) {
        if($chk(el.form))
            el.addEvent('click', function(e) {
                new Event(e).stop();
                $(this.form).getElements('input[type=text]').each(function(el) { el.set('value', ''); });
                $(this.form).getElements('input[type=checkbox]').each(function(el) { el.checked = false; });
                $(this.form).getElements('select').each(function(el) { el.selectedIndex = 0; });
                new Element('input', {
                    'type' : 'hidden',
                    'name' : 'reset',
                    'value' : 1
                }).inject($(this.form));
                $(this.form).submit();
            });
    });

    $$('button.reset').each(function(el) {
        if($chk(el.form))
            el.addEvent('click', function(e) {
                new Event(e).stop();
                $(this.form).getElements('input[type=text]').each(function(el) { el.set('value', ''); });
                $(this.form).getElements('input[type=checkbox]').each(function(el) { el.checked = false; });
                $(this.form).getElements('select').each(function(el) { el.selectedIndex = 0; });
            });
    });

    if('string' == $type(OptionsDefault) && OptionsDefault.length > 0) {
        var d = eval(Base64.decode(OptionsDefault));
        var o = $$('div.stocks select');
        for(var x = 0; x < o.length; ++x)
            o[x].value = d[x % d.length];
    }

    if('string' == $type(OptionsConfiguration) && OptionsConfiguration.length > 0) {

        var d = JSON.decode(Base64.decode(OptionsConfiguration));

        if('string' == $type(OptionCurrentStock) && OptionCurrentStock.length > 0)
            OptionCurrentStock = OptionCurrentStock.toInt();

        if(0 == d.length) {
            $$('div.stocks').setStyle('display', 'none');
            return;
        }

        var n = 0;
        var first = null, last = null;
        var list = $$('div.stocks select');

        var fv = [ ];
        for(var s in d)
            fv.push( d[s][0] );
        fv = fv.unique();
        for(var x = 0; x < list[0].options.length;)
            if(! fv.contains($(list[0].options[x]).get('value')) )
                list[0].remove(x);
            else
                ++x;

        if(list.length > 0) {
            list.each(function(el) {
                el._n = n++;
                el._conf = d;
                el._options = $A(el.options);
                el._list = list;

                el.addEvent('change', function(e) {
                    var values = this._list.get('value');

                    for(var x = this._n + 1; x < this._list.length; ++x) {
                        while(this._list[x].length > 0)
                            this._list[x].remove( 0 );
                    }

                    for(var s in this._conf) {
                        var ok = true;
                        for(var x = 0; x < this._n + 1; ++x) {
                            if(this._list[x].value != this._conf[s][x]) {
                                ok = false;
                                break;
                            }
                        }


                        if(true === ok) {
                            for(var x = this._n + 1; x < this._list.length; ++x)
                                this._list[x].addByValue(this._conf[s][x]);
                            console.log('ok', this._conf[s], s);
                        } else {

                        }
                    }

                    for(var x = this._n + 1; x < this._list.length; ++x) {
                        var vars = [];
                        for(var y = 0; y < this._list[x].options.length; ++y)
                            vars.push( $(this._list[x].options[y]) );

                        if( $$(vars).get('value').contains( values[x] ) ) {
                            this._list[x].set('value', values[x]);
                        } else {
                            if(this._list[x].options.length > 1) {
                                var o = new Option(Lang.common.product_stock_select, '');
                                try {
                                    this._list[x].add(o, this._list[x].options[0]);
                                } catch(e) {
                                    this._list[x].add(o, 0);
                                }
                            }
                            this._list[x].selectedIndex = 0;
                        }
                    }

                    values = this._list.get('value');
                    if(false == values.contains('')) {
                        values = values.join(',');
                        for(var s in el._conf)
                            if( this._conf[s].join(',') == values )
                                StockDownloader.get( s.replace('stock_', '').toInt() );
                    } else {
                        $$('#box_productfull form.basket input[name^=stock_id]').set('value', '');
                    }

                    for(var x = this._n + 1; x < this._list.length; ++x) {
                        this._list[x].fireEvent('change', null);
                    }
                });

                el.addByValue = function(v) {
                    for(var x = 0; x < this.options.length; ++x)
                        if($(this.options[x]).get('value') == v)
                            return;

                    for(var x = 0; x < this._options.length; ++x)
                        if(this._options[x].value == v)
                            try {
                                this.add(this._options[x], null);
                            } catch(e) {
                                this.add(this._options[x]);
                            }
                }
            });
            list[ list.length - 1 ]._last = true;
            list[0].fireEvent('change', null);
        }
    }

    $$('#box_productfull form.basket').addEvent('submit', function(e) {
        new Event(e).stop();
        var sid = $(this).getElements('input[name^=stock_id]').get('value').join('').toInt();
        if(sid > 0)
            $(this).submit();
        else
            alert(Lang.common.product_select_stock);
    });

    $$('.error_message a.close', '.info_message a.close', '.success_message a.close', '.warning_message a.close').each(function(el) {
        el.addEvent('click', function(e) {
            new Event(e).stop();
            $(this).getParent().destroy();
        });
        el.setStyle('display', 'block');
    });

    $$('#box_register form input[type=radio][name=address_type]').each(function(el) {
        el._form = $(el.form);
        el.addEvent('change', function(e) {
            if( 1 == this.get('value') && true == this.checked ) {
                $S('#box_register form input[name=coname] ! tr')[0].addClass('none');
                $S('#box_register form input[name=nip] ! tr')[0].addClass('none');
            } else {
                $S('#box_register form input[name=coname] ! tr')[0].removeClass('none');
                $S('#box_register form input[name=nip] ! tr')[0].removeClass('none');
            }
        });
        if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
        if(true == el.checked)
            el.fireEvent('change', null);
    });

    $$('label').each(function(lbl) {
        var f = lbl.get('for');
        if($chk(f) && ! $chk($(f))) {
            var i = $$('input[name=' + f + ']', 'textarea[name=' + f + ']').pop();
            if($chk(i)) {
                f += '_' + Math.round(new Date().getTime() * Math.random()).toString();
                lbl.set('for', f);
                i.set('id', f);
            }
        }
    });

    if($chk($('box_basketlist')))
        ShoperBasket.initialize(1);

    if($chk($('box_basketaddress')))
        ShoperBasket.initialize(2);

    $$('.titlealert').each(function(el) {
        el.addEvent('click', function(e) {
            new Event(e).stop();
            this.blur();
            alert(this.get('title'));
        });
    });

    $$('.titlequestion').each(function(el) {
        el.addEvent('click', function(e) {
            new Event(e).stop();
            this.blur();
            if(confirm(this.get('title')))
                window.location.href = this.get('href');
        });
    });

    PopupMapper();

    ImageZoom.init();

    $$('#box_productfull .productimg .smallgallery').each(function(div) {
        new ImageSlider({
            'container' : div,
            'left_arrow_img' : skin_href + 'images/so_left.png',
            'right_arrow_img' : skin_href + 'images/so_right.png'
        });
    });

    if('string' == $type(Cookie.read('skinpreview')))
        new SkinPreviewBox();

    /* layout fixes for IE6 and IE7 browsers (assuming IEs are browsers) */
    if(IE67) {
        $$('select').each(function(el) {
            var mw = el.getStyle('min-width');
            if(mw && mw.toInt() && mw.toInt() > el.getSize().x)
                el.setStyle('width', mw.toInt() + 'px');
        });

        $$('.shaded_inputwrap').each(function(el) {
            var nodes = [];
            var node = el.firstChild;
            while(node) {
                if(3 == node.nodeType)
                    nodes.push(node);
                node = node.nextSibling;
            }
            nodes.each(function(node) {
                node.parentNode.removeChild(node);
            });
        });

        $$('.main .floatcenterwrap .paginator').each(function(el) {
            var sizes = el.getElements('li').getSize();
            var w = 0;
            for(var x = 0; x < sizes.length; ++x)
                w += sizes[x].x;
            el.setStyle('left', 0);
            el.getParent().setStyle('margin-left',  -w + 'px');
        });

        $$('#box_productfull table.maininfo').each(function(table) {
            var dl = table.getElement('td.availability dl');
            var basket = table.getElement('td.basket');
            if($chk(dl) && $chk(basket)) {
                var h = table.getComputedSize().totalHeight - dl.getComputedSize().totalHeight;
                basket.setStyle('height', h - 20 + 'px');
            }
        });
    }

    if(IE6) {
        $$('form').each(function(el) {
            var b = el.getElements('button');
            if(b.length > 1)
                b.addEvent('click', function(e) {
                    new Event(e).stop();
                    $(this.form).getElements('button').set('disabled', true);
                    this.set('disabled', false);
                    $(this.form).submit();
                });
        });

        $$('img', 'li').each(function(img) {
            if(!img.getStyle('filter') && img.getStyle('background-image').match(/^url\(".*\.png"\)$/)) {
                var url = img.getStyle('background-image').replace(/^url\("(.*\.png)"\)$/, "$1");
                img.setStyles({
                    'background-image' : 'none',
                    'filter' : 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + url + '",sizingMethod="crop")'
                });
            }
        });

        document.body.style.behavior = 'url("' + skin_href + 'styles/csshover3.htc")';
    }
    /* */
});


var ImageSlider = new Class({
    Implements: Options,
    'options' : {
        'container' : null,
        'sdiv' : null,
        'ul' : null,
        'left_arrow' : null,
        'left_arrow_img' : null,
        'right_arrow' : null,
        'right_arrow_img' : null,
        'imgwidth' : 0,
        'imgcount' : 0,
        'imglimit' : 0,
        'pos' : 0,
        'left_delta' : -2,
        'right_delta' : 2,
        'loaded_left_arrow' : false,
        'loaded_right_arrow' : false,
        'images_loaded' : 0
    },

    'initialize' : function(options) {
        this.setOptions(options);
        if(!$chk(this.options.container)) return;

        var div = this.options.container;
        this.options.sdiv = div.getChildren('.innersmallgallery').pop();
        this.options.ul = div.getElements('.innersmallgallery ul').pop();
        if(!$chk(this.options.sdiv) || !$chk(this.options.ul) || this.options.ul.getChildren().length < 2) return;

        this.options.imgcount = this.options.ul.getChildren().length;
        this.options.ul.getElements('img').each(function(img) {
            img.addEvent('load', this.image_loaded.bind(this) );
        }, this);
    },

    'image_loaded' : function() {
        this.options.images_loaded++;
        if(this.options.imgcount == this.options.images_loaded)
            this.start_init();
    },

    'start_init' : function() {
        var div = this.options.container;
        var sdiv = this.options.sdiv;
        var ul = this.options.ul;

        div.setStyles({
            'width' : div.getSize().x,
            'height' : div.getSize().y,
            'position' : 'relative'
        }).setOpacity(0);

        sdiv.setStyles({
            'overflow' : 'hidden',
            'width' : 100 * ul.getChildren().length
        });

        var w = 0;
        ul.getChildren().each(function(li) {
            w += li.getComputedSize().totalWidth;
        });
        if(w <= 10) return;
        sdiv.setStyle('width', w);
        this.options.imgwidth = Math.round(w / this.options.imgcount);

        this.options.left_arrow = new Element('img', {
            'src' : this.options.left_arrow_img,
            'styles' : {
                'left' : 0,
                'position' : 'absolute',
                'border-width' : 0,
                'cursor' : 'pointer'
            },
            'events' : {
                'load' : function(e) {
                    this._class.options.loaded_left_arrow = true;
                    this.setStyle('top', Math.round( (this.getParent().getSize().y - this.getSize().y) / 2 ) );
                    this._class.continue_init();
                },
                'click' : function(e) {
                    new Event(e).stop();
                    this._class.slide( this._class.options.left_delta );
                }
            }
        }).inject( div );
        this.options.left_arrow._class = this;

        this.options.right_arrow = new Element('img', {
            'src' : this.options.right_arrow_img,
            'styles' : {
                'right' : 0,
                'position' : 'absolute',
                'border-width' : 0,
                'cursor' : 'pointer'
            },
            'events' : {
                'load' : function(e) {
                    this._class.options.loaded_right_arrow = true;
                    this.setStyle('top', Math.round( (this.getParent().getSize().y - this.getSize().y) / 2 ) );
                    this._class.continue_init();
                },
                'click' : function(e) {
                    new Event(e).stop();
                    this._class.slide( this._class.options.right_delta );
                }
            }
        }).inject( div );
        this.options.right_arrow._class = this;
    },

    'continue_init' : function() {
        if(false == this.options.loaded_right_arrow || false == this.options.loaded_left_arrow) return;

        var imglimit = this.options.container.getSize().x - this.options.left_arrow.getSize().x - this.options.right_arrow.getSize().x;
        imglimit = Math.round( imglimit / this.options.imgwidth );
        this.options.sdiv.setStyle('margin-left', Math.round( (this.options.container.getSize().x - imglimit * this.options.imgwidth) / 2 ) );
        this.options.imglimit = imglimit;

        if(this.options.imglimit >= this.options.imgcount) {
            this.options.left_arrow.dispose();
            this.options.right_arrow.dispose();
        }

        this.slide();
        this.options.container.setOpacity(1);
    },

    'slide' : function(delta) {
        if(!$chk(delta)) delta = 0;
        this.options.pos += delta;
        if(this.options.pos < 0)
            this.options.pos = 0;
        else if(this.options.pos > (this.options.imgcount - this.options.imglimit) )
            this.options.pos = this.options.imgcount - this.options.imglimit;

        var list = this.options.ul.getChildren();
        var start = this.options.pos;
        var stop = this.options.pos + this.options.imglimit - 1;
        for(var x = 0; x < list.length; ++x) {
            if(x >= start && x <= stop)
                list[x].removeClass('none');
            else
                list[x].addClass('none');
        }
    }

});


var ImageZoom = new Class({

    'img' : null,
    'div' : null,
    'divimg' : null,
    'src' : null,

    'mmfx' : false,
    'infx' : false,
    'inner' : true,
    'inside' : false,
    'startpos' : null,

    'shade1' : null,
    'shade2' : null,

    'initialize' : function(img, inner) {
        img._class = this;
        img._zoomimage = this;

        this.img = img;
        this.inner = !!inner;

        img.addEvent('mouseenter', function(e) {
            if(this.getSize().x < 5) return;
            this._class.inside = true;
            if(true == this._class.infx)
                this._class.show_div.delay(150, this._class);
            else
                this._class.show_div();
        }).addEvent('mouseleave', function(e) {
            this._class.inside = false;
        }).addEvent('mousemove' , function(e) {
            if(true == this._class.inside)
                this._class.startpos = e.page;
        });


        if(img.get('class').match(/gallery_[0-9]+/)) {
            var id = img.get('class').replace(/.*gallery_([0-9]+).*/, 'prodimg$1');
            if(id.match(/^prodimg[0-9]+$/) && $(id))
                this.src = $(id).get('href');
        } else {
            this.src = img.getParent().get('href');
        }

        if($chk(this.src))
            new Asset.image( this.src );
    },

    'destroy' : function() {
        delete this.img._class;
        delete this.img._zoomimage;
        if($chk(this.div)) this.div.dispose();
        if($chk(this.shade1)) this.shade1.dispose();
        delete this;
    },

    'show_div' : function() {
        if(false == this.inside) return;

        if(!$chk(this.div)) {
            this.div = new Element('div', {
                'class' : 'imagezoom'
            }).inject(document.body);
            var c = this.img.getComputedSize();
            var p = this.img.getPosition();

            if(true == this.inner) {
                this.div.setStyles({
                    'left' : p.x,
                    'top' : p.y,
                    'width' : c.width + c['padding-left'] + c['padding-right'] + ( Browser.Engine.gecko ? c['border-left-width'] : 0 ),
                    'height' : c.height + c['padding-top'] + c['padding-bottom']
                });
                this.div._size = this.div.getSize();
                this.div._pos = this.div.getPosition();
            } else {
                this.div.setStyles( ImageZoom.sidebox_size(this.img, this.div, this.divimg) );
                this.shade1 = new Element('div', {
                    'class' : 'imagezoom_shade'
                })
                    .inject( document.body );
                this.shade1.setStyles({
                    'left' : p.x + ( Browser.Engine.gecko ? c['border-left-width'] : 0 ),
                    'top' : p.y,
                    'width' : c.width,
                    'height' : c.height
                });
                this.shade1._size = this.img.getSize();
                this.shade1._pos = this.img.getPosition();
                this.shade1._class = this;
                this.shade1.set('tween', { duration: 300 }).fade('hide');

                this.shade2 = new Element('div', {
                    'class' : 'imagezoom_transbox',
                    'styles' : {
                        'background-image' : 'url("' + this.img.get('src') + '")',
                        'width' : 0,
                        'height' : 0
                    }
                })
                    .inject( this.shade1 );
            }

            this[this.inner ? 'div' : 'shade1']
                .removeEvents('mouseleave')
                .removeEvents('mousemove')
                .removeEvents('click')
                .addEvent('click', function(e) {
                    this._class.hide_div();
                    var a = this._class.img.getParent();
                    if('a' == a.get('tag') && $chk(a._milkbox)) {
                        a._milkbox.showGallery({ gallery : 'gall' });
                    } else {
                        this._class.img.fireEvent('click', e);
                    }
                })
                .addEvent('mouseleave', function(e) {
                    this._class.hide_div();
                })
                .addEvent('mousemove', function(e) {
                    var xfactor = ImageZoom.transform( ( e.page.x - this._pos.x ) / this._size.x, this._class.inner );
                    var yfactor = ImageZoom.transform( ( e.page.y - this._pos.y ) / this._size.y, this._class.inner );
                    var s = this._class.divimg.getSize();

                    var x = -Math.round(xfactor * (s.x - this._size.x));
                    var y = -Math.round(yfactor * (s.y - this._size.y));

                    if(false == this._class.mmfx)
                        this._class.divimg.setStyles({ 'left' : x, 'top' : y });
                    else
                        this._class.divimg.morph({ 'left' : x, 'top' : y });

                    if($chk(this._class.shade2)) {
                        if(0 == this._class.shade2.getSize().x) {
                            this._class.shade2.setStyles({
                                'width' : Math.round( ( this._class.div.getSize().x / this._class.divimg.getSize().x ) * this._size.x ) ,
                                'height' : Math.round( ( this._class.div.getSize().y / this._class.divimg.getSize().y ) * this._size.y )
                            });
                            this._class.shade2._size = this._class.shade2.getSize();
                        }

                        x = Math.round(xfactor * (this._size.x - this._class.shade2._size.x));
                        y = Math.round(yfactor * (this._size.y - this._class.shade2._size.y));

                        this._class.shade2.setStyles({
                            'left' : x,
                            'top' : y,
                            'background-position' : (-x) + 'px ' + (-y) + 'px'
                        });
                    }
                });

            this.div._class = this;
            this.div.set('tween', { duration: 300 }).fade('hide');

            this.divimg = new Element('img', {
                'src' : this.src,
                'styles' : {
                    'position' : 'relative',
                    'left' : 0,
                    'top' : 0
                }
            }).inject(this.div).set('morph', {
                'duration' : 100
                //'transition' : 'linear:in:out'
            });

            if($chk(this.startpos) && $chk(this.startpos.x))
                this[this.inner ? 'div' : 'shade1'].fireEvent('mousemove', { 'page' : this.startpos });
        }

        if(true == this.infx) {
            this.div.fade('in');
            if($chk(this.shade1))
                this.shade1.fade(0.75);
        } else {
            this.div.fade('show');
            if($chk(this.shade1)) {
                this.shade1.fade('show');
                this.shade1.setOpacity(0.75);
            }
        }
    },

    'hide_div' : function() {
        this.inside = false;
        var fadetype = ( this.infx ? 'out' : 'hide' );
        this.div.fade(fadetype);
        if($chk(this.shade1))
            this.shade1.fade(fadetype);
    }

});

ImageZoom.transform = function(x, inner) {
    if(false == inner) return x;
    if(x >= 1) return 1;
    if(x <= 0) return 0;
    if(x < 0.5) return 2 * x * x; // (2x)^2 / x
    return Math.sqrt(x - 0.5) + 0.5;
}

ImageZoom.init = function() {
    $$('img.innerzoom').each(function(img) { img._zoom = new ImageZoom(img, true); });
    $$('img.outerzoom').each(function(img) { img._zoom = new ImageZoom(img, false); });
}

ImageZoom.sidebox_size = function(oimg, sidediv, divimg) {
    var c = oimg.getComputedSize();
    var p = oimg.getPosition();
    return {
        'left' : p.x + c.width + 10,
        'top' : p.y,
        'width' : c.width,
        'height' : c.height
    };
}





var SkinPreviewBox = new Class({
    'initialize' : function() {
        var div = new Element('div', {
            'class' : 'skinpreview',
            'events' : {
                'mouseenter' : function(e) { $(this).fade(0.8); },
                'mouseleave' : function(e) { $(this).fade(0.3); }
            }
        }).inject(document.body).setOpacity(0.3);

        var a = new Element('a', {
            'class' : 'spanhover',
            'events' : {
                'click' : function(e) {
                    new Event(e).stop();
                    Cookie.dispose('skinpreview', { 'path' : '/' + base_href.replace(/(^\/|\/$)/g, '') });
                    window.location.href = window.location.href;
                }
            }
        }).inject(div);

        new Element('img', {
            'src' : base_href + 'public/images/1px.gif'
        }).inject(a);

        new Element('span', {
            'text' : 'Zamknij podgląd stylu'
        }).inject(a);

        new Drag.Move(div);
    }
});


var ShoperBasket = {
    'shipping_id' : 0,

    'force_rows' : false,

    'currency' : {
        'dec_point' : ',',
        'thousands_sep' : ' ',
        'prefix' : '',
        'postfix' : ''
    },

    'containers' : {
        'step1' : false,
        'step2' : false
    },

    'initialize' : function(step) {
        if($chk(window.CurrencyMap))
            this.parse_currency(CurrencyMap);

        this['step_' + step]();
    },

    'parse_currency' : function(cmap) {
        this.currency.prefix = cmap.replace(/^(.*)1.*/, '$1');
        this.currency.postfix = cmap.replace(/.*6(.*)$/, '$1');
        this.currency.dec_point = cmap.replace(/.*4(.*)5.*/, '$1');
        this.currency.thousands_sep = cmap.replace(/.*1(.*)2.*/, '$1');
    },

    'format_currency' : function(x) {
        return this.currency.prefix + x.numberFormat(2, this.currency.dec_point, this.currency.thousands_sep) + this.currency.postfix;
    },

    'calculate' : function() {
        var td = $$('#box_basketlist table.productlist tfoot tr.sum td.value').pop();
        if($chk(td) && $chk(ShippingValue) && $chk(SumNoShipping) && this.shipping_id > 0) {
            var s = SumNoShipping + ShippingValue['s' + this.shipping_id];
            td.set('text', this.format_currency(s));
        }
    },

    'step_1_show_delivery' : function() {
        this.step_1_hide_payment();
        this.containers.step1.getElements('tr.delivery').removeClass('none');
        //this.containers.step1.getElement('tr.deliveryhead em.fold a').addClass('none');
    },

    'step_1_show_payment' : function() {
        this.step_1_hide_delivery();
        this.containers.step1.getElements('tr.payment').filter(function(el) {
            return !el.getElement('input[type=radio]').disabled;
        }).removeClass('none');
        //this.containers.step1.getElement('tr.paymenthead em.fold a').addClass('none');
    },

    'step_1_hide_delivery' : function() {
        if(false == this.force_rows) return;
        this.containers.step1.getElements('tr.delivery').addClass('none');
        this.containers.step1.getElements('tr.deliveryhead em.fold a').removeClass('none');
    },

    'step_1_hide_payment' : function() {
        if(false == this.force_rows) return;
        this.containers.step1.getElements('tr.payment').addClass('none');
        this.containers.step1.getElements('tr.paymenthead em.fold a').removeClass('none');
    },

    'step_1' : function() {
        this.containers.step1 = $$('#box_basketlist table.productlist tfoot').pop();
        if(!$chk(this.containers.step1)) return;

        var i = this.containers.step1.getParent().getElements('input[type=text]').shift();
        if($chk(i)) i.focus();

        var f = this.containers.step1.getElement('tr.deliveryhead em.fold a');
        if($chk(f)) {
            f.removeClass('none');
            if(f.getSize().x > 0) {
                this.force_rows = true;

                this.containers.step1.getElements('tr.deliveryhead em.fold a').addEvent('click', function(e) {
                    if(e) new Event(e).stop();
                    this.blur();
                    if(true == this._class._folden_delivery) {
                        this._class.step_1_hide_payment();
                        this._class._folden_payment = true;
                        this._class.step_1_show_delivery();
                    } else
                        this._class.step_1_hide_delivery();
                    this._class._folden_delivery = ! this._class._folden_delivery;
                }).each(function(el) { el._class = this }, this);

                this.containers.step1.getElements('tr.paymenthead em.fold a').addEvent('click', function(e) {
                    if(e) new Event(e).stop();
                    this.blur();
                    if(true == this._class._folden_payment) {
                        this._class.step_1_show_payment();
                        this._class.step_1_hide_delivery();
                        this._class._folden_delivery = true;
                    } else
                        this._class.step_1_hide_payment();
                    this._class._folden_payment = ! this._class._folden_payment;
                }).each(function(el) { el._class = this }, this);

                this.step_1_hide_delivery();
                this.step_1_hide_payment();
                this._folden_payment = true;
                this._folden_delivery = true;
            }
        }

        this.containers.step1.getElements('tr.payment input[type=radio]').each(function(el) {
            el.addEvent('change', function(e) {
                this._class.containers.step1.getElements('tr.payment').removeClass('selected');
                tr = $(this).getParent();
                while('tr' != tr.get('tag'))
                    tr = tr.getParent();
                tr.addClass('selected');

                this._class.containers.step1.getElement('tr.paymenthead td.desc em.color').set('html',
                    tr.getElements('td.name label').get('html')
                );

                this._class.step_1_hide_payment();
                this._class._folden_payment = true;
                PopupMapper();
            })._class = this;
            if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
            if(true == el.checked)
                el.fireEvent('change', null);
        }, this);

        this.containers.step1.getElements('tr.delivery input[type=radio]').each(function(el) {
            el.addEvent('change', function(e) {
                this._class.shipping_id = $(this).get('value').toInt();

                var tr = $(this).getParent();
                while('tr' != tr.get('tag'))
                    tr = tr.getParent();
                tr.getParent().getChildren('tr.delivery').removeClass('selected');
                tr.addClass('selected');

                this._class.containers.step1.getElement('tr.deliveryhead td.desc em.color').set('html',
                    tr.getElements('td.name label').get('html')
                );

                this._class.containers.step1.getElement('tr.deliveryhead td.value em.color').set('text',
                    tr.getElements('td.value').get('text')
                );

                var a = Shipping2Payment['s' + $(this).get('value')];
                var trs = this._class.containers.step1.getElements('tr.payment');
                var inputs = [];
                var first = false;
                trs.each(function(tr) {
                    var input = tr.getElements('td.name input[type=radio]').pop();
                    if(! $chk(input)) return;

                    if(a.contains( input.get('value').toInt() )) {
                        inputs.push(input);
                        input.disabled = input.readonly = false;
                        tr.removeClass('none');

                        if(false == first) {
                            tr.addClass('first');
                            first = true;
                        } else
                            tr.removeClass('first');
                    } else {
                        input.disabled = input.readonly = true;
                        input.checked = false;
                        tr.addClass('none').removeClass('first');
                    }
                }, this);

                if(inputs.length > 0) {
                    var checked = false;
                    for(var x = 0; x < inputs.length; ++x)
                        if(true == inputs[x].checked)
                            checked = true;
                    if(false == checked) {
                        inputs[0].checked = true;
                        inputs[0].fireEvent('change', null);
                    }
                }

                this._class.calculate();
                this._class.step_1_hide_delivery();
                this._class._folden_delivery = true;
            })._class = this;
            if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
            if(true == el.checked)
                el.fireEvent('change', null);
        }, this);


        this.step_1_hide_delivery();
        this.step_1_hide_payment();
    },

    'step_2' : function() {
        this.containers.step2 = $('box_basketaddress');
        if(!$chk(this.containers.step2)) return;

        var i = this.containers.step2.getElements('input[type=text]').shift();
        if($chk(i)) i.focus();

        var f = (function myself(_form, _sub) {
            myself._form = _form;
            myself._sub = _sub;
            var trs = myself._form.getElements('tr.different');
            var i = myself._form.getElement('input[name=different]');
            if($chk(i)) {
                if(i.checked)
                    trs.removeClass('none');
                else
                    trs.addClass('none');
            }

            var r = myself._form.getElementById('address_type2');
            if($chk(r)) {
                myself._sub(myself._form.getElement('input[name=coname]'), r.checked);
                myself._sub(myself._form.getElement('input[name=nip]'), r.checked);
                myself._sub(myself._form.getElement('input[name=coname2]'), i.checked); //another address
                //myself._sub(myself._form.getElement('input[name=coname2]'), r.checked && i.checked); // another address & company
                myself._sub(myself._form.getElement('input[name=nip2]'), i.checked); //another address
                //myself._sub(myself._form.getElement('input[name=nip2]'), r.checked && i.checked); // another address & company
            }
        }).pass([
            this.containers.step2.getElements('form').pop(),
            function(el, show) {
                if($chk(el)) {
                    var p = $(el);
                    while('tr' != p.get('tag')) p = p.getParent();
                    if(true == show)
                        p.removeClass('none');
                    else
                        p.addClass('none');
                }
            }
        ], this);
        f();

        this.containers.step2.getElements('input[type=radio][name^=address_type]').each(function(el) {
            el._change = f;
            el.addEvent('change', function(e) {
                this._change();
            })
            if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
        });

        this.containers.step2.getElements('input[type=checkbox][name=different]').each(function(el) {
            el._change = f;
            el.addEvent('change', function(e) {
                this._change();
            })
            if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
        });
        this.containers.step2.getElements('*[type=submit][name^=address_submit]').addClass('none');

        this.containers.step2.getElements('select[name^=address]').each(function(el) {
            el.addEvent('change', function(e) {
                var val = this.get('value').toInt();
                if(val > 0) {
                    var req = new Request.JSON({
                        'url' : base_href + 'panel/getaddress/id/' + val,
                        'secure' : true,
                        'async' : false,
                        'noCache' : true,
                        'method' : 'get',
                        'onFailure' : function(xhr) {
                            alert(Lang.basket.address_request_error);
                        },
                        'onComplete' : function(json) {
                            if($chk(json) && $chk(json.name)) {
                                var n = this._select.get('name').match(/2$/) ? '2' : '';
                                for(var k in json)
                                    this._class.containers.step2.getElements('input[name=' + k + n + ']').set('value', json[k]);

                                if('' == n) {
                                    i = ('' == json.nip && '' == json.coname) ? $('address_type1') : $('address_type2');
                                    if($chk(i))
                                        i.set('checked', true).fireEvent('change', null);
                                }
                            } else
                                alert(Lang.common.product_vote_alert);
                        }
                    });
                    req._select = this;
                    req._class = this._class;
                    req.send();
                } else {
                    var keys = [ 'name','surname','phone','coname','nip','street','zip','city','country' ];
                    var n = this.get('name').match(/2$/) ? '2' : '';
                    for(var x = 0; x < keys.length; ++x)
                        this._class.containers.step2.getElements('input[name=' + keys[x] + n + ']').set('value', '');
                }
            });
            if(IE) el.addEvent('click', function(e) { this.fireEvent('change', e); });
            el._class = this;
        }, this);
    }
}


var StockDownloaderClass = new Class({
    'sid' : null,
    'stock' : null,

    'initialize' : function(sid) {
        this.sid = sid;
        this.get();
    },

    'get' : function() {
    	$$('.addtobasket').hide();
        var request = new Request.JSON({
            'url' : base_href + 'product/getstock/stock/' + this.sid + '/imgwidth/' + OptionImgWidth,
            'secure' : true,
            'async' : true,
            'noCache' : true,
            'method' : 'get',
            'onFailure' : function(xhr) {
                alert(Lang.common.product_stock_download_error);
            },
            'onComplete' : function(json) {
                if('object' == $type(json) && $defined(json.sid) ) {
                    this._class.stock = json;
                    this._class.display();
                    $$('.addtobasket').show();
                } else {
                    alert(Lang.common.product_stock_download_error);
                }
                
            }
        });

        request._class = this;
        request.send();
    },

    'display' : function() {
        if($chk(this.stock) && $chk(this.stock.sid) && OptionCurrentStock != this.stock.sid) {
            OptionCurrentStock = this.stock.sid;

            $$('#box_productfull form.basket input[name^=stock_id]').set('value', this.stock.sid);

            if(false != this.stock.photo)
                $$('#box_productfull td.productimg img.productimg').set('src', this.stock.photo);

            var atd = $$('#box_productfull td.availability dd.availability').pop();
            if($chk(atd)) {
                atd.set('text', ' ' + this.stock.availability);
                if(false != this.stock.availability_photo)
                    new Element('img', {
                        'src' : this.stock.availability_photo,
                        'alt' : this.stock.availability
                    }).inject(atd, 'top');
            }

            var dtd = $$('#box_productfull td.availability dd.delivery').pop();
            var dtr = $$('#box_productfull td.availability dt.delivery').pop();
            if($chk(dtd)) {
                if(false == this.stock.delivery) {
                    dtd.addClass('none');
                    dtr.addClass('none');
                } else {
                    dtd.removeClass('none').set('text', ' ' + this.stock.delivery);
                    dtr.removeClass('none');
                }
            }

            var pdiv = $$('#box_productfull table.maininfo div.price').pop();
            if($chk(pdiv)) {
                if(false == this.stock.special_offer) {
                    pdiv.getElements('em').removeClass('color').set('text', this.stock.price);
                    //pdiv.getElements('del').addClass('none').set('text', '');
                } else {
                    pdiv.getElements('em').addClass('color').set('text', this.stock.special_offer);
                    pdiv.getElements('del').removeClass('none').set('text', this.stock.price);
                }
            }

            var ndiv = $$('#box_productfull table.maininfo div.nettoprice').pop();
            if($chk(ndiv)) {
                if(false == this.stock.net_special_offer)
                    ndiv.getElements('em').set('text', this.stock.net_price);
                else
                    ndiv.getElements('em').set('text', this.stock.net_special_offer);
            }

            $$('#box_productfull .additionalinfo a.addtofav').each(function(el) {
                el.set('href', el.get('href').replace(/\/\w+$/, '/') + this.stock.sid);
            }, this);

            if(true == this.stock.can_buy)
                $$('#box_productfull form.basket fieldset').removeClass('none');
            else
                $$('#box_productfull form.basket fieldset').addClass('none');

            $$('#box_productfull form.basket span.unit').set('text', this.stock.unit);
        }
    }
});

var StockDownloader = {
    'downloaders' : [ ],

    'get' : function(sid) {
        if($chk(this.downloaders[sid]))
            this.downloaders[sid].display();
        else if(OptionCurrentStock != sid)
            this.downloaders[sid] = new StockDownloaderClass(sid);
    }
}

var ProductVoter = new Class({
    'span' : false,
    'stars' : [ ],
    'votecount' : false,

    'mouseenter' : function(score) {
        var n = 1;
        this.stars.each(function(el) {
            el.removeClass('star0').removeClass('star0-5').removeClass('star1').addClass('star' + (n++ <= score ? 1 : 0));
        });
    },

    'mouseleave' : function() {
        this.stars.each(function(el) {
            el.set('class', el._initial_class);
        });
    },

    'vote' : function(score) {
        var id = this.span.get('id').replace(/[^0-9]/g, '').toInt();
        if(id > 0 && score > 0) {

            var req = new Request({
                'url' : base_href + 'product/vote/prod/' + id + '/vote/' + score,
                'secure' : true,
                'async' : false,
                'noCache' : true,
                'method' : 'get',
                'onFailure' : function(xhr) {
                    alert(Lang.common.product_vote_alert);
                },
                'onComplete' : function(txt) {
                    if('1' == txt) {
                        this._class.span.removeEvents('mouseleave');
                        this._class.stars.setStyle('cursor', 'default').removeEvents('mouseenter').removeEvents('click');
                        this._class.votecount.set('text', this._class.votecount.get('text').toInt() + 1);
                    } else
                        alert(Lang.common.product_vote_alert);
                }
            });
            req._class = this;
            req.send();
        }
    },

    'initialize' : function(span) {
        this.span = span;
        span._class = this;

        var stars = span.getElements('img');
        for(var x = 0; x < stars.length; ++x) {
            this.stars.push(stars[x]);
            stars[x]._class = this;
            stars[x]._initial_class = stars[x].get('class');
        }

        this.stars = $$(this.stars);

        var vc = span.getParent().getElements('span.votecount');
        if(1 == vc.length) {
            this.votecount = vc[0];
            vc[0]._class = this;
        }

        if(Lang.voting.vote_n && Lang.voting.vote_n.length > 0)
            new Tips(stars, {
                'className' : 'tool-tip'
            });

        stars.each(function(el) {
            el._value = el.get('alt').toInt();
            el.set('alt', '');
            el.addEvent('mouseenter', function(e) {
                this._class.mouseenter(this._value);
            });
            el.addEvent('click', function(e) {
                this._class.vote(this._value);
            });
            el.setStyle('cursor', 'pointer');
            el.store('tip:className');
            el.store('tip:title', '');
            el.store('tip:text', Lang.voting.vote_n.substitute({ 'score' : el._value }) );
        });

        span.addEvent('mouseleave', function(e) {
            this._class.mouseleave();
        });
    }
});

var PopupMapper = function() {
    $$('.popupsmall').removeEvents('click').addEvent('click', function(e) {
        new Event(e).stop();
        $(this).blur();
        window.open(this.href, '', 'width=630,height=500,directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no');
    });

    $$('.popup').removeEvents('click').addEvent('click', function(e) {
        new Event(e).stop();
        $(this).blur();
        window.open(this.href);
    });
}


var ImagePreloader = new Class({
    'initialize' : function(list) {
        if('array' == $type(list) && list.length > 0)
            for(var x = 0; x < list.length; ++x) {
                ( function(img) {
                    new Asset.image( img );
                } ).delay(50 * x, this, skin_href + 'images/' + list[x]);
            }
    }
});


var CssLoader = new Class({
    'initialize' : function(list) {
        if('array' == $type(list) && list.length > 0)
            list.each(function(css) {
                new Asset.css(css);
                console.log(css);
            });
    }
});

var JsLoader = new Class({
    'initialize' : function(jslist, onload) {
        if('string' == $type(jslist)) jslist = [ jslist ];
        if($chk(jslist) && 'array' == $type(jslist) && jslist.length > 0) {
            var me = {
                'onload' : function() { },
                'loaded' : 0,
                'limit' : jslist.length
            };

            if($chk(onload) && 'function' == $type(onload)) {
                me._onload = onload;

                me.onload = (function() {
                    this.loaded++;
                    if(this.limit == this.loaded)
                        this._onload();
                }).bind(me);
            }

            jslist.each(function(js) {
                Asset.javascript(js, {
                    'onload' : (function() {
                        this.onload();
                    }).bind(this)
                });
            }, me);
        }
    }
});

var HrefParser = {
    'check' : function() {
        if(false == base_href || false == skin_href)
            HrefParser.load();
    },

    'load' : function() {
        $$('link[rel=home]').each(function(el) {
            if('string' == $type(el.get('href')))
                base_href = (el.get('href') + '/').replace(/\/\//g, '/');
        });

        $$('link[rel=skin]').each(function(el) {
            if('string' == $type(el.get('href')))
                skin_href = (el.get('href') + '/').replace(/\/\//g, '/');
        });
    }
}

