// Product page Javascript
// Version 1.0.0 to 1.1.0 changelog:
// totalUpdate() function altered to allow dynamic price changes according to option via additional hidden fields in XHTML document.

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 = $("input[name=unitPrice]").val();
  var total = 0;
  $("#items *[name=quantity]").each(function() {
    var $number = $(this).parent().find('.number').text();
    if ( $(this).parent().find('*[name=option' + $number + ']').length ) {
      if ( $(this).parent().find('select[name=option' + $number + ']').length ) {
        var $option = $(this).parent().find('select[name=option' + $number + ']').val();
      } else {
        var $option = $(this).parent().find('input[name=option' + $number + '][type=radio]').filter(':checked').val();
      }
      $option = parseInt( $('#option_' + $option + '_price').val() )
    } else {
      $option = 0;
    }
    total = total + parseInt( $(this).val() * productPrice ) + $option;
  });

  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() {
  $newItem = $("#items div:first").clone();
  if ( $newItem.find('input[type=radio]').length ) {
    $newItem.find( 'input[type=radio]' ).attr( 'name', 'option' + ( $("#items div").length + 1 ) );
  }
  $newItem.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() {
    if ( $('input[type=radio]', this).length ) {
      $option = $('input[type=radio]').filter(':checked').val();
    } else {
      $option = $('select[name=option]').val();
    }
    $.post( '/includes/addToCart.php', {
      productID: $("input[name='productID']", this).val(),
      colorID: $("select[name='color']", this).val(),
      optionID: $option,
      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: $option,
              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;
  if ( $("*[name=quantity]").length ) {
    $("#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 ) );
  } else {
    $('.shipCost').text( "$" + ( parseFloat( $('input[name=shipping]').val() ) ).toFixed( 2 ) );
    $('.taxCost').text( "$" + ( parseFloat( $('input[name=unitPrice]').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");
}

$(document).ready(
  function() {
    $("select[name^=option]").bind(
      "onchange",
      function() {
        totalUpdate();
      }
    );
  }
);
