if (typeof odyssey != 'object') var odyssey = []; // make sure global environment exists

var isMobile = {
    Android: function () {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function () {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function () {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function () {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function () {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function () {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};
var mobileDevice = (isMobile.any() != null);

function parseQueryData(query) {
    var data = query.split("&");
    var result = {};
    for (var i = 0; i < data.length; i++) {
        var item = data[i].split("=");
        result[item[0]] = item[1];
    }
    return result;
}

function initializeCalendar() {
    odyssey.cData = getCalendarData(null, odyssey.selectedDay, odyssey.currentMonth, odyssey.currentYear);
    firstIndex = odyssey.cData.firstIndex;
    lastIndex = odyssey.cData.lastIndex;
    firstrowdays = odyssey.cData.firstrowdays;
    rows = odyssey.cData.rows;
    previousMonth = odyssey.cData.previousMonth;
    daysInMonth = odyssey.cData.daysInMonth;

    if (odyssey.firstRun) {
        fillCurrentMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth);
        odyssey.firstRun = 0;
    } else {
        prepareMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth);
        if (odyssey.action == "next") {
            $('#ody_calendar #dates').animate({
                left: odyssey.dates_left * 2
            }, 300, function () {
                $('#current_month').html($('#next_month').html());
                $(this).css("left", odyssey.dates_left);
                resetMonths();
                fillCurrentMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth);
            });
        } else {
            $('#ody_calendar #dates').animate({
                left: "0"
            }, 300, function () {
                $('#current_month').html($('#previous_month').html());
                $(this).css("left", odyssey.dates_left);
                resetMonths();
                fillCurrentMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth);
            });
        }
    }
    $('#month_year').html(odyssey.monthNames[odyssey.currentMonth] + " " + odyssey.currentYear);
    $('#month').val(odyssey.currentMonth);
    $('#year').val(odyssey.currentYear);
    moveEventsBoard();
}

function resetMonths() {
    var id1 = "next_month";
    var id2 = "previous_month";
    for (var n = 1; n <= rows; n++) {
        for (var m = 1; m <= 7; m++) {
            box1 = $('#' + id1 + ' > [data-pos="' + n + '_' + m + '"]');
            box2 = $('#' + id2 + ' > [data-pos="' + n + '_' + m + '"]');
            box1.html(odyssey.eventHTML);
            box1.removeClass().addClass("day");
            box2.html(odyssey.eventHTML);
            box2.removeClass().addClass("day");
        }
    }
}

function getToday() {
    currentDate = new Date();
    odyssey.currentDay = currentDate.getDate();
    odyssey.currentMonth = currentDate.getMonth() + 1;
    odyssey.currentYear = currentDate.getFullYear();
    odyssey.currentDateYear = odyssey.currentYear;
    odyssey.currentDateMonth = odyssey.currentMonth;
}

function prepareMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth) {
    if (!odyssey.action) {
        return;
    }
    var id = (odyssey.action == "next") ? "next_month" : "previous_month";
    var counter = 0;
    var nextCounter = 0;
    var day;
    for (var n = 1; n <= rows; n++) {
        for (var m = 1; m <= 7; m++) {
            box = $('#' + id + ' > [data-pos="' + n + '_' + m + '"]');
            day = "";
            if (n == 1 && m < firstIndex) {
                day = (previousMonth - (7 - firstrowdays)) + m;
                box.html(day + odyssey.eventHTML).attr("data-val", day);
                setDayStatus(box, "outOfMonth");
            } else {
                if (counter <= daysInMonth) {
                    counter++;
                    if (counter <= daysInMonth) {
                        day = counter;
                        box.html(day + odyssey.eventHTML).attr("data-val", day);
                        setDayStatus(box, "classic");
                    }
                }
                if ((counter > daysInMonth) && (lastIndex < 7) && (n <= rows)) {
                    nextCounter++;
                    day = nextCounter;
                    box.html(day + odyssey.eventHTML).attr("data-val", day);
                    setDayStatus(box, "outOfMonth");
                }
            }
        }
        box = null;
    }
}

function setDayStatus(box, className) {
    box.removeClass();
    box.addClass("day");
    box.addClass(className);
}

function fillCurrentMonth(firstIndex, lastIndex, firstrowdays, rows, previousMonth, daysInMonth) {
    restoreDim();
    var eventsDates = null;
    var peventsDates = null;
    var neventsDates = null;
    eventsDates = odyssey.cData.eventsDates.split("|");
    peventsDates = odyssey.cData.peventsDates.split("|");
    neventsDates = odyssey.cData.neventsDates.split("|");
    var counter = 0;
    var nextCounter = 0;
    var box;
    var day;
    for (var n = 1; n <= 6; n++) {
        for (var m = 1; m <= 7; m++) {
            box = $('#current_month > [data-pos="' + n + '_' + m + '"]');
            if (n == 1 && m < firstIndex) {
                day = (previousMonth - (7 - firstrowdays)) + m;
                box.html(day + odyssey.eventHTML).attr("data-val", day);
                setDayStatus(box, "outOfMonth");
                if (peventsDates[day - 1] == day) {
                    setDayStatus(box, "outOfMonthWithEvent");
                    $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                }
            } else {
                if (counter <= daysInMonth) {
                    counter++;
                    if (counter <= daysInMonth) {
                        day = counter;
                        box.html(day + odyssey.eventHTML).attr("data-val", day);
                        setDayStatus(box, "classic");
                        if (eventsDates[day - 1] == day) {
                            setDayStatus(box, "classicWithEvent");
                            $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                        }
                        if (counter == odyssey.selectedDay) {
                            box.html(day + odyssey.eventHTML).attr("data-val", day);
                            setDayStatus(box, "classicSelected");
                            if (eventsDates[day - 1] == day) {
                                setDayStatus(box, "classicWithEventSelected");
                                $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                            }
                        }

                        if ((counter == odyssey.currentDay) && (odyssey.currentYear == odyssey.currentDateYear) && (odyssey.currentMonth == odyssey.currentDateMonth)) {
                            box.html(day + odyssey.eventHTML).attr("data-val", day);
                            setDayStatus(box, "today");
                            if (eventsDates[day - 1] == day) {
                                setDayStatus(box, "todayWithEvent");
                                $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                            }
                            if ((counter == odyssey.selectedDay) || !odyssey.selectedDay) {
                                odyssey.selectedDay = counter;
                                box.html(day + odyssey.eventHTML).attr("data-val", day);
                                setDayStatus(box, "todaySelected");
                                if (eventsDates[day - 1] == day) {
                                    setDayStatus(box, "todayWithEventSelected");
                                    $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                                }
                            }
                        }
                    }
                }
                if ((counter > daysInMonth) && (lastIndex < 7) && (n <= rows)) {
                    nextCounter++;
                    day = nextCounter;
                    box.html(day + odyssey.eventHTML).attr("data-val", day);
                    setDayStatus(box, "outOfMonth");
                    if (neventsDates[day - 1] == day) {
                        setDayStatus(box, "outOfMonthWithEvent");
                        $('#current_month > [data-pos="' + n + '_' + m + '"] span').css("display", "inline");
                    }
                }
            }
        }
    }

    if (!odyssey.selectedDay) {
        odyssey.selectedDay = 1;
        box = $('#current_month > [data-pos="1_' + firstIndex + '"]');
        box.html(1 + odyssey.eventHTML).attr("data-val", 1);
        setDayStatus(box, "classicSelected");
        if (eventsDates[0] == 1) {
            setDayStatus(box, "classicWithEventSelected");
        }
    }
    box = null;
    $(window).trigger('resize');
    getEvents();
    odyssey.action = null;
}

function selectDay(day) {
    odyssey.selectedDay = day;
    hideDateChanger();
    fillCurrentMonth(odyssey.cData.firstIndex, odyssey.cData.lastIndex, odyssey.cData.firstrowdays, odyssey.cData.rows, odyssey.cData.previousMonth, odyssey.cData.daysInMonth, false);
}

function handleClick(elm) {
    var day = elm.attr('data-val');
    selectDay(day);
    if (elm.hasClass("outOfMonth") || elm.hasClass("outOfMonthWithEvent")) {
        if (day < 10) {
            nextMonth();
        } else {
            prevMonth();
        }
    }
}

function nextMonth() {
    $("#eventsBoard .eventButton").remove();
    $('#noEvents').show();
    var currentMonth = odyssey.currentMonth;
    var currentYear = odyssey.currentYear;
    var nextMonth = currentMonth + 1;
    var nextYear = currentYear;
    if (nextMonth == 13) {
        nextMonth = 1;
        nextYear++;
    }
    odyssey.action = "next";
    odyssey.currentMonth = nextMonth;
    odyssey.currentYear = nextYear;
    odyssey.eventsDates = null;
    odyssey.peventsDates = null;
    odyssey.neventsDates = null;
    initializeCalendar();
}


function prevMonth() {
    $("#eventsBoard .eventButton").remove();
    $('#noEvents').show();
    var currentMonth = odyssey.currentMonth;
    var currentYear = odyssey.currentYear;
    var previousMonth = currentMonth - 1;
    var previousYear = currentYear;
    if (previousMonth == 0) {
        previousMonth = 12;
        previousYear--;
    }
    odyssey.action = "previous";
    odyssey.currentMonth = previousMonth;
    odyssey.currentYear = previousYear;
    odyssey.eventsDates = null;
    odyssey.peventsDates = null;
    odyssey.neventsDates = null;
    initializeCalendar();
}

function loadDate() {
    var selectedMonth = parseInt($('#month').val());
    var selectedYear = parseInt($('#year').val());
    hideDateChanger();
    if (selectedMonth == odyssey.currentMonth && selectedYear == odyssey.currentYear) return false;
    $("#eventsBoard .eventButton").remove();
    $('#noEvents').show();
    odyssey.currentMonth = selectedMonth;
    odyssey.currentYear = selectedYear;
    odyssey.eventsDates = null;
    odyssey.peventsDates = null;
    odyssey.neventsDates = null;
    initializeCalendar();
}

function showDateChanger() {
    $('#changeDate').animate({
        top: 0
    }, 300);
}
function hideDateChanger() {
    $('#changeDate').animate({
        top: -42
    }, 300);
}

function moveEventsBoard() {
    var rows = odyssey.cData.rows;
    var endPoint = (odyssey.cellHeight * 6 - (rows * odyssey.cellHeight));
    endPoint = (!endPoint) ? 0 : 0 - endPoint;
    $('#eventsBoard').animate({
        top: endPoint
    }, 100);
}

function scrollEvents() {
    if (odyssey.eventsData.numOfEvents > 3) { // scroll the events list
        var subjectHeight = 0;
        var viewportHeight = (15 * odyssey.cData.rows) + ((6 - odyssey.cData.rows) * 15);
        $('.eventButton').each(function () {
            subjectHeight += $(this).outerHeight();
        });
        if (!mobileDevice) {
            var viewportWidth = $('#eventsBoard').width();
            var divide = 2;
            var parentOffset;
            var mouseX;
            var mouseY;
            var percent;
            var step;
            var dif;
            var newY;
            var initialY = 7;
            var subjectY = parseInt($('#eventsBoard').css("top"));
            $('#eventButtons').css("top", "100px");
            newY = initialY;
            $('#eventButtons').animate({
                top: newY
            }, 300);

            $('#eventsBoard').mousemove(function (event) {
                parentOffset = $(this).parent().offset();
                mouseX = parseInt(event.pageX - parentOffset.left);
                mouseY = parseInt(event.pageY - (parentOffset.top + 84 + (odyssey.cellHeight * odyssey.cData.rows)));
                mouseY = (mouseY < 0) ? 0 : mouseY;
                mouseY = (mouseY > viewportHeight) ? viewportHeight : mouseY;
                percent = parseInt(100 * (mouseY / viewportHeight)) - 10;
                percent = (percent < 0) ? 0 : percent;
                if (mouseX > 0 && mouseX < viewportWidth) {
                    newY = initialY - parseInt((subjectHeight - viewportHeight) * (percent / 100));
                } else {
                    mouseX = 0;
                    newY = initialY;
                }
                subjectY = parseInt($('#eventButtons').css("top"));
                if (subjectY > newY) {
                    dif = subjectY - newY;
                    dif = (dif < 0) ? 0 : dif;
                    step = parseInt(dif / divide);
                    $('#eventButtons').stop().animate({
                        top: (subjectY - step)
                    }, 20);
                }
                if (subjectY < newY) {
                    dif = newY - subjectY;
                    dif = (dif < 0) ? 0 : dif;
                    step = parseInt(dif / divide);
                    $('#eventButtons').stop().animate({
                        top: (subjectY + step)
                    }, 20);
                }
                step = (step < 0) ? 0 : step;
            });
            $('#eventsBoard').mouseleave(function (event) {
                mouseX = 0;
                newY = initialY;
                $('#eventButtons').animate({
                    top: newY
                }, 300);
            });
        } else {
            $('#ody_calendar').css("height", (odyssey.calendar_height + (subjectHeight - viewportHeight)) + "px");
            $('#ody_calendar').css("overflow-y", "visible");
            $('#eventButtons').css("position", "relative");
            $('#eventsBoard').css("overflow", "visible");
        }
    } else {
        restoreDim();
    }
}

function restoreDim() {
    $("#eventsBoard").unbind("mousemove");
    $("#eventsBoard").unbind("mouseleave");
    $('#ody_calendar').css("height", "450px");
    $('#eventButtons').css("position", "absolute");
    $('#ody_calendar').css("overflow-y", "hidden");
    $('#eventsBoard').css("overflow", "hidden");
}

/*************************  start responsive behavior *****************************/
jQuery().ready(function () {

    $(window).on('resize', function () {
        odyssey.calendar_factor = get_calendar_factor();
        odyssey.calendar_width = 267 * odyssey.calendar_factor;
        odyssey.calendar_height = 450 * odyssey.calendar_factor;
        odyssey.dates_width = (268 * odyssey.calendar_factor) * 3;
        odyssey.dates_height = 228 * odyssey.calendar_factor;
        odyssey.dates_left = 0 - 268 * odyssey.calendar_factor;
        odyssey.span_width = (238 * odyssey.calendar_factor) / 7;
        odyssey.day_width = ((Math.abs(odyssey.dates_left) - 16) / 7) - .05;
        odyssey.day_font_size = 17 * odyssey.calendar_factor;
        odyssey.day_padding_top = (odyssey.day_width - odyssey.day_font_size) / 2;
        odyssey.day_font_weight = (odyssey.calendar_factor > 1.3) ? 'normal' : 'bold';
        odyssey.span_font_size = 18 * odyssey.calendar_factor;
        odyssey.span_top = 0 - (3 * odyssey.calendar_factor);
        odyssey.span_left = 16 * odyssey.calendar_factor;
        odyssey.cellHeight = $('#current_month > [data-pos="1_1"]').outerHeight();
        $('#ody_calendar').css({'height': odyssey.calendar_height});
        $('#ody_calendar .day').css({
            'width': odyssey.day_width,
            'height': odyssey.day_width - odyssey.day_padding_top,
            'font-size': odyssey.day_font_size + 'px',
            'line-height': odyssey.day_font_size + 'px',
            'padding-top': odyssey.day_padding_top + 'px',
            'font-weight': odyssey.day_font_weight
        });
        $('#ody_calendar #dates').css({'width': odyssey.dates_width, 'height': odyssey.dates_height, 'left': odyssey.dates_left});
        $('#previous_month, #current_month, #next_month').css({'width': odyssey.calendar_width});
        $('#days_shortcuts span').css({'width': odyssey.span_width});
        $('#ody_calendar .day span').css({
            'top' : odyssey.span_top,
            'left' : odyssey.span_left,
            'font-size' : odyssey.span_font_size + 'px'
        });
        if(typeof(odyssey.cData) != 'undefined') moveEventsBoard();
    });

    $('#tablist1-tab5').trigger('click'); // need to be removed

    function get_calendar_factor() {
        var factor = $('#ody_calendar').width() / 267;
        factor = (factor < 1) ? 1 : factor;
        factor = (factor > 2) ? 2 : factor;
        return factor;
    }

});
/*************************  end responsive behavior *****************************/
