godo.addtocart = {
    nodes: {},
    template: "",
    //subtotal: 0,    
    isOpen: false,
    init: function(cartnode) {

        var self = this;

        self.nodes.cart = cartnode ? $(cartnode) : $("#addtocart");

        // Events
        self.nodes.cart.click(function(event) {
            event.stopPropagation();
        });

        self.nodes.cart.delegate(".submit", "click", function() {
            //event.preventDefault();
            if (parseInt(subtotalamount) > 0) {

                // Simulate Non-JS which actions /cart
                $("#cartForm").submit();

            } else {
                //console.log('No Subtotal');
                $("#validationMsg").html("<div class=\"alertImg\"></div>Please select a ticket quantity before \"Adding to cart\".").fadeIn();
                $("#validationMsg").delay(3000).fadeOut();
            }
        });

        self.nodes.cart.delegate(".cancel", "click", function(event) {
            event.preventDefault();
            self.close();
        });

        self.nodes.cart.delegate(".pagefade", "click", function(event) {
            self.close();
        });


        // IE fix added to handle bug: Change events in IE don't bubble up.
        self.nodes.cart.delegate(".bookingSelect", $.browser.msie ? 'click' : 'change', function(event) {
            self.subtotal();
        });

        // IE fix added to handle bug: Change events in IE don't bubble up.
        self.nodes.cart.delegate("#optInInsuranceFlag", $.browser.msie ? 'click' : 'change', function(event) {
            self.subtotal();
        });

        return false;


    },

    open: function (session) {
        var self = this;

        godo.util.template.fetch("addToCart", function() {
            // Pass the model to the view and render using mustache template
            godo.util.template.make("addToCart", session, function(html) {
                html.appendTo(self.nodes.cart);

                //Omniture - Track Product Details - Booking Popup
                s.channel = "Product Booking Pop-Up";
                //s.prop4="";
                //s.prop5="";
                s.prop8 = ""; // Clear the product details prop
                s.prop14 = ""; // Clear the product details prop
                s.prop15 = "Product Booking Pop-Up";
                s.events = "event2";
                void(s.t());

                self.isOpen = true;

            });
        });
        return false;
    },

    openvoucher: function (session) {
        var self = this;

        godo.util.template.fetch("addVoucherToCart", function() {
            // Pass the model to the view and render using mustache template
            godo.util.template.make("addVoucherToCart", session, function(html) {
                html.appendTo(self.nodes.cart);

                //Omniture - Track Voucher Personalise Popup
                s.pageName = "Gift Voucher Personalise";
                s.channel = "Gift Vouchers";
                //s.prop4="";
                //s.prop5="";
                s.prop8 = ""; // Clear the product details prop
                s.prop14 = ""; // Clear the product details prop
                s.events = "event10";
                void(s.t());

                self.isOpen = true;

                // Continuous preview
                $("#voucherMessage #voucherto").keyup(function(event) {
                    $("#voucherMessagePreview #messageto").empty();
                    $("#voucherMessagePreview #messageto").html($("#voucherMessage #voucherto").val());
                })
                $("#voucherMessage #vouchermessage").keyup(function(event) {
                    var message = $("#voucherMessage #vouchermessage").val()
                    var max_lines = 6
                    var chars_per_line = 300 / max_lines
                    var lines = message.split(/\r\n|\r|\n/)
                    if (lines.length > max_lines || Math.ceil(message.length / chars_per_line) > max_lines) {
                        $("#voucherMessage #vouchermessage").val(message.substr(0, message.length - 1))
                    } else {
                        $("#voucherMessagePreview #message pre").empty();
                        $("#voucherMessagePreview #message pre").html(message);
                    }
                })
                $("#voucherMessage #voucherfrom").keyup(function(event) {

                    $("#voucherMessagePreview #messagefrom").empty();
                    $("#voucherMessagePreview #messagefrom").html($("#voucherMessage #voucherfrom").val());
                })

                $("#cartVoucherForm").submit(function(event) {
                    event.preventDefault();
                    $.ajax({
                        url:  '/cart/addvoucher',
                        data: ({siteUrl:params.siteUrl,
                            voucheremail: this.voucheremail.value,
                            voucherto : this.voucherto.value,
                            voucherfrom : this.voucherfrom.value,
                            vouchermessage : this.vouchermessage.value,
                            booking : this.booking.value
                        }),
                        success: function(response) {
                            if (response.success) {
                                window.location.href = "/cart";
                            } else {
                                $("#validationMsg").html(response.messages).fadeIn();
                            }
                        },
                        dataType: "json"
                    });
                    return true;
                });
            });
        });
        return false;
    },

    close: function () {
        if (this.isOpen) {
            this.nodes.cart.empty();
            this.isOpen = false;
        }
        return false;
    },


    subtotal: function() {
        var subtotal = 0;
        var insurance = 0;
        $.each($(".bookingSelect option:selected"), function(i, bookingSelect) {
            //console.log(bookingSelect.id);

            var ticketQuantityPrice = parseFloat(bookingSelect.id); // TODO: Not ideal that ID holds the price*quantity
            var ticketInsurance = ticketQuantityPrice * 0.07;

            if (parseInt(ticketQuantityPrice) == 0) {
                insurance += 0;
                subtotal += 0;
            } else if (!$("#optInInsuranceFlag:checked").val() == 1) {
                subtotal += ticketQuantityPrice
                insurance = 0;
            } else if (ticketInsurance > 6) {
                insurance += ticketInsurance;
                subtotal += ticketQuantityPrice + ticketInsurance;
            } else {
                insurance += 6;
                subtotal += ticketQuantityPrice + 6;
            }
            //$(bookingSelect).next(".cost").html('$'+ticketQuantityPrice.toFixed(2));
            //console.log(bookingSelect.parent);

        });
        $(".insurance .cost").html('$' + insurance.toFixed(2));
        $(".subtotal .cost").html('$' + subtotal.toFixed(2));
        subtotalamount = parseInt(subtotal);
        //console.log(self.subtotalamount);
        return false;
    }
}
