// Dynamic slider-tab shopping cart code.
$(document).ready(function() {

    // The Webinfuse namespace is initialized in the document header

    Webinfuse.tax_row_template = '<tr class="dynamic_tax_row"><th>$NAME$</th><td class="dyn_tax_amount">$AMOUNT$</td></tr>';

    // *********** Utility methods  ******************
    Webinfuse.parse_vid = function(string_to_parse) {
        var start_ind = string_to_parse.indexOf("[");
        var end_ind = string_to_parse.indexOf("]");
        return string_to_parse.substring(start_ind + 1, end_ind);
    }


    Webinfuse.load_cart_tab = function(hide_details) {
        $("#cartTab").load('/cart/cart_tab', function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == 'success') {
                // JS is a really dynamic language; for instance, it will convert a
                // string to a numeric if you use the multiplication operator on the
                // string. The "items-count" element contains the number of items
                // in the user's cart as a string, so applying the * operator converts
                // it for us.
                if ($("#items-count").html() * 1 > 0) {
                    if (hide_details == true) {
                        $("#cartDetails").hide();
                    } else {
                        $("#cartDetails").show();
                    }
                    $("#cartPanel-1").show();
                    $("#cartTab").show();
                }

                // on-click of the checkout link in the cartTab, cancel event bubbling so
                // that the cartTab slider code above isn't triggered. Without this, clicking
                // the checkout shortcut link will slide the tab down first, which is a bit weird
                $("a.checkoutShortcutLink").click(function(event) {
                    event.stopPropagation();
                });
            }
        });
    }

    Webinfuse.continue_shopping_handler = function() {
        $("a.continueShopping").click(function(event) {
            event.preventDefault();
            if ($("#cartHasItems").length > 0) {
                $("#cartDetails").slideUp();
            } else {
                $("#cartDetails").slideUp();
                $("#cartPanel-1").fadeOut();
            }
        });
    }

    // Event handler for click events for line-item removal in the cart view. This is the general event-listener - it
    // delegates the main functionality for line-item removal to the Webinfuse.li_del_and_refresh_cart_details method.
    Webinfuse.remove_line_item_handler = function() {
        $(".remove-line-item").click(function(event) {
            event.preventDefault();
            // fire off a simple ajax request to nuke the line item,
            // then i guess refresh the entire inner cart view...
            var submit_to = $(this).attr("href");
            var vid = $(this).attr("id").split("-").pop();
            var li_id = submit_to.split("/").pop();
            Webinfuse.li_del_and_refresh_cart_details(li_id, vid);
        });
    }

    // deletes a line-item and update the cart details
    Webinfuse.li_del_and_refresh_cart_details = function(li_id, v_id) {
        var path_to_del = "/cart/delete/" + li_id;
        $("#cartDetails").load(path_to_del, function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == 'success') {
                $("#cartPanel-1").fadeIn();
                $("#cartTab").slideDown();
                Webinfuse.continue_shopping_handler();
                $("#tab-content").html($("#updated-tab-content").html());
                $("#add-to-cart-message").fadeIn();

                // apply a listener to the form events of the cart view form contained in the slide-down window
                Webinfuse.inner_cart_view_handler();
                Webinfuse.load_cart_tab(false);

                // need to remove the variant from the line_items collection as well
                delete Webinfuse.line_items["line_item_id_" + v_id];
                delete Webinfuse.line_items["line_item_quantity_" + v_id];
                var item_input = $("input[class*='productViewInput']");
                var vid = Webinfuse.parse_vid(item_input.attr("id"));
                if(v_id == vid){
                   Webinfuse.clean_up_after_delete();
                   item_input.val("");
                }

                var checkoutContainer = $("#ecomCheckout");
                if (checkoutContainer && checkoutContainer.hasClass("step2")) {
                    $(".continueShopping-1").hide();
                    $(".checkoutShortcutLink").each(function() {
                        $(this).text("continue");
                    });
                    $(".checkoutButtonLink").each(function() {
                        $(this).text("continue");
                    });
                    $("#orderSubmit").submit(function() {
                        alert("Please click on a 'continue' link in the cart tab in order to continue your checkout. On doing so, you will be taken back to step 1 of the checkout to re-confirm your details.");
                        return false;
                    });
                }
            }
        });
    }

    Webinfuse.close_notice = function() {
        $(".closeNotice").click(function(event) {
            event.stopPropagation();
            event.preventDefault();
            $("#cartDetails").slideUp();
            var item_flag = $("#cartHasItems");
            if (!item_flag.length > 0) {
                $("#cartPanel-1").fadeOut();
            }
        });
    }

    Webinfuse.synch_cart_items_with_view_items = function() {
        $(".lineItemInputs").each(function(i) {
            //var var_input_id = this.id.replace("line_item", "variant");
            var t = $(this);
            var vid = t.attr("variant_id");
            var var_input_id = "variant[" + vid + "][quantity]";
            var sid = "input:text[id='" + var_input_id + "']";
            var uz = $(sid);
            if (uz.length > 0) {
                uz.val(t.val());
            }
        });
    }

    Webinfuse.out_of_stock = function() {
        $("#cartSubmit").click(function(event) {
            if (out_of_stock) {
                alert("This item cannot be added to you cart as it is currently not in stock.");
            }
        });
    }

    Webinfuse.force_reload_on_checkout_edit = function() {
        var checkoutContainer = $("#ecomCheckout");
        if (checkoutContainer && checkoutContainer.hasClass("step2")) {
            $(".continueShopping-1").hide();
            $(".checkoutShortcutLink").each(function() {
                $(this).text("continue");
            });
            $(".checkoutButtonLink").each(function() {
                $(this).text("continue");
            });
            $("#orderSubmit").submit(function() {
                alert("Please click on a 'continue' link in the cart tab in order to continue your checkout. On doing so, you will be taken back to step 1 of the checkout to re-confirm your details.");
                return false;
            });
        }
    }

    // Handler for the cart-view update form (when you're looking at your cart and edit the quantity of one or more of the items).
    Webinfuse.inner_cart_view_handler = function() {
        // on-click of the checkout link in the cartTab, cancel event bubbling so
        // that the cartTab slider code above isn't triggered. Without this, clicking
        // the checkout shortcut link will slide the tab down first, which is a bit weird
        $("a.checkoutShortcutLink").click(function(event) {
            event.stopPropagation();
        });
        Webinfuse.remove_line_item_handler();
        Webinfuse.empty_cart_handler();
        Webinfuse.shipping_estimator_handler();
        Webinfuse.bind_state_prov_handler();
        Webinfuse.close_notice();
        $("form#cartDetailsForm").submit(function(event) {
            event.preventDefault();
            var form_details = $("form#cartDetailsForm").serialize();

            $("#cartDetails").load("/cart/index", form_details, function(responseText, textStatus, XMLHttpRequest) {
                if (textStatus == 'success') {
                    Webinfuse.continue_shopping_handler();
                    $("#tab-content").html($("#updated-tab-content").html());
                    Webinfuse.inner_cart_view_handler();
                    Webinfuse.synch_cart_items_with_view_items();
                    Webinfuse.force_reload_on_checkout_edit();
                    var item_input = $("input[class*='productViewInput']");
                    // update the details of the currently viewed item vis-a-vis its status in line_items
                    if(item_input.length > 0){
                        var vid = Webinfuse.parse_vid(item_input.attr("id"));
                        if(typeof(Webinfuse.line_items["line_item_id_"+vid]) != "undefined"){
                            var lis = Webinfuse.line_items["line_item_id_"+vid];
                            var quant = Webinfuse.line_items["line_item_quantity_"+vid];
                            item_input.val(quant);
                        } else {
                            // if it isn't present in line_items, make sure the input is for a variant
                             Webinfuse.clean_up_after_delete();
                            item_input.val("");
                            //$("#cartSubmit").val("add to cart");
                        }
                    }
                }
            });
        });
    }

    // Empty-cart handler.
    Webinfuse.empty_cart_handler = function() {
        $("#empty-cart").click(function(event) {
            event.preventDefault();
            $("#cartDetails").load("/cart/empty", function(responseText, textStatus, XMLHttpRequest) {
                if (textStatus == 'success') {
                    var checkoutContainer = $("#ecomCheckout");
                    if (checkoutContainer.length > 0 && checkoutContainer.hasClass("step2")) {
                        window.location = "/checkout/empty_cart";
                    } else {
                        Webinfuse.continue_shopping_handler();

                        // apply a listener to the form events of the cart view form contained in the slide-down window
                        Webinfuse.inner_cart_view_handler();
                        Webinfuse.load_cart_tab(false);
                        $("form#addToCartForm input:text").val("");
                        // empty the line_items collection
                        Webinfuse.line_items = {};
                        Webinfuse.clean_up_after_delete();
                    }
                }
            });
        });
    }

    Webinfuse.convert_item_input_to_variant = function() {
        var item_input = $("input[class*='productViewInput']");
        // need to change the name attribute. The data we need is contained in the id attr
        item_input.attr("name", item_input.attr("id"));
    }

    Webinfuse.clean_up_after_delete = function(){
        $("#cartSubmit").val("add to cart");
        $("#add-to-cart-message").fadeOut();
        $(".viewCart").fadeOut();
        $("#update-cart-message").fadeOut();
        // Also need to see if the current item input is a line-item one, and if it is convert it to a variant
         Webinfuse.convert_item_input_to_variant();
    }

    // retrieves shipping estimate with country/state data
    Webinfuse.estimate_for_address = function() {
        $("#ajaxLoadingAnimForShipping").show();
        var ship_form_details = $("form#shippingEstimatorForm").serialize();
        $.getJSON("/cart/shipping_and_taxes_estimate", ship_form_details, function(data, textStatus) {
            if (textStatus == 'success') {
                $("#shipping_form_wrapper").html('<p><span id="estimated_shipping_cost"></span></p><a href="#" id="edit_shipping_estimator_address">edit address</a>');
                $("#shipping_estimater_header").html(data["shipping_header"]);
                // check for the no-rate element
                var no_available_rate = data["destination_not_supported"];

                if (!no_available_rate) {
                    $("#shipping_amount").html(data["shipping_estimate"]);
                    $("#estimated_shipping_cost").html(data["shipping_estimate"]);
                    $("#tax_row").remove();
                    $(".dynamic_tax_row").remove();
                    jQuery.each(data["taxes"], function(k, v) {
                        var trt = new String(Webinfuse.tax_row_template);
                        trt = trt.replace("$NAME$", k);
                        trt = trt.replace("$AMOUNT$", v);
                        $("#shipping_row").after(trt);
                    });
                    $("#cart_total_amount").html(data["grand_total"]);

                    $(".dyn_tax_amount").each(function() {
                        $(this).format({format:"$###.00", locale:"us"});
                    });

                } else {
                    $("#shipping_amount").html("TBD");
                    $("#estimated_shipping_cost").html(data["shipping_estimate"]);
                }
                $("#ajaxLoadingAnimForShipping").hide();
                Webinfuse.reload_shipping_estimator();
            } else {
                window.location = "/cart/error_notice";
            }
        });
    }

    Webinfuse.reload_shipping_estimator = function() {
        $("#edit_shipping_estimator_address").click(function() {
            $("#shipping_form_wrapper").load("/cart/shipping_estimate_reload", function(responseText, textStatus, XMLHttpRequest) {
                if (textStatus == 'success') {
                    $(".dynamic_tax_row").remove();
                    var trt = new String(Webinfuse.tax_row_template);
                    trt = trt.replace("$NAME$", "Taxes");
                    trt = trt.replace("$AMOUNT$", "TBD");
                    $("#shipping_row").after(trt);
                    $("#shipping_estimater_header").html("Estimate Shipping <span id='ajaxLoadingAnimForShipping' style='display:none;' ><img src='/plugin_assets/pws/design/images/ajax-loader.gif' /></span>");
                    $("#shipping_amount").html("TBD");
                    $("#tax_amount").html("TBD");
                    $("#cart_total_amount").html($("#cart_subtotal_amount").html());
                    Webinfuse.shipping_estimator_handler();
                }
            });
        });
    }

    Webinfuse.shipping_estimator_handler = function() {
        // Need seperate listeners for the country-select and state/prov select
        // since some estimates will -only- use country data, while others
        // use both
        $("#address_countryCode").change(function(event) {
            var country = $("#address_countryCode").val();
            var cloned_selectors;
            if (country == "CA") {
                $("#state_prov_select").empty();
                cloned_selectors = $("#can_provs").clone(true);
                $("#state_prov_select").append(cloned_selectors);
                $("#state_prov_select #can_provs").show();
            } else if (country == "US") {
                $("#state_prov_select").empty();
                cloned_selectors = $("#amer_provs").clone(true);
                $("#state_prov_select").append(cloned_selectors);
                $("#state_prov_select #amer_provs").show();
            } else if (country == "-") {
                $("#state_prov_select").empty();
            } else {
                Webinfuse.estimate_for_address();
            }
        });
    }

    Webinfuse.bind_state_prov_handler = function() {
        $(".stateProvSelect").change(function(event) {
            Webinfuse.estimate_for_address();
        });
    }

    Webinfuse.cart_tab_slider = function(event) {
        if(typeof(event) != "undefined"){
            event.preventDefault();
        }

        if ($("#cartDetails").html() == "") {
            $("#cartDetails").load('/cart/index', function(responseText, textStatus, XMLHttpRequest) {
                if (textStatus == 'success') {
                    $("#cartDetails").slideDown();
                    Webinfuse.inner_cart_view_handler();
                    Webinfuse.continue_shopping_handler();
                }
            });

        } else {
            $("#cartDetails").slideDown();
        }
    }

    Webinfuse.show_ajax_anim = function() {
        $("#ajaxLoadingAnim").show();
        $('input:submit').attr({ disabled : true });
    }

    Webinfuse.hide_ajax_anim = function() {
        $("#ajaxLoadingAnim").hide();
        $('input:submit').attr({ disabled : false });
    }

    // ************** Main work-flow mechanics  *****************************

    // Ping the server for the current user's cart stats, and populate the tab-view template with whatever is there. If
    // there is anything in his/her cart, show the tab. Note: the cart isn't loaded (by default) on the final_details page.
    if ($("div#checkoutFlag").length == 0) {
        Webinfuse.load_cart_tab(true);
    }

    $(".viewCartForEdit").click(function(event) {
        window.location = "/checkout?vt=1";
    });

    var edit_mode = $("#checkoutEditMode");
    if(typeof(edit_mode) != "undefined" && edit_mode.length > 0){
        var mode = edit_mode.html();
        if(mode == "display"){
          Webinfuse.load_cart_tab(false);
          Webinfuse.cart_tab_slider();
        }
    }

    // bind a listener to the add-to-cart form. On submit, intercept and handle it with ajax.
    $("form#addToCartForm").submit(function(event) {
        event.preventDefault();

        var item = $(".productViewInput");
        var quantity_to_submit;
        if (item.length > 0) {
            var inputValue = jQuery.trim(item.val());
            if (inputValue == "") {
                item.val("1");
                quantity_to_submit = 1;
            } else if (!inputValue.match(/^[\d]+$/)) {
                alert("Please note: Only numbers are permitted in quantity box.");
                return;
            } else {
                quantity_to_submit = parseInt(inputValue);
            }
        }

        var variantItems = $(".variantCartQuantity");
        var alertCustomer = false;
        var blanks = 0;
        var bad_format = false;
        if (variantItems.length > 0) {
            variantItems.each(function(i) {
                var currentInputValue = jQuery.trim(this.value);
                if (!currentInputValue.match(/^[\d]+$/) && currentInputValue != "") {
                    this.value = "";
                    alertCustomer = true;
                    bad_format = true;
                } else if (currentInputValue == "") {
                    alertCustomer = true;
                    blanks++;
                }
            });
        }

        if (alertCustomer && bad_format) {
            alert("Please note: Only numbers are permitted in quantity box.");
            return;
        } else if (alertCustomer && blanks == variantItems.length) {
            alert("Please enter a quantity before attempting adding an item to your cart.");
            return;
        }

        var form_details = $("form#addToCartForm").serialize();
        Webinfuse.show_ajax_anim();
        // need to make the url part conditional on the add/edit mode
        var url_to;
        var is_update = false;
        if ($("#cartSubmit").val() == 'add to cart') {
            url_to = "/cart/add";
        } else {
            url_to = "/cart/";
            is_update = true;
        }
        $("#cartDetails").load(url_to, form_details, function(responseText, textStatus, XMLHttpRequest) {
            if (textStatus == 'success' && $.string(responseText).include("<h1>Error Notice</h1>")) {
                $("#cartPanel-1").fadeIn();
                $("#cartTab").slideDown();
                Webinfuse.continue_shopping_handler();
                $("#cartDetails").slideDown();
                Webinfuse.close_notice();
                Webinfuse.hide_ajax_anim();
            } else if (textStatus == 'success') {
                $("#cartPanel-1").fadeIn();
                $("#cartTab").slideDown();
                Webinfuse.continue_shopping_handler();
                $("#tab-content").html($("#updated-tab-content").html());
                if (is_update) {
                    $("#add-to-cart-message").fadeOut();
                    $("#update-cart-message").fadeIn();
                } else {
                    $("#add-to-cart-message").fadeIn();
                }
                $(".viewCart").fadeIn();
                Webinfuse.hide_ajax_anim();
                // apply a listener to the form events of the cart view form contained in the slide-down window
                Webinfuse.inner_cart_view_handler();

                // Embed the line_item id in the response text. Scrape it out here and update the Webinfuse.line_items var.
                var item_input = $("input[class*='productViewInput']");
                var vid = Webinfuse.parse_vid(item_input.attr("id"));
                if (typeof( Webinfuse.line_items) != "undefined") {
                    if (typeof( Webinfuse.line_items["line_item_id_" + vid]) != "undefined") {
                        Webinfuse.line_items["line_item_quantity_" + vid] = quantity_to_submit;
                    } else {
                        var new_li = $("#newItemId").html();
                        Webinfuse.line_items["line_item_id_" + vid] = new_li;
                        Webinfuse.line_items["line_item_quantity_" + vid] = quantity_to_submit;
                        Webinfuse.item_edit_mode = true;
                        $("#cartSubmit").val("update cart");
                    }
                }
            }
        });
    });

    // The cart tab handler for sliding the tab up and down.
    $("#cartTab").click(function(event) {
        Webinfuse.cart_tab_slider(event);
    });

    $(".viewCart").click(function(event) {
        Webinfuse.cart_tab_slider(event);
    });

});
