function in_array(needle, haystack) {
    for (hay in haystack) {
        if (haystack[hay] == needle) {
            return true;
        }
    }
    return false;
}

function BasketViewJS() {

    var that=this;
    var _products_total_price = 0.0;
    var _price_after_discount = 0.0;

    var _shipmentCost = {
        'kurier' : {
            'mtransfer' : 20,
            'przelew' : 20,
            'wysylka' : 27,
            'zagiel': 20
        },
        'paczka_pri' : {
            'mtransfer' : 9,
            'przelew' : 9,
            'wysylka' : 15,
            'zagiel': 9
        },
        'paczka_eko' : {
            'mtransfer' : 8,
            'przelew' : 8,
            'wysylka' : 12,
            'zagiel': 8
        },
        'pickup' : {
            'mtransfer': 0,
            'przelew': 0,
            'wysylka': 0,
            'zagiel': 0
        }
    }; // only defaults, in case JSON is late

    this.getShipmentCosts = function() {
        var data = {
            'class': 'Basket',
            'method': 'currentShipmentCost'
        };
        $.getJSON('/_json/', data, function(json) {
            var costs = json.shipmentCosts;
            for (type in costs) {
                for (payment in costs[type]) {
                    _shipmentCost[type][payment] = parseFloat(costs[type][payment]);
                }
            }
        });
    };

    var _selects = ["mtransfer","przelew", "wysylka", "zagiel", "kurier", "paczka_pri", "paczka_eko"];

    this.blurTrigger = null,

    this.getquant = function(row) {
        var input = row.find("input[type=text]");
        var val = parseInt(input.val());
        val = (isNaN(val) || val < 0) ? 0 : val;
        input.val(val);
        return val;
    };

    this.modify = function(elem, delta) {
        var parent = $(elem).parent().parent();
        var input = parent.find("input[type=text]");
        var newValue = Math.max(0, that.getquant(parent) + delta);
        if (isNaN(newValue)) {
             input.val(0);
        }
        else {
             input.val(newValue);
        };
        input.trigger('blur');
    };

    this.recalc = function(row) {
        var price = parseFloat(row.find("input[name=price]").val().replace(',', '.').replace(/[^,.0-9]/g, ''));
        if (isNaN(price)) price = 0;
        var quant = that.getquant(row);
        var cost = Math.round(price*quant*100);
        if (isNaN(cost)) {
           cost = 0;
        };
        var priceContent = row.find('.basket_price').html();
        var currencies = priceContent.replace(/([0-9])\s([0-9])/gi,'$1$2').replace(/[0-9]+/gi, '|').split('|');
        row.find(".basket_price_total").html(currencies[0]+' '+parseInt(cost/100)+currencies[1]+((cost%100 < 10)?'0':'')+(cost%100)+currencies[2]);
        var table = row.parent();
        var total = 0.0;
        var totquant = 0;
        table.find("td.basket_price_total").each(
            function() {
                var text = $(this).text();
                var expr = /([0-9][0-9\s]*[,.][0-9]+)/gi;
                var tot = parseFloat(text.match(expr)[0].replace(',', '.').replace(' ',''));
                total += tot;
                totquant += that.getquant($(this).closest('tr'));
        });
        _price_after_discount = _products_total_price = total;
        var gr = total.toFixed(2).replace('.', currencies[1]);
        var text = currencies[0]
            +' '+gr+' '+currencies[2];
        $("span.total_total").html(text);
        table.find("span.total_quant").html(parseInt(totquant));

        var minprice = parseFloat($("input[name=minprice]").val());
        $(".below_min_price").css('display', (minprice>total) ? 'block' : 'none');
        $(".above_min_price").css('display', (minprice>total) ? 'none' : 'block');

        if (in_array('zagiel', _selects)) {
            var zagiel_href = jQuery('span#basket_zagiel a').attr('href');
            zagiel_href = zagiel_href.substr(0, zagiel_href.lastIndexOf('=')+1) + price_to_pay;
            jQuery('span#basket_zagiel a').attr('href', zagiel_href);
        }

    };

    this.minusClick = function(elem) {
       that.modify(elem, -1);
    };


    this.plusClick = function(elem) {
       that.modify(elem, +1);
    };

    this.refreshPriceToPay = function() {

        if (_price_after_discount>=99) {
            jQuery('#paczka_eko').attr('disabled',true);
            jQuery('#paczka_pri').attr('disabled',true);
        }
        else{
            jQuery('#paczka_eko').attr('disabled',false);
            jQuery('#paczka_pri').attr('disabled',false);
        }

        var paymentSelected = $('input[name=payment]:checked').val();
        var shipmentSelected = $('input[name=shipment]:checked').val();

        var price_to_pay = _price_after_discount;

        if ((paymentSelected!=undefined) && (shipmentSelected!=undefined) &&
            (_shipmentCost[shipmentSelected] != undefined) &&
            (_shipmentCost[shipmentSelected][paymentSelected] != undefined)) {

            if (_price_after_discount<399) {
                price_to_pay += _shipmentCost[shipmentSelected][paymentSelected];
                jQuery("#sending_price").html(
                    _shipmentCost[shipmentSelected][paymentSelected].toFixed(2).replace('.',',')+" zł");
            }
            else {
                jQuery("#sending_price").html('gratis');
            }
            jQuery("#shipment_cost_info").css("display","block");

        }
        else {
            jQuery("#shipment_cost_info").css("display","none");
        }
        jQuery("#final_price").html(price_to_pay.toFixed(2).replace('.',',')+" zł");

        if (in_array('zagiel', _selects)) {
            var zagiel_href = jQuery('span#basket_zagiel a').attr('href');
            zagiel_href = zagiel_href.substr(0, zagiel_href.lastIndexOf('=')+1) + price_to_pay;
            jQuery('span#basket_zagiel a').attr('href', zagiel_href);
        }


    };

/*
    this.giftsUpdate = function(json) {
        var newlist = '';
        if (json[0].length==0) {
            jQuery('#basket_promotion_no_gifts').css({display:'block'});
            jQuery('#basket_promotion_with_gifts').css({display:'none'});
        }
        else {
            jQuery("#basket_promotion_no_gifts").css("display","none");
            jQuery("#basket_promotion_with_gifts").css("display","block");
            if (json[0].length==1) {
                jQuery("#gifts_list_single_item").css("display","inline");
                jQuery("#gifts_list_many_items").css("display","none");
            }
            else {
                jQuery("#gifts_list_single_item").css("display","none");
                jQuery("#gifts_list_many_items").css("display","inline");
            }

            for (var id in json[0]) {
            newlist += "<li><b>"+json[0][id].name+"</b>" + ((json[0][id].items>1) ? " szt. "+json[0][id].items : "") +"</li>";
            }
            $("#gifts_list").html(newlist);
            $("#gifts_price").html(json[1]);
        };
        _price_after_discount = _products_total_price-parseFloat(json[1].replace(",",".").replace(/[^0-9\.]+/gi,""));
        jQuery("#price_after_discount").html(_price_after_discount.toFixed(2).replace('.',','));
        that.refreshPriceToPay();
    };

    this.triggerGiftsUpdate = function() {

        var data = {
            "class" : "PromotionGiftForPrice",
            "method" : "getList",
            "timestamp" : (new Date()).getTime()
        };
        $.getJSON("/_json/",
                  data,that.giftsUpdate);
    };
*/

    this.getShipmentCosts();
    var quants = $("tr.basket_row input[type=text]");
    if (quants.size() > 0) {
        quants.before("<a href='#' class='minus'>&ndash;</a>&nbsp;");
        quants.after("&nbsp;<a href='#' class='plus'>+</a>");
        $("input[name=recalc]").hide();
        $("tr.basket_row a.minus").each(
            function() {
                $(this).click(
                    function() {
                        that.minusClick(this);
                        return false;
                });
            });
        $("tr.basket_row a.plus").each(
            function() {
                $(this).click(
                    function() {
                        that.plusClick(this);
                        return false;
                    });
            });
        $("input[name^=quantity]").keyup(
            function() {
                that.recalc($(this).parent().parent());
            }
        ).blur(
            function() {
                var pid = $(this).closest('.item').find('input[name=pid]').val();
                var count = $(this).val();
                var d = new Date();
                var data = {
                    'class': 'Basket',
                    'method': 'updateBasket',
                    'pid' : pid,
                    'count' : count,
                    'timestamp': d.getTime()
                };
                $.getJSON('/_json/',
                          data,
                          function(json) {
                              var totalBasket = $('.basket_info img');
                              SectionJS.setBasketCount(totalBasket, json.counts.total);
                              for(var pid in json.counts) {
                                  var box = $('#basket_row'+pid);
                                  if (box.size() > 0) {
                                      that.recalc(box);
                                      //that.triggerGiftsUpdate();
                                  }
                              }
                          });
            });
        $("#make_an_order_submit").click(
            function(evt) {
                var isPaymentSelected = $('input[name=payment]:checked').val() != undefined;
                var isShipmentSelected = $('input[name=shipment]:checked').val() != undefined;
                if (!isPaymentSelected) {
                    alert("Proszę wybrać sposób płatności");
                    return false;
                }
                if (!isShipmentSelected) {
                    alert("Proszę wybrać metodę dostawy");
                    return false;
                }
                return true;
            });
        for (var key in _selects) {
            jQuery("#"+_selects[key]).click(that.refreshPriceToPay);
        }
//        _price_after_discount = parseFloat(jQuery("#price_after_discount").html());
        _price_after_discount = parseFloat(jQuery(".total_total").html().replace(/,/gi,"."));
        this.refreshPriceToPay();
    };
};

