//var EventStatus = [
//    "Planned",
//    "Declined",
//    "Confirmed", //Not available anymore
//    "Approved",
//    "In progress",// not available
//    "Done",
//    "Deleted"
//]
var selectedEvent, CurrentDate = "";
$(document).ready(function() {
    window.Events = [];
    $("#calendar-event").appendTo("#main-wrapper")
    if (window.CurrentLeave) {
        for (var x = 0; x < CurrentLeave.length; x++) {
            var CA = CurrentLeave[x],
                TimeFrom = "T" + moment(Date.parse("1/1/2001 " + (CA["LeaveTime"].split("##")[0]? CA["LeaveTime"].split("##")[0] : "09:00 AM"))).format("HH:mm"),
                TimeTo = "T" + moment(Date.parse("1/1/2001 " + (CA["LeaveTime"].split("##")[1] ? CA["LeaveTime"].split("##")[1] : "09:30 AM"))).format("HH:mm");
            if (CA["LeaveRequest_Status"] != 4) { //not deleted
                Events.push({
                    title: CA["AssignLeave_Reason"],
                    class: 'eventState-' + CA["LeaveRequest_Status"],
                    start: CA["AssignLeave_From_Date"] + TimeFrom,
                    end: CA["AssignLeave_To_Date"] + TimeTo,
                    other: {
                        id: CA["Leave_ID"],
                        Employee_ID:CA["Employee_ID"],
                        Employee_Name:CA["Employee_Name"],
                        status: CA["LeaveRequest_Status"]
                    }
                })
            }
        }   
    }
    $('body').pagescalendar({
        minTime: 0,
        maxTime: 25,
        ui: {
            minTime: 1,
            year: {
                visible: true,
                format: 'YYYY',
                startYear: '2013',
                endYear: moment().add(15, "year").format("YYYY"),
                eventBubble: true
            },
            month: {
                visible: !0,
                format: "MMM",
                eventBubble: !0
            },
            date: {
                format: "MMMM YYYY, D dddd"
            },
            week: {
                day: {
                    format: "D"
                },
                header: {
                    format: "dd"
                },
                eventBubble: !0,
                startOfTheWeek: "0",
                endOfTheWeek: "6"
            },
            grid: {
                dateFormat: "D dddd",
                timeFormat: "h A",
                eventBubble: !0,
                slotDuration: "30"
            }
        },
        events: Events,
        onViewRenderComplete: function(Events) {},
        onEventClick: function(event) {
            selectedEvent = event;
            setEventDetailsToForm(selectedEvent);
            $('#calendar-event').addClass("open");
            document.body.style.overflowY = "hidden";
            if(selectedEvent.other.status == 1 || selectedEvent.other.status == 3 ){    
                $("#eventSave").hide()
            }
            else{
                $("#eventSave").show()
            }
        }
    });
    $('body').pagescalendar('render');
    CollisionGroups(Events)
    if (window.parent.UpdateIframeHeight) window.parent.UpdateIframeHeight(document.body.scrollHeight);
    window.setEventDetailsToForm = function(event) {
        if (!$("#calendar").attr("FixedWidth")) {
            $("#calendar").attr("FixedWidth", "yes").width($("body").width() - $("#calendar").offset().left)
        }
        $("#eventView").attr("IsCancel", "no").html("View")
        $("#eventSave").html("Edit")
        $("#DateTimeEdit").addClass("hidden")
        $('#txtEventName').removeClass("hidden").html(event.title).next().addClass("hidden");
        $('#txtEventTeamName').removeClass("hidden").html(event.other.teamName).next().addClass("hidden");
        $("#DateTimeView").removeClass("hidden")
        $("#LeaveID").val(event.other.id)
        $("#txtEventStatus").html(EventStatus[parseInt(event.other.status)]);
        $("#txtEventEmployeeName").html((event.other.Employee_Name));
        $('#eventIndex').val();
        $('#txtEventCode').val();
        $('#event-date').html(moment(event.start).format('MMM, D dddd'));
        $('#lblfromTime').html(moment(event.start).format('hh:mm A'));
        $('#lbltoTime').html(moment(event.end).format('hh:mm A'));
        $('#eventIndex').val(event.index);
        $('#txtEventCode').val(event.other.code);
        $("#AutoScheduledNote,#eventDelete,#eventSave").hide();
        if (event.other.note == "autoAssigned") {
            $("#AutoScheduledNote").show();
        } else {
            $("#eventDelete").css("display", event.other.status == 4 ? "none" : "inline-block")
            $("#eventSave").show();
        }
    }
    function SaveCurrentEvent(DoRemove, OnSave) {
        $("body").append($('<div id="ajaxLoaderModal" style="position:fixed;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.4);z-index:999"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>'))
        if (DoRemove) {
            selectedEvent.class = "eventState-4";
            selectedEvent.other.status = "4";
        }
        $.ajax({
            url: "xhr/calendar.php",
            method: "POST",
            data: DoRemove ? {
                cmd: "remove",
                id: selectedEvent.other.id
            } : {
                cmd: "update",
                id: selectedEvent.other.id,
                Employee_ID: selectedEvent.other.Employee_ID,
                AssignLeave_Reason: selectedEvent.title,
                AssignLeave_Start_Time: selectedEvent.start.split("T")[0],
                AssignLeave_End_Time: selectedEvent.end.split("T")[0],
                LeaveTime: selectedEvent.start.split("T")[1] + "##" + selectedEvent.end.split("T")[1],
                LeaveRequest_Status: selectedEvent.other.status
            },
            complete: function(v1, v2) {
                if (v2 == "success") {
                    if (DoRemove == false) {
                        if (selectedEvent.other.note == "autoAssigned") {}
                    }
                }
                $("#CurrentLeaveTable tr[data-event-id='" + selectedEvent.other.id + "'] .TableStatusContainer").parent().attr("class", "StatusTD-6")
                $('#element').pagescalendar('updateEvent', $('#eventIndex').val(), selectedEvent);
                if (OnSave) OnSave((v2 == "success" && v1.responseText == "done"))
                $("#ajaxLoaderModal").remove();
            }
        })
    }
    $('#eventSave').on('click', function(e) {
        e.preventDefault();
        $("#AssignLeave").modal("show");
        $("#LeaveID").val(selectedEvent.other.id)
    });
    $('#eventDelete').on('click', function(e) {
        e.preventDefault();
        selectedEvent.other.status = 4;
        selectedEvent.class = 'eventState-' + selectedEvent.other.status;
        SaveCurrentEvent(true, function(IsOK) {
            if (IsOK) {
                $('#element').pagescalendar('updateEvent', $('#eventIndex').val(), selectedEvent);
                $('#calendar-event').removeClass('open');
                document.body.style.overflowY = "auto";
            } else {
                alert("Something is wrong, please try again later")
            }
        });
    })
    $("#EventCloser").on("click", function(e) {
        e.preventDefault();
        $('#calendar-event').removeClass('open');
        document.body.style.overflowY = "auto";
    })
    setTimeout(function() {
        $("#CalendarLoading").remove();
        $("#calendarContainer").animate({
            opacity: 1
        })
    }, 500)
    $("#CurrentLeaveTable").on("click", "tr[data-event-index]", function() {
        $('#calendar-event').addClass("open");
        document.body.style.overflowY = "hidden";
        var Event = $('#element').pagescalendar('getEvents')[parseInt($(this).attr("data-event-index"))]
        selectedEvent = Event;
        setEventDetailsToForm(Event);
    })
    $("#eventView").on("click", function(e) {
        if ($(this).attr("IsCancel") == "yes") {
            setEventDetailsToForm(selectedEvent)
            e.preventDefault();
        }
    })
});
function CollisionGroups(event){
    var collisionGroups = []
    for (var i = 1; i < event.length; i++) {
        var event1Range = (event[i].start);
                
        var j = i-1 ;
               
        do {
            var temp = [],
            event2Range = (event[j].start);
                
            if (event1Range !== (event2Range)) {
                temp.push(event[i]);
                temp.push(event[j]);
                collisionGroups.push(temp);
            }
                
            j--;
        }
        while (j === 0);
    }
    
    
    
    
    
    
      function union_arrays(x, y) {
                var obj = {};
                for (var i = x.length - 1; i >= 0; --i)
                    obj[x[i]] = x[i];
                for (var i = y.length - 1; i >= 0; --i)
                    obj[y[i]] = y[i];
                var res = []
                for (var k in obj) {
                    if (obj.hasOwnProperty(k))
                        res.push(obj[k]);
                }
                return res;
            }
            for (var i = 1; i < collisionGroups.length; i++) {
              
                var j = i - 1;
                do {
                    collisionGroups[j] = union_arrays(collisionGroups[i], collisionGroups[j]);
                    collisionGroups.splice(i, 1);
                    
                    i--;
                    j--;
                }
                while (j === 0);
            }
    for (var i = 0; i < collisionGroups.length; i++) {
        var width = 100 / collisionGroups[i].length;
        var left = 0;
                 
               
        for (var j = 0; j < collisionGroups[i].length; j++) {
            var el = $(".event-container[data-index='" + collisionGroups[1] + "']");
      
            
            el.css({
                "width": width + "%",
                "left": left + "%"
            });
            left = left + width
        }
    }
}