var theApp = null;

var ra = new Object();

ra.Cart = Class.create();
ra.Cart.prototype = {
  
  initialize: function() {
    this.subtotal = 0;
    theApp = this;
  },

  update_subtotal: function() {
    check_string = 'price_for_';
    subtotal = 0;
    i = 0;
    form_hash = document.forms[0];
    while (i < form_hash.length)
    {
      field = form_hash[i];
      i++;
      if (field.id.substring(0, check_string.length) == check_string)
      {
        id = field.id.substring(check_string.length, field.id.length);
        price = field.value;
        quantity = $(id).value;
		var shipping;
        dest_array = document.getElementsByName('ship_dest');

		if (dest_array[0].checked)
		{
			shipping = $('price_ship_usa').value;
		}
		else if (dest_array[1].checked)
		{
			shipping = $('price_ship_canada').value;
		}
		else if (dest_array[2].checked)
		{
			shipping = $('price_ship_other').value;
		}
        subtotal += quantity * price + quantity * shipping;
      }
    }
    $('total').innerHTML = '$' + subtotal.toFixed(2);
  },

  inc_quantity: function() {
    field = $A(arguments)[1];
    new_value = field.value - 0;
    new_value++;
    field.value = new_value;
    theApp.update_subtotal();
  },

  dec_quantity: function() {
    field = $A(arguments)[1];
    new_value = field.value - 0;
    new_value--;
	if (new_value < 2)
    {
       new_value = 2;
    }
    field.value = new_value;
    theApp.update_subtotal();
  }

};


function showCart()
{
  $('cart_overlay').style.display='block';
  $('cart').style.display='block';
  raCart = new ra.Cart();
  time = new Date();
  nocache = time.getTime();
  new Ajax.Updater('cart', 'http://www.thaioolongtea.com/cart.php?nocache=' + nocache, 
     { method: 'get', onComplete: wireCart} 
  );
  return false;
}

function cartSubmit()
{
  if (($('oolong_tea').value - 0) < 2) 
  {
    alert('The minimum order is 2 bags'); 
    return false;
  }
  else 
  {
    $('oolong_tea').enable(); 
  }
}

function wireCart()
{
  Event.observe($('add_oolong_tea'), "click", raCart.inc_quantity.bindAsEventListener(null, $('oolong_tea')));    
  Event.observe($('sub_oolong_tea'), "click", raCart.dec_quantity.bindAsEventListener(null, $('oolong_tea')));  

  dest_array = document.getElementsByName('ship_dest');
  Event.observe(dest_array[0], "click", raCart.update_subtotal.bindAsEventListener(null, dest_array[0]));    
  Event.observe(dest_array[1], "click", raCart.update_subtotal.bindAsEventListener(null, dest_array[1]));    
  Event.observe(dest_array[2], "click", raCart.update_subtotal.bindAsEventListener(null, dest_array[2]));    
  
  $('spinner_for_oolong_tea').style.display = 'block';

  $('oolong_tea').disable();

  raCart.update_subtotal();
}
