/**
 * Written by I Ørstavik for Skrivesenteret. For free public consumption :)
 * "month, year" can be given in relative format. For example:
 * 		"-1, 2009" => 11, 2008
 *		"14, 2009" => 2, 2010
 */

function Calendar(month, year, name, tableIn) {
    this._m = month;
    this._y = year;
	
	/** 
	the two loops allows  
	**/
    while (this._m < 0){
	    this._m += 12;
	    this._y -= 1;    
    } 
    while (this._m > 11){
	    this._m -= 12;
	    this._y += 1;    
    }

    this._calendar = name;
    this._monthsNO = ['jan','feb','mar','apr','mai','jun','jul','aug','sept','okt','nov','des'];

    this.today = new Date();

    this._copycat = $("#template2").hide();
    //this.table = $("#template1").hide().clone().attr("id", "").show();
    this.table = tableIn;
    this._tds = this.table.find(".calDate");
    this._weeks = this.table.find(".calWeek");
    this._left = $(this.table.find(".calImg")[0]);
    this._right = $(this.table.find(".calImg")[1]);
    this._header = this.table.find("#calTH a");
}

Calendar.prototype.nextMonth = function() {
    this._y = this._m == 11 ? this._y + 1 : this._y;
    this._m = this._m == 11 ? 0 : this._m + 1;
    this.makeCalendar();
};

Calendar.prototype.prevMonth = function() {
    this._y = this._m == 0 ? this._y - 1 : this._y;
    this._m = this._m == 0 ? 11 : this._m - 1;
    this.makeCalendar();
};

Calendar.prototype.updateHeader = function() {
    this._left.unbind().bind('click', {caller: this}, function(e) { e.data.caller.prevMonth(); });
    this._right.unbind().bind('click', {caller: this}, function(e) { e.data.caller.nextMonth(); });
    this._header.attr("href", "http://skrivesenteret.no/scripts/calendarlist?calendar=" + this._calendar + "&month=" + this._m + "&year=" + this._y)
            .html(this._monthsNO[this._m] + " " + this._y);
};

Calendar.prototype.makeCalendar = function () {
    this.colorToday();
    this.shuffleDays();
    this.updateHeader();
    this._tds.hover( function() { $(this).stop().addClass("hover").find("div").show(); },
                    function() { $(this).stop().removeClass("hover").find("div").hide(); });
    this.updateInfo();
    return this;
};

Calendar.prototype.toHtml = function(){
    return this.makeCalendar().table;
};

Calendar.prototype.shuffleDays = function() {
    var td = this._tds;
    var lastDayOfMonth = new Date(this._y, this._m + 1, 0).getDate();
    td = td.slice(0, lastDayOfMonth);

    this._weeks.empty();
    var firstWeekDay = new Date(this._y, this._m, 1).getDay();
    firstWeekDay = (firstWeekDay == 0) ? 6 : firstWeekDay - 1; //Norwegian style, not US
    if (firstWeekDay != 0)
        $(this._weeks[0]).append("<td colspan='" + firstWeekDay + "'>&nbsp;</td>");
    $(this._weeks[0]).append(td.splice(0, 7 - firstWeekDay));

    for (var i = 1; td.length != 0; i++)
        $(this._weeks[i]).append(td.splice(0, 7));
};

Calendar.prototype.updateInfo = function() {
    this.table.find(".calInfo").remove();
    this.table.find(".calEvent").removeClass("calEvent");
    var thiz = this;

	$.ajax({
	  url: 'http://skrivesenteret.no/scripts/hent_kalendernyheter?jsoncallback=?',
	  dataType: 'json',
	  data: { 'month' : this._m, 'year' : this._y, 'calendar' : this._calendar },
	  async: false,
	  success: function(data){
            $.each(data, function() {
                for (var day = this.start; day <= this.stop; day++) {
                    var clone = thiz._copycat.clone();
                    clone.find(".calLink").attr("href", this.url);
                    clone.find(".calTitle").html(this.title);
                    clone.find(".calSubtitle1").html(this.subtitle1);
                    clone.find(".calSubtitle2").html(this.subtitle2);
                    clone.find(".calDescription").html(this.description);
                    var theDay = $(thiz._tds[day - 1]);
                    var exisiting = theDay.find(".calInfo");
                    if (exisiting.length == 0) 
                    	theDay.addClass("calEvent").append(clone);
                    else
                    	exisiting.append("<hr />").append(clone.find(".calLink"));
                    if (this.url == "") 
                    	clone.find(".calTitle").unwrap();
                }
            });
       }
	});
};

Calendar.prototype.colorToday = function () {
    if (this.today.getMonth() == this._m && this.today.getFullYear() == this._y)
        $(this._tds[this.today.getDate() - 1]).addClass("today");
    else
        this.table.find(".today").removeClass("today");
};
