/**
 * 
 * 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 Jan Finsel <jan.finsel@open-xchange.com>
 * 
 */
/* IE FIX */
register("Loaded", function () {
	addDOMEvent($("calendarWorkweek"), "click" ,function(e) {
		if (calendarSelection.count != 0) {
			cwwchangeSelected();
			cwwchangeSelectedFull();
			calendarSelection.reset();
			selectedAppointment = null;
			triggerEvent("Selected",[]);
		}
	});
});

register("OX_Configuration_Changed", function () {
	if (calendarinittemplates) {
        calendarinittemplates=false;
        createTemplatesWW(getWWInterval(), getWWStartTime(), getWWEndTime());
    }
});

var maxappointmentsperday=3;
var cwwdaysinweek = 5;
var startofweek=0;
var cww_oldvalues=new Object();

function setDaysInWeek(days,start) {
	cwwdaysinweek = days;
	startofweek=start;
	calendarinittemplates=false;
	showCalendarWorkweek();
}

var calendar_activedate;
var calendar_wholeday;
register("_IE_resize_complete",cwwwresizeHeader);

/* Enable/Disable Calendar Workweek Functions */
function cwwenable() {
	resizeEvents.register("Resized",cwwwresizeHeader);
}
function cwwdisable() {
	resizeEvents.unregister("Resized",cwwwresizeHeader);
}

var allcalendarobjects=new Object();
var wwhovers=new Object();
function default_calendar_workweek_create_object(module,folder) {
	
	if(module=="calendar")
	{
		if(!calendar_activedate) {
//			var myinterval=configGetKey("gui.calendar.interval");
			var myinterval=15;
			var d=new Date();			
			d.setUTCDate(1);
			d.setUTCMonth(activeMonth);
			d.setUTCFullYear(activeYear);
			d.setUTCDate(activeDay);
			d.setUTCHours(d.getHours());
			var mymin=d.getUTCMinutes();
			if(mymin % myinterval) {
				mymin=mymin - (mymin % myinterval)+ myinterval;
			}
			d.setUTCMinutes(mymin);
			calendar_createNewAppointment(d,folder,false);	
		} else {
			calendar_createNewAppointment(calendar_activedate,folder,calendar_wholeday);
		}
	}
	calendar_activedate=null;
	calendar_wholeday=null;
}
function CalendarWorkWeekObject(id,folderid,recurrence_position,recurrence_id,created_by,title,start_date,end_date,note,recurrence_type,participants,full_time,shown_as,color_label,location,private_flag,interval,categories,users)
{
	this.index;
	this.selected=false;
	this.id=id;
	this.folder_id=folderid;
	this.title=title;
	this.start_date=new Date(start_date);
	this.end_date=new Date(end_date);
	this.note=note;
	this.recurrence_type=recurrence_type;
	this.recurrence_position=recurrence_position;
	this.recurrence_id=recurrence_id;
	this.created_by=created_by;
	this.location=location;
	this.participants=participants;
	this.full_time=full_time;				
	this.shown_as=shown_as;
	this.color_label=color_label;
	this.private_flag=private_flag;
	this.interval=interval;
	this.categories=categories;
	this.divs=new Object();
	// this must really be subject to a total rebuild
	// adding just another property
	this.users = users;
}
CalendarWorkWeekObject.prototype = {
	addDiv : function (id,node) {
		this.divs[id]=node;
	}
}
function MatrixObject(folderid,id,recurrence_id,div_id,startpoint,endpoint) {
	this.folderid=folderid;
	this.id=id;
	this.element_id=div_id;
	this.recurrenceid=recurrence_id;
	this.startpoint = startpoint || 0;
	this.endpoint = endpoint || 0;
}

var globalinterval = 0;
var globalintervalcounts=0;
var calendarwwfields = new Array(200, 201, 202, 203, 209, 221, 401, 402, 102, 400, 101, 220, 215, 100);
var calendarinittemplates=false;
var firstenter=false;
var cwwstorage;
var wwline=20;

var cwwdays;
var cwwdaysfull;
var cwwactualday;
var showallappointments=true;
function cww_onShowAllAppointmentsChanged(mybool) {
	showallappointments=mybool;
	configSetKey("gui.calendar.allfolders",mybool); 
	var oDateLoc = new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0));	
	updateWWView(oDateLoc);
}

function showCalendarWorkweek() {	
	if(!firstenter) {
		var callbacks=new Object();
		callbacks["CALENDAR_BOTTOM"]=function(event,dragType,data,mouseposition,targetNode) { cww_saveAppointment(data,event,"CALENDAR_BOTTOM");  }
		callbacks["calendar"]=function(event,dragType,data,mouseposition,targetNode) { cww_saveAppointment(data.currentObjects[0],event,"calendar",false);  }
		callbacks["CALENDAR_TOP"]=function(event,dragType,data,mouseposition,targetNode) { cww_saveAppointment(data,event,"CALENDAR_TOP");  }
		callbacks["CALENDAR_NEW"]=function(event,dragType,data,mouseposition,targetNode) { cww_createAppointment(data,event,"CALENDAR_NEW",mouseposition,createPreviewNewAppointmentWW) } 
		registerTarget($("cwwtimecontentall"),callbacks,null,null,
		function(event,type,object,mouseposition) { 
			if(type=="CALENDAR_NEW") {
				drawpreviewnewAppointment(event,type,object,mouseposition)
			} else if (type == "calendar") {
				if(object && object.currentObjects && object.currentObjects.length>0) {
					drawpreviewDragandDrop(event,type,object.currentObjects[0]); 
				}
			}
			else {
				drawpreviewDragandDrop(event,type,object); 
			}
		},
		function(event,type,object,mouseposition) { 
			if(type=="CALENDAR_NEW") {
				drawpreviewnewAppointment(event,type,object,mouseposition)
			} else if (type == "calendar") {
				if(object && object.currentObjects && object.currentObjects.length>0) {
					drawpreviewDragandDrop(event,type,object.currentObjects[0]); 
				}
			} else {
				drawpreviewDragandDrop(event,type,object); 
			}
		},
		function(event,type,object) { removeDDPreviewDivs(); } );
				
		function disabled(e) {
			var iconNode = $2("dragdrop_default_node");
			if(iconNode == undefined) {
				iconNode = newnode("div", {left: (e.clientX + iconOffset) + "px",top: (e.clientY + iconOffset) + "px"},
 			    { className : "dragdropdefaultnode background-color-default border-color-design", id: "dragdrop_default_node"},[
 			    	newnode("table",{ width:"100%" , height: "100%" },{ cellPadding:"0" , cellSpacing :"0" , border : "0" },[
 			    		newnode("tbody",null,null,[
 			    			newnode("tr",null,null,[
 			    				newnode("td",null,null,[
 			    					newnode("img",{},{ src : getFullImgSrc("img/dnd_disabled.gif") },[])
 			    				]),
 			    				newnode("td",{ fontSize : "8pt", whiteSpace : "nowrap" },null,[
 			    					newnode("div",{ overflow: "hidden"},null,[addTranslated(_("No subject"))])
 			    				])
 			    			])
 			    		])
 			    	])
 			    ]);
				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) {
			if($2("dragdrop_default_node")) {
				$2("dragdrop_default_node").parentNode.removeChild($2("dragdrop_default_node"));
				removeTMPId($2("dragdrop_default_node"));	
			}
			
		}
		registerSource($("cwwcontentresize"),"CALENDAR_NEW",function () { return null; },null,null,disabled,disabledremove);
		firstenter=true;
	}
	function checkChanges() {
        if (cwwdaysinweek != cww_oldvalues.cwwdaysinweek) { 
            return true; 
        }
        return false;
    }

    var tmpinterval=getWWInterval();
    var tmpstarttime=getWWStartTime();
    var tmpendtime=getWWEndTime();        
    
    if (!calendarinittemplates || checkChanges()) {
        createTemplatesWW(tmpinterval,tmpstarttime,tmpendtime);
        cww_oldvalues.cwwdaysinweek=cwwdaysinweek;
        calendarinittemplates=true;
    }
    
    var scrollpoint=tmpstarttime/tmpinterval;
    setTimeout(function() {
        $("cwwtimecontentall").scrollTop=(scrollpoint*20); 
    },0);    
	
	showallappointments=calendar_getAllFoldersAttribute();
	$("cwwshowAllAppointments").checked=showallappointments;
	var oDateLoc = new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0));	
	updateWWView(oDateLoc);
}

function getWWInterval() {
	var tmpinterval=15*60000;
	if (configContainsKey("gui.calendar.interval")) {
        tmpinterval=configGetKey("gui.calendar.interval")*60000;
    }
    return tmpinterval;
}

function getWWStartTime() {
    var tmpstarttime=8*60*60000;
    if (configContainsKey("gui.calendar.starttime")) {
        tmpstarttime=configGetKey("gui.calendar.starttime")*60*60000;
    }
    return tmpstarttime;
}

function getWWEndTime() {
    var tmpendtime=17*60*60000;
    if (configContainsKey("gui.calendar.endtime")) {
        tmpendtime=configGetKey("gui.calendar.endtime")*60*60000;
    }
    return tmpendtime;
}

function clearAppointments() {
	if (cwwdaysfull) {
		for (var zaehler1=0; zaehler1 < cwwdaysfull.length; zaehler1++){ 
			removeChildNodes(cwwdaysfull[zaehler1].node); 
		}
	}
	if(cwwdays) {
		for(var zaehler1=0;zaehler1<cwwdays.length;zaehler1++){
			removeChildNodes(cwwdays[zaehler1].node); 
			for(zaehler2=0;zaehler2<cwwdays[zaehler1].matrix.length;zaehler2++) {
				cwwdays[zaehler1].matrix[zaehler2]=new Array();
			}
		}
	}
	for(var i in allcalendarobjects) {
		for(var i2 in allcalendarobjects[i]["divs"]) {
			removeTMPId(i2);
		}
	}
	allcalendarobjects=new Object();
	if(calendarSelection.count != 0) {
		calendarSelection.reset();
	}
	for (var i=0;$2("cwwmoreappointments"+i);i++) {
		if ($2("cwwmoreappointments"+i).style.display!="none") { 
			$2("cwwmoreappointments"+i).style.display="none" 
		}
	}
}
function cwwchangeView(days,view){
	cwwactualday.setUTCDate(cwwactualday.getUTCDate()+days);
	activeMonth = cwwactualday.getUTCMonth();
	activeYear = cwwactualday.getUTCFullYear();		
	activeDay = cwwactualday.getUTCDate();	
	if(view == "list") {
		menuswitchCalendarView(view);
	}
	if(view == "day") {
		menuswitchCalendarTimerange(view);
	}
}
function goToNextWeek(nDirection)
{
	var step=1;
	if(currentpath2.join("/") == "calendar/calendar/workweek"  || currentpath2.join("/") == "calendar/list/workweek")  { step = 7 }
	if(currentpath2.join("/") == "calendar/calendar/custom"  || currentpath2.join("/") == "calendar/list/custom")  { step = configGetKey("gui.calendar.custom.countdays") }
	var oDateLoc = new Date(Date.UTC(activeYear,activeMonth,activeDay,0,0,0));	
	oDateLoc.setUTCDate(oDateLoc.getUTCDate()+(nDirection*step));	
	activeMonth = oDateLoc.getUTCMonth();
	activeYear = oDateLoc.getUTCFullYear();		
	activeDay = oDateLoc.getUTCDate();	
	if(currentpath2.join("/") == "calendar/calendar/workweek"  || currentpath2.join("/") == "calendar/list/workweek") {
		
	} else {
		startofweek=oDateLoc.getUTCDay(); 
	}
	oMiniCalendar.setSelectedByDate(activeYear, activeMonth, activeDay);
	updateWWView(oDateLoc);
}
function updateWWView(oDateLoc) {		
	clearAppointments();
    cwwactualday = new Date(getDayInSameWeek(oDateLoc, startofweek) * 864e5);      
	updateHeaderWW(oDateLoc);
	getCalendarObjectsWW(cwwactualday);
}
function updateHeaderWW(oDateLoc) {
	var oHeader = $("wwViewHeader");
	if(currentpath2.join("/") == "calendar/calendar/workweek") {
		$("wwViewHeader").parentNode.parentNode.parentNode.parentNode.parentNode.style.width="200px";
		oHeader.style.width="160px";
		oHeader.firstChild.nodeValue = _("CW") + " " + 
				formatDateTime("w yyyy", new Date(getKeyDayOfWeek(new Date(Date.UTC(activeYear,activeMonth,activeDay))) * 864e5));		
	} else if (currentpath2.join("/") == "calendar/calendar/day"){
		$("wwViewHeader").parentNode.parentNode.parentNode.parentNode.parentNode.style.width="200px";
		oHeader.style.width="160px";
		oHeader.firstChild.nodeValue = formatDate(oDateLoc,"dateday");
	} else {
		if(cwwdaysinweek!=1) {
			var myenddate=new Date(oDateLoc.getTime());
			myenddate.setUTCDate(oDateLoc.getUTCDate() + (cwwdaysinweek-1) );
			$("wwViewHeader").parentNode.parentNode.parentNode.parentNode.parentNode.style.width="300px";
			oHeader.style.width="260px";
			oHeader.firstChild.nodeValue = formatDate(oDateLoc,"date") +" - "+ formatDate(myenddate,"date");
		} else {
			$("wwViewHeader").parentNode.parentNode.parentNode.parentNode.parentNode.style.width="200px";
			oHeader.style.width="160px";
			oHeader.firstChild.nodeValue = formatDate(oDateLoc,"dateday");
		}
	}
	var oMonday= new Date(cwwactualday);
	for (indDay=0;indDay<cwwdaysinweek;indDay++) {
		if (currentpath2.join("/") == "calendar/calendar/workweek" || currentpath2.join("/") == "calendar/calendar/custom") {
			var sId = 'singleDay' + (indDay) + 'stWw';			
			var nCurrHeader = $2(sId);
			// set class name
			nCurrHeader.className = "font-color-default";
			// today?
			if (isToday(oMonday)) {
			    // change proper parent's class name
			    jQuery(nCurrHeader).parents(".appointmentViewHeadBG").addClass("todayBackground");
			}
			nCurrHeader.innerHTML = formatDate(oMonday,"dateday"); 
			if( nCurrHeader.style.display!="") { nCurrHeader.style.display=""; }
			oMonday.setDate(oMonday.getDate()+1);

		} else {
			var sId = 'singleDay' + (indDay) + 'stWw';
			var nCurrHeader  = $2(sId);
			//if (!nCurrHeader) continue;
			removeChildNodes(nCurrHeader);
			nCurrHeader.className += " font-color-selected";
			nCurrHeader.appendChild(document.createTextNode(".")); 
		}
	}
}
function getCalendarObjectsWW(actualmonday) {
	var start = actualmonday;
	var end = new Date(start.getTime());
	end.setDate(start.getDate()+cwwdaysinweek);
	var starttime=start.getTime();
	var endtime=end.getTime();
	var params=new Object();
	params.action="all";
	params.start=starttime;
	params.end=endtime;
	params.columns="1,20,207,206,2";
	if(!showallappointments) {
		params.folder= activefolder;
	}
	params.showPrivate = true;
	storageCache.get(AjaxRoot + "/calendar", params, initCalendarObjectsWW,
        calendarwwfields.toString(), true,
		function (x) { 
			return x.folder + "." + x.id + "." + x.recurrence_position 
                + "." + x.recurrence_id + "." + x.created_by;
		},
		function (x) { 
		 	var mObj = { id: x[0], folder: x[1], recurrence_position: x[2] || 0,
		 	    recurrence_id: x[3], created_by: x[4] }; 
		    return mObj;
		}
	);
	storageCache.update();	
}
function cwwwupdateView()
{
	if(!lastUpdateOfCalendarTimestamp || lastUpdateOfCalendarTimestamp<cwwstorage.timestamp) {
		lastUpdateOfCalendarTimestamp=cwwstorage.timestamp;
	}
	clearAppointments();
	cwwstorage.newIterate(cwwstorage.ids, emptyFunction, showCalendarObject,
		function(){ 
			redrawAppointment();
		 });
	calendar_HeaderUpdate(cwwstorage.ids.length);	
}
var cww_myboolean=true;

function initCalendarObjectsWW(storage) {
	cww_activehovers=new Object();
	if(cww_myboolean) {
		cww_myboolean=false;
	}
	cwwstorage=storage;
	calendarSelection.setStorage(cwwstorage);
	if (!lastUpdateOfCalendarTimestamp || lastUpdateOfCalendarTimestamp<cwwstorage.timestamp) {
		lastUpdateOfCalendarTimestamp=cwwstorage.timestamp;
	}
	cwwstorage.newIterate(cwwstorage.ids, emptyFunction, showCalendarObject,
		function() {
			redrawAppointment();
		}
	);
	storage.events.register("Changed", cwwwupdateView);	
	calendar_HeaderUpdate(cwwstorage.ids.length);
}

function showCalendarObject(index,object) {
	// consolidate users and participants (field 220 and 221)
	for (var i in object[16]) {
		var a1 = object[16][i];
		for (var ia in object[10]) {
			if (object[10][ia].id == a1.id) {
				a1.confirmation = object[10][ia].confirmation;
				if (object[10][ia].confirmmessage) a1.confirmmessage = object[10][ia].confirmmessage;
				break;
			}
		}
	}
	
    var calendarobject = new CalendarWorkWeekObject(object[0], object[1],
        object[2] || 0, object[3], object[4], object[5], object[6], object[7],
        object[8], object[9], object[16], object[11], object[12], object[13],
        object[14], object[15], object[17], object[18], object[10]);
	calendarobject.index=index;
	allcalendarobjects[""+calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position]=calendarobject;		
	cwwdrawAppointment(calendarobject);
}
function cwwchangeSelected(elementid) {
	if(calendarSelection.count != 0) {
		calendarSelection.reset();		
	}
	for(var myzaehler in allcalendarobjects) {
		for(var myzaehler2 in allcalendarobjects[myzaehler].divs) {
			var tds = allcalendarobjects[myzaehler].divs[myzaehler2].getElementsByTagName("td");
			var divs = allcalendarobjects[myzaehler].divs[myzaehler2].getElementsByTagName("div");			
			var wholeDayEl = !(tds[1] && tds[2]);
			if(wholeDayEl)
			{ 
				divs[2].className = removeClass(divs[2].className,"background-color-selection-elements");
				divs[2].className = removeClass(divs[2].className,"font-color-selected");		
				divs[2].className = removeClass(divs[2].className,"font-weight-high");									
			}
			if(tds[2])
			{
				tds[2].className = removeClass(tds[2].className,"appointmentTitleBG");
				tds[2].className = removeClass(tds[2].className,"background-color-selection-elements");
				tds[2].className = removeClass(tds[2].className,"font-color-selected");
				tds[2].className = removeClass(tds[2].className,"font-weight-high");
			}
			if(tds[1])			
			{
				tds[1].className = removeClass(tds[1].className,"border-color-content-default");				
				tds[1].className = removeClass(tds[1].className,"border-color-selection-elements");
			}
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"border-color-selection-elements");
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"background-color-selection-elements");								
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 			
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"selectedAppointmentWW");				
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"deselectedAppointmentWW");							
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"border-color-image");											
			allcalendarobjects[myzaehler].divs[myzaehler2].className = 
				removeClass(allcalendarobjects[myzaehler].divs[myzaehler2].className,"appointmentBGWW");					
			if (elementid == myzaehler) {
				allcalendarobjects[myzaehler].divs[myzaehler2].className += " selectedAppointmentWW background-color-selection-elements border-color-selection-elements";
				if (tds[1])
					tds[1].className += " border-color-selection-elements";	
				if (tds[2])
					tds[2].className += " background-color-selection-elements font-color-selected font-weight-high";
				if (wholeDayEl) {
					divs[2].className += " background-color-selection-elements font-color-selected font-weight-high";			
				}
			} else {
				allcalendarobjects[myzaehler].divs[myzaehler2].className += "  border-color-image deselectedAppointmentWW appointmentBGWW";
				if(tds[1])
					tds[1].className += " border-color-content-default";									
				if(tds[2])				
					tds[2].className += " appointmentTitleBG";
			}
		}
	}
	
	if (elementid) {
	    // toggle
		calendarSelection.toggle(allcalendarobjects[elementid].index);
		// set global var
		var obj = allcalendarobjects[elementid];
		var names = [
             "id", "folder_id", "recurrence_position", "recurrence_id", 
             "created_by", "title", "start_date", "end_date", "note", 
             "recurrence_type", "participants", "full_time", "shown_as",
             "color_label", "location", "private_flag", "interval", "categories",
             "users"
		];
		// copy properties
		selectedAppointment = {};
		var i = 0, $l = names.length, name;
		for (; i < $l; i++) {
		    name = names[i];
		    selectedAppointment[name] = obj[name];
		}
		// copy folder (duplicate)
        selectedAppointment.folder = obj.folder_id;
		// trigger event
		triggerEvent("Selected", calendarSelection.getSelected());
	}	
}
function cwwchangeSelectedFull(elementid) {
	if (calendarSelection.count != 0){
		calendarSelection.reset();
	}
	for (var myzaehler in allcalendarobjects) {
		for (var myzaehler2 in allcalendarobjects[myzaehler].divs) {
			if (elementid == myzaehler) {
				allcalendarobjects[myzaehler].divs[myzaehler2].className += " selectedAppointmentWW background-color-selection-elements border-color-selection-elements";
			}
		}
	}
	
	if (elementid) {
		if(calendarSelection.count != 0) {
			calendarSelection.toggle(allcalendarobjects[elementid].index);		
		}
		selectedAppointment = { 
			id: allcalendarobjects[elementid].id, folder: allcalendarobjects[elementid].folder_id,
			recurrence_position: allcalendarobjects[elementid].recurrence_position, 
	        recurrence_id: allcalendarobjects[elementid].recurrence_id, 
	        created_by: allcalendarobjects[elementid].created_by
		};
		triggerEvent("Selected",calendarSelection.getSelected());
	}
}

function cwwdrawAppointment(calendarobject) {
	function cww_doDblClick (event) {
		if(!event) {
			event=window.event;
		}
		triggerEvent('OX_Calendar_Edit');
		stopEvent(event);
	}
	//Check Full Time Object
	//Check Time
	var oneday=1000*60*60*24;
	var showappointment=true;
	var zaehler3=0;

	// Startdate Correction Complete Appointment
	// Setze Startzeit des Termins um , falls er vor meiner Anzeige beginnt
	var sdt=calendarobject["start_date"].getTime();
	if (sdt<cwwactualday.getTime()) {
		sdt=new Date(cwwactualday.getTime()).getTime();
	}
	// Setze Endzeit des Termins um , falls er nach meiner Anzeige beginnt
	var edt=calendarobject["end_date"].getTime();
	if (edt>cwwactualday.getTime()+(cwwdaysinweek*(oneday))) {
		edt=new Date(cwwactualday.getTime()+(cwwdaysinweek*oneday)).getTime();
	}
	
	var owner = activeFolderOwner;
	var isPrivateShared = (owner !== configGetKey('identifier') && calendarobject.private_flag === true);
	
	var sdttmp=sdt;
	// IST es ein Ganztagstermin
	if (calendarobject.full_time) {
		// Kann Termin angezeigt werden???
		showappointment=true;
		while (sdttmp<edt) {
			if (!document.getElementById(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3))	{
				// Hol mir den Tag der Woche
				var sdd = (new Date(sdttmp).getUTCDay()-new Date(cwwactualday.getUTCDay()) +7) % 7;

				//Zeichne Ganztagstermin					
				showappointment=true;
				var appointmentcontainer = cwwdaysfull[sdd].node;
				var myappointment=$("cww_appointment_template_full_time").cloneNode(true);
				var	paramObj = { 
					id: calendarobject.id, folder_id: calendarobject.folder_id,
				    recurrence_position: calendarobject.recurrence_position,
				    recurrence_id: calendarobject.recurrence_id, created_by: calendarobject.created_by
				};	
				var divs = myappointment.getElementsByTagName("div");			
				
				var oInplEdit  = new inplaceEdit(divs[2], calendarobject.title, function (sStr, oObj) {
					editAppointment(paramObj,{title:sStr});
				});
				oInplEdit.style.color = "#FFFFFF";
				oInplEdit.style.fontSize = "8pt";
				oInplEdit.style.height = "1.2em";
				//fixed bug with auto selection													
				calendarSelection.reset();	
				var myfunc1 = function(oInplEdit) {
					return function(e) {
						var SelObj = calendarSelection.getID();
						if(SelObj && SelObj.id == paramObj.id &&
							SelObj.folder == paramObj.folder_id &&
							SelObj.recurrence_position == paramObj.recurrence_position)
							{
								if(window.event) {
									e = window.event;
								}
								oInplEdit.on();
								stopEvent(e);
						}
					};
				};
                var tds = myappointment.getElementsByTagName("td");
                var title = tds[1].getElementsByTagName("span")[0];
                
                var backColor = "appointmentTitleBG";
                if (calendarobject.categories) {
        			// getting the first color out of the categories list
        			var cat = ox.categories.getFirstMatch(calendarobject.categories);
        			if (cat.color != 0) {
        				backColor = "colorLabel" + cat.color;
        			}
        		}
                tds[1].className += " " + backColor;
		
				myappointment.id=calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3;				
				addTMPId(myappointment,"calendar/calendar/workweek");
				zaehler3++;
				
				if (isPrivateShared == false) {
					myappointment.oxcalobj = calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3;
					
					addDOMEvent(myappointment,"mousedown",function (e) {
						cwwchangeSelected(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position);
						cancelBubbling(e);
					});
					addDOMEvent(tds[1], "mousedown", myfunc1(oInplEdit));		
					addDOMEvent(myappointment, "click", function(e) {
						var SelObj = calendarSelection.getID();
						if (SelObj && SelObj.id == paramObj.id &&
							SelObj.folder == paramObj.folder_id &&
							SelObj.recurrence_position == paramObj.recurrence_position) {
						} else {
							cwwchangeSelected(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position); 
						}
						cancelBubbling(e);
					});
					
					/* Drag & Drop Source */
					registerSource(myappointment,"calendar",function () { 
						var mymove=new MoveCopy(); 
						mymove.begin("calendar",[calendarobject]); 
						return mymove; 
					},null,null,calendardefaultdisabled,defaultdisabledremove);
					
					addDOMEvent(myappointment, "dblclick", cww_doDblClick);
	                addDOMEvent(myappointment, "contextmenu", function(e) {
	                    stopEvent(e);
	                    globalContextMenus.calendar.display(e.clientX, e.clientY, calendarSelection);
	                });
				} else {
					// private apps in shared folder, set cursor to default
					tds[1].style.cursor = "default";
				}
				allcalendarobjects[calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position].addDiv(myappointment.id,myappointment);
				/** Shown As **/
				switch (calendarobject.shown_as) {
					case 1:
						tds[0].className = "appointmentRESERVED";
						break;
					case 2:
						tds[0].className = "appointmentTEMPORARY";
						break;
					case 3:
						tds[0].className = "appointmentABSENT";
						break;
					case 4:
						tds[0].className = "appointmentFREE";
						break;
				}
				
				// title & location
				var appTitle = [];
				if (calendarobject.title) appTitle.push(calendarobject.title);
				if (calendarobject.location) appTitle.push(calendarobject.location);
				title.firstChild.data = appTitle.join(" - ") || "";
									
				// setting confirmation styles
				if (calendarobject.participants.length) {
					for (var i in calendarobject.participants) {
						if (calendarobject.participants[i].id == owner) {
							switch(calendarobject.participants[i].confirmation) {
								case 0:
									myappointment.style.opacity = ".6";
									title.style.fontStyle = "italic";
									calendarobject.title += " (" + _("waiting") + ")";
									break;
								case 2:
									title.style.textDecoration = "line-through";
									break;
								case 3:											
									title.style.fontStyle = "italic";
									calendarobject.title += " (" + _("tentative") + ")";
									break;
							}
							break;
						}
					}
				}
				
				appointmentcontainer.appendChild(myappointment);
			}
			sdttmp = sdttmp+oneday;
		}
	} else {
		if (sdttmp==edt && edt != new Date(cwwactualday.getTime()+(cwwdaysinweek*oneday)).getTime() ) {
			edt++;
		}
		//Hier alle nicht Ganztagstermine	
		while (sdttmp<edt) {
			if (!document.getElementById(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3)) {
				showappointment=true;
				var sdd        = (new Date(sdttmp).getUTCDay()-new Date(cwwactualday.getUTCDay()) +7) % 7;
				var longstart  = (sdttmp % oneday);
                if (longstart < 0) longstart += oneday;
				var startpoint = Math.floor((longstart/globalinterval)+0.0000001);
				var edttmp     = edt;
				var longend    = (edt % oneday);
                if (longend < 0) longend += oneday;
				var endpoint   =   Math.ceil((longend/globalinterval)-0.0000001);
				// An diesem Tag nicht zu Ende
				if(Math.floor(sdttmp / oneday + 1) * oneday <= edt) {
					endpoint   = globalintervalcounts;							
				}
				if(startpoint  ==  endpoint) {
					endpoint++;
				}
				/** Check Place Allocation*/
				
				var tiefe=0;  			//Place
				var allelements=0;		//AllElements
			
				for (var zaehler=startpoint;zaehler<endpoint;zaehler++) {
					var maxelements = cwwdays[sdd].matrix[zaehler].length;
					if(allelements<maxelements) {
						allelements=maxelements;
					} 
					if(cwwdays[sdd].matrix[zaehler][tiefe]) {
						tiefe++;
						zaehler=startpoint-1; //Zaehler is added after loop
						if(tiefe==maxappointmentsperday) {
							showappointment=false;	
							break;
						}
					}
				}
				if (!showappointment){
					$2("cwwmoreappointments"+sdd).style.display = "";
				} else {
					var myappointment=$("cww_appointment_template").cloneNode(true);
					myappointment.id=+calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3;					
					addTMPId(myappointment,"calendar/calendar/workweek");
					zaehler3++;
					
					var	paramObj = { 
						id: calendarobject.id, folder_id: calendarobject.folder_id,
						recurrence_position: calendarobject.recurrence_position, recurrence_id: calendarobject.recurrence_id,
						created_by: calendarobject.created_by
					};	
					var tds = myappointment.getElementsByTagName("td");			
					var oInplEdit  = new inplaceEdit(tds[2].getElementsByTagName("div")[0], calendarobject.title, function (sStr,oObj) {
								editAppointment(paramObj,{title:sStr});
							});
	
					oInplEdit.style.color = "white";
					oInplEdit.style.fontSize = "8pt";
					oInplEdit.style.height = "1.2em";
					//fixed bug with auto selection													
					calendarSelection.reset();
					var myfunc1 = function(oInplEdit) {
						return function(e) {
							var SelObj = calendarSelection.getID();
							if (SelObj && SelObj.id == paramObj.id &&
									SelObj.folder == paramObj.folder_id &&
									SelObj.recurrence_position == paramObj.recurrence_position) {
								oInplEdit.on();
								stopEvent(e);
							}
						};
					};
                    var tds = myappointment.getElementsByTagName("td");
                    var title = tds[2].getElementsByTagName("span")[0];
                    
                    var backColor = "appointmentTitleBG";
                    if (calendarobject.categories) {
            			// getting the first color out of the categories list
            			var cat = ox.categories.getFirstMatch(calendarobject.categories);
            			if (cat.color != 0) {
            				backColor = "colorLabel" + cat.color;
            			}
            		}
                    tds[2].className += " " + backColor;
                    var domdivs=myappointment.getElementsByTagName("div");
                    
					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) {
						if ($2("cww_node_dd")) {
							$2("cww_node_dd").parentNode.removeChild($2("cww_node_dd"));
							removeTMPId($2("cww_node_dd"));
						}
					}	
					if (isPrivateShared == false) {
						myappointment.oxcalobj = calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position+"-"+zaehler3;
						
                    	addDOMEvent(myappointment,"mousedown",function (e) {						
							cwwchangeSelected(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position);
							cancelBubbling(e);
						});
						addDOMEvent(tds[2], "mousedown", myfunc1(oInplEdit));
						addDOMEvent(myappointment, "click", function(e) {
							var SelObj = calendarSelection.getID();
							if(SelObj && SelObj.id == paramObj.id &&
								SelObj.folder == paramObj.folder_id &&
								SelObj.recurrence_position == paramObj.recurrence_position) {							
							} else {
								cwwchangeSelected(calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position); 
							}
							cancelBubbling(e);
						});	
						addDOMEvent(myappointment,"dblclick",cww_doDblClick);
						
						/* Cursor fuer Drag&Drop */
						addDOMEvent(domdivs[1], "mouseover",
							(function(obj){
								return function(){ 
									obj.style.cursor = "move"; };
							})(domdivs[1]));
						addDOMEvent(domdivs[0], "mouseover",
							(function(obj){
								return function(){ obj.style.cursor = "n-resize"; };
							})(domdivs[0]));
						addDOMEvent(domdivs[4], "mouseover",
							(function(obj){ return function(){ obj.style.cursor = "s-resize"; }; })(domdivs[4]));
						
	                    addDOMEvent(myappointment, "contextmenu", function(e) {
	                        stopEvent(e);
	                        globalContextMenus.calendar.display(e.clientX, e.clientY, calendarSelection);
	                    });
						registerSource(domdivs[0],"CALENDAR_TOP",function () { return calendarobject; }, null,null,disabled,disabledremove);
						registerSource(domdivs[4],"CALENDAR_BOTTOM",function () { return calendarobject; },null,null,disabled,disabledremove);
						registerSource(domdivs[1],"calendar",function () { 
							var mymove=new MoveCopy(); 
							mymove.begin("calendar",[calendarobject]); 
							return mymove; 
						},null,null,calendardefaultdisabled,defaultdisabledremove);
					} else {
						// private apps in shared folder, set cursor to default
						tds[1].style.cursor = "default";
					}
					allcalendarobjects[calendarobject.folder_id+"-"+calendarobject.id+"-"+calendarobject.recurrence_position].addDiv(myappointment.id,myappointment);			
					
					var appointmentcontainer=cwwdays[sdd].node;
					//FILL APPOINTMENTS
						/** Shown As **/
						switch (calendarobject.shown_as) {
							case 1:
								tds[0].className="appointmentRESERVED";
								break;
							case 2:
								tds[0].className="appointmentTEMPORARY";
								break;
							case 3:
								tds[0].className="appointmentABSENT";
								break;
							case 4:
								tds[0].className="appointmentFREE";
								break;
						}
						
						// Title & location
						var appTitle = [];
						if (calendarobject.title) appTitle.push(calendarobject.title);
						if (calendarobject.location) appTitle.push(calendarobject.location);
						title.firstChild.data = appTitle.join(" - ") || "";
						
						// setting confirmation styles
						if (calendarobject.participants.length) {
							for (var i in calendarobject.participants) {
								if (calendarobject.participants[i].id == owner) {
									switch(calendarobject.participants[i].confirmation) {
										case 0:
											myappointment.style.opacity = ".6";
											title.style.fontStyle = "italic";
											calendarobject.title += " (" + _("waiting") + ")";
											break;
										case 2:
											title.style.textDecoration = "line-through";
											break;
										case 3:											
											title.style.fontStyle = "italic";
											calendarobject.title += " (" + _("tentative") + ")";
											break;
									}
									break;
								}
							}
						}
												
						/** Recurrence Type **/
						if (calendarobject.recurrence_type && calendarobject.recurrence_type!=0) {
							tds[3].getElementsByTagName("img")[0].style.display = "inline";
						} else { 
							tds[3].getElementsByTagName("img")[0].style.display = "none";
						}
												
						/** Private or Group **/
						if (calendarobject.participants && calendarobject.participants.length>1) {
							tds[3].getElementsByTagName("img")[1].style.display = "inline";
							tds[3].getElementsByTagName("img")[1].src=getFullImgSrc("img/calendar/group.gif");							
						} else {
							tds[3].getElementsByTagName("img")[1].style.display = "none";
						}
		
						/** Tagging **/
						if (calendarobject.color_label && calendarobject.color_label!=0) {
							tds[3].getElementsByTagName("img")[2].style.display = "inline";
							tds[3].getElementsByTagName("img")[2].src=getFullImgSrc("img/menu/tag_"+calendarobject["color_label"]+".gif");
						} else { 
							tds[3].getElementsByTagName("img")[2].style.display = "none";
						}
							
						if (calendarobject.private_flag) {
							tds[3].getElementsByTagName("img")[3].style.display = "inline";
							tds[3].getElementsByTagName("img")[3].src=getFullImgSrc("img/private_flag.gif");
						} else {
							tds[3].getElementsByTagName("img")[3].style.display = "none";
						}
						
						if (calendarobject.categories) {
							var categories = clone(ox.categories.getByString(calendarobject.categories, ox.categories.match.MATCH));
							categories.shift();
							if (categories.length) {
//								var tmpMap = {}, cats = [];
//								// filter 
//								for (var i=0; i < categories.length; i++) {
//									if (!tmpMap[categories[i].color]) {
//										cats.push(categories[i]);
//										tmpMap[categories[i].color] = true
//									}
//								}
//								tmpMap = null, categories = null;
								ox.categories.ui.drawCategoriesList(categories, tds[3].getElementsByTagName("div")[0], true);								
							}
						}
						
						//New Element is Latest
					if (allelements<tiefe+1) {
						allelements=tiefe+1;
					}
					myappointment.style.height=((endpoint-startpoint) * wwline) + "px";
					myappointment.getElementsByTagName("div")[1].style.height = (((endpoint-startpoint) * wwline)-4) + "px";
					myappointment.style.top=startpoint*wwline+"px";							
					appointmentcontainer.appendChild(myappointment);
					
					for(var zaehler=startpoint;zaehler<endpoint;zaehler++)
					{
						cwwdays[sdd].matrix[zaehler][tiefe]=new MatrixObject(calendarobject.folder_id,calendarobject.id,calendarobject.recurrence_position,myappointment.id,startpoint,endpoint);
					}
					allredrawelements=new Object();
				}
			}
			if(sdt==sdttmp) {
				sdttmp = Math.floor(sdttmp / oneday) * oneday;
			}
			sdttmp = sdttmp+oneday;
		}
	}
}
var allredrawelements=new Object();
function redrawAppointment(elementlength,position,elementid) {
	var allobjects=new Object();
	for(var tagezaehler=0;tagezaehler<cwwdaysinweek;tagezaehler++) {  //<7
		var currentday=cwwdays[tagezaehler].matrix;
		for(var intervalzaehler=0;intervalzaehler<currentday.length;intervalzaehler++) { // 24,48,96,144,288
			var currentinterval=currentday[intervalzaehler];
			var elementsperline=currentinterval.length;
			var tmpobjects=new Array();
			for(var i=0;i<currentinterval.length;i++) { //<max appointments
				var element=currentinterval[i] 
				if(element) {
					tmpobjects.push(element.element_id);
					if(!allobjects[element.element_id]) { 
						allobjects[element.element_id]=new Object(); 
						allobjects[element.element_id]["name"]=element.element_id; 
						allobjects[element.element_id]["nodes"]=new Object();
						allobjects[element.element_id]["plength"]=currentinterval.length;
						allobjects[element.element_id]["pposition"]=i;
					} else if(allobjects[element.element_id]["plength"]<currentinterval.length) {
						allobjects[element.element_id]["plength"]=currentinterval.length;
						allobjects[element.element_id]["pposition"]=i;
					}
				}				
			}
			//Fill childnodes
			for(var i=0;i<tmpobjects.length;i++) {
				var element=allobjects[tmpobjects[i]];
				for(var i2=0;i2<tmpobjects.length;i2++) {
					if(!element["nodes"][tmpobjects[i2]] && (tmpobjects[i2]!=tmpobjects[i])) {
						element["nodes"][tmpobjects[i2]]=true;
					}
				}
			}
		}
	}
	for(var myelements in allobjects) {
		if(!allobjects.highest) {
			var highest=0;
			var checked=new Object();
			var tocheck=new Array();
			var zaehler=0;
			function checkNext() {
				for(zaehler=0;zaehler<tocheck.length;zaehler++) {
					var curobj=tocheck[zaehler];
					if(!checked[curobj.name]) {
						if(highest<curobj.plength) { highest=curobj.plength }
						checked[curobj.name]=true;
						for(var i in curobj.nodes) {
							if(!checked[i]) {
								tocheck.push(allobjects[i]);
							}
						}					
					}
				}
			}
			var myobject=allobjects[myelements];		
			tocheck.push(myobject)
			checkNext();
			
			for(var i1 in checked) {
				allobjects[i1].highest=highest;
			}
		}
	}
	for(var last in allobjects) {
		var d=$2(allobjects[last].name);
		d.style.width=(Math.round(100/allobjects[last].highest)-2)+"%";
		d.style.left=(Math.round(100/allobjects[last].highest)*allobjects[last].pposition)+"%";
	}
	cwwresizeTopHeader();	
}						

/**** Templates Creation *******************************************************************************************/
/**
* Create Matrix
* Create Template Timeline
* Create Template Background Calendar Main Content
*/
function createTemplatesWW(interval,startworktime,endworktime) {
	this.globalinterval=interval;
	var completetime=1000*60*60*24;
	this.globalintervalcounts=Math.round(completetime/interval);
	
	createNewTimeLine(interval);
	createCalendarContentFullTime();
	createCalendarContentWW(interval,startworktime,endworktime);
	cwwdays=new Array();	
	for(var zaehler=0;zaehler<cwwdaysinweek;zaehler++) {
		cwwdays[zaehler]=new Object();
		cwwdays[zaehler].node=$2("cww-line-"+zaehler);
		cwwdays[zaehler].matrix=new Array(globalintervalcounts);
		for(i=0;i<cwwdays[zaehler].matrix.length;i++)
		{
			cwwdays[zaehler].matrix[i]=new Array();
		}
	}
	cwwdaysfull=new Array();
	for(var zaehler=0; zaehler<cwwdaysinweek; zaehler++) {
		cwwdaysfull[zaehler]=new Object();
		cwwdaysfull[zaehler].node = $2("cwwheaderfull:"+zaehler);
	}
}
function createCalendarContentFullTime() {
	function getfunction(list,i) {
		return function() {
			cwwchangeView(i,list);
		}
	}
	
	for (var i=0; $2("cwwmoreappointments"+i); i++) {
		removeTMPId("singleDay"+(i)+"stWw");
		removeTMPId("cwwmoreappointments"+(i));
		removeTMPId("cwwwholeday_dnd:"+i);
		removeTMPId("cwwheaderfull:"+i);
		removeTMPId("cww_wholeday:"+i);	
	}
	
	removeChildNodes($("cwwheaderdates"));
	var tbody=newnode("tbody", null,null,[]);
	//var firsttr=newnode("tr", null, null,[]);
	var secondtr=newnode("tr", { height: "100%" }, { height: "100%" }, []);
	for(var i=0; i<cwwdaysinweek; i++) {
		var onetd=
			newnode("td",{ width: Math.floor(100/cwwdaysinweek)+"%", borderRight: "1px solid", paddingLeft: "5px", overflow:"hidden" },{className: "border-color-design appointmentViewHeadBG"},[
				newnode("table",{ width: "100%"},{ cellPadding: 0 , cellSpacing : 0 , border : 0 },[
					newnode("tbody",null,null,[
						newnode("tr",null,null,[
							newnode("td",{ width: "100%"},null,[
								newnode("div",{ overflow: "hidden" },null,[
									newnode("div",{ whiteSpace :"nowrap" ,cursor: "pointer", zIndex:"-1" },{id: "singleDay"+(i)+"stWw"},[
										newnode("img",{},{src: getFullImgSrc("img/dummy.gif")},[])
									])
								])
							]),
							newnode("td",null,{ id : "cwwmoreappointments"+(i), title : _("Click here for further appointments") },[
								newnode("div", { paddingRight : "7px", height: "16px" , cursor : "pointer" }, null,[
									newnode("img",null,{ src : getFullImgSrc("img/menu/weiterzuListe.gif") },[])
								])
							])
						])
					])
				])
			]);
		addTMPId(onetd.getElementsByTagName("div")[1]);
		addTMPId(onetd.getElementsByTagName("td")[1]);
		addDOMEvent(onetd.getElementsByTagName("td")[0],"click",getfunction("day",i));
		addDOMEvent(onetd.getElementsByTagName("td")[1],"click",getfunction("list",i));
		//firsttr.appendChild(onetd.);
		$("cwwheaderdates").appendChild(onetd);
		
		var secondtd = newnode("td",{ width: Math.floor(100/cwwdaysinweek) + "%" , borderRight: "1px solid" }, 
				{ className: "border-color-design", vAlign: "top", id: "cwwwholeday_dnd:" + i },[
			newnode("div",{ width:"100%", position:"relative"},{ id: "cwwheaderfull:"+i },[ document.createTextNode(" ") ]) ]);
		function getfunction2(node) {
			return function() {
				cww_createNewWholeAppointment(node);
			}
		}
		
		addTMPId(secondtd);
		addTMPId(secondtd.getElementsByTagName("div")[0]);
		//addTMPId(secondtd.getElementsByTagName("table")[0]);
		addDOMEvent(secondtd, "dblclick", getfunction2(secondtd.getElementsByTagName("div")[0]));	
		//addDOMEvent(secondtd.getElementsByTagName("table")[0],"dblclick",getfunction2(secondtd.getElementsByTagName("table")[0]));	
		secondtr.appendChild(secondtd);
	}
	/*
	if (IE < 8) $("cwwheaderscroll").style.display="none";
	else $("cwwheaderscroll").style.display="";
	*/
	
	delete calendarhovers["daywwcustom"];
	calendarhovers["daywwcustom"]=new Hover(secondtr,OXAppointmentHover.getContent().node);
	calendarhovers["daywwcustom"].setSize(OXAppointmentHover.contentobject.node);
	calendarhovers["daywwcustom"].getTarget = function (node) {
        try {
            while (node) {
                if (node.oxcalobj) return node.parentNode ? node : null;
                node = node.parentNode;
            }
        } catch (e) { }
    };
	calendarhovers["daywwcustom"].onShow = function (node) {
		OXAppointmentHover.actualHover=this;
		var splitid=node.oxcalobj.split("-");
		OXAppointmentHover.refillContent(splitid[1],splitid[0],splitid[2]);
		
	}
	tbody.appendChild(secondtr);
	var d=$("cwwheader");
	removeChildNodes(d);
	d.appendChild(tbody);
	var i=0;
	while($2("cwwwholeday_dnd:"+i)) {
		var mynode=$2("cwwwholeday_dnd:"+i);
		var mycallback=new Object();
		mycallback["calendar"]=returni(i);
		registerTarget(mynode,mycallback,null,null,
			function(event,type,object,mouseposition) {
				drawpreviewDragandDropWholeDay(event,type,object.currentObjects[0]); 
			},
			function(event,type,object,mouseposition) { 
				drawpreviewDragandDropWholeDay(event,type,object.currentObjects[0]); 
			},
			function(event,type,object) { cww_lastdateddwholeday=null; removeDDPreviewDivs(); } 
		);
		i++;
	}
	function returni(i) {
		return function(event,dragType,data,mouseposition,targetNode) { cww_saveAppointment(data.currentObjects[0],event,"calendar",true,i);  }
	}
}

function cww_createNewAppointment(clickedobject) {
	var day=clickedobject.id.split(":")[1];
	var time=clickedobject.parentNode.id.split("-")[2];

	var mydate=new Date(Date.UTC(cwwactualday.getUTCFullYear(),cwwactualday.getUTCMonth(),cwwactualday.getUTCDate()+parseInt(day),0,0,0));
	mydate.setTime(mydate.getTime()+parseInt(time));
	calendar_activedate=mydate;
	calendar_wholeday=false;
	triggerEvent("OX_Before_Create_Calendar");
}
function cww_createNewWholeAppointment(clickedobject) {
	var day=clickedobject.id.split(":")[1];
	var mydate=new Date(Date.UTC(cwwactualday.getUTCFullYear(),cwwactualday.getUTCMonth(),cwwactualday.getUTCDate()+parseInt(day),0,0,0));
	mydate.setTime(mydate.getTime());
	calendar_activedate=mydate;
	calendar_wholeday=true;
	triggerEvent("OX_Before_Create_Calendar");
}
function createCalendarContentWW(interval,startworktime,endworktime){
	var mytable=$("cwwtimecontent");
	for(var zaehler=0;$2("cww-line-"+zaehler);zaehler++) {
		removeTMPId("cww-line-"+zaehler);
	}
	var completetime =1000*60*60*24; 
	var timehour =1000*60*60;
	var templateofftimenohour=$("cwww_calendar_offtime_nohour");
	templateofftimenohour.style.width=Math.floor(100/cwwdaysinweek)+"%";
	var templateofftimehour=$("cwww_calendar_offtime_hour");
	templateofftimehour.style.width=Math.floor(100/cwwdaysinweek)+"%";
	var templateworktimenohour=$("cwww_calendar_worktime_nohour");
	templateworktimenohour.style.width=Math.floor(100/cwwdaysinweek)+"%";
	var templateworktimehour=$("cwww_calendar_worktime_hour");
	templateworktimehour.style.width=Math.floor(100/cwwdaysinweek)+"%";	
	var comtemplateofftimenohour =document.createElement("tr");
	var comtemplateofftimehour =document.createElement("tr");
	var comtemplateworktimenohour =document.createElement("tr");
	var comtemplateworktimehour =document.createElement("tr");
	for (i=0;i<cwwdaysinweek;i++) {
		var tmp1=templateofftimenohour.cloneNode(true);
		tmp1.id="App-ONH:"+i;
		comtemplateofftimenohour.appendChild(tmp1);
		var tmp2=templateofftimehour.cloneNode(true);
		tmp2.id="App-OH:"+i;
		comtemplateofftimehour.appendChild(tmp2);
		var tmp3=templateworktimenohour.cloneNode(true);
		tmp3.id="App-WNH:"+i;
		comtemplateworktimenohour.appendChild(tmp3);
		var tmp4=templateworktimehour.cloneNode(true);
		tmp4.id="App-WH:"+i;
		comtemplateworktimehour.appendChild(tmp4);
	}
	var mytable2=mytable.cloneNode(false);
	var mytable2tbody=document.createElement("tbody");
    var numOfLines = 0;
	for (currenttime=0;currenttime<completetime;numOfLines++) {
		var temp1;
		if((currenttime % timehour) == 0) {
			if(currenttime >= startworktime && currenttime < endworktime) {
				temp1 = comtemplateworktimehour.cloneNode(true);
				temp1.id="cww-tr-"+currenttime;
			}
			else {
				temp1 = comtemplateofftimehour.cloneNode(true);
				temp1.id="cww-tr-"+currenttime;
			}
		}
		else {
			if(currenttime >= startworktime && currenttime < endworktime) {
				temp1 = comtemplateworktimenohour.cloneNode(true);
				temp1.id="cww-tr-"+currenttime;
			}
			else {
				temp1 = comtemplateofftimenohour.cloneNode(true);
				temp1.id="cww-tr-"+currenttime;
			}
		}
		if(currenttime==0)
		{
			for (var zaehler=0;zaehler<temp1.childNodes.length;zaehler++)
			{
				var shorttmp=temp1.childNodes[zaehler];
				var table1=shorttmp.getElementsByTagName("table");
				//var appointmentinsert=table1[0].getElementsByTagName("td")[0];
				var appointmentinsert = document.createElement("div");
				appointmentinsert.id="cww-line-"+zaehler;
				addTMPId(appointmentinsert);
				appointmentinsert.style.width="100%";
				appointmentinsert.style.height="0px";
				appointmentinsert.style.lineHeight="0px";
				appointmentinsert.style.fontSize="0pt";
				appointmentinsert.style.position="relative";
				shorttmp.insertBefore(appointmentinsert,table1[0]);
			}
		}
		mytable2tbody.appendChild(temp1);
		currenttime=currenttime+interval;
	}
	mytable2.appendChild(mytable2tbody);
	replace$(mytable2);	
	
	mytable.parentNode.replaceChild(mytable2,mytable);
	mytable=$("cwwtimecontent");
	calendarhovers["daywwcustom2"]=new Hover(mytable,OXAppointmentHover.getContent().node);
	calendarhovers["daywwcustom2"].setSize(OXAppointmentHover.contentobject.node);
	calendarhovers["daywwcustom2"].getTarget = function (node) {
		try {
            while (node) {
                if (node.oxcalobj) return node.parentNode ? node : 0;
                node = node.parentNode;
            }
        } catch (e) { /*see default implementation*/ }
	}
	calendarhovers["daywwcustom2"].onShow = function (node) {
		OXAppointmentHover.actualHover=this;
		var splitid=node.oxcalobj.split("-");
		OXAppointmentHover.refillContent(splitid[1],splitid[0],splitid[2]);	
	}
	
	cwwwresizeHeader();
    wwline = (temp1.offsetTop + temp1.offsetHeight) / numOfLines;
}

function cwwwresizeHeader() {
	$("cwwheaderresize").style.width = cww_maxShownFD <= 5 ? $("cwwcontentresize").offsetWidth + "px" : $("cwwtimecontentall").offsetWidth + "px";
	$("cwwheaderresize").style.overflowY = cww_maxShownFD <= 5 ? "hidden" : "scroll";
}

var cww_maxShownFD = 0;
function cwwresizeTopHeader() {
	var tmpMax = 0;
	// iterate through curr whole day apps and check if something changed
	// from previous view to current view
	for (var i=0; i<cwwdaysfull.length; i++) {
		if (cwwdaysfull[i].node.childNodes.length > tmpMax) {
			tmpMax = cwwdaysfull[i].node.childNodes.length;			
		}
	}
	// has something changed? if yes, resize the header
	if (tmpMax != cww_maxShownFD) {
		var size = tmpMax <= 1 ? 62 : ((tmpMax > 5 ? 5 : tmpMax) * 20) + 40;		
		resizeSplit("cwwheader_top", size + "px");
		cww_maxShownFD = tmpMax;
	}	
}

/* Create TimeLine */
function createNewTimeLine(interval) {
	$("cwwcontentresize").className = "interval" + (interval/60000);
	var template5min=$("cww_timeline_minutes5_template");
	var time5min = 1000*60*5;
	var template15min=$("cww_timeline_minutes15_template");
	var time15min = time5min*3;
	var template60min=$("cww_timeline_onehour_template");
	var time60min = time15min*4;
	var templateonehourcomplete;
	var node=$("cww_timeline");
	var node2=node.cloneNode(false);
	removeChildNodes(node2);
	var nodetbody=document.createElement("tbody");
	var templateonehourcomplete = new Array();
	var currenttime=0;
	var hourzaehler=0;
	var completetime=1000*60*60; //Zeit einer Stunde
	var rowsperhour=Math.round(time60min/interval);
	for(;currenttime<completetime;) {
		var tmp;
		var modulo=currenttime % time15min;
		if((currenttime % time15min == 0)) 
		{
			if((currenttime % time60min == 0)) 
			{
				tmp=template60min.cloneNode("true");
				if(rowsperhour>1) 
				{
					var bigtext=tmp.getElementsByTagName("td")[0];
					//bigtext.setAttribute("rowspan",rowsperhour);
					bigtext.rowSpan=rowsperhour;
				}
			}
			else  
			{
				tmp=template15min.cloneNode("true");
				tmp.id="T"+currenttime;
				var smalltext=tmp.getElementsByTagName("td")[0];
				if(interval<time15min) 
				{
					var minutes=currenttime / (1000*60);
					smalltext.firstChild.nodeValue=""+minutes; 
				}
			}
		}
		else 
		{
			tmp=template5min.cloneNode("true");
			tmp.id="T"+currenttime;
		}
		templateonehourcomplete.push(tmp);
		currenttime=currenttime+interval;
	}

	/*** Create TimeLine ***/

	for(i=0;i<24;i++)
	{
		for(var zaehler=0;zaehler<templateonehourcomplete.length;zaehler++)
		{
			var myelement=templateonehourcomplete[zaehler].cloneNode(true);
			if(zaehler==0)
			{
				var d1 = new Date(i * 36e5); // ms/h
				if(interval>=time60min)
				{
					myelement.getElementsByTagName("td")[0].style.fontSize="0pt"
					myelement.getElementsByTagName("td")[1].firstChild.nodeValue =formatDate(d1, "hour");
				}			
				else
				{
					myelement.getElementsByTagName("td")[0].firstChild.nodeValue = formatDate(d1, "prefix");
					myelement.getElementsByTagName("td")[1].firstChild.nodeValue = formatDate(d1, "suffix");
				}
			}
			myelement.id="cwwtimeline_"+((i*time60min)+((zaehler*interval) % time60min));
			if(i==23 && (zaehler+1) == templateonehourcomplete.length)	{
				//TODO: BORDER BOTTOM
			}
			nodetbody.appendChild(myelement);
		}
		
	}
	node2.appendChild(nodetbody);
	replace$(node2);
	node.parentNode.replaceChild(node2,node);
	
}
var scrollit=false;
var scrolltimeoutww;
function getDragandDropPointWholeDay(e) {
	var node = e.currentTarget || e.srcElement || false;
	var myday=node.id.split(":")[1];
	if(myday) {
		myday=parseInt(myday);
		return new Date(Date.UTC(cwwactualday.getUTCFullYear(),cwwactualday.getUTCMonth(),cwwactualday.getUTCDate()+myday,0,0,0));	
	}
}
function getDragandDropPoint(e) {
	var coreelement=$("cwwtimecontent");
	var scrollposition= $("cwwtimecontentall").scrollTop;
	var posx=getAbsolutePositionLeft(coreelement);
	var posy=getAbsolutePositionTop(coreelement);
	var poscontent=e.clientY-getAbsolutePositionTop(coreelement)-scrollposition;
	var posheight= $("cwwtimecontentall").offsetHeight;
	var fieldposx=e.clientX-posx;
	var fieldposy=e.clientY-posy;
	if(fieldposx<0 || fieldposx>coreelement.offsetWidth) {
		return null;
	}
	if(fieldposy<0 || fieldposy>coreelement.offsetHeight) {
		return null;
	}
	if(poscontent<40 && $("cwwtimecontentall").scrollTop>0) {
		if(!scrollit) {
			function scrollworkweekup() {
				var newscroll=scrollposition-80;
				if(newscroll>0) {
					$("cwwtimecontentall").scrollTop=newscroll;
				} else {
					$("cwwtimecontentall").scrollTop=0;
				}
				scrollit=false;
			}
			scrolltimeoutww=setTimeout(scrollworkweekup,100);
		}
		scrollit=true;
	} 
	else if((posheight-poscontent)<40 && $("cwwtimecontentall").scrollTop<coreelement.offsetHeight-posheight) {
		if(!scrollit) {
			function scrollworkweekdown() {
				var newscroll=scrollposition+80;
				if(newscroll<coreelement.offsetHeight-posheight) {
					$("cwwtimecontentall").scrollTop=newscroll;
				} else {
					$("cwwtimecontentall").scrollTop=coreelement.offsetHeight-posheight;
				}
				scrollit=false;
			}
			scrolltimeoutww=setTimeout(scrollworkweekdown,100);
		}
		scrollit=true;
	} 
	var daylength=coreelement.offsetWidth/cwwdaysinweek;
	var day=Math.floor(fieldposx/daylength);
	var intervalcount=Math.floor(fieldposy/wwline)*configGetKey("gui.calendar.interval")*60000;
	var mydate=new Date(intervalcount);
	return new Date(Date.UTC(cwwactualday.getUTCFullYear(),cwwactualday.getUTCMonth(),cwwactualday.getUTCDate()+day,mydate.getUTCHours(),mydate.getUTCMinutes(),0));
	 
}
var cww_lastdatedd;
var cww_lastdatestart;
var cww_lastdateend;
function drawpreviewnewAppointment(event,target,object,mouseposition) {
	var startdate;
	if(!mouseposition.startdate) {
		startdate = getDragandDropPoint(mouseposition);
		mouseposition.startdate=startdate;
	} else {
		startdate=mouseposition.startdate;
	}
	var enddate = getDragandDropPoint(event);
	if((startdate && enddate) && (!cww_lastdatestart || cww_lastdateend || (cww_lastdatestart.getTime() != startdate.getTime() && enddate.getTime() != enddate.getTime()))) {
		cww_lastdatestart = startdate;
		cww_lastdateend = enddate;
		if(startdate.getTime()<=enddate.getTime()) {
			createDDPreviewDivs(startdate,enddate);
		} else {
			createDDPreviewDivs(enddate,startdate);
		}
	}
}
var cww_lastdateddwholeday;
function drawpreviewDragandDropWholeDay(event,target,object) {
	stopEvent(event);
    var newdate=getDragandDropPointWholeDay(event);
	if((cww_lastdateddwholeday && !newdate) || (!cww_lastdateddwholeday && newdate) || (cww_lastdateddwholeday && newdate && (cww_lastdateddwholeday.getTime() != newdate.getTime()))) {
		cww_lastdateddwholeday = newdate;
		var starttime=object.start_date;
		var endtime=object.end_date;
		if(newdate) {
			var oneday=1000*60*60*24;
			var changes=newdate.getTime()-starttime.getTime();
			starttime=new Date(starttime.getTime()+changes);
			endtime=new Date(endtime.getTime()+changes);
			if(endtime.getTime % oneday) {
				endtime.setUTCDate(endtime.getUTCDate()+1);
			}
		}
		createDDPreviewDivsWholeDay(starttime,endtime);	
	}
}
function drawpreviewDragandDrop(event,target,object) {
    stopEvent(event);
	var newdate = getDragandDropPoint(event);
	if((cww_lastdatedd && !newdate) || (!cww_lastdatedd && newdate) || (cww_lastdatedd && newdate && (cww_lastdatedd.getTime() !=newdate.getTime()))) {
		cww_lastdatedd = newdate;
		var starttime=object.start_date;
		var endtime=object.end_date;
		var oneintervaltime=configGetKey("gui.calendar.interval")*60000;
		switch (target) {
			case "CALENDAR_BOTTOM":
				if(newdate) {
					if(newdate.getTime()<=starttime.getTime()) {
						endtime=new Date(starttime.getTime()+oneintervaltime);
					} else {
						endtime=newdate;
					}								
				}
				break;
			case "CALENDAR_TOP":
				if(newdate) {
					if(newdate.getTime()>=endtime.getTime()) {
						starttime=new Date(endtime.getTime()-oneintervaltime);
					} else {
						starttime=newdate;
					}								
				}
				break;
			case "calendar":
				if(newdate) {
					var changes=newdate.getTime()-starttime.getTime();
					starttime=new Date(starttime.getTime()+changes);
					endtime=new Date(endtime.getTime()+changes);
				}
				
				break;
			default:
				break;
		}
		createDDPreviewDivs(starttime,endtime);
	}
}
function removeDDPreviewDivs() {
	var zaehler3=0;
	while($2("cwwpreview"+zaehler3)) {
		if($2("cwwpreview"+zaehler3).parentNode) {
			$2("cwwpreview"+zaehler3).parentNode.removeChild($2("cwwpreview"+zaehler3));
		}
		removeTMPId($2("cwwpreview"+zaehler3));
		zaehler3++;
	}
	if($2("dnd_div_") != undefined) {
		body.removeChild($2("dnd_div_"));
		removeTMPId($2("dnd_div_"));
		
	}
	
}
function createDDPreviewDivsWholeDay(starttime,endtime) {
	removeDDPreviewDivs();
	var oneday=1000*60*60*24;
	var sdt=starttime.getTime();
	if(sdt<cwwactualday.getTime()) {
		sdt=new Date(cwwactualday.getTime()).getTime();
	}
	var edt=endtime.getTime();
	if(edt>cwwactualday.getTime()+cwwdaysinweek*(oneday)) {
		edt=new Date(cwwactualday.getTime()+(cwwdaysinweek*oneday)).getTime();
	}
	var sdttmp=sdt;
	var zaehler3=0;
	while(sdttmp<edt) {
		var sdd  = (new Date(sdttmp).getUTCDay()-new Date(cwwactualday.getUTCDay()) +7) % 7;
		myappointment=document.createElement("div");
		myappointment.className="dndSelectionCalendarBG dndAbsoluteSelection";
		myappointment.id="cwwpreview"+zaehler3;
		addTMPId(myappointment);
		myappointment.style.height="19px";
		myappointment.style.top="0px";
		myappointment.style.width="98%";
		var appointmentcontainer=$2("cwwheaderfull:"+sdd);
		appointmentcontainer.appendChild(myappointment);
		zaehler++;
		if(sdt==sdttmp) {
			sdttmp = Math.floor(sdttmp / oneday) * oneday;
		}
		sdttmp = sdttmp+oneday;
	}
}
function createDDPreviewDivs(starttime,endtime) {
	removeDDPreviewDivs();
	zaehler3=0;
	var oneday=1000*60*60*24;
	
	var sdt=starttime.getTime();
	if(sdt<cwwactualday.getTime()) {
		sdt=new Date(cwwactualday.getTime()).getTime();
	}
	var edt=endtime.getTime();
	if(edt>cwwactualday.getTime()+cwwdaysinweek*(oneday)) {
		edt=new Date(cwwactualday.getTime()+(cwwdaysinweek*oneday)).getTime();
	}
	var sdttmp=sdt;
	while(sdttmp<edt)
	{
		var sdd        = (new Date(sdttmp).getUTCDay()-new Date(cwwactualday.getUTCDay()) +7) % 7;
		var longstart  = (sdttmp % oneday);
        if (longstart < 0) longstart += oneday;
		var startpoint = Math.floor((longstart/globalinterval)+0.0000001);
		var edttmp     = edt;
		var longend    = (edt % oneday);
        if (longend < 0) longend += oneday;
		var endpoint   =   Math.ceil((longend/globalinterval)-0.0000001);
		// An diesem Tag nicht zu Ende
		if(Math.floor(sdttmp / oneday + 1) * oneday <= edt) {
			endpoint   = globalintervalcounts;							
		}
		if(startpoint  ==  endpoint) {
			endpoint++;
		}
		var myappointment=document.createElement("div");
		myappointment.className="dndSelectionCalendarBG dndAbsoluteSelection";
		myappointment.id="cwwpreview"+zaehler3;
		addTMPId(myappointment);
		myappointment.style.height=((endpoint-startpoint) * wwline) + "px";
		myappointment.style.top=startpoint*wwline+"px";
		myappointment.style.width="98%";
		zaehler3++
		var appointmentcontainer=cwwdays[sdd].node;
		appointmentcontainer.appendChild(myappointment);
		if(sdt==sdttmp) {
			sdttmp = Math.floor(sdttmp / oneday) * oneday;
		}
		sdttmp = sdttmp+oneday;
	}
}
function cww_saveAppointment(object,event,target,wholeday,i) {
	var myappointmentobj;
	if(!wholeday) {
		var newdate=getDragandDropPoint(event);
	} else {
		var newdate=new Date(Date.UTC(cwwactualday.getUTCFullYear(),cwwactualday.getUTCMonth(),cwwactualday.getUTCDate()+parseInt(i),0,0,0));
	}
	var starttime=object.start_date;
	var endtime=object.end_date;
	var oneintervaltime=configGetKey("gui.calendar.interval")*60000;
	switch (target) {
		case "CALENDAR_BOTTOM":
			if(newdate) {
				if(newdate.getTime()<=starttime.getTime()) {
					endtime=new Date(starttime.getTime()+oneintervaltime);
				} else {
					endtime=newdate;
				}								
			}
			break;
		case "CALENDAR_TOP":
			if(newdate) {
				if(newdate.getTime()>=endtime.getTime()) {
					starttime=new Date(endtime.getTime()-oneintervaltime);
				} else {
					starttime=newdate;
				}								
			}
			break;
		case "calendar":
			if(newdate) {
				var changes=newdate.getTime()-starttime.getTime();
				starttime=new Date(starttime.getTime()+changes);
				endtime=new Date(endtime.getTime()+changes);
				if(wholeday) {
					var oneday=1000*60*60*24;
					if(endtime.getTime() % oneday) {
						endtime.setUTCDate(endtime.getUTCDate()+1);
					}
				}
			}
			break;
	}
	if((starttime.getTime() == object.start_date.getTime()) && (endtime.getTime() == object.end_date.getTime())) {
		removeDDPreviewDivs();
		return;
	}
	if(!wholeday) {
		wholeday=false;
	}
	myappointmentobj = { start_date : starttime.getTime(), end_date : endtime.getTime(), full_time: wholeday };
	editAppointment(object,myappointmentobj);
	removeDDPreviewDivs();
}

function cww_createAppointment(object,event,type,mouseposition,cb) {
	if(!object) {
		object=new Object();
	} 
	if(!object.folder_id) {
		object.folder_id=activefolder;
	}
	var startdate;
	if(!mouseposition.startdate) {
		startdate = getDragandDropPoint(mouseposition);
		mouseposition.startdate=startdate;
	} else {
		startdate=mouseposition.startdate;
	}
	var enddate = getDragandDropPoint(event);
	if(startdate && enddate) {
		if(startdate.getTime() <= enddate.getTime()) {
			object.start_date=startdate.getTime();
			object.end_date=enddate.getTime();
		} else {
			object.end_date=startdate.getTime();
			object.start_date=enddate.getTime();
		}
		removeDDPreviewDivs();
		if(configGetKey("gui.calendar.openpopup")) {
			openNewAppointmentWindow(object);
		} else {
			if(object.end_date!=object.start_date) {
				setTimeout(function (){openImplaceEdit(object,cb);},0);
			}
		}
	}
}
function openImplaceEdit(object,cb) {
	removeDDPreviewDivs();
	if(cb) cb(object);
}
function createPreviewNewAppointmentWW(object) {
	function dounregister() {
		removeDDPreviewDivs();
		unregister("OX_Dummy",dounregister);
	}
	zaehler3=0;
	var oneday=1000*60*60*24;
	var sdt=object.start_date;
	if(sdt<cwwactualday.getTime()) {
		sdt=new Date(cwwactualday.getTime()).getTime();
	}
	var edt=object.end_date;
	if(edt>cwwactualday.getTime()+cwwdaysinweek*(oneday)) {
		edt=new Date(cwwactualday.getTime()+(cwwdaysinweek*oneday)).getTime();
	}
	var sdttmp=sdt;
	while(sdttmp<edt)
	{
		var sdd        = (new Date(sdttmp).getUTCDay()-new Date(cwwactualday.getUTCDay()) +7) % 7;
		var longstart  = (sdttmp % oneday);
        if (longstart < 0) longstart += oneday;
		var startpoint = Math.floor((longstart/globalinterval)+0.0000001);
		var edttmp     = edt;
		var longend    = (edt % oneday);
        if (longend < 0) longend += oneday;
		var endpoint   =   Math.ceil((longend/globalinterval)-0.0000001);
		// An diesem Tag nicht zu Ende
		if(Math.floor(sdttmp / oneday + 1) * oneday <= edt) {
			endpoint   = globalintervalcounts;							
		}
		if(startpoint  ==  endpoint) {
			endpoint++;
		}
		var myappointment=$("cww_appointment_template").cloneNode(true);
		myappointment.id="cwwpreview"+zaehler3;
		addTMPId(myappointment);
		var appointmentcontainer=cwwdays[sdd].node;
		var tds = myappointment.getElementsByTagName("td");					
		tds[0].className="appointmentShowAsReserved";
		tds[2].getElementsByTagName("div")[0].firstChild.data = "tre";
		tds[3].getElementsByTagName("img")[0].style.display = "none";
		tds[3].getElementsByTagName("img")[1].style.display = "none";
		tds[3].getElementsByTagName("img")[2].style.display = "none";
		tds[3].getElementsByTagName("img")[3].style.display = "none";
		myappointment.style.height=((endpoint-startpoint) * wwline) + "px";
		myappointment.getElementsByTagName("div")[1].style.height = (((endpoint-startpoint) * wwline)-4) + "px";
		myappointment.style.top=startpoint*wwline+"px";		
		myappointment.style.width="98%";
		appointmentcontainer.appendChild(myappointment);					
		
		if(sdt==sdttmp) {
			sdttmp = Math.floor(sdttmp / oneday) * oneday;
		}
		sdttmp = sdttmp+oneday;
		zaehler3++;
	}
	var implElem=$2("cwwpreview0");
	var oInplEdit  = new inplaceEdit(implElem.getElementsByTagName("div")[2], _("New appointment"), function (sStr,oObj){
			object.title=sStr;
			createAppointment(object);
			removeDDPreviewDivs();
			storageCache.update();
 	});		
 	oInplEdit.really_edit_check = false;
 	oInplEdit.style.color = "#000000";
 	oInplEdit.style.fontSize = "8pt";
 	oInplEdit.style.height = "1.2em";
	oInplEdit.on();
	register("OX_Dummy",dounregister);
}

function editAppointment(obj, changes, callback) {
	// copy important data
	var app = {
		id: obj.id,
		folder_id: obj.folder_id,
		recurrence_id: obj.recurrence_id,
		recurrence_position: obj.recurrence_position,
		recurrence_type: obj.recurrence_type
	};
	// start & end data
	if (typeof obj.start_date != "undefined") { app.start_date = obj.start_date.getTime(); }
	if (typeof obj.end_date != "undefined") { app.end_date = obj.end_date.getTime(); }
	// clean up
	if (app.recurrence_position > 0 && app.id != app.recurrence_id) {
		app.recurrence_id = app.id;
		app.recurrence_position = 0;
		app.recurrence_type = 0;
	}
	// update via UI
	ox.calendar.ui.update(app, changes, callback);
}

function createAppointment(object) {
	if (!object.alarm && configContainsKey("gui.calendar.default_reminder")) {
		object.alarm = configGetKey("gui.calendar.default_reminder");
	}
	json.put(AjaxRoot + "/calendar?action=new&session=" + session, object, null, 
	function(response){
		function cbignore() {
			object.ignore_conflicts=true;
			json.put(AjaxRoot + "/calendar?action=new&session=" + session, object, null,
			function(responseinternal) {
				if(responseinternal && responseinternal.data && responseinternal.data.id) {	
					storageCache.update();	
				} 		
			});
		}
		if(response && response.data && response.data.id) {	
			storageCache.update();	
		} 
		else if(response && response.data && response.data.conflicts) {
			ConflictsPopup.open(object,response.data.conflicts,null,null,cbignore);
		}
	});
}
function openNewAppointmentWindow(object) {
	function createAppyes() {
		function myok() {
			object.title=$("create_window_text_field").value;
			createAppointment(object);
		}
		function myadvanced() {
			ox.api.calendar.compose({
				params: {
					folder: object.folder_id,
					start_date: object.start_date,
					end_date: object.end_date
				}
			});
		}
		removeDDPreviewDivs();
		newAppointmentObject(object,myok,function() {},myadvanced,null);
	}
	rightshandler.checkRights("calendar",null , object, createAppyes, function() {}); 
}

fileloaded();