var SectionJS = {
    lockMagicPanel: -1,
    oldIE: ((jQuery.browser.msie) && (jQuery.browser.version < 7)),

    equalizeRows: function() {
        $("#mainpanel>table>tbody>tr").each(function () {
            // equalize heights of items
            var maxHeight = 0;
            var children = $(this).find("td>form table.eq");
            for (i = 0; i < children.length; i++) {
                var wys = children[i].clientHeight;
                if (wys > maxHeight) {
                    maxHeight = wys;
                };
            }
            $(this).find("td>form table.eq").height(maxHeight+2);
        });
    },

    getScrollDest: function(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();
        var elemTop = elem.closest('tr').offset().top + elem.closest('tr').height() - 45;
        var elemBottom = elemTop + $(elem).height();
        if (elemBottom >= docViewBottom) {
            var form = elem.closest('form');
            return elemBottom - $(window).height() + 2;
        };
        if ((elemTop-10) <= docViewTop) {
            return elemTop - 7;
        }
        return 0;
    },

    showMagicBasket: function(elem) {
        // over
        elem = $(elem).parent().parent().find(".magic_price_box");
        if (elem.size() > 0) {
            elem.stop();
            if (this.getScrollDest(elem) != 0) {
                var destTop = this.getScrollDest(elem);
                $(window).scrollTo({top: destTop+'px', left: $(window).scrollLeft()}, 400);
            };
            if (elem.css('display') == 'none') {
                // initial show
                elem.css({
                    'display': 'block',
                    'opacity': 0.01
                });
            };
            var destOpac = ((this.oldIE) ? 0.8 : 0.9);
            elem.animate({opacity: destOpac}, 500, 'swing');
        };
    },

    hideMagicBasket: function(elem) {
        // out
        elem = $(elem).parent().parent().find(".magic_price_box");
        elem.stop();
        elem.fadeOut({opacity: 0}, 500, 'swing', function() {elem.hide();});
    },

    getItemCount: function(magicBasket) {
        var quant = parseInt(magicBasket.find("input[type=text]").val());
        if (isNaN(quant)) quant = 0;
        return quant;
    },

    recalcItem: function(magicBasket) {
        var priceInput = magicBasket.find("input[name=price]");
        if (priceInput.size() > 0) {
            var priceAsis = priceInput.val().replace(',', '.').replace(/[^,.0-9]/g, '');
            var price = parseFloat(priceAsIs);
            if (isNaN(price)) price = 0;
            var quant = this.getItemCount(magicBasket);
            var cost = Math.round(price*quant*100);
            var priceContent = magicBasket.find('.product_price').html();

            var currencies = priceContent.replace(/[0-9]+<sup>[0-9]{2}<\/sup>/gi, '|').split('|');
            magicBasket.find(".magic_total_price").html(currencies[0]+' '+parseInt(cost/100)+'<sup>'+((cost%100 < 10)?'0':'')+(cost%100)+'</sup> '+currencies[1]);
        }
    },

    incItem: function(magicBasket) {
        var input = magicBasket.find("input[type=text]");
        var newValue = 1+this.getItemCount(magicBasket);
        input.attr('value', newValue);
        try {
            this.recalcItem(magicBasket);
        }
        catch (err) {
        }
    },

    decItem: function(magicBasket) {
        var input = magicBasket.find("input[type=text]");
        var newValue = Math.max(0, this.getItemCount(magicBasket)-1);
        input.attr('value', newValue);
        try {
            this.recalcItem(magicBasket);
        }
        catch (err) {
        }
    },

    setBasketCount: function(basket, count, fancy) {
        var cnt = basket.parent().find('.basket_count');
        count = parseInt(count);
        if ((cnt.size() == 0) && (count > 0)) {
            basket.before('<div class="basket_count">'+count+'</div>');
            basket.parent().find(".basket_count").click( function() {
                var row = $(this).closest(".basket_row");
                row.find('.addItem').trigger('click');
                row.find('.buy').trigger('click');
                return false;
            });

            if (!fancy) {
                basket.parent().parent().find('.basket_count').hover(
                    function() {
                        SectionJS.showMagicBasket(this);
                    },
                    function() {
                    }).mousemove(function(e) {
                        e.stopPropagation();
                    });
            };
        };
        if ((count == 0) && (cnt.size() > 0)) {
            cnt.fadeOut();
            cnt.remove();
        };
        if (count > 0) {
            cnt.animate({
                opacity: 0.1
            }, 400, function() {
                cnt.html(count);
                cnt.animate({opacity: 1});
            });
        }
        if (fancy) {
            basket.attr('src', (count == 0) ? '/_gfx/basket_black.png' : '/_gfx/basket_black_b.png');
            cnt = basket.parent().find('.basket_count');
            var mr = (cnt.size() == 0) ? 0 : cnt.innerWidth();
            /* does something very, very wrong:

            basket.parent().find('.symbol').animate({
                'margin-right': mr
            }); */
        }
        else {
            basket.attr('src', (count == 0) ? '/_gfx/basket.png' : '/_gfx/basket_b.png');
        }
        if (this.oldIE) {
            basket.ifixpng('scale');
        }
    },

    buyClick: function(event, element) {
        var magicBasket = $(this).parent().parent();
        if (element) {
            magicBasket = jQuery(element).parent().parent();
        }
        var theBasketImg = magicBasket.find('.another_basket');
        var inFancy = (theBasketImg.size() > 0);
        var pid = parseInt(magicBasket.find('input[name=pid]').val());
        var input = magicBasket.find("input[name=quantity]");
        var count = parseInt(input.attr('value'));
        var d = new Date();
        var data = {
            'class': 'Basket',
            'method': 'updateBasket',
            'pid' : pid,
            'count' : count,
            'timestamp': d.getTime()
        };
        try {
            input.animate({
                backgroundColor: ((inFancy) ? '#ffff00' : '#ccaa44')
            }, 60);
            input.animate({
                backgroundColor: ((inFancy) ? '#eeeeee' : '#660000')
            }, 1200);
        }
        catch (e) {}; // yup, there. I did it. Sue me.

        $.getJSON('/_json/',
                  data,
                  function(json) {
                      var totalPrice = $('.basket_info .basket_sum');
                      if (totalPrice.size() > 0) {
                         totalPrice.html(json.total_value);
                      };
                      var totalBasket = $('.basket_info img');
                      SectionJS.setBasketCount(totalBasket, json.counts.total);
                      // would have to wait at least 400ms before reading the new basket count...
                      if (BasketThing) {
                          // BasketThing.flashMessage('Zmienił się stan koszyka!');
                          BasketThing.basketCount = json.counts.total;
                          BasketThing.setDefaultContent();
                          BasketThing.showTheThing();
                          setTimeout("BasketThing.hideTheThing()", 3000);
                      };

                      if (inFancy) {
                          for (var pid in json.added) {
                              // should execute only once but I had
                              // no better idea, where to get the pid from
                              SectionJS.setBasketCount($('#gt_fancy_content .another_basket'), json.added[pid], true);
                          }
                      };
                      for(var pid in json.counts) {
                          // FFS.
                          var box = $('#bookmarkbox-'+pid+' .basket_to_basket ,#product_box'+pid+' .magic_price_box, #topten_box'+pid+' .basket_to_basket_submit, #basket_row'+pid+' td').parent();
                          if (box.size() > 0) {
                              var img = box.find('.basket_to_basket_submit');
                              img.each(function() {
                                  SectionJS.setBasketCount($(this), json.counts[pid]);
                              });
                              box.find('.quantity').val(json.counts[pid]).trigger('change');
                              var basketViewQuant = box.find('input[name=quantity['+pid+']]');
                              if (basketViewQuant.size() > 0) {
                                  basketViewQuant.val(json.counts[pid]);
                                  basketView.recalc(basketViewQuant.closest('tr'));
                              };
                              var btn = box.find('.buy');
                              btn.attr('src', '/_gfx/circle.png');
                              if (SectionJS.oldIE) {
                                  btn.ifixpng('scale');
                              };
                              btn.css({
                                  'padding': 0
                              });
                              box.find('.magic_price_box').css({
                                  'cursor': 'default'
                              });
                              btn.click(SectionJS.buyClick);
                              SectionJS.lockMagicPanel = -1;
                          }
                      }
                  });
        SectionJS.lockMagicPanel = pid;

        var buy = magicBasket.find('.buy');
        buy.attr('src', '/_gfx/basket_loading.gif');
        buy.css({
            'padding': '3.5px'
        });
        buy.closest('.magic_price_box').css({
            'cursor': 'wait'
        });
        buy.click(SectionJS.buyClick);
        SectionJS.recalcItem(magicBasket);
    },

    makeMagicBaskets: function() {
        var magicBasketForm = '<span class="property_name quantity_text">'+_('Number of packages')+':</span> <input type="text" class="quantity" name="quantity" size="10" value="0" /><span class="plusminus"><a href="#" class="addItem">+</a><a href="#" class="remItem">-</a></span><br /><span class="property_name magic_total">'+_('Total')+':</span><span class="magic_total_price"></span> <a href="" onclick="return false"><img src="/_gfx/circle.png" alt="ok" class="buy" align="right" /></a>';
        $("div.basket_row").each(function () {

            var image = $(this).find("input[type=image]");
            var img = new Image();
            img.src = image.attr('src');
            img.className = image.attr('class');
            $(image).before(img).remove();

            var dest = $(this).parent().find(".magic_price_box");
            dest.html($(this).html());
            dest.append(magicBasketForm);
            SectionJS.recalcItem(dest);
            dest.find('.addItem').click(
                function() {
                    SectionJS.incItem($(this).parent().parent());
                    return false;
            });
            dest.find('.remItem').click(
                function() {
                    SectionJS.decItem($(this).parent().parent());
                    return false;
            });
            dest.find('.quantity').change(function() {
                SectionJS.recalcItem($(this).parent().parent());
            }).keyup(
                function() {
                    SectionJS.recalcItem($(this).parent().parent());
            }).val((dest.find('.basket_count').size() > 0) ? parseInt(dest.find('.basket_count').text()) : 0).trigger('change');
            dest.find('img.buy').click(SectionJS.buyClick);
            dest.find("img.basket_to_basket_submit").click( function() {
                var row = $(this).closest(".magic_price_box");
                row.find('.addItem').trigger('click');
                row.find('.buy').trigger('click');
                return false;
            });
            dest.parent().find('.basket_count, .basket_count a').click(function() {
                var row = $(this).parent().parent().parent();
                row.find('.addItem').trigger('click');
                row.find('.buy').trigger('click');
                return false;
            });
        });
        $("div.basket_row > .basket_to_basket_submit, .basket_count").hover(
            function() {
                SectionJS.showMagicBasket(this);
            },
            function() {}
        );
        $(".magic_price_box").hover(
            function() {
                //SectionJSshowMagicBasket(this);
            },
            function() {
                var pid = $(this).parent().find('input[name="pid"]');
                pid = parseInt(pid.val());
                if (SectionJS.lockMagicPanel != pid) {
                    SectionJS.hideMagicBasket(this);
                }
            }
        );
        $(".magic_price_box input[type=text]").focus(function() {
            SectionJS.lockMagicPanel = parseInt($(this).parent().find('input[name=pid]').val());
            SectionJS.hideMagicBasket($("*[id^=product_box]").filter("[id!=product_box"+SectionJS.lockMagicPanel+"]").find(".magic_price_box"));
        });
        $(".magic_price_box input[type=text]").blur(function() {
            //SectionJS.hideMagicBasket($("#product_box"+SectionJS.lockMagicPanel+" .magic_price_box"));
            SectionJS.lockMagicPanel = -1;
        });

        $(".magic_price_box, .basket_to_basket_submit, .basket_count").mousemove(function(e) {
            e.stopPropagation();
        }).click(function(e) {
            e.stopPropagation();
        });

/*
        $(document).mousemove(function() {
            $(".magic_price_box").trigger('mouseout');
        }).click(function() {
            $(".magic_price_box").trigger('mouseout');
        });
*/
    }
}


