/**
 * @filename itw.js
 * @created 12/10/2009 13:56:56
 * @original author uhu
 * @copyright Kemen s.r.l.
 * @license Mozilla Public License Version 1.1
 * @version 0.1
 * $LastChangedDate: 2010-07-08 16:00:04 +0200 (Thu, 08 Jul 2010) $
 * $LastChangedRevision: 849 $
 * $LastChangedBy: giancarlo $
 */

var Orders = {

    payOrder: function() {

        if (! $('#paymentForm').valid()) {
            return false;
        }

        $('#payment').val($.toJSON(Orders.createPaymentObjectFromForm()));

        var data = $.toJSON(Orders.createPaymentObjectFromForm());

        $.post($('#paymentForm').attr('action'), {payment: data}, Orders.handlePaymentResult, "json");

        $('#payment-button').attr('src', 'images/btn-do-payment-disabled.png');
        $('#payment-button').attr('disabled', 'disabled');
        $("#spinning_wheel").show('fast');

        return false;
    },

    handlePaymentResult: function(result) {
        $("#spinning_wheel").hide('fast');
        if (result.resultStatus == true) {
            location.href = Context.lang + '/confirm.jsp';
            return;
        }

        $('#error_label').html('Si &egrave; verificato un problema con il pagamento. ' +
                               'Si prega di verificare i dati della carta di credito e riprovare<br/>' +
                               'Messaggio di errore della banca: ' + result.resultDescription);

        $('#payment-button').attr('src', 'images/btn-do-payment.png');
        $('#payment-button').attr('disabled', '');

    },

    newPayment: function() {
        return {"orderId":null,"creditCardNumber":"","creditCardOwner":"","twoDigitsYear":null,"month":null,"cvv":""};
    },

    placeOrder: function() {
        $("#order").val($.toJSON(Orders.createJsonObjectFromForm()));
        $("#orderCharges").val($.toJSON(Orders.createJsonOrderChargesFromForm()));
        return true;

    },

    createPaymentObjectFromForm: function() {
        var payment = Orders.newPayment();
        payment.creditCardNumber = $('#cc_nr').val();
        payment.creditCardOwner = $('#cc_name').val();
        payment.cvv = $('#cc_cvv').val();
        payment.twoDigitsYear = $('#cc_year').val();
        payment.month = $('#cc_month').val();
        return payment;
    },

    /**
     * Update the cart form using ajax.
     */
    updateCart: function() {
        // build the data to send via GET        
        var quantity = $("#quantity").val();

        if (isEmpty(quantity) || isNaN(quantity)) return;

        var country = $("#shipping_country").val();
        var isACompany = $('#is_a_company').is(':checked');
        var discountCode = $("#discount_code").val();
        var captchaReponse = $("#captcha_response").val();

        var requestData = {quantity: quantity, country: country, isACompany: isACompany, discountCode: discountCode,
            captcha: captchaReponse};

        $.ajax({
            url: Context.path + "/webresources/order/calculateOrderCharges",
            type: "POST",
            data: requestData,
            cache: true,
            success: function(ret) {
                var retObj = $.evalJSON(ret);

                $('.totalAmountDue').html(retObj.totalAmountDue);
                $('.watchesPriceWithVat').html(retObj.watchesPriceWithVat);
                $('.deliveryChargesWithVat').html(retObj.deliveryChargesWithVat);
                $('.discountPercentage').text(retObj.discountPercentage);
                $('.discountAmount').text(retObj.discountOnWatchesPrice);
                $("#deliveryCharges").val(retObj.deliveryCharges);
                $("#vat").val(retObj.vat);
                $("#quantity").val(retObj.quantity);
                $('#spinning_wheel').hide();

                $('#discount_code_error').html('');
                if (retObj.isValidDiscountCode) {
                    $('.discountCodeRow').show();
                    if ($("#discount_code").val() == '') {
                        Orders.hideDiscountCodeRowAndShowApplyButton();
                    } else {
                        $('#code_ok').fadeIn('fast');
                        $('#code_failed').hide();
                    }
                } else {                    
                    //$('#captcha_img').attr('src', $('#captcha_img').attr('src') + '?' + (new Date()).getTime());
                    $('.discountCodeRow').each(function() {
                        $(this).hide();
                    }
                            );
                    if ($("#discount_code").val() == '') {
                        Orders.hideDiscountCodeRowAndShowApplyButton();
                    } else {
                        $('#apply').show();
                        $('#code_ok').hide();
                        $('#code_failed').fadeIn('fast');
                        $('#discount_code_error').html(retObj.errorMessage);
                    }
                }
            },

            error: function(ret) {
                alert("Error during request." + ret);
                $("#cartForm").reset();
            }
        });
        return false;
    },

    hanldeResults: function(data) {
        //alert("results:" + data);
    },

    hanldePaymentResults: function(data) {
        //alert("results:" + data);
    },

    hideDiscountCodeRowAndShowApplyButton: function () {
        $('#apply').show();
        $('#code_ok').hide();
        $('#code_failed').hide();
    },

    createJsonOrderChargesFromForm: function() {
        var orderCharges = {};
        $('.totalAmountDue').each(
                function() {
                    orderCharges.totalAmountDue = $(this).html();
                }
                );
        $('.deliveryChargesWithVat').each(
                function() {
                    orderCharges.deliveryChargesWithVat = $(this).html();
                }
                );
        $('.watchesPriceWithVat').each(
                function() {
                    orderCharges.watchesPriceWithVat = $(this).html();
                }
                );

        orderCharges.deliveryCharges = $("#deliveryCharges").val();
        orderCharges.vat = $("#vat").val();
        return orderCharges;
    },

    createJsonObjectFromForm: function() {
        var order = Orders.newInstance();
        
        order.comment = $("#comment").val();        
        order.customer.firstname = $("#firstname").val();
        order.customer.lastname = $("#lastname").val();
        order.customer.email = $("#email").val();
        order.customer.mobilePhone = $("#contacts").val();
        order.customer.isCompany = $("#is_a_company").is(":checked");
        order.quantity = $("#quantity").val();

        var sh_street = $("#shipping_address1").val() + " " + $("#shipping_address2").val();
        var in_street = $("#invoicing_address1").val() + " " + $("#invoicing_address2").val();

        order.shippingAddress = Orders.createAddress(sh_street, $("#shipping_nearby").val(), $("#shipping_postcode").val(),
                $("#shipping_city").val(), $("#shipping_province").val(), $("#shipping_country").val());

        if ($("#is_a_company").is(":checked")) {
            order.customer.companyName = $("#company_name").val();
            order.customer.vatNumber = $("#vat_number").val();
            order.customer.taxCode = $("#tax_code").val();
        }

        if (($("#is_a_company").is(":checked") && $("#is_using_shipping_data").is(":checked")) || !$("#is_a_company").is(":checked")) {
            order.invoicingAddress = Orders.createAddress(sh_street, $("#shipping_nearby").val(), $("#shipping_postcode").val(),
                    $("#shipping_city").val(), $("#shipping_province").val(), $("#shipping_country").val());
        } else {
            order.invoicingAddress = Orders.createAddress(in_street, "", $("#invoicing_postcode").val(),
                    $("#invoicing_city").val(), $("#invoicing_province").val(), $("#invoicing_country").val());
        }

        order.discountCode = $("#discount_code").val();

        return order;
    },

    createAddress: function(street, nearby, postcode, city, province, country) {
        var address = {};
        address.street = street;
        address.nearby = nearby;
        address.zipCode = postcode;
        address.city = city;
        address.provinceState = province;
        address.country = country;
        return address;
    },

    newInstance: function() {

        return {
            "trackingNumber": "",
            "quantity": 0,

            "customer": {
                "firstname": "",
                "lastname": "",
                "phone": "",
                "mobilePhone": "",
                "email": "",
                "vatNumber": "",
                "sellingRegion":"ITA",
                "companyName": "",
                "taxCode": "",
                "isCompany": false
            },
            "shippingAddress": {
                "street": "",
                "nearby": "",
                "zipCode": "",
                "city": "",
                "provinceState": "",
                "country": ""
            },
            "invoicingAddress": {
                "street": "",
                "nearby": "",
                "zipCode": "",
                "city": "",
                "provinceState": "",
                "country": ""
            },
            "discountCode": ""
        };
    }
};

// Validate the order form
$(document).ready(function() {
    $("#orderForm").validate({
        rules: {
            comment: {
                required: true,
                maxlength: 4095
            }
        }
    });
});

// Validate the cart form
$(document).ready(function() {
    $("#cartForm").validate();
});

// Validate the payment form
$(document).ready(function() {
    $('#paymentForm').validate({
        rules: {
            cc_cvv: {
                required: true,
                maxlength: 4
            }
        }
    });
});

// Update the cart form on submit
$(document).ready(function() {
    $('#cartForm').submit(Orders.updateCart);
});

jQuery.validator.addMethod(
        "selectNone",
        function(value, element) {
            if (element.value == "none") {
                return false;
            }

            element.setAttribute("class", "error");
            return true;
        },
        "Selezionare un valore"
        );


function isEmpty(inputStr) {
    return !(inputStr && inputStr.length)
}