jQuery.Cart = function(container, imagerule, info, price, options){
  var $container = $(container);
  var products = {};
  var $cart_info = jQuery('.cartThumbnail-area');
  var state;
  var images = jQuery.fn.get_image_rule(imagerule);
  var info_name = info;
  var price_name = price;

  function setup_events(){
    jQuery(document).bind('iselect', function(event, data){
      state = data.state;
    });
    jQuery('#iselect-cart-button').click(function(){
      render_cart();
    });
    jQuery(document).bind('cart-add', function(event, data){
      if(products[data.id]==undefined) products[data.id] = 0;
      products[data.id] += 1;
      render_cart_info();
    });
  }

  function render_cart_info(){
    $cart_info.html(count_cart_items() + ' items in your cart');
    $('#iselect-cart-msg').html('<span style="font-size: 16px; color: #fff; font-weight: bold;">Product added to cart.</div>');
    jQuery.openPopupLayer({ name:'cart', target:'iselect-cart-msg' });
    var t=setTimeout("jQuery.closePopupLayer('cart');", 1500);
  }

  function render_cart(){
    var data = new Array();
    for(var p in products){
      var product = mindsteps.iSelect.getObject(state.name, p);
      data.push({ img:images[p], info:product[info_name], price:product[price_name], id:p, quantity:products[p] });
    }
    var node = jQuery('.templates .iselect-cart').bindTo(data);
    jQuery('#iselect-cart').html(node);
    jQuery.openPopupLayer({ name:'cart_msg', target:'iselect-cart' });
  }

  function count_cart_items(){
    var c = 0;
    for(var p in products){
      if(products[p]>0) c++;
    }
    return c;
  }

  setup_events();
}

jQuery.fn.cart = function(imagerule, info, price, options){
  this.each(function(){
    var container = this;
    options = jQuery.extend({}, jQuery.fn.cart.defaults, options);
    new jQuery.Cart(container, imagerule, info, price, options);
  });
  return this;
}

jQuery.fn.cart.defaults = {
}
