var lessonplansToHandle = new Object({
	textsToHandle: [],
	gridsToHandle: []
});
var daysofweek = Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
var assignmentStore = new Ext.data.MotherStore({
	url: 'teacher_tools/lessonplans_data.json.php',
	baseParams: {
		command: 'assignments'
	},
	reader: new Ext.data.JsonReader({
		root: 'assignments'
	}, [{
		name: 'assignment'
	},
	{
		name: 'assignmentdue'
	},
	{
		name: 'plandate'
	},
	{
		name: 'id'
	}]),
	autoLoad: false,
	autoSave: true,
	writer: new Ext.data.JsonWriter({
		writeAllFields: true
	}),
	resetFilters: function() {
		aDate = (new Date(this.baseParams.weekof)).add(Date.DAY, -3);
		this.childStores[0].setFilter('plandate', aDate.format('m/d/Y'));
		aDate = aDate.add(Date.DAY, 3);
		for (i = 1; i <= 5; i++) {
			this.childStores[i].setFilter('plandate', aDate.format('m/d/Y'));
			aDate = aDate.add(Date.DAY, 1);
		}
		aDate = aDate.add(Date.DAY, 2);
		this.childStores[6].setFilter('plandate', aDate.format('m/d/Y'));
	},
	listeners: {
		beforeload: function() {
			this.resetFilters();
		},
		beforesave: function() {}
	}
});
var lessonplanEditor = function(config) {
	lessonplanEditor.superclass.constructor.call(this, {
		border: false,
		id: config.day + '_lpbox',
		tbar: new Ext.Toolbar({
			layout: 'hbox',
			items: [{
				xtype: 'container',
				flex: 0.5,
				items: [{
					xtype: 'button',
					iconCls: 'arrow_left_blue',
					cls: 'floatLeft',
					day: config.day,
					tooltip: 'Move lesson plan back a day',
					listeners: {
						click: function(b) { //move Plan Back
							var today = b.day,
								yesterday = daysofweek.indexOf(today) > 0 ? daysofweek[daysofweek.indexOf(today) - 1] : "last Friday";
							var txtToday = Ext.getCmp(today + 'LP'),
								txtYesterday = Ext.getCmp(yesterday + 'LP');
							recs = Ext.getCmp(today + 'LP_grid').store.data.items;
							yesterdayStore = Ext.getCmp(yesterday + 'LP_grid').store;
							todayStore = Ext.getCmp(today + 'LP_grid').store;
							recsYesterday = yesterdayStore.data.items;
							if (txtToday.getValue() || recs.length > 0) {
								if (txtYesterday.getValue() || recsYesterday.length > 0) {
									Ext.Msg.show({
										title: 'Overwrite ' + yesterday + '?',
										msg: 'Moving ' + today + "'s lesson plans to " + yesterday + ' will overwrite ' + yesterday + "'s lesson plans. Are you sure you want to continue?",
										buttons: Ext.Msg.YESNO,
										icon: Ext.MessageBox.WARNING,
										fn: function(btn) {
											if (btn == 'yes') {
												Ext.getCmp('lessonplans-panel').moveDay(todayStore.filterValue, yesterdayStore.filterValue);
											}
										}
									});
								} else {
									Ext.getCmp('lessonplans-panel').moveDay(todayStore.filterValue, yesterdayStore.filterValue);
								}
							}
						}
					}
				}]
			},
			{
				xtype: 'label',
				html: '<span class="lpDayHeader">' + config.day + '</span>'
			},
			{
				xtype: 'container',
				flex: 0.5,
				items: [{
					xtype: 'button',
					cls: 'floatRight',
					iconCls: 'arrow_right_blue',
					day: config.day,
					tooltip: 'Move lesson plan forward a day',
					listeners: {
						click: function(b) { //move Plan Forward
							var today = b.day,
								tomorrow = daysofweek.indexOf(today) < 4 ? daysofweek[daysofweek.indexOf(today) + 1] : "next Monday";
							var txtToday = Ext.getCmp(today + 'LP'),
								txtTomorrow = Ext.getCmp(tomorrow + 'LP');
							tomorrowStore = Ext.getCmp(tomorrow + 'LP_grid').store;
							todayStore = Ext.getCmp(today + 'LP_grid').store;
							recs = Ext.getCmp(today + 'LP_grid').store.data.items;
							recsTomorrow = tomorrowStore.data.items;
							if (txtToday.getValue() || recs.length > 0) {
								if (!txtTomorrow.getValue() && recsTomorrow.length == 0) {
									Ext.getCmp('lessonplans-panel').moveDay(todayStore.filterValue, tomorrowStore.filterValue);
								} else {
									Ext.Msg.show({
										title: 'Overwrite ' + tomorrow + '?',
										msg: 'Moving ' + today + "'s lesson plans to " + tomorrow + ' will overwrite ' + tomorrow + "'s lesson plans. Are you sure you want to continue?",
										buttons: Ext.Msg.YESNO,
										icon: Ext.MessageBox.WARNING,
										fn: function(btn) {
											if (btn == 'yes') {
												Ext.getCmp('lessonplans-panel').moveDay(todayStore.filterValue, tomorrowStore.filterValue);
											}
										}
									});
								}
							}
						}
					}
				}]
			}]
		}),
		items: [{
			xtype: "textarea",
			style: {
				border: 'none',
				padding: '5px'
			},
			hideLabel: true,
			day: config.day,
			name: config.day + "LP",
			id: config.day + "LP",
			anchor: "100% 100%",
			emptyText: "Type your lesson plan here",
			border: false,
			disabled: true,
			listeners: {
				change: function(textarea, newValue, oldValue) {
					var curDate = textarea.plandate.format('m/d/Y');
					var index = lessonPlans.store.find('plandate', curDate);
					var record = lessonPlans.store.getAt(index);
					if (record != undefined) {
						record.set('plan', newValue);
					} else { //new record
						dayFullName = this.day.split(' ');
						dayName = dayFullName[dayFullName.length - 1];
						dayAbr = dayName.substring(0, (dayName != "Thursday") ? 1 : 2);
						var lPRecord = Ext.data.Record.create(lessonPlans.store.fields.items);
						var newRecord = new lPRecord({
							plan: newValue,
							plandate: curDate,
							usethislp: true,
							day: dayAbr
						});
						lessonPlans.store.add(newRecord);
					}
				},
				render: function(textarea) {
					this.dropZone = new Ext.dd.DropZone(this.el, {
						ddGroup: 'masterplans',
						notifyOver: function() {
							return this.dropAllowed;
						},
						notifyDrop: function(source, e, data) {
							existingPlan = textarea.getValue();
							if (existingPlan != '' && existingPlan != data.draggedRecord.data.plan) {
								Ext.Msg.show({
									title: 'Overwrite ' + textarea.day + '?',
									msg: 'Assigning a masterplan to ' + textarea.day + ' will overwrite the existing lesson plan. Are you sure you want to continue?',
									buttons: Ext.Msg.YESNO,
									icon: Ext.MessageBox.WARNING,
									fn: function(btn) {
										if (btn == 'yes') {
											textarea.fireEvent('change', textarea, data.draggedRecord.data.plan, textarea.getValue());
											textarea.setValue(data.draggedRecord.data.plan);
										}
									}
								});
							} else {
								textarea.fireEvent('change', textarea, data.draggedRecord.data.plan, textarea.getValue());
								textarea.setValue(data.draggedRecord.data.plan);
							}
						}
					});
				}
			}
		}]
	});
	lessonplansToHandle.textsToHandle.push(this.items.items[0]);
}
Ext.extend(lessonplanEditor, Ext.form.FormPanel);
var lessonplanAssignments = function(config) {
	lessonplanAssignments.superclass.constructor.call(this, {
		border: false,
		bodyStyle: (config.bodyStyle != undefined) ? config.bodyStyle : "border-left: 1px solid #99bbe8; ",
		flex: (config.day.match(/ /gi) ? 0 : 1),
		// "next monday" and "last friday"
		hidden: (config.day.match(/ /gi) ? true : false),
		// "next monday" and "last friday"
		layout: 'fit',
		items: new lessonplansAssignmentsGrid(config.day, assignmentStore)
	});
	lessonplansToHandle.gridsToHandle.push(this.items.items[0]);
}
Ext.extend(lessonplanAssignments, Ext.Panel);

var lessonPlans = {
	id: 'lessonplans-panel',
	layout: "border",
	border: false,
	hideMode: 'offsets',
	items: [{
		border: true,
		region: "center",
		title: "Lesson Plans",
		layout: 'hbox',
		layoutConfig: {
			align: 'stretch',
			pack: 'start'
		},
		tools: [{
			id: 'help',
			handler: function(btn) {
				helppopup.loadHelpFile("Lesson Plans", 500, 455);
			}
		}],
		tbar: [{
			xtype: 'label',
			text: 'Course:'
		},
		{
			xtype: 'tbspacer',
			width: 5
		},
		new SchoolDynamics.coursesCombo({
			id: 'lessonplan_course',
			listeners: {
				select: function(combo, record, index) {
					lpstore = this.ownerCt.ownerCt.ownerCt.store;
					lpstore.baseParams.courseid = SchoolDynamics.currentCourseID = record.data.courseid;
					lpstore.load();
					assignStore = this.ownerCt.ownerCt.ownerCt.assignStore;
					assignStore.baseParams.courseid = record.data.courseid;
					assignStore.load();
					masterPlanList = Ext.getCmp('masterplanList');
					masterPlanList.store.filterBy(function(rec) {
						return rec.data.courseid == record.data.courseid;
					}, this);
					masterPlanList.store.currCourseID = record.data.courseid;
				}
			}
		}),
		{
			xtype: 'tbspacer',
			width: 5
		},
		{
			xtype: 'tbseparator'
		},
		{
			xtype: 'tbspacer',
			width: 5
		},
		{
			xtype: 'label',
			text: 'Week:'
		},
		{
			xtype: 'tbspacer',
			width: 5
		},
		new SchoolDynamics.weekofDatefield({
			id: 'lessonplan_weekof',
			listeners: {
				change: function(datefield, newValue, oldValue) {
					lpstore = this.ownerCt.ownerCt.ownerCt.store;
					lpstore.baseParams.weekof = getWeekOf(newValue);
					assignStore = this.ownerCt.ownerCt.ownerCt.assignStore;
					assignStore.baseParams.weekof = getWeekOf(newValue);
					assignStore.baseParams.fromdate = new Date(assignStore.baseParams.weekof).add(Date.DAY, -3).format('m/d/Y');
					assignStore.baseParams.todate = new Date(assignStore.baseParams.weekof).add(Date.DAY, 7).format('m/d/Y');
					if (Ext.getCmp('lessonplan_course').getValue() != '') {
						lpstore.load();
						assignStore.load();
					}
				}
			}
		}),
		{
			xtype: 'tbspacer',
			width: 5
		},
		{
			xtype: 'tbseparator'
		},
		{
			xtype: 'tbspacer',
			width: 5
		},
		{
			xtype: 'button',
			text: 'Retrieve lesson plans',
			iconCls: 'table_replace',
			listeners: {
				click: function(button) {
					jsLoader.load('teacher_tools/' + modulizerPath + '/lessonplans_retrieve_module.js');
					jsLoader.loadedCall(function() {
						lessonplansRetrievePopup.show();
					});
				}
			}
		}],
		//daily lesson plan editors
		defaults: {
			border: false,
			cls: 'lpDayEditor',
			flex: 1,
			lessonplans: lessonPlans
		},
		items: [{
			hidden: true,
			flex: 0,
			items: new lessonplanEditor({
				day: 'last Friday'
			}, this.lessonplans)
		},
		{
			cls: null,
			items: new lessonplanEditor({
				day: 'Monday'
			}, this.lessonplans)
		},
		{
			items: new lessonplanEditor({
				day: 'Tuesday'
			}, this.lessonplans)
		},
		{
			items: new lessonplanEditor({
				day: 'Wednesday'
			}, this.lessonplans)
		},
		{
			items: new lessonplanEditor({
				day: 'Thursday'
			}, this.lessonplans)
		},
		{
			items: new lessonplanEditor({
				day: 'Friday'
			}, this.lessonplans)
		},
		{
			hidden: true,
			flex: 0,
			items: new lessonplanEditor({
				day: 'next Monday'
			}, this.lessonplans)
		}]
	},
	{
		region: "south",
		title: "Assignments",
		height: 150,
		split: true,
		border: true,
		layout: 'hbox',
		layoutConfig: {
			align: 'stretch',
			pack: 'start'
		},
		//assignment grids
		items: [new lessonplanAssignments({
			day: 'last Friday'
		}, this), new lessonplanAssignments({
			bodyStyle: '',
			day: 'Monday'
		}, this), new lessonplanAssignments({
			day: 'Tuesday'
		}, this), new lessonplanAssignments({
			day: 'Wednesday'
		}, this), new lessonplanAssignments({
			day: 'Thursday'
		}, this), new lessonplanAssignments({
			day: 'Friday'
		}, this), new lessonplanAssignments({
			day: 'next Monday'
		}, this)]
	}],
	assignStore: assignmentStore,
	store: new Ext.data.Store({
		url: 'teacher_tools/lessonplans_data.json.php',
		baseParams: {
			command: 'getLessonPlans'
		},
		reader: new Ext.data.JsonReader({
			root: 'lessonplans'
		}, [{
			name: 'id'
		},
		{
			name: 'plandate'
		},
		{
			name: 'day'
		},
		{
			name: 'plan'
		}]),
		autoLoad: false,
		writer: new Ext.data.JsonWriter({
			writeAllFields: true
		}),
		listeners: {
			beforeload: function(store, options) { //only make a server call when all baseparams are set
				lessonPlans.resetInputs();
				return (store.baseParams.courseid != undefined && store.baseParams.weekof != undefined);
			},
			load: function(store, records, options) {
				var today = new Date(store.baseParams.weekof);
				var currDOW, day;
				for (var i = 0, len = records.length; i < len; i++) {
					var rec = records[i].data;
					var plandate = new Date(rec.plandate);
					switch (rec.day) {
					case 'M':
						currDOW = new Date(today.add(Date.DAY, 7)); //next Monday
						if (currDOW.format('m/d/Y') == plandate.format('m/d/Y')) {
							day = 'next Monday';
						} else {
							currDOW = new Date(today.add(Date.DAY, 0));
							day = daysofweek[0];
						}
						break;
					case 'T':
						day = daysofweek[1];
						currDOW = new Date(today.add(Date.DAY, 1));
						break;
					case 'W':
						day = daysofweek[2];
						currDOW = new Date(today.add(Date.DAY, 2));
						break;
					case 'Th':
						day = daysofweek[3];
						currDOW = new Date(today.add(Date.DAY, 3));
						break;
					case 'F':
						currDOW = new Date(today.add(Date.DAY, -3)); //last friday
						if (currDOW.format('m/d/Y') == plandate.format('m/d/Y')) {
							day = 'last Friday';
						} else {
							currDOW = new Date(today.add(Date.DAY, 4));
							day = daysofweek[4];
						}
						break;
					default:
						//do nothing
					}
					if (currDOW.format('m/d/Y') == plandate.format('m/d/Y')) { //load currDOW's plan
						Ext.getCmp(day + 'LP').setValue(rec.plan); /*                  //load currDOW's assignment grid                  var g = Ext.getCmp(day+'LP_grid');                  g.lplanid = rec.lplanid;                  g.plandate = rec.plandate;                  g.store.loadData( new Array( new Array(rec.assignmenttype, rec.assignment,  rec.assignmentdue) ), true );       */
					}
				}
			}
		}
	}),
	//Lesson Plan functions
	resetInputs: function() { //prep fields for new data
		for (i = 0, len = daysofweek.length; i < len; i++) {
			editorid = daysofweek[i] + 'LP';
			gridid = daysofweek[i] + 'LP_grid';
			Ext.getCmp(editorid).enable();
			Ext.getCmp(editorid).reset();
			Ext.getCmp(editorid).plandate = new Date(Ext.getCmp('lessonplan_weekof').value).add(Date.DAY, i);
			Ext.each(Ext.getCmp(gridid).getTopToolbar().items.items, function(btn) {
				btn.enable();
			});
			Ext.getCmp(gridid).store.removeAll(false, true);
		}
		Ext.getCmp('last FridayLP').enable();
		Ext.getCmp('last FridayLP').reset();
		Ext.getCmp('last FridayLP').plandate = new Date(Ext.getCmp('lessonplan_weekof').value).add(Date.DAY, -3);
		Ext.each(Ext.getCmp('last FridayLP_grid').getTopToolbar().items.items, function(btn) {
			btn.enable();
		});
		Ext.getCmp('last FridayLP_grid').store.removeAll(false, true);
		Ext.getCmp('next MondayLP').enable();
		Ext.getCmp('next MondayLP').reset();
		Ext.getCmp('next MondayLP').plandate = new Date(Ext.getCmp('lessonplan_weekof').value).add(Date.DAY, 7);
		Ext.each(Ext.getCmp('next MondayLP_grid').getTopToolbar().items.items, function(btn) {
			btn.enable();
		});
		Ext.getCmp('next MondayLP_grid').store.removeAll(false, true);
	},
	moveLeft: function(txtYesterday, txtToday, recs) {
		txtYesterday.setValue(txtToday.getValue());
		txtToday.setValue(null);
		for (i = 0; i < recs.length; i++) {
			nextDay = new Date(recs[i].data.plandate).add(Date.DAY, -1);
			if (nextDay.format('D') == "Sun") {
				nextDay = nextDay.add(Date.DAY, -2);
			}
			recs[i].beginEdit();
			recs[i].set('plandate', nextDay.format('m/d/Y'));
			recID = nextDay.format('m/d/Y') + '-HW' + (i + 1);
			recs[i].set('id', recID);
			recs[i].id = recID;
			recs[i].endEdit();
		}
		assignmentStore.loadChildren();
	},
	moveRight: function(txtTomorrow, txtToday, recs) {
		txtTomorrow.setValue(txtToday.getValue());
		txtToday.setValue(null);
		for (i = 0; i < recs.length; i++) {
			nextDay = new Date(recs[i].data.plandate).add(Date.DAY, 1);
			if (nextDay.format('D') == "Sat") {
				nextDay = nextDay.add(Date.DAY, 2);
			}
			recs[i].beginEdit();
			recs[i].set('plandate', nextDay.format('m/d/Y'));
			recID = nextDay.format('m/d/Y') + '-HW' + (i + 1);
			recs[i].set('id', recID);
			recs[i].id = recID;
			recs[i].endEdit();
		}
		assignmentStore.loadChildren();
	},
	moveDay: function(fromDate, toDate) {
		Ext.Ajax.request({
			url: 'teacher_tools/lessonplans_data.json.php',
			success: function() {
				this.lessonplans.store.load();
				assignmentStore.load();
			},
			failure: function() {},
			params: {
				command: 'moveDay',
				fromdate: fromDate,
				todate: toDate,
				courseid: Ext.getCmp('lessonplan_course').getValue()
			}
		});
	},
	listeners: {
		show: function(panel) {
			var courseCombo = Ext.getCmp('lessonplan_course');
			if (courseCombo.store.find('courseid', courseCombo.getValue()) == -1 && courseCombo.getValue() != '') {
				courseCombo.clearValue();
				assignmentStore.removeAll(true);
				assignmentStore.fireEvent('datachanged', assignmentStore);
				lessonplans.store.removeAll(true);
				lessonplans.store.fireEvent('datachanged', lessonplans.store);
				for (var i = 0; i < lessonplansToHandle.gridsToHandle.length; i++) {
					lessonplansToHandle.gridsToHandle[i].store.removeAll(true);
					lessonplansToHandle.gridsToHandle[i].store.fireEvent('datachanged', lessonplansToHandle.gridsToHandle[i].store);
					lessonplansToHandle.gridsToHandle[i].getTopToolbar().items.items[0].disable();
				}
				for (var i = 0; i < lessonplansToHandle.textsToHandle.length; i++) {
					lessonplansToHandle.textsToHandle[i].reset();
					lessonplansToHandle.textsToHandle[i].disable();
				}
			}
		}
	}
}
var lessonPlansTools = {
	regionTitle: 'Lesson Plan Tools',
	defaults: {
		autoHeight: true,
		cls: 'toolbox',
		frame: true
	},
	items: [{
		title: 'Master Plan Templates',
		tools: [{
			id: 'help',
			handler: function(btn) {
				helppopup.loadHelpFile("Master Plan Templates", 500, 455);
			}
		}],
		items: [{
			xtype: 'link',
			iconCls: 'lessonplan_manage',
			text: 'Manage master plans',
			handler: function() {
				jsLoader.load('teacher_tools/' + modulizerPath + '/lessonplans_mng_module.js');
				jsLoader.loadedCall(function() {
					SD.teacherTools.lessonPlans.masterPlans.display();
				});
			}
		},
		{
			xtype: 'tbtext',
			iconCls: 'lessonplan_add',
			text: 'Assign master plan:',
			style: 'margin-bottom: 5px;'
		},
		{
			xtype: 'panel',
			cls: 'white',
			bodyStyle: 'border: 1px solid #ADC9EA',
			layout: 'form',
			items: [{
				xtype: 'listview',
				height: 100,
				id: 'masterplanList',
				store: new Ext.data.Store({
					url: 'teacher_tools/lessonplans_data.json.php',
					baseParams: {
						command: 'masterPlan',
						xaction: 'read'
					},
					reader: new Ext.data.JsonReader({
						root: 'masterPlans'
					}, [{
						name: 'id'
					},
					{
						name: 'plan'
					},
					{
						name: 'title'
					},
					{
						name: 'courseid'
					},
					{
						name: 'date'
					}]),
					autoLoad: true,
					listeners: {
						load: function() {
							this.filterBy(function(rec) {
								return this.currCourseID == rec.data.courseid;
							});
						}
					}
				}),
				multiSelect: false,
				singleSelect: true,
				emptyText: 'No masterplans to display',
				reserveScrollOffset: true,
				columns: [{
					header: 'Master Plan',
					dataIndex: 'title'
				}],
				listeners: {
					render: function(list) {
						this.dragZone = new Ext.dd.DragZone(this.innerBody, {
							ddGroup: 'masterplans',
							getDragData: function(e) { //          Use the DataView's own itemSelector (a mandatory property) to
								//          test if the mousedown is within one of the DataView's nodes.
								var sourceEl = e.getTarget(list.itemSelector, 10); //          If the mousedown is within a DataView node, clone the node to produce
								//          a ddel element for use by the drag proxy. Also add application data
								//          to the returned data object.
								if (sourceEl) {
									d = sourceEl.cloneNode(true);
									d.id = Ext.id();
									Ext.get(d).setWidth(175);
									return {
										ddel: d,
										sourceEl: sourceEl,
										repairXY: Ext.fly(sourceEl).getXY(),
										sourceStore: list.store,
										draggedRecord: list.getRecord(sourceEl)
									}
								}
							},
							getRepairXY: function() {
								return this.dragData.repairXY;
							}
						});
					}
				}
			}]
		}]
	},
	{
		title: 'Lesson Plan Shifting',
		tools: [{
			id: 'help',
			handler: function(btn) {
				helppopup.loadHelpFile("Lesson Plan Shifting", 500, 455);
			}
		}],
		items: [{
			xtype: 'link',
			iconCls: 'resultset_last',
			text: 'Shift yearly plan forward',
			handler: function() {
				Ext.Ajax.request({
					url: 'teacher_tools/lessonplans_data.json.php',
					success: function() {
						lessonPlans.store.load();
						assignmentStore.load();
					},
					failure: function() {},
					params: {
						command: 'shiftYearForward',
						courseid: Ext.getCmp('lessonplan_course').getValue()
					}
				});
			}
		},
		{
			xtype: 'link',
			iconCls: 'resultset_first',
			text: 'Shift yearly plan backward',
			handler: function() {
				Ext.Ajax.request({
					url: 'teacher_tools/lessonplans_data.json.php',
					success: function() {
						lessonPlans.store.load();
						assignmentStore.load();
					},
					failure: function() {},
					params: {
						command: 'shiftYearBackward',
						courseid: Ext.getCmp('lessonplan_course').getValue()
					}
				});
			}
		}]
	},
	{
		title: 'Extended Access',
		tools: [{
			id: 'help',
			handler: function(btn) {
				helppopup.loadHelpFile("Supervise", 500, 455);
			}
		}],
		items: [{
			xtype: 'toolboxtext',
			iconCls: 'magnifier',
			text: 'View the following teacher:'
		},
		new SchoolDynamics.extendedAccessCombo({
			id: 'lessonplan_teacher',
			reshowPage: 'lessonplans-panel'
		})]
	}]
};

SD.teacherTools.addPage('lessonPlans',lessonPlans, lessonPlansTools);

