(function($){

    $.fn.jqueryCal = function(options){

        var defaults = {

            xmlPath: '',

            noEvents: 'brak zdarzeń.',

            noEventsToday: 'Brak zdarzeń dzisiaj',

            monthText: '',

            getXMLmonthly: true,

         toolTipBigPrev: "Ubiegły miesiąc",

        toolTipSmallPrev: "Ubiegły tydzień",

        toolTipSmallNext: "Następny tydzień",

        toolTipBigNext: "Następny miesiąc",

        };

        var options = $.extend(defaults, options);

        return this.each(function(){

            // global vars

            var divID = $(this).attr("id");

            var dateList = new Array();

            var weekClasses = new Array("Pn", "Wt", "Śr", "Cz", "Pt", "So", "N");

            var weekday = new Array("Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota")
			
		    var currentDate = new Date();

            currentDate.setHours(0);

            currentDate.setMinutes(0);

            currentDate.setSeconds(0);

            currentDate.setMilliseconds(0);

            var selectedDate = new Date();

            selectedDate.setDate(1);

            selectedDate.setHours(0);

            selectedDate.setMinutes(0);

            selectedDate.setSeconds(0);

            selectedDate.setMilliseconds(0);

            var selectedWeek = new Date();

            selectedWeek.setHours(0);

            selectedWeek.setMinutes(0);

            selectedWeek.setSeconds(0);

            selectedWeek.setMilliseconds(0);

            var tempDate = new Date();

            tempDate.setHours(0);

            tempDate.setMinutes(0);

            tempDate.setSeconds(0);

            tempDate.setMilliseconds(0);

            var clickedEventText = "";

            var todayText = "";

            var xmlPath = xmlPath;

            var tmpString = "";

            var tmpStringParts = new Array();

            var datesInWeek = new Array();

            var htmlString = "";

            

            writeHTML();

            

            // parse XML

            function parseXML(){

                try {

                    if (options.getXMLmonthly) 

                        xmlPath = options.xmlPath + "year=" + selectedDate.getFullYear() + "-month=" + (selectedDate.getMonth() + 1) + ".xml";

                    else 

                        xmlPath = options.xmlPath + "year=" + selectedDate.getFullYear() + ".xml";

                    // parse XML

                    $.ajax({

                        type: "GET",

                        url: xmlPath,

                        dataType: "xml",

                        success: function(xml){

                            $(xml).find('calendardoc').each(function(i){

                                dateList[i] = new Object();

                                dateList[i]["dateStart"] = Date.parse($(this).children("dateStart").text());

                                dateList[i]["dateEnd"] = Date.parse($(this).children("dateEnd").text());

                                dateList[i]["title"] = $(this).find('title').text();

                                dateList[i]["text"] = $(this).find('text').text();

                       

                            })

                            fillHTML();

                        }

                    })

                } 

                catch (err) {

                    fillHTML();

                }

            }

            

            

            // write HTML

            function writeHTML(){

                if ((divID).match("Month")) {

                    htmlString += "<div class='head'><a class='bigPrev' title='" + options.toolTipBigPrev + "' href='#'></a><a class='smallPrev'  title='" + options.toolTipSmallPrev + "' href='#'></a><span class='text'></span><a class='smallNext' title='" + options.toolTipSmallNext + "' href='#'></a><a class='bigNext' title='" + options.toolTipBigNext + "' href='#'></a></div><div class='body'><div class='calendarWeekContainer'>";

                    htmlString += "<span class='kw'>T</span>";

                    for (var i = 0; i <= 5; i++) {

                        htmlString += "<span class='calendarWeek'></span>";

                    }

                    htmlString += "</div><div class='weekDaysContainer'>";

                    for (var i = 0; i <= 6; i++) {

                        htmlString += "<span class='weekDays " + weekClasses[i] + "'></span>";

                    }

                    htmlString += "</div><div class='weekDatesContainer'>";

                    for (var i = 0; i <= 41; i++) {

                        var j = 0;

                        j++;

                        htmlString += "<span class='weekDates " + weekClasses[j] + "'></span>";

                        if (j = 6) 

                            j = 0;

                    }

                    htmlString += "</div><div class='contentBegin'></div><div class='content'></div><div class='footer'></div></div>";

                    $("#" + divID).html(htmlString);

                    // month

                    $("#" + divID + " .head .bigPrev").click(function(){

                        selectedDate.setYear(selectedDate.getFullYear() - 1);

                        tempDate.setDate(1);

                        tempDate.setYear(tempDate.getFullYear() - 1);

                        parseXML();

                    });

                    $("#" + divID + " .head .smallPrev").click(function(){

                        selectedDate.setMonth(selectedDate.getMonth() - 1);

                        tempDate.setDate(1);

                        tempDate.setMonth(tempDate.getMonth() - 1);

                        parseXML();

                    });

                    $("#" + divID + " .head .smallNext").click(function(){

                        selectedDate.setMonth(selectedDate.getMonth() + 1);

                        tempDate.setDate(1);

                        tempDate.setMonth(tempDate.getMonth() + 1);

                        parseXML();

                    });

                    $("#" + divID + " .head .bigNext").click(function(){

                        selectedDate.setYear(selectedDate.getFullYear() + 1);

                        tempDate.setDate(1);

                        tempDate.setYear(tempDate.getFullYear() + 1);

                        parseXML();

                    });

                }

                else 

                    if ((divID).match("Week")) {

                        htmlString += "<div class='head'><a class='bigPrev' title='" + options.toolTipBigPrev + "' href='#'></a><a class='smallPrev' title='" + options.toolTipSmallPrev + "' href='#'></a><span class='text'></span><a class='smallNext'  title='" + options.toolTipSmallNext + "'  href='#'></a><a class='bigNext' title='" + options.toolTipBigNext + "'  href='#'></a></div><div class='body'>";

                        for (var i = 0; i <= 6; i++) 

                            htmlString += "<a class='date'><span class='day " + weekClasses[i] + "'></span><span class='weekday'> " + weekClasses[i] + "</span></a>";

                        htmlString += "</div><div class='content'></div><div class='footer'></div>";

                        $("#" + divID).html(htmlString);

                        // week

                        $("#" + divID + " .head .bigPrev").click(function(){

                            selectedWeek.setMonth(selectedWeek.getMonth() - 1);

                            parseXML();

                        });

                        $("#" + divID + " .head .smallPrev").click(function(){

                            selectedWeek.setDate(selectedWeek.getDate() - 7);

                            parseXML();

                        });

                        $("#" + divID + " .head .smallNext").click(function(){

                            selectedWeek.setDate(selectedWeek.getDate() + 7);

                            parseXML();

                        });

                        $("#" + divID + " .head .bigNext").click(function(){

                            selectedWeek.setMonth(selectedWeek.getMonth() + 1);

                            parseXML();

                        });

                    }

                fillHTML();

                parseXML();

            }

            

            

            // fill HTML

            function fillHTML(){

                if ((divID).match("Month")) {

                    // clean HTML

                    cleanHTMLMonth();

                    var firstOfSelectedMonth = selectedDate;

                    firstOfSelectedMonth.setDate(1);

                    currentDate = new Date();

                    $("#" + divID + " .head .text").html(options.monthText + " " + selectedDate.getMonthName() + " " + selectedDate.getFullYear());

                    for (i = 0; i <= weekClasses.length; i++) {

                        $("#" + divID + " .body .weekDaysContainer .weekDays." + weekClasses[i]).text(weekClasses[i]);

                    }

                    var startWrite = 0;

                    var j = 1;

                    if (selectedDate.getDay() == 0) {

                        startWrite = 6;

                    }

                    else {

                        startWrite = selectedDate.getDay() - 1;

                    }

                    // write calendarweeks

                    var tempMonth = selectedDate.getMonth();

                    $("#" + divID + " .body .calendarWeek").each(function(i){

                        $(this).text((getCalendarWeek(selectedDate.getFullYear(), selectedDate.getMonth() + 1, selectedDate.getDate())));

                        selectedDate.setDate(selectedDate.getDate() + 7);

                    });

                    selectedDate.setMonth(tempMonth);

                    selectedDate.setDate(1);

                    $("#" + divID + " .body .weekDatesContainer .weekDates").each(function(i){

                        if (startWrite <= i && j <= (daysInMonth(firstOfSelectedMonth.getMonth() + 1, firstOfSelectedMonth.getFullYear() + 1))) {

                            $(this).text(j);

                            $(this).addClass("pointer");

                            $(this).hover(function(){

                                $(this).addClass("hover");

                            }, function(){

                                $(this).removeClass("hover");

                            });

                            j++;

                            // mark current day

                            if ((selectedDate.getMonth() == currentDate.getMonth()) && (selectedDate.getFullYear() == currentDate.getFullYear()) && ($(this).text() == currentDate.getDate())) 

                                $(this).addClass("currentDate");

                        }

                    });

                    // mark events

                    for (var i = 0; i <= dateList.length - 1; i++) {

                        $("#" + divID + " .body .weekDatesContainer .weekDates").each(function(){

                            if ($(this).text() != "") {

                                tempDate.setDate($(this).text());

                                if (tempDate.getTime() >= dateList[i]["dateStart"].getTime() && tempDate.getTime() <= dateList[i]["dateEnd"].getTime()) {

                                    $(this).addClass("event");

                                }

                            }

                        })

                    }

                    // add events

                    addEventInfo();

                }

                else 

                    if ((divID).match("Week")) {

                        // clean HTML

                        cleanHTMLWeek();

                        // define weekstart

                        selectedWeek.setDate(selectedWeek.getDate() - selectedWeek.getDay());

                        // fill html

                        $("#" + divID + " .head .text").html(options.monthText + " " + selectedWeek.getMonthName() + " " + selectedWeek.getFullYear());

                        $("#" + divID + " .body .date .day").each(function(i){

                            selectedWeek.setDate(selectedWeek.getDate() + 1);

                            $(this).text(selectedWeek.getDate());

                            // mark current day

                            if ((selectedWeek.getMonth() == currentDate.getMonth()) && (selectedWeek.getFullYear() == currentDate.getFullYear()) && ($(this).text() == currentDate.getDate())) 

                                $(this).parent().addClass("currentDate");

                        })

                        selectedWeek.setDate(selectedWeek.getDate() - 6);

                        // mark events

                        tempDate.setDate(selectedWeek.getDate());

                        tempDate.setMonth(selectedWeek.getMonth());

                        tempDate.setFullYear(selectedWeek.getFullYear());

                        $("#" + divID + " .body .date .day").each(function(j){

                            for (var i = 0; i <= dateList.length - 1; i++) {

                                if (tempDate.getTime() >= dateList[i]["dateStart"].getTime() && tempDate.getTime() <= dateList[i]["dateEnd"].getTime()) {

                                    $(this).parent().addClass("event");

                                }

                            }

                            tempDate.setDate(tempDate.getDate() + 1);

                        })

                        addEventInfo();

                    }

            }

            

            

            // clean HTML month

            function cleanHTMLMonth(){

                $("#" + divID + " .body .weekDatesContainer .weekDates").each(function(){

                    $(this).text("");

                    $(this).removeClass("event");

                    $(this).removeClass("currentDate");

                    $(this).removeClass("pointer");

                    $(this).unbind();

                    $(this).click(function(){

                    });

                })

                $("#" + divID + " .head .text").text = "";

            }

            

            

            // clean HTML week

            function cleanHTMLWeek(){

                $("#" + divID + " .body .date").each(function(j){

                    $(this).removeClass("event");

                    $(this).removeClass("currentDate");

                    $(this).removeClass("pointer");

                    $(this).unbind();

                    $(this).click(function(){

                    });

                })

                $("#" + divID + " .head .text").text = "";

            }

            

            

            // get days of month

            function daysInMonth(month, year){

                var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

                if (month != 2) 

                    return m[month - 1];

                if (year % 4 != 0) 

                    return m[1];

                if (year % 100 == 0 && year % 400 != 0) 

                    return m[1];

                return m[1] + 1;

            }

            

            

            // week of year & week of month

            function getWeekOfMonth(date){

                var todayDayOfMonth = date.getDate() - 1;

                var first = new Date(date.getFullYear() + '/' + (date.getMonth() + 1) + '/01');

                var monthFirstDateDay = first.getDay();

                return Math.ceil((todayDayOfMonth + monthFirstDateDay) / 7);

            }

            

            

            // calculate CalendarWeek

            function getCalendarWeek(jahr, monat, tag){

                var datum = new Date(jahr, monat - 1, tag);

                var jh = jahr + 1;

                var kalwo = getkaldiff(datum, jh);

                while (kalwo < 1) {

                    jh--;

                    kalwo = getkaldiff(datum, jh);

                }

                return kalwo;

            }

            function getkaldiff(datum, jahr){

                var d4j = new Date(jahr, 0, 4);

                var wt4j = (d4j.getDay() + 6) % 7;

                var m1wjT = Math.floor(0.01 + d4j.getTime() / 864e5 - wt4j);

                var datumT = Math.floor(0.01 + datum.getTime() / 864e5);

                return Math.floor(1 + (datumT - m1wjT) / 7);

            }

            

            

            // add event info  

            function addEventInfo(){

                if ((divID).match("Month")) {

                    if ((currentDate.getMonth() == selectedDate.getMonth()) && (currentDate.getFullYear() == selectedDate.getFullYear())) {

                        todayText = "";

                        for (var i = 0; i <= dateList.length - 1; i++) {

                            if ((currentDate.toLocaleDateString() == dateList[i]["dateStart"].toLocaleDateString() || currentDate.getTime() >= dateList[i]["dateStart"].getTime()) && (currentDate.toLocaleDateString() == dateList[i]["dateEnd"].toLocaleDateString() || currentDate.getTime() <= dateList[i]["dateEnd"].getTime())) {

                                todayText = todayText.concat("<b>" + dateList[i]["title"] + "</b><br />" + currentDate.toLocaleDateString() + "<br />" + dateList[i]["text"] + "<br />"); // <a href class='url'>" + dateList[i]["url"] + "</a>

                            }

                        }

                        if (todayText == "") {

                            todayText = "<b>" + todayText.concat(options.noEventsToday) + "</b>";

                        }

                        $("#" + divID + " .content").html(todayText);

                    }

                    // add day events

                    $("#" + divID + " .body .weekDatesContainer .pointer").each(function(){

                        $(this).hover(function(){

                            $(this).addClass("mouseOver");

                        }, function(){

                            $(this).removeClass("mouseOver");

                        });

                        $(this).click(function(){

                            $("#" + divID + " .body .weekDatesContainer .pointer").each(function(){

                                $(this).removeClass("currentDate");

                            })

                            $(this).addClass("currentDate");

                            clickedEventText = "";

                            selectedDate.setDate($(this).text());

                            for (var i = 0; i <= dateList.length - 1; i++) {

                                if ((selectedDate.toLocaleDateString() == dateList[i]["dateStart"].toLocaleDateString() || selectedDate.getTime() >= dateList[i]["dateStart"].getTime()) && (selectedDate.toLocaleDateString() == dateList[i]["dateEnd"].toLocaleDateString() || selectedDate.getTime() <= dateList[i]["dateEnd"].getTime())) {

                                    clickedEventText = clickedEventText.concat("<b>" + dateList[i]["title"] + "</b><br />" + selectedDate.toLocaleDateString() + "<br />" + dateList[i]["text"] + "<br />"); // <a href class='url'>" + dateList[i]["url"] + "</a>

                                }

                            }

                            if (clickedEventText == "") 

                                clickedEventText = "<b>" + clickedEventText.concat(options.noEvents) + "</b>";

                            $("#" + divID + " .content").html(clickedEventText);

                        })

                    });

                }

                else {

                    if ((currentDate.getMonth() == selectedWeek.getMonth()) && (currentDate.getFullYear() == selectedWeek.getFullYear())) {

                        todayText = "";

                        for (var i = 0; i <= dateList.length - 1; i++) {

                            if ((currentDate.toLocaleDateString() == dateList[i]["dateStart"].toLocaleDateString() || currentDate.getTime() >= dateList[i]["dateStart"].getTime()) && (currentDate.toLocaleDateString() == dateList[i]["dateEnd"].toLocaleDateString() || currentDate.getTime() <= dateList[i]["dateEnd"].getTime())) {

                                todayText = todayText.concat("<b>" + dateList[i]["title"] + "</b><br />" + currentDate.toLocaleDateString() + "<br />" + dateList[i]["text"] + "<br />"); // <a href class='url'>" + dateList[i]["url"] + "</a>

                            }

                        }

                        if (todayText == "") {

                            todayText = "<b>" + todayText.concat(options.noEventsToday) + "</b>";

                        }

                        $("#" + divID + " .content").html(todayText);

                    }

                    // add day events

                    $("#" + divID + " .body .date .day").each(function(){

                        $(this).parent().hover(function(){

                            $(this).addClass("mouseOver");

                        }, function(){

                            $(this).removeClass("mouseOver");

                        });

                        $(this).parent().click(function(){

                            $("#" + divID + " .body .date").each(function(){

                                $(this).removeClass("currentDate");

                            })

                            $(this).addClass("currentDate");

                            clickedEventText = "";

                            selectedDate.setFullYear(selectedWeek.getFullYear());

                            selectedDate.setMonth(selectedWeek.getMonth());

                            var date;

                            if ($(this).text().length == 5) 

                                date = $(this).text().substr(0, 2);

                            else 

                                if ($(this).text().length == 4) 

                                    date = $(this).text().substr(0, 1);

                            selectedDate.setDate(date);

                            $("#" + divID + " .body .date .day").each(function(){

                                if ($(this).text() == daysInMonth(selectedDate.getMonth() + 1, daysInMonth(selectedDate.getFullYear()))) {

                                    if (date >= 1 && date <= 7) {

                                        selectedDate.setMonth(selectedDate.getMonth() + 1);

                                    }

                                }

                            })

                            for (var i = 0; i <= dateList.length - 1; i++) {

                                if ((selectedDate.toLocaleDateString() == dateList[i]["dateStart"].toLocaleDateString() || selectedDate.getTime() >= dateList[i]["dateStart"].getTime()) && (selectedDate.toLocaleDateString() == dateList[i]["dateEnd"].toLocaleDateString() || selectedDate.getTime() <= dateList[i]["dateEnd"].getTime())) {

                                    clickedEventText = clickedEventText.concat("<b>" + dateList[i]["title"] + "</b><br />" + selectedDate.toLocaleDateString() + "<br />" + dateList[i]["text"] + "<br />"); // <a href class='url'>" + dateList[i]["url"] + "</a>

                                }

                                else {

                                    if ((selectedDate.toLocaleDateString() == dateList[i]["dateStart"].toLocaleDateString() || selectedDate.getTime() >= dateList[i]["dateStart"].getTime()) && (selectedDate.toLocaleDateString() == dateList[i]["dateEnd"].toLocaleDateString() || selectedDate.getTime() <= dateList[i]["dateEnd"].getTime())) {

                                        clickedEventText = clickedEventText.concat("<b>" + dateList[i]["title"] + "</b><br />" + selectedDate.toLocaleDateString() + "<br />" + dateList[i]["text"] + "<br />"); // <a href class='url'>" + dateList[i]["url"] + "</a>

                                    }

                                }

                            }

                            if (clickedEventText == "") 

                                clickedEventText = "<b>" + clickedEventText.concat(options.noEvents) + "</b>";

                            $("#" + divID + " .content").html(clickedEventText);

                        })

                    });

                }

            }

        });

    };

})(jQuery);


