// Product page Javascript

function totalUpdate() {

  if ( $("#items").children().length > productMax + 1 && productMax != 0 ) {
    $("#items fieldset.addNew").css("display", "none");
    $("#limitReach").css("display", "block");
  } else {
    $("#items fieldset.addNew").css("display", "block");
    $("#limitReach").css("display", "none");
  }

  var number = 0;
  $("#items .number").each(function () {
    number++;
    $(this).text(number);
  });

  if ( $("#items > div").length > 1 ) {
    $(".remove").css("display", "inline-block" );
  } else {
    $(".remove").css("display", "none" );
  }

  var productPrice = $("#product_price").text().replace(/\,/g,'');
  var total = 0;
  $("#items select[name=quantity]").each(function() {
    total = total + parseInt( $(this).val() * productPrice.substring( 1, productPrice.length ) );
  });

  $("#items input[name=quantity]").each(function() {
    total = total + parseInt( $(this).val() * productPrice.substring( 1, productPrice.length ) );
  });

  if ( $("#required_1_include").is(':checked') ) {
    include = $("#required_1_price").text();
    total = parseInt( include.substring(1, include.length) ) + total;
  }

	if ( $("#optional").length > 0 ) {
		$("#optional > div").each( function () {
	 		total += parseFloat( $("input[name='price']", this).val() ) * parseFloat ( $("select[name='quantity']", this).val() );
		});
	}
  $("#totalValue").val( total );
  $("#total").text( "$" + addCommas( total ) );
}

function newItem() {
  $("#items div:first").clone().insertAfter($("#items div:last"));
  $("#items div:last .number").text( $("#items div").length );
  $("#items div:last").css('height', '0');
  var height = $('#items div:first').height();
  $("#items div:last").animate(
    { height: height },
    500,
    function() {
      totalUpdate()
    });
}

function submitCart() {
	$("#items div").each( function() {
		$.post( '/includes/addToCart.php', {
			productID: $("input[name='productID']", this).val(),
			colorID: $("select[name='color']", this).val(),
			optionID: $("select[name='option']", this).val(),
			quantity: $("*[name='quantity']", this).val()
		},
		function () {
			if ( $("#optional").length > 0 ) {
				$("#optional > div").each( function () {
					if ( $("*[name='quantity']", this).val() > 0 ) {
						$.post( '/includes/addToCart.php', {
							productID: $("input[name='productID']", this).val(),
							colorID: $("select[name='color']", this).val(),
							optionID: $("select[name='option']", this).val(),
							quantity: $("*[name='quantity']", this).val()
						});
					}
				});
			}
			if ( $("#required").length > 0 ) {
				if ( $("#required_1_include").is(':checked') ) {
					$.post( '/includes/addToCart.php', {
						productID: $("#required input[name='productID']").val(),
						colorID: 'undefined',
						optionID: 'undefined',
						quantity: 1
					});
				};
			};
			tb_show('title', "#TB_inline?height=100&width=500&inlineId=addedModal&modal=true");
		});
	});
}

function removeItem( item ) {
  $(item).parent().parent().parent().animate({
    height: 0,
    queue: true
  },
	500,
  function() {
    $(this).remove();
    totalUpdate();
  });
}

/*
 * Cart Functions
 */


function adjustQuantity( id, quantity ) {
	if ( quantity < 1 ) {
		removeProduct( id );
	} else {
		$.post( '/includes/adjustQuantity.php', {
			id: id,
			quantity: quantity
		});
	}
}

function removeProduct( id ) {
	$.post( '/includes/removeItem.php', {
		id: id
	},
	function() {
		$("#product_" + id).fadeOut("normal", function() {
			$(this).slideUp( "normal", function() {
				$(this).remove() } ) } );
		$("#product_divider_" + id).fadeOut( "normal", function() {
			$(this).remove() } );
		updateCart();
	});
}

function removePackage( id ) {
	$.post( '/includes/removePackage.php', {
		id: id
	},
	function() {
		$("#package_" + id).fadeOut("normal", function() {
			$(this).slideUp( "normal", function() {
				$(this).remove() } ) } );
		$("#package_divider_" + id).fadeOut( "normal", function() {
			$(this).remove() } );
		updateCart();
	});
}

function updateCart() {
	var shipping = 0;
	var total = 0;
    var quantity = 0;
	$('tr.values').each( function() {
		shipping += $("input[name='quantity']", this).val() * $("input[name='shipping']", this).val();
		total += $("input[name='quantity']", this).val() * $("input[name='price']", this).val();
		quantity += parseInt( $("input[name='quantity']", this).val() );
		$("span.productTotal", this).text( "$" + addCommas( ( $("input[name='quantity']", this).val() * $("input[name='price']", this).val() ).toFixed( 2 ) ) );
	});
	$(".shippingTotal").text( "$" + addCommas( ( shipping ).toFixed( 2 ) ) );
	$("#tax").text( "$" + addCommas( ( parseFloat( parseFloat( total ) * parseFloat( $("input[name='taxRate']" ).val() ) ) ).toFixed( 2 ) ) );
	$(".cartTotal").text( "$" + addCommas( ( total + shipping + parseFloat( parseFloat( total ) * parseFloat( $("input[name='taxRate']" ).val() ) ) ).toFixed( 2 ) ) );
	$(".totalQuantity").text( quantity );
}

// This adds commas to numeric strings
function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}


$(document).ready(function() {
  totalUpdate();
});

// This is unrelated to the cart!
function previewReplace( ident, value, text ) {
  var colorString = '';
  var optionString = '';
  if ( ident == 'color' ) {
   color = value;
  } else {
   option = value;
  }

  if ( color != null ) {
  	colorString = "_" + color;
  }

  if ( option != null ) {
    optionString = "_" + option;
  }
  $('#preview').attr( "src", "images/products/" + image + colorString + optionString + ".jpg" );
  $('#productPreview .' + ident ).text( text );
}

/* Shipping and Tax Functions */

function updateShipping() {
	$('.shipTotal').text( $("#total").text() );
	var quantity = 0;
	$("#items div").each( function() {
		quantity += parseInt( $("*[name='quantity']", this).val() );
	});
	$('.shipCost').text( "$" + ( parseFloat( $('input[name="shipping"]').val() ) * parseInt( quantity ) ).toFixed( 2 ) );
	$('.taxCost').text( "$" + ( $("#totalValue").val() * $('input[name="tax"]').val() ).toFixed( 2 ) );
}

function getTax() {
	$.post( '/includes/tax.php', {
		state: $("select[name='taxState']").val()
	},
	function (i) {
		$("input[name='tax']").val( i.tax );
		$("#taxes").css( 'visibility', 'visible' );
		updateShipping();
	},
	"json");
}

function submitAndWait() {
	$('form').submit();
	tb_show('title', "#TB_inline?height=100&width=300&inlineId=processingModal&modal=true");
}
