function cartAjax(data)
{
    $.ajax({
        type: 'post', 
        dataType: 'json',
        url: '/cart.ajax.php',
        data: data,
        success: function (msg) {
            items = msg.items;
            clearOrderLines();
            drawOrderLines();
            
            if ($('#CouponCode').val().length > 0) {
                $('#applybutton').click();
            }
        } 
    });
};

function clearOrderLines()
{
    pageOrder = {};
    lines = 0;
    pageOrder = new Order();
    pageOrder.setCustomer(customer);
    pageOrder.setShippingRates(shippingRates);
    pageOrder.setShippingMethod($('.radioShipping input:checked').val());

    $('.orderLine').remove();
    $('#subtotalPayNow').html('$0.00');
}

function drawOrderLines()
{
    $.each(items, function() {

        current = $('#cloneMe').clone().insertBefore('#cloneMe');
        current.attr('id', 'line' + lines++);
        current.addClass('orderLine');
        current.show();
        current.find('.itemDescription').html(this.i.firstName + ' ' + this.i.secondName);
        if (this.i.calcPrice != 0) {
        	current.find('.itemPrice').html('$' + this.i.calcPrice);
        } else {
        	current.find('.itemPrice').html('<span style="color:#F00; font-weight: bold;">Free</span>');
        }
        if (this.i.calcPrice != 0) {
        	current.find('.totalPrice').html('$' + Order.prototype.TotalPrice(this.count,this.i.calcPrice).toFixed(2));
        } else {
        	current.find('.totalPrice').html('<span style="color:#F00; font-weight: bold;">Free</span>');
        }
        if (this.i.calcPrice != 0) {
        	current.find('.qty').val(this.count);
        } else {
        	current.find('.qty').html('<option value="1" selected="selected">1</option>');
        }
        current.find('.updateLink').attr('rel', this.i.itemNumber);
        current.find('.removeLink').attr('rel', this.i.itemNumber);

        //Update function
        current.find('.updateLink').click(function(e) {

            cartAjax({
                action: 'update',
                item: $(this).attr('rel'), 
                qty: $(this).parents('tr').find('.qty').val()
            });

            return false;
        });

        //Update function
        current.find('.qty').change(function(e) {
            cartAjax({
                action: 'update',
                item: $(this).parents('tr').find('.removeLink').attr('rel'), 
                qty: $(this).val()
            });

            return false;
        });

        //Remove function
        current.find('.removeLink').click(function(e) {

            cartAjax({
                action: 'remove',
                item: $(this).attr('rel')
            });

            $('#'+$(this).attr('rel')).hide();

            return false;
        });

        pageOrder.addItem(this.i, this.count, this.totalPrice);
    });
    if (lines != 0) {
        $('#noItems').hide();
        $('#headlines').show();
        $('.pos1').show();
        $('.pos2').show();
        $('.termsOfConditions').show();
        $('table.tab3 .bb1 td.no_nl').addClass('nl');
    } else {
        $('#noItems').show();
        $('#headlines').hide();
        $('.pos1').hide();
        $('.pos2').hide();
        $('.termsOfConditions').hide();
        $('#rowCoupon').hide();
        $('#rowShipping').hide();
        $('#rowSubtotal').hide();
        $('#rowTax').hide();
        $('#labelTotal').hide();
        $('#tdTotal').hide();
        $('#couponTr').hide();
        $('#tdCheckout').hide();
        $('table.tab3 .bb1 td.no_nl').removeClass('nl');                                                
    }

    pageOrder.calcOrder();
    updateTotal();
    $('#priceShipping').html('$' + Number(pageOrder.shippingPrice).toFixed(2));

    if (typeof pageOrder.subtotal != 'undefined') {
        $('#subtotalPayNow').html('$' + Number(pageOrder.subtotal).toFixed(2));
    };

    $('#tax').html('$' + Number(pageOrder.tax).toFixed(2));

}


// Validate form on keyup and submit
$(function () {

    $('#applybutton').click(function(){
        $('#couponPrice').html('<span style="color:#F00;">Please wait ...</span>');
        couponEnabled = false;
        $.ajax({
            type: 'post', 
            dataType: 'json',
            url: '/coupon.ajax.php',
            data:{
                action: 'checkpromo',
                promo: $('#CouponCode').val() 
            },
            success: function (msg) {
                if (msg.response != 'success') {
                    $('#couponDesc').html('');
                    
                    if (msg.response == 'failed') {

                        if (typeof(msg.err_msg) == 'undefined') {
                            msg.err_msg = 'Invalid Promotional Code. Please try your code again or call 1-877-872-2071';
                        } 

                        $('#couponPrice').html('<span style="color:#F00;">' + msg.err_msg + '</span>');
                        
                    } else if (msg.response == 'changed') {
                        $('#couponPrice').html('');
                    } 
                    $('#couponTr').hide();
                    pageOrder.calcOrder();
                    updateTotal();
                } else {
                    if (msg.discount_description != '') {
                        $('#couponDesc').html('(' + msg.discount_description + ')');
                    }
                    if (msg.discount_type == 'PERCENT') {
                        $('#couponPrice').html('<span style="color:#F00; font-weight: bold;">- '+parseFloat(msg.discount_amount)+'%</span>');
                        $('#couponTotal').html(moneyFormat(parseFloat(msg.discount_amount)*parseFloat($('#subtotalPayNow').text().substr(1,$('#subtotalPayNow').text().length-1))/100));
                        $('#orderTotal').html(moneyFormat(pageOrder.total));
                        $('#total').html(moneyFormat(pageOrder.total-parseFloat(msg.discount_amount)*parseFloat($('#subtotalPayNow').text().substr(1,$('#subtotalPayNow').text().length-1))/100));
                        couponEnabled = true;
                        pageOrder.calcOrder();
                        updateTotal();
                        $('#couponTr').show();
                    } else if(msg.discount_type == 'DOLLAR') {
                        $('#couponPrice').html('<span style="color:#F00; font-weight: bold;">- $' + parseFloat(msg.discount_amount) + ((msg.discount_amount.toString().indexOf('.') == -1)?'.00':'') +'</span>');
                        $('#couponTotal').html(parseFloat(msg.discount_amount));
                        $('#orderTotal').html(moneyFormat(pageOrder.total));
                        $('#total').html(moneyFormat(pageOrder.total-parseFloat(msg.discount_amount)));
                        couponEnabled = true;
                        pageOrder.calcOrder();
                        updateTotal();
                        $('#couponTr').show();
                    }
                }
            } 
        });
    });
    
    $('#clickCoupon').click(function(){
        $.prompt('*The promotion code will be applied on your total eligible purchase(s) and is not applicable to shipping and processing or taxes. Eligible Purchases exclude Try-It-Before-You-Buy-It offers, Buy-2-Get-1 -Free Offers, or Gift-bag purchases. Only 1 discount may be used per transaction and per customer. Discount can be modified or withdrawn at any time without prior notice. Coupon is one time use only. This offer cannot be combined with any other discount or promotional offer and is not refundable for cash or credit. We reserve the right to limit quantities, change terms without notice and reserve the right to cancel orders arising from pricing, promotions or other errors. Other restrictions may apply.');
    });
    
    jQuery.validator.addMethod(
        "expdate",
        function(value, element) {
            d = new Date();
            return this.optional(element) || (element.value == d.getFullYear()) ? ($("#expMonth").val() >= d.getMonth() + 1) : true;
        },
        "Expiration date is not valid"
    );

    jQuery.validator.addMethod(
            "zip",
            function(value, element) {
                return this.optional(element) || (/^[0-9A-Z]+$/ig.test(element.value));
            },
            "Zip code is invalid"
    );

    jQuery.validator.addMethod(
            "phoneFormat",
            function(value, element) {
                return this.optional(element) || (/^\+*[-0-9\ \(\)]+$/.test(element.value));
            },
            "Phone is invalid"
    );

    $("#billinfo").validate({

        rules: {

            billFirstname: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billLastname: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billAddress1: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billCity: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billState: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billZip: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            	,zip: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,billPhone: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            	,phoneFormat: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }


            ,billEmail: {
                required: function () {return $('#billingIsSameAsShippingNo').get(0).checked},
                email: function () {return $('#billingIsSameAsShippingNo').get(0).checked}
            }

            ,cardNumber: {
                required: true
                ,creditcard: true
            }

            ,cvc: {
                required: true
                ,number: true
                ,minlength: 3
                ,maxlength: 4
            }

            ,expYear: {
                expdate: true
            }

            ,agree: {
                required: true
            }
        }

        ,messages: {

            billFirstname: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billLastname: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billAddress1: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billCity: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billState: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billZip: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
            }

            ,billPhone: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
                ,phoneFormat: '<img src="/img/error.gif" hspace="2" title="The phone format is wrong"><br><span style="color: red">The phone format is wrong</span>'
            }

            ,billEmail: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>',
                email: '<img src="/img/error.gif" hspace="2" title="E-mail is not valid"><br><span style="color: red">E-mail is not valid</span>'
            }

            ,cardNumber: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
                ,creditcard: '<img src="/img/error.gif" hspace="2" title="Enter valid credit card"><br><span style="color: red">Enter valid credit card</span>'
            }

            ,cvc: {
                required: '<img src="/img/error.gif" hspace="2" title="This field is required"><br><span style="color: red">This field is required</span>'
                ,number: '<img src="/img/error.gif" hspace="2" title="Enter valid cvc code"><br><span style="color: red">Enter valid cvc code</span>'
                ,minlength: '<img src="/img/error.gif" hspace="2" title="Enter valid cvc code"><br><span style="color: red">Enter valid cvc code</span>'
                ,maxlength: '<img src="/img/error.gif" hspace="2" title="Enter valid cvc code"><br><span style="color: red">Enter valid cvc code</span>'
            }

            ,expYear: {
                expdate: '<img src="/img/error.gif" hspace="2" title="Expiration date is not valid"><br><span style="color: red">Expiration date is not valid</span>'
            }

            ,agree: {
                required: '<img src="/img/error.gif" hspace="2" title="You must read and accept the TERMS of the Hydroxatone Risk Free Trial to complete your order"> <span style="color: red">You must read and accept the TERMS of theHydroxatone Risk Free Trial to complete your order. </span>'
            }
        }

    });
});

