

$(document).ready(function(){
	
	$(".copyFields").click(function(){
		
		$("#ship_first_name").attr("value",$("#first_name").attr("value"));
		$("#ship_last_name").attr("value",$("#last_name").attr("value"));
		$("#ship_company").attr("value",$("#company").attr("value"));
		$("#ship_address").attr("value",$("#address").attr("value"));
		$("#ship_address_line_2").attr("value",$("#address_line_2").attr("value"));
		$("#ship_city").attr("value",$("#city").attr("value"));
		$("#ship_zip").attr("value",$("#zip").attr("value"));
		$("#ship_phone").attr("value",$("#phone").attr("value"));
		
		return false;
	});
	
	function get_pricing()
	{
		var _textual = "";
		
		$(".product").each(function(){
			
			if($(this).attr("value") != "")
			{
				_textual += $(this).attr("name") + "=" + $(this).attr("value")+"&";
			} else {
				_textual += $(this).attr("name") + "=0" + "&";
			}
			
		});
		
		if(_textual == "")
		{
			return;
		}
		
		
		_textual += "disc_code="+$("#disc_code").attr("value")+"&";
		
		var _discCode = $("#disc_code").attr("value");
		
		if($("#shipping_to").attr("value") != "")
		{
			_textual += "shipping_to="+$("#shipping_to").attr("value")+"&";
		} else {
			_textual += "shipping_to=null&";
		}
		
		
		
		if($("#club_member").attr("checked") == true)
		{
			_textual += "club_member=true";
		} else {
			_textual += "club_member=false";
		}
		
		$("#submit").attr("disabled",true);
		
		$.ajax({
			type: "POST",
			url: "/weinbox/handler",
			data: _textual,
			success: function(ret){
				
				if($("clear_pricing", ret).text() == "1")
				{
					return;
				}
				
				$("#subtotal").text( "$" + $("subtotal", ret).text() );
				$("#tax").text( "$" + $("tax", ret).text() );
				$("#shipping").text( "$" + $("shipping", ret).text() );
				$("#grandTotal").text(  "$" + $("grandTotal", ret).text() );
				
				if( $("discount", ret).text() != "0.00" )
				{
					$("#discount").text( "($" + $("discount", ret).text() + ")" ).parent().show();
					
				} else {
					$("#discount").parent().hide();
				}
				
				if( $("discountCodeValid", ret).text() == "true" )
				{
					$("#discCodeValid").html("<strong style=\"color:#5F9E3C\">(Valid)</strong>").show("normal");
				} else {
					if(_discCode != "")
					{
						$("#discCodeValid").html("<strong style=\"color:#FF0000\">(Not Valid)</strong>").show("normal");
					}
				}
				
				$("#submit").attr("disabled",false);
			}
			});
		
	}
	
	
	$(".product").keyup(function(e){
		
		if(e.keyCode != 9)
		{
			get_pricing();
		}
		
	});
	
	$("#shipping_to").change(get_pricing);
	
	$("#club_member").change(get_pricing);
	
	$("#disc_code").keyup(function(e){
		
		var _currValue = $(this).attr("value");
		
		if(_currValue.length > 3)
		{
			if(e.keyCode != 9)
			{
				get_pricing();
			}
		}
		
		
		
	});
	
});