
  cart = {
    init: function(){
      $('.add-item').click(function(ev){
        ev.preventDefault();
        var $this = $(this);
        var wdata = $this.parents('.wdata');

        wdata.find('.wine-details').hide();
        wdata.find('.cart-details').show();
        wdata.find('.wform').load($this.attr('href'));
      });
    }
  }


  var winecart = {
    ids: [],
    wines: {},
    gtotal: 0,
    discount: 0,
    wineclub: undefined,
    init: function(){
      winecart.ids = [];
      // get current wine ids
      $('#tcart tbody tr').each(function(){
        if(this.className != ''){
          winecart.ids.push(this.className);
        }
      });
      // get wines data
      $.getJSON('/cart/wine_info', {ids: winecart.ids.join()}, function(json){
        winecart.wines = json.wines;
        winecart.initialRecalc();
      });
      // listen for some change on cart elements
      $('#tcart input[type=radio]').click(function(){
        var row = $(this).parents('tr');
        winecart.recalc_row(row);
        winecart.recalc();
      });
      $('#tcart select').change(function(){
        var row = $(this).parents('tr');
        winecart.recalc_row(row);
        winecart.recalc();
      });

      // listen for change on quantity data
      $('#tcart .qtity').keyup(function(){
        var row = $(this).parents('tr');
        winecart.recalc_row(row);
        winecart.recalc();
      });

      $('#tcart .remove').click(function(ev){
          ev.preventDefault();
          var el = $(this);
          $.get(el.attr('href'), {id: this.rel}, function(){
            el.parents('tr').remove();
            winecart.recalc();
          });
      });

      $('#wineclub').click(function(){
        if(this.checked){
          $('#wcm').show();
          $('#wcm input:first').attr('checked', 'checked');
          $('#wcm input:first').trigger('click');
        }else{
          winecart.wineclub = undefined;
          $('#wcm').hide();
          $('#wcm input').each(function(){
            this.checked = false;
          });
          winecart.initialRecalc();
        }
      });

      $('#wcm input[type=radio]').click(function(){
        winecart.wineclub = this.value;
        //console.log(winecart.wineclub);
        winecart.initialRecalc();
      });

    },

    set_discount: function(disc){
      var radio = $('#wcm input[type=radio]:checked').val();
      winecart.discount = disc || parseFloat(winecart.wines.wineclub[radio]);
    },

    recalc_row: function(row){
        var tr = $(row);
        var wine = tr.get(0).className;
        var type = tr.find('input[type=radio]:checked').val();
        var size = tr.find('select').val();
        var qtity = tr.find('.qtity').val();
        var price = winecart.wines[wine][type][size];
        var old_price = 0;
        var discount = winecart.check_discount(winecart.wines[wine], type);

        if(discount > 0){
          old_price = price;
          price = winecart.roundNumber(price - (discount * price / 100));
        }
        else if(winecart.wineclub != undefined){
          old_price = price;
          var disc = winecart.wines.wineclub[winecart.wineclub][type]
          price = winecart.roundNumber(price - (disc * price / 100));
        }

        var punit = tr.find('.punit');
        punit.html('<div>$'+ price +'</div>');
        if(old_price > 0){
          punit.prepend('<div class="stout">$'+ old_price +'</div>');
        }

        tr.find('.subt').html('$' + winecart.roundNumber(price * qtity));
    },

    check_discount: function(wine, type){
      var disc = 0;

      if(wine.discount.special[type] > 0){
        disc = parseFloat(wine.discount.special[type]);
      }
      else if(wine.discount.manager > 0){
        disc = parseFloat(wine.discount.manager);
      }
      else {
        disc = 0;
      }

      return disc;
    },

    recalc: function(){
      var gtotal = 0.0;
      $('#tcart .subt').each(function(){
        gtotal += parseFloat(this.innerHTML.replace('$', ''));
      });

      winecart.gtotal = winecart.roundNumber(gtotal)
      $('#gtotal').html('$' + winecart.roundNumber(winecart.gtotal));
    },

    roundNumber: function(num){
      var dec = 2;
      var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10, dec);
      return result;
    },

    initialRecalc: function(){
      $('#tcart tbody tr').each(function(){
        winecart.recalc_row(this);
      });
      winecart.recalc();
    }
};


  (function($){
    $.fn.minicart = function(options){
      var defaults = {ids: [], wines: {}, debug: false}
      var options = $.extend(defaults, options);
      var $this = undefined;

      return this.each(function(){
        $this = $(this);
        init();
      });

        function init(){
          // get wine id
          $this.find('tbody tr').each(function(){
            if(this.className != ''){
              options.ids.push(this.className);
            }
          });

          // get wines data
          $.getJSON('/cart/wine_info', {ids: options.ids.join()}, function(json){
            options.wines = json.wines;
            recalc();
          });

          // listen for some change on cart data
          $this.find('tbody tr:first').change(function(){
            recalc();
          });

          // check change on input field
          $this.find('.qtity').keyup(function(){
            recalc();
          });

          //submit cart form
          $this.find('.buy-item').click(function(ev){
            ev.preventDefault();
            submitCart();
          });


          //cancel cart item
          $this.find('.cancel-item').click(function(ev){
            ev.preventDefault();
            var data = $this.parents('.wdata');
            
            data.find('.cart-details').hide();
            data.find('.cart-details .wform').html('Loading...');
            data.find('.wine-details').show();
          });

        }

        function recalc(){
          var wine  = $this.find('tr')[0].className;
          var type  = $this.find('input[type=radio]:checked').val();
          var size  = $this.find('select').val();
          var qtity = $this.find('.qtity').val();
          var price = options.wines[wine][type][size];
          var old_price = 0;
          var discount = check_discount(options.wines[wine], type);
msg('Discount: ' + discount);
          if(discount > 0){
            old_price = price;
            price = roundNumber(price -(discount * price / 100));
          }
msg('Old price: ' + old_price + ' Price: ' + price);

          $this.find('.punit').html('<div>$' + price + '</div>');
          if(old_price > 0){
            $this.find('.punit').prepend('<div class="stout">$' + old_price + '</div>');
          }
          $this.find('.subt').html('$' + roundNumber(price * qtity));
        }

        function check_discount(wine, type){
          var disc = 0;

          if(wine.discount.special[type] > 0){
            disc = parseFloat(wine.discount.special[type]);
          }
          else if(wine.discount.manager > 0){
            disc = parseFloat(wine.discount.manager);
          }
          else{
            disc = 0;
          }

          return disc;
        }

        function roundNumber(num){
          var dec = 2;
          var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10, dec);
          return result;
        }

        function submitCart(){
          var fdata = $this.parent('form').serialize();

          $.ajax({
            url: '/cart/add_item',
            data: fdata,
            dataType: 'html',
            success: function(data, textStatus){
              $('.basket-content').html(data);
            }
          });
          var data = $this.parents('.wdata');
          data.find('.cart-details').hide();
          data.find('.cart-details .wform').html('Loading...');
          data.find('.wine-details').show();
        }

        function msg(txt){
          if(options.debug){
            console.log(txt);
          }
        }


    }
  })(jQuery);
