﻿var sSchedule_viewModels_checkFieldAvailabilityViewModel = function() {

	var common = new Sschedule_commonFunctions();
	var locationsDataStore = new sSchedule_dataSources_locationDataSource();
	
	var activeLocationsDataSource = locationsDataStore.getDsByName("LocationTreeListDs", function(options, operation) {
		var params = { portalId: sSchedule_portalId, isActiveLocationOnly: false };
		return params;
	}, function() {
		/*style for field availability treeview node to make link*/
		jQuery('.k-in').css('text-decoration', 'underline');

		var treeView = $('#treeview').data('kendoTreeView');
		var allnodes = treeView.dataItems();
        for (var i = 0; i < allnodes.length; i++) {
            if (allnodes[i].hasChildren) {
                if (typeof $(".hdnSelectedLocation").val() === 'undefined'|| $(".hdnSelectedLocation").val() == '') {
                    var parentNode = treeView.findByUid(allnodes[i].uid);
                    treeView.expand(parentNode);
                    var firstChildOfParentNode = parentNode.find(' > ul > li.k-item:first');
                    treeView.select(firstChildOfParentNode);
                    treeView.trigger('select', { node: firstChildOfParentNode });
                    break;
                }
                if (allnodes[i].Id == $(".hdnSelectedLocation").val()) {
                    var parentNode = treeView.findByUid(allnodes[i].uid);
                    treeView.expand(parentNode);
                    var firstChildOfParentNode = parentNode.find(' > ul > li.k-item:first');
                    treeView.select(firstChildOfParentNode);
                    treeView.trigger('select', { node: firstChildOfParentNode });
                    break;
                }
            }
		}
	});

	var fieldAvailabilityModel = kendo.observable({
		activeLocationsDataSource: activeLocationsDataSource,

		selectedFieldData: null,
		onSelect: function(e) {

			var data = $('#treeview').data('kendoTreeView').dataItem(e.node);

			if (data == null)
                return;
            if ($(".isScheduleTab").length == 0) {
                if ($(".hdnSelectedDate").val() == undefined || $(".hdnSelectedDate").val() == "") {
                    fieldAvailabilityModel.set("fieldAvailabilityDate", kendo.format("{0:d}", new Date()));
                }
                else {
                    fieldAvailabilityModel.set("fieldAvailabilityDate", kendo.format("{0:d}", new Date($(".hdnSelectedDate").val())));
                }
            }

			var currentDate = Date.parse(fieldAvailabilityModel.fieldAvailabilityDate);
			//Check if Date parse is successful
			if (!currentDate) {
				return false;
			}

			if (typeof(data.Id) == "undefined") {
				fieldAvailabilityModel.set("selectedFieldData", 0);
				return;
			}
			
			fieldAvailabilityModel.set("selectedFieldData", data);
			if (data.get("ParentId") <= 0) return;

            jQuery(".TimeSlot").css({ "position": "", "top": "", "z-index": "" });
            common.showProgress("#availabilityListDiv");
            fieldAvailabilityModel.getFieldAvailability();
            setTimeout(function () {
                if ($(".isScheduleTab").length > 0) {
                    $("#divScrolling").scrollTop(575);
                }
                else {
                    $("#divScrolling").scrollTop(470);
                }
            }, 500)
		},
		fieldAvailabilityDate: new Date(),
		fieldAvailabilityDateChanged: function(e) {
			
			var currentDate = Date.parse($(e.sender._value)[0]);
            //Check if Date parse is successful
			if (!currentDate) {
			    fieldAvailabilityModel.set("fieldAvailabilityDate", new Date());
			    fieldAvailabilityModel.getFieldAvailability();
                return false;
            }
            $(".hdnSelectedDate").val($(e.sender._value)[0]);
            jQuery(".TimeSlot").css({ "position": "", "top": "", "z-index": ""});
            common.showProgress("#availabilityListDiv");

            fieldAvailabilityModel.getFieldAvailability();
            if ($(".isScheduleTab").length > 0) {
                $("#divScrolling").scrollTop(575);
            }
            else {
                $("#divScrolling").scrollTop(470);
            }
		},
		fieldAvailability: new kendo.data.ObservableArray([]),
		getFieldAvailability: function() {
			if (fieldAvailabilityModel.selectedFieldData == null) {
                common.hideProgress("#availabilityListDiv");
                jQuery(".TimeSlot").css({"position": "sticky", "top": "0px", "z-index": "99"});
				return;
			}
			var fieldId = fieldAvailabilityModel.selectedFieldData.Id;
			var date = kendo.toString(fieldAvailabilityModel.fieldAvailabilityDate, "MM/dd/yyyy");
            var isScheduleTab = false;
            var isEditMatches = false;
			var eventId = 0;
			if ($(".isScheduleTab").length > 0)
			{
			    isScheduleTab = $(".isScheduleTab").val();
			    eventId = $(".scheduleEventId").val();
            }

            if ($(".hdnIsEditMatches").length > 0) {
                isEditMatches = $(".hdnIsEditMatches").val();
            }
			var serviceRootUrl = common.getServiceRootUrl();
			serviceRootUrl += "Fields/GetFieldAvailability";

			$.ajax({
				type: "GET",
                data: { portalId: sSchedule_portalId, fieldId: fieldId, date: date, isScheduleTab: isScheduleTab, eventId: eventId, isEditMatches: isEditMatches },
				url: serviceRootUrl,
				success: function(d) {
					var fieldAvailability = fieldAvailabilityModel.fieldAvailability;
					fieldAvailability.splice(0, fieldAvailability.length);
					for (var i = 0; i < d.length; i++) {
						fieldAvailability.push(d[i]);
                    }
                    common.hideProgress("#availabilityListDiv");
                    jQuery(".TimeSlot").css({ "position": "sticky", "top": "0px", "z-index": "99" });
				}
			});
		},
	});

	return {
		fieldAvailabilityModel: fieldAvailabilityModel
	};
}

function CompareScheduleNameForSchedule(current, next) {

    if (current.scheduleName < next.scheduleName) {
        return -1;
    }

    if (current.scheduleName > next.scheduleName) {
        return 1;
    }
    return 0;
};

function PopUpForBlackoutDetailsForSchedule(el) {
    var blackoutData = $(el).find(".divPopup").html();
    const blackoutDataJson = [];
    for (i = 0; i < blackoutData.split(/\r?\n/).length; i++) {
        const blackoutDetails = {};
        blackoutDetails.scheduleName = (blackoutData.split(/\r?\n/)[i]).split("in")[1];
        blackoutDetails.blackoutMessage = "<ul><li>" + (blackoutData.split(/\r?\n/)[i]) + "</li></ul>";
        blackoutDataJson.push(blackoutDetails);
    }

    blackoutDataJson.sort(CompareScheduleNameForSchedule);
    var allBlackoutDetails = blackoutDataJson.map(function (item) { return item['blackoutMessage'] + '\r\n'; });
    $("#timeslotBlackoutDetailDiv").html(allBlackoutDetails);
    var popupWindow = $("#timeSlotPopup");
    popupWindow.kendoWindow({
        width: "850px",
        title: "Time Slot Message",
        modal: true,
    });
    $dialog = popupWindow.data("kendoWindow");
    $dialog.wrapper.addClass("scom tournament-popup");
    popupWindow.data("kendoWindow").center().open();
};


$(document).click((event) => {
    if ($(event.target).closest('.k-overlay').length) {
        $("#timeSlotPopup").data("kendoWindow").close();
    }
});
