/*
 *  Knockout implementation of the logic
 */

AvailabilityRequest.viewModel = {
    //  Properties of the view model
    lastRequests: ko.observableArray([]),
    inboundJourneys: ko.observableArray([]),
    outboundJourneys: ko.observableArray([]),
    selectedOrigin: ko.observable(),
    selectedDestination: ko.observable(),
    isRequestViewVisible: ko.observable(true),
    isResponseViewVisible: ko.observable(false),
    isLastRequestsViewVisible: ko.observable(false),

    //  event handlers
    checkAvailability: function () {

        if (AvailabilityRequest.viewModel.selectedOrigin() && AvailabilityRequest.viewModel.selectedDestination() &&
                    AvailabilityRequest.viewModel.selectedOrigin() != AvailabilityRequest.viewModel.selectedDestination() && AvailabilityRequest.departureDate && AvailabilityRequest.returnDate) {
            var data = {
                request: {
                    Origin: AvailabilityRequest.viewModel.selectedOrigin(),
                    Destination: AvailabilityRequest.viewModel.selectedDestination(),
                    DepartureDate: AvailabilityRequest.departureDate.toJSON(),
                    ReturnDate: AvailabilityRequest.returnDate.toJSON()
                }
            };

            AvailabilityRequest.doAvailabilityRequest(data, function (res) {
                loading.hide();
                AvailabilityRequest.viewModel.inboundJourneys(res.GetAvailabilityResult.InboundJourneys);
                AvailabilityRequest.viewModel.outboundJourneys(res.GetAvailabilityResult.OutboundJourneys);
                AvailabilityRequest.viewModel.isRequestViewVisible(false);
                AvailabilityRequest.viewModel.isResponseViewVisible(true);
                AvailabilityRequest.viewModel.isLastRequestsViewVisible(false);
            }, AvailabilityRequest.handleAjaxError);
            loading.show();
        } else {
            msgError.show();
        }
    },

    checkLastRequests: function () {

        loading.show();
        AvailabilityRequest.getLastRequests(function (res) {
            AvailabilityRequest.viewModel.lastRequests(res.GetLastRequestsResult);

            loading.hide();
            AvailabilityRequest.AvailabilityRequestDiv.hide();
            AvailabilityRequest.LastRequestsDiv.fadeIn();
        }, AvailabilityRequest.handleAjaxError);
    },

    //  helper functions
    formatDate: function (date) {
        return moment(date).format("DD-MM-YYYY, hh:mm:ss");
    }
};

//  DOM loaded
$(function () {

    ko.applyBindings(AvailabilityRequest.viewModel);

});

//  Extension
ko.bindingHandlers.fadeVisible = {
    init: function (element, valueAccessor) {
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value));
    },
    update: function (element, valueAccessor) {
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).fadeIn() : $(element).hide();
    }
};