/**
 * 
 * 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) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Suphi Basdemir <suphi.basdemir@open-xchange.com>
 * 
 */

var weekStorage;
var allcalendarWeekObjects=new Object();

function openNewAppointmentInWeek(date) {
	calendar_activedate=date;
	calendar_wholeday=false;
	triggerEvent("OX_Before_Create_Calendar");
}

function WeekCalendarTool() {
	this.firstinit=false;
	this.oCalendarTool = new calendarTool(activeMonth,activeYear);
	this.switchedToNext = 0;
	this.oCalendarTool1970 = new calendarTool(1,1970);
	this.calendarwfields = new Array(200, 201, 202, 203, 207, 221, 401, 402, 102, 400, 101, 206, 2, 220, 100);
	//title, startdate, enddate, note, seq(0-4), participants, fulltime(true|false), shownas, tag
	this.calendarWeekTimer = null;
	this.timer = 700;
	this.showallappointments = true;
	this.aAppointmentAssoc = new Object();
	this.divIdCurrentDay = "";
	this.aDateForNewWindow = new Object();
	this.aMonthForNewWindow = new Object();
	this.registeredEvents = new Array();
	this.registeredEventsAdd = new Array();
	this.displayedWeekLinks = new Array();
	this.appendetFirstChilds = new Array();	
}

WeekCalendarTool.prototype = {
	
	init: function(paramYear, paramMonth, paramDay) {
		//fixed text selection bug in IE
		if(!this.firstinit) {
			addDOMEvent($("weekcontainer"), "selectstart", function() { return false; });			
			addDOMEvent($("weekcontainer"), "drag" , function() { return false; });
			addDOMEvent($("weekcontainer"), "click", function (e) {
				if (calendarSelection.count != 0) {
					triggerEvent("Selected", []);
					calendarSelection.reset();
					selectedAppointment = null;
					selectAppointmentWeekView();					
				}
			});
			this.firstinit=true;
			var hover=new Hover($("weekcontainer"),OXAppointmentHover.getContent().node);
			calendarhovers["week"]=hover;
			
			hover.setSize(OXAppointmentHover.contentobject.node);
			hover.getTarget = function (node) {
                try {
                    while (node) {
                        if (node.oxcalobj) return node.parentNode ? node : null;
                        node = node.parentNode;
                    }
                } catch (e) { /*see default implementation*/ }
            };
			hover.onShow = function (node) {
				OXAppointmentHover.actualHover=this;
				var splitid=node.oxcalobj.split("-");
				OXAppointmentHover.refillContent(splitid[1],splitid[0],splitid[2]);	
			}
		}
		
		if (configGetKey("gui.effects.hover.calendar") && calendarhovers["week"]) {
			calendarhovers["week"].enable();
		}
		
		for (var t = 1; t< 8; t++) {
			$("imageList"+t).style.display = "none";
		}
		
		if (paramYear && (paramMonth != undefined) && paramDay) {			
			activeYear = paramYear;
			activeMonth = paramMonth;
			activeDay = paramDay;
			this.oDateLoc = new Date(Date.UTC(paramYear, paramMonth, paramDay, 0, 0, 0));
		} else {
			this.oDateLoc = new Date(Date.UTC(activeYear, activeMonth, activeDay, 0, 0, 0));
		}
		
		this.setKW();
		this.setDays();
		
		if(calendar_getAllFoldersAttribute()) {
			this.showallappointments=true;
			$("allAppointmentWeekView").checked = true;
		} else { 
			this.showallappointments=false;
			$("allAppointmentWeekView").checked = false;
		}
			
		this.getStorageCache();
		this.getData = 0;		
	},
	setKW: function() {
		this.currentKW = this.oCalendarTool.getKW(this.oDateLoc.getUTCFullYear(),
															this.oDateLoc.getUTCMonth(),
																	this.oDateLoc.getUTCDate());
		
		
		this.testToday();
	},
	testToday: function() {
		if(this.divIdCurrentDay != "") {
			/* reset background-color */
			$(this.divIdCurrentDay).className = "weekViewDivContent font-color-default workTimeBackground border-color-design";
		}
		this.oDateAct = new Date();
		this.nKW = this.oCalendarTool.getKW(this.oDateAct.getUTCFullYear(),this.oDateAct.getUTCMonth(),this.oDateAct.getDate());
		if(this.currentKW == this.nKW && activeYear == this.oDateAct.getUTCFullYear()) {
			this.divIdCurrentDay = 'weekDayContent'+this.oDateAct.getDay();
			$(this.divIdCurrentDay).className = "weekViewDivContent background-color-content todaySelectionBorder";
		}
		
	},
	openNewCalendar: function(evt,clicked) {
		var DOMTarget = (evt.target) ? evt.target : evt.srcElement;
		var oDate = new Date();
		activeDay = oDate.getUTCDate();
		activeMonth = oDate.getUTCMonth();
		activeYear = oDate.getUTCFullYear();
		if (clicked == "dblclick") {
			triggerEvent('OX_Before_Create_Calendar');
		} else if (clicked == "click") {
			window.setTimeout(function() {
				menuswitchCalendarTimerange("day")
			}, 20);
		}
	},
	setDays: function() {
		this.oMonday = new Date(getDayInSameWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0)), weekStart) * 864e5);
		var Self = this;
		
		function drawpreviewDragandDrop(evt,type,object) {
		    stopEvent(evt);
			var subObject = object;
			if(object && object.currentObjects && object.currentObjects.length>0) {
					subObject = object.currentObjects[0]; 
			}			
			var DOMTarget = (evt.target)?evt.target:evt.srcElement;	
			DOMTarget.style.cursor = "move";
			if(!$2("dnd_div_")) {				
				var iconNode = Self.getAppointmentDiv(subObject);					
				iconNode.id = "dnd_div_";
				iconNode.style.left = (evt.clientX + iconOffset) + "px";
				iconNode.style.top = (evt.clientY + iconOffset)+ "px";	
				body.appendChild(iconNode);
				addTMPId(iconNode);
				iconNode.style.width = "320px";
				iconNode.style.position = "absolute";				
			} else {
				var iconNode = $2("dnd_div_");
				iconNode.style.left = (evt.clientX + iconOffset) + "px";
				iconNode.style.top = (evt.clientY + iconOffset)+ "px";	
			}
			var sId = DOMTarget.id;
			if(sId.slice(0,14) != "weekDayContent")
				return;
			DOMTarget.className = removeClass(DOMTarget.className,"dndSelectionCalendarBG");			
			DOMTarget.className += " dndSelectionCalendarBG";
		}
		
		function removeDDPreviewDivs(evt,type,object) {
			var DOMTarget = (evt.currentTarget)?evt.currentTarget:evt.srcElement;
			var DOMTarget2 = (evt.target)?evt.target:evt.srcElement;
			DOMTarget2.style.cursor = "default";
			DOMTarget.className = removeClass(DOMTarget.className,"dndSelectionCalendarBG");
			if($2("dnd_div_")) {
				body.removeChild($2("dnd_div_"));
				removeTMPId($2("dnd_div_"));
			}
		}					

		function dropCallBack(evt,dragType,object,mousepos,targetNode,dropNode){
			var subObject = object;
			if (object && object.currentObjects && object.currentObjects.length > 0) {
				subObject = object.currentObjects[0]; 
			}						
			var DOMTarget = targetNode;//(evt.target)?evt.target:evt.srcElement;
			var sId = DOMTarget.id;	

			var nNum = (parseInt(sId.slice(sId.length-1, sId.length)) == 0)
			     ? 7 : parseInt(sId.slice(sId.length-1, sId.length));

			var sKey = "weekviewDay" + nNum;
			if (Self.aDateForNewWindow[sKey] == undefined
			    || Self.aMonthForNewWindow[sKey] == undefined) return;

			DOMTarget.className = removeClass(DOMTarget.className,"dndSelectionCalendarBG");			

			var oDate = new Date();
			oDate.setUTCHours(0);		
			oDate.setUTCMinutes(0);					
			oDate.setUTCSeconds(0);								
			oDate.setUTCDate(1);		
			oDate.setUTCFullYear(activeYear);				
			oDate.setUTCMonth((Self.aMonthForNewWindow[sKey]-1));				
			oDate.setUTCDate(Self.aDateForNewWindow[sKey]);			
			var start_date = new Date(subObject.start_date);
			var end_date = new Date(subObject.end_date);			
			oDate.setUTCHours(start_date.getUTCHours());
			oDate.setUTCMinutes(start_date.getUTCMinutes());
			var changes=oDate.getTime()-start_date.getTime();
			var oDateEnd=new Date(end_date.getTime()+changes);
			
			// drop only allowed if destination date != current date	
			if (formatDate(start_date, "date") != formatDate(oDate, "date"))
			     moveAppToNewStart(subObject,oDate,oDateEnd);
			     
			if($2("dnd_div_")) {
				body.removeChild($2("dnd_div_"));
				removeTMPId($2("dnd_div_"));
			}
			var DOMTarget2 = (evt.target)?evt.target:evt.srcElement;
			DOMTarget2.style.cursor = "default";						
		}
		
		for (var inWeekDay=0; inWeekDay<7; inWeekDay++) {
			(function (inWeekDayIndex) {
				
				if (inWeekDayIndex == 6) {
					var dayContentId = 'weekDayContent0';
				} else {
					var dayContentId = 'weekDayContent'+(inWeekDayIndex +1);
				}
				
				var sId = 'weekviewDay'+(inWeekDayIndex+1);			
				var nCurrHeader  = $(sId);
				var nCurrContent  = $(dayContentId);				
				
				if (Self.registeredEvents["dbl_1_" + inWeekDayIndex]) {
					removeDOMEvent(nCurrContent,'dblclick', Self.registeredEvents["dbl_1_" + inWeekDayIndex]);
				}
				if (Self.registeredEvents["dbl_2_" + inWeekDayIndex]) {
					removeDOMEvent(nCurrHeader,'dblclick', Self.registeredEvents["dbl_2_" + inWeekDayIndex]);
				}				
				
				var nDisplayMonth = Self.oMonday.getUTCMonth()+1;
				Self.aMonthForNewWindow[sId] = nDisplayMonth;
				
				if (nDisplayMonth < 10)	nDisplayMonth = '0' + nDisplayMonth;
				var nDisplayDate = Self.oMonday.getUTCDate();
				Self.aDateForNewWindow[sId] = nDisplayDate;
				
				if(nDisplayDate < 10) nDisplayDate = '0' + nDisplayDate;		

				var date=new Date();
				date.setUTCDate(1);
				date.setUTCFullYear(Self.oMonday.getUTCFullYear());
				date.setUTCMonth(Self.oMonday.getUTCMonth());
				date.setUTCDate(Self.oMonday.getUTCDate());
				date.setUTCHours(configGetKey("gui.calendar.starttime") || 8);
				
				function openNewAppointmentInWeek(e) {
					calendar_activedate=date;
					calendar_activedate.setUTCMinutes(0);					
					calendar_wholeday=false;
					triggerEvent("OX_Before_Create_Calendar");					
				}
				
				function openNewWholeAppointmentInWeek(e) {
					var date2=date;
					date2.setUTCHours(0);
					date2.setUTCMinutes(0);
					calendar_activedate=date2;
					calendar_wholeday=true;
					triggerEvent("OX_Before_Create_Calendar");
				}
				Self.registeredEvents["dbl_1_" + inWeekDayIndex] = openNewAppointmentInWeek;
				Self.registeredEvents["dbl_2_" + inWeekDayIndex] = openNewWholeAppointmentInWeek;
				
				addDOMEvent(nCurrContent, 'dblclick', openNewAppointmentInWeek);	
				addDOMEvent(nCurrHeader, 'dblclick', openNewWholeAppointmentInWeek);
				
				Self.yearUTC=Self.oMonday.getUTCFullYear();
				nCurrHeader.parentNode.className += isToday(Self.oMonday) ? " todayBackground" : "";

				nCurrHeader.firstChild.nodeValue = formatDate(Self.oMonday,"dateday");
				Self.oMonday.setUTCDate(Self.oMonday.getUTCDate()+1);
				
				registerTarget(nCurrContent,{calendar:dropCallBack},null,null,
						drawpreviewDragandDrop,	//drawpreviewDragandDrop
						drawpreviewDragandDrop,	//drawreviewDragandDrop
						removeDDPreviewDivs );//removeDDPreviewDivs				
			})(inWeekDay)
		}
		$('weekviewheader').firstChild.nodeValue = _("CW") + " " + 
				formatDateTime("w yyyy", new Date(getKeyDayOfWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay))) * 864e5));
		
	},
	goToNextWeek: function(nDirection) {		
		this.clearContentFields();
		this.getData = 1;
		this.nDirection = nDirection;
		this.oDateLoc.setUTCDate(this.oDateLoc.getUTCDate()+(nDirection*7));	
		activeMonth = this.oDateLoc.getUTCMonth();
		activeYear = this.oDateLoc.getUTCFullYear();		
		activeDay = this.oDateLoc.getUTCDate();	
		this.setKW();
		this.setDays();
		var Self = this;
		
		Self.calendarWeekTimer  = window.setTimeout(
									function() 	{
											Self.goToNextWeek(Self.nDirection); 
											Self.switchedToNext++;
									}, Self.timer);
		if (this.switchedToNext>4) {
			Self.timer = 400;
		} else {
			Self.timer = 700;
		}
		
		if (oMiniCalendar) oMiniCalendar.setSelectedByDate(activeYear, activeMonth, activeDay);
	},
	clearTimer: function() {
		this.switchedToNext = 0;
		window.clearTimeout(this.calendarWeekTimer);
		if(this.getData >0) {
			this.getData = 0;
			this.getStorageCache();
		}		
	}, 
	clearContentFields: function() {
		for (var t = 1; t< 8; t++)
		 		$("imageList"+t).style.display = "none";
		allcalendarWeekObjects = {};
		this.weekAppointments = new Array();
		for(var i=0; i<7;i++) {
			removeChildNodes($('weekDayContent'+i));
		}
	},
	updateView: function() {
		this.clearContentFields();
		this.iterateStorage();
		lastUpdateOfCalendarTimestamp = storageCache.current.timestamp;
		calendar_HeaderUpdate(weekStorage.ids.length);
	},
	showAllAppointments: function(mybool) {
		this.showallappointments=mybool;
		configSetKey("gui.calendar.allfolders",mybool)
		this.getStorageCache();
	},
	getStorageCache: function() {
		if (weekStorage) {
            weekStorage.events.unregister("Changed", function() {
                Self.updateView();
            });
        }
		this.clearContentFields();
		var start = new Date(getDayInSameWeek(this.oDateLoc, weekStart) * 864e5);		
		var end = new Date(start.getTime());
		end.setUTCDate(start.getUTCDate()+7);
		this.starttime=start.getTime();
		var endtime=end.getTime();
		this.endtime = endtime;
		var Self = this;
		Self.params=new Object();
		Self.params.action="all";
		Self.params.start=Self.starttime;
		Self.params.end=endtime;		
		Self.params.columns="1,20,207";
		if(!Self.showallappointments) {
			Self.params.folder= activefolder;
		}
		Self.params.showPrivate = true;
		storageCache.get(AjaxRoot + "/calendar",
		 Self.params,
		 function(storage) {
		 	Self.weekAppointments = new Array()
		 	for (var t = 0; t< Self.displayedWeekLinks.length; t++)
		 		Self.displayedWeekLinks[t].style.display = "none";
		 		
		 		
		 	storageCache.current = storage;		 	
			calendarSelection.setStorage(storage);
		 	storageCache.update();
		 	Self.iterateStorage(storage);
			lastUpdateOfCalendarTimestamp = storage.timestamp;
		 },
		 Self.calendarwfields.toString(),
		 true,
		 function(x) { return x.folder + "." + x.id + "." + x.recurrence_position; } ,
		 function(x) {
		     return { id: x[0], folder: x[1], recurrence_position: x[2] || 0 };
	     }
		);
	},
	iterateStorage: function(storage) {		
		var Self = this;
		Self.displayedWeekLinks = [];
		this.appendetFirstChilds = [];
		if (storage) {
			weekStorage = storage;
			storage.events.register("Changed", function() {
				Self.updateView();
			});
		}
		weekStorage.newIterate(weekStorage.ids, emptyFunction, function(x,y) {
			Self.buildAppointments(x,y);
		},function(){
			Self.sortAppointments();
		});
	}, 
	buildAppointments: function(index, object) {
		this.weekAppointments[index] = object;
		object["indxxx"]  = index;
	},
	sortAppointments: function() {
		this.weekAppointments.sort(
			function(a, b){
				return (a[9] || a[4] < b[4] ? -1 : 1); 
			}
		);
		for(var i=0; i<this.weekAppointments.length;i++) {
			this.generateCalendarObjects(this.weekAppointments[i]["indxxx"],this.weekAppointments[i]);
		}
	},
	getAppointmentDiv:function (object) {
		var appointmentDate = new Date(object.start_date);
		var appointmentDateEnd = new Date(object.end_date);
		if(!object.title) {
			object.title="";
		}
		var textToView = formatDate(appointmentDate, "time") + " - " + formatDate(appointmentDateEnd, "time") + "  " + object.title;
		var shownDiv = getShownDiv(object.shown_as);
		
		var divIconParticipant = newnode("div", {},{ className: "showAppointmentSeqWeek"});
		if(object.participants && object.participants.length > 1) {
			var imageGroupFlag=document.createElement("img");
			imageGroupFlag.setAttribute("src",getFullImgSrc("img/calendar/group.gif"));
			divIconParticipant.appendChild(imageGroupFlag);
		}
		
		var divIconPrivate = newnode("div", {},{ className: "showAppointmentSeqWeek"});
		if(object.private_flag) {
			var imagePrivatFlag=document.createElement("img");
			imagePrivatFlag.setAttribute("src",getFullImgSrc("img/private_flag.gif"));
			divIconPrivate.appendChild(imagePrivatFlag);
		}
		
		var divIconTag = newnode("div", {}, { className: "showAppointmentSeqWeek"});
		if(object.color_label && object.color_label > 0) {
			var imageColorLabel=document.createElement("img");
			imageColorLabel.setAttribute("src",getFullImgSrc("img/menu/tag_" + object.color_label + ".gif"));
			divIconTag.appendChild(imageColorLabel);
		}		
		
		var textDiv;
		shownDiv.appendChild(document.createTextNode(" "));
		var datDIV = newnode('div');
		if (object.full_time) {
			datDIV.className = 'textFullTimeWeek wholeDayBackground border-color-design borderDefault';
		} else {
			datDIV.className = 'appInWeekView borderDefault border-color-design';
		}
		textDiv = newnode('div');
		textDiv.className = "showAppointmentTextWeek mozSelected";
		
		textDiv.appendChild(document.createTextNode(textToView));
		datDIV.appendChild(shownDiv);	
		datDIV.appendChild(textDiv);
		
		if (divIconParticipant.firstChild) datDIV.appendChild(divIconParticipant);
		if (divIconPrivate.firstChild) datDIV.appendChild(divIconPrivate);
		if (divIconTag.firstChild) datDIV.appendChild(divIconTag);
		
		if (object.recurrence_type > 0) {
			var image=document.createElement("img");
			image.setAttribute("src",getFullImgSrc("img/calendar/calendar_series.gif"));
			var seqDiv = newnode('div', {}, { className: "showAppointmentSeqWeek"});
			seqDiv.className = "showAppointmentSeqWeek";	
			seqDiv.appendChild(image);
			datDIV.appendChild(seqDiv);	
		}
		
		return datDIV;						
	},
	
	generateCalendarObjects: function(index, object) {
		this.object = object;
		this.object.index = index;
		
		// consolidate users and participants (field 220 and 221)
        for (var i in object[16]) {
            var a1 = object[16][i];
            for (var ia in object[8]) {
                if (object[8][ia].id == a1.id) {
                    a1.confirmation = object[8][ia].confirmation;
                    if (object[8][ia].confirmmessage) a1.confirmmessage = object[8][ia].confirmmessage;
                    break;
                }
            }
        }
		
		var id = this.object[0];
		var folder = this.object[1];
		var recurrencePos = this.object[2] || 0;	
		var title = this.object[3];
		var start_date = this.object[4];
		var end_date = this.object[5];
		var note = this.object[6];
		var recurrenceType = this.object[7];
		var isFullTime = this.object[9];
		var shownAs = this.object[10];
		var colorLabel = this.object[11];
		var location = this.object[12];
		var privateFlag = this.object[13];
		var recurrenceID = this.object[14];
		var createdBy = this.object[15];
		var participants = this.object[16];
		var categories = this.object[17];
		var owner = activeFolderOwner;
		var oneday=1000*60*60*24;
		
		var isPrivateShared = (owner !== configGetKey('identifier') && privateFlag === true);
				
		allcalendarWeekObjects[ folder + "-" + id + "-" + recurrencePos ] = this.object;
		
		var selectedAppointmentWeek = { 
			id: id, folder: folder, recurrence_position: recurrencePos, 
			recurrence_id: recurrenceID, created_by: createdBy, 
			participants: participants
		};
		
		var	appObject = {
				id: this.object[0],
				folder: this.object[1], 
			    folder_id: this.object[1],
			    recurrence_id: this.object[14],
			    recurrence_position: (this.object[2] || 0),
			    recurrence_type: this.object[7]
		};
		
		// app start date before week start?
		if (start_date < this.starttime) {
			start_date = this.starttime;
		}
		
		// app end date after week end?
		if (end_date > this.endtime) {
			end_date = this.endtime-1;
		}
				
		/******* INIT NODE TEMPLATE *******/
		
		var divIconParticipant = newnode("div", {},{ className: "showAppointmentSeqWeek"});
		if (participants && participants.length > 1) {
			var imageGroupFlag=document.createElement("img");
			imageGroupFlag.setAttribute("src",getFullImgSrc("img/calendar/group.gif"));
			divIconParticipant.appendChild(imageGroupFlag);
		}
		
		var divIconPrivate = newnode("div", {},{ className: "showAppointmentSeqWeek"});
		if (privateFlag) {
			var imagePrivatFlag=document.createElement("img");
			imagePrivatFlag.setAttribute("src",getFullImgSrc("img/private_flag.gif"));
			divIconPrivate.appendChild(imagePrivatFlag);
		}
		
		var divIconTag = newnode("div", {}, { className: "showAppointmentSeqWeek"});
		if (colorLabel && colorLabel > 0) {
			var imageColorLabel=document.createElement("img");
			imageColorLabel.setAttribute("src",getFullImgSrc("img/menu/tag_" + colorLabel + ".gif"));
			divIconTag.appendChild(imageColorLabel);
		}
		
		var appNode = newnode("div");
		
		switch (shownAs) {
			case 1:
				appNode.className = "appointmentRESERVED";
				break;
			case 2:
				appNode.className = "appointmentTEMPORARY";
				break;
			case 3:
				appNode.className = "appointmentABSENT";
				break;
			case 4:
				appNode.className = "appointmentFREE";
				break;
			default:
				appNode.className = "appointmentNONE";
		}
		appNode.className += " showAppointmentShownWeek";

		appNode.appendChild(document.createTextNode(" "));
		var cName = "appInWeekView border-color-design borderDefault";
		var backColor = "";
		if (isFullTime) {
			cName = "textFullTimeWeek border-color-design borderDefault";
			backColor = "wholeDayBackground";
		}
		
		// setting background color depending on categories, if set
		if (categories) {
			// getting the first color out of the categories list
			var cat = ox.categories.getFirstMatch(categories);
			if (cat.color != 0) {
				backColor = "colorLabel" + cat.color;
			}
		}
		cName += " " + backColor;
		
		var contentDiv = newnode("div", 0, { className: cName });
		if (selectedAppointmentWeekView == divAppId) {
			contentDiv.className = removeClass(contentDiv.className,"borderDefault");
			contentDiv.className += ' selectedAppMonth border-color-selection-elements';
		}

		var textDiv = newnode("div");
		textDiv.className = "showAppointmentTextWeek";
		var textToView = title || "";
		if (location) {
			textToView += " - " + location;
		}
		
		// setting confirmation styles
		if (participants.length) {
			for (var i in participants) {
				if (participants[i].id == owner) {
					switch(participants[i].confirmation) {
						case 0:
							datDIV.style.opacity = ".6";
							textDiv.style.fontStyle = "italic";
							textToView = "(" + _("waiting") + ")";
							break;
						case 2:
							textDiv.style.textDecoration = "line-through";
							break;
						case 3:											
							textDiv.style.fontStyle = "italic";
							textToView = "(" + _("tentative") + ")";
							break;
					}
				}
			}
		}
		textDiv.appendChild(document.createTextNode(textToView));
		contentDiv.appendChild(appNode);	
		contentDiv.appendChild(textDiv);
		
		if (divIconParticipant.firstChild) {
			contentDiv.appendChild(divIconParticipant);
		}
		
        if (divIconPrivate.firstChild) {
        	contentDiv.appendChild(divIconPrivate);
        }
        
        if (divIconTag.firstChild) {
        	contentDiv.appendChild(divIconTag);
        }
		
		if (recurrencePos > 0 && recurrenceID == id) {
			var image = document.createElement("img");
			image.setAttribute("src",getFullImgSrc("img/calendar/calendar_series.gif"));
			var seqDiv = newnode('div');
			seqDiv.className = "showAppointmentSeqWeek";	
			seqDiv.appendChild(image);
			contentDiv.appendChild(seqDiv);	
		}
		
		function disabled(e) {
			var iconNode=$2("cww_node_dd");
			if (iconNode == undefined) {
				iconNode = newnode("img", 
				        { position:"absolute", left:(e.clientX + iconOffset) + "px", 
				          top:(e.clientY + iconOffset) + "px" },
			            { src: getFullImgSrc("img/dnd_disabled.gif"), alt: "" });
				iconNode.id="cww_node_dd";
				body.appendChild(iconNode);
				addTMPId(iconNode);
			}
			iconNode.style.left = (e.clientX + iconOffset) + "px";
			iconNode.style.top = (e.clientY + iconOffset)+ "px";
			stopEvent(e);
			return false;
		}
		
		function disabledremove(e,targetNode) {
			if ($2("cww_node_dd")) {
				$2("cww_node_dd").parentNode.removeChild($2("cww_node_dd"));
			}
		}
						
		// fixed bug with auto selection													
		if (calendarSelection) {
			calendarSelection.reset();
		}
		
		// calculating appointment duration in days
		var appDuration = Math.ceil(end_date / 864e5) - Math.floor(start_date / 864e5);
		
		var timeA = formatDate(new Date(Date.UTC(1970,1,1,0,0,0)), "time");
		var timeB = formatDate(new Date(Date.UTC(1970,1,1,23,59,59)), "time");	
		
		// iterate through days and draw appointments
		for (var ia=1; ia <= appDuration; ia++) {
			var datDIV = contentDiv.cloneNode(true);
			
			var textNode = datDIV.getElementsByTagName("div")[1];
			var appointmentDate = new Date(start_date);
			var appointmentDateEnd = new Date(end_date);
			var timeWeekpart1 = formatDate(appointmentDate, "time");
			var timeWeekpart2 = formatDate(appointmentDateEnd, "time");			
			var textToView = timeWeekpart1 + " - " + timeWeekpart2 ;
			
			if (appDuration > 1) {				
				if (ia == 1) {	
					textToView = timeWeekpart1 + " - " + timeB;			
				} else if (ia == appDuration) {
					textToView = timeA + " - " + timeWeekpart2;
				} else {
					textToView = timeA + " - " + timeB;	
				}
			}			
			
			if (isFullTime) {
				textToView = title; 
			} else {
				textToView = textToView + "  " + textNode.firstChild.nodeValue;
			}
			textNode.firstChild.data = textToView;
						
			var appId = 'appInWeekView' + folder + "_" + id + "_" + recurrencePos;
			var divAppId = appId + "-" + ia;
			
			var divId = "weekDayContent" + appointmentDate.getUTCDay();
			this.aAppointmentAssoc[appId] = this.object;
			
			// additional clean-up? hack to fix bug #11406
			if ($2(divAppId) && $2(divAppId).parentNode) {
				$2(divAppId).parentNode.removeChild($2(divAppId));
			}		
			
			datDIV.id = divAppId;
			
			var oInplEdit = new inplaceEdit(textNode, title, 
	                 function (sStr, oObj) {
	                 	editAppointment(appObject, {title: sStr });
					});
			
			if (isPrivateShared == false) {
				registerSource(datDIV, "calendar", function () {
					     	objMoveCopy.begin("calendar",
					     	[ new CalendarWorkWeekObject(
					     	       object[0], object[1], object[2], object[14], object[15], object[3], object[4], 
					     	       object[5], null, object[7], null, object[9], object[10],
					     	       null,null,null)
					     	]);
						    return objMoveCopy;
						}, null,null, calendardefaultdisabled, defaultdisabledremove);
				addDOMEvent(datDIV, "click", (function (divAppId, oInplEdit) {
					return function(e) {
						var SelObj = calendarSelection.getID();
						if (SelObj && SelObj.id == appObject.id &&
									SelObj.folder == appObject.folder_id &&
											SelObj.recurrence_position == appObject.recurrence_position &&
												selectedAppointmentWeekView == divAppId) {
							if (window.event) {
								e = window.event;
							}
							oInplEdit.on();
						} else {
							setSelectionWeekView(selectedAppointmentWeek);
							selectAppointmentWeekView(divAppId, (isFullTime ? 2 : 1));
						}
						stopEvent(e);
					}
				})(appId, oInplEdit));
									
		        addDOMEvent(datDIV, "contextmenu", (function(divAppId) {
		        		return function(e) {  
			        		stopEvent(e);
			        		setSelectionWeekView(selectedAppointmentWeek);
							selectAppointmentWeekView(divAppId, (isFullTime ? 2 : 1));
			            	globalContextMenus.calendar.display(e.clientX, e.clientY, calendarSelection);
			        	}
		        })(appId));
		        
				addDOMEvent(datDIV, "dblclick", (function(divAppId) {
						return function(e) {
							setActivatedWeekView(selectedAppointmentWeek, e);
							selectAppointmentWeekView(divAppId, (isFullTime ? 2 : 1));
						}
				})(appId)); 
				
				datDIV.oxcalobj = folder + "-" + id + "-" + recurrencePos;
			} else {
				// is a private app in shared folder, so default cursor
				datDIV.style.cursor = "default";
			}

			$(divId).appendChild(datDIV);
			addTMPId(datDIV);
			
			// switch start date to next date
			start_date += oneday;
		}
	}
}

function setSelectionWeekView(selectedAppointmentWeek) {
	selectedAppointment = selectedAppointmentWeek;
	var arrId = new Array();
	arrId.push(selectedAppointment);
	var arrayIndex = selectedAppointmentWeek.folder + "-" + selectedAppointmentWeek.id + "-" + selectedAppointmentWeek.recurrence_position;
	calendarSelection.click(allcalendarWeekObjects[arrayIndex].index);
	triggerEvent("Selected", arrId);
}

function setActivatedWeekView(selectedAppointmentWeek, evt) {
	selectedAppointment = selectedAppointmentWeek;
	openAppointmentPopup(evt);
}

var selectedAppointmentWeekView = "";
function selectAppointmentWeekView(divAppId, app) {
	// remove any selection first
	if (selectedAppointmentWeekView) {
		for (var i=0; i<=7; i++) {
			var myDiv = $2(selectedAppointmentWeekView + "-" + i);
			if (myDiv) {
				var cname = myDiv.className;
				cname = removeClass(cname, "selectedAppMonth");
				cname = removeClass(cname, "border-color-selection-elements");
				myDiv.className = trimStr(cname + " borderDefault");
			}
		}
	}
	
	// reselect required divs
	for (var i=0; i<=7; i++) {
		var myDiv = $2(divAppId + "-" + i);
		if (myDiv) {
			var cname = myDiv.className;
			cname = removeClass(cname, "borderDefault");
			myDiv.className = trimStr(cname + " selectedAppMonth border-color-selection-elements");
		}
	}
	
	if (divAppId) {
		selectedAppointmentWeekView = divAppId;
	}
}

var objWeekCalendarTool = new WeekCalendarTool();
fileloaded();