//GetShippingInfo gets TradeGlobal shipping costs as well as domestic costs. The regular shipping control displays if domestic shipping.
var valueChanged = false;
var selectedShippingMethod = "";
var strInitialTGContent = "<td colspan='2' align='center'>You must fill in all required billing and shipping information before shipping options will display.</td>";
var currentRequest = null;
var requestCounter = 0;
var errorCounter = 0;


function GetShippingInfo(setValueChanged, isAfterError) {       
        var getShippingInfo = true;
        $(".field .checkTradeGlobal").each(function () {
            if (this.value === "") {
                getShippingInfo = false;
                return false;
            }
        });

        if ($.trim($("#State_SHIP").val()) == "") {
            getShippingInfo = false;
        }

        if (getShippingInfo) {

            if (valueChanged || setValueChanged) {

                displayLoadingImage();

                $("input[value=Submit Order]").css("display", "none");

                var shippingQueryString = "";

                //get needed field values
                if (isAfterError == true) {
                    $("input.submitTG").each(function () {
                        var thisVal = $.trim(this.value.toString());
                        var thisName = $.trim(this.name.toString());
                        if (thisName.indexOf("FNAme") >= 0 || thisName.indexOf("LName") >= 0 || thisName.indexOf("Address1") >= 0 || thisName.indexOf("Address2") >= 0 || thisName.indexOf("City") >= 0) {
                            thisVal = "TradeGlobal";
                        }
                        shippingQueryString = shippingQueryString + "&" + $.trim(this.name.toString()) + "=" + thisVal;
                    });

                    $("select.submitTG").each(function () {
                        shippingQueryString = shippingQueryString + "&" + $.trim(this.name.toString()) + "=" + $.trim(this.value.toString());
                    });
                }
                else {
                    $("input.submitTG").each(function () {
                        shippingQueryString = shippingQueryString + "&" + $.trim(this.name.toString()) + "=" + $.trim(this.value.toString());
                    });

                    $("select.submitTG").each(function () {
                        shippingQueryString = shippingQueryString + "&" + $.trim(this.name.toString()) + "=" + $.trim(this.value.toString());
                    });
                }

                if (shippingQueryString.indexOf("State_SHIP") <= 0) {
                    shippingQueryString = shippingQueryString + "&State_SHIP=" + $.trim($("#State_SHIP").val());
                }

                
                $.ajaxSetup({ complete: onRequestCompleted });
                $(".required").attr("disabled", "disabled");
                    if ($("#Country_SHIP").val() != "US") {
                        shippingQueryString = fixedEncodeURI("request=UpdateTradeGlobalShippingCost" + shippingQueryString + "&extra=" + rnd());
                        requestCounter = requestCounter + 1;
                        currentRequest = $.get(
                                    "DmiAjaxSecure.aspx",
                                    shippingQueryString,
                                    function (data) {
                                        if (data.indexOf("successful") != -1) 
                                        {
                                            shippingQueryString = shippingQueryString.replace("UpdateTradeGlobalShippingCost", "SubmitOrderCartShippingTradeGlobal");
                                            $.get(
                                                "DmiAjaxSecure.aspx",
                                                shippingQueryString,
                                                function (shippingData) {
                                                    $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html(shippingData.slice(shippingData.indexOf("DMI:AJAX:BEGIN") + 14, shippingData.indexOf("DMI:AJAX:END")));
                                                    $("tr.orderTotalRow").css("display", "");
                                                    $("tr#USTaxRow").css("display", "none");
                                                },
                                                "html"
                                            );
                                        }
                                        else {
                                            $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html("<td colspan='2' align='center'>" + data.slice(data.indexOf("DMI:AJAX:BEGIN") + 14, data.indexOf("DMI:AJAX:END")) + "</td>");
                                            $("tr.orderTotalRow").css("display", "none");
                                            $("tr#USTaxRow").css("display", "none");

                                        }
                                        requestCounter = requestCounter - 1;
                                        InvalidShippingMethodCheck();
                                    },
                                    "html"
                                );
                    }
                    else {
                        shippingQueryString = fixedEncodeURI("request=SubmitOrderCartShipping" + shippingQueryString + "&extra=" + rnd());
                        currentRequest = $.get(
                                    "DmiAjaxSecure.aspx",
                                    shippingQueryString,
                                    function (shippingData) {
                                        $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html(shippingData.slice(shippingData.indexOf("DMI:AJAX:BEGIN") + 14, shippingData.indexOf("DMI:AJAX:END")));
                                        $("tr.orderTotalRow").css("display", "");
                                        $("tr#USTaxRow").css("display", "");
                                        requestCounter = requestCounter - 1;
                                        InvalidShippingMethodCheck();
                                    },
                                     "html"
                                 );
                    }
 
            }
        }
        else {
            $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html(strInitialTGContent);
            $("tr.orderTotalRow").css("display", "none");
            $("tr#USTaxRow").css("display", "none");
            //$("input[value=Submit Order]").css("display", "none");
            $(".required").attr("disabled", "");

        }
        
        valueChanged = false;
    }

function onRequestCompleted(xhr, textStatus) {
    $(".required").attr("disabled", "");
    if (xhr.status != 200) 
    { 
        errorCounter = errorCounter + 1;
        requestCounter = requestCounter - 1;
        if(errorCounter <= 2)
        {
            GetShippingInfo(true,true);
        }
        else
        {
            $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html(strInitialTGContent);
            $("tr.orderTotalRow").css("display", "none");
            $("tr#USTaxRow").css("display", "none");
            //$("input[value=Submit Order]").css("display", "none");
            errorCounter = 0;
        }
    }

    if (requestCounter <= 0) {
        $("input[value=Submit Order]").css("display", "");
    }
    
}

function GetBillingStates(countrycode, initialLoad) {
    if (countrycode == null || $.trim(countrycode) == "") {
        $("#billingstates").css("display", "none");
    }
    else {
        if (countrycode == "CA" || countrycode == "US" || countrycode == "BR" || countrycode == "AU") {
            var billingstaterequest = "request=billingstatecontent&cn=" + countrycode + "&extra=" + rnd();
            var billinglabel = "<label for='State' title='State'><span style='color:Red'>*</span>State / Province</label>";
            var initialState = "";

            if (initialLoad) {
                initialState = $.trim($("div#billingstates").html().replace("/n"));
            }

            $.get(
            "DmiAjaxSecure.aspx",
            billingstaterequest,
            function (pageData) {
                $("div#billingstates").html(billinglabel + pageData.slice(pageData.indexOf("DMI:AJAX:BEGIN") + 14, pageData.indexOf("DMI:AJAX:END")));
                $("#billingstates").css("display", "");
                ResetValidatious();
                $("select#State").bind('change', function () {
                    GetShippingInfo(true, false);
                });
                if (initialLoad) {
                    $("select#State").val(initialState);
                    GetShippingStates($("select#Country_SHIP").val(), true);
                }
            },
            "html"
            );
        }
        else {
            $("div#billingstates").html("<input name='State' id='State' type='hidden' value='NA' class='submitTG checkTradeGlobal' />");
            $("#billingstates").css("display", "none");
        }
    }

}

function GetShippingStates(countrycode, setShippingState) {
    if (countrycode == null || $.trim(countrycode) == "") {
        $("#shippingstates").css("display", "none");
    }
    else {
        if (countrycode == "CA" || countrycode == "US" || countrycode == "BR" || countrycode == "AU") {
            var shippingstaterequest = "request=shippingstatecontent&cn=" + countrycode + "&extra=" + rnd();
            var shippinglabel = "<label for='State_SHIP' title='State'><span style='color:Red'>*</span>State / Province</label>";
            $.get(
            "DmiAjaxSecure.aspx",
            shippingstaterequest,
            function (pageData) {
                $("div#shippingstates").html(shippinglabel + pageData.slice(pageData.indexOf("DMI:AJAX:BEGIN") + 14, pageData.indexOf("DMI:AJAX:END")));
                $("#shippingstates").css("display", "");
                if (setShippingState == true) {
                    $("#State_SHIP").val($("#State").val());
                }
                if (setShippingState == true) {
                    GetShippingInfo(true, false);
                }
                ResetValidatious();
                $("select#State_SHIP").bind('change', function () {
                    GetShippingInfo(true, false);
                });
            },
            "html"
            );
        }
        else {
            $("div#shippingstates").html("<input name='State_SHIP' id='State_SHIP' type='hidden' value='NA' class='submitTG checkTradeGlobal' />");
            $("#shippingstates").css("display", "none");
            if (setShippingState == true) {
                GetShippingInfo(true, false);
            } 
        }

    }

}

function displayLoadingImage() {
    var loadingHTML = "<td align='center' colspan='2'><img src='images/art/loading.gif' /><br />Getting Shipping Costs...</td>";
    $("table#shippingSummary.borders tr#SubmitOrderCartShippingRow").html(loadingHTML);
}

function InvalidShippingMethodCheck() {
    if (requestCounter <= 0 && ($("#Country_SHIP").val() != null))
    {
        if ($("#Country_SHIP").val() == "US") {
            if ($("shipping_method").val() == "1000009" || $("shipping_method").val() == "1000008" || $("shipping_method").val() == "1000010") {
                GetShippingInfo(true,false);
            }
        }
        else {
            if ($("shipping_method").val() == "1000001" || $("shipping_method").val() == "1000003" || $("shipping_method").val() == "1000007") {
                GetShippingInfo(true,false);
            }
        }
    }

}

function InitializeDomesticTotals() {

    $("#tgShippingMethod").val(selectedShippingMethod);
    var domesticShippingCharge = parseFloat($("#" + selectedShippingMethod + " span.domesticCharge").text().replace("$", ""));
    $("td#domesticShippingCharge").html("$" + domesticShippingCharge);

    var orderTotal = parseFloat(domesticShippingCharge);

    $("table#shippingSummary td.promotionCredits").each(function () {
        orderTotal = orderTotal - parseFloat($(this).text().replace("$", ""));
    });

    orderTotal = orderTotal + parseFloat($("tr#USTaxRow span#USTaxTotal").html().replace("$", ""));

    orderTotal = orderTotal + parseFloat($("table#shippingSummary td span#TretornItemsTotal").html().replace("$", ""));

    $("table#shippingSummary td span#TretornOrderTotal").html("$" + orderTotal.toFixed(2));

}

function InitializeTradeGlobalTotals() {

    $("#tgShippingMethod").val(selectedShippingMethod);

    var tradeGlobalShippingCharge = parseFloat($("li#" + selectedShippingMethod + " span.totalTradeGlobalShippingCosts").text().replace("$", ""));
    $("td#TradeGlobalCustomCharge").html("$" + tradeGlobalShippingCharge);

    var orderTotal = parseFloat(tradeGlobalShippingCharge);

    $("table#shippingSummary td.promotionCredits").each(function () {
        orderTotal = orderTotal - parseFloat($(this).text().replace("$", ""));
    });

    orderTotal = orderTotal + parseFloat($("table#shippingSummary td span#TretornItemsTotal").html().replace("$", ""));

    $("table#shippingSummary td span#TretornOrderTotal").html("$" + orderTotal.toFixed(2));

}


//Javascript function refreshes CheckoutCartContent. call GetShippingInfo to redisplay shipping controls, with new values if necessary.

$("div.TradeGlobalShippingMethods input").live("click", function () {
    selectedShippingMethod = this.value;
    InitializeTradeGlobalTotals();
});

$("div.domesticShippingMethods input[type=radio]").live("click", function () {
    selectedShippingMethod = this.value;
    InitializeDomesticTotals();
});

$("li.tgExpandCollapse").live("click", function () {
    $("li#" + this.id).css("list-style-image",
                    (!$("#" + this.id + " ul.tradeGlobalShippingBreakdown").is(":hidden")) ? "url(images/art/plusbox.gif)" : "url(images/art/minusbox.gif)");
    $("li#" + this.id + " ul.tradeGlobalShippingBreakdown").toggle("slow");
    return false;
});

//sets shipping address fields = to billing fields when checked. Clears the fields when unchecked.
$("#sameasbilling").live("click", function () {
   
    if ($("input#sameasbilling").is(":checked")) {       
        $("input#FName_SHIP").val($("input#FirstName").val());
        $("input#LName_SHIP").val($("input#LastName").val());
        $("input#Address1_SHIP").val($("input#Address1").val());
        $("input#Address2_SHIP").val($("input#Address2").val());
        $("input#City_SHIP").val($("input#City").val());
        $("select#State_SHIP").val($("select#State").val());
        $("input#PostalCode_SHIP").val($("input#PostalCode").val());
        $("input#Phone_SHIP").val($("input#Phone").val());
        $("select#Country_SHIP").val($("select#COUNTRY").val());
    }
    else {
        $("input#FName_SHIP").val("");
        $("input#LName_SHIP").val("");
        $("input#Address1_SHIP").val("");
        $("input#Address2_SHIP").val("");
        $("input#City_SHIP").val("");
        $("select#State_SHIP").val("");
        $("input#PostalCode_SHIP").val("");
        $("input#Phone_SHIP").val("");
        $("select#Country_SHIP").val("");
    }

    GetShippingStates($("select#COUNTRY").val(), true);
});


$("#applyKeyCode").live("click", function () {
    if ($.trim($("input[name=keycode]").val()) === "") {
        return false;
    }
    else {
        $(".required").attr("disabled", "");
        displayLoadingImage();
        var appliedKeyCode = $.trim($("input[name=keycode]").val());
        var keycodeQueryString = fixedEncodeURI("request=CheckOutCartItemsContent&keycode=" + appliedKeyCode + "&extra=" + rnd());
        $.get(
            "DmiAjaxSecure.aspx",
            keycodeQueryString,
            function (pageData) {
                $("span#CheckOutCartItemsContent").html(pageData.slice(pageData.indexOf("DMI:AJAX:BEGIN") + 14, pageData.indexOf("DMI:AJAX:END")));
                $("#currentKeyCode").val(appliedKeyCode);
                GetShippingInfo(true,false);
            },
            "html"
        );
    }
 });

 function fixedEncodeURI(str) {
     str = encodeURIComponent(str).replace(/%3D/g, '=').replace(/%26/g, '&').replace(/%40/g, '@');
     return str;
 }

function tgUpdateBillingInfo() {
    if ($.trim($("select[name=State]").val()) === "" || $.trim($("select[name=COUNTRY]").val()) === "" || $.trim($("input[name=PostalCode]").val()) === "") {
        $(".required").attr("disabled", "");
        return false;
        
    }
    else {
        displayLoadingImage();
        var keycodeQueryString = "request=CheckoutCartTotalContent&state_bill=" + $.trim($("select[name=State]").val()) + "&country_bill=" + $.trim($("select[name=COUNTRY]").val()) + "&zip_bill=" + $.trim($("input[name=PostalCode]").val()) + "&extra=" + rnd();
        $.get(
            "DmiAjaxSecure.aspx",
            keycodeQueryString,
            function (pageData) {
                $("span#CheckoutCartTotalContent").html(pageData.slice(pageData.indexOf("DMI:AJAX:BEGIN") + 14, pageData.indexOf("DMI:AJAX:END")));
                GetShippingInfo(true,false);
            },
            "html"
        );
    }
}
