


var CLUBHOUSEWIDGET = {

    variables: {

        "venueTime": "2025-12-10T20:17:33.8769749",
        "bookingInterval": "30",
        "minimumBookingIntervals": "1",
        "formSubmitURL": "https://play.tennis.com.au/emupointsportingclub/Booking/Availability",
        "bookingSheetURL": "https://play.tennis.com.au/emupointsportingclub/Booking/BookByDate",
        "layout": "Landscape1", //Options are "Landscape1", "Landscape2", "Landscape3", "Portrait1"
        "colourScheme": "Dark", //Options are "FullColour", "Light", "Dark", "White", "Neutral"
        "dates": ["Tomorrow|2025-12-11","12 December 2025|2025-12-12","13 December 2025|2025-12-13","14 December 2025|2025-12-14","15 December 2025|2025-12-15 "],
        "times": ["07:00","07:30","08:00","08:30","09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00","18:30 "],
        "durations": ["30","60","90","120 "],
        "surfaces": ["Artificial Grass|1 "],
        "target": null, 
        "CSS": "https://play.tennis.com.au/Content/LegacyTa2/Public/Widget/ta2/CSS/core.css", 
        "tomorrow": false
    },

    HTMLLayouts: {

        "Landscape1": '<div class="CHW-AS-container"><h2>I want to play...</h2><form method="get" id="CHW-AS-form"><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-date"><label for="CHW-AS-Date">Date</label><select id="CHW-AS-Date" name="Date"></select></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-time"><label for="CHW-AS-Time">Time</label><select id="CHW-AS-Time" name="Time"></select></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-duration"><label for="CHWIDGET-Duration">Duration</label><select id="CHW-AS-Duration" name="Duration"></select></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-surface"><label for="CHW-AS-Surface">Surface</label><select id="CHW-AS-Surface" name="Surface"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_9"><p><a href="#" id="CHW-AS-booking-sheet">View schedule</a></p></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-availability"><button id="CHW-AS-button">Check availability</button></div></div></form></div>',
        "Landscape2": '<div class="CHW-AS-container"><h2>I want to play...</h2><form method="get" id="CHW-AS-form"><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_2 CHW-AS-date"><label for="CHW-AS-Date">Date</label><select id="CHW-AS-Date" name="Date"></select></div><div class="CHW-AS-col CHW-AS-span_2 CHW-AS-time"><label for="CHW-AS-Time">Time</label><select id="CHW-AS-Time" name="Time"></select></div><div class="CHW-AS-col CHW-AS-span_2 CHW-AS-duration"><label for="CHWIDGET-Duration">Duration</label><select id="CHW-AS-Duration" name="Duration"></select></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-surface"><label for="CHW-AS-Surface">Surface</label><select id="CHW-AS-Surface" name="Surface"></select></div><div class="CHW-AS-col CHW-AS-span_3 CHW-AS-availability"><button id="CHW-AS-button">Check availability</button></div></div></form><p><a href="#" id="CHW-AS-booking-sheet">View schedule</a></p></div>',
        "Landscape3": '<div class="CHW-AS-container"><h2>I want to play...</h2><form method="get" id="CHW-AS-form"><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_6 CHW-AS-date"><label for="CHW-AS-Date">Date</label><select id="CHW-AS-Date" name="Date"></select></div><div class="CHW-AS-col CHW-AS-span_6 CHW-AS-time"><label for="CHW-AS-Time">Time</label><select id="CHW-AS-Time" name="Time"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_6 CHW-AS-duration"><label for="CHW-AS-Duration">Duration</label><select id="CHW-AS-Duration" name="Duration"></select></div><div class="CHW-AS-col CHW-AS-span_6 CHW-AS-surface"><label for="CHW-AS-Surface">Surface</label><select id="CHW-AS-Surface" name="Surface"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_6"><p><a href="#" id="CHW-AS-booking-sheet">View schedule</a></p></div><div class="CHW-AS-col CHW-AS-span_6 CHW-AS-availability"><button id="CHW-AS-button">Check availability</button></div></div></form></div>',
        "Portrait1": '<div class="CHW-AS-container"><h2>I want to play...</h2><form method="get" id="CHW-AS-form"><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12 CHW-AS-date"><label for="CHW-AS-Date">Date</label><select id="CHW-AS-Date" name="Date"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12 CHW-AS-time"><label for="CHW-AS-Time">Time</label><select id="CHW-AS-Time" name="Time"></select></div></div><div class="row gutters"></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12 CHW-AS-duration"><label for="CHW-AS-Duration">Duration</label><select id="CHW-AS-Duration" name="Duration"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12 CHW-AS-surface"><label for="CHW-AS-Surface">Surface</label><select id="CHW-AS-Surface" name="Surface"></select></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12 CHW-AS-availability"><button id="CHW-AS-button">Check availability</button></div></div><div class="CHW-AS-row CHW-AS-gutters"><div class="CHW-AS-col CHW-AS-span_12"><p><a href="#" id="CHW-AS-booking-sheet">View schedule</a></p></div></div></form></div>'
    },

    init: function () {

        var self = this;

        self.loadCSS();

        //Write the HTML to the page
        var target = document.getElementById("CHW-availability-search");

        if (!target) {
            return;
        }

        if (target) {

            //Get the scripts
            self.getScripts();

            //Set the layout
            self.variables.target = target;
            self.variables.target.innerHTML = self.HTMLLayouts[this.variables.layout];

            //Load the colour scheme by adding a class to the widget DIV
            target.className = self.variables.colourScheme;

            //Load layout specific style
            target.className += " " + self.variables.layout;


            var form = null;
            form = document.getElementById("CHW-AS-form");

            //Update the form action (if our form is there and there is no pre-existing form)
            /*if (form != null) {
                form.action = self.variables.formSubmitURL;
            }*/

            //(if our form doesn't exist (usually means there is a pre-existing form)

            var button = document.getElementById("CHW-AS-button");
            
            button.onclick = function (e) {
                e.preventDefault();
                self.submitForm();
                return false;
            };

            //Update the booking sheet URL
            var bookingSheet = document.getElementById("CHW-AS-booking-sheet");
            bookingSheet.href = self.variables.bookingSheetURL;

            self.loadDates();
            self.loadTimes();
            self.loadDurations();
            self.loadSurfaces();
        }
    },

    loadCSS: function () {

        var htmlTag = document.getElementsByTagName("head");

        var newCSSFile = document.createElement("link");
        newCSSFile.type = "text/css";
        newCSSFile.media = "screen";
        newCSSFile.rel = "stylesheet";
        newCSSFile.href = this.variables.CSS;

        htmlTag[0].appendChild(newCSSFile);

    },

    loadDates: function () {

        var datesOptions = document.getElementById("CHW-AS-Date");
        var dateValues = this.variables.dates;
        var dateValuesL = dateValues.length;
        var self = this;

        //Loop through all the values in the dates variable and write in the option tags
        for (i = 0; i < dateValuesL; i++) {

            var parts = dateValues[i].split("|");

            var newOption = document.createElement("option");
            newOption.value = parts[1];

            var textValue = document.createTextNode(parts[0]);
            newOption.appendChild(textValue);

            datesOptions.appendChild(newOption);
        }

        datesOptions.onchange = function () {

            //Reload the times
            self.loadTimes();

            if (jQuery) {
                jQuery("#CHW-AS-Time").trigger("change");
            }
        };
    },

    loadTimes: function () {

        var self = this;
        var venueTime = self.utilities.parseISO8601(self.variables.venueTime);
        var timeOption = self.utilities.parseISO8601(self.variables.venueTime);
        var selectedDate = self.utilities.parseISO8601(document.getElementById("CHW-AS-Date").value);

        var timesOptions = document.getElementById("CHW-AS-Time");
        var timeValues = this.variables.times;
        var timeValuesL = timeValues.length;

        //Work out if the selected date is tomorrow or today (if the selected date is greater than the venue time, then it's definately tomorrow)
        if (selectedDate > venueTime) {
            self.variables.tomorrow = true;
        } else {
            self.variables.tomorrow = false;
        }

        //Empty the time select
        timesOptions.innerHTML = "";

        function addOption(i) {

            var newOption = document.createElement("option");
            newOption.value = timeValues[i];

            var textValue = document.createTextNode("at " + timeValues[i]);
            newOption.appendChild(textValue);

            timesOptions.appendChild(newOption);
        }


        //Loop through all the values in the times variable and write in the option tags
        for (i = 0; i < timeValuesL; i++) {
            
            var timeStr = timeValues[i].split(":");

            timeOption.setHours(timeStr[0]);
            timeOption.setMinutes(timeStr[1]);

            //If tomorrow is selected, output all the times
            if (self.variables.tomorrow == true) {
                addOption(i);
            }
            //If tomorrow is NOT selecetd, only output times in the future
            else {
                if (venueTime < timeOption) {
                    addOption(i);
                }
            }
        }

        timesOptions.selectedIndex = "0";

        function fireEvent(element, event) {

            if (document.createEventObject) {
                // dispatch for IE
                var evt = document.createEventObject();
                return element.fireEvent('on' + event, evt)
            } else {
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent(event, true, true); // event type,bubbling,cancelable
                return !element.dispatchEvent(evt);
            }
        }

        fireEvent(timesOptions, "change")
    },

    loadDurations: function () {

        var durationOptions = document.getElementById("CHW-AS-Duration");
        var durationValues = this.variables.durations;
        var durationValuesL = durationValues.length;

        //Loop through all the values in the times variable and write in the option tags
        for (i = 0; i < durationValuesL; i++) {

            var newOption = document.createElement("option");
            newOption.value = durationValues[i];

            var textValue = document.createTextNode("for " + durationValues[i] + " minutes");
            newOption.appendChild(textValue);

            durationOptions.appendChild(newOption);
        }
    },

    loadSurfaces: function () {

        var surfaceOptions = document.getElementById("CHW-AS-Surface");
        var surfaceValues = this.variables.surfaces;
        var surfaceValuesL = surfaceValues.length;

        var newOption = document.createElement("option");
        var textValue = document.createTextNode("on any surface");
        newOption.appendChild(textValue);
        surfaceOptions.appendChild(newOption);

        //Loop through all the values in the times variable and write in the option tags
        for (i = 0; i < surfaceValuesL; i++) {

            newOption = document.createElement("option");
            var parts = surfaceValues[i].split("|");
            var textValue = "";

            textValue = document.createTextNode("on " + parts[0].toLowerCase());
            newOption.value = parts[1];
            newOption.appendChild(textValue);

            surfaceOptions.appendChild(newOption);
        }
    },

    submitForm: function () {

        var self = this;
        var dateVal = document.getElementById("CHW-AS-Date").value;
        var timeVal = document.getElementById("CHW-AS-Time").value;
        var durationVal = document.getElementById("CHW-AS-Duration").value;
        var surfaceVal = document.getElementById("CHW-AS-Surface").value;
        var minimumSelectedIntervals = self.getSelectedInterval();
        var errorMsg = document.createElement('p');
        var container = document.getElementsByClassName('CHW-AS-container')[0];

        var submitString = self.variables.formSubmitURL +
            "?Date=" + dateVal +
            "&Time=" + timeVal +
            "&Duration=" + durationVal +
            "&Surface=" + surfaceVal;

        errorMsg.id = 'CHW-AS-minimum-booking-error-msg';
        errorMsg.className = 'CHW-AS-minimum-booking-error-msg';

        if (minimumSelectedIntervals >= parseInt(this.variables.minimumBookingIntervals, 10)) {
            document.location.href = submitString;
        } else if (!document.getElementById('CHW-AS-minimum-booking-error-msg')) {
            errorMsg.innerHTML = 'Your booking does not meet the minimum duration. Please extend finish time.';
            container.appendChild(errorMsg);
        }
    },

    getSelectedInterval: function () {
        var selectedIntervalDuration = parseFloat(document.getElementById('CHW-AS-Duration').value, 10);
        var defaultIntervals = parseInt(this.variables.bookingInterval, 10);

        if (defaultIntervals !== null && typeof defaultIntervals !== 'undefined') {
            return Math.floor(selectedIntervalDuration / defaultIntervals);
        } else {
            return false;
        }
    },

    getScripts: function (url, callback) {
        var thisPageUsingOtherJSLibrary = false,
            supportedVersion = null;

        var getScript = function (url, callback) {
            var script = document.createElement('script');
            script.src = url;

            var body = document.getElementsByTagName('body')[0],
                done = false;

            // Attach handlers for all browsers
            script.onload = script.onreadystatechange = function () {

                if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

                    done = true;

                    // callback function provided as param
                    callback();

                    script.onload = script.onreadystatechange = null;
                };
            };

            body.appendChild(script);
        };


        var getjQueryVersion = function () {
            return jQuery.fn.jquery;
        };

        var comparejQueryVersions = function (v1, v2) {
            //v1 is the existing version
            //v2 is the minimum spec
            //This function returns "true" if v1 meets the minimum spec (equal or greather than)
            //This function returns "false" if v2 DOES NOT meet the minimum spec

            var v1arr = v1.split("."),
                v2arr = v2.split("."),
                supported = false;

            if (v1arr[0] && v1arr[1] && v2arr[0] && v2arr[1]) {

                if (parseInt(v2arr[0]) < parseInt(v1arr[0])) {
                    supported = true;
                }

                if (parseInt(v1arr[0]) == parseInt(v2arr[0])) {
                    if (parseInt(v1arr[1]) >= parseInt(v2arr[1])) {
                        supported = true;
                    }
                }
            }

            return supported;
        };

        var jQueryLoaded = function () {
            return (typeof jQuery == 'undefined') ? false : true;
        };

        function getSelectTwo() {
            jQuery(function () {

                jQuery.noConflict();

                //Get select2 - for styled selects
                var selectTwo = document.createElement("script");
                selectTwo.src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js";

                var body = document.getElementsByTagName("body")[0];

                //Select2 load event (once the JS file has loaded)
                selectTwo.onload = function () {

                    jQuery("#CHW-availability-search select").select2({
                        minimumResultsForSearch: Infinity,
                        width: "100%"
                    });

                }

                body.appendChild(selectTwo);
            });
        }

        //Check for jQuery
        if (typeof jQuery === 'undefined') {
            if (typeof $ === 'function') {
                // warning, global var
                thisPageUsingOtherJSLibrary = true;
            }

            getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', function () {
                if (typeof jQuery === 'undefined') {

                    // Super failsafe - still somehow failed...

                } else {
                    // jQuery loaded! Make sure to use .noConflict just in case
                    //fancyCode();
                    if (thisPageUsingOtherJSLibrary) {
                        // Run your jQuery Code
                        getSelectTwo();

                    } else {
                        // Use .noConflict(), then run your jQuery Code
                        getSelectTwo();
                    }
                }
            });

        } else {
            supportedVersion = comparejQueryVersions(getjQueryVersion(), '1.8');

            if (supportedVersion) {
                // Run your jQuery Code
                getSelectTwo();
            } else {
                getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', function () {
                    getSelectTwo();
                });
            }
        }
    },

    utilities: {
        parseISO8601: function (dateStringInRange) {
            var isoExp1 = /(\d{4})-(\d{2})-(\d{2})/;
            var isoExp2 = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;

            var parts = isoExp2.exec(dateStringInRange);
            if (parts)
                return new Date(+parts[1], +parts[2] - 1, +parts[3], +parts[4], +parts[5], +parts[6]);

            parts = isoExp1.exec(dateStringInRange);
            if (parts)
                return new Date(+parts[1], +parts[2] - 1, +parts[3]);

            return new Date(NaN);
        }
    }
}

CLUBHOUSEWIDGET.init();