// ---------------------------------------------------------
// ---------- jquery.roomAlternateOptions ------------------
// ---------------------------------------------------------
// Controls the room alternate booking option table loading
// ---------------------------------------------------------

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

    var pluginName = "roomAlternateOptions";

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

        this.init();
    }

    function isValidDate(date) {
        return (date.getMonth && typeof date.getMonth === "function");
    };

    function getDayName(day) {
        var dayNames = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];

        return dayNames[day];
    }

    function getMonthName(month) {
        var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

        return monthNames[month];
    }

    function getHiddenMonthNamePart(month) {
        var monthNames = ["uary", "ruary", "ch", "il", "", "e", "y", "ust", "tember", "ober", "ember", "ember"];

        return monthNames[month];
    }

    function formatHtmlMonthString(dt) {
        var mm = dt.getMonth();
        var monthName = getMonthName(mm);
        var hiddenMonthPart = getHiddenMonthNamePart(mm);

        if (hiddenMonthPart === "") {
            return monthName;
        }

        return monthName +
            '<span class="visuallyhidden">' +
            hiddenMonthPart +
            "</span>";
    }

    function formatHtmlDateString(dt, longDate) {

        var monthNames = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"
        ];

        var day = dt.getDay();
        var dayName = getDayName(day);
        var hiddenDayPart = getHidenDayNamePart(day);
        var dd = dt.getDate();
        var daySuffix = getSuffix(dd);
        var mm = monthNames[dt.getMonth()];
        var yyyy = dt.getFullYear();

        if (longDate === false) {
            dayName = "";
            mm = mm.substring(0, 3);
        } else {
            dayName = dayName + hiddenDayPart + " ";
        }

        return dayName +
            dd +
            "<sup>" +
            daySuffix +
            "</sup> " +
            mm +
            " " +
            yyyy;
    };

    function convertStringToDate(dtStr) {

        var parts = dtStr.split("-");

        if (parts.length !== 3)
            return null;

        var yy = parseInt(parts[0]);
        var mm = parseInt(parts[1]);
        var dd = parseInt(parts[2]);

        if (isNaN(yy) === false || isNaN(mm) === false || isNaN(dd) === false)
            return null;

        var dt = new Date(yy, mm - 1, dd);

        return dt;
    };

    function formatIsoDateTimeString(dt) {

        var dd = dt.getDate();
        var mm = dt.getMonth() + 1;
        var yyyy = dt.getFullYear();
        var hh = dt.getHours();
        var mi = dt.getMinutes();


        if (dd < 10) {
            dd = "0" + dd;
        }

        if (mm < 10) {
            mm = "0" + mm;
        }

        if (hh < 10) {
            hh = "0" + hh;
        }

        if (mi) {
            mi = "0" + mi;
        }

        return "" + yyyy + "-" + mm + "-" + dd + "T" + hh + ":" + mi;
    };

    function getHidenDayNamePart(day) {
        switch (day) {
            case 3:
                return "nesday";
            case 6:
                return "urday";
            default:
                return "day";
        }
    };

    function getStartOfWeek(dt) {

        var day = dt.getDay();
        var diff = 0;

        if (day === 0) {
            diff = -6;
        } else {
            diff = ((day - 1) * -1);
        }

        return addDaysToDate(dt, diff);
    };

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

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

    function getSuffix(dd) {
        switch (dd) {
        case 1:
        case 21:
        case 31:
            return "st";
        case 2:
        case 22:
            return "nd";
        case 3:
        case 23:
            return "rd";
        default:
            return "th";
        }
    };

    function isNullOrWhiteSpace(str) {
        if (typeof str === "undefined" ||
            !str ||
            str.length === 0 ||
            !/[^\s]/.test(str) ||
            /^\s*$/.test(str) ||
            str.replace(/\s/g, "") === "") {
            return true;
        } else {
            return false;
        }
    }

    $.extend(roomAlternateOptions.prototype, {

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

            this.bindEvents();
        },

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

            this.$element.removeData();
        },

        buildCache: function () {
            this.$element = $(this.element);

            this.$alternateButtons = $(this.options.alternateButtonSelector);
            this.$tableBody = $(this.options.alternateTableBodyId);
            this.$alternateModal = $(this.options.modalId);
            this.$alternateModalCloseBtn = $(this.options.modalCloseButtonSelector);
            this.$alternateSubmitButton = $(this.options.alternateSubmitButtonId);

            this.offsetHeight = $(this.options.mastId).height();

            this.$scrollToTopElement = $(this.options.scrollToTopId);

            this.rowDate = null;
            this.rowId = null;
            this.rowSlotSize = null;
            this.$rowBtn = null;
        },

        bindEvents: function () {
            var plugin = this;

            plugin.$alternateButtons.on("click", function(e) {

                e.preventDefault();

                plugin.$rowBtn = $(this);

                plugin.rowDate = plugin.$rowBtn.data("date");
                plugin.rowSlotSize = plugin.$rowBtn.data("slotsize");
                plugin.rowId = plugin.$rowBtn.data("id");

                //console.log("id: " + plugin.rowId);
                //console.log("date: " + plugin.rowDate);
                //console.log("slotSize: " + plugin.rowSlotSize);

                // Load alternate times
                plugin.loadAlternateOptions();

                plugin.$alternateModal.foundation("reveal", "open");

                // make sure the mouse is focused for the tab based users
                setTimeout(function () {
                    plugin.$alternateModal.find("button[data-close]").focus();
                }, 250); // After the animation completes

            });

            plugin.$alternateModalCloseBtn.on("click", function () {

                plugin.closeDialog(plugin.$scrollToTopElement);

            });

            plugin.$alternateSubmitButton.on("click", function (e) {

                e.preventDefault();

                var $selectedRb = $("input.altoptionrb:checked");

                if ($selectedRb.length === 0) {

                    plugin.closeDialog(plugin.$scrollToTopElement);

                    return;
                }

                var $row = plugin.$rowBtn.closest("tr");

                if ($row.length === 0) {

                    plugin.closeDialog(plugin.$scrollToTopElement);

                    return;
                }

                var dateHtml = $selectedRb.data("dateslot");
                var timeHtml = $selectedRb.data("timeslot");
                var val = $selectedRb.attr("value");

                $row.children("td:nth-child(1)").html(dateHtml);
                $row.children("td:nth-child(2)").html(timeHtml);
                $row.children("td:nth-child(3)").html(plugin.options.selectedDescriptionHtml);

                var html = '<div class="buttonCheckRadio">' +
                    '<input name="slot" id="' + plugin.rowId + '" value="' + val + '" type="checkbox" checked="checked">' +
                    '<label for="' + plugin.rowId + '" class="button hollow">' +
                    '<span class="negative">Select</span><span class="positive">Selected</span>' +
                    "</label>" +
                    "</div>";

                $row.children("td:nth-child(4)").html(html);

                plugin.closeDialog($row);

            });

        },

        closeDialog: function($scrollTo) {

            var plugin = this;

            //plugin.$rowBtn = null;
            //plugin.rowDate = null;
            //plugin.rowSlotSize = null;
            //plugin.rowId = null;

            $('html, body').animate({
                scrollTop: $scrollTo.offset().top + plugin.offsetHeight
            }, 2000);

        },

        unbindEvents: function () {
            var plugin = this;

            plugin.$alternateButtons.off("click");

            plugin.$alternateModalCloseBtn.off("click");

        },

        removeTableRows: function () {
            var plugin = this;

            plugin.$tableBody.empty();
        },

        buildTableRow: function(data, idx) {

            var plugin = this;

            var html;

            var val = data.DateStartValue;
            var id = "altSlot" + plugin.rowId + "_" + idx;

            html = "<tr>" +
                "<td>" +
                data.DateText +
                "</td>" +
                "<td>" +
                data.TimeSlot +
                "</td>" +
                '<td class="text-center">' +
                '<div class="buttonCheckRadio">' +
                '<input class="altoptionrb" name="altSlot" id="' + id + '" value="' + val + '" type="radio" data-timeslot="' + data.TimeSlot + '" data-dateslot="' + data.DateText + '">' +
                '<label for="' + id + '" class="button hollow"><span class="negative">Select</span><span class="positive">Selected</span></label>' +
                "</div>" +
                "</td>" +
                "</tr>";

            return html;
        },

        setLoadError: function(errorMessage) {
            var plugin = this;

            var columns = 3;

            var html = '<tr><td colspan="' + columns + '"><p><span class="warning expanded label largeText paddingAll radius">' + errorMessage + "</span></p></td></tr>";

            plugin.$tableBody.html(html);
        },

        loadAlternateOptions: function() {

            var plugin = this;

            plugin.removeTableRows();

            if (plugin.options.getTimetableUrl === null) {
                plugin.setLoadError("No load url has been set");
                return;
            }

            var loadData = {
                duration: plugin.rowSlotSize,
                date: plugin.rowDate,
                roomId: plugin.options.roomId,
                offPeakOnly: plugin.options.offPeakOnly
            };

            $.ajax({
                type: "POST",
                url: plugin.options.getTimetableUrl,
                data: JSON.stringify(loadData),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                success: function (data) {
                    if (data === null) {
                        plugin.setLoadError("An error has occurred loading the alternate slot options");
                        return;
                    }

                    if (data.length === 0) {
                        plugin.setLoadError('No available slots found');
                        return;
                    }

                    // loop through
                    var d = [];

                    $.each(data, function (i, item) {
                        d.push(plugin.buildTableRow(item, i));
                    });

                    plugin.$tableBody.html(d.join(""));
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    plugin.setLoadError("A problem prevented the slots from being loaded: " + textStatus);
                },
                complete: function () {

                }
            });
        }

    });

    $.fn.roomAlternateOptions = function (options) {
        this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new roomAlternateOptions(this, options));
            }
        });

        return this;
    };

    $.fn.roomAlternateOptions.defaults = {
        alternateButtonSelector: ".alternateBtn",
        alternateSubmitButtonId: "#alternateSelectBtn",
        modalId: "#modalAlternate",
        modalCloseButtonSelector: ".altclose",
        alternateTableBodyId: "#alternativeSlots",
        selectedDescriptionHtml: "<span class='secondary label'>Add to basket</span>",
        mastId: ".mast",
        scrollToTopId: "#scrollTarget",
        hasPeakPricing: false,
        getTimetableUrl: null,
        roomId: null,
        offPeakOnly: false
    };

})(jQuery, window, document);
