$(document).ready(function() {
    $('#qq-calc').click(function() {
        if (isNaN(parseInt($("#qq-num-colorsf").val()))) $("#qq-num-colorsf").val("0");
        if (isNaN(parseInt($("#qq-num-colorsb").val()))) $("#qq-num-colorsb").val("0");

        if (isNaN(parseInt($("#qq-num-items").val())) ||
            parseInt($("#qq-num-colorsf").val()) + parseInt($("#qq-num-colorsb").val()) == 0) {
            //Error
            alert("Please enter the number of shirts and at least one color for the front or back of the shirt.");
        } else {
            $("#qq-result").html("calculating...").fadeIn('slow');
            
            var params = {
                numShirts: $("#qq-num-items").val(),
                numColorsF: $("#qq-num-colorsf").val(),
                numColorsB: $("#qq-num-colorsb").val(),
                discount: $('#qq-discount').val()
            };
            
            $.getJSON($("#qq-base-url").val() + "/services/qq.php",
                params,
                function(data) {
                    $("#qq-result").html("<strong>Total:</strong> " + formatCurrency(data.total) +
                    "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                    "<strong>Per Shirt:</strong> " + formatCurrency(data.shirtAvg) +
                    (parseInt(data.numFreeShirts) > 0
                        ? "<br/><strong>" + data.numFreeShirts + " Free Shirts Included</strong>"
                        : "") +
                    (parseFloat(data.discount) > 0
                        ? "<br/><strong>Discount:</strong> " + formatCurrency(data.discount)
                        : "") +
                    ((data.debugInfo && data.debugInfo.length > 0) ? "<div>" + data.debugInfo + "</div>" : "") +
                    "<div class='fine-print'>* not including setup, tax, and shipping</div>"
                    );

                    try {
                      pageTracker._trackPageview("/qq/shirts/"+data.numShirts+'/colorsf/'+data.numColorsF+
                        '/colorsb/'+data.numColorsB+'/discount/'+$('#qq-discount').val());
                    } catch(ex) { }
                }
            );
        }

        return false;
    });
});

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);
}