Number.prototype.formatMoney = function(c, d, t)
{
  var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

var colors = new Array();


var prices = new Array();


var quantities = new Array();


var discount_factor  = 1.0;
var blank_field      = '';
var subtotal         = 0;
var shipping_price   = 0;
var valid_page_count = 0;
var sales_tax        = null;
var sales_tax_value  = 0;
var shipping_pricing = { first:0, each_add:0 };

function updateHTML( target, string )
{
  $( target ).innerHTML = string;
}

function displayGrandTotal( string )
{
  updateHTML( 'grand_total', string );
}

function updateGrandTotal()
{
  var grand_total = subtotal + shipping_price + sales_tax_value;
  displayGrandTotal( '$' + grand_total.formatMoney(2, ".", ",") + ' USD' );
}

function displaySalesTax( string )
{
  var field = document.getElementById( 'sales_tax' );
  if ( field )
    field.innerHTML = string;
}

function displayShippingPrice( string )
{
  updateHTML( 'shipping_price', string );
}

function updateSalesTax()
{
  if ( sales_tax == null )
    {
      sales_tax_value = 0;
	  displaySalesTax( blank_field );
	}
  else
    {
	  sales_tax_value = subtotal * sales_tax;
	  displaySalesTax( '&nbsp;$' + sales_tax_value.formatMoney( 2, ".", "," ) );
	}
}

function getShippingPrice( quantity )
{
  var price = shipping_pricing.first;
  if ( quantity > 0 )
    price += ( quantity - 1 ) * shipping_pricing.each_add;
  return price / 100.0;
}

function getQuantity()
{
  var quantity = parseInt( $('product_quantity').value );
  if ( isNaN( quantity ) || ( quantity <= 0 ) ) 
    { quantity = 1; $('product_quantity').value = 1; }
  return quantity;
}

function updateShippingPrice()
{
  shipping_price = getShippingPrice( getQuantity() );
  displayShippingPrice( '$' + shipping_price.formatMoney(2, ".", ",") );
  /* $('shipping_price').innerHTML = '$' + shipping_price.formatMoney(2, ".", ","); */
  updateGrandTotal();
}

function updateSubtotal()
{
  price = prices[$('product_size_product_id').getValue()][$('product_color_product_id').getValue()][$('product_quantity_product_id').getValue()];

  var quantity = getQuantity();

  var string_to_pass = 'price_id=' + encodeURIComponent( price.price_id ) + '&quantity=' +
    encodeURIComponent( quantity );

  if (price.page_count_enabled)
  {
    $('page_count_view').style.display = "block";
    page_count = parseInt($('page_count').value);

	if ( isNaN( page_count ) ) { page_count = 1; }
	string_to_pass += '&page_count=' + page_count;

	new Ajax.Request('/product_prices/price_pre_set', {asynchronous:false, evalScripts:true, method:'get', parameters:string_to_pass})

	$('page_count').value = valid_page_count;

  }
  else
  {
    $('page_count_view').style.display = "none";

	new Ajax.Request('/product_prices/price_pre_set', {asynchronous:false, evalScripts:true, method:'get', parameters:string_to_pass})

  }

  subtotal  = ProductCustoms.addProductCustoms(subtotal);
  subtotal *= discount_factor;
  updateHTML( 'subtotal', '$' + subtotal.formatMoney(2, ".", ",") );
  /* $('subtotal').innerHTML = '$' + subtotal.formatMoney(2, ".", ","); */

  updateSalesTax();
  updateShippingPrice();
}

function getField( field_name )
{
  return encodeURIComponent( $( field_name ).getValue() );
}

function getZip()
{
  return getField( 'zip' );
}

function getCountryName()
{
  return getField( 'country_name' );
  /* return encodeURIComponent( $('country_name').getValue() ); */
}

function eraseSalesTax()
{
  if ( sales_tax != null )
    {
	  sales_tax = null;
	  updateSalesTax();
	  updateGrandTotal();
	}
}

function processCountryChange()
{
  eraseHandlingPrice();

  var string_to_pass = 'country_name=' + getCountryName() + '&quantity=' +
    encodeURIComponent( getQuantity() );
  new Ajax.Request('/handling_cost/setup', {asynchronous:true, evalScripts:true, method:'get', parameters:string_to_pass})

}

function getShippingService()
{
  return getField( 'shipping_service_id' );
  /* return encodeURIComponent( $('shipping_service_id').getValue() ); */
}

function processServiceChange()
{
  var string_to_pass = 'country_name=' + getCountryName() + '&shipping_service_id=' +
    getShippingService() + '&quantity=' + encodeURIComponent( getQuantity() );
  new Ajax.Request('/handling_cost/provider_change', {asynchronous:true, evalScripts:true, method:'get', parameters:string_to_pass})
}

function processMethodChange()
{
  var string_to_pass = 'method_link_id=' + 
  	encodeURIComponent( $('method_link_id').getValue() ) + '&quantity=' +
	encodeURIComponent( getQuantity() );
  new Ajax.Request('/handling_cost/method_change', {asynchronous:true, evalScripts:true, method:'get', parameters:string_to_pass})
}

function calculationDisable() {
  $$('a.calculate').invoke('hide');
  $$('img.calculate').invoke('show');
}

function calculationEnable() {
  $$('a.calculate').invoke('show');
  $$('img.calculate').invoke('hide');
}

function calculateTax() {
  calculationDisable();
  var string_to_pass = 'zip=' + getZip();
  new Ajax.Request('/handling_cost/calculate_tax', {asynchronous:true, evalScripts:true, method:'get', parameters:string_to_pass})
}

function onTaxCalculate()
{
  calculationEnable();
  updateSalesTax();
  updateGrandTotal();
}

function processZipChange()
{
  eraseSalesTax();
}

var ProductCustoms = new Object();
ProductCustoms["addProductCustoms"] = function(price)
{
    return price;
}

function updateColorImage()
{
  element = $('product_color_product_id');
  if (colors[element.getValue()] != "")
    $('product_color_image').innerHTML = '<div class="form-box"><div class="form-img"><img src="' + colors[element.getValue()] + '"></div></div>';
  else
    $('product_color_image').innerHTML = '';
}

function updateCustomItemImage(custom_id)
{
  element = $('product_custom_' + custom_id);
  if (customs[custom_id][element.getValue()].image != "")
    $('product_custom_' + custom_id + '_image').innerHTML = '<div class="form-box"><div class="form-img"><img src="' + customs[custom_id][element.getValue()].image + '"></div></div>';
  else
    $('product_custom_' + custom_id + '_image').innerHTML = '';
}

document.observe('dom:loaded', function() {
  $('product_color_product_id').observe('change', function() {
    updateColorImage();
    updateSubtotal();
  });

  updateColorImage();
  $$('img.calculate').invoke('hide');

  new Ajax.Request('/product_sizes/update_customs_dropdowns/4', {asynchronous:false, evalScripts:true, method:'get'})
  new Ajax.Request('/handling_cost/setup', {asynchronous:true, evalScripts:true, method:'get'})
});