// ---------------------------------------
// ------ jquery.roomBookingSummary ------
// ---------------------------------------
// Controls the room booking schedule
// ---------------------------------------

; (function ($, window, document, undefined) {

    var pluginName = "roomBookingSummary";

    function roomBookingSummary(options) {
        this._name = pluginName;
        this._defaults = $.fn.roomBookingSummary.defaults;
        this.options = $.extend({}, this._defaults, options);

        this.total = 0;
        this.endsTotal = 0;
        this.customisationsTotal = 0;

        this.init();
    };

    function htmlEncode(value) {
        return $("<div/>").text(value).html();
    };

    function htmlDecode(value) {
        return $("<div/>").html(value).text();
    };

    function customisationChanged(plugin, $this, calculateTotal) {

        var id = $this.attr("id");

        var selectedValue = $this.val();
        var $option = $this.find("option:selected");

        var $displaySummaryContainer = $("#" + id + "_text");

        var $displaySummaryText = $displaySummaryContainer.find(".customtext");
        var $displaySummaryPrice = $displaySummaryContainer.find(".customprice");

        var price = parseFloat($option.data("price"));

        if (isNaN(price) || price <= 0 || selectedValue === "") {
            $displaySummaryText.html("");
            $displaySummaryPrice.html("");

            $displaySummaryContainer.hide();
        } else {
            var description = $option.data("description");

            if (typeof description === "undefined") {
                description = $option.html();
            }

            var priceHtml = htmlEncode("£" + price.toFixed(2));

            $displaySummaryText.html(description);
            $displaySummaryPrice.html(priceHtml);
            $displaySummaryContainer.show();
        }

        if (calculateTotal === true) {
            plugin.calculateCustomisationTotal();
        }
    };

    function durationChanged(plugin, $rb, calculateTotal) {

        var description = $rb.data("description");
        var price = parseFloat($rb.data("price"));

        if (plugin.isCommunityRate) {
            var cprice = parseFloat($rb.data("communityprice"));

            if (isNaN(cprice) === false && cprice > 0) {
                price = cprice;
            }
        }

        var displayTime = $rb.data("display");
        var priceHtml = "";

        if (isNaN(price) || price <= 0) {
            price = 0;
        } else {
            priceHtml = htmlEncode("£" + price.toFixed(2));
        }

        plugin.$endTimeDisplay.html(displayTime);
        plugin.$durationDisplay.html(description);
        plugin.$durationPrice.html(priceHtml);

        plugin.endsTotal = price;

        if (calculateTotal === true) {
            plugin.calculateTotal();
        }
    };

    function changePriceLabels(plugin) {
        $.each(plugin.$endsRadioButtons, function (i, item) {

            var $rb = $(item);

            var id = $(item).attr("id");

            var price = parseFloat($rb.data("price"));

            if (plugin.isCommunityRate) {
                var cprice = parseFloat($rb.data("communityprice"));

                if (isNaN(cprice) === false && cprice > 0) {
                    price = cprice;
                }
            }

            var $endTotal = $("#" + id + "cost");

            var html = htmlEncode("£" + price.toFixed(2));

            if (i > 0) {
                html = "+" + html;
            }

            if (html.endsWith(".00")) {
                html = html.substring(0, html.length - 3);
            }

            $endTotal.html(html);
        });
    }

    function hireRateChanged(plugin, $rb, calculateTotal) {

        if ($rb.val() === "community") {
            if (plugin.isCommunityRate === true)
                return;

            plugin.isCommunityRate = true;
        } else {
            if (plugin.isCommunityRate === false)
                return;

            plugin.isCommunityRate = false;
        }

        // Change labels
        changePriceLabels(plugin);

        if (plugin.$endsRadioButtons.length > 0) {
            var $dRb = plugin.$endsRadioButtons.closest(":checked");

            if ($dRb.length === 1) {
                durationChanged(plugin, $dRb, true);
            }
        }

    };

    $.extend(roomBookingSummary.prototype, {

        init: function () {
            this.buildCache();

            this.bindEvents();

            this.isCommunityRate = false;

            if (this.$hireRateRadioButtons.length > 0) {

                var $hrRb = this.$hireRateRadioButtons.closest(":checked");

                if ($hrRb.length === 1) {
                    hireRateChanged(this, $hrRb, false);
                }
            }

            if (this.isCommunityRate === false) {
                this.defaultPrice = parseFloat(this.options.standardPrice);
            } else {
                this.defaultPrice = parseFloat(this.options.communityPrice);
            }

            // trigger the events
            this.$customisations.each(function () {
                customisationChanged(this, $(this), false);
            });

            if (this.$endsRadioButtons.length > 0) {
                var $rb = this.$endsRadioButtons.closest(":checked");

                if ($rb.length === 1) {
                    durationChanged(this, $rb, false);
                }
            }

            this.calculateCustomisationTotal();
            this.calculateTotal();
        },

        destroy: function () {
            this.unbindEvents();
        },

        buildCache: function () {

            this.$totalPriceDisplay = $(this.options.totalPriceDisplayId);
            this.$vatTotalPriceDisplay = $(this.options.vatRatePriceId);
            this.$durationDisplay = $(this.options.durationDisplayId);
            this.$endTimeDisplay = $(this.options.endTimeDisplayId);
            this.$durationPrice = $(this.options.durationPriceId);

            this.$customisations = $(this.options.customisationsSelector);

            var radioSelector = "input[type=radio][name=" + this.options.durationEndsRadioButtonName + "]";

            this.$endsRadioButtons = $(radioSelector);

            radioSelector = "input[type=radio][name=" + this.options.hireRateRadioButtonName + "]";

            this.$hireRateRadioButtons = $(radioSelector);
        },

        bindEvents: function () {
            var plugin = this;

            plugin.$customisations.on("change", function () {

                var $this = $(this);

                customisationChanged(plugin, $this, true);
            });

            plugin.$endsRadioButtons.on("change", function () {

                var $rb = $(this);

                durationChanged(plugin, $rb, true);
            });

            plugin.$hireRateRadioButtons.on("change", function () {

                var $rb = $(this);

                hireRateChanged(plugin, $rb, true);
            });

        },

        unbindEvents: function () {
            var plugin = this;

            plugin.$customisations.off("change");

            plugin.$endsRadioButtons.off("change");
        },

        calculateCustomisationTotal: function() {

            var plugin = this;

            var sum = 0;

            plugin.$customisations.each(function () {

                var $this = $(this);

                var selectedValue = $this.val();

                if (selectedValue === "") {
                    return;
                }

                var $option = $this.find("option:selected");

                var price = parseFloat($option.data("price"));

                if (isNaN(price) || price <= 0) {
                    return;
                }

                sum += price;
            });

            plugin.customisationsTotal = sum;

            plugin.calculateTotal();
        },

        calculateTotal: function () {
            var plugin = this;

            var sum = plugin.endsTotal + plugin.customisationsTotal;

            if (isNaN(sum) || sum<= 0) {
                sum = 0;
            }

            if (plugin.options.vatRate > 0) {
                var vat = (plugin.options.vatRate / 100) * sum;

                plugin.$vatTotalPriceDisplay.html(htmlEncode("£" + vat.toFixed(2)));

                sum += vat;
            }

            plugin.$totalPriceDisplay.html(htmlEncode("£" + sum.toFixed(2)));
        }

    });

    $.fn.roomBookingSummary = function (options) {

        var self = new roomBookingSummary(options);

        return this;
    };

    $.fn.roomBookingSummary.defaults = {
        customisationsSelector: ".customisationSelect",
        totalPriceDisplayId: "#totalPriceHtml",
        durationDisplayId: "#durationHtml",
        endTimeDisplayId: "#endTimeContainer",
        durationPriceId: "#durationPriceHtml",
        standardPrice: 0,
        communityPrice: 0,
        durationEndsRadioButtonName: "ends",
        hireRateRadioButtonName: "hirerate",
        vatRate: 0,
        vatRatePriceId: "#vatRateHtml"
    };

})(jQuery, window, document);
