/* Originally written by InitUser of http://plugins.jquery.com/project/Eventcalendar March 31 2009.
Script modified from German to English by Sam Cleaver (Beaver6813). Script modifications by Sam Cleaver (Beaver6813).*/
(function($){
    $.fn.jqueryCal = function(options){
        var defaults = {
            xmlPath: '',
            noEvents: 'no events.',
            noEventsToday: 'no events today',
            monthText: '',
            getXMLmonthly: true,
            toolTipBigPrev: "Last Year",
            toolTipSmallPrev: "Last Month",
            toolTipSmallNext: "Next Year",
            toolTipBigNext: "Next Month"
        };
        var options = $.extend(defaults, options);
        return this.each(function(){
            // global vars
            var divID = $(this).attr("id");
            var dateList = new Array();
            var weekClasses = new Array("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su");
            var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
            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();
			//Update outer calendar height
            function updateCal()
				{
				$('.cal_contentCalendar').height($('.cal_body').height()+$('.cal_head').height());		
				}
            // parse XML
            function parseXML(){
                try {
                    if (options.getXMLmonthly) 
                        xmlPath = options.xmlPath + "year=" + selectedDate.getFullYear() + "-month=" + (selectedDate.getMonth() + 1);
                    else 
                        xmlPath = options.xmlPath + "year=" + selectedDate.getFullYear();
                    // 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();
                                dateList[i]["link"] = $(this).find('link').text();
                            })
                            fillHTML();
                        },
						error: function() {fillHTML();}
                    })
                } 
                catch (err) {
                    fillHTML();
                }
            }
            
            
            // write HTML
            function writeHTML(){
                if ((divID).match("Month")) {
                    htmlString += "<div class='cal_head'><a class='cal_bigPrev' title='" + options.toolTipBigPrev + "' style='cursor:pointer;'</a><a class='cal_smallPrev'  title='" + options.toolTipSmallPrev + "' style='cursor:pointer;'></a><span class='cal_text'></span><a class='cal_smallNext' title='" + options.toolTipSmallNext + "' style='cursor:pointer;'></a><a class='cal_bigNext' title='" + options.toolTipBigNext + "' style='cursor:pointer;'></a></div><div class='cal_body'><div class='cal_calendarWeekContainer'>";
                    htmlString += "<span class='cal_kw'></span>";
                    for (var i = 0; i <= 5; i++) {
                        htmlString += "<span class='cal_calendarWeek'></span>";
                    }
                    htmlString += "</div><div class='cal_weekDaysContainer'>";
                    for (var i = 0; i <= 6; i++) {
                        htmlString += "<span class='cal_weekDays cal_" + weekClasses[i] + "'></span>";
                    }
                    htmlString += "</div><div class='cal_weekDatesContainer'>";
                    for (var i = 0; i <= 41; i++) {
                        var j = 0;
                        j++;
                        htmlString += "<span class='cal_weekDates cal_" + weekClasses[j] + "'></span>";
                        if (j = 6) 
                            j = 0;
                    }
					
                    htmlString += "</div><div class='cal_contentBegin'></div><div class='cal_content'></div><div class='cal_footer'></div></div>";
                    $("#" + divID).html(htmlString);
                    // month
                    $("#" + divID + " .cal_head .cal_bigPrev").click(function(){
                        selectedDate.setYear(selectedDate.getFullYear() - 1);
                        tempDate.setDate(1);
                        tempDate.setYear(tempDate.getFullYear() - 1);
                        parseXML();
						updateCal();
                    });
                    $("#" + divID + " .cal_head .cal_smallPrev").click(function(){
                        selectedDate.setMonth(selectedDate.getMonth() - 1);
                        tempDate.setDate(1);
                        tempDate.setMonth(tempDate.getMonth() - 1);
                        parseXML();
						updateCal();
                    });
                    $("#" + divID + " .cal_head .cal_smallNext").click(function(){
                        selectedDate.setMonth(selectedDate.getMonth() + 1);
                        tempDate.setDate(1);
                        tempDate.setMonth(tempDate.getMonth() + 1);
                        parseXML();
						updateCal();
                    });
                    $("#" + divID + " .cal_head .cal_bigNext").click(function(){
                        selectedDate.setYear(selectedDate.getFullYear() + 1);
                        tempDate.setDate(1);
                        tempDate.setYear(tempDate.getFullYear() + 1);
                        parseXML();
						updateCal();
                    });
                }
                else 
                    if ((divID).match("Week")) {
                        htmlString += "<div class='cal_head'><a class='cal_bigPrev' title='" + options.toolTipBigPrev + "' style='cursor:pointer;'></a><a class='cal_smallPrev' title='" + options.toolTipSmallPrev + "' style='cursor:pointer;'></a><span class='cal_text'></span><a class='cal_smallNext'  title='" + options.toolTipSmallNext + "'  style='cursor:pointer;'></a><a class='cal_bigNext' title='" + options.toolTipBigNext + "'  style='cursor:pointer;'></a></div><div class='cal_body'>";
                        for (var i = 0; i <= 6; i++) 
                            htmlString += "<a class='cal_date'><span class='cal_day cal_" + weekClasses[i] + "'></span><span class='cal_weekday'> " + weekClasses[i] + "</span></a>";
                        htmlString += "</div><div class='cal_content'></div><div class='cal_footer'></div>";
                        $("#" + divID).html(htmlString);
                        // week
                        $("#" + divID + " .cal_head .cal_bigPrev").click(function(){
                            selectedWeek.setMonth(selectedWeek.getMonth() - 1);
                            parseXML();
							updateCal();
                        });
                        $("#" + divID + " .cal_head .cal_smallPrev").click(function(){
                            selectedWeek.setDate(selectedWeek.getDate() - 7);
                            parseXML();
							updateCal();
                        });
                        $("#" + divID + " .cal_head .cal_smallNext").click(function(){
                            selectedWeek.setDate(selectedWeek.getDate() + 7);
                            parseXML();
							updateCal();
                        });
                        $("#" + divID + " .cal_head .cal_bigNext").click(function(){
                            selectedWeek.setMonth(selectedWeek.getMonth() + 1);
                            parseXML();
							updateCal();
                        });
                    }
                fillHTML();
                parseXML();
            }
            
            
            // fill HTML
            function fillHTML(){
                if ((divID).match("Month")) {
                    // clean HTML
                    cleanHTMLMonth();
                    var firstOfSelectedMonth = selectedDate;
                    firstOfSelectedMonth.setDate(1);
                    currentDate = new Date();
                    $("#" + divID + " .cal_head .cal_text").html(options.monthText + " " + selectedDate.getMonthName() + " " + selectedDate.getFullYear());
                    for (i = 0; i <= weekClasses.length; i++) {
                        $("#" + divID + " .cal_body .cal_weekDaysContainer .cal_weekDays.cal_" + 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 + " .cal_body .cal_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 + " .cal_body .cal_weekDatesContainer .cal_weekDates").each(function(i){
                        if (startWrite <= i && j <= (daysInMonth(firstOfSelectedMonth.getMonth() + 1, firstOfSelectedMonth.getFullYear() + 1))) {
                            $(this).text(j);
                            $(this).addClass("cal_pointer");
                            $(this).hover(function(){
                                $(this).addClass("cal_hover");
                            }, function(){
                                $(this).removeClass("cal_hover");
                            });
                            j++;
                            // mark current day
                            if ((selectedDate.getMonth() == currentDate.getMonth()) && (selectedDate.getFullYear() == currentDate.getFullYear()) && ($(this).text() == currentDate.getDate())) 
                                $(this).addClass("cal_currentDate");
                        }
                    });
                    // mark cal_events
                    for (var i = 0; i <= dateList.length - 1; i++) {
                        $("#" + divID + " .cal_body .cal_weekDatesContainer .cal_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("cal_event");
                                }
                            }
                        })
                    }
                    // add cal_events
                    addEventInfo();
                }
                else 
                    if ((divID).match("Week")) {
                        // clean HTML
                        cleanHTMLWeek();
                        // define weekstart
                        selectedWeek.setDate(selectedWeek.getDate() - selectedWeek.getDay());
                        // fill html
                        $("#" + divID + " .cal_head .cal_text").html(options.monthText + " " + selectedWeek.getMonthName() + " " + selectedWeek.getFullYear());
                        $("#" + divID + " .cal_body .cal_date .cal_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("cal_currentDate");
                        })
                        selectedWeek.setDate(selectedWeek.getDate() - 6);
                        // mark cal_events
                        tempDate.setDate(selectedWeek.getDate());
                        tempDate.setMonth(selectedWeek.getMonth());
                        tempDate.setFullYear(selectedWeek.getFullYear());
                        $("#" + divID + " .cal_body .cal_date .cal_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("cal_event");
                                }
                            }
                            tempDate.setDate(tempDate.getDate() + 1);
                        })
                        addEventInfo();
                    }
					updateCal();
            }
            
            
            // clean HTML month
            function cleanHTMLMonth(){
                $("#" + divID + " .cal_body .cal_weekDatesContainer .cal_weekDates").each(function(){
                    $(this).text("");
                    $(this).removeClass("cal_event");
                    $(this).removeClass("cal_currentDate");
                    $(this).removeClass("cal_pointer");
                    $(this).unbind();
                    $(this).click(function(){
                    });
                })
                $("#" + divID + " .cal_head .cal_text").cal_text = "";
            }
            
            
            // clean HTML week
            function cleanHTMLWeek(){
                $("#" + divID + " .cal_body .cal_date").each(function(j){
                    $(this).removeClass("cal_event");
                    $(this).removeClass("cal_currentDate");
                    $(this).removeClass("cal_pointer");
                    $(this).unbind();
                    $(this).click(function(){
                    });
                })
                $("#" + divID + " .cal_head .cal_text").cal_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 cal_event info  
            function addEventInfo(){
                if ((divID).match("Month")) {
                    if ((currentDate.getMonth() == selectedDate.getMonth()) && (currentDate.getFullYear() == selectedDate.getFullYear())) {
                        todayText = "";
						var firststop = false;
                        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(!firststop)
									{
								var firststop = true;								
                                todayText = todayText.concat("- <b><a href=\""+dateList[i]["link"]+"\" title=\"View events for this day.\">View events for this day.</a></b><br/>"); // <a href class='url'>" + dateList[i]["url"] + "</a>
									}
                            }
                        }
                        if (todayText == "") {
                            todayText = "<b>" + todayText.concat(options.noEventsToday) + "</b>";
                        }
                        $("#" + divID + " .cal_content").html(todayText);
                    }
                    // add day cal_events
                    $("#" + divID + " .cal_body .cal_weekDatesContainer .cal_pointer").each(function(){
                        $(this).hover(function(){
                            $(this).addClass("cal_mouseOver");
                        }, function(){
                            $(this).removeClass("cal_mouseOver");
                        });
                        $(this).click(function(){
                            $("#" + divID + " .cal_body .cal_weekDatesContainer .cal_pointer").each(function(){
                                $(this).removeClass("cal_currentDate");
                            })
                            $(this).addClass("cal_currentDate");
                            clickedEventText = "";
							var firststop = false;
                            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(!firststop)
									{
								var firststop = true;	
                                    clickedEventText = clickedEventText.concat("- <b><a href=\""+dateList[i]["link"]+"\" title=\"View events for this day.\">View events for this day.</a></b><br/>"); // <a href class='url'>" + dateList[i]["url"] + "</a>
									}
                                }
                            }
                            if (clickedEventText == "") 
                                clickedEventText = "<b>" + clickedEventText.concat(options.noEvents) + "</b>";
                            $("#" + divID + " .cal_content").html(clickedEventText);
							updateCal();
                        })
                    });
                }
                else {
                    if ((currentDate.getMonth() == selectedWeek.getMonth()) && (currentDate.getFullYear() == selectedWeek.getFullYear())) {
                        todayText = "";
						var firststop =false;
                        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(!firststop)
									{
								var firststop = true;	
                                todayText = todayText.concat("- <b><a href=\""+dateList[i]["link"]+"\" title=\"View events for this day.\">View events for this day.</a></b><br/>"); // <a href class='url'>" + dateList[i]["url"] + "</a>
									}
                            }
                        }
                        if (todayText == "") {
                            todayText = "<b>" + todayText.concat(options.noEventsToday) + "</b>";
                        }
                        $("#" + divID + " .cal_content").html(todayText);
                    }
                    // add day cal_events
                    $("#" + divID + " .cal_body .cal_date .cal_day").each(function(){
                        $(this).parent().hover(function(){
                            $(this).addClass("cal_mouseOver");
                        }, function(){
                            $(this).removeClass("cal_mouseOver");
                        });
                        $(this).parent().click(function(){
                            $("#" + divID + " .cal_body .cal_date").each(function(){
                                $(this).removeClass("cal_currentDate");
                            })
                            $(this).addClass("cal_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 + " .cal_body .cal_date .cal_day").each(function(){
                                if ($(this).text() == daysInMonth(selectedDate.getMonth() + 1, daysInMonth(selectedDate.getFullYear()))) {
                                    if (date >= 1 && date <= 7) {
                                        selectedDate.setMonth(selectedDate.getMonth() + 1);
                                    }
                                }
                            })
							var firststop = false;
                            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(!firststop)
									{
								var firststop = true;	
                                    clickedEventText = clickedEventText.concat("- <b><a href=\""+dateList[i]["link"]+"\" title=\"View events for this day.\">View events for this day.</a></b><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())) {
										if(!firststop)
									{
								var firststop = true;	
                                        clickedEventText = clickedEventText.concat("- <b><a href=\""+dateList[i]["link"]+"\" title=\"View events for this day.\">View events for this day.</a></b><br/>"); // <a href class='url'>" + dateList[i]["url"] + "</a>
									}
                                    }
                                }
                            }
                            if (clickedEventText == "") 
                                clickedEventText = "<b>" + clickedEventText.concat(options.noEvents) + "</b>";
                            $("#" + divID + " .cal_content").html(clickedEventText);
							updateCal();
                        })
                    });
                }
            }
			updateCal();
        });
    };
})(jQuery);

