Number.prototype.toCurrency = function()
{
  return '$' + this.toFixed(2);
}

var Cart = {
  scheduleTimeoutID: null,
  popup: null,

  init: function(cartShippingAddressPopupHtml)
  {
    this.cartShippingAddressPopupHtml = cartShippingAddressPopupHtml;
		
		this.ajaxCallback = this.update.bind(this);
  },
	
	callServer: function(action, params)
	{
    sendAjaxMessage('cart', 
                    action,
										params,
                    this.ajaxCallback); 
										
    this.showAjaxLoading(); 
  },
  
  showAjaxLoading: function()
  {
    $('cart-ajax-loading').show();
  },
  
  hideAjaxLoading: function()
  {
    $('cart-ajax-loading').hide();
  }, 
	
  addItem: function(idproduct)
  {
    this.callServer('addItem',
                    {
                      idproduct: idproduct,
                      quantity: 1
                    }); 
  },
	 
  removeItem: function(itemID)
	{
		// remove item html from page
    if ($('cart-item-separator-' + itemID))
      $('cart-item-separator-' + itemID).remove();
    $('cart-item-' + itemID).remove();
    $('cart-item-shipping-' + itemID).remove();
		
		// notify server
		this.callServer('removeItem',
										{
                      item_id: itemID
                    }); 
										
  },

	itemQuantityChanged: function(itemID)
	{
		var quantity = $F('cart-item-quantity-' + itemID);

    // notify server
    this.callServer('itemQuantityChanged',
                    {
                      item_id: itemID,
											quantity: quantity
                    });
	},
	
	scheduleItemQuantityChanged: function(itemID)
	{
    window.clearTimeout(this.ajaxScheduleTimeoutID);
    this.ajaxScheduleTimeoutID = this.itemQuantityChanged.bind(this).delay(0.5, itemID); 
  },
	
	customerChanged: function()
	{
    var customer = {
      first_name: $F('customer-first-name'),
      last_name: $F('customer-last-name'),
      business_name: $F('customer-business-name'),
      email_address: $F('customer-email-address'),
      phone_number: $F('customer-phone-number'),
      mobile_number: $F('customer-mobile-number'),
			fax_number: $F('customer-fax-number'),
      address: {
        street1: $F('customer-address-street1'),
        street2: $F('customer-address-street2'),
        city: $F('customer-address-city'),
        state: $F('customer-address-state'),
        postcode: $F('customer-address-postcode'),
        country_code: $F('customer_address_country_code_field')
		  }
    };

		this.callServer('customerChanged',
		                {
                      customer: customer
                    });
		
  },
  
  scheduleCustomerChanged: function()
  {
    window.clearTimeout(this.ajaxScheduleTimeoutID);
    this.ajaxScheduleTimeoutID = this.customerChanged.bind(this).delay(0.5);
  },
	
	update: function(params)
	{
		var serverCart = params.cart;
		
		// update items
		var items = $H(serverCart.items);
    var itemIDs = serverCart.itemIDs;
    if (itemIDs.length == 0)
    {
      $('cart-is-empty').show();
    }
    else
    {
      $('cart-is-empty').hide();
      
  		for (var i=0; i<itemIDs.length; ++i) 
  		{
        var itemID = itemIDs[i];
        var item = items.get(itemID);
        
        if (!$('cart-item-'+itemID) && item.html)
          $('cart-items').insert(item.html);
  			
  			$('cart-item-price-ex-gst-' + item.id).innerHTML = item.priceExGST.toCurrency();
        $('cart-item-subtotal-' + item.id).innerHTML = item.subtotalExGST.toCurrency();
  			
  			// addresses
  			this.updateItemShippingAddressSelect(item, serverCart.shippingAddresses);
      }
    }
    		
		// update totals
    $('cart-items-subtotal-ex-gst').innerHTML = serverCart.itemsSubtotalExGST.toCurrency();
    $('cart-total-discount').innerHTML = '-' + (serverCart.totalDiscount > 0 ? serverCart.totalDiscount.toCurrency() : '');
		if (Object.isNumber(serverCart.postageExGST))
      $('cart-postage-ex-gst').innerHTML = serverCart.postageExGST.toCurrency();
	  else
		  $('cart-postage-ex-gst').innerHTML = '<span class="postage-quote-required">Please contact Fiona Lake to obtain a personal quote</span>';
    $('cart-gst').innerHTML = serverCart.gst.toCurrency();
    $('cart-total').innerHTML = serverCart.total.toCurrency();
		
		this.hideAjaxLoading();
  },
	
	updateItemShippingAddressSelect: function(item, shippingAddresses)
	{
    var shippingAddressSelect = $('item-shipping-address-' + item.id);
		
		for(var i=1; i<shippingAddresses.length; ++i)
		{
      if (!shippingAddressSelect.hasOption(i))
			 shippingAddressSelect.addOption(i, shippingAddresses[i]);
    }
		
		shippingAddressSelect.selectOption(item.shippingAddressIndex);
  },
	
	itemShippingAddressChanged: function(itemID)
	{
    var addressIndex = $F('item-shipping-address-' + itemID);
		if (addressIndex == 'new')
		  this.showShippingAddressForm(itemID);
	  else
		  this.setItemShippingAddress(itemID, addressIndex);
  },
	
	showShippingAddressForm: function(itemID)
	{

    this.popup=popup.show(this.cartShippingAddressPopupHtml, 
		           ["Cancel","OK"], 
							 this.shippingAddressCallback.bind(this, itemID));
  },
	
	shippingAddressCallback: function(itemID, button)
	{		
		if(button == 'Cancel') {
			this.popup.close();
		}
		
		var addressSelect = $('item-shipping-address-' + itemID);
		
    var address = {
      first_name: $F('shipping-address-first-name'),
      last_name: $F('shipping-address-last-name'),
      street1: $F('shipping-address-street1'),
      street2: $F('shipping-address-street2'),
      city: $F('shipping-address-city'),
      state: $F('shipping-address-state'),
      postcode: $F('shipping-address-postcode'),
      country_code: $F('shipping-address-country-code_field')
    }
		
    if (button != 'OK' || !Validate("shipping-pop"))
    {
      addressSelect.options[0].selected = true;
      return false;
    }
		
		// notify server
		this.callServer('itemNewShippingAddress',
                    {
                      item_id: itemID,
											address: address
                    });
  },

  validateAddress: function(address)
	{
    return !(address.first_name.blank() || address.last_name.blank() || address.street1.blank() || address.city.blank())
		       && address.country_code.match(/[A-Z]{2}/);
  },
	
	setItemShippingAddress: function(itemID, addressIndex)
	{
    this.callServer('setItemShippingAddress',
										{
                      item_id: itemID,
											address_index: addressIndex
										});
  },
	
	setItemOption: function(itemID, option, value)
	{
    this.callServer('setItemOption',
                    {
                      item_id: itemID,
                      option: option,
											value: value
                    });
  },
	
  
  photographFramedOptionChanged: function(itemID)
  {
    var framed = $F('framed-' + itemID) == 'framed';
    
		var note = $('item-framed-note-' + itemID);
		if (framed)
      note.show();
		else
		  note.hide();		  

    this.setItemOption(itemID, 'framed', framed);
  }, 
	
	photographPaperOptionChanged: function(itemID)
	{
    var paper = $F('paper-' + itemID);
		
		var overlay = $('item-paper-overlay-' + itemID);
		overlay.src = 'images/i-' + paper.toLowerCase() + '-overlay.png';
		
		this.setItemOption(itemID, 'paper', paper);
  },

	requireIsGift: function(itemID)
	{
		if ($F('is-gift-' + itemID + '-yes') == null 
		    && $F('is-gift-' + itemID + '-no') == null)
	  {
      // set global error for Validate() to pick up
		  error = "Is your purchase a gift? yes/no";
	  }
  },
	
	requireSignBook: function(itemID)
	{
		if ($F('sign-book-' + itemID + '-yes') == null 
		    && $F('sign-book-' + itemID + '-no') == null)
	  {
      // set global error for Validate() to pick up
		  error = "Like your book(s) signed? yes/no";
	  }
  }

}