﻿/*
Depends on: NamLu updated 07.22.2009
- carmd_member.js
- jquery 1.3.2
- jquery validate 1.5.5
- jquery ui
*/
var totalCost = 0;
var subTotalCost = 0;

var commonError = "Sorry, your session has been time out.";
function OrderLogin() {
    var theForm = $("#loginForm");
    if (!theForm.valid()) return false;
    var paramString = CollectPostFormValues(theForm);
    //alert("start calling " + paramString);
    $('#ModalContent').modal();
    xhr = $.ajax(
                    {
                        type: "POST",
                        url: "/Shop/Login",
                        data: paramString,
                        dataType: "json",
                        error: function() { /*could not load ajax*/
                            //alert(commonError);
                            ReloadShoppingCart();
                        },
                        success: function(result) {
                            $.modal.close();
                            //alert("result returned");
                            var contentType = xhr.getResponseHeader('Content-Type');

                            if (result.Error != undefined) {
                                $("#loginForm").prepend(CreateErrorMessage(result.Error));
                            }
                            else {
                                $("#CA_StepRegion").html(result.ContactSummary);
                            }
                        }
                    }
                );
    return false;
}

function isResultJSON(contentType) {
    return contentType.indexOf("json") >= 0;
}

function isResultHTML(contentType) {
    return contentType.indexOf("html") >= 0;
}

function ExpandFirstIncompleteRegion() {
    var firstIncomplete = $().find(".InCompleteRegion")[0];
    if (firstIncomplete != undefined) {
        firstIncomplete.style.display = 'block';
        var val = $('input:radio[name=PaymentMethod]:checked').val();
        if (val == undefined || val == 1) {
            $("#divCreditCardInfo").hide();
        }
    }
    SetUpValidationAddressForm();
}

function ChangeStepStatusCaption(addressType) {
    var incompelteStatus = $("#" + addressType).parents('table').eq(0).find('.incompletedStatus').get(0);
    if (incompelteStatus != null) {
        var rootTable = $("#" + addressType).parents('table').eq(0);
        rootTable.find('.incompletedStatus')[0].style.display = "none";
        rootTable.find('.completedStatus')[0].style.display = "block";
    }
}

function SetUpValidationAddressForm() {
    if ($("#EditAddressForm")[0] != undefined) {
        var editForm = $("#EditAddressForm");
        SetUpValidation_AddressInfo(editForm);
        editForm.validate().settings.submitHandler = function(form) { SaveAddressInfo(form); };
        changeClassesInIe6(editForm);
    }
}

function SetUpValidationCartOrderQuantity(theForm) {
    theForm.validate(
    {
        submitHandler: function() { return; },
        wrapper: "p",
        errorPlacement: function(error, element) {
            error.appendTo(element.parents('div').eq(0));
        }
    });

    theForm.find('input[type=text]').each(function() {
        $(this).rules("add", { required: true, digits: true,
            messages: {
                required: "Quantity is required",
                digits: "Quantity must be a number"
            }
        });

        $(this).keypress(function(evt) {
            var keynumber = evt.keyCode;
            if (keynumber == 13) {
                return false;
            }
        });
    });
}

function EditAddressInfo(regionId) {

    //Fix validation bug when change contact edit region
    //$().find('#EditAddressForm').each(function() { $(this).remove(); });

    // close all other editting region and display the corresponding summary region
    $().find('.InCompleteRegion, .EditingAddress').each(function() { this.style.display = 'none'; });
    $().find('.SummaryAddress').each(function() { this.style.display = 'block'; });

    var shipMethod = $('#ShippingServiceLevel').val();
    // ajax to get the editing form
    var dataString = "addressType=" + regionId + "&shippingMethod=" + shipMethod;
    $('#ModalContent').modal();
    xhr = $.ajax(
                {
                    type: "POST",
                    url: "/Shop/ContactEdit",
                    data: dataString,
                    //dataType: "html",
                    error: function() { /*could not load ajax*/
                        //alert(commonError);
                        ReloadShoppingCart();
                    },
                    success: function(result, textStatus) {
                        /*Check session is time out?*/
                        var contentType = xhr.getResponseHeader('Content-Type');
                        if (isResultJSON(contentType)) {
                            alert("Sorry, your session has been time out.");
                            ReloadShoppingCart();
                        }
                        //
                        $.modal.close();
                        var domElement = $(result); // create element from html
                        var currentRegion = $("#" + regionId);
                        currentRegion.html(domElement); // replace html content of the step region
                        SetUpValidationAddressForm();
                        if ($("#ShippingBillingAddressTheSame")[0] != undefined) {
                            ToggleShippingBillingTheSame($("#ShippingBillingAddressTheSame")[0].checked);
                        }

                        //Mask ZIP and Phone
                        $("#phoneNumber").mask("999-999-9999");
                        $("#postCode").mask("99999");
                    }
                }
            );
}

function CollectPostFormValues(theForm) {
    var paramString = "";
    theForm.find("input[type=text],input[type=password], input[type=checkbox], select").each(function() { paramString = paramString + this.id + "=" + this.value + "&"; });
    return paramString;
}

function SaveAddressInfo(theForm) {
    var paramString = "";
    $(theForm).find("input[type=text], select").each(function() { paramString = paramString + this.id + "=" + this.value + "&"; });
    $(theForm).find("input[type=checkbox]").each(function() { paramString = paramString + this.id + "=" + this.checked + "&"; });

    var regionId = $(theForm).parent().attr("id");
    paramString = paramString + "addressType=" + regionId;
    $('#ModalContent').modal();
    xhr = $.ajax(
                    {
                        type: "POST",
                        url: "/Shop/SaveAddressInfo",
                        data: paramString,
                        //dataType: "html",
                        error: function() { /*could not load ajax*/
                            //alert(commonError);
                            ReloadShoppingCart();
                        },
                        success: function(result) {
                            $.modal.close();
                            var contentType = xhr.getResponseHeader('Content-Type');
                            if (isResultHTML(contentType)) {
                                /*Check if return data is Login page?*/
                                if (result.indexOf("<html") > -1) {
                                    ReloadShoppingCart();
                                    return false;
                                }
                                //continue processing
                                var domElement = $(result); // create element from html
                                $("#" + regionId).html(domElement); // append to end of list
                                ChangeStepStatusCaption(regionId);
                                ExpandFirstIncompleteRegion();

                                if (regionId.substring(0, 2) == "SA") {
                                    IsShippingAddressCompleted = true;
                                    SetUpValidation_ShippingServiceLevel($("#ShippingServiceLevelForm"));
                                    ReloadShoppingCart(); //In this case, reload web page to get new tax value from server

                                } else if (regionId.substring(0, 2) == "BA") {
                                    IsBillingAddressCompleted = true;
                                } else if (regionId.substring(0, 2) == "CA") {
                                    ReloadShoppingCart();
                                }
                            }
                            else {
                                var myObject = eval('(' + result + ')');
                                if (regionId.substring(0, 2) == "SA") {
                                    showDialog('Cart Information', 'We\'re sorry, but your address does not match national postal records. Please try again.', 'd_error', '1.5');
                                    SetUpValidation_ShippingServiceLevel($("#ShippingServiceLevelForm"));
                                } else {
                                    if (!HasServerErrorAlready($(theForm))) {
                                        $(theForm).parent().find(".error").remove();
                                        $(theForm).before(CreateErrorMessage(myObject.ErrorMessage));
                                    }
                                }
                            }
                        }
                    }
            );

}


function HasServerErrorAlready(theForm) {
    return theForm.parent().siblings('.error')[0] != undefined;
}

function CancelEditingAddressInfo(regionId) {
    $('#' + regionId).find('.InCompleteRegion, .EditingAddress')[0].style.display = 'none';
    $('#' + regionId).find('.SummaryAddress')[0].style.display = 'block';
    ExpandFirstIncompleteRegion();
    SetUpValidation_ShippingServiceLevel($("#ShippingServiceLevelForm")); //Always setup validation for this

    if (regionId == "CA_StepRegion") $("#CA_StepRegion >.error").hide();
}

function ToggleShippingBillingTheSame(theCheckBox) {
    var submitButton = $('#SA_StepRegion').find('#EditAddressForm').eq(0).find('input[type=submit]');

    if (theCheckBox) {
        $('#SA_StepRegion').find('.AddressContent')[0].style.display = 'none';
        submitButton.bind('click', { theForm: submitButton[0].form }, SaveShippingClickWhenSameAsBilling);
    }
    else {
        $('#SA_StepRegion').find('.AddressContent')[0].style.display = 'block';
        submitButton.unbind('click', SaveShippingClickWhenSameAsBilling);
    }
}

function SaveShippingClickWhenSameAsBilling(event) {
    if (!$(event.data.theForm).valid()) {
        SaveAddressInfo(event.data.theForm);
    }
}

// intercept F5 key
function interceptKeyDown(e) {
    if (!e)
        var e = window.event;

    var keycode = e.keyCode;
    if (e.which)
        keycode = e.which;

    var src = e.srcElement;
    if (e.target)
        src = e.target;

    // 116 = F5
    if (116 == keycode) {
        // Firefox and other non IE browsers
        if (e.preventDefault) {
            e.preventDefault();
            e.stopPropagation();
        }
        // Internet Explorer
        else if (e.keyCode) {
            e.keyCode = 0;
            e.returnValue = false;
            e.cancelBubble = true;
        }

        return false;
    }
}

/*
* According to the type of browser, adds a new event listener to
* the specified object ,for the requested event, binded to the
* specific function.
*/
function attachEventListener(obj, type, func, capture) {
    if (window.addEventListener) { // Mozilla, Netscape, Firefox
        obj.addEventListener(type, func, capture);
    } else { // IE
        obj.attachEvent('on' + type, func);
    }
}

function placeOrder(successUrl) {    
    if (IsLoggedIn == false) {
        showDialog('Cart Information', 'Please login to check out the order.', 'd_error', '1.5');
        return false;
    }
    if (IsBillingAddressCompleted == false) {
        showDialog('Cart Information', 'Please enter billing address to check out.', 'd_error', '1.5');
        return false;
    }
    if (IsShippingAddressCompleted == false) {
        showDialog('Cart Information', 'Please enter shipping address to check out.', 'd_error', '1.5');
        return false;
    }

    var ccValid = false;
    var skipCC = false;
    if (document.getElementById("CCForm").style.display == "none" || totalCost == 0) {

        ccValid = true;
        skipCC = true;
    }
    else {
        try {
            // {MULTIPAYMENT}
            
            var pm = $('input:radio[name=PaymentMethod]:checked').val();
            if (pm == undefined) {
                $("#error-message").html("Please select a Payment Method.");
                ccValid = false;
            } else {
                //0 = credit card
                if (pm == 0) {
                    ccValid = $("#CCForm").valid();
                }
                else {
                    ccValid = true;
                    skipCC = true;
                }
            }
            
            // Credit Card
            //ccValid = $("#CCForm").valid();
                        
        } catch (Error) {
            ccValid = false;
        }
    }

    var sslValid = true;

    if ($("#ShippingServiceLevelForm")[0] != undefined) {
        sslValid = $("#ShippingServiceLevelForm").valid();
    }

    if (sslValid && ccValid) {

        var paramString = "";
        if (skipCC == false) {
            $('#CCForm').find("input[type=text], select").each(function() { paramString = paramString + this.id + "=" + this.value + "&"; });
        } else {
            paramString = "cardType=0&cardNumber=0&cardExpiredMonth=0&cardExpiredYear=0&cvv2=0";
            // {MULTIPAYMENT}
            paramString = paramString + "&PaymentMethod=" + $('input:radio[name=PaymentMethod]:checked').val();
        }

        if ($("#ShippingServiceLevelForm")[0] != undefined) {
            paramString = paramString + "&shippingMethodLevel=" + $("#ShippingServiceLevel").val();
        }

        //Where to here
        paramString = paramString + "&SelectHowDidYouHears=" + $("#SelectHowDidYouHears").val();
        paramString = paramString + "&HowDidYouHearOther=" + $("#HowDidYouHearOther").val();
        //Why to buy
        paramString = paramString + "&SelectReasonToBuys=" + $("#SelectReasonToBuys").val();
        paramString = paramString + "&ReasonToBuyOther=" + $("#ReasonToBuyOther").val();

        paramString = paramString + "&orderToken=" + $("#OrderToken").val();
        
        attachEventListener(document, "keydown", interceptKeyDown, true);

        $("#PageHeader").hide();
        $("#PageContent").hide();
        $("#divFooter").hide();
        $("#transition").show();
        $('body').css('background-image', "url()");        
        
        $('#ModalContent').modal();
        try {
            xhr = $.ajax(
                {
                    type: "POST",
                    url: "/Shop/PlaceOrder",
                    data: paramString,
                    dataType: "json",
                    error: function(xhr, des, ex) { /*could not load ajax*/
                        $.modal.close();
                        $("#PageHeader").show();
                        $("#PageContent").show();
                        $("#divFooter").show();
                        $("#transition").hide();
                        $('body').css('background-image', "url(../../Content/Images/bg-gra-Dblue.gif)");
                        alert('Could not process the Order.');
                        ReloadShoppingCart();
                    },
                    success: function(result) {
                        $.modal.close();
                        if (result.Success) {
                            // {MULTIPAYMENT}
                            if (result.IsExpressCheckout) {
                                window.location = "/Shop/PayPalCheckout";
                            } else {
                                window.location = successUrl;
                            }

                            // Credit Card
                            //window.location = successUrl;
                        }
                        else {                            
                            $("#PageHeader").show();
                            $("#PageContent").show();
                            $("#divFooter").show();
                            $("#transition").hide();
                            $('body').css('background-image', "url(../../Content/Images/bg-gra-Dblue.gif)");
                            $("#cardType").parent().parent().find(".error").remove();
                            //$("#cardType").parent().before(CreateErrorMessage(result.ErrorMessage));
                            // {MULTIPAYMENT}
                            $("#error-message").html(result.ErrorMessage);
                        }
                    }
                }
            );
        } catch (Error) {
            $("#PageHeader").show();
            $("#PageContent").show();
            $("#divFooter").show();
            $("#transition").hide();
            $('body').css('background-image', "url(../../Content/Images/bg-gra-Dblue.gif)");
            
            alert("Could not check out this Cart");            
            ReloadShoppingCart();
        }
    }
}

function CreateErrorMessage(message) {
    return "<label class='error'>" + message + "</label>";
}

function ApplyDiscountCode() {

    if (subTotalCost == 0) {
        showDialog('Cart Information', 'Your cart is empty.', 'd_error', '1.5');
        return false;
    }
    if ($("#DiscountCode").val() == "") {
        showDialog('Try Again', 'Please enter a discount code.', 'd_error', '1.5');
        return false;
    }

    $('#ModalContent').modal();
    try {
        $.ajax(
                {
                    type: "GET",
                    url: "/Shop/ApplyDiscountCode/" + $("#DiscountCode").val() + "?r=" + Math.random(),
                    //data: dataString,
                    dataType: "json",
                    error: function(xhr, des, ex) { /*could not load ajax*/
                        $.modal.close();
                        alert("Could not apply this code.");
                        ReloadShoppingCart();
                    },
                    success: function(discountResult) {
                        $.modal.close();
                        if (!discountResult.CodeIsValid) {
                            //Display Coupon status
                            showDialog('Try Again', 'Your discount code is invalid. Please try again.', 'd_error', '1.5');
                        }
                        if (discountResult.CodeExpired) {
                            showDialog('Try Again', 'Your discount code has expired or out of service. Please try again.', 'd_error', '1.5');
                        }

                        if (discountResult.CodeInvalidMessage.length > 0) {
                            showDialog('Try Again', discountResult.CodeInvalidMessage, 'd_error', '1.5');
                        }
                        
                        $("#DiscountCode").val('');

                        $("#tax").html(ToDollarDisplay(discountResult.Tax).toString());

                        $("#discountAmount").html(ToDollarDisplay(discountResult.Discount).toString());

                        $("#totalCost").html(ToDollarDisplay(discountResult.Total).toString());

                        //Display Coupon status
                        $("#AppliedCoupon").html(discountResult.CouponStatus);

                        totalCost = discountResult.Total;
                        if (discountResult.Total == 0) {
                            $("#CCForm").css("display", "none");
                            $("#lblPaymentMethod").html("Completed <img alt='' src='" + httpRoot + "/content/images/complete_icon_open.gif' />");
                            $("#lblPaymentMethod").css("color", "#4993CF");
                        } else {
                            $("#CCForm").css("display", "block");
                            $("#lblPaymentMethod").html("Not Completed <img alt='' src='" + httpRoot + "/content/images/not_complete_icon_close.gif' />");
                            $("#lblPaymentMethod").css("color", "#666666");
                        }
                    }
                }
            );
    } catch (error) {
        alert("Could not apply this code!")
        ReloadShoppingCart();
    }
}

function RemoveCartItem(cartItemId) {
    $('#ModalContent').modal();

    $.ajax(
            {
                type: "GET",
                url: "/Shop/RemoveItemFromCart/" + cartItemId + "?r=" + Math.random(),
                //data: dataString,
                dataType: "json",
                error: function(xhr, des, ex) { /*could not load ajax*/
                    //alert(xhr.responseText);
                    ReloadShoppingCart();
                },
                success: function(costResult) {
                    $.modal.close();
                    updateOrderCartCost(costResult);
                    $("#carItemPanel_" + cartItemId).remove();
                    /*Check shipable*/
                    CheckShipable(costResult);
                    showDialog('Cart Information', 'The items have been removed.', 'd_success', '1.5');
                }
            }
        );
}

function ClearCart() {
    $('#ModalContent').modal();
    try {
        $.ajax(
                {
                    type: "GET",
                    url: "/Shop/ClearCart/?r=" + Math.random(),
                    //data: dataString,
                    dataType: "json",
                    error: function(xhr, des, ex) { /*could not load ajax*/
                        $.modal.close();
                        ReloadShoppingCart();
                    },
                    success: function(costResult) {
                        $.modal.close();
                        updateOrderCartCost(costResult);
                        /*Check shipable*/
                        CheckShipable(costResult);
                        showDialog('Cart Information', 'Order cart has been removed.', 'd_success', '1.5');
                    }
                }
            );
    } catch (Error) {
        //window.location.reload();
    }
}

function updateOrderCartCost(costResult) {

    totalCost = costResult.Total;
    subTotalCost = costResult.SubTotal;

    //Display Coupon status
    $("#AppliedCoupon").html(costResult.CouponStatus);

    //SetUpValidation_ShippingServiceLevel($("#ShippingServiceLevelForm"));

    if (costResult.IsShipable == false) /*If order cart contains no shipable items, so no shipping address required*/
        IsShippingAddressCompleted = true;

    if (costResult.Total == 0) {
        $("#CCForm").css("display", "none");
        $("#lblPaymentMethod").html("Completed <img alt='' src='" + httpRoot + "/content/images/complete_icon_open.gif' />");
        $("#lblPaymentMethod").css("color", "#4993CF");
    } else {
        $("#CCForm").css("display", "block");
        $("#lblPaymentMethod").html("Not Completed <img alt='' src='" + httpRoot + "/content/images/not_complete_icon_close.gif' />");
        $("#lblPaymentMethod").css("color", "#666666");

        // Rem this if use {MULTIPAYMENT}
        /*
        if (IsShippingAddressCompleted == true) {
            $("#divCreditCardInfo").show();
        } else {
            $("#divCreditCardInfo").hide();
        }*/
    }
    if ($("#discountAmount")[0] != undefined) {
        $("#discountAmount").html(ToDollarDisplay(costResult.Discount).toString());
    }
    if ($("#totalCost")[0] != undefined) {
        $("#totalCost").html(ToDollarDisplay(costResult.Total).toString());

    }
    if ($("#shippingFeeAmount")[0] != undefined) {
        $("#shippingFeeAmount").html(ToDollarDisplay(costResult.ShippingFee).toString());

    }
    if ($("#tax")[0] != undefined) {

        $("#tax").html(ToDollarDisplay(costResult.Tax).toString());

    }
    $(".subtotalCost").each(function() { this.innerHTML = ToDollarDisplay(costResult.SubTotal).toString(); });

    if (costResult.TotalQuantity > 0) {

        $(".fullCartPart").each(function() { this.style.display = "block"; });
        $(".emptyCartPart").each(function() { this.style.display = "none"; });


        $("#orderCartProductQuantity").html(costResult.TotalQuantity);
        /*
        Enable Payment
        */
        $("#tblPayment").show();
        //document.getElementById("tblPayment").style.display = "block";
    }
    else {
        $(".fullCartPart").each(function() { this.style.display = "none"; });
        $(".emptyCartPart").each(function() { this.style.display = "block"; });
        /*
        Disable Payment
        */
        $("#tblPayment").hide();
    }
}

function UpdateCartItem() {
    var paramString = "";
    if (!$("#orderCartForm").valid()) return false;

    $().find(".orderCartItemQuantity").each(function() { paramString = paramString + this.id + "=" + this.value + "&"; });
    $('#ModalContent').modal();
    $.ajax(
            {
                type: "POST",
                url: "/Shop/UpdateCart",
                data: paramString,
                dataType: "json",
                error: function(xhr, des, ex) { /*could not load ajax*/
                    //alert(xhr.responseText);
                    ReloadShoppingCart();
                },
                success: function(result) {
                    $.modal.close();
                    updateOrderCartCost(result);

                    /*Check shipable*/
                    CheckShipable(result);

                    if (result.HasExceedQuantity) {
                        showDialog('Cart Information', 'There has at least one product exceeding its maximum quantity to buy.', 'd_error', '1.5');
                    }
                    else {
                        showDialog('Cart Information', 'Shopping cart has been updated.', 'd_success', '1.5');
                    }
                    for (i = 0; i < result.CartItems.length; i++) {
                        if (result.CartItems[i].Quantity > 0) {
                            $("#orderCartItemSubtotal_" + result.CartItems[i].Id).html(ToDollarDisplay(result.CartItems[i].SubTotal));
                            $("#" + result.CartItems[i].Id).val(result.CartItems[i].Quantity);
                        }
                        else {
                            $("#carItemPanel_" + result.CartItems[i].Id).remove();
                        }
                    }
                    if (result.ReloadPage == true) {
                        ReloadShoppingCart();
                    }
                }
            }
        );
}

function CheckShipable(JSONResult) {
    /*Check shipable*/
    var payment = document.getElementById('lblPaymentMethod');
    if (JSONResult.IsShipable == true) {
        $(".lblPaymentMethod").each(function() { this.innerHTML = '4.&nbsp;'; });
        //if (shipping != null) shipping.style.display = "block";
    } else {
        $(".lblPaymentMethod").each(function() { this.innerHTML = '3.&nbsp;'; });
        $("#shippingBreakLine").css("display", "none");
        $("#tblShipping").hide();
        SetUpValidation_ShippingServiceLevel($("#ShippingServiceLevelForm")); /*This will remove validation on shipping method level*/
    }

    /*end check shipable*/
}

/*ReCalculate shipping fee when user select ship method level*/
function CalculateShippingFee(shipLevel) {
    if (shipLevel != "") {
        $('#ModalContent').modal();
        $.ajax(
            {
                type: "GET",
                url: "/Shop/CalculateShippingFee/?shippingLevel=" + shipLevel + "&r=" + Math.random(),
                //data: dataString,
                dataType: "json",
                error: function(xhr, des, ex) { /*could not load ajax*/
                    alert(xhr.responseText);
                    ReloadShoppingCart();
                },
                success: function(Result) {
                    $.modal.close();
                    $("#shippingFeeAmount").html(ToDollarDisplay(Result.ShippingFee));
                    $("#tax").html(ToDollarDisplay(Result.Tax));
                    $("#totalCost").html(ToDollarDisplay(Result.Total));
                    $("#discountAmount").html(ToDollarDisplay(Result.Discount.toString()));

                    //Display Coupon status
                    $("#AppliedCoupon").html(Result.CouponStatus);

                    totalCost = Result.Total;
                    if (Result.Total == 0) {
                        $("#CCForm").css("display", "none");
                        $("#lblPaymentMethod").html("Completed <img alt='' src='" + httpRoot + "/content/images/complete_icon_open.gif' />");
                        $("#lblPaymentMethod").css("color", "#4993CF");
                    } else {
                        $("#CCForm").css("display", "block");
                        $("#lblPaymentMethod").html("Not Completed <img alt='' src='" + httpRoot + "/content/images/not_complete_icon_close.gif' />");
                        $("#lblPaymentMethod").css("color", "#666666");
                    }
                }
            }
        );
    }
}

//Currency format util
function checkNum(data) {      // checks if all characters 
    var valid = "0123456789.";     // are valid numbers or a "."
    var ok = 1; var checktemp;
    for (var i = 0; i < data.length; i++) {
        checktemp = "" + data.substring(i, i + 1);
        if (valid.indexOf(checktemp) == "-1") return 0;
    }
    return 1;
}

function ToDollarDisplay(dollar) { // idea by David Turley
    Num = dollar.toString();
    dec = Num.indexOf(".");
    end = ((dec > -1) ? "" + Num.substring(dec, Num.length) : ".00");
    Num = "" + parseInt(Num);
    var temp1 = "";
    var temp2 = "";
    if (checkNum(Num) == 0) {
        alert("This does not appear to be a valid number.  Please try again.");
    }
    else {
        if (end.length == 2) end += "0";
        if (end.length == 1) end += "00";
        if (end == "") end += ".00";
        var count = 0;
        for (var k = Num.length - 1; k >= 0; k--) {
            var oneChar = Num.charAt(k);
            if (count == 3) {
                temp1 += ",";
                temp1 += oneChar;
                count = 1;
                continue;
            }
            else {
                temp1 += oneChar;
                count++;
            }
        }
        for (var k = temp1.length - 1; k >= 0; k--) {
            var oneChar = temp1.charAt(k);
            temp2 += oneChar;
        }
        return "$" + temp2 + end;
    }
}

//Using this function instead of Location.reload() function will prevent re-posting data to server
function ReloadShoppingCart() {
    window.location.href = "/Shop/CheckOut/";
}