$(document).ready(function() {
    jQuery.validator.addMethod("cases", function( value, element ) {
		var result = this.optional(element) || value.length >= 1 && /^\d+$/.test(value) && parseInt(value) > 0;
		if (!result) {
			element.value = "0";
			var validator = this;
			setTimeout(function() {
				validator.blockFocusCleanup = true;
				element.focus();
				validator.blockFocusCleanup = false;
			}, 1);
		}
		return result;
	}, "You must enter the number of cases as a positive numeric value.");

    jQuery.validator.addMethod("billingRequired", function(value, element) {
		if ($("#billing_same").is(":checked"))
			return $(element).parents(".subTable").length;
		return !this.optional(element);
	}, "");
	
	jQuery.validator.messages.required = "";
	$("#order").validate({
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 required field. It has been highlighted below'
					: 'You missed ' + errors + ' required fields.  They have been highlighted below';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		onkeyup: false,
		submitHandler: function() {
			$("div.error").hide();
                        form.submit();
			//alert("'form' = " + $('form').attr('id') + " 'this' = " + $(this).attr('id'));
                        //document.order.submit();
                        //form.submit();
                        //return true;
		},
                
		messages: {
			email: {
				required: " ",
				email: "Please enter a valid email address, example: you@yourdomain.com",
				remote: jQuery.validator.format("{0} is already taken, please enter a different address.")	
			}
		}
		//debug:false
	});
    
    $(".resize").vjustify();
    
    $("input.phone").mask("(999) 999-9999");
    $("input.zipcode").mask("99999");
    var creditcard = $("#billing_cardnumber").mask("9999 9999 9999 9999");
    
    $('#number_cases').keypress(function(event) {
        if (event.keyCode == '13') 
        {
            event.preventDefault();
        }
        
        setTimeout("$('#number_cases').calculate_costs()", 200);
    });
    
    /*$("#number_cases").keypress(function(event) {
        
        
        $.print(event);
        alert('keydown!');
        //$("#shipping_handling").val(calculate_shipping($(this).val());
        //$("#total_cost").val(calculate_total($(this).val());
    });*/
    
    // keep this in case American Express is ever added, they use "9999 999999 99999"
    $("#billing_cardtype").change(function() {
        switch ($(this).val()){
            default: creditcard.unmask().mask("9999 9999 9999 9999");
            break;
        }
    });
    
    // toggle optional billing address
    var subTableDiv = $("div.subTableDiv");
    var toggleCheck = $("input.toggleCheck");
    
    toggleCheck.is(":checked")? subTableDiv.hide() : subTableDiv.show();
    
    $("input.toggleCheck").click(function() {
        if (this.checked == true) 
        {
            subTableDiv.slideUp("medium");
            $("form").valid();
        } 
        else 
        {
            subTableDiv.slideDown("medium");
        }
    });
});

$.fn.vjustify = function() {
    var maxHeight=0;
    $(".resize").css("height","auto");
    this.each(function()
    {
        if (this.offsetHeight > maxHeight) 
        {
            maxHeight = this.offsetHeight;
        }
    });
    
    this.each(function() {
        $(this).height(maxHeight);
        if (this.offsetHeight > maxHeight) 
        {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight)));
        }
    });
};

$.fn.calculate_costs = function () {
    if($(this).val().length >= 1 && $(this).val().match(/^\d+$/))
    {
        $('#subtotal_cost').val('$'+calculate_cost($(this).val()));
        $('#shipping_handling').val('$'+calculate_shipping($(this).val()));
        $('#total_cost').val('$'+calculate_total($(this).val()));
    }
};

function calculate_cost(numCases)
{
    numCases = parseInt(numCases);
    var cost = 80.00;
    
    if(numCases >= 3)
        cost = 70.00;
    else if(numCases == 2)
        cost = 75.00;
        
    return (cost * numCases).toFixed(2);
}

function calculate_shipping(numCases)
{
    numCases = parseInt(numCases);
    var shipping = 8.95;
    
    return (shipping * numCases).toFixed(2);
}

function calculate_total(numCases)
{
    return (parseFloat(calculate_cost(numCases)) + parseFloat(calculate_shipping(numCases))).toFixed(2);
}
