
HJ.Schedule = Class.create();

HJ.Schedule.prototype = {


    initialize: function() {
        this.date = new Date();

        // These fields contain the actual schedule and event data
        // The month (+-10 days) for which the event data has been loaded
        this.eventDataMonth
        // users's schedules
        this.scheduleList = null;
        // shared schedules
        this.sharedSchedules = null;
        // community schedules
        this.communitySchedules = null;

        this.targetContainerId = "content";
        this.target = document.getElementById(this.targetContainerId);
        this.scheduleTable = new Af.HtmlTable("scheduleTable", ",,name");
        this.sharedScheduleTable = new Af.HtmlTable("sharedScheduleTable", ",,name");
        this.communityScheduleTable = new Af.HtmlTable("communityCalTable", ",,name");
        this.sharedScheduleTable.autoDeselect = false;
        this.communityScheduleTable.autoDeselect = false;
        this.scheduleTable.listener = this;
        this.sharedScheduleTable.listener = this;
        this.communityScheduleTable.listener = this;
        this.currentRow = -1;
        this.currentSch = null;
        this.calendarContainer = document.getElementById("templateCalendar");

        this.delCommCalndLink = document.getElementById("delCommCalndLink");
        this.delCommCalndLink.onclick = this.doDelCommCalndLink.bindAsEventListener(this); 
        
        this.delSharedSchLink = document.getElementById("delSharedSchLink");
        this.delSharedSchLink.onclick = this.doDelSharedSchLink.bindAsEventListener(this); 
       
        this.scheduleAddLink = document.getElementById("scheduleAddLink");
        this.scheduleAddLink.onclick = this.loadScheduleDetailTemplate1.bindAsEventListener(this);
        
        this.scheduleEditLink = document.getElementById("scheduleEditLink");
        this.scheduleEditLink.onclick = this.loadScheduleDetailTemplate2.bindAsEventListener(this);
        
        this.tl = null;

        this.url = basePageURL + "ScheduleAddEdit.html";
        this.targetContainerId = "content";

        this.currentCalType = "monthly";
        
        
        this.calendarDisplayStyle = document.getElementById("calendarDisplayStyle");
        this.addEventLink = document.getElementById("addEvent");
        this.printEventLink = document.getElementById("printEvent");
        this.todaysCalendarLink = document.getElementById("todaysCalendar");
        this.previousCalendarLink = document.getElementById("previousCalendar");
        this.dayCalendarLink = document.getElementById("dayCalendar");
        this.weeklyCalendarLink = document.getElementById("weeklyCalendar");
        this.monthlyCalendarLink = document.getElementById("monthlyCalendar");
        this.yearlyCalendarLink = document.getElementById("yearlyCalendar");
        this.nextCalendarLink = document.getElementById("nextCalendar");
        
        
        this.calendarHeader = document.getElementById("calendarHeader");
        this.calendarArea = document.getElementById("calendarArea");
        this.allDayEvents = document.getElementById("allDayEvents");
        this.calendarTitle = document.getElementById("calendarTitle");
        this.journalArea = document.getElementById("journalArea");
        
        this.calendarDisplayStyle.onclick = this.calendarDisplayStyleChanged.bind(this);
        this.addEventLink.onclick = this.addEventClicked.bind(this);
        this.printEventLink.onclick = this.printEventClicked.bind(this);
        this.todaysCalendarLink.onclick = this.todaysCalendarSelected.bind(this);
        this.previousCalendarLink.onclick = this.previousCalendarSelected.bind(this);
        this.dayCalendarLink.onclick = this.dayCalendarSelected.bind(this);
        this.weeklyCalendarLink.onclick = this.weeklyCalendarSelected.bind(this);
        this.monthlyCalendarLink.onclick = this.monthlyCalendarSelected.bind(this);
        this.yearlyCalendarLink.onclick = this.yearlyCalendarSelected.bind(this);
        this.nextCalendarLink.onclick = this.nextCalendarSelected.bind(this);   
        
        this.dailyCalendar = new HJ.DailyCalendar(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents, this.todaysCalendarLink);
        this.dailyAgenda = new HJ.DailyAgenda(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents, this.todaysCalendarLink);
    
        this.weeklyCalendar = new HJ.WeeklyCalendar(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);
        this.weeklyAgenda = new HJ.WeeklyAgenda(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);
    
        this.monthlyCalendar = new HJ.MonthlyCalendar(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);
        this.monthlyCalendar.listener = this;
        this.monthlyAgenda = new HJ.MonthlyAgenda(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);
        
        this.yearlyCalendar = new HJ.YearlyCalendar(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);
        this.yearlyCalendar.listener = this;
        this.yearlyAgenda = new HJ.YearlyAgenda(this.calendarTitle, this.calendarArea, this.calendarHeader, this.allDayEvents);

        this.currentCalendar = this.monthlyCalendar;
        this.currentAgenda = this.monthlyAgenda;        
        this.currentActiveLink = this.monthlyCalendarLink;
        
        
        this.date.setHours(0,0,0,0);

        // various date ranges in milliseconds to avoid 
        // lots of arithmetic
        this.DT_10_DAYS = 10 * 24 * 3600000;
        this.DT_51_DAYS = 51 * 24 * 3600000;

        this.normalBackcolor = "";
        this.normalTextColor = "#000000";
        
        this.shownScList = new Array();
        
        this.miniCalendar = new HJ.MiniCalendar();
        this.miniCalendar.listener = this;
        this.miniCalendar.render(this.shownScList, this.date);
        
        this.calendarArea.onscroll = this.handleScroll.bindAsEventListener(this);
        
        this.journalText = document.getElementById("journalText");
        /*  this.journalSubmit = document.getElementById("journalSubmit");
            this.journalSubmit.onclick = this.saveNote.bind(this);  */
        
        this.journalText.onblur = this.saveNote.bindAsEventListener(this);
        
        this.currentNote = null;

        this.newHomePageCalendar = null;
    },
    
    cleanup:function() {
        this.scheduleAddLink.onclick = null;
        this.scheduleEditLink.onclick = null;
       
        this.addEventLink.onclick = null;
        this.printEventLink.onclick = null;
        this.todaysCalendarLink.onclick = null;
        this.previousCalendarLink.onclick = null;
        this.dayCalendarLink.onclick = null;
        this.weeklyCalendarLink.onclick = null;
        this.monthlyCalendarLink.onclick = null;
        this.yearlyCalendarLink.onclick = null;
        this.nextCalendarLink.onclick = null;    
        this.calendarArea.onscroll = null;
       
        this.allDayEvents.onclick = null;
       
        this.scheduleTable.cleanup();
        this.sharedScheduleTable.cleanup();
        this.communityScheduleTable.cleanup();
        
        this.dailyCalendar.cleanup();
        this.dailyAgenda.cleanup();
       
        this.weeklyCalendar.cleanup();
        this.weeklyAgenda.cleanup();
       
        this.monthlyCalendar.cleanup();
        this.monthlyAgenda.cleanup();
       
        this.yearlyCalendar.cleanup();
        this.yearlyAgenda.cleanup();

        // just forget it.  Should be cleaned up by homepage
        this.newHomePageCalendar = null;
    },
    
    handleScroll: function() {
        if (!this.calendarDisplayStyle.checked) {
            this.currentCalendar.handleScroll();
        } 
    },
    
    getSelectedSchedule: function() {       
        var mySch = this.scheduleTable.getSelectedRowData(); 
        return mySch
    },
    
    showCalendar: function() {
        if (this.target.childNodes.length > 0 && this.target.childNodes[0] == this.calendarContainer) {
            return;
        }
        removeAll(this.target);
        this.target.appendChild(this.calendarContainer);
        if (this.calendarDisplayStyle.checked) {
            app.setCurrentView(this.currentAgenda);
        } else {
            app.setCurrentView(this.currentCalendar);
            setTimeout(this.currentCalendar.scrollTo7AM.bind(this.currentCalendar), 10);
        }
        //change calendar's frame color:   
        this.setCalendarColor();
    },


    setWorkspace: function(workspace) {
        // Used only for "notes"
        // XXX: workspace should disappear in the future in favor of loading
        // notes, plus we should get ride of getWorkspace
        this.workspace = workspace;

        // note: 
        // - schedule data is loaded from this.loadSchedule if we get here from
        // home page
        // - schedule data is loaded from getWorkspace if we get here from 
        // somewhere else

        if (this.eventDataMonth != null) {
            // event data already loaded
            return;
        }
        // event data not loaded yet. 

        // getWorkspace gets data for the current month
        this.eventDataMonth = this.getMonthStart(new Date());
        this.setSchedules(workspace["schedule"], 
                          workspace["sharedSchedule"], 
                          workspace["communitySchedule"]);
    },

    /**
     * Set the schedule arrays
     * Each parameter is an array of Schedule that cannot be null 
     * (see Dashboard.completeWorkspace())
     *
     */
    setSchedules: function(schedule, sharedSchedule, communitySchedule) {
        this.shownScList.length = 0;
        this.scheduleList = schedule;
        this.sharedSchedules = sharedSchedule;
        this.communitySchedules = communitySchedule;
        this.scheduleTable.setDataList(this.scheduleList);
        this.sharedScheduleTable.setDataList(this.sharedSchedules);
        this.communityScheduleTable.setDataList(this.communitySchedules);
        this.addCheckClickListener(this.scheduleTable);
        this.addCheckClickListener(this.sharedScheduleTable);
        this.addCheckClickListener(this.communityScheduleTable);
        this.showCurrentCalendar(false);
        setTimeout(this.currentCalendar.scrollTo7AM.bind(this.currentCalendar),
                   10);
        if(this.scheduleList == null) {
            return;
        }
        
        // check whether sched_id is passed as a parameter
        var sharedSchedUUID = HJ.requestQueryString.get("sched_id", null);

        app.db.displayCalendarHeader(true);

        this.showCalendar();
      
        if (sharedSchedUUID == null) {
            var listLength = this.scheduleList.length;
            if (listLength > 10) {
                listLength = 10; // select at most 10 schedules
            }
            for(idx = 0; idx < listLength && listLength>0; idx++) {
                if (this.scheduleList[idx].selected == "false" && listLength < this.scheduleList.length) {
                    listLength++; // adding 1 to the total number of schedules whose events are displayed because the current schedule is not selected
                }
                this.showEventsInSchedule(idx, 2 , this.scheduleTable);
            }
        }

        if (sharedSchedUUID == null) {
            var listLength = this.communitySchedules.length;
            if (listLength > 10) {
                listLength = 10; // select at most 10 schedules
            }
            for(idx = 0; idx < listLength && listLength>0; idx++) {
                if (this.communitySchedules[idx].selected == "false" && listLength < this.communitySchedules.length) {
                    listLength++; // adding 1 to the total number of schedules whose events are displayed because the current schedule is not selected
                }
                this.showEventsInSchedule(idx, 2 , this.communityScheduleTable);                            
            }
        }   


        if(this.sharedSchedules == null) {
            return;
        }

        if (sharedSchedUUID == null) {
            var listLength = this.sharedSchedules.length;
            if (listLength > 10) {
                listLength = 10; // select at most 10 schedules
            }
            for(idx1 = 0; idx1 < listLength && listLength>0; idx1++) {
                if (this.sharedSchedules[idx1].selected == "false" && listLength < this.sharedSchedules.length) {
                    listLength++;
                }
                this.showEventsInSchedule(idx1, 2 , this.sharedScheduleTable);                          
            }
        } else {
            for (idx1 = 0; idx1 < this.sharedSchedules.length; idx1++) {
                if (this.sharedSchedules[idx1].UUID==sharedSchedUUID) {
                    this.showEventsInSchedule(idx1, 2 , this.sharedScheduleTable);
                    // figure out the month and year in which the first event occurs
                    var req = new Af.DataRequest(svcURL,
                                                 this.requestFirstEventDateLoadCompleted.bind(this),
                                                 this.requestFailedCommon.bind(this), null, 
                                                 this.requestTimedoutCommon.bind(this));
                    req.addService("WorkspaceService", "getFirstEventDate");
                    req.addParameter("scheduleUUID", sharedSchedUUID);
                    ajaxEngine.processRequest(req);
                }                           
            }
        }
    },

    requestFirstEventDateLoadCompleted: function() {
        if (response.responseText == null || response.responseText == "") {
            // do nothing, show the current month in the calendar
        }
       
    },

    communityCalendarListChanged: function() {
        this.communityScheduleTable.setDataList(this.communitySchedules);
        this.addCheckClickListener(this.communityScheduleTable);
        this.updateShceduleSelection(this.communityScheduleTable, this.communitySchedules);
    },

       
    viewSelected: function(invoker) {       
        if (this.currentRow == -1 && this.scheduleList.length > 0) {
            this.cellSelected(0, 0, false, this.scheduleTable);
        } else {
            this.showCalendar();
        }
    },
    

    cellSelected: function(row, col, reselected, htmlTable) {       
        app.db.displayCalendarHeader(true);
        this.showCalendar();
        if (this.scheduleTable == htmlTable) {
            this.currentRow = row;
            this.currentSch = this.scheduleList[this.currentRow];
            if (!reselected) {
                var bc = this.scheduleList[row]["color"];
                var c = getTextColor(bc);
                var bc = getBackground(bc);
                this.setScheduleCheckState(htmlTable, htmlTable.tableElement.rows[row], row, true);
         
                var cell = htmlTable.tableElement.rows[row].cells[1];
                var check;
                // following is needed for the Firefox
                for (var i=0; i<cell.childNodes.length; i++) {
                    if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                        check = cell.childNodes[i];
                        break;
                    }
                }
                if (check != null && this.scheduleList[row].selected) {
                    check.checked = true; // check box
                }
                htmlTable.selectRow(row, bc, c); 
                //change calendar's frame color
                this.target.style.backgroundColor = bc; 
            }
        } else {            
            var cell = htmlTable.tableElement.rows[row].cells[1];
            var check;
            var c; 
            var bc;

            // following is needed for the Firefox
            for (var i=0; i<cell.childNodes.length; i++) {
                if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                    check = cell.childNodes[i];
                    break;
                }
            }
            if (check != null) {
                check.checked = true; // check box
            }
            this.setScheduleCheckState(htmlTable, htmlTable.tableElement.rows[row], row, true);            
            var bc = htmlTable.dlist[row]["color"];
            c = getTextColor(bc);
            bc = getBackground(bc);
               
            var p = htmlTable.previousRowNumber;
            if (p >= 0) {
                htmlTable.unselectRow(p);          
                var color = htmlTable.dlist[p]["color"];
                htmlTable.tableElement.rows[p].cells[2].style.backgroundColor = getBackground(color);
                htmlTable.tableElement.rows[p].cells[2].style.color = getTextColor(color);;
            }
            htmlTable.selectRow(row, bc, c); 
        }
    },

    showEventsInSchedule: function(row, col, htmlTable) {     
        // CODE TO SHOW SELECTED MY SCHEDULE ON DASHBOARD LOAD

        if (this.scheduleTable == htmlTable) {         
            this.currentSch = this.scheduleList[row];
            if (true) {
                var bc = this.scheduleList[row]["color"];
                var c = getTextColor(bc);
                var bc = getBackground(bc);
                if (this.scheduleList[row].selected == "true") {
                    this.setScheduleCheckState(htmlTable, htmlTable.tableElement.rows[row], row, true);          
             
                    var cell = htmlTable.tableElement.rows[row].cells[1];
                    var check;
                    // following is needed for the Firefox
                    for (var i=0; i<cell.childNodes.length; i++) {
                        if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                            check = cell.childNodes[i];
                            break;
                        }
                    }
                 
                    if (check != null) {
                        check.checked = true; // check box
                    }
                }
                if(row == 0){
                    htmlTable.selectRow(row, bc, c);            
                    this.target.style.backgroundColor = bc; 
                }
            
            }
        } 

        // CODE TO SHOW SELECTED SHARED SCHEDULE ON DASHBOARD LOAD

        if (this.sharedScheduleTable == htmlTable) {                  
            if (true) {
                var bc = this.sharedSchedules[row]["color"];
                var c = getTextColor(bc);
                var bc = getBackground(bc);
             
                if (this.sharedSchedules[row].selected == "true") {
                    this.setScheduleCheckState(htmlTable, htmlTable.tableElement.rows[row], row, true);          
                 
                    var cell = htmlTable.tableElement.rows[row].cells[1];
                    var check;
                    // following is needed for the Firefox
                    for (var i=0; i<cell.childNodes.length; i++) {
                        if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                            check = cell.childNodes[i];
                            break;
                        }
                    }
                    if (check != null) {
                        check.checked = true; // check box
                    }
                }
            }
        } 

        // CODE TO SHOW SELECTED COMMUNITY CALENDAR " ON " WHILE ADDED FROM PUBLIC CALENDAR

        if (this.communityScheduleTable == htmlTable) {               
            if (true) {

                // HERE ROW IS THE OBJECT WHICH IS TO BE SELECTED
                var schObj = this.communitySchedules[row];

                // var objIndex = findObjIndex(this.communityScheduleTable.dlist, schObj);
                // if(objIndex == -1) {
                //  return;
                // }
                var bc = schObj["color"];
                var c = getTextColor(bc);
                var bc = getBackground(bc);
                if (this.communitySchedules[row].selected == "true") {
                    this.setScheduleCheckState(htmlTable, htmlTable.tableElement.rows[row], row, true);             
                 
                    var cell = htmlTable.tableElement.rows[row].cells[1];
                    var check;
                    // following is needed for the Firefox
                    for (var i=0; i<cell.childNodes.length; i++) {
                        if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                            check = cell.childNodes[i];
                            break;
                        }
                    }
                    if (check != null) {
                        check.checked = true; // check box
                    }
                }
            }
        } 

    },
   
    selectScheduleAndRefresh: function(sch) {
        var row = findObjIndex(this.scheduleTable.dlist, sch);
        if (row < 0) {
            return false;
        }
      
        this.setScheduleCheckState(this.scheduleTable, this.scheduleTable.tableElement.rows[row], row, true); 
    },  
   
    addCheckClickListener: function(htmlTable) {
        var tbl = htmlTable.tableElement;
        for (var i=0; i<tbl.rows.length; i++) {
            var r = tbl.rows[i];
            var cell = r.cells[1];
           
            var check = null;
           
            // following is needed for the Firefox
            for (var j=0; j<cell.childNodes.length; j++) {
                if (cell.childNodes[j] && cell.childNodes[j].tagName == 'INPUT') {
                    check = cell.childNodes[j];
                    break;
                }
            }
           
            if (check != null) {
                check.onclick = this.scheduleCheckClicked.bindAsEventListener(this);
            }
        }
       
    },
    
    scheduleCheckClicked: function(ev) {
        app.db.displayCalendarHeader(true);

        var eventTarget = ev.target ? ev.target : ev.srcElement;
        // check box's parent is cell, cell's parent is row, row.id gives the row number  
        var tr = eventTarget.parentNode.parentNode;
        var schedIndex = parseInt(tr.id);
        this.showCalendar();
        var tbl = tr.parentNode.parentNode;
        var htmlTable = null;
        if (tbl == this.scheduleTable.tableElement) {
            htmlTable = this.scheduleTable;
        } else if (tbl == this.sharedScheduleTable.tableElement) {
            htmlTable = this.sharedScheduleTable;
        } else if (tbl == this.communityScheduleTable.tableElement) {
            htmlTable = this.communityScheduleTable;
        }
       
        if (htmlTable != null) {
            if (!eventTarget.checked) {
                htmlTable.unselectRow(schedIndex);
            } else if (htmlTable == this.sharedScheduleTable || htmlTable == this.communityScheduleTable) {
                htmlTable.selectedRowNumber = schedIndex;
            }
            this.setScheduleCheckState(htmlTable, tr, schedIndex, eventTarget.checked);
        }
    },  
    
    setScheduleCheckState: function(htmlTable, tr, schedIndex, f) {     
        var bc;
        var c;
        var list = htmlTable.dlist;
        if (f) {
            bc = list[schedIndex]["color"];
            c = getTextColor(bc);
            bc = getBackground(bc);
            this.addToShownList(list[schedIndex]);
        } else {
            bc = this.normalBackcolor;
            c = this.normalTextColor;
            this.removeFromShownList(list[schedIndex]);
        }
        tr.cells[2].style.backgroundColor = bc;
        tr.cells[2].style.color = c;

        // This causes undesired UI interruption when showing the home page
        // We need something less intrusive
        // app.showBusy();
        var selected = f?"true":"false";
        var startDT = null;
        var endDT = null;

        startDT = this.eventDataMonth.getTime() - this.DT_10_DAYS;
        endDT = startDT + this.DT_51_DAYS;
    
        var req = new Af.DataRequest(
                svcURL,
                this.requestSelectScheduleCompleted.bind(this), 
                requestFailedCommon.bind(this), 
                null, 
                requestTimedoutCommon.bind(this));
        var s = "<Schedule></Schedule>";
        req.addService("WorkspaceService", "selectSchedule");
        req.addParameter("UUID", list[schedIndex].UUID);
        req.addParameter("Select", selected);
        req.addParameter("startDT", startDT);
        req.addParameter("endDT", endDT);
        req.xmlDoc = s;
        ajaxEngine.processRequest(req);
    },
    
    requestSelectScheduleCompleted: function(response) {
        if (response != null && response.responseText != "") {
            var xds = new Af.XMLToDataSet(response.responseXML);
            var scheduleData = xds.data;
            for(i = 0; i < this.scheduleList.length; i++) {
                if (this.scheduleList[i].UUID == scheduleData.UUID) {
                    this.scheduleList[i].event = scheduleData.event;  // replace existing data with the new data
                    break;
                }
            }           
        }
        this.renderCurrentCalendar(false);
        app.endBusy();
        return false;
    },
    
    paneStateChanged: function(comp) {
        
    },
    
    loadScheduleDetailTemplate: function () {   
        app.db.displayCalendarHeader(false);
          
        if (this.tl == null) {          
            this.tl = new Af.TemplateLoader(this.url, this.targetContainerId, "schedulesView");
            this.tl.listener = this;
            this.tl.loadTemplate();
        } else {
            this.tl.reAttachElement();
            this.myScheduleDetail.setSchedules(this.scheduleList, this.scheduleObj);
            app.setCurrentView(this);
        }    
        return false;
    },

    loadScheduleDetailTemplate1: function (ev) {
        consumeEvent(ev);
        this.scheduleObj = null;
        this.loadScheduleDetailTemplate();
        GATrackEvent("addCalendar");
        return false;
    },
   
   
    loadScheduleDetailTemplate2: function (ev) { 
        consumeEvent(ev);
        if (this.scheduleTable.selectedRowNumber == -1) {
            return;
        }
        var dataList = this.scheduleTable.dlist;
        this.scheduleObj = dataList[this.scheduleTable.selectedRowNumber];
        this.loadScheduleDetailTemplate();
        return false;
    },
   
    templateLoaded: function() {
        // instantiate table components, associate with html elements    
        this.myScheduleDetail = new HJ.ScheduleDetail();
        this.myScheduleDetail.setSchedules(this.scheduleList, this.scheduleObj);
        app.setCurrentView(this);
      
    },
     
    calendarDisplayStyleChanged: function() {       
        setTimeout(this.showCurrentCalendar.bind(this, true), 1);     
        return true;
    },
   
    saveCurrentCalendarDate: function() {
        if (this.calendarDisplayStyle.checked) {
            this.date = this.currentAgenda.date;
        } else {
            this.date = this.currentCalendar.date;
        }
      
        if (this.currentCalendar == this.dailyCalendar) {
            var n = this.getNote(this.date.getTime());
            if (n == null) {
                this.journalText.value = "";
            } else {   
                if(n["description"] == null){
                    this.journalText.value = "";
                } else {
                    this.journalText.value = textDisplay((n["description"]));
                }
            }
        }
    },
   
    showCurrentCalendar: function(scroll) {
        this.loadEventData(this.date);
        if (this.currentCalendar != this.dailyCalendar) {
            this.journalArea.style.display = "none";
        } else {
            this.journalArea.style.display = "";
            var n = this.getNote(this.date.getTime());
            if (n == null) {
                this.journalText.value = "";
            } else {   
                if(n["description"] == null){
                    this.journalText.value = "";
                } else {
                    this.journalText.value = textDisplay((n["description"]));
                }
            }
        }
        this.renderCurrentCalendar(scroll);
        //change calendar's frame color
        this.setCalendarColor();
    },

    renderCurrentCalendar: function(scroll) {
        if (this.calendarDisplayStyle.checked) {
            this.currentAgenda.render(this.shownScList, this.date);
            app.setCurrentView(this.currentAgenda);
        } else if (app.getCurrentTab() == HJ.DESTINATION_PAGE_HOME && this.newHomePageCalendar != null) {
            this.newHomePageCalendar.render(this.shownScList, this.date);           
        } else {
            this.currentCalendar.render(this.shownScList, this.date);
            app.setCurrentView(this.currentCalendar);
            if (scroll) {
                this.currentCalendar.scrollTo7AM();
            }
        }
        // Keep the minicalendar updated
        this.miniCalendar.render(this.shownScList, this.date);
    },
    
    addEventClicked: function() {
        var eventDate;
        if (this.calendarDisplayStyle.checked) {
            eventDate = this.currentAgenda.date;
        } else {
            eventDate = this.currentCalendar.date;
        }
        this.addNewEvent(eventDate);
        GATrackEvent("addEvent");
        return false;
    },

    // separate from addEventClicked so it can be called from other 
    // objects 
    addNewEvent: function(eventDate) {
    	if (app.db.workspace == null) {
    		showMessageDialog("Initializing...please try again", "Excuse us!", 200, 150);
    		return false;
    	}

        if (this.scheduleList.length == 0) {
            this.showSelectScehduleMessage();
            return;
        }
        if (this.newEventDialog != null) {      
            //  this.newEventDialog.close();
            //  this.newEventDialog = null;
        }
        if (this.eventDialog != null) {
            this.eventDialog.close();
            delete this.eventDialog;
        }
        
        this.eventDialog = new HJ.EventDetail("Event Details", this, null); 
        this.eventDialog.setWorkspace(this.workspace);      
        this.eventDialog.width = "470px";
        var obj = new Object();
      
        obj["timeFlag"] = true;
        obj["fromTime"] = "450";
        obj["toTime"] = "510";
        //obj["displayName"] = "New Event";
      
        var dt;
        obj["date"] = eventDate.getTime();

        var dt = new Date(obj["date"]);
        dt.setHours(7, 30, 0, 0);
        obj["startDT"] = dt.getTime();
        dt.setHours(8, 30, 0, 0);
        obj["endDT"] = dt.getTime();
          
        this.eventDialog.setObj(obj, true, this.getSelectedSchedule());   
        this.eventDialog.showHTMLTemplate(basePageURL + "EventDetails2.html", "content", "eventDetail");
        return false;
    },
    
    addQuickNewEvent: function(obj, sch, mode) {  
        if (this.newEventDialog != null) {
            delete this.newEventDialog;
        }
        this.newEventDialog = new HJ.NewEvent("New Event Detail", this, null);   
        this.newEventDialog.setWorkspace(this.workspace);        
        this.newEventDialog.width = "470px";
        this.newEventDialog.centerDialog(470, 280);
      
        this.newEventDialog.showHTMLTemplate(basePageURL + "NewEvent.html", "content", "newEventDetail");
        this.newEventDialog.setObj(obj, true, sch);    
        return false;
    },
   
    editEventDetails: function(obj, sch, mode, actualDate, driverSch,
                               dialogContainer, isFocusGuestTab) {
                                   if (dialogContainer == null) {
                                       dialogContainer = "content";
                                   }
                                   if (this.eventDialog != null) {
                                       var dlgElemList = document.getElementsByClassName("Dialog");
                                       if (dlgElemList != null && dlgElemList.length > 0) {
                                           for (var i=0; i<dlgElemList.length; i++) {
                                               var dlgElem = dlgElemList[i];
                                               if (dlgElem.style.display != "none") {
                                                   // an event is displayed currently
                                                   return false;
                                               }
                                           }
                                       }
                                       // dialog was closed by user.
                                       delete this.eventDialog;
                                   }
                                   this.eventDialog = new HJ.EventDetail("Event Details", this, null);  
                                   this.eventDialog.setWorkspace(this.workspace);
                                   this.eventDialog.width = "470px";
                                   this.eventDialog.showHTMLTemplate(basePageURL + "EventDetails2.html", dialogContainer, "eventDetail");
        
                                   if(!this.isPrivateCalendar(sch)) {
                                       var object = cloneObject(obj);
                                       this.eventDialog.setObj(object, mode, sch, actualDate, driverSch,
                                                               isFocusGuestTab);
                                   } else {
                                       this.eventDialog.setObj(obj, mode, sch, actualDate, driverSch,
                                                               isFocusGuestTab);
                                   }
                                   return false;
                               },

    /**
     * Edit an event that was retrieved from the database, possibly without
     * its schedule being fetched with it (as on the archive page).
     * 
     * @param event an Event as fetched from the db
     *
     * @param isCreateMode true if the event is being created new 
     *        (as for a copy), false if an existing event is being edited.
     *
     * @return void
     */
    editEvent: function(event, isCreateMode, dialogContainer, isFocusGuestTab) {
        // find the schedule for the event
        var schedule;
        for (var i = 0; i < this.scheduleList.length; i++) {
            if (this.scheduleList[i].UUID == event["scheduleId"]) {
                schedule = this.scheduleList[i];
                break;
            }
        }
        if (schedule == null) {
            // XXX: signal error to user? 
            return;
        }
        // XXX: fixme: What to do about a driver schedule, if any? 
        this.editEventDetails(event, 
                              schedule, 
                              isCreateMode, 
                              -1, 
                              null, 
                              dialogContainer,
                              isFocusGuestTab);
    },
   
    printEventClicked: function() {
        var noOfIds = "";
        for (index = 0;index <this.shownScList.length ;index++ ) {
            if (noOfIds == "") {
                noOfIds = this.shownScList[index].UUID;
            }
            else {
                noOfIds += "," + this.shownScList[index].UUID;
            }     
        }  
        var req = new Af.DataRequest(svcURL,this.printCompleted.bind(this), this.printFailed.bind(this), null, this.requestTimedout.bind(this));           
        req.addService("WorkspaceService", "getPrintHtmlFromXML");
        req.addParameter("templateName", "printAgenda");
        req.addParameter("xlstFile","printAgenda.xsl");
        req.addParameter("noOfIds",noOfIds);
        req.addParameter("displayCalType",this.currentCalType);     
        req.addParameter("date",this.date.getTime());
        ajaxEngine.processRequest(req);  
        return false;    
    },
  
    printingDone: function() {
        this.currentCalendar.scrollTo7AM();
    },
   
    todaysCalendarSelected: function() {
        this.currentCalType = "day";
        if (this.currentCalendar != this.dailyCalendar) {
            this.setActiveLink(this.dayCalendarLink);
            this.currentCalendar = this.dailyCalendar;
            this.currentAgenda = this.dailyAgenda;
            this.date = new Date();
            this.date.setHours(0,0,0,0);
            this.showCurrentCalendar(true);
        } else {
            this.saveCurrentCalendarDate();
            var dt = new Date();
            dt.setHours(0,0,0,0);
            if (dt.getTime() != this.date.getTime()) {
                this.date = dt;
                this.showCurrentCalendar(true);
            }
        }
       
        return false;
    },
   
    previousCalendarSelected: function() {
        app.showBusy();
        if (this.calendarDisplayStyle.checked) {
            this.currentAgenda.previous();
            this.date = this.currentAgenda.date;
        } else {
            this.currentCalendar.previous();
            this.date = this.currentCalendar.date;
        }
        app.endBusy();
        return false;
    },
   
    dayCalendarSelected: function() {
        this.currentCalType = "day";
        var f = this.currentCalendar != this.dailyCalendar;
        //   if (this.currentCalendar != this.dailyCalendar) {
        this.saveCurrentCalendarDate();
        this.setActiveLink(this.dayCalendarLink);
        this.currentCalendar = this.dailyCalendar;
        this.currentAgenda = this.dailyAgenda;
        this.showCurrentCalendar(f);
        //  }
        return false;
    },
   
    weeklyCalendarSelected: function() {
        app.showBusy();
        this.currentCalType = "weekly";
        if (this.currentCalendar != this.weeklyCalendar) {
            this.saveCurrentCalendarDate();
            this.setActiveLink(this.weeklyCalendarLink);
            this.currentCalendar = this.weeklyCalendar;
            this.currentAgenda = this.weeklyAgenda;
            this.showCurrentCalendar(true);
        }
        app.endBusy();
        return false;
    },
   
    monthlyCalendarSelected: function() {
        app.showBusy();
        this.currentCalType = "monthly";
        if (this.currentCalendar != this.monthlyCalendar) {
            this.saveCurrentCalendarDate();
            this.setActiveLink(this.monthlyCalendarLink);
            this.currentCalendar = this.monthlyCalendar;
            this.currentAgenda = this.monthlyAgenda;
            this.showCurrentCalendar(true);
        }
        app.endBusy();
        return false;
    },
   
    yearlyCalendarSelected: function() {
        app.showBusy();
        this.currentCalType = "yearly";
        if (this.currentCalendar != this.yearlyCalendar) {
            this.saveCurrentCalendarDate();
            this.setActiveLink(this.yearlyCalendarLink);
            this.currentCalendar = this.yearlyCalendar;
            this.currentAgenda = this.yearlyAgenda;
            this.showCurrentCalendar(true);
        }
        app.endBusy();
        return false;
    },
   
    nextCalendarSelected: function() {
        app.showBusy();
        if (this.calendarDisplayStyle.checked) {
            this.currentAgenda.next();
            this.date = this.currentAgenda.date;
        } else {
            this.currentCalendar.next();
            this.date = this.currentCalendar.date;
        }
        app.endBusy();
        return false;
    },

    // Called from NewHomePage calendar. 
    // We might want either better integration between the NewHomePageCalendar
    // the other calendars or better separation, but for now it's not clear
    // what's best. 
    setCalendarDate: function(date) {
        this.date = date;
        this.renderCurrentCalendar(false);
    },
   
    setActiveLink:function(l) {

        //  CHANGE COLOR OF SELECTED CALENDAR'S HEADER TAB
        
        if(l.parentNode.childNodes[0] != null){
            var id = l.parentNode.childNodes[0].id;
            var classNm = l.parentNode.childNodes[0].className;
            if( classNm == (id + "_on")){
                //   l.parentNode.childNodes[0].className = (id + "_off");
            }else{

                l.parentNode.childNodes[0].className = (id + "_on");
                if(l == this.dayCalendarLink || l == this.todaysCalendarLink){  
                    this.todaysCalendarLink.className = "todaysCalendar_on";                    
                    this.dayCalendarLink.className = "dayCalendar_on";  
                }else{
                    this.todaysCalendarLink.className = "todaysCalendar_off";
                    this.dayCalendarLink.className = "dayCalendar_off";     
                }
                if(l != this.weeklyCalendarLink){                   
                    this.weeklyCalendarLink.className = "weeklyCalendar_off";
                }
                if(l != this.monthlyCalendarLink){                  
                    this.monthlyCalendarLink.className = "monthlyCalendar_off";
                }
                if(l != this.yearlyCalendarLink){                   
                    this.yearlyCalendarLink.className = "yearlyCalendar_off";
                }
            }
        }/*
           this.currentActiveLink.parentNode.className = "calTime";
           this.currentActiveLink = l;
           this.currentActiveLink.parentNode.className = "calTime active";
           //this.todaysCalendarLink.className = "calTime";
           this.todaysCalendarLink.className = "todaysCalendar_off";*/
    },
   
    dateClicked: function(calendar, date) {
        var f = this.currentCalendar != this.dailyCalendar;
        this.currentCalType = "day";
        this.date = new Date(date.getTime());
        this.date.setHours(0,0,0,0);
        this.setActiveLink(this.dayCalendarLink);
        this.currentCalendar = this.dailyCalendar;
        this.currentAgenda = this.dailyAgenda;
        this.showCalendar();
        this.showCurrentCalendar(f);
      
    },
   
    addToShownList: function(sc) {    
        for (var i=0; i<this.shownScList.length; i++) {
            if (this.shownScList[i] == sc) {
                return;
            }
        }
        var t = this.shownScList.length == 0;
        this.shownScList.push(sc);
        this.shownScheduleListChanged();    
        if (t && !this.calendarDisplayStyle.checked) {
            this.currentCalendar.scrollTo7AM();
        }  
    },
   
    selectedScheduleDeleted: function() {
        this.currentRow = -1;
        this.currentSch = null;
    },
  
    removeFromShownList: function(sc) {
        var l = new Array();
        var refresh = false;
        for (var i=0; i<this.shownScList.length; i++) {
            if (this.shownScList[i] != sc) {
                l.push(this.shownScList[i]);
            } else {
                refresh = true;
            }
        }
      
        this.shownScList.length = 0;
        for (var i=0; i<l.length; i++) {
            this.shownScList.push(l[i]);
        }
        if (refresh) {
            this.shownScheduleListChanged();
        }       
    },
   
    shownScheduleListChanged: function() {
        if (this.target.childNodes.length < 1 || this.target.childNodes[0] != this.calendarContainer) {
            //  This code is not working in Firefox   so commenting return;
            // return;
        }
        if (this.calendarDisplayStyle.checked) {
            this.currentAgenda.scheduleListChanged(this.shownScList);
        } else {
            this.currentCalendar.scheduleListChanged(this.shownScList);
        }
      
        this.miniCalendar.scheduleListChanged(this.shownScList);
    },
   
    myScheduleListChanged: function(doNotShow) {
     
        this.scheduleTable.setDataList(this.scheduleList);
        this.addCheckClickListener(this.scheduleTable);
      
        if (this.currentSch != null) {
            this.currentRow = findObjIndex(this.scheduleList, this.currentSch);
        }
        if (this.currentRow >= 0 && this.currentRow < this.scheduleList.length) {
            var rowColor = this.getRowColor(this.scheduleList[this.currentRow]["color"]);
            this.scheduleTable.selectRow(this.currentRow, rowColor.background, rowColor.foreground);
            var tr = this.scheduleTable.tableElement.rows[this.currentRow];

            //  tr.cells[1].childNodes[0].checked = true;
            var cell = tr.cells[1];

            var check;

            // following is needed for the Firefox

            for (var i=0; i<cell.childNodes.length; i++) {
                if (cell.childNodes[i] && cell.childNodes[i].tagName == 'INPUT') {
                    check = cell.childNodes[i];
                    break;
                }
            }
            if (check != null) {
                check.checked = true; 
            }
         
                 
        } else {
            this.currentRow = -1;
        }
      
        for (var i=0; i<this.shownScList.length; i++) {
            var idx = findObjIndex(this.scheduleList, this.shownScList[i]);
            if (idx >= 0) {
                var rowColor = this.getRowColor(this.scheduleList[idx]["color"]);
                var tr = this.scheduleTable.tableElement.rows[idx];
                tr.cells[2].style.backgroundColor = rowColor.background;
                tr.cells[2].style.color = rowColor.foreground;
            
                for(var idx = 0; idx < tr.cells[1].childNodes.length; idx++){
                    if(tr.cells[1].childNodes[idx].tagName == 'INPUT'){
                        tr.cells[1].childNodes[idx].checked = true;
                    }
                }        
                             
            }
        }
        if (!doNotShow) {
            this.showCurrentCalendar(false);
        }
    },
   
    getRowColor: function(bc) {
        var c = getTextColor(bc);
        var bc = getBackground(bc);
      
        return {background: bc, foreground: c};
    },   
   
        
    printCompleted: function(response)    {
        var p = new Af.PrintUtil(this);
        p.showPrintView(response);      
    },
  
    printFailed: function() {     
        showMessageDialog("We are currently unable to print Calendar. Please try again.", "Excuse us!", 350, 100);
    },
   
    requestTimedout: function() {
        showMessageDialog("We are currently unable to print Calendar. Please try again.", "Excuse us!", 350, 100);
    },

    doDelCommCalndLink: function(e) {       
        consumeEvent(e);
        if (this.communityScheduleTable.selectedRowNumber == -1) {
            showMessageDialog("Please select the community calendar you would like to delete, then click Delete icon.", "Select Community Calendar", 350, 100);
            return false;
        }
        var dataList = this.communitySchedules;
        this.calObj = dataList[this.communityScheduleTable.selectedRowNumber];
        showConfirmDialog("Are you sure you want to delete this Calendar?", "Are You Sure?", 300, 110, this.doDelCommCalndr.bind(this));
        return false;
    },
    
    doDelCommCalndr: function() {
        hideDialogWin();      
        var dataList = this.communitySchedules;
        this.calObj = dataList[this.communityScheduleTable.selectedRowNumber];
        if(this.calObj != null) {
            var dataTable = new Af.DataTable(this.communitySchedules);
            dataTable.deleteObjectByIndex(this.communityScheduleTable.selectedRowNumber);                 
            this.communityScheduleTable.setDataList(dataTable.getDataList());    
            this.removeFromShownList(this.calObj);    
            this.deleteCommCalander();
        }                                                                     
    },

    deleteCommCalander: function() {
        var req = new Af.DataRequest(svcURL,this.reqDeletedCompleted.bind(this), 
                                     requestFailedCommon, null, requestTimedoutCommon);
        req.addService("WorkspaceService", "deleteCommCalander");
        req.addParameter("UUID", this.calObj.UUID);
        ajaxEngine.processRequest(req);
    },
   
    reqDeletedCompleted: function(response) {
        var res = response.responseText;
        if(res == "SUCCESS") {
            showMessageDialog("This Community Calendar has been successfully deleted. ", " Deletion Successful", 320, 100);
            this.communityCalendarListChanged();
        } else {
            showMessageDialog("We are currently unable to delete this Community Calendar. Please try again.", "Excuse us!", 320, 100);
        }
    },
   
    doDelSharedSchLink: function(e) {
        consumeEvent(e);
        if (this.sharedScheduleTable.selectedRowNumber == -1) {
            return false;
        }
        var dataList = this.sharedSchedules;
        this.calObj = dataList[this.sharedScheduleTable.selectedRowNumber];
        //showConfirmDialog("Are you sure you want to delete this Calendar? <br/>It is currently being shared with other people.", "Are You Sure?", 330, 130, this.doDelSharedCalndr.bind(this));
        showConfirmDialog("You will need to ask the originator to send it to you again if you need it.", "Are you sure you want to delete this calendar? ", 370, 120, this.doDelSharedCalndr.bind(this));       
        return false;
    },
    
    doDelSharedCalndr: function() {
        hideDialogWin();      
        var dataList = this.sharedSchedules;
        this.calObj = dataList[this.sharedScheduleTable.selectedRowNumber];
        if(this.calObj != null) {
            var dataTable = new Af.DataTable(this.sharedSchedules);
            dataTable.deleteObjectByIndex(this.sharedScheduleTable.selectedRowNumber);                
            this.sharedScheduleTable.setDataList(dataTable.getDataList());   
            this.removeFromShownList(this.calObj);    
            this.deleteSharedCalander();
        }
    },
   
    deleteSharedCalander: function() {
        var req = new Af.DataRequest(svcURL,this.reqSharedCalDeletedCompleted.bind(this), 
                                     requestFailedCommon, null, requestTimedoutCommon);
        req.addService("WorkspaceService", "deleteSharedCalander");
        req.addParameter("UUID", this.calObj.UUID);
        ajaxEngine.processRequest(req);
    },
   
    reqSharedCalDeletedCompleted: function(response) {
        var res = response.responseText;
        if(res == "SUCCESS") {
            showMessageDialog("Your Calendar has been successfully deleted.", "Deletion Successful", 300, 100); 
            this.sharedScheduleTable.setDataList(this.sharedSchedules);    
            this.addCheckClickListener(this.sharedScheduleTable);
            this.updateShceduleSelection(this.sharedScheduleTable, this.sharedSchedules);
        } else {
            showMessageDialog("We are currently unable to delete this shared Calendar. <br/> Please try again.", "Excuse us!", 300, 100);
        }
    },
    
    updateShceduleSelection: function(tbl, schl) {
        var row = -1;
        for (var i=0; i<this.shownScList.length; i++) {
            var idx = findObjIndex(schl, this.shownScList[i]);
            if (idx >= 0) {
                if (row < 0) {
                    row = idx;
                }
                var rowColor = this.getRowColor(schl[idx]["color"]);
                var tr = tbl.tableElement.rows[idx];
                tr.cells[2].style.backgroundColor = rowColor.background;
                tr.cells[2].style.color = rowColor.foreground;
                tr.cells[1].childNodes[0].checked = true;
            }
        }
        tbl.selectedRowNumber = row;
        this.showCurrentCalendar(false);
    },
    
    getNote: function(time) {
        var d = new Date(time);
        d.setHours(0,0,0,0);
        time = d.getTime();
        var l = this.workspace["notes"];
        for (var i=0; i<l.length; i++) {
            var n = l[i];
            var t = parseInt(n["notedate"]);
            if (t == time) {
                return n;
            }
        }
        return null;
    },
    
    saveNote: function() {
        var s = "<properties>";
        var v = this.journalText.value;
        if (v == null) {
            v = "";
        }
        v = xmlEncode(v);
        s += "<property name=\"description\" value=\"" + v + "\" />";
       
        if (this.calendarDisplayStyle.checked) {
            this.date = this.currentAgenda.date;
        } else {
            this.date = this.currentCalendar.date;
        }
       
        var d = new Date(this.date.getTime());
        d.setHours(0,0,0,0);
       
        s += "<property name=\"notedate\" value=\"" + d.getTime() + "\" />";
       
        s += "</properties>";
       
        this.currentNote = this.getNote(d.getTime());
       
        if (this.currentNote == null) {
            this.currentNote = new Object();
            this.currentNote["notedate"] = d.getTime();
            var l = this.workspace["notes"];
            l.push(this.currentNote);
        }
        this.currentNote["description"] = v;
       
       
        var req = new Af.DataRequest(svcURL,this.reqSaveNoteCompleted.bind(this), 
                                     requestFailedCommon, null, requestTimedoutCommon);
        req.addService("WorkspaceService", "saveNotes"); 
      
        if (this.currentNote.UUID != null) {
            req.addParameter("UUID", this.currentNote.UUID);
        } 
      
        req.xmlDoc = s;

        ajaxEngine.processRequest(req);
      
        return false;
    },
    
    reqSaveNoteCompleted: function(response) {
        if (this.currentNote.UUID == null) {
            this.currentNote.UUID = response.responseText;
        }
        // showMessageDialog("Your record has been successfully saved. ", "Success !", 300, 100, null, true);
    },
    
    showSelectScehduleMessage: function() {     
        var l = this.scheduleList;
        if(this.scheduleTable.selectedRowNumber > -1) {
            showMessageDialog("You need to select a My Calendar for the intended operation. <br/>A selected Calendar is shown using a long bar in the Calendar widget.", "Excuse us!", 400, 150); 
            return;
        }
        else if(this.sharedScheduleTable.selectedRowNumber > -1) {
            showMessageDialog("This is a shared Calendar. <br/>You do not have access to modify it.", "Excuse us!", 310, 120); 
            return;
        } else if(this.communityScheduleTable.selectedRowNumber > -1) {
            showMessageDialog("This is a community Calendar. <br/>You do not have access to modify it.", "Excuse us!", 310, 120); 
            return;
        } else {
            if (l.length == 0) {
                showMessageDialog("There are no Calendars to add the event to. Create a Calendar first.","Excuse us!", 350, 120);
                return;
            }
            showMessageDialog("You need to select a My Calendar for the intended operation. <br/>A selected Calendar is shown using a long bar in the Calendar widget.", "Excuse us!", 400, 150); 
        }
    },
   
    //change calendar's frame color
    setCalendarColor: function() {
        if (this.currentRow >= 0 && this.currentRow < this.scheduleList.length) {
            var color = this.getRowColor(this.scheduleList[this.currentRow]["color"]);
            this.target.style.backgroundColor = color.background; 
        }
    },
    isPrivateCalendar: function(sch) {
        if(sch == null) {
            return false;
        }
        this.index = findObjIndex(this.scheduleList, sch)
        if(this.index == -1)  {
            return false;
        }       
        return true;
    },

    loadEventData: function(month) {
        if (month == null) {
            // XXX: ideally, callers should not be passing null
            return false;
        }
        // console.log("loadEventData for " + month);
        // XXX: for now, fetch 10 days each way from the 
        // end of the current month.
        // This should cover monthly, weekly, and daily.
        // In the future, we might want to cache less data. 
        // XXX: not implemented: only fetch if we don't already have the 
        // data. 
        var d = this.getMonthStart(month);
        if (this.eventDataMonth != null 
            && d.getTime() == this.eventDataMonth.getTime()) {
            // already have the data for that month
            // console.log("Already have data for " + d);
            return true;
        } else {
            // console.log("Fetching event data for " + d + " already have " 
            // + this.eventDataMonth);
        }
        var startDT = d.getTime() - this.DT_10_DAYS;
        var endDT = startDT + this.DT_51_DAYS;
        // console.log("calling loadSchedule");
        this.loadSchedule(startDT, endDT);
        this.eventDataMonth = d;
        return false;
    },

    getMonthStart: function(month) {
        var d = new Date(month);
        d.setDate(1);
        d.setHours(0,0,0,0);
        return d;
    },

    // Get the schedule data for the give date range
    loadSchedule: function(startDT, endDT) {
        // debugging only
        var start = new Date(startDT);
        var end = new Date(endDT);
        // console.log("Fetching from " + start + " to " + end);
        var req = new Af.DataRequest(
                svcURL,
                this.requestGetSchedulesCompleted.bind(this), 
                requestFailedCommon.bind(this), 
                null, 
                requestTimedoutCommon.bind(this));
        req.addService("WorkspaceService", "getSchedules");
        req.addParameter("startDT", startDT);
        req.addParameter("endDT", endDT);
        ajaxEngine.processRequest(req);
      
    },

    requestGetSchedulesCompleted: function(response) {
        //debugA(response.responseText);
        var xds = new Af.XMLToDataSet(response.responseXML);
        // console.log("Got response");
        var scheduleLists = xds.data.ObjList;

        // hack: new array so I can use createOneToManyAssoc and 
        // copy code from Dashboard.completeWorkspace
        // and for more obvious code
        var schedules = new Array();
        schedules["schedule"] = scheduleLists[0].Schedule
        schedules["sharedSchedule"] = scheduleLists[1].Schedule
        schedules["communitySchedule"] = scheduleLists[2].Schedule
        if (schedules["schedule"] == null) {
            createOneToManyAssoc(schedules, "schedule", "Schedule");
        }
        if (schedules["sharedSchedule"] == null) {
            createOneToManyAssoc(schedules, "sharedSchedule", "Schedule");
        }
        if (schedules["communitySchedule"] == null) {
            createOneToManyAssoc(schedules, "communitySchedule", "Schedule");
        }
       
        // Schedules have not been set, initialize
        if (this.scheduleList == null) {
            this.setSchedules(schedules["schedule"], 
                              schedules["sharedSchedule"],
                              schedules["communitySchedule"]);
            return;
        }
       
        // 3-long array: schedule, sharedSchedule, communitySchedule
        // update the events in each schedule
        this.updateEvents(this.scheduleList, schedules["schedule"]);
        this.updateEvents(this.sharedSchedules, schedules["sharedSchedule"]);
        this.updateEvents(this.communitySchedules, 
                          schedules["communitySchedule"]);
       
        this.renderCurrentCalendar(false);
    },

    // update the events for a current schedule list
    updateEvents: function(current, updated) {
        for (var i = 0; i < current.length; i++) {
            var c = current[i];
            var u = findObjById(updated, current[i].UUID);
            if (u != null) {
                c["event"] = u["event"];

            }
        }
    },

    setNewHomePageCalendar: function (calendar) {
        this.newHomePageCalendar = calendar;
    },

    getNewHomePageCalendar: function () {
    	return this.newHomePageCalendar;
    },
    
    /** 
     * Some event changed.
     * Called from EventDetail.js
     * XXX: This is only used to refresh NewHomePageCalendar and Archive
     *      In future, this should also be used for the other calendars, 
     *      but I don't want to spend time now untangling things. 
     *      See app.schedule.eventChanged calls in EventDetails.js
     */
    eventChanged: function(event, wasDeleted) {
        if (this.newHomePageCalendar != null) {
            this.newHomePageCalendar.eventChanged(event, wasDeleted);
        }
        // XXX: add notification to new archive display on 
        // signups page
        if ((app.SIHP != null) && (app.SIHP.archive != null))
        app.SIHP.archive.eventChanged(event, wasDeleted);
    }

}


