(function ($) {

    $(document).ready(function () {
        var $widget = $("#DisruptionsSummaryWidget");
        if ($widget.length === 1) {
            $(".diss_loading", $widget).show();
            $widget.on("click", ".diss_title", function () {
                expandOrCollapseSummary($(this))
            });
            $widget.on("click", ".diss_share_toggle", function () {
                expandOrCollapseSocialLinks($(this).closest(".diss_share"));
            });
            var $selectionForm = $(".diss_selection", $widget).closest("form");
            showSelectionOptions($selectionForm);
            var refreshFrequency = Number($("#DisruptionsRefreshFrequencyInSeconds", $widget).val());
            if (isNaN(refreshFrequency) || (refreshFrequency <= 0)) {
                refreshFrequency = 300;
            }
            var getContext = {
                form: $selectionForm,
                refreshFrequency: refreshFrequency,
                timer: null
            };
            getDisruptions(getContext);
            $("select", $selectionForm).change(function () {
                if ($(this).attr("name") === "SelectedMode") {
                    showSelectionOptions($selectionForm);
                }
                getDisruptions(getContext);
            });
        }
    });

    function expandOrCollapseSummary($itemTitle) {
        var $item = $itemTitle.closest(".diss_item");
        $itemTitle.toggleClass("expanded");
        $(".diss_item_summary", $item).slideToggle();
    };

    function expandOrCollapseSocialLinks($shareArea) {
        var $socialLinkImages = $(".diss_social_link img", $shareArea);
        if ($shareArea.hasClass("expanded")) {
            $socialLinkImages.animate({ "height": "0px" });
            $shareArea.removeClass("expanded");
        }
        else {
            $shareArea.addClass("expanded");
            $socialLinkImages.animate({ "height": "25px" });
        }
    };

    function showSelectionOptions($selectionForm) {
        var selectedMode = $("#SelectedMode", $selectionForm).val();
        $("#SelectedBusArea", $selectionForm).toggle(selectedMode.toLowerCase() === "bus");
        $("#SelectedTramRoute", $selectionForm).toggle(selectedMode.toLowerCase() === "tram");
        $("#SelectedTrainOperator", $selectionForm).toggle(selectedMode.toLowerCase() === "train");
    };

    function getDisruptions(getContext, autoRefresh) {
        resetGetDisruptionsTimer(getContext);
        var $widget = $("#DisruptionsSummaryWidget");
        $(".diss_errorMessage", $widget).empty().hide();
        var formData = getContext.form.serialize();
        var actionUrl = window.globals.controllerActionUrl.replace("controllername", "DisruptionsSummaryWidget") + "/Disruptions";
        $.ajax({
            url: actionUrl,
            type: 'POST',
            data: formData,
            success: function (data) {
                $(".diss_loading", $widget).hide();
                $(".diss_results", $widget).html(data);
                setGetDisruptionsTimer(getContext);
            },
            error: function (jqXhr) {
                $(".diss_loading", $widget).hide();
                if (autoRefresh && jqXhr.status === 500) {
                    var redirectUrl = window.globals.controllerActionUrl.replace("controllername", "disruptions");
                    var selectedMode = $("#SelectedMode", getContext.form).val();
                    if (selectedMode && !/^\s*$/.test(selectedMode)) {
                        redirectUrl += "?mode=" + selectedMode;
                    }
                    window.location.href = redirectUrl;
                }
                else {
                    var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                        jqXhr.statusText + ' (' + jqXhr.status + ')';
                    $(".diss_errorMessage", $widget).html(errorMessage).show();
                    setGetDisruptionsTimer(getContext);
                }
            }
        });
    };

    function setGetDisruptionsTimer(getContext) {
        var timeOut = getContext.refreshFrequency * 1000;
        getContext.timer = setTimeout(function () { getDisruptions(getContext, true); }, timeOut);
    };

    function resetGetDisruptionsTimer(getContext) {
        if (getContext.timer) {
            clearTimeout(getContext.timer);
            getContext.timer = null;
        }
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {
        var $widget = $("#DisruptionsWidget");
        if ($widget.length === 1) {
            getDisruptions($widget);
        }
    });

    function getDisruptions($widget) {
        var actionUrl = window.globals.controllerActionUrl.replace("controllername", "DisruptionsWidget") + "/Disruptions";
        $.ajax({
            url: actionUrl,
            type: 'GET',
            success: function (data) {
                $(".dis_errorMessage", $widget).hide();
                $(".dis_loading", $widget).hide();
                $(".dis_contentContainer", $widget).html(data);
            },
            error: function (jqXhr) {
                var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                    jqXhr.statusText + ' (' + jqXhr.status + ')';
                $(".dis_errorMessage", $widget).html(errorMessage).show();
                $(".dis_loading", $widget).hide();
            }
        });
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {

        $("body").on("click keypress", ".expander_header", function (e) {
            e.preventDefault();
            var $expanderContent = $(this).next(".expander_content");
            $expanderContent.slideToggle();
            $(this).toggleClass("expanded");
        });

    });

})(jQuery);
(function ($) {

    $(document).ready(function () {
        var href = $(".blockLink").attr("href");
        if (href !== undefined) {
            $(".blockLink").addClass("stretched-link");
        }
        else { $(".blockLink").removeClass("stretched-link") };
    });

})(jQuery);
(function ($) {

    $(document).on("change", ".jp_form .jp_leave_arrive_label input", function () {
        $(".jp_leave_arrive_label", $(this).closest(".jp_leave_arrive")).each(function () {
            $(this).toggleClass("selected", $("input", $(this)).is(":checked"));
        });
    });

    $(document).on("change", ".jp_form #SelectedMonth", function () {
        var $formSection = $(this).closest(".jp_form");
        var $daySelect = $("#SelectedDay", $formSection);
        var daysPerMonth = $daySelect.data("days").split(",");
        var selectedMonthIndex = $(this).prop("selectedIndex");
        if (selectedMonthIndex < daysPerMonth.length) {
            var daysInSelectedMonth = daysPerMonth[selectedMonthIndex].split("-");
            if (daysInSelectedMonth.length === 2) {
                var firstDay = Number(daysInSelectedMonth[0]);
                var lastDay = Number(daysInSelectedMonth[1]);
                if (!isNaN(firstDay) && !isNaN(lastDay) && (firstDay <= lastDay)) {
                    $daySelect.empty();
                    for (var day = firstDay; day <= lastDay; day++) {
                        $daySelect.append($("<option/>").val(day).html(day));
                    }
                }
            }
        }
    });

    $(document).ready(function () {

        var $widget = $("#JourneyPlannerWidget");

        $(".jp_location_description", $widget).each(function () {
            var preselectedId = $(this).siblings(".jp_location_id").val();
            if (preselectedId && !/^\s*$/.test(preselectedId)) {
                $(this).data("selectedValue", $(this).val());
            }
            else {
                $(this).val("");
            }

            $(this)
                .attr("spellcheck", false)
                .setAutocomplete()
                .blur(function () { validateLocationSelection($(this)); });
        });

        $(".jp_button_plan", $widget).click(function (e) {
            e.preventDefault();
            var $form = $(this).closest("form");
            if (validateForm($form)) {
                $(".jp_error_plan", $form).empty().hide();
                var formData = $form.serialize();
                var actionUrl = window.globals.controllerActionUrl.replace("controllername", "JourneyPlannerWidget") + "/PlanJourney";
                $.ajax({
                    url: actionUrl,
                    type: 'POST',
                    data: formData,
                    success: function (data) {
                        if (data.formData) {
                            postToJourneyPlanner(data.redirectUrl, data.formData);
                        }
                        else {
                            window.location.href = data.redirectUrl;
                        }
                    },
                    error: function (jqXhr) {
                        var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                            jqXhr.statusText + ' (' + jqXhr.status + ')';
                        $(".jp_error_plan", $form).html(errorMessage).show();
                    }
                });
            }
        });

    });

    function validateForm($form) {
        var isValid = true;
        $(".jp_location_description", $form).each(function () {
            $(this).data("validateSelection", true);
            if (!validateLocationSelection($(this))) {
                isValid = false;
            }
        });
        return isValid;
    };

    function validateLocationSelection($element) {
        var isValid = true;
        if ($element.data("validateSelection") === true) {
            var enteredValue = $element.val();
            var selectedValue = $element.data("selectedValue");
            isValid = !/^\s*$/.test(enteredValue) && enteredValue === selectedValue;
            $element.siblings(".jp_error_select").toggle(!isValid);
        }
        return isValid;
    };

    $.fn.setAutocomplete = function () {
        var $descriptionElement = $(this);
        $descriptionElement.autocomplete({
            source: function (request, response) {
                var actionUrl = window.globals.controllerActionUrl.replace("controllername", "JourneyPlannerWidget") + "/SearchLocations";
                $.ajax({
                    url: actionUrl,
                    type: 'POST',
                    data: { searchTerm: request.term },
                    success: function (data) {
                        if (data && $.isArray(data) && data.length > 0) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Description,
                                    value: item
                                }
                            }));
                        }
                        else {
                            var noResult = [
                                {
                                    label: "Sorry, no match found...",
                                    value: null
                                }
                            ];
                            response(noResult);
                        }
                    },
                    error: function (jqXhr) {
                        var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                            jqXhr.statusText + ' (' + jqXhr.status + ')';
                        var errorResult = [
                            {
                                label: errorMessage,
                                value: null
                            }
                        ];
                        response(errorResult);
                    }
                });
            },
            delay: 500,
            minLength: 3,
            select: function (e, ui) {
                e.preventDefault();
                if (ui.item.value) {
                    $(this).val(ui.item.label);
                    $(this).data("selectedValue", ui.item.label);
                    $(this).siblings(".jp_location_id").val(ui.item.value.Id);
                    $(this).siblings(".jp_location_name").val(ui.item.value.Name);
                    $(this).siblings(".jp_location_type").val(ui.item.value.Type);
                    $(this).siblings(".jp_location_latitude").val(ui.item.value.Latitude);
                    $(this).siblings(".jp_location_longitude").val(ui.item.value.Longitude);
                    $(this).siblings(".jp_error_select").hide();
                }
            },
            classes: {
                "ui-autocomplete": "ui-autocomplete-jp",
                "ui-autocomplete-input": "ui-autocomplete-input-jp"
            }
        });
        return $(this);
    };

    function postToJourneyPlanner(url, formData) {
        var $form = $("<form></form>");
        $form.attr("action", url);
        $form.attr("method", "POST");
        for (var key in formData) {
            var $field = $("<input></input>");
            $field.attr("type", "hidden");
            $field.attr("name", key);
            $field.attr("value", formData[key]);
            $form.append($field);
        }
        $form.appendTo("body").submit();
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {

        $("#LatestNewsWidget").on("click", ".latest_news_show_button", function (e) {
            e.preventDefault();
            var actionUrl = window.globals.controllerActionUrl.replace("controllername", "LatestNewsWidget") + "/Show";
            $.ajax({
                url: actionUrl,
                type: 'GET',
                data: {
                    showMax: $(this).data("show-max")
                },
                success: function (data) {
                    $(".latest_news").html(data);
                }
            });
        });

    });

})(jQuery);

(function ($) {


$(document).ready(function () {
    //initialising variables
    var stopSearch = false;                                                         //determines whether second Ajax which returns stops for service should run
    var dataF = [];                                                                 //combined response from location and service queries - used globally to aid station streamlining
    var noResult;                                                                   //returns list with "Sorry, no match found..." message

    var url = (window.location.protocol + "//" + window.location.host + window.location.pathname).split("en-gb")[0];
    console.log(url);

    $('#txtLiveDept').autocomplete({
        source: function (request, response) {
            SetLoadingSwitch();                                                     //initiates the loading animation when request is started and hides the reset button
            if (stopSearch === false) {                                             //returns combined Location and Service responses
                $.ajax({
                    url: url + '/en-gb/LiveDeparturesWidget/CombinedAjax',
                    data: "{ inputTerm: '" + request.term + "'}",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    autoFocus: true,
                    success: function (data) {
                        ResetLoadingSwitch();                                       //shows reset button and stops loading animation when response is generated
                        CombineResponseArrays(data);
                        if (dataF.length === 0) {                                   //returns "No matches found..." message if no results are returned
                            NoResults(response);
                            response(noResult);
                        }
                        else {
                            response($.map(dataF, function (item) {                 //generates the list if response is received
                                ReturnLabel(item);                                  //generates the label - differs for location and service response
                                return {
                                    dataF: dataF,
                                    Label: label,
                                    FullText: item.FullText,
                                    Category: item.Category,
                                    Latitude: item.Latitude,
                                    Longitude: item.Longitude,
                                    value: label,
                                    StopLabel: item.StopLabel,
                                    ServiceId: item.ServiceId,
                                    Description: item.Description
                                }
                            }));
                        }
                    },
                    failure: function err(response) {
                        console.log("error: " + response.d);
                    }
                });
            }
            else if (stopSearch === true) {
                $.ajax({
                    url: url + '/en-gb/LiveDeparturesWidget/GetStops',
                    data: "{ serviceId: '" + sel + "'}",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    autoFocus: true,
                    success: function (data) {
                        ResetLoadingSwitch();                                      //shows reset button and stops loading animation when response is generated
                        if (data.length === 0) {
                            NoResults(response);                                   //returns "No matches found..." message if no results are returned
                            response(result);
                        }
                        else {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name + ", " + item.StopLabel,
                                    Name: item.Name,
                                    Category: item.Category,
                                    Latitude: item.Latitude,
                                    Longitude: item.Longitude,
                                    value: item.Name + ", " + item.StopLabel,
                                    StopLabel: item.StopLabel,
                                };
                            }));
                        }
                        ShowAutocompleteList();                                   //forces to show autocomplete list for second ajax - stop search for service
                    },
                });
            }
        },
        delay: 1000,
        select: function (e, selected) {
            var item = selected.item;
            if (selected.item.ServiceId !== undefined) {                           //if selected item is service - has service id, stop search - second ajax call is forced
                sel = selected.item.ServiceId;
                ForceStopSearch(sel);
            }
            else {
                console.log(selected.item.value);
                var nameStationFilter = selected.item.value;                      //takes value of selected item to evaluate if we are searching for station
                if (nameStationFilter.toLowerCase().includes("rail station") === true || nameStationFilter.toLowerCase().includes("railway station") === true || nameStationFilter.toLowerCase().includes("train station")) {
                    console.log("in stations");
                    var found = false;
                    for (i = 0; i < dataF.length; i++) {
                        if (dataF[i].StopLabel !== undefined) {
                            $("#stopLabel").val(dataF[i].StopLabel);
                            $("#category").val("TRAIN_STATION");
                            $("#Name").val(dataF[i].FullText);
                            $("#Latitude").val(dataF[i].Latitude);
                            $("#Longitude").val(dataF[i].Longitude);
                            found = true;
                            console.log($("#stopLabel").val() + $("#category").val() + $("#Name").val() + $("#Latitude").val() + $("#Longitude").val());
                            break;
                        }
                    }
                    if (found === false) {
                        $("#name").val(nameStationFilter);
                        $("#category").val(selected.item.Category);
                        $("#longitude").val(selected.item.Longitude);
                        $("#latitude").val(selected.item.Latitude);
                        $("#stopLabel").val(selected.item.StopLabel);
                    }                                                             //if search terms includes station, list is searched for returned items containing rail stop and and this item is used to build url and redirect - this is to allow dirct access to departures rather than further selection from stops when positive choise of railway station has already been made by user - requested by marketing
                }
                else {                                                            //else all values used to build the url are passed from selected item
                    $("#Name").val(selected.item.value);
                    $("#category").val(selected.item.Category);
                    $("#Longitude").val(selected.item.Longitude);
                    $("#Latitude").val(selected.item.Latitude);
                    $("#stopLabel").val(selected.item.StopLabel);
                }
            }
            $("#goButton").focus();                                              //shifts focus to go button after item has been selected - this is to allow for keyboard based submitting
        },
        minLength: 0,
        classes: {
            "ui-autocomplete": "ui-autocomplete-ld"
        }
    });

    //*******************************   Functions   ******************************//

    //forces stop search when service is selected from first response
    function ForceStopSearch(sel) {
        stopSearch = true;
        $("#txtLiveDept").autocomplete("search");
    }

    //decides if user is searching for station, searches the returned item for railstop and if found, uses the railstop to build query - this is to allow users to go directly to departure after positive action of selecting the railwaystation instead of being forced to choose from another list of stops when forwarded to Trapeze - this has been done on request by marketing
    function StreamlineStations(nameStationFilter, item) {
        console.log("in stations");
        var found = false;
        for (i = 0; i < dataF.length; i++) {
            if (dataF[i].StopLabel !== undefined) {
                $("#stopLabel").val(dataF[i].StopLabel);
                $("#category").val("TRAIN_STATION");
                $("#Name").val(dataF[i].FullText);
                $("#Latitude").val(dataF[i].Latitude);
                $("#Longitude").val(dataF[i].Longitude);
                found = true;
                console.log($("#stopLabel").val() + $("#category").val() + $("#Name").val() + $("#Latitude").val() + $("#Longitude").val());
                break;
            }
        }
        if (found === false) {
            $("#name").val(nameStationFilter);
            $("#category").val(selected.item.Category);
            $("#longitude").val(selected.item.Longitude);
            $("#latitude").val(selected.item.Latitude);
            $("#stopLabel").val(selected.item.StopLabel);
        }
    }

    //returns "Sorry, no match found..." message if no response is returned
    function NoResults(response) {
        noResult = [
            {
                label: 'Sorry, no match found...',
                value: response.term
            }
        ];
    }

    //forces to show an autocomplete list of suggestions after second ajax returning stops for service ran
    function ShowAutocompleteList() {
        var e = jQuery.Event("keydown");
        e.which = 40;                                                       //forces the arrow down button press - can be any button to trigger displaying of the list but arrow down button is adviced to bring up the list in documentation
        $("#txtLiveDept").trigger(e);
    }

    //combines the location and service response - to bring in line with Trapeze
    function CombineResponseArrays(data) {
        var resp1 = data.Locations;
        var resp2 = data.ServiceResponses;
        if (resp1 !== undefined && resp2 !== undefined) {
            dataF = resp2.concat(resp1);
        }
    };

    //shows the loading wheel when request is made, hides the reset button
    function SetLoadingSwitch() {
        $("#spinnerCont").removeClass("d-none");
        $("#resetCont").addClass("d-none");
    }

    //hides the loading wheel when response is returned and shows the reset button
    function ResetLoadingSwitch() {
        $("#spinnerCont").addClass("d-none");
        if ($("#txtLiveDept").val().length > 0) {
            $("#resetCont").removeClass("d-none");
        }
    };

    //determins what label is used to build the autocomplete list - different labels for service and location queries
    function ReturnLabel(item) {
        if (item.FullText === undefined) {
            label = item.ServiceNumber + ", " + item.Description;
        }
        else {
            label = item.FullText;
        }
    };

    //resets all values
    function Reset() {
        $("#txtLiveDept").autocomplete("disable");
        $("#resetCont").addClass("d-none");
        $("#txtLiveDept").val("");
        $("#txtLiveDept").removeClass("ui-autocomplete-loading");
        $("#stopLabel").val();
        $("#category").val();
        $("#name").val();
        $("#latitude").val();
        $("#longitude").val();
        var stopSearch = false;
        var dataF = [];
        var found = false;
        var selectedIs = false;
    };

    //gets category to pass on submit to form the url
    function GetCategory() {
        var cat = $('#category').val();

        if (cat === "locality") {
            $("#category").val("LOCALITY");
        }
        if (cat === "railStop") {
            $("#category").val("TRAIN_STATION");
        }
        if (cat === "busStop") {
            $("#category").val("BUS_STOP");
        }
        if (cat === "address") {
            $("#category").val("LOCATION");
        }
        if (cat === "street") {
            $("#category").val("LOCATION");
        }
        if (cat === "pointOfInterest") {
            $("#category").val("LOCATION");
        }
        if (cat === "coachStop") {
            $("#category").val("COACH_STOP");
        }
        if (cat === "allstops") {
            $("#category").val("STOP");
        }
    };

    //*******************************   Listeners   ******************************//

    //disables autocomplete when backspace or delete are pressed and input box is empty - this hides the suggestion list on input
    $("#txtLiveDept").on("keyup", function (event) {
        if ((event.which === 8 || event.which === 46) && $(this).val().length < 1) {
            console.log("in condition");
            $(this).autocomplete("disable");
        }
    });

    //re-enables autocomplete on user input after it has been disabled by erasing values from textbbox by delete or backspace keys
    $("#txtLiveDept").on("keydown", function (event) {
        $(this).autocomplete("enable");
    });

    //validation is handled on server but to make the warning nicer, I do this on click, this also ensures that the correct category is sent to back end as well as resetting all values when redirected to trapeze to rrevent storage of old values on pressing the back button
    $("#goButton").on("click", function () {
        GetCategory();
        if ($("#txtLiveDept").val() === "") {
            $("#warning").removeClass("d-none");
        }
        Reset();
    });

    //x button in the search box - resets all values and hides lists when clicked
    $("#btnReset").on("click", function () {
        Reset();
    });

    //hides the watning on click to textbox //disables autocomplete on click and hides loading/x buttons for IE compatibility
    $("#txtLiveDept").on("click", function () {
        if ($(this).val() === "") {
            $(this).autocomplete("disable");
            $("#spinnerCont").addClass("d-none");
            $("#resetCont").addClass("d-none");
        };
        $("#warning").addClass("d-none");
    });

    //////////////////////////////////////////// GeoLocation//////////////////////////////////////////////////////////////

    var name = "";
    var lat = 0;
    var lng = 0;

    // Current Location click - uses HTML5 Geolocation API to fetch latitude and longitude - those are then passed to Google Geocoding API to find address
    $('#geoButton').click(function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(processPosition, handleError,
                {
                    maximumAge: 50000,
                    timeout: 20000,
                    enableHighAccuracy: true
                });
        }
        else {
            alert("Sorry, your browser does not support the Geolocation!");
        }
    });

    //This function processes latitude and longitude from HTML5 Geolocation API to find the address
    function processPosition(position) {
        var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en&key=AIzaSyAmNg6t6W6iMdTUe6e2naXl04v19DVJ4do';

        $.getJSON(url).done(function (location) {
            console.log(location);
            name = location.results[0].formatted_address;
            lat = position.coords.latitude;
            lng = position.coords.longitude;
            PostCurrentLocationData();
        });
    }

    //Handles HTML5 Geolocation Errors
    var handleError = function (error) {
        switch (error.code) {
            case error.UNKNOWN_ERROR:
                alert("We have encountered an Unknown Error");
                break;
            case error.TIMEOUT:
                alert("The request to get user location timed out. Please, try again.");
                break;
            case error.PERMISSION_DENIED:
                alert("User denied the request for Geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("Location information is unavailable.");
                break;
        }
    };

    //Redirects the user to trapeze to show them stops in their area based on Geolocation and Geocoding results
    function PostCurrentLocationData() {
        var url = "https://tsy.yorkshiretravel.net/lts/#/liveDepartures";

        postData = "?name=" + name; //comes from Google Geocoding - function processPosition
        postData += "&type=LOCATION"; //fixed term
        postData += "&latitude=" + lat; //comes from HTML5 Geolocation API
        postData += "&longitude=" + lng; //comes from HTML5 Geolocation API

        console.log(postData);

        var map = window.parent.open(url + postData, "_blank");

        //As this opens a new window, pop ups need to be allowed. 
        //if (map) {
        //    map.focus();
        //} else {
        //    alert('You must allow popups to view this journey.');
        //}
    }
});

})(jQuery);
(function ($) {

    $(document).ready(function () {

        var $widget = $("#SeniorPassAddressChangeWidget");

        $(".spac_submit", $widget).click(function (e) {
            e.preventDefault();
            var $form = $(this).closest("form");
            $(".spac_messages", $form).empty().hide();
            if (validateForm($form)) {
                $("html").addClass("wait");
                var formData = $form.serialize();
                var actionUrl = window.globals.controllerActionUrl.replace("controllername", "SeniorPassAddressChangeWidget") + "/Submit";
                $.ajax({
                    url: actionUrl,
                    type: 'POST',
                    data: formData,
                    success: function (data) {
                        $("html").removeClass("wait");
                        if (data.Success) {
                            $(".spac_form_container", $widget).hide();
                            $(".spac_confirmation", $widget).show();
                        }
                        else if (data.Messages && $.isArray(data.Messages) && (data.Messages.length > 0)) {
                            showMessages(data.Messages, "error");
                        }
                        else {
                            var message = "Invalid response.";
                            showMessages([message], "error");
                        }
                    },
                    error: function (jqXhr) {
                        $("html").removeClass("wait");
                        var errorMessage = jqXhr.status === 0 ? "An unexpected error occurred." :
                            jqXhr.statusText + " (" + jqXhr.status + ")";
                        showMessages([errorMessage], "error");
                    }
                });
            }
        });
    });

    function validateForm($form) {
        var validator = $form.validate();
        var isValid = validator && validator.form();
        if (!isValid) {
            $(".input-validation-error", $form).get(0).scrollIntoView();
        }
        return isValid;
    };

    function clearForm($form) {
        $form.find(":input").not(":button, :submit, :reset, :hidden, :checkbox, :radio").val("");
        $form.find(":checkbox, :radio").prop("checked", false);
    };

    function showMessages(messages, messageClass) {
        var $messagesElement = $(".spac_messages", $("#SeniorPassAddressChangeWidget"));
        if (messages && $.isArray(messages)) {
            messages.forEach(function (message) {
                var $messageElement = $("<li></li").html(message).addClass(messageClass);
                $messagesElement.append($messageElement);
            });
            $messagesElement.show();
        }
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {

        var $widget = $("#TellUsWidget");

        $(".tell_us_submit", $widget).click(function (e) {
            e.preventDefault();
            var $form = $(this).closest("form");
            $(".tell_us_messages", $form).empty().hide();
            if (validateForm($form)) {
                $("html").addClass("wait");
                var formData = $form.serialize();
                var actionUrl = window.globals.controllerActionUrl.replace("controllername", "TellUsWidget") + "/Submit";
                $.ajax({
                    url: actionUrl,
                    type: 'POST',
                    data: formData,
                    success: function (data) {
                        $("html").removeClass("wait");
                        if (data.Success) {
                            showMessages(data.Messages, "success");
                            clearForm($form);
                        }
                        else if (data.Messages && $.isArray(data.Messages) && (data.Messages.length > 0)) {
                            showMessages(data.Messages, "error");
                        }
                        else {
                            var message = "Invalid response.";
                            showMessages([message], "error");
                        }
                    },
                    error: function (jqXhr) {
                        $("html").removeClass("wait");
                        var errorMessage = jqXhr.status === 0 ? "An unexpected error occurred." :
                            jqXhr.statusText + " (" + jqXhr.status + ")";
                        showMessages([errorMessage], "error");
                    }
                });
            }
        });

        $(".tell_us_options_box input[type='radio']", $widget).change(function () {
            $(this).closest(".tell_us_options_inner").removeClass("validation_error");
        });
    });

    function validateForm($form) {
        var validator = $form.validate();
        var isValid = validator && validator.form();
        if (!isValid) {
            var handled = false;
            var $optionsBox = $(".tell_us_options_box", $form);
            $("input[type='radio']", $optionsBox).each(function () {
                if ($(this).hasClass("input-validation-error")) {
                    $(".tell_us_options_inner", $optionsBox).addClass("validation_error");
                    $optionsBox.get(0).scrollIntoView();
                    handled = true;
                    return false;
                }
            });
            if (!handled) {
                $(".input-validation-error", $form).get(0).scrollIntoView();
            }
        }
        return isValid;
    };

    function clearForm($form) {
        $form.find(":input").not(":button, :submit, :reset, :hidden, :checkbox, :radio").val("");
        $form.find(":checkbox, :radio").prop("checked", false);
    };

    function showMessages(messages, messageClass) {
        var $messagesElement = $(".tell_us_messages", $("#TellUsWidget"));
        if (messages && $.isArray(messages)) {
            messages.forEach(function (message) {
                var $messageElement = $("<li></li").html(message).addClass(messageClass);
                $messagesElement.append($messageElement);
            });
            $messagesElement.show();
        }
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {
        if (window.location.search !== "") {
            $(".disruptionsCollapse").addClass("d-block");
            $(".disruptionsDiv i").addClass("fas fa-minus");
        }
        else {
            $(".disruptionsCollapse").addClass("d-none");
            $(".disruptionsDiv i").addClass("fas fa-plus");
        }

        var url = (window.location.protocol + "//" + window.location.host + window.location.pathname).split("en-gb")[0];
        var selectedItem = "";
        var userSelected = false;

        jQuery.ui.autocomplete.prototype._resizeMenu = function () {
            var ul = this.menu.element;
            ul.outerWidth(this.element.outerWidth());
        }

        $("#dBox").on("keydown", function () {
            $("#dBox").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: url + '/en-gb/TFNDisruptionsSearchWidget/CombinedAjax',
                        data: "{ inputTerm: '" + request.term + "'}",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            console.log(data);
                            if (data != null) {
                                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                                response($.grep(data, function (item) {
                                    return matcher.test(item);
                                }));
                            }
                        },
                    });
                },
                autoFocus: true,
                select: function (e, selected) {
                    userSelected = true;
                    $("#tfnSubmit").attr("href", url + "en-gb/newsupdates/Disruptions?searchTerm=" + encodeURIComponent(selected.item.value));
                    $("#dBox").val(selected.item.value)
                    setTimeout(function () {
                        $("#tfnSubmit").focus();
                    }, 0);
                },
                minLength: 1,
                classes: {
                    "ui-autocomplete": "ui-autocomplete-ld"
                }
            });
        });

        $("#dBox").on("keyup", function () {

            setTimeout(function () {
                if ($("#ui-id-1").css("display") == "none" && $("#dBox").val() != "Please select item from the dropdown list." && $("#dBox").val().length > 1 && userSelected == false) {
                    $("#dBox").val("No known disruptions for this search.");
                    $("#dBox").css("color", "red")
                    console.log("invisible")
                };
            }, 1000);
        });

        $("#dBox").on("click", function () {
            $("#dBox").val("");
            $("#dBox").css("color", "black")
        });

        $("#tfnSubmit").on("click", function (e) {
            if ($("#dBox").val() == null || userSelected == false) {
                e.preventDefault();
                $("#dBox").val("Please select item from the dropdown list.")
                $("#dBox").css("color", "red")
            }
            else {
                $("#dBox").val("");
            };
        });

        $(".disruptionsDiv").click(function (event) {
            $(this).parent().next('.disruptionsCollapse').toggleClass("d-none");
            $(this).parent().next('.disruptionsCollapse').toggleClass("d-block");
            $(this).next().children("i").toggleClass("fas fa-plus");
            $(this).next().children("i").toggleClass("fas fa-minus");
            $(this).children("i").toggleClass("fas fa-plus");
            $(this).children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        $(".consDiv").click(function (event) {
            $(this).nextUntil(".consDiv", ".consCollapse").toggleClass("d-none");
            $(this).children().children("i").toggleClass("fas fa-plus");
            $(this).children().children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        $(".stopsDiv").click(function (event) {
            $(this).siblings(".stopsCollapse").toggleClass("d-none");
            $(this).children("i").toggleClass("fas fa-plus");
            $(this).children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        //Same code as above, but for keypress instead of mouse

        $(".disruptionsDiv").keypress(function (event) {
            $(this).parent().next('.disruptionsCollapse').toggleClass("d-none");
            $(this).parent().next('.disruptionsCollapse').toggleClass("d-block");
            $(this).next().children("i").toggleClass("fas fa-plus");
            $(this).next().children("i").toggleClass("fas fa-minus");
            $(this).children("i").toggleClass("fas fa-plus");
            $(this).children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        $(".consDiv").keypress(function (event) {
            $(this).nextUntil(".consDiv", ".consCollapse").toggleClass("d-none");
            $(this).children().children("i").toggleClass("fas fa-plus");
            $(this).children().children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        $(".stopsDiv").keypress(function (event) {
            $(this).siblings(".stopsCollapse").toggleClass("d-none");
            $(this).children("i").toggleClass("fas fa-plus");
            $(this).children("i").toggleClass("fas fa-minus");
            event.stopPropagation();
        });

        

        $(".socialCollapseContainer").click(function (event) {
            $(this).siblings(".socialCollapse").toggleClass("d-none");
            event.stopPropagation();
        });

        //mouse becomes pointer when hovered over the plus signs
        $(".disruptionsDiv").mouseenter(function () {
            $(this).css("cursor", "pointer");
        });

        $(".consDiv").mouseenter(function () {
            $(this).css("cursor", "pointer");
        });

        $(".stopsDiv").mouseenter(function () {
            $(this).css("cursor", "pointer");
        });

        //on keypress expand social menu
        $(".socialCollapseContainer").keypress(function (event) {
            $(this).siblings(".socialCollapse").toggleClass("d-none");
            event.stopPropagation();
        });

        $(".socialImg").mouseenter(function () {
            $(this).css("max-width", "30px");
            $(this).css("cursor", "pointer");
        });

        $(".socialImg").mouseleave(function () {
            $(this).css("max-width", "25px");
        });

        $(".socialLink").mouseleave(function () {
            $(".socialLink").css("color", "white");
        });

        $(".socialLink").mouseenter(function () {
            $(this).css("color", "#b6bbce");
        });

        $(".copyLink").on("click", function (event) {
            event.preventDefault();
            var linkUrl = window.location.origin + window.location.pathname + $(this).attr("href");

            document.addEventListener('copy', function (e) {
                e.clipboardData.setData('text/plain', linkUrl);
                e.preventDefault();
            }, true);

            document.execCommand('copy');

            $(this).attr("title", "Link copied");
            $(this).tooltip("enable");
            $(this).tooltip("show");
            setTimeout(function () {
                $(".copyLink").tooltip("hide");
            }, 1500);
        });


        //copies link on keypress and sends up shows message saying link copied
        $(".copyLink").on("keypress", function (event) {
            event.preventDefault();
            var linkUrl = window.location.origin + window.location.pathname + $(this).attr("href");

            document.addEventListener('copy', function (e) {
                e.clipboardData.setData('text/plain', linkUrl);
                e.preventDefault();
            }, true);

            document.execCommand('copy');

            $(this).attr("title", "Link copied");
            $(this).tooltip("enable");
            $(this).tooltip("show");
            setTimeout(function () {
                $(".copyLink").tooltip("hide");
            }, 1500);
        });

        $(".copyLink").on("mouseout", function () {
            $(this).tooltip("disable")
        });

        $(".twitter").on("click", function (event) {
            var url = window.location.origin + window.location.pathname + $(this).siblings("a").attr("href");
            var href = "https://www.twitter.com/share?url=" + encodeURIComponent(url);
            window.open(href, "_blank");
        });

        //on keypress goes to twitter url
        $(".twitter").on("keypress", function (event) {
            var url = window.location.origin + window.location.pathname + $(this).siblings("a").attr("href");
            var href = "https://www.twitter.com/share?url=" + encodeURIComponent(url);
            window.open(href, "_blank");
        });


        $(".facebook").on("click", function (event) {
            var url = window.location.origin + window.location.pathname + $(this).siblings("a").attr("href")
                ;
            //var url = "https://www.travelsouthyorksire.com"
            var href = "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(url);
            window.open(href, "_blank");
        });

        //on keypress goes to facebook url
        $(".facebook").on("keypress", function (event) {
            var url = window.location.origin + window.location.pathname + $(this).siblings("a").attr("href")
                ;
            //var url = "https://www.travelsouthyorksire.com"
            var href = "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(url);
            window.open(href, "_blank");
        });

    });

})(jQuery);
(function ($) {

    $(document).ready(function () {
        $("#TicketFinderForm").on("click", ".tf_button_search", function (e) {
            e.preventDefault();
            if (validateSelectedModes(false)) {
                $(".tf_loading").show();
                submitCurrentForm($(this), "Search");
            }
        });
        $(".tf_contentContainer").on("change", ".tf_formSection_modes input", function () {
            validateSelectedModes(true);
        });
        $("#TicketFinderResults").on("click", ".tf_button_sort", function (e) {
            e.preventDefault();
            submitCurrentForm($(this), "Sort");
        });
        $("#TicketFinderResults").on("click", ".tf_button_search_again", function (e) {
            e.preventDefault();
            $("#TicketFinderResults").hide();
            $("#TicketFinderForm").show();
            scrollToWidgetTop();
        });
        $("#TicketFinderResults").on("click", ".tf_paging_button", function (e) {
            e.preventDefault();
            $("#RequestedPage").val($(this).val());
            submitCurrentForm($(this), "Page");
        });
    });

    function validateSelectedModes(resetOnly) {
        var isValid = true;
        var $modesSection = $(".tf_formSection_modes");
        if (!resetOnly || $modesSection.hasClass("validation_error")) {
            var $selections = $("input[type='checkbox']:checked", $modesSection);
            if ($selections.length == 0) {
                isValid = false;
            }
            $modesSection.toggleClass("validation_error", !isValid);
            var $errorMessage = $modesSection.prev(".tf_errorMessage");
            $errorMessage.toggle(!isValid);
            if (!isValid) {
                scrollToWidgetTop();
            }
        }
        return isValid;
    };

    function submitCurrentForm($button, actionName) {
        var $form = $button.closest("form");
        if ($form.length > 0) {
            $(".tf_serverError", $form).empty().hide();
            var formData = $form.serialize();
            var actionUrl = window.globals.controllerActionUrl.replace("controllername", "TicketFinderWidget") + "/" + actionName;
            $.ajax({
                url: actionUrl,
                type: 'POST',
                data: formData,
                success: function (data) {
                    $(".tf_loading").hide();
                    $("#TicketFinderForm").hide();
                    $("#TicketFinderResults").html(data).show();
                    scrollToWidgetTop();
                },
                error: function (jqXhr) {
                    var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                        jqXhr.statusText + ' (' + jqXhr.status + ')';
                    $(".tf_serverError", $form).html(errorMessage).show();
                    $(".tf_loading").hide();
                    scrollToWidgetTop();
                }
            });
        }
        else {
            $(".tf_loading").hide();
        }
    };

    function scrollToWidgetTop() {
        $(".ticketFinder").get(0).scrollIntoView();
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {
        var $widget = $("#TimetableFinderWidget");
        if ($widget.length === 1) {
            $(".ttf_button", $widget).click(function (e) {
                e.preventDefault();
                var searchUrl = $(this).data("search-url");
                if ($(this).hasClass("ttf_button_bus")) {
                    var busSearchTerm = $("#TtfBusSearch", $widget).val();
                    if (busSearchTerm && !/^\s*$/.test(busSearchTerm)) {
                        redirectToSearch(searchUrl, busSearchTerm);
                    }
                    else {
                        $("#TtfBusSearch", $widget).addClass("ttf_has_error");
                    }
                }
                else if ($(this).hasClass("ttf_button_tram")) {
                    var tramSearchTerm = $("#TtfTramSearch", $widget).val();
                    if (tramSearchTerm && !/^\s*$/.test(tramSearchTerm)) {
                        redirectToSearch(searchUrl, tramSearchTerm);
                    }
                }
                else if ($(this).hasClass("ttf_button_train")) {
                    var trainTimetableId = $("#TtfTrainSearch", $widget).val();
                    if (trainTimetableId && !/^\s*$/.test(trainTimetableId)) {
                        redirectToTimetable(trainTimetableId);
                    }
                }
            });
            $("#TtfBusSearch", $widget).change(function () {
                $(this).removeClass("ttf_has_error");
            });
        }
    });

    function redirectToSearch(searchUrl, searchTerm) {
        if (searchUrl && !/^\s*$/.test(searchUrl)) {
            var searchParam = searchTerm.trim();
            if (/\s/.test(searchParam)) {
                searchParam = '"' + searchParam + '"';
            }
            var url = searchUrl + "?searchTerm=" + encodeURI(searchParam);
            window.location.href = url;
        }
    };

    function redirectToTimetable(timetableId) {
        var url = window.globals.controllerActionUrl.replace("controllername", "TimetableDetails") + "/" + timetableId;
        window.location.href = url;
    };

})(jQuery);

(function ($) {

    $(document).ready(function () {
        var actionUrl = window.globals.controllerActionUrl.replace("controllername", "TimetableFinderWidget") + "/TimetableSearch";
        var isSelected = false;
        var downloadUrl = "";
        $('.autocomplete').on("focus", function () {
            $(this).autocomplete({
                minLength: 1,
                delay: 1000,
                autoFocus: true,
                source: function (request, response) {
                    SetLoadingSwitch();
                    $.ajax({
                        url: actionUrl,
                        data: "{ inputTerm: '" + request.term + "'}",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            ResetLoadingSwitch();
                            $("#errorTF").hide();
                            response($.map(data, function (item) {                 //generates the list if response is received
                                return {
                                    Label: item.Title,
                                    value: item.Title,
                                    Title: item.Title,
                                    Url: item.Url,
                                };
                            }));
                        },
                        error: function (jqXhr) {
                            var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                                jqXhr.statusText + ' (' + jqXhr.status + ')';
                            ResetLoadingSwitch();
                            $("#errorTF").html(errorMessage).show();
                        }
                    });
                },
                select: function (e, selected) {
                    downloadUrl = selected.item.Url;
                    isSelected = true;
                    $("#goButtonTF").focus();
                },
                open: function () {
                    $("ul.ui-menu").width($(this).parent().width());
                },
                classes: {
                    "ui-autocomplete": "ui-autocomplete-tf"
                }
            });
        });

        $("#goButtonTF").on("click", function () {
            if ($("#inputTF").val() !== "" && isSelected === true) {
                window.open(downloadUrl);
                resetTF();
            }
            else {
                $("#warningTF").removeClass("d-none");
            }
        });

        $("#btnResetTF").on("click", function () {
            resetTF();
        });

        $("#inputTF").on("click", function () {
            $("#warningTF").addClass("d-none");
            $("#inputTF").val("");
        });

        $("#inputTF").on("keyup", function (event) {
            if ((event.which === 8 || event.which === 46) && $(this).val().length < 1) {
                $("#resetContTF").addClass("d-none");
            }
        });

        //shows the loading wheel when request is made, hides the reset button
        function SetLoadingSwitch() {
            $("#spinnerContTF").removeClass("d-none");
            $("#resetContTF").addClass("d-none");
        }

        //hides the loading wheel when response is returned and shows the reset button
        function ResetLoadingSwitch() {
            $("#spinnerContTF").addClass("d-none");
            $("#resetContTF").removeClass("d-none");
        }

        function resetTF() {
            $("#inputTF").val("");
            isSelected = false;
            $("#resetContTF").addClass("d-none");
        }
    });

})(jQuery);

(function ($) {

    $(document).ready(function () {
        var $widget = $("#TimetableSearchWidget");
        if ($widget.length === 1) {
            $(".tts_submit", $widget).click(function (e) {
                e.preventDefault();
                getTimetables($(this).closest("form"), "GetTimetables");
            });
            var $searchBox = $(".tts_search", $widget);
            var searchTerm = $searchBox.val();
            if (searchTerm && !/^\s*$/.test(searchTerm)) {
                getTimetables($searchBox.closest("form"), "GetTimetables");
            }
            $("#TimetableSearchResults").on("click", ".tts_paging_bar button", function (e) {
                e.preventDefault();
                if (!$(this).hasClass("current")) {
                    $("#RequestedPage").val($(this).val());
                    getTimetables($(this).closest("form"), "Page");
                }
            });

        }
    });

    function getTimetables($form, action) {
        var $widget = $("#TimetableSearchWidget");
        $(".tts_errorMessage", $widget).empty().hide();
        var validator = $form.validate();
        if (validator && validator.form()) {
            $("html").addClass("wait");
            var formData = $form.serialize();
            var actionUrl = window.globals.controllerActionUrl.replace("controllername", "TimetableSearchWidget") + "/" + action;
            $.ajax({
                url: actionUrl,
                type: 'POST',
                data: formData,
                success: function (data) {
                    $("html").removeClass("wait");
                    $("#TimetableSearchResults").html(data);
                },
                error: function (jqXhr) {
                    $("html").removeClass("wait");
                    $("#TimetableSearchResults").empty();
                    var errorMessage = jqXhr.status === 0 ? 'An unexpected error occurred.' :
                        jqXhr.statusText + ' (' + jqXhr.status + ')';
                    $(".tts_errorMessage", $widget).html(errorMessage).show();
                }
            });
        }
    };

})(jQuery);
