/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */

var oMiniCalendar;
var b3xViewLoaded;
var calendarMiniJson = new JSON();

function cAnimMiniCalendar(actionFunction, oDOMHeader, nodes) {
		this.initDate = new Date();
		this.actionFunction = actionFunction;
		this.MiniRefer = null;
		this.selectedDate = this.initDate.getDate();
		this.selectedMonth = this.initDate.getMonth();
		this.selectedYear = this.initDate.getFullYear();
		this.animationInProgress = false;
		this.todayYear = this.selectedYear;
		this.selectedTime = this.initDate.getTime();
		this.selectedId;
		this.header = oDOMHeader;
		this.header0;
		this.nodes = nodes;
		this.enable_action = configGetKey("modules.calendar.module");
		var bDisplayApps = configGetKey("modules.calendar.module");		
		if (!this.enable_action) {
			actionFunction = function () { 
				triggerEvent("Feature_Not_Available", "modules/calendar/mini_calender"); 
			};
		}
		
		if (this.nodes == undefined) {
			this.nodes = [ $("container_mini"), $("header_mini_month"), $("header_mini_year") ];
		}
		
		this.MiniRefer = new cMiniCalendar(oDOMHeader,
				nodes[0], actionFunction,bDisplayApps,
				'mini_subcontainer_0', nodes[1], nodes[2], this.initDate);
		this.MiniRefer.dnd_enabled = true;
		this.MiniRefer.enable_action = this.enable_action;
		var Self = this;
		
		function fn_KWAction(arg) {	
			
			var DOMTarget = (arg.target)?arg.target:arg.srcElement;
			var sId = DOMTarget.id;
			for (var indx in Self.MiniRefer.miniCalendarAssoc) {
				var aInf = Self.MiniRefer.miniCalendarAssoc[indx];
				if(aInf[3] == sId.split('_')[1]) {
					break;
				}
			}	
			var nDate = aInf[0];
			var oDate = new Date();
			oDate.setDate(1);
			oDate.setMonth(Self.MiniRefer.currentMonth);						
			oDate.setFullYear(Self.MiniRefer.currentYear);						
			if (aInf[1] == 1) {
				oDate.setMonth(oDate.getMonth());
			} else if (aInf[1] == 0) {
				oDate.setMonth(oDate.getMonth()-1);
			} else if (aInf[1] == 2) {
				oDate.setMonth(oDate.getMonth()-1);
			}			
			oDate.setDate(nDate);
				    
		    if (currentpath2[1] != "team") {
		    	objWeekCalendarTool.init(oDate.getFullYear(),oDate.getMonth(),oDate.getDate());
				objWeekCalendarTool.setKW();
		    	if (currentpath2[2] != "week") {
                    ox.UIController.setModule({module: "calendar", folder:"auto", view:"calendar/calendar/week",force: "module"});
		    	}
				// notify via event
			    triggerEvent("OX_Mini_Calendar_Date_Picked", oDate.getUTCFullYear(), 
			    		oDate.getUTCMonth(), oDate.getUTCDate());
		    }
		   
		    Self.MiniRefer.setSelectedByDate(oDate.getFullYear(),oDate.getMonth(),oDate.getDate());
			
			
		}
		function fn_DBLAction(arg) {
			triggerEvent('OX_Before_Create_Calendar');
			Self.MiniRefer.setSelectedByDate(Self.selectedYear, Self.selectedMonth, Self.selectedDate);
		}
		// don't implement functions for CW clicks and double clicks; simple clicks are disabled in the constructor
		if (this.enable_action) {
			this.MiniRefer.setfnKWAction(fn_KWAction);
			this.MiniRefer.setfnDBLAction(fn_DBLAction);	
		} else {
			this.MiniRefer.setfnKWAction(function() { 
				    triggerEvent("Feature_Not_Available", "modules/calendar/mini_calender"); 
			});		
		}
}
cAnimMiniCalendar.prototype = {
	destroy: function() {
		this.MiniRefer.destroy();
	},
	
	load: function() {
		this.MiniRefer.load(this.MiniRefer);		
	},
	
	setSelectedByDate: function (year, month, day) {
		this.MiniRefer.setSelectedByDate(year, month, day);
	},
	
	update: function () {
		this.MiniRefer.update();
		this.MiniRefer.setToday();
	},	
	
	setSelected: function(sId) {
		this.MiniRefer.setUnselected();	
		//find calendar where id is defined
		if (this.MiniRefer.miniCalendarAssoc[sId]) {
			this.MiniRefer.setSelected(sId);
			this.selectedDate = this.MiniRefer.selectedDate;
			this.selectedMonth = this.MiniRefer.selectedMonth;
			this.selectedYear  = this.MiniRefer.selectedYear;
			this.selectedTime = Date.UTC(this.MiniRefer.selectedYear,
												this.MiniRefer.selectedMonth,
														this.MiniRefer.selectedDate);		
		}
	},	
	
	checkloaded: function() {		
		return this.MiniRefer.loaded;		
	},
	
	scroll: function(nDirection,cb_fn) {		
		var Self = this;
		var nStart = jQuery(Self.nodes[0]).parent()[0].scrollLeft;
		function do_scroll(nStep) {
			if (nDirection > 0)
				jQuery(Self.nodes[0]).parent()[0].scrollLeft = Math.log(Math.pow(nStep,0.66))*66;
			else
				jQuery(Self.nodes[0]).parent()[0].scrollLeft = nStart - Math.log(Math.pow(nStep,0.66))*66;
		}
		animate((configGetKey("gui.effects.fading") ? 750 : 0), 245, do_scroll,cb_fn);
	},
	
	next: function(num) {
		var Self = this;		
		if (!this.checkloaded() || this.animationInProgress) return;
		var NextDate = new Date();
		NextDate.setUTCFullYear(this.MiniRefer.currentYear);
		NextDate.setUTCDate(1);	
		NextDate.setUTCMonth(this.MiniRefer.currentMonth);			
		NextDate.setUTCMonth(NextDate.getUTCMonth()+num);
		Self.MiniRefer.set_header(NextDate);		
		this.MiniRefer.appointmentList = new Array();	
		Self.MiniRefer.currentMonth = NextDate.getUTCMonth();
		Self.MiniRefer.currentYear = NextDate.getUTCFullYear();																
		Self.MiniRefer.oCalendar = new cCalendar(NextDate.getUTCMonth(),NextDate.getUTCFullYear());		
		var oNextTable = this.MiniRefer.getTable(Self.MiniRefer.oCalendar);
		var switchsubContainer = newnode('div',{ left:"239px", position:"absolute" });
		switchsubContainer.appendChild(oNextTable);
		this.nodes[0].appendChild(switchsubContainer);
		this.animationInProgress = true;
		jQuery(this.nodes[0]).parent()[0].scrollLeft = 0;
		this.MiniRefer.subcontainer.style.left = "0px";		
		this.scroll(1, function(){
			Self.nodes[0].removeChild(Self.MiniRefer.subcontainer);
			Self.MiniRefer.subcontainer = switchsubContainer;
			Self.animationInProgress = false;
			if(Self.MiniRefer.displayAppointments)
				Self.MiniRefer.update();						
		});
	},
	
	back: function(num) {
		var Self = this;		
		if (!this.checkloaded() || this.animationInProgress) return;
		var NextDate = new Date();
		NextDate.setUTCFullYear(this.MiniRefer.currentYear);
		NextDate.setUTCDate(1);	
		NextDate.setUTCMonth(this.MiniRefer.currentMonth);			
		NextDate.setUTCMonth(NextDate.getUTCMonth()-num);
		Self.MiniRefer.set_header(NextDate);	
		this.MiniRefer.appointmentList = new Array();	
		Self.MiniRefer.currentMonth = NextDate.getUTCMonth();								
		Self.MiniRefer.currentYear = NextDate.getUTCFullYear();																
		Self.MiniRefer.oCalendar = new cCalendar(NextDate.getUTCMonth(),NextDate.getUTCFullYear());		
		var oNextTable = this.MiniRefer.getTable(Self.MiniRefer.oCalendar);
		var switchsubContainer = newnode('div',{ left:"0px", position:"absolute" });
		switchsubContainer.appendChild(oNextTable);
		this.nodes[0].insertBefore(switchsubContainer, this.MiniRefer.subcontainer);
		this.animationInProgress = true;
		this.MiniRefer.subcontainer.style.left = "239px";
		jQuery(this.nodes[0]).parent()[0].scrollLeft = 245;
		this.scroll(-1,function (){
			Self.nodes[0].removeChild(Self.MiniRefer.subcontainer);
				Self.MiniRefer.subcontainer = switchsubContainer;
				Self.animationInProgress = false;
				if(Self.MiniRefer.displayAppointments)
					Self.MiniRefer.update();
			});
	},
	go_to: function(oDate){
		this.MiniRefer.go_to(oDate);
	},
	
	today: function() {
	    
	    if (!this.checkloaded() || this.animationInProgress) return;
        
		// get current date
	    var today = new Date();
	    // do NOT use UTC here! 
	    // see Bug 17397 - [L3] 'Today' button in calendar only works for GMT
	    // Example: 8:00 (AM) in Tokio is 23:00 UTC - but yesterday.
	    activeDay = today.getDate();
        activeMonth = today.getMonth();
        activeYear = today.getFullYear();
        
        // notify via event
        triggerEvent("OX_Mini_Calendar_Date_Picked", activeYear, activeMonth, activeDay);
        
        if (currentpath2[0] == "calendar") {
        	switch(currentpath2[2]) {
        		case "week":
        		    objWeekCalendarTool.init(activeYear,activeMonth,activeDay);
	                objWeekCalendarTool.setKW();
	                break;
                case "month":
                    loadMonthView();
                    break;
        	}
            triggerEvent("OX_Switch_View", currentpath.join("/"));
            
        } else if (configContainsKey("folder.calendar")) {
	        ox.api.ui.setFolder(configGetKey("folder.calendar"), function () {
	            triggerEvent("OX_Switch_View","calendar/calendar/day"); 
	        });
        }
		this.MiniRefer.go_to(new Date());		
	},
	
	addView: function() {
		this.initDate.setMonth(this.initDate.getMonth()+1);		
		if(!this.header0)	
		{
			var oHeader0 = newnode('div',0,{id:'DOMHeaderMini0'});	
			this.header0  = oHeader0;
			this.MiniCalWidgets[0].header = oHeader0;			
			this.MiniCalWidgets[0].subcontainer.insertBefore(oHeader0,this.MiniCalWidgets[0].table);
			this.MiniCalWidgets[0].updateHeaderMini();	
			//this.header.innerHTML = this.MiniCalWidgets[0].currentYear;
		}
		var oHeader = newnode('div',0,{id:'DOMHeaderMini' + this.MiniCalWidgets.length});			
		var oMiniCalendarNext = new cMiniCalendar(oHeader,
	 			this.nodes[0], this.actionFunction,true,'mini_subcontainer_'+this.MiniCalWidgets.length,
	 			this.nodes[1],this.nodes[2],this.initDate);
		if (oMiniCalendarNext.table)	 
			oMiniCalendarNext.subcontainer.insertBefore(oHeader
															,oMiniCalendarNext.table);
		else
			oMiniCalendarNext.subcontainer.appendChild(oHeader);
		this.MiniCalWidgets.push(oMiniCalendarNext);
	},
	
	removeView: function() {
		if(this.header0) {
			this.MiniCalWidgets[0].subcontainer.removeChild(this.header0);			
			this.MiniCalWidgets[0].header = this.header;
			this.header0 = null;
			this.MiniCalWidgets[0].updateHeaderMini();				
		}
		this.initDate.setMonth(this.initDate.getMonth()-1);
		var oMonthView = this.MiniCalWidgets.pop();
		if (oMonthView) {
			oMonthView.subcontainer.removeChild(oMonthView.header);
			oMonthView.destroy();
		}
	}	
}


function comboMonthChanged(param,minical)
{
	var NextDate = new Date();
	NextDate.setUTCFullYear(minical.currentYear);
	NextDate.setUTCDate(1);	
	NextDate.setUTCMonth(param);	
	minical.go_to(NextDate);
}
function comboYearChanged(param,minical)
{
	var NextDate = new Date();
	NextDate.setUTCFullYear(param);
	NextDate.setUTCDate(1);	
	NextDate.setUTCMonth(minical.currentMonth);			
	minical.go_to(NextDate);
}

function cMiniCalendar(displayPanelContainer, container, actionFunction,
			bDisplayAppointments, subcontainerid, displayPanelContainerM,
				displayPanelContainerY, initDate, selectedDate) {
	this.enable_action = true;
	this.aMonthNames = [_("January"), _("February"), _("March"), _("April"),
        _("May"), _("June"), _("July"), _("August"), _("September"),
        _("October"), _("November"), _("December")];
	this.container = container;
	this.table;
	this.loaded = false;
	this.dnd_enabled = false;
	this.subcontainerid = subcontainerid || "min_subcontainer_default";
	this.subcontainer = newnode('div', { left:"0px", right:"0px",position:"absolute" });
	jQuery(this.container).parent()[0].scrollLeft = 0;
	this.container.appendChild(this.subcontainer);
	addTMPId(this.subcontainer);
	this.header = displayPanelContainer;
	this.header_month = displayPanelContainerM;
	this.header_year = displayPanelContainerY;	
	this.actionFN = actionFunction;
	this.displayAppointments = bDisplayAppointments;
	// get today (NOT UTC here!)
	var odat = new Date();
	this.todayDate = odat.getDate();
	this.todayMonth = odat.getMonth();	
	this.todayYear = odat.getFullYear();
	if (initDate) {
		this.currentMonth = initDate.getUTCMonth();
		this.currentYear = initDate.getUTCFullYear();
	} else {
		this.currentMonth = this.todayMonth;
		this.currentYear = this.todayYear;
	}
	this.selectedDate = (selectedDate)?selectedDate.getUTCDate():this.todayDate;
	this.selectedMonth = (selectedDate)?selectedDate.getUTCMonth():this.todayMonth;
	this.selectedYear = (selectedDate)?selectedDate.getUTCFullYear():this.todayYear;
	this.selectedTime = Date.UTC(this.todayYear,this.todayMonth,this.todayDate);
	this.appointmentList = new Array();	
	this.selectedID;
	this.miniCalendarAssoc = new Object();
	this.load(this);
	this.oCalendar;
	this.oComboMonth;
	this.oComboYear;	
	this.fnKWAction = null;
	this.actionDBLFN = null;
	
	this.open_in_calendar = newnode("img", { verticalAlign:"middle" }, 
			{ src:getFullImgSrc("img/toolbar/calnder.png"), 
			  alt: _("Show in Calendar"), title: _("Show in Calendar")});
	register("LanguageChanged",(function(Self) {
		return function() {
			Self.open_in_calendar.title = _("Show in Calendar");
			Self.open_in_calendar.alt = _("Show in Calendar");
		}
	})(this));
}	

cMiniCalendar.prototype = {
	setfnDBLAction: function (fn) {
		this.actionDBLFN = fn;
	},
	
	setfnKWAction: function(fn) {
		this.fnKWAction = fn;
	},
	
	setDate: function (year, month, date) { },
	
	destroy: function() {	
		this.selectedID = undefined;	
		this.subcontainer.removeChild(this.table);
		removeTMPId(this.subcontainer.id+"_table");
		for (var i=0; $2(this.subcontainer.id+"mc_"+i+"_0"); i++) {
			for (var i2=0; $2(this.subcontainer.id+"mc_"+i+"_"+i2); i2++) {
				removeTMPId(this.subcontainer.id+"mc_"+i+"_"+i2);
			}
		}	
		for (var i=0; i<54; i++) {
			if ($2("kw_month_"+i)) {
				removeTMPId("kw_month_"+i);
			}
		}
		//TODO REMOVE FROM TMPIDS
		this.loaded = false;
	},
	
	next: function(num) {
		if(num == undefined) num = 1;
		if(!this.loaded) return;
		this.destroy();
		var oDateLoc = new Date();
		oDateLoc.setFullYear(this.currentYear);
		oDateLoc.setDate(1);	
		oDateLoc.setMonth(this.currentMonth);
		oDateLoc.setMonth(oDateLoc.getMonth()+num); 
		this.oComboYear.setDynamicKey(oDateLoc.getFullYear());		
		this.oComboMonth.setKey(oDateLoc.getMonth());

		this.currentMonth = oDateLoc.getMonth();
		this.currentYear = oDateLoc.getFullYear();		
		this.load(this);
	},
	
	back: function(num) {
		if(num == undefined) num = 1;
		if(!this.loaded) return;
		this.destroy();
		var oDateLoc = new Date();
		oDateLoc.setFullYear(this.currentYear);
		oDateLoc.setDate(1);	
		oDateLoc.setMonth(this.currentMonth);
		oDateLoc.setMonth(oDateLoc.getMonth()-num); 
		this.oComboYear.setDynamicKey(oDateLoc.getFullYear());
		this.oComboMonth.setKey(oDateLoc.getMonth());
		
		this.currentMonth = oDateLoc.getMonth();
		this.currentYear = oDateLoc.getFullYear();		
		this.load(this);
	},
	
	go_to: function(oDateLoc) {
		if (!this.loaded) return;
		this.destroy();
		this.set_header(oDateLoc);
		this.currentMonth = oDateLoc.getMonth();
		this.currentYear = oDateLoc.getFullYear();		
		this.load(this);
	},
	
	set_header: function(oDateLoc){
		unregister('OX_Select_MiniMonth',comboMonthChanged);
		unregister('OX_Select_MiniYear',comboYearChanged);
		this.oComboYear.setDynamicKey(oDateLoc.getUTCFullYear());
		this.oComboMonth.setKey(oDateLoc.getUTCMonth());		
		register('OX_Select_MiniMonth',comboMonthChanged);
		register('OX_Select_MiniYear',comboYearChanged);		
	},
	
	load: function(obj) {
		this.oCalendar = new cCalendar(this.currentMonth,this.currentYear);
		if (this.header_month && !this.oComboMonth && !this.oComboYear) {
			this.oComboMonth = new ComboBoxSpecial(window, this.header_month, '7em', this.todayMonth, 
																	false, 'OX_Select_MiniMonth', 6,this) ;
			this.oComboYear = new ComboBoxSpecial(window, this.header_year, '3em', 5, 
																	false, 'OX_Select_MiniYear', 10,this) ;
			this.oComboYear.optWidth = "4em";
			this.oComboYear.show_buttons = true;
			for (var nKeyIndx=-5; nKeyIndx < 5; nKeyIndx++){
				this.oComboYear.addElement(noI18n(this.todayYear+nKeyIndx),
				                           this.todayYear+nKeyIndx);
			}
			for (var nKeyIndx=0;nKeyIndx<this.aMonthNames.length;nKeyIndx++) {
				this.oComboMonth.addElement(this.aMonthNames[nKeyIndx], nKeyIndx);
			}
			this.oComboYear.getDomNode();
			this.oComboMonth.getDomNode();
			register('OX_Select_MiniMonth', comboMonthChanged);
			register('OX_Select_MiniYear', comboYearChanged);			
		}
		var oFirstDayDate = new Date();
		var oLastDayDate = new Date();		

		oFirstDayDate.setUTCHours(0);
		oFirstDayDate.setUTCMinutes(0);		
		oFirstDayDate.setUTCSeconds(0);				
		oFirstDayDate.setUTCDate(1);
		oLastDayDate.setUTCHours(0);
		oLastDayDate.setUTCMinutes(0);		
		oLastDayDate.setUTCSeconds(0);			
		oLastDayDate.setUTCDate(1);		
		
		oFirstDayDate.setUTCFullYear(this.currentYear);
		oLastDayDate.setUTCFullYear(this.currentYear);		

		var aDay = this.oCalendar.aWeeks[0].aDays[0];
		var aDay2 = this.oCalendar.aWeeks[(this.oCalendar.aWeeks.length-1)].aDays[6];		

		oFirstDayDate.setUTCMonth(this.currentMonth);		
		oLastDayDate.setUTCMonth(this.currentMonth);			

		if (aDay.nCurrMonth == 0) {
			oFirstDayDate.setUTCMonth(oFirstDayDate.getUTCMonth()-1);
		}
		if (aDay2.nCurrMonth == 2) {
			oLastDayDate.setUTCMonth(oLastDayDate.getUTCMonth()+1);
		}
			
		oFirstDayDate.setUTCDate(aDay.nDate);
		oLastDayDate.setUTCDate(aDay2.nDate);

		oLastDayDate.setUTCDate(oLastDayDate.getUTCDate()+1);
		
		if (!this.displayAppointments){
			this.create();
		} else {
			function cb_fkt_mc(cbobjCalendar)  {						
				if (cbobjCalendar && cbobjCalendar.data) {
					obj.appointmentList = cbobjCalendar.data;					
				} else if(cbobjCalendar && cbobjCalendar.error) {
					newServerError(cbobjCalendar,4);
				}
				obj.create();
			}
			this.getCalObjMC(oFirstDayDate,oLastDayDate,cb_fkt_mc);					
		}
	},
	
	getCalObjMC: function(oFirstDayDate,oLastDayDate,callback) {
		var start = oFirstDayDate.getTime();
		var end = oLastDayDate.getTime();		
		var sAjaxRequest = AjaxRoot + "/calendar?action=has&session=" + session +"&start=" + start + "&end=" + end;
		calendarMiniJson.get(sAjaxRequest, null, callback);
	},	
	
	update: function() {
		//TODO
		var oFirstDayDate = new Date();
		var oLastDayDate = new Date();		
		this.loaded = false;
		oFirstDayDate.setUTCHours(0);
		oFirstDayDate.setUTCMinutes(0);		
		oFirstDayDate.setUTCSeconds(0);				
		oFirstDayDate.setUTCDate(1);
		oLastDayDate.setUTCHours(0);
		oLastDayDate.setUTCMinutes(0);		
		oLastDayDate.setUTCSeconds(0);			
		oLastDayDate.setUTCDate(1);	

		oFirstDayDate.setUTCFullYear(this.currentYear);
		oLastDayDate.setUTCFullYear(this.currentYear);		

		var aDay = this.oCalendar.aWeeks[0].aDays[0];
		var aDay2 = this.oCalendar.aWeeks[(this.oCalendar.aWeeks.length-1)].aDays[6];		
		
		oFirstDayDate.setUTCMonth(this.currentMonth);		
		oLastDayDate.setUTCMonth(this.currentMonth);			

		if(aDay.nCurrMonth == 0)
			oFirstDayDate.setUTCMonth(oFirstDayDate.getUTCMonth()-1);
		if(aDay2.nCurrMonth == 2)
			oLastDayDate.setUTCMonth(oLastDayDate.getUTCMonth()+1);
			
		oFirstDayDate.setUTCDate(aDay.nDate);
		oLastDayDate.setUTCDate(aDay2.nDate);
		oLastDayDate.setUTCDate(oLastDayDate.getUTCDate()+1);		
		var Self = this;
		function fn_refreshCurrentMiniCal(cbobjCalendar) {
			if (cbobjCalendar && cbobjCalendar.data) {
				Self.appointmentList = cbobjCalendar.data;					
			} else if(cbobjCalendar && cbobjCalendar.error) {
				newServerError(cbobjCalendar);
			}
			Self.refreshView();
		}
		if (this.displayAppointments) {
			this.getCalObjMC(oFirstDayDate,oLastDayDate,fn_refreshCurrentMiniCal);
		}
	},	
	
	refreshView: function() {		
		var nAllDaysCount=0;
		//loop weeks
		for (var indexWeek=0; indexWeek<this.oCalendar.aWeeks.length; indexWeek++){
				var currentWeek = this.oCalendar.aWeeks[indexWeek];
				//loop days
				for (var indexDay=0; indexDay<7; indexDay++) {
					var bAppExist = false;
					if (this.displayAppointments) {
						bAppExist = this.appointmentList[nAllDaysCount];
					}
					var oTD = $2(this.subcontainer.id + 'mc_' + indexWeek + '_' + indexDay);
					oTD.className = removeClass(oTD.className,"font-style-lable");
	 				if(bAppExist) {
	 					oTD.className += " font-style-lable";		 			
	 				}
	 				nAllDaysCount++;
				}
				this.loaded = true;
		}	
	},	
	
	create: function() {
		var oCalminiMain = this.subcontainer;
		oCalminiMain.appendChild(this.getTable());
		this.updateHeaderMini();
	},
	
	getTable: function(oCalObj){
		var Self = this;
		var nAllDaysCount = 0;
		var oTable = newnode("table", {}, { 
			className: "CalMiniMainTable1", 
				cellPadding: 0, cellSpacing: 0, border: 0 });
		this.table = oTable;
		var oTableBody = newnode('tbody');	// IE specific
		var oTRHead = newnode('tr');
		var weekDays = [pgettext("monday", "M"), pgettext("tuesday", "T"),
                        pgettext("wednesday", "W"), pgettext("thursday", "T"),
                        pgettext("friday", "F"), pgettext("saturday", "S"),
                        pgettext("sunday", "S")];
        
        var _nTd = newnode('td', { height:"2em", padding:"0px" }, { className: "cursorPointer" });
        if (this.fnKWAction != null) {
        	 _nTd.appendChild(Self.open_in_calendar);        
        	 _nTd.onclick = function(e) {
	            activeDay=1;
	            activeMonth=Self.currentMonth;
	            activeYear=Self.currentYear;
	            Self.setSelectedByDate(activeYear, activeMonth, activeDay);
                ox.UIController.setModule({module: "calendar", folder:"auto", view:"calendar/calendar/week",force: "module"});
	            
	        };       	
        }
        oTRHead.appendChild(_nTd);
        for (var i=0; i<weekDays.length; i++) {
            var HeadTD = newnode('td', { height:"2em", padding:"0px" }, 0,
                [addTranslated(weekDays[i])]);
			oTRHead.appendChild(HeadTD);
		}
		oTRHead.className = "miniCalendarTRHead dateCalendarFontSize background-color-additional-content font-style-headline";
		oTableBody.appendChild(oTRHead);
		var locCalObj = (oCalObj != undefined) ? oCalObj : this.oCalendar;
		//loop weeks
		for (var indexWeek=0; indexWeek<locCalObj.aWeeks.length; indexWeek++) {
				var oTR = newnode('tr', { border:"0" });
				var currentWeek = locCalObj.aWeeks[indexWeek];
				var oKWTD = newnode('td', 0, { height:"1.5em", padding:"0px", verticalAlign:"middle",
								className:"miniCalendarTDKW background-color-additional-content font-size-footer border-color-default",
								id:'kw_'+currentWeek.nKW });			
				var KWTDText = document.createTextNode(currentWeek.nKW);							
				oKWTD.appendChild(KWTDText);
				if (!this.enable_action || !this.fnKWAction) {
 					oKWTD.className += " cursorReset";		 			
 				}
				
				if (this.fnKWAction != null) {	
					addDOMEvent(oKWTD, "click", this.fnKWAction);
					
				}
				oTR.appendChild(oKWTD);
				addTMPId(oKWTD);
				//loop days
				for (var indexDay=0; indexDay<7; indexDay++) {
					var bAppExist = false;
					if(this.displayAppointments) {
						var bAppExist = this.appointmentList[nAllDaysCount];
					}
					var oTD = newnode('td', { height:"1.5em", padding:"0px" });
					sID = this.subcontainer.id+'mc_' + indexWeek + '_' + indexDay;				
	 				var cDay = currentWeek.aDays[indexDay];	
					var TDText = document.createTextNode(cDay.nDate);			
	 				oTD.appendChild(TDText);
	 				//save id, date  & appointments info in assoc array
					this.miniCalendarAssoc[sID] = new Array(cDay.nDate, cDay.nCurrMonth, bAppExist, currentWeek.nKW);
	 				if (cDay.nCurrMonth==0 || cDay.nCurrMonth==2) {
						oTD.className = "miniCalendarTDNotCurr dateCalendarFontSize font-color-disabled";
	 				} else {
						oTD.className = "miniCalendarTD dateCalendarFontSize";
	 				}
	 				if (bAppExist) {
	 					oTD.className += " font-style-lable";		 			
	 				}
	 				if (!this.enable_action) {
	 					oTD.className += " cursorReset";		 			
	 				}
	 				
	 				var oDateOthMonth = new Date();
	 				oDateOthMonth.setFullYear(this.currentYear);
	 				oDateOthMonth.setDate(cDay.nDate);
	 				oDateOthMonth.setMonth(this.currentMonth);	 
					
					oDateOthMonth.setMonth(oDateOthMonth.getMonth()-1);
 					nLastMonth = oDateOthMonth.getMonth();
 					nLastYear = oDateOthMonth.getFullYear();	 				
 					oDateOthMonth.setMonth(oDateOthMonth.getMonth()+2);	 					
 					nNextMonth = oDateOthMonth.getMonth();
	 				nNextYear = oDateOthMonth.getFullYear();	 				
					if ((cDay.nCurrMonth == 1 && this.currentYear == this.todayYear
	 														 && this.currentMonth == this.todayMonth
	 																	 && this.todayDate == cDay.nDate)
						|| (cDay.nCurrMonth == 0 && nLastYear == this.todayYear
	 													&& nLastMonth == this.todayMonth
	 																	 && this.todayDate == cDay.nDate)
						|| (cDay.nCurrMonth == 2 && nNextYear == this.todayYear
	 													&& nNextMonth == this.todayMonth
	 																	 && this.todayDate == cDay.nDate)) 
					{
		 				oTD.className += " miniCalendarToday todaySelectionBorder";
		 			
		 			}
					if((cDay.nCurrMonth == 1 && this.currentYear == this.selectedYear
	 													&& this.currentMonth == this.selectedMonth
	 																	 && this.selectedDate == cDay.nDate)										
						|| (cDay.nCurrMonth == 0 && nLastYear == this.selectedYear
	 													&& nLastMonth == this.selectedMonth
	 																	 && this.selectedDate == cDay.nDate)
						|| (cDay.nCurrMonth == 2 && nNextYear == this.selectedYear
	 													&& nNextMonth == this.selectedMonth
	 																	 && this.selectedDate == cDay.nDate))
	 				{
	 					oTD.className += ' background-color-PMG-selection-elements';
 						this.selectedID = sID;
	 				}	 				
					oTD.id = sID;
					if (this.actionDBLFN != null) {
						oTD.onselectstart = function() { return false; };
						oTD.style.MozUserSelect = "none";
						oTD.ondblclick = this.actionDBLFN;
					}

					oTD.onclick = this.actionFN;
								
					oTR.appendChild(oTD);
					addTMPId(oTD);
					function fnOver(node) {
						return function(e, dragType, draggedObjects, mouseposition, targetNode) {
							    minicalenable(e,dragType,draggedObjects,mouseposition,targetNode,node);
                                var mynode = e.currentTarget || e.srcElement || false;												
								mynode.className += " dndOver";
							}
					}
					function clearOpenNOdeOver(e, dragType, draggedObjects, mouseposition, OutOpen, dropNode) {
						if (dropNode) {
							dropNode.className = removeClass(dropNode.className,'dndOver');									
						} else if(e) {
							var mynode = e.currentTarget || e.srcElement || false;
							if (mynode) { 
								mynode.className = removeClass(mynode.className,'dndOver'); 
							}
						}
					}
					if (this.dnd_enabled) {
						var tObj = new Object();
						tObj["mail"] = function (event,dragType,draggedObjects,mouseposition,targetNode,dropNode) {
										clearOpenNOdeOver(event,dragType,draggedObjects,mouseposition,null,dropNode);
										openMailToApp(Self.getDateByID(dropNode.id),draggedObjects.currentObjects,"mail");}	
						tObj["contacts"] = function (event,dragType,draggedObjects,mouseposition,targetNode,dropNode) {
										clearOpenNOdeOver(event,dragType,draggedObjects,mouseposition,null,dropNode);
										openMailToApp(Self.getDateByID(dropNode.id),draggedObjects.currentObjects,"contacts");}											
						tObj["calendar"] = function (event,dragType,draggedObjects,mouseposition,targetNode,dropNode) {
							clearOpenNOdeOver(event,dragType,draggedObjects,mouseposition,null,dropNode);
							var collection={};     
							collection.columns = null;
				            collection.objects = [];
				            for (var i in draggedObjects.currentObjects) {
				            	var myObj = draggedObjects.currentObjects[i];
				            	collection.objects.push(
				            			OXCalendarMapping.createKeyFromObject(
					                      { module: "calendar", 
					                        folder_id: myObj.folder || myObj.folder_id, 
					                        id: myObj.id,
					                        recurrence_position: myObj.recurrence_position || 0 }
					                  )
				            	)
				            }
				            OXCache.newRequest(null, "calendar", collection, null,
				                function(daten) {
				                    for (var j in daten.objects) {
				                    	
				                    	var oDate = Self.getDateByID(dropNode.id);
				                    	var myObj = daten.objects[j];
				                    	myObj.start_date = new Date(myObj.start_date);
										myObj.end_date = new Date(myObj.end_date);
										oDate.setUTCHours(myObj.start_date.getUTCHours());
										oDate.setUTCMinutes(myObj.start_date.getUTCMinutes());
										var changes=oDate.getTime()-myObj.start_date.getTime();
										var oDateEnd=new Date(myObj.end_date.getTime()+changes);
										moveAppToNewStart(myObj, oDate, oDateEnd, function () { Self.update(); });
				                    }	
				                },
				                true
				            );
						}										
						registerTarget(oTD, tObj,null,null,fnOver(oTD),fnOver(oTD),clearOpenNOdeOver,true);										
					}
					nAllDaysCount++;
				}
				oTableBody.appendChild(oTR);
				this.loaded = true;
		}
		//display 6 rows in any case
		for(var indexWeek=0; indexWeek< 6; indexWeek++) {
			var oTR = newnode('tr');
			var oTD = newnode('td', { height:"1.5em", padding:"0px" }, { colspan:"8", className:"miniCalendarTDNotCurr dateCalendarFontSize font-color-disabled minicalendar6thline"});			
			oTD.innerHTML = '&#xa0;';
			oTR.appendChild(oTD);
			oTableBody.appendChild(oTR);
		}
		oTable.appendChild(oTableBody);		
		addTMPId(oTable);		
		return oTable;
	},
	
	setSelectedByDate: function(year, month, day) {
		this.selectedDate = day;
		this.selectedMonth = month;		
		this.selectedYear = year;
		this.selectedTime = Date.UTC(year,month,day);
		this.setUnselected(this.selectedID);
		if (this.selectedYear == this.currentYear && this.selectedMonth == this.currentMonth) {
			for (var sId in this.miniCalendarAssoc) {					
				var nCurrMonthFlag = this.miniCalendarAssoc[sId][1];
				var nDay = this.miniCalendarAssoc[sId][0];
 				var oDateOthMonth = new Date();
 				oDateOthMonth.setFullYear(this.currentYear);
 				oDateOthMonth.setDate(nDay);
 				oDateOthMonth.setMonth(this.currentMonth);	 
				
				oDateOthMonth.setMonth(oDateOthMonth.getMonth()-1);
 					nLastMonth = oDateOthMonth.getMonth();
 					nLastYear = oDateOthMonth.getFullYear();	 				
				oDateOthMonth.setMonth(oDateOthMonth.getMonth()+2);	 					
 					nNextMonth = oDateOthMonth.getMonth();
	 				nNextYear = oDateOthMonth.getFullYear();	
				if ((nCurrMonthFlag == 1 && nDay == this.selectedDate
												 && this.currentMonth == this.selectedMonth
												 			&& this.currentYear == this.selectedYear)
						|| (nCurrMonthFlag == 0 && nLastYear == this.selectedYear
	 													&& nLastMonth == this.selectedMonth
	 																	 && nDay == this.selectedDate)												 			
						|| (nCurrMonthFlag == 2 && nNextYear == this.selectedYear
	 													&& nNextMonth == this.selectedMonth
	 																	 && nDay == this.selectedDate)) 																	 
				{
					this.selectedID = sId;
					var markTDSelected = $2(sId);
					if(markTDSelected != undefined)
						markTDSelected.className += " background-color-PMG-selection-elements";
					break;
				}
			}
		} else {
			var oDateLoc = new Date();
			oDateLoc.setFullYear(this.selectedYear);
			oDateLoc.setDate(1);
			oDateLoc.setMonth(this.selectedMonth);
			this.go_to(oDateLoc);
		}
	},
	setToday: function() {
		var todayDate = new Date();
		this.todayDate = todayDate.getDate();
		this.todayMonth = todayDate.getMonth();	
		this.todayYear = todayDate.getFullYear();
		for(var sId in this.miniCalendarAssoc)
		{
			//deselect today selection
			var currDayDate = $2(sId);
			/*
			 * should not happen. however, results in some strange errors if not
			 * set and prevent executing updates within the calender views so we
			 * better check this.
			 */
			if (!currDayDate) {
				return;
			}
			currDayDate.className = removeClass(currDayDate.className,"todaySelectionBorder");
			currDayDate.className = removeClass(currDayDate.className,"miniCalendarToday");			
			
			var nCurrMonthFlag = this.miniCalendarAssoc[sId][1];
			var nDay = this.miniCalendarAssoc[sId][0];
			var oDateOthMonth = new Date();
			oDateOthMonth.setFullYear(this.currentYear);
			oDateOthMonth.setDate(nDay);
			oDateOthMonth.setMonth(this.currentMonth);	 
			
			if(nCurrMonthFlag == 0)
				oDateOthMonth.setMonth(oDateOthMonth.getMonth()-1);
			if(nCurrMonthFlag == 2)
				oDateOthMonth.setMonth(oDateOthMonth.getMonth()+1);
			if(oDateOthMonth.getMonth() == this.todayMonth
					&& oDateOthMonth.getDate() == this.todayDate
						&& oDateOthMonth.getFullYear() == this.todayYear) 
			{
				currDayDate.className += " miniCalendarToday todaySelectionBorder";	
 			} 				 			
		}
	},	
	setSelected: function (sId)
	{
		//deselect
		if(this.selectedID)
			this.setUnselected();
		
		//select
		this.selectedID = sId;
		var oDateOthMonth = new Date();
		oDateOthMonth.setFullYear(this.currentYear);
		oDateOthMonth.setDate(1);	
		oDateOthMonth.setMonth(this.currentMonth);	 	
		var back=1;
		if(this.miniCalendarAssoc[sId][1] == 0)	
		{
			oDateOthMonth.setMonth(oDateOthMonth.getMonth()-1);
			var back=0;
		}
		else if(this.miniCalendarAssoc[sId][1] == 2)	
		{
			oDateOthMonth.setMonth(oDateOthMonth.getMonth()+1);			
			var back=2;			
		}
		oDateOthMonth.setDate(this.miniCalendarAssoc[sId][0]);				
		this.selectedMonth = oDateOthMonth.getMonth();
		this.selectedYear = oDateOthMonth.getFullYear();
		this.selectedDate = oDateOthMonth.getDate();
		
		this.selectedTime = oDateOthMonth.getTime();

		oTD = $2(sId);
		oTD.className += ' background-color-PMG-selection-elements';
		if(back==0)
			this.back();
		if(back==2)
			this.next();			
	},
	getDateByID : function (sId)
	{
		var oDateOthMonth = new Date(null);
		oDateOthMonth.setUTCFullYear(this.currentYear);
		oDateOthMonth.setUTCDate(1);	
		oDateOthMonth.setUTCMonth(this.currentMonth);
		
		if(this.miniCalendarAssoc[sId][1] == 0)	
		{
			oDateOthMonth.setUTCMonth(oDateOthMonth.getUTCMonth()-1);
		}
		else if(this.miniCalendarAssoc[sId][1] == 2)	
		{
			oDateOthMonth.setUTCMonth(oDateOthMonth.getUTCMonth()+1);			
		}		
		oDateOthMonth.setUTCDate(this.miniCalendarAssoc[sId][0]);			
		return oDateOthMonth;		
	},
	setUnselected: function ()
	{
		var oTD = $2(this.selectedID);
		if(!oTD) return;
		sClassName = oTD.className;
		var aSplited = sClassName.split(' ');
		var sDeseletedClassName = '';
		for(var nInd=0;nInd < aSplited.length;nInd++)
		{
			if(aSplited[nInd].length>0 && aSplited[nInd] != "background-color-PMG-selection-elements")
			{
				sDeseletedClassName += ' '+aSplited[nInd];
			}
		}			
		oTD.className = sDeseletedClassName;
	},
	
	updateHeaderMini: function ()
	{
		//var showHeader = _(this.aMonthNames[this.currentMonth]) + ' ' + this.currentYear;
		//this.header.innerHTML = showHeader;	
	}	
}
fileloaded();