(function($){
    $.fn.jqueryCal = function(options){
        var defaults = {
            xmlPath: BASE_URL + 'user_content/kalendarz/',
            noEventsToday: 'brak wydarzeń w dniu dzisiejszym',
            noEvents: 'brak wydarzeń',
			getXMLmonthly: true,
            toolTipBigPrev: "poprzedni rok",
			toolTipSmallPrev: "poprzedni miesiąc",
			toolTipSmallNext: "następny rok",
			toolTipBigNext: "nastepny 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("Po", "Wt", "Śr", "Cz", "Pi", "So", "Ni");
            var weekday = new Array("Sobota", "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
					dateList = new Array();
					
                    $.ajax({
                        type: "GET",
                        url: xmlPath + "?random=" + (Math.random() * 1000),
                        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]["category"]	= $(this).find('category').text();
                                dateList[i]["title"]	= $(this).find('title').text();
                                dateList[i]["text"]		= $(this).find('text').text();
                                dateList[i]["url"]		= $(this).find('url').text();
                            });
							
							fillHTML(true);
                        },
						
						error: function() {
							fillHTML();
						}
						
                    })
				} 
                catch (err) {
                    //fillHTML();
                }

            }
			
			function loaderToogle(__state)
			{
				if (__state) {
					$("#" + divID + " .loader").show();
	
					$("#" + divID + " .body").stop().fadeTo(300, 0.5);
				}

				else {
					$("#" + divID + " .loader").hide();

					$("#" + divID + " .body").stop().fadeTo(300, 1);
				}
			}
            
            
            // write HTML
            function writeHTML(){
                if ((divID).match("Month")) {
                    htmlString += "<div class='head'><a class='smallPrev but'  title='" + options.toolTipSmallPrev + "' href='#'></a><span class='text'></span><a class='smallNext but' title='" + options.toolTipSmallNext + "' href='#'></a><div class='loader-holder'><div class='loader'></div></div></div><div class='body'>";
                    //htmlString += "<span class='kw'>KW</span>";
					
                    //for (var i = 0; i <= 5; i++) {
                    //    htmlString += "<span class='calendarWeek'></span>";
                    //}
					
					
					// name of weekDays
                    htmlString += "<div class='weekDaysContainer'>";
                    for (var i = 0; i <= 6; i++) {
                        htmlString += "<span class='weekDays " + weekClasses[i] + "'></span>";
                    }
					
					
					
                    htmlString += "</div><div class='weekDatesContainer'>";
					var j = 0;
                    for (var i = 0; i <= 41; i++) {
                        
                        if (j == 7) htmlString += "<span class='weekDates weekDatesSun " + weekClasses[j] + "'></span>";
						else htmlString += "<span class='weekDates " + weekClasses[j] + "'></span>";
						
						j++;
						
                        if (j == 7) j = 0;
                    }
                    htmlString += "</div><br class='clearfloat' /><div class='events-holder'><div class='selected-date'>Wybrana data: <span class='date-value'></span></div><div class='content'></div></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(){
						loaderToogle(true);
						
                        selectedDate.setMonth(selectedDate.getMonth() - 1);
                        tempDate.setDate(1);
                        tempDate.setMonth(tempDate.getMonth() - 1);
                        parseXML();
						return false;
                    });
                    $("#" + divID + " .head .smallNext").click(function(){
						loaderToogle(true);
						
                        selectedDate.setMonth(selectedDate.getMonth() + 1);
                        tempDate.setDate(1);
                        tempDate.setMonth(tempDate.getMonth() + 1);
                        parseXML();
						return false;
                    });
//                    $("#" + divID + " .head .bigNext").click(function(){
//                        selectedDate.setYear(selectedDate.getFullYear() + 1);
//                        tempDate.setDate(1);
//                        tempDate.setYear(tempDate.getFullYear() + 1);
//                        parseXML();
//                    });
                }

                fillHTML(true);
                parseXML();
            }
            
            
            // fill HTML
            function fillHTML(markEvents){
                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();
					
					// disable displaying calendar weeks numbers
                    //$("#" + 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");
							
							
                        }
                    });
					
					if(markEvents)
					{
						// mark events
						for (var i = 0; i <= dateList.length - 1; i++) {
							//console.log('dateList', dateList[i]);
							
							$("#" + divID + " .body .weekDatesContainer .weekDates").each(function(){
								if ($(this).text() != "") {
									tempDate.setDate($(this).text());
									//console.log('tempDate', tempDate);
									
									if (tempDate.getTime() == dateList[i]["dateStart"].getTime() && tempDate.getTime() == dateList[i]["dateEnd"].getTime()) 
									{
										//console.log('tempDate.getTime()', tempDate.getTime());
										//console.log('dateList[i]["dateStart"].getTime()', dateList[i]["dateStart"].getTime());

										switch (dateList[i]["category"])
										{
											case 'event':	$(this).addClass("event"); break;	
											case 'gallery': $(this).addClass("gallery"); break;

											default: $(this).addClass("event");
										}
										
										if ($(this).attr('title') == '') $(this).attr('title', ' -=- ' + dateList[i]["title"]);
										else $(this).attr('title', $(this).attr('title') + '<br />' + dateList[i]["title"]);
									}
								}
							})
						}	
						
						$('#' + divID + ' .body .event, #' + divID + ' .body .gallery').tooltip({
							track: true,
							delay: 0,
							showURL: false,
							showBody: " -=- ",
							fade: 250
						});
					}
					
					// add events
					addEventInfo();
                }
                
				loaderToogle(false);
            }
            
            
            // clean HTML month
            function cleanHTMLMonth(){
                $("#" + divID + " .body .weekDatesContainer .weekDates").each(function(){
                    $(this).text("");
                    $(this).removeClass("event");
					$(this).removeClass("gallery");
                    $(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-1) % 4 == 0) && ((year-1) % 100 != 0)) || ((year-1) % 400 == 0))
                    return m[1] + 1;
                return m[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 = "<ul>";
						
                        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())) 
							{
								if (dateList[i]["url"] == '') todayText = todayText.concat("<li><span class='" + dateList[i]["category"] + "'>" + dateList[i]["title"] + "</span></li>");
                                else todayText = todayText.concat("<li><a href='" + dateList[i]["url"] + "' class='" + dateList[i]["category"] + "'>" + dateList[i]["title"] + "</a></li>");
                            }
                        }
						
						todayText += "</ul>";
						
                        if (todayText == "<ul></ul>") 
						{
                            todayText = "<b>" + todayText.concat(options.noEventsToday) + "</b>";
                        }
						
                        $("#" + divID + " .content").html(todayText);
						// add value of current
						$("#" + divID + " .date-value").html(currentDate.toLocaleDateString());
                    }
                    // 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 = "<ul>";
                            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())) {
                                    if(dateList[i]["url"] == '') clickedEventText = clickedEventText.concat("<li><span class='" + dateList[i]["category"] + "'>" + dateList[i]["title"] + "</span></li>");
									else clickedEventText = clickedEventText.concat("<li><a href='" + dateList[i]["url"] + "' class='" + dateList[i]["category"] + "'>" + dateList[i]["title"] + "</a></li>");
                                }
                            }
							
							clickedEventText += "</ul>";
							
                            if (clickedEventText == "<ul></ul>")
							{
								clickedEventText = "<strong>" + clickedEventText.concat(options.noEvents) + "</strong>";
							}
							
                            $("#" + divID + " .content").html(clickedEventText);
							$("#" + divID + " .date-value").html(selectedDate.toLocaleDateString());
                        })
                    });
                }
            }
        });
    };
})(jQuery);
