
function addToCart(product)
{
	product['date'] = (new Date).getTime();

	$("#cartMessage").html('Adding item(s) to your cart...');
	$("#cartMessage").fadeIn(400);


	$.getJSON('/cart/addtocart.php',product,function (results)
	{
		update_display(results);
		$("#cartMessage").fadeIn(400);
		$("#cartMessage").html(results.added +' item(s) have been added to your <a href="/checkout.php"">Cart</a>');
		$('#qty').val('1');
		$('#hasCartProduct').val('1');
	});
}

function update_display(status)
{
	$('#cartQuantity').text(status.quantity + ' Item(s)');
	$('#cartTotal').text(formatCurrency(status.total));
	if (status.total > 0) {
		$("#fastCheckout").html('<a href="/cart/index.php?main_page=checkout_shipping" class="btn_checkout">&nbsp;</a>');
		$(".fastCheckoutSm").html('<a href="/cart/index.php?main_page=checkout_shipping" class="btn_checkout_sm">&nbsp;</a>');


		$("#sizeMeNoSafari").css("width", "80px");

	}
}

function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
			num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$ ' + num + '.' + cents);
}



$.fn.disable = function()
{
	$(this).attr('disabled','disabled');
}

$.fn.enable = function()
{
	$(this).attr('disabled','');
}

var syncFields = false;

$.fn.syncTo = function(other)
{
	$(this).addClass('syncer');
	this.syncOther = other;

	$(this).bind('reSync',function ()
	{
		if(syncFields)
			$(this).val($(other).val());
	});

	var syncer = $(this);
	$(other).keyup(function () {$(syncer).trigger('reSync');});
	$(other).change(function () {$(syncer).trigger('reSync');});
}

function validatekit(el)
{
    if($(el).attr('prodid') == 503)
    {
        if($('#kit_wine').val() == 0)
        {
            alert('Please choose a wine refill.');
            return false;
        }

        window.location = "/cart/addtocart.php?ID=" + $(el).attr('prodid') + "&qty=1&redir=1&kit_wine="+$('#kit_wine').val();

        return false;
    }

    return true;
}

$(function ()
{
	$.getJSON('/cart/query_cart.php',{'date':(new Date).getTime()}, function (results)
	{
        if(results['logged_in'] == 'true')
        {
            $('#headerLogin').html('<span>|</span><a href="/cart/index.php?main_page=logoff">Logout</a>');
        }
		update_display(results);
	});

	$('#addToCart').click(function ()
	{
        if($('#kit_wine').val() == 0 && ($(this).attr('productID')==503 || $(this).attr('productID')==521))
        {
            alert('Please choose a wine refill.');
            return false;
        }

        if(($('#qty').val()).length < 1)
        {
            alert('Please enter a quantity');
            return false;
        }

		addToCart({
			'ID':$(this).attr('productID'),
			'qty':$('#qty').val(),
			'kit_wine':$('#kit_wine').val()
		});

		if($(this).attr('productID')==503)
		{
			var kitWine=$('#kit_wine').val();
			$(".wcJoinNow").attr("attrID",kitWine);
			if ( $('.WC_pop_IE6').length ) {
				$(".WC_pop_IE6").show();
			}
			else
			{
				$("#WC_pop").show();
			}

		}
		return false;
	});

    //sync the checkout billing and shipping fields.
	$('#firstname_s').syncTo('#firstname');
	$('#lastname_s').syncTo('#lastname');
	$('#lastname_s').syncTo('#lastname');
	$('#telephone_s').syncTo('#telephone');
	$('#street-address').syncTo('#street-address_b');
	$('#city').syncTo('#city_b');
	$('#postcode').syncTo('#postcode_b');
	$('#stateZone').syncTo('#stateZone_b');
	$('#stateZone').syncTo('#stateZone_b');
	$('#country').syncTo('#country_b');

	if(($("#cartMessage").text()).length < 1)
		$("#cartMessage").hide();

	if($('#create_account'))
	{
		$('#create_account').validate({
			onkeyup:false,
			onfocusout:false,
			showErrors: function (errors) {
				for ( var name in errors ) {
					alert($(this.findByName(name)[0]).attr('displayTitle') + ': ' + errors[name]);
					break;
				}
			}
		});

		$('#same_ship').click(function ()
		{
			if(this.checked)
			{
				syncFields = true;
				$('.syncer').disable();
				$('.syncer').trigger('reSync');
			}
			else
			{
				syncFields = false;
				$('.syncer').enable();
			}
		});
	}
});