var shipping_updater;
var shipping_updater_timeout;

function update_quantities_and_shipping(){
  shipping_updater = true;
  $('ul.shipping_methods > li .price').each(function(i, e){
    $(e).append('<img src="/images/grey-loader.gif"/>');
  });

  $.post($('#order-form').attr('action'), $('#order-form').serialize(), function(result,status){
    if(status == "success") {
      $.each(result, function(cart_id,sms){
        var scope = $('#cart_'+cart_id);
        $.each(sms, function(sm_id, value){
          scope.find('#shipping-method-'+sm_id+' .price').text(value);
        });
      });
    }
    shipping_updater = false;
  }, 'json');
}

function recalculate_order_totals() {
  var all_total = 0;

  $('.order').each(function(i,order){
    var $o = function(selector) {return($(order).find(selector));};
    var v = function(t){return(parseFloat(t.text().replace(/[^\d.]/mg, '')))};

    $o('td.qty').each(function(j, line_item) {
      var el = $(line_item);
      var price = v($(el).prev());
      price = price * parseInt(el.find('input').val());

      if(!isFinite(price)) {price = v($(el).next())};
      el.next().text(price.toFixed(2) + " PLN");
    });

    var subtotal = 0;
    $o('.line_item td.total_display').each(function(){subtotal += v($(this))});
    $o('.subtotal .total_display').text(subtotal.toFixed(2)+" PLN");

    var sc = $o('.shipping_method input[checked] ~ strong');
    $o('.shipping_charge .total_display').text(sc.text());

    var total = v(sc) + subtotal;
    $o('.order-total .total_display').text(total.toFixed(2) + " PLN");

    all_total += total;
  });

  $('.summary .price.selling').text(all_total.toFixed(2)+ " PLN");
}


function update_order_totals(){
  recalculate_order_totals()

  if(!shipping_updater) {
    if (shipping_updater_timeout) {
      clearTimeout(shipping_updater_timeout);
    }
    shipping_updater_timeout = setTimeout(update_quantities_and_shipping, 1000);
  }
}

$(window).load(function(){
  $('.qty input').change(update_order_totals).keyup(update_order_totals);
  $('input[type="radio"]').change(update_order_totals).click(update_order_totals);
  recalculate_order_totals();
});