define([
	"dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
	"dojo/parser", 
	"dojo/ready", 
	"dojox/calendar/Calendar",
	"dojox/calendar/Mouse",
	"dojo/_base/array",
	"dojo/when",
	"dojo/store/Memory",
	"dojo/store/Observable",
	"dojo/_base/xhr",
	"dojo/date/stamp",
	"dijit/Dialog",	
	"dijit/TooltipDialog",
    "dijit/form/TextBox",
    "dijit/form/Button",
    "dijit/form/DropDownButton",
    "dojo/dom",
	"dojo/_base/lang",
	"dojo/_base/event",
	"dojo/on", 
	"dojo/_base/window", 
	"dijit/Calendar",
	"dojo/text!./templates/Schedule.html"	
], function(declare, _WidgetBase, _TemplatedMixin, parser, ready, Calendar,Mouse,array,when,Memory,Observable,xhr,stamp,Dialog,TooltipDialog, TextBox, Button, DropDownButton, dom, lang, event, on, win, DatePicker, template) {
	return declare("chy.widget.Schedule",[_WidgetBase, _TemplatedMixin], {
		//properties
		templateString: template,
		activeSchedules: [],
		
		//constructor
		constructor: function(args){
			this.inherited(arguments);
			console.log("Load Schedules",args);
			declare.safeMixin(this,args);			
									
			this.cal_data=[];	
			this.cal_store=new Observable(new Memory({data: this.cal_data}));
			
			/* Override from calendar/Mouse.js so ie doesn't focus on div and scrolls during  Mousedown event */	    
			lang.extend(Mouse,{
			   _rendererMouseDownHandler: function(e, renderer){
					event.stop(e);							
					var item = renderer.item._item;
					this.selectFromEvent(e, item, renderer, true);	
				},
				_onRendererHandleMouseDown: function(e, renderer, editKind){
					event.stop(e);									
					this.showFocus = false;					
					var ritem = renderer.item;
					var item = ritem.item;					
					if(!this.isItemBeingEdited(item)){
						if(this._isEditing){								
							this._endItemEditing("mouse", false);								
						}
						this.selectFromEvent(e, renderer.item._item, renderer, true);
						this._edProps = {
							editKind: editKind,
							editedItem: item,
							rendererKind: renderer.rendererKind,
							tempEditedItem: item,					
							liveLayout: this.liveLayout				
						};									
						this.set("focusedItem", this._edProps.editedItem);	
					}																								
					var handles = [];
					handles.push(on(win.doc, "mouseup", lang.hitch(this, this._editingMouseUpHandler)));
					handles.push(on(win.doc, "mousemove", lang.hitch(this, this._editingMouseMoveHandler)));
					var p = this._edProps;
					p.handles = handles;
					p.eventSource = "mouse";
					p.editKind = editKind;					
					this._startPoint = {x: e.screenX, y: e.screenY};												
				}
			});
		},
		
		postCreate:function(){
			this.inherited(arguments);
			var _this = this;
			
			//set store for calendar
			this.calendar = new Calendar({
				dateInterval: this.view,
				startTimeAttr:'startTime',
				endTimeAttr:'endTime',
				allDayAttr:'allDay',
				date: new Date(),
				editable: true,
				cal_store: _this.cal_store,
				columnView: {
					minHours:0,
					maxHours:24
					},
				style:this.style,
				columnViewProps:{
					timeSlotDuration: 15,
					minHours: 8,
					maxHours: 20,
					hourSize: _this.hourSize
				},
				cssClassFunc: function(item){
					return item.calendar;
				},
				isItemEditable: function(item){
					if(typeof item == "undefined"){
						return true;
					}
					return !_this.cal_store.query({id:item.id})[0].readonly;
				},
				isItemResizeEnabled: function(item, rendererKind){
					return !_this.cal_store.query({id:item.id})[0].readonly;
				},
				isItemMoveEnabled: function(item, rendererKind){
					return !_this.cal_store.query({id:item.id})[0].readonly;
				},
				query: function(item){
					return array.indexOf(_this.activeSchedules,item.calendar) != -1;
				},
				toggle: function(calendar){
					var i = _this.activeSchedules.indexOf(calendar);
					if(i != -1) {
						_this.activeSchedules.splice(i, 1);
					} else {
						_this.activeSchedules.push(calendar);
					}
					array.forEach(_this.cal_data,function(item){
						_this.cal_store.notify(item,item.id);
					});
				},
				todayButtonClick: function(){
					this.set("date", this.floorToDay(new this.dateClassObj(), true));
				},
				setDate: function(date){
					this.set("date", date);
				}
			},this.id+'_calendar');
			
			this.calendar.set('store',this.cal_store);
		
			this.calendar.startup();

			this.calendar.on("itemEditEnd",function(e){
				console.log("edit end",e);
				xhr("POST", {
					url: "cheyenne?cddid="+e.storeItem.dialog,
					content:{
						id: e.storeItem.realid,
						date_from: stamp.toISOString(e.item.startTime),
						date_to: stamp.toISOString(e.item.endTime)
					},
					handleAs: "text",
					error: function(error){console.error("Cthulhu",error);}
				}).then(function(data){	
					e.item.dirty=false;					
				});
			});
			
			this.calendar.on("itemClick", function(e){
				console.log("item click",e);
				var href="cheyenne?cddid=xam.instance_addedit&P_CONTEXT_CODE="+e.item.contextcode+"&P_INSTANCE_ID=" + e.item.realid + "&P_READONLY="+ e.item.readonly +"&P_NAV_ID=&P_TASK_ID=&cmode=kpwindow_dialogborder_overlay";
				KPWindowLoad(href,"kpwindowoverlay","kpwindowoverlay");
			});
					
			array.forEach(this.schedule,function(scheduleitem){
				console.log("scheduleitem",scheduleitem);
				//haal data
				var results = xhr("GET", {
					url: "cheyenne?cddid="+scheduleitem.dialog+"&cmode=json&P_CONTEXT_CODE="+scheduleitem.contextcode,
					handleAs: "json",
					error: function(error){console.error("Cthulhu",error);}
				}).then(function(result){
					array.forEach(result.item,function(item){
						var cal_item={
							realid: item.id,
							summary: item.name + " - " + item.desc,
							desc: item.desc,
							startTime: new Date(item.date_from),
							endTime: new Date(item.date_to),
							calendar: scheduleitem.cssclass,
							readonly: item.readonly,
							contextcode: scheduleitem.contextcode,
							dialog: scheduleitem.dialog
						};
						_this.cal_store.add(cal_item);
						if(array.indexOf(_this.activeSchedules,scheduleitem.cssclass) == -1){
							_this.activeSchedules.push(scheduleitem.cssclass);
						}
					});
				});
			});
			
			var myDialog = new TooltipDialog({
				content:
					'<div data-dojo-type="dijit/Calendar"><script type="dojo/method" data-dojo-event="onChange" data-dojo-args="value">'+
						'require(["dojo/dom", "dojo/date/locale"], function(dom, locale){'+
							'dijit.byId("'+this.id+'_calendar").setDate(value);'+
						'});'+
					'</script></div>'
			});

			var myButton = new DropDownButton({
				label: '<img src="dojo/dojo-release-1.10.4/dijit/themes/nihilo/images/treeExpand_loading.gif"/>',
				dropDown: myDialog
			});
			dom.byId("dropDownButtonContainer").appendChild(myButton.domNode);
			myButton.startup();			
		},

		onStart: function(){
			this.inherited(arguments);
		},
		
		destroy:function(){
			this.inherited(arguments);
			this.calendar.destroy();
		}
	});
});	
