
var calendartools = {
   regionTitle: 'Calendar Tools',
   defaults: {autoHeight: true, cls: 'toolbox', frame: true},
   items:[{
      title: 'Calendar Utilities',
      itemId: 'calendar',
      tools: [
            {
              id:'help',
              handler: function(btn){
                helppopup.loadHelpFile("Calendar Utilities", 500, 455);
              }  
            }
        ],
      items: [   
        {
           xtype: 'link',
           iconCls: 'calendar_add',
           itemId: 'calendar_event',
           text: 'Schedule event',
           handler: function(){
              calendarSchedulePopup.show();
           }
        },
        {
           xtype: 'link',
           iconCls: 'calendar_user',
           text: 'My events',
           handler: function(){
              calendarMyEvents.show();
           }
        },
        {
           xtype: 'link',
           iconCls: 'calendar_filter',
           text: 'Filter events',
           handler: function(){
             calendarEventFilter.show();
           }
        }
      ]
   },
   {
    title: 'Administrative Utilities',
    itemId: 'admin',
    tools: [
            {
              id:'help',
              handler: function(btn){
                helppopup.loadHelpFile("Administrative Calendar Utilities", 500, 455);
              }  
            }
        ],
    items: [
      {
         xtype: 'link',
         iconCls: 'calendar_approval',
         itemId: 'calendar_approval',
         text: 'Event Approval',
         handler: function(){
            calendarEventApprovalPopup.show();
         }
      },
      {
         xtype: 'link',
         iconCls: 'calendar_category',
         text: 'Event categories',
         handler: function(){
           calendarEventCategories.show();
         }
      },
      {
         xtype: 'link',
         iconCls: 'calendar_import',
         text: 'Import calendar',
         handler: function(){
            calendarImportPopup.show();
         }
      },
      {
         xtype: 'link',
         iconCls: 'calendar_export',
         text: 'Export Calendar',
         handler: function(){
            calendarExportPopup.show();
         }
      }            
    ]
   
   }],
   listeners: {
      show: function(toolbox) {
         allow = SchoolDynamics.isAccessible("Calendar Events Popup");
         parentitem = toolbox.items.item('calendar');
         parentitem.items.item('calendar_event')[allow?'show':'hide']();
         
         allow = SchoolDynamics.isAccessible("Calendar Approval Form");
         parentitem = toolbox.items.item('admin');
         parentitem.items.item('calendar_approval')[allow?'show':'hide']();
      }
   }
};

/*
 * ================  Start page config  =======================
 */
function updateStoreincalendar(){
	var viewx = cal.currentView;
	var mycategory = cal.currentcategory;  
	if (viewx=='month'){
		var mynewmonth= cal.currentdate.format('m');
		mynewmonth= (mynewmonth<10?parseInt(mynewmonth.charAt(mynewmonth.length-1)):parseInt(mynewmonth));  
		var mynewyear= parseInt(cal.currentdate.format('Y'));	
		calendarstore.baseParams={action:'month',displaymonth:mynewmonth,displayyear:mynewyear,category:mycategory};
		calendarstore.reload(); 
	}else if (viewx=='day'){ 
		var mynewdate= cal.currentdate.format('m/d/Y'); 
		calendarstore.baseParams={action:'day',day:mynewdate,category:mycategory};
		calendarstore.reload(); 
	} else if (viewx=='week'){ 
		var mynewdate= parseInt(cal.currentdate.format('W'));
		var myrange = cal.getDateRangeOfWeek(mynewdate); 
		calendarstore.baseParams={
					action:'week',
					weeknumber:mynewdate,
					startweek:myrange[0].format('m/d/Y'),
					endweek:myrange[1].format('m/d/Y'),
					category:mycategory
					};
		calendarstore.reload(); 
	} else if (viewx=='schedule'){
		// e2cs.schedviews.subView ={ Day:  0,  Week: 1,  Month: 2, TwoMonths: 3,  Quarter: 4};
		if (cal.viewscheduler.listbody.periodType==0){  // day 
			var mynewdate= cal.currentdate.format('m/d/Y'); 
			calendarstore.baseParams={action:'day',day:mynewdate,category:mycategory};
			calendarstore.reload();
		} else if (cal.viewscheduler.listbody.periodType==1){ //week 
			var mynewdate= parseInt(cal.currentdate.format('W'));
			var myrange = cal.getDateRangeOfWeek(mynewdate); 
			calendarstore.baseParams={
						action:'week',
						weeknumber:mynewdate,
						startweek:myrange[0].format('m/d/Y'),
						endweek:myrange[1].format('m/d/Y'),
						category:mycategory
						};
			calendarstore.reload();
		} else if (cal.viewscheduler.listbody.periodType==2){ //month
   		var mynewmonth= cal.currentdate.format('m');
   		mynewmonth= (mynewmonth<10?parseInt(mynewmonth.charAt(mynewmonth.length-1)):parseInt(mynewmonth));  
			calendarstore.baseParams={action:'month',displaymonth:mynewmonth,category:mycategory};
			calendarstore.reload(); 
		} else if (cal.viewscheduler.listbody.periodType==3){ // two months 
			var myrange = cal.viewscheduler.getDatesforBimonth(cal.currentdate); 
			calendarstore.baseParams={
				action:'period',
				start:myrange[0].format('m/d/Y'),
				ends:myrange[1].format('m/d/Y'),
				category:mycategory
				};
			calendarstore.reload(); 
		} else if (cal.viewscheduler.listbody.periodType==4){ // Quarter 
			var myrange = cal.viewscheduler.getDatesforBimonth(cal.currentdate); 
			calendarstore.baseParams={
				action:'period',
				start:myrange[0].format('m/d/Y'),
				ends:myrange[1].format('m/d/Y'),
				category:mycategory
				};
			calendarstore.reload(); 		
		} 		
	}	
} 

calendarstore=new Ext.data.Store({
    url:'main_menu/calendar_data.json.php',
    baseParams:{action:'all' },
    reader: new Ext.data.JsonReader({
        root:'records',
        id: 'id',
        totalProperty: 'totalCount'
    },[
        {name:'recid',       mapping:'id',          type: 'string'},
        {name:'subject',     mapping:'subject',     type: 'string'},
        {name:'description', mapping:'description', type: 'string'},
        {name:'startdate',   mapping:'startdate',   type: 'string'},
        {name:'enddate',     mapping:'enddate',     type: 'string'},
        {name:'color',       mapping:'color',       type: 'string'},
        {name:'alldayevent', mapping:'alldayevent', type: 'string'}          
    ]),
    listeners: {
      load: function() {
         if (this.baseParams.action == 'day'){
           this.dayLoaded=true;
         }
         Ext.getCmp('test_calx').refreshCalendarView(true);
      },
      beforeload : function(){
        this.dayLoaded=false;
        this.baseParams.command = 'eCalendarCommands';
      }      
    }
});

calendarDaysStore=new Ext.data.Store({
    url:'main_menu/calendar_data.json.php',
    baseParams:{command: 'getDays'},
    reader: new Ext.data.JsonReader({
        root:'days'
    },[
        {name:'date'},
        {name:'instructionDay'},
        {name:'daysLeft'},
        {name:'attend'} 
    ]), 
    autoLoad: false,
    listeners: {
      load: function() {
         this.loaded = true;
         Ext.getCmp('test_calx').refreshCalendarView(true);
      }
    }    
});


var cal = new Ext.ECalendar({
		id: 'test_calx', 
		name: 'test_calx',		
		title: 'Calendar',
		tools: [
            {
              id:'help',
              handler: function(btn){
                helppopup.loadHelpFile("Calendar", 500, 455);
              }  
            }
        ],
		//width:750,	
		//height:500,
		fieldsRefer:{ //0.0.11 
			id:'recid',
			subject:'subject',
			description:'description', 
			color:'color',
			startdate:'startdate',
			enddate:'enddate',
			alldayevent:'alldayevent'
		},
		storeOrderby:'id', 	//0.0.11 
		storeOrder:'DESC',		//0.0.11 
		showCal_tbar: true,
		//showrefreshbtn:true,
		//refreshAction:'data', //0.0.11 
		currentView: 'month',
		currentdate: new Date(),
		dateSelector: true,
		dateSelectorIcon: 'e2cs/images/date.png',
		dateSelectorIconCls: 'x-cmscalendar-icon-date-selector',
		dateformat :'d-m-Y',
		categorySelector: true,		
		currentcategory: 'Summary',
		categoryFieldsRefer:{
			id:'CatID',
			category:'Description'
		},
		categoryStore: new Ext.data.Store({
          url:'main_menu/calendar_data.json.php', 
          baseParams: {action: 'getCategories'},
          reader: new Ext.data.JsonReader({
          	root: 'records',
          	totalProperty: 'totalCount'
          },[
      	{name:'id', 	     mapping:'CatID',          type: 'string'},     
      	{name:'category',    mapping:'Description',    type: 'string'}
          ]),
          listeners: {
            beforeload : function(){
              this.baseParams.command = 'eCalendarCommands';
            }
          }		        	
      }),
		header: true,
		//iconCls: 'x-cmscalendar-icon-main',
		dateSelector:true,
		store:	calendarstore, 
		monitorBrowserResize:true, 
		widgetsBind: {bindMonth:null,bindDay:null,binWeek:null},
		tplTaskZoom: new Ext.XTemplate( 
		'<tpl for=".">',
			'<div class="ecal-show-basetasktpl-div"><b>Subject:</b>{subject}<br>',
			'<b>Starts:</b>{startdate}<br><b>Ends:</b>{enddate}',
			'<br><b>Details:</b><div><hr><div>{description}<div><hr>',
		'</tpl>'
		),
		iconToday:'e2cs/images/cms_calendar.png',
		iconMonthView:'e2cs/images/calendar_view_month.png',
		iconWeekView:'e2cs/images/calendar_view_week.png',
		iconDayView:'e2cs/images/calendar_view_day.png',
		iconSchedView:'e2cs/images/calendar_view_schedule.png', //0.0.10  // NEW :) 
		//-------- NEW on 0.0.10 -------------------
	 
		//-------------------------------------------
		mview:{
			header: true,
			headerFormat:'F-Y',
			headerButtons: true,
			dayAction:'viewday',    //dayAction: //viewday , event, window			
			//moreMenuItems:[],
			showTaskcount: false,
			startDay:0,
			taskStyle:'margin-top:2px;', //Css style for text in day(if it has tasks and showtaskcount:true)
			showTaskList: true,
			showNumTasks:10,
			TaskList_launchEventOn:'click', //0.0.11 
			//TaskList_tplqTip: new Ext.XTemplate( '<tpl for=".">{starxl}{startval}<tpl if="endval"><br>{endxl}{endval}</tpl><hr color="#003366" noshade>{details}</tpl>' ), // conditional template, but doesn't quite work
         TaskList_tplqTip: new Ext.XTemplate( '<tpl for=".">{starxl}{startval}<br>{endxl}{endval}<hr color=\'#003366\' noshade>{details}</tpl>' ), //0.0.11 
			ShowMenuItems:[1,1,1,1,1,1],  //0.0.11  - ADD, nextmonth, prevmonth, chg Week , CHG Day, chg Sched,				
			TaskList_ShowMenuItems:[1,1,1]//0.0.11 	- Add, DELETE, EDIT 	
		},
		wview:{
			headerlabel:'Week #',
			headerButtons: true,
			dayformatLabel:'D j', 			
			style: 'google',
			alldayTaksMore:'window', 
			alldayTasksMaxView:9,
			store: null, 
			task_width:25, 
			tasksOffset:40,
			headerDayClick:'viewday',
			ShowMenuItems:[1,1,1,1,1,1],	//0.0.11  add, go next w , go prev w , chg month , chg day, chg sched 
			task_ShowMenuItems:[1,1,1,1,1], //0.0.11  add, delete, edit, go next w , go prev w
			task_eventLaunch:'click',		//0.0.11
			task_clsOver:'test_taskovercss'
		},
		dview:{
			header:true,
			headerFormat:'l, F d, Y',
			headerButtons: true,
			headerTooltips: { prev: 'Previous month..',	next: 'Next Month'  },
			contextMenuLabels: { 
					task: "Create Task", 
					chgwview: "Change to month view.", 
					chgdview: "Change to week view."
			},
			moreMenuItems:[],
			// day specific 
			hourFormat: 'h',
			startTime: '12:00:00 am',
			endTime:   '11:59:59 pm',
			// task settings 
			store: null,
			taskBaseColor: '#ffffff', 
			task_width:30,
			taskAdd_dblclick: true,				//added on 0.0.7
			taskAdd_timer_dblclick:true,		//0.0.11
			useMultiColorTasks: false, 
			multiColorTasks:[], 
			tasks:[],			
			task_clsOver:'test_taskovercss',	
			ShowMenuItems:[1,1,1,1,1,1],		//0.0.11 ADD, next day, prev day , chg Month , CHG Week, chg Sched, (for daybody menu) 
			task_DDeditable:true, 			    //0.0.11   
			task_eventLaunch:'dblclick',  		    //0.0.11 'click, dblclick, if set to '' then no action is taken
			task_ShowMenuItems:[1,1,1,1,1]		//0.0.11 ADD, delete, edit, Next day , Prev Day  (for Taks/events) 
		}
	});
    
    	
	//dayClick only event on this object  
	cal.viewmonth.on({		
		'dayClick':{
				fn: function(datex, mviewx, calx) { 
					//alert ("dayclick event for " + datex);
				},
				scope:this
		},
		'beforeMonthChange':{
				fn: function(currentdate,newdate) { 
					//alert ("gonna change month to " + newdate.format('m/Y') + ' Actual date=' + currentdate.format('m/Y') );
					return false; 
				},
				scope:this
		},
		'afterMonthChange':{
				fn: function(newdate) { 
					//alert ("Month changed to " + newdate.format('m/Y') ) ;
					updateStoreincalendar();  // refresh the data for that selected month 
				},
				scope:this
		}
	}); 
	cal.viewweek.on({
		'dblClickTaskAllDay':{
				fn: function(task,dxview,calendar) { 
					var datatest='Task all day <br>record No:' + task[0] + '<br>';
					datatest+='id-task:'  + task[1] + ' ' + task[2] + '<br>';
					datatest+='starts:'    + task[3] + '<br>';
 					datatest+='ends:'   + task[4] + '<br>';
 					datatest+='contents'  + task[5] + '<br>';	
					datatest+='index'     + task[6] + '<br>';	
					//Ext.Msg.alert('Information', datatest);	
				},
				scope:this
		},
		'beforeWeekChange':{
			fn: function (currentDate, newDate){
					return false;	
			}
		}, 
		'afterWeekChange':{
			fn: function(newdate){
				updateStoreincalendar();
				return false; 
			}
		}
	});  
	//'beforeDayChange' and  'afterDayChange' unique events on day view 	
	cal.viewday.on({
		'beforeDayChange':{
				fn: function(currentdate, newdate) { 					
					return false; 
				},
				scope:this
		},		
		'afterDayChange':{
				fn: function(newdate) { 					
					updateStoreincalendar();
				},
				scope:this
		}	
	}); 
	cal.on({
		'beforeChangeDate': {
			fn: function( newdate , calobj){
				return true; 
			} 		
		},
		'afterChangeDate':{
			fn: function( newdate , calobj){				
				updateStoreincalendar();  // refresh the data for that selected date and view 
			}
		},
		'beforeChangeCategory': {
			fn: function( newcategory , calobj){
				return true; 
			} 		
		},
		'afterChangeCategory':{
			fn: function( newcategory , calobj){				
				updateStoreincalendar();  // refresh the data for that selected date and view 
			}
		},
		'onChangeView':{
			fn: function(newView, oldView, calobj){ 					
				updateStoreincalendar(); // refresh the data for that selected date and view 
			},scope: this
		},
		'beforeChangeView':{
				fn: function (newView,OldView,calendarOBJ){
					if (newView==OldView){ 	return true; } 
					//var r=confirm("Change from " + OldView + " to " + newView);
					//return r;
          				return true; 
				},scope:this
		},		
		'taskDblClick':{
				fn: function (task,dxview,calendar,refviewname){
					var datatest='Record No:' + task[0] + '<br>';
					datatest+='id-task:'  + task[1] + ' ' + task[2] + '<br>';
					datatest+='starts:'    + task[3] + '<br>';
 					datatest+='ends:'   + task[4] + '<br>';
 					datatest+='contents'  + task[5] + '<br>';	
					datatest+='index'     + task[6] + '<br>';	
					//Ext.Msg.alert('Information on Object - ' + refviewname, datatest);		
				},
				scope:this 
		}		
	});
	
	// cal.render('calendar');
	// calendarstore.load();	
	calendarstore.on('load',function(){
	 	cal.refreshCalendarView(true); 
	});	
	Ext.EventManager.onWindowResize( function(){ 
		cal.refreshCalendarView(); 
	});
    
var calendar = { 
    id: 'calendar-panel',    	                 
    bodyBorder: false,
    layout: 'fit',
    border: false,     
    items: [ cal ],
    listeners: {
       show: function(panel) {
          calendarstore.load(); 
       },
       beforeShow: function(){
          calendarDaysStore.load();
       }
    }
};
