// ------------------------------------
// ------ jquery.scheduleSummary ------
// ------------------------------------
// Controls the timetable table loading
// ------------------------------------

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

    var pluginName = "scheduleSummary";

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

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

        this.init();
    };

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

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

    function placeChanged(plugin, $this, calculateTotal) {
        var places = parseInt($this.val());

        if (isNaN(places) === true) {
            places = 1;
        }

        plugin.$placesDisplay.hide();

        var $displaySummaryText = plugin.$placesDisplay.find(".placestext");
        var $displaySummaryPrice = plugin.$placesDisplay.find(".placesprice");

        if (places === 1) {
            plugin.placesTotal = 0;

            $displaySummaryText.html("");
            $displaySummaryPrice.html("");

            plugin.$placesDisplay.hide();

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

        var price = (plugin.options.defaultPrice * places);

        plugin.placesTotal = price;

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

        $displaySummaryText.html(description);
        $displaySummaryPrice.html(priceHtml);

        plugin.$placesDisplay.show();

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

    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"));
        var priceHtml;

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

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

        plugin.endsTotal = price;

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

    $.extend(scheduleSummary.prototype, {

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

            this.bindEvents();

            // trigger the events            
            placeChanged(this, this.$placesSelect, false);

            this.$customisations.each(function () {
                customisationChanged(this, $(this), false);
            });

            if (this.options.variableLengthSchedule === true) {
                if (this.$endsRadioButtons.length > 0) {
                    var $rb = this.$endsRadioButtons.find(":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.$durationPrice = $(this.options.durationPriceId);
            this.$placesSelect = $(this.options.placesSelectId);
            this.$placesDisplay = $(this.options.placesSectionId);

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

            if (this.options.variableLengthSchedule === false) {
                return;
            }

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

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

        bindEvents: function () {
            var plugin = this;

            plugin.$placesSelect.on("change", function () {
                var $this = $(this);

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

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

                var $this = $(this);

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

            if (plugin.options.variableLengthSchedule === false) {
                return;
            }

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

                var $rb = $(this);

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

        unbindEvents: function () {
            var plugin = this;

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

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

            if (plugin.options.variableLengthSchedule === false) {
                return;
            }

            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 + plugin.placesTotal;
            
            if (isNaN(sum) || sum<= 0) {
                sum = 0;                
            }

            if (plugin.placesTotal === 0 && isNaN(plugin.options.defaultPrice) === false) {
                sum += plugin.options.defaultPrice;
            }

            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.scheduleSummary = function (options) {

        var self = new scheduleSummary(options);

        return this;
    };

    $.fn.scheduleSummary.defaults = {
        customisationsSelector: ".customisationSelect",
        variableLengthSchedule: false,
        totalPriceDisplayId: "#totalPriceHtml",
        durationDisplayId: "#durationHtml",
        durationPriceId: "#durationPriceHtml",
        placesSelectId: "#places",
        placesSectionId: "#placesSummarySection",
        defaultPrice: 0,        
        durationEndsRadioButtonName: "ends",
        vatRate: 0,
        vatRatePriceId: "#vatRateHtml"
    };

})(jQuery, window, document);
