// JavaScript Document

function collapseAll() {
    document.getElementById("product_1_readMoreButton").style.display = "block";
    document.getElementById("product_2_readMoreButton").style.display = "block";
    document.getElementById("product_3_readMoreButton").style.display = "block";

    document.getElementById("product_1_description").style.display = "none";
    document.getElementById("product_2_description").style.display = "none";
    document.getElementById("product_3_description").style.display = "none";
}

function expand(id) {
    collapseAll();

    document.getElementById("product_" + id + "_readMoreButton").style.display = "none";
    document.getElementById("product_" + id + "_description").style.display = "block";
}

var ajax_obj, ajax_response_div, ajax_progress_msg, ajax_error_msg;

ajax_response_div = null;

function AJAX_sendAndLoad(script, vars) {
    ajax_obj = createAjaxObject();

    if (ajax_obj != false) {
        ajax_obj.onreadystatechange = AJAX_parseServerResponse;
        ajax_obj.open("POST", script + "?randID=" + parseInt(Math.random()*99999999), true);
        ajax_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajax_obj.send(vars);
    } else {
        if (ajax_response_div !== null) {
            ajax_response_div.innerHTML = "Your browser does not support AJAX.";
        }
    }
}

function AJAX_parseServerResponse() {
    if (ajax_obj.readyState == 4) {
        if (ajax_obj.status == 200) {
            var xmlDoc;
            if (window.DOMParser) {
                var parser = new DOMParser();
                xmlDoc = parser.parseFromString(ajax_obj.responseText, "text/xml");
            } else {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(ajax_obj.responseText);
            }

            var displayMessage = new Object();
            var displayMessage_element = xmlDoc.getElementsByTagName("displayMessage")[0];

            displayMessage.successMessage = displayMessage_element.getElementsByTagName("successMessage")[0].childNodes[0].nodeValue;

            var message;

            message = displayMessage.successMessage;

            ajax_response_div.innerHTML = message;

            var commands = Array();
            var commands_element = xmlDoc.getElementsByTagName("commands")[0];

            for (var command = 0; command < commands_element.childNodes.length; command++) {
                if (commands_element.childNodes[command].nodeType == 1) {
                    var command_name = commands_element.childNodes[command].nodeName;
                    var command_value = commands_element.childNodes[command].childNodes[0].nodeValue;

                    if (command_name == "addItemToCart") {

                        command_values = command_value.split(",");
                        var item_number = command_values[0];
                        var item_id = command_values[1];
                        var item_qty = command_values[2];

                        showNewCartItem(item_number, item_id, item_qty);

                        document.getElementById("product_" + item_id + "_addToCartButton").style.display = "block";
                        document.getElementById("product_" + item_id + "_addingToCartText").style.display = "none";

                        ajax_response_div = null;

                    } else if (command_name == "updateCartItem") {

                        command_values = command_value.split(",");
                        var item_number = command_values[0];
                        var item_id = command_values[1];
                        var item_qty = command_values[2];

                        updateCartItem(item_number, item_id, item_qty);

                        document.getElementById("product_" + item_id + "_addToCartButton").style.display = "block";
                        document.getElementById("product_" + item_id + "_addingToCartText").style.display = "none";

                        ajax_response_div = null;

                    } else if (command_name == "removeItemFromCart") {

                        var item_number = command_value;

                        collapseItem("cart_item_" + item_number, false);

                        ajax_response_div = null;

                    } else if (command_name == "updateCartTotal") {

                        var totalprice_float = parseFloat(command_value);
                        var url = String(window.location);

                        document.getElementById("cart-total-price").innerHTML = command_value;

                        document.getElementById("cart-total-calculating").style.display = "none";
                        document.getElementById("cart-total-calculated").style.display = "block";

                        if (url.indexOf("cart.php", url.lastIndexOf("/") + 1) > -1) {
                            document.getElementById("cart-total-calculated").innerHTML = "<span style=\"font-size:12px; font-weight:normal; color:#990000;\">NOTE: Your total has been updated.</span> <a href=\"#\" onclick=\"loadCartBackup(); return false;\">Undo Changes</a> &gt;&gt; TOTAL: <span style=\"font-size:18px;\">$<span id=\"cart-total-price\">" + command_value + "</span></span>";
                        }

                        if (totalprice_float == 0) {
                            collapseItem("cart-totals", true);
                            expandItem("cart-empty", false);

                            if (url.indexOf("cart.php", url.lastIndexOf("/") + 1) > -1) {
                                document.getElementById("pp_submit_btn").style.display = "none";
                                document.getElementById("pp_submit_btnDisabled").style.display = "inline-block";

                                document.getElementById("dd_submit_btn").disabled = "disabled";

                                //window.location.reload(true);
                                //collapseItem("temp", false);
                            }
                        }

                    } else if (command_name == "submitPPForm") {

                        if (command_value) {
                            submitPPForm(2, command_value);

                            ajax_response_div = null;
                        }

                    } else if (command_name == "submitDDForm") {

                        submitDDForm(2);

                    }
                }
            }

        } else {
            if (ajax_response_div !== null) {
                if (ajax_error_msg != "") {
                    ajax_response_div.innerHTML = ajax_error_msg;
                }
            }
        }
    } else {
        if (ajax_response_div !== null) {
            if (ajax_progress_msg != "") {
                ajax_response_div.innerHTML = ajax_progress_msg;
            }
        }
    }
}

function formatAsCurrency(float) {
    var price;

    if (isNaN(parseFloat(float))) {
        price = "0.00";
    } else {
        price = parseFloat(float);

        if (price < 0.01) {
            price = "0.00";
        } else {

            // Format to 2 decimal places

            price = Math.round(price * 100) / 100;
            price_cents_str = String(Math.round((price - Math.floor(price)) * 100) / 100);
            if (price_cents_str.length == 3) {
                price = String(price) + "0";
            } else if (price_cents_str.length == 1) {
                price = String(price) + ".00";
            } else {
                price = String(price);
            }

            // Format with comma-separated thousands

            var number_parts, dollars, cents, formatted_dollars, loop_limit;

            number_parts = price.split(".");
            dollars = number_parts[0];
            cents = number_parts[1];
            formatted_dollars = "";
            loop_limit = 15;

            while (dollars.length > 3 && loop_limit > 0) {
                formatted_dollars = "," + dollars.slice(dollars.length - 3, dollars.length) + formatted_dollars;
                dollars = dollars.slice(0, dollars.length - 3);
                loop_limit--;
            }
            formatted_dollars = dollars + formatted_dollars;

            price = formatted_dollars + "." + cents;
        }
    }

    return price;
}

function calcPrices(item_id, qty) {
    var prices = new Object();

    var unit_price, single_unit_price;

    var unitPrice, totalPrice, discount;

    if (isNaN(parseFloat(qty))) {
        unitPrice = "0.00";
        totalPrice = "0.00";
        discount = "0.00";
    } else {
        qty = Math.abs(Math.floor(parseFloat(qty)));

        if (qty == 1 || qty == 2) {
            unit_price = products_arr[item_id]["qty_" + qty + "_unitPrice"];
        } else {
            unit_price = products_arr[item_id]["qty_3plus_unitPrice"];
        }
        single_unit_price = products_arr[item_id]["qty_" + 1 + "_unitPrice"];

        if (isNaN(parseFloat(unit_price)) || isNaN(parseFloat(single_unit_price))) {
            unitPrice = "0.00";
            totalPrice = "0.00";
            discount = "0.00";
        } else {
            unit_price = parseFloat(unit_price);
            single_unit_price = parseFloat(single_unit_price);

            unitPrice = formatAsCurrency(unit_price);
            totalPrice = formatAsCurrency(unit_price * qty);
            discount = formatAsCurrency((single_unit_price * qty) - (unit_price * qty));
        }
    }

    prices.unitPrice = unitPrice;
    prices.totalPrice = totalPrice;
    prices.discount = discount;

    return prices;
}

function updatePricePreview(id) {
    var qty;

    qty = document.getElementById("product_" + id + "_qty").value;

    var prices;

    prices = calcPrices(id, qty);

    document.getElementById("product_" + id + "_calculatedPrice").innerHTML = prices.totalPrice;
    document.getElementById("product_" + id + "_calculatedDiscount").innerHTML = prices.discount;
}

function updateCartPrices(id) {

    var qty;

    if(id != null) //this is for when the user clicks a check box for postage.
        {
        qty = document.getElementById("product_" + id + "_qty").value;

        var prices;

        prices = calcPrices(id, qty);

        document.getElementById("cartItem_" + id + "_price").innerHTML = prices.totalPrice;
    }

    var done = false;
    var totalPrice = 0;

    for (var i = 0; i < 200 && !done; i++) {
        var element_id_holder = document.getElementById("cart_item_" + i + "_id");
        if (element_id_holder === null) {
            done = true;
        } else {
            var element_id = element_id_holder.value;

            if (document.getElementById("cart_item_" + i).style.display.toLowerCase() != "none") {
                qty = document.getElementById("product_" + element_id + "_qty").value;

                prices = calcPrices(element_id, qty);

                totalPrice += Number(prices.totalPrice.split(",").join(""));
            }
        }
    }

    if (totalPrice == 0) {
        document.getElementById("pp_submit_btn").style.display = "none";
        document.getElementById("pp_submit_btnDisabled").style.display = "inline-block";

        document.getElementById("dd_submit_btn").disabled = "disabled";
    } else {
        document.getElementById("pp_submit_btn").style.display = "inline-block";
        document.getElementById("pp_submit_btnDisabled").style.display = "none";

        document.getElementById("dd_submit_btn").disabled = false;
    }

    if(document.getElementById("_standardPost") != null)
        {
        if(document.getElementById("_standardPost").checked == true)
            {
            totalPrice += 7;
        }
        else
            {
            totalPrice += 9;
        }
    }
    totalPrice = formatAsCurrency(totalPrice);


    document.getElementById("cart-total-calculated").innerHTML = "<span style=\"font-size:12px; font-weight:normal; color:#990000;\">NOTE: Your total has been updated.</span> <a href=\"#\" onclick=\"loadCartBackup(); return false;\">Undo Changes</a> &gt;&gt; TOTAL: <span style=\"font-size:18px;\">$<span id=\"cart-total-price\">" + totalPrice + "</span></span>";
}

function addProductToCart(id) {
    if (ajax_response_div === null) {

        var qty;
        qty = document.getElementById("product_" + id + "_qty").value;

        qty = Number(qty);
        if (!isNaN(qty)) {
            qty = Math.floor(qty);
            if (qty > 0) {
                ajax_response_div = document.getElementById("product_" + id + "_status");
                ajax_progress_msg = "Adding item to cart...";
                ajax_error_msg = "Item could not be added.";

                if (document.getElementById("cart-items").style.display == "none") {
                    document.getElementById("cart-items").style.display = "block";
                }

                if (document.getElementById("cart-empty").style.display == "block") {
                    collapseItem("cart-empty", true);
                    expandItem("cart-totals", false);
                }

                document.getElementById("product_" + id + "_addToCartButton").style.display = "none";
                document.getElementById("product_" + id + "_addingToCartText").style.display = "block";
                document.getElementById("cart-total-calculating").style.display = "block";
                document.getElementById("cart-total-calculated").style.display = "none";

                AJAX_sendAndLoad("includes/ajax/addProductToCart.php", "id=" + id + "&qty=" + qty);
            }
        }
    }
}

function removeProductFromCart(item_number) {
    if (ajax_response_div === null) {
        ajax_response_div = document.getElementById("cart_item_" + item_number + "_status");
        ajax_progress_msg = "Removing...";
        ajax_error_msg = "Error.";

        ajax_response_div.style.display = "block";

        document.getElementById("cart-total-calculating").style.display = "block";
        document.getElementById("cart-total-calculated").style.display = "none";

        AJAX_sendAndLoad("includes/ajax/removeProductFromCart.php", "item_number=" + item_number);
    }
}

function loadCartBackup() {
    var df = document.createElement("form");
    df.setAttribute("method", "post");
    df.setAttribute("action", "cart.php");
    document.body.appendChild(df);

    var i_cmd = document.createElement("input");
    i_cmd.setAttribute("type", "hidden");
    i_cmd.setAttribute("name", "undoCartChanges");
    i_cmd.setAttribute("value", 1);
    df.appendChild(i_cmd);

    df.submit();
}

function submitPPForm(stage, encryptedPostData) {
    document.getElementById("pp_newsletter").disabled = "disabled";
    document.getElementById("pp_email").readOnly = "readonly";

    document.getElementById("pp_submit_btn").style.display = "none";
    document.getElementById("pp_submit_btnDisabled").style.display = "inline-block";

    if (stage == 1) {
        if (ajax_response_div === null) {
            ajax_response_div = document.getElementById("pp_submitting_msg");
            ajax_progress_msg = "Submitting...";
            ajax_error_msg = "Error.";

            var done = false;
            var vars = "";
            var totalItems = 0;

            for (var i = 0; i < 200 && !done; i++) {
                var element_id_holder = document.getElementById("cart_item_" + i + "_id");
                if (element_id_holder === null) {
                    done = true;
                } else {
                    var element_id = element_id_holder.value;

                    if (document.getElementById("cart_item_" + i).style.display.toLowerCase() != "none") {
                        qty = document.getElementById("product_" + element_id + "_qty").value;
                        if (isNaN(parseFloat(qty))) {
                            qty = 0;
                        } else {
                            qty = Math.abs(Math.floor(parseFloat(qty)));
                        }

                        if (qty == 0) {
                            document.getElementById("cart_item_" + i).style.display = "none";
                        }

                        vars += "&item_" + i + "_id=" + element_id;
                        vars += "&item_" + i + "_qty=" + qty;

                        totalItems += qty;
                    }
                }
            }

            vars = "cartItems=" + (i - 1) + "&totalItems=" + totalItems + vars;

            if (document.getElementById("pp_newsletter").checked) {
                vars = vars + "&newsletter=" + escape(document.getElementById("pp_email").value);

                var newsletter_email_host = document.getElementById("pp_email").value;
                newsletter_email_host = newsletter_email_host.slice(newsletter_email_host.lastIndexOf("@") + 1);
                newsletter_email_host = newsletter_email_host.toLowerCase();

                if (newsletter_email_host.indexOf("hotmail.com") === 0 || newsletter_email_host.indexOf("live.com") === 0 || newsletter_email_host.indexOf("msn.com") === 0) {
                    alert("Please add \"newsletter@vitalhealthchoices.com.au\" to your email address book\nto prevent our newsletters being filtered as spam.\nThank you.");
                }
            }

            if(document.getElementById("_standardPost") != null)
            {
                if(document.getElementById("_standardPost").checked == false)
                {
                    vars+="&standard_post=0";
                }
                else
                {
                     vars+="&standard_post=1";
                }
            }

            vars = vars + "&paypal=1";

            AJAX_sendAndLoad("includes/ajax/updateCart.php", vars);
        }
    } else if (stage == 2) {
        document.getElementById("pp_submitting_msg").innerHTML = "Processing...";

        document.getElementById("pp_encryptedPostData").value = encryptedPostData;

        document.getElementById("pp_form").submit();

        /*document.getElementById("pp_submitting_msg").innerHTML = "";

        document.getElementById("pp_newsletter").disabled = false;
        document.getElementById("pp_email").readOnly = false;

        document.getElementById("pp_submit_btn").style.display = "inline-block";
        document.getElementById("pp_submit_btnDisabled").style.display = "none";*/
    }
}

function submitDDForm(stage) {
    document.getElementById("dd_name_first").readOnly = "readonly";
    document.getElementById("dd_name_last").readOnly = "readonly";
    document.getElementById("dd_email").readOnly = "readonly";
    document.getElementById("dd_newsletter_1").disabled = "disabled";
    document.getElementById("dd_newsletter_2").disabled = "disabled";
    document.getElementById("dd_address_1").readOnly = "readonly";
    document.getElementById("dd_address_2").readOnly = "readonly";
    document.getElementById("dd_city").readOnly = "readonly";
    document.getElementById("dd_state_select").disabled = "disabled";
    document.getElementById("dd_postcode").readOnly = "readonly";
    document.getElementById("dd_phone").readOnly = "readonly";

    document.getElementById("dd_submit_btn").disabled = "disabled";
    document.getElementById("_standardPost").disabled = "disabled";
    // you don't really need to update the cart if it hasn't changed.
    if (stage == 1) {
        if (false) {
            stage = 2;
        }
    }

    if (stage == 1) {
        if (ajax_response_div === null) {
            ajax_response_div = document.getElementById("dd_submitting_msg");
            ajax_progress_msg = "Submitting...";
            ajax_error_msg = "Error.";

            var done = false;
            var vars = "";
            var totalItems = 0;

            for (var i = 0; i < 200 && !done; i++) {
                var element_id_holder = document.getElementById("cart_item_" + i + "_id");
                if (element_id_holder === null) {
                    done = true;
                } else {
                    var element_id = element_id_holder.value;

                    if (document.getElementById("cart_item_" + i).style.display.toLowerCase() != "none") {
                        qty = document.getElementById("product_" + element_id + "_qty").value;
                        if (isNaN(parseFloat(qty))) {
                            qty = 0;
                        } else {
                            qty = Math.abs(Math.floor(parseFloat(qty)));
                        }

                        vars += "&item_" + i + "_id=" + element_id;
                        vars += "&item_" + i + "_qty=" + qty;

                        totalItems += qty;
                    }
                }
            }


            if(document.getElementById("_standardPost") != null)
                {

                if(document.getElementById("_standardPost").checked == false)
                {
                    vars+="&standard_post=0";
                }
                else
                {
                     vars+="&standard_post=1";
                }

            }

            vars = "cartItems=" + (i - 1) + "&totalItems=" + totalItems + vars;
            AJAX_sendAndLoad("includes/ajax/updateCart.php", vars);

        }
    } else if (stage == 2) {
        document.getElementById("dd_submitting_msg").innerHTML = "Processing...";

        if (document.getElementById("dd_newsletter_1").checked) {
            document.getElementById("dd_newsletter").value = 1;
        } else {
            document.getElementById("dd_newsletter").value = 0;
        }
        document.getElementById("dd_state").value = document.getElementById("dd_state_select").value;

        document.getElementById("dd_form").submit();
    }
}

function showNewCartItem(item_number, item_id, item_qty) {
    var title = products_arr[item_id].title;
    var image = products_arr[item_id].image;
    var prices = calcPrices(item_id, item_qty);
    var totalPrice = prices.totalPrice;

    var item_div = document.createElement("div");
    item_div.id = "cart_item_" + item_number;
    item_div.style.margin = "2px 0 2px 0";
    item_div.style.backgroundColor = "#DDDDDD";
    item_div.style.position = "relative";

    var item_status_div = document.createElement("div");
    item_status_div.id = "cart_item_" + item_number + "_status";
    item_status_div.style.position = "absolute";
    item_status_div.style.width = "178px";
    item_status_div.style.height = "25px";
    item_status_div.style.top = "10px";
    item_status_div.style.left = "25px";
    item_status_div.style.backgroundColor = "#CC9999";
    item_status_div.style.textAlign = "center";
    item_status_div.style.display = "none";

    item_div.appendChild(item_status_div);

    var item_graphics_1_div = document.createElement("div");
    item_graphics_1_div.style.width = "232px";
    item_graphics_1_div.style.height = "4px";
    item_graphics_1_div.style.backgroundImage = "url(images/cart-item_01.jpg)";
    item_graphics_1_div.style.backgroundRepeat = "no-repeat";

    item_div.appendChild(item_graphics_1_div);

    var item_graphics_2_div = document.createElement("div");
    item_graphics_2_div.style.width = "232px";
    item_graphics_2_div.style.backgroundImage = "url(images/cart-item_02.jpg)";
    item_graphics_2_div.style.backgroundRepeat = "repeat-y";

    item_div.appendChild(item_graphics_2_div);

    var item_table = document.createElement("table");
    item_table.width = "100%";
    item_table.border = "0";
    item_table.cellPadding = "2";
    item_table.cellSpacing = "2";

    var item_table_row_1 = item_table.insertRow(0);

    var item_table_cell_1 = item_table_row_1.insertCell(0);
    item_table_cell_1.width = "50";
    item_table_cell_1.vAlign = "top";
    item_table_cell_1.innerHTML = "<img src=\"images/product_images/sample_50x50/" + image + "\" alt=\"" + title + "\" width=\"50\" height=\"50\" />";

    var item_table_cell_2 = item_table_row_1.insertCell(1);
    item_table_cell_2.vAlign = "top";
    item_table_cell_2.innerHTML = "<div id=\"cart_item_" + item_number + "_content\"><div style=\"color:#7E574F; font-size:13px;\">" + title + "</div>" +
    "<div style=\"width:100%; height:0.75em;\"></div>" +
    "<div>" + item_qty + " Box" + (item_qty > 1 ? "es" : "") + " - <strong>$" + totalPrice + "</strong> <span style=\"font-size:10px;\"><a href=\"#\" onclick=\"removeProductFromCart(" + item_number + "); return false;\">[remove]</a></span></div></div>";

    item_graphics_2_div.appendChild(item_table);

    var item_graphics_3_div = document.createElement("div");
    item_graphics_3_div.style.width = "232px";
    item_graphics_3_div.style.height = "4px";
    item_graphics_3_div.style.backgroundImage = "url(images/cart-item_03.jpg)";
    item_graphics_3_div.style.backgroundRepeat = "no-repeat";

    item_div.appendChild(item_graphics_3_div);

    document.getElementById("cart-items").appendChild(item_div);

    expandItem(item_div.id, false);

}

function updateCartItem(item_number, item_id, item_qty) {
    var title = products_arr[item_id].title;
    var prices = calcPrices(item_id, item_qty);
    var totalPrice = prices.totalPrice;

    var cart_item_content = document.getElementById("cart_item_" + item_number + "_content");
    cart_item_content.innerHTML = "<div style=\"color:#7E574F; font-size:13px;\">" + title + "</div>" +
    "<div style=\"width:100%; height:0.75em;\"></div>" +
    "<div>" + item_qty + " Box" + (item_qty > 1 ? "es" : "") + " - <strong>$" + totalPrice + "</strong> <span style=\"font-size:10px;\"><a href=\"#\" onclick=\"removeProductFromCart(" + item_number + "); return false;\">[remove]</a></span></div>";

    var item_div = document.getElementById("cart_item_" + item_number);

    if (cart_item_content.offsetHeight > 50) {
        item_div.style.height = (cart_item_content.offsetHeight + 16) + "px";
    } else {
        item_div.style.height = (50 + 16) + "px";
    }
}

