var total_order_cost = 0;
var shipping_destination = 1;
var credit_card_validations = new Hash();
var webmoney_validations = new Hash();
var customer_validations = new Hash();
var customer_email = true;
var customer_phone = false;
var customer_agreement = false;
var customer_location = false;

function update_location(location) {
    $("deliveryLoc").update(location.value.split("|")[1]);
}

function update_shipping() {
    var shipping_type = Form.getInputs("purchase_form","radio","cart[shipping_type]").find(function(radio) { return radio.checked; }).value;
    var fDeliveryCost = parseFloat($("cart_shipping_cost_" + shipping_type).value);
    $$("#deliveryCost .money")[0].update(format_money(fDeliveryCost) + " руб.");
    var fTotalCost = parseFloat($("totalCostNoDelivery").value) + fDeliveryCost;
    $$("#totalCost .money")[0].update(format_money(fTotalCost) + " руб.");
    total_order_cost = fTotalCost;
    update_deposit();
}

function update_pay_info() {
    var payment_type = Form.getInputs("payment_form", "radio", "order[payment_type]").find(function(radio) { return radio.checked; }).value;
    var payment_type = $("pay_info_" + payment_type);

    $$(".pay_info").invoke("hide");
    if (payment_type) {
        payment_type.show();
    }
    if ($("deposit_table")) {
        if (payment_type != "1") {
            $("deposit_table").hide();
        } else {
            $("deposit_table").show();
            update_deposit();
        }
    }
    try {
        if (customer_email == false) {
            customer_email = new LiveValidation("customer_email", { validMessage: "", onlyOnBlur: true });
            customer_email.add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            customer_email.add(Validate.Email, { failureMessage: "Адрес электронной почты неправильного формата" });
        }
        if (customer_phone == false) {
            customer_phone = new LiveValidation("customer_phone_home", { validMessage: "", onlyOnBlur: true });
            customer_phone.add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            customer_phone.add(Validate.Length, {minimum: 3, maximum: 40, tooShortMessage: "Поле должно быть заполнено" });
            customer_phone.add(Validate.Format, {pattern: /^\s+$/, negate: true, failureMessage: "Поле должно быть заполнено" });
        }
        if (customer_agreement == false) {
            customer_agreement = new LiveValidation("customer_agreement", { validMessage: "" });
            customer_agreement.add( Validate.Acceptance, { failureMessage: "Вы должны ознакомиться и согласиться с условиями соглашения о предоставлении услуг" } );

        }

        // No address required for cash payment
        if ($('order_payment_type_1') && $('order_payment_type_1').checked == true) {
            customer_validations.each(function(pair) {
                pair.value.destroy();
                customer_validations.unset(pair.key);
            });
            customer_location = new LiveValidation("location", { validMessage: "", onlyOnBlur: true });
            customer_location.add(Validate.Exclusion, { within: ['-1'], failureMessage: "Пожалуйста, выберите пункт доставки" });
        } else {
            if (customer_location != false) {
                customer_location.destroy();
            }
            customer_validations.set("first_name", new LiveValidation("customer_first_name", { validMessage: "", onlyOnBlur: true }));
            customer_validations.get("first_name").add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            customer_validations.set("last_name", new LiveValidation("customer_last_name", { validMessage: "", onlyOnBlur: true }));
            customer_validations.get("last_name").add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            customer_validations.set("postal_code", new LiveValidation("customer_postal_code", { validMessage: "", onlyOnBlur: true }));
            customer_validations.get("postal_code").add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            //customer_validations.set("region", new LiveValidation("customer_region", { validMessage: "" }));
            //customer_validations.get("region").add(Validate.Exclusion, { within: ['---'], failureMessage: "Поле должно быть заполнено" });
            customer_validations.set("city", new LiveValidation("customer_city", { validMessage: "", onlyOnBlur: true }));
            customer_validations.get("city").add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
            customer_validations.set("street1", new LiveValidation("customer_street1", { validMessage: "", onlyOnBlur: true }));
            customer_validations.get("street1").add(Validate.Presence, { failureMessage: "Поле должно быть заполнено" });
        }
        // Credit card required for CC payments
        if ($('order_payment_type_3') && $('order_payment_type_3').checked == true) {
            credit_card_validations.each(function(pair) {
                pair.value.enable();
            });
        } else {
            credit_card_validations.each(function(pair) {
                pair.value.disable();
            });
        }
        // Web money wallet required for web money payments
        if ($('order_payment_type_4') && $('order_payment_type_4').checked == true) {
            webmoney_validations.each(function(pair) {
                pair.value.enable();
            });
        } else {
            webmoney_validations.each(function(pair) {
                pair.value.disable();
            });
        }
    } catch(e) {}
}

function change_shipping_destinations(destination){
    if(shipping_destination != destination) {
        shipping_destination = destination;
        $$('.shipping_address').invoke('toggle');
    }
}

function update_deposit() {
    if ($("depositCostPerc")) {
        var fDepositCost = total_order_cost;
        var payment_type = Form.getInputs("purchase_form","radio","payment_type").find(function(radio) { return radio.checked; }).value;
        if (payment_type == "1") {
            fDepositCost = Math.round(fDepositCost * parseFloat($("depositCostPerc").value)) / 100;
        }
        $$("#depositCost .money")[0].update(format_money(fDepositCost + " руб."));
    }
}

function format_money(money_float) {
    thousands = 0;
    if (money_float > 999) {
        thousands = Math.floor(money_float / 1000);
        money_float -= thousands * 1000;
    }
    var money_string = "";
    if (thousands > 0) {
        money_string = thousands + ".";
        if (money_float < 10) {
            money_string += "00";
        } else if (money_float < 100) {
            money_string += "0";
        }
    }

    // Remove all but last 2 decimal places
    var money_float = Math.round(money_float * 100) / 100;
    // If nothing after separator
    if (Math.floor(money_float) == money_float) {
        money_string += money_float.toString() + ",00";
    // Only 1 number after separator
    } else if (Math.floor(money_float * 10) == money_float * 10) {
        money_string += (money_float.toString() + "0").replace(".", ",");
    } else {
        money_string += money_float.toString().replace(".", ",");
    }
    return money_string;
}


