HJ.EventDetail = Class.create();

HJ.EventDetail.prototype = Object.extend(new Af.HtmlDialog(), {

   initialize: function(title, handler, content) {
	    this._initializeDialog(title, handler, content);
	    this.top = 200;
	    this.dateUtil = new Af.DateUtil();
	    this.defaultMessage1 = "";
		this.IsInvitationSent = false;
		this.editing = true;
		this.saveStartDate = null;
		this.actualDate = null;
		this.savedRepeatFlag = null;
   },
   
   setWorkspace: function(workspace) {
      this.workspace = workspace;
   },
	
   templateLoaded: function() {
      // element collection class limits the look up by id within the scope of the given element (in this case this.element).
      // In case there are other elements with the same id in the "document" scope, this avoids id collision
      var ec = new Af.ElementCollection(this.element);
      
     
	  this.save = ec.getFirstElementById("save");
	  this.armedButton = this.save;
	  this.save.onclick = this.doSaveStep1.bind(this);
	  this.send = ec.getFirstElementById("sendInvitation");
	  this.send.onclick = this.doSend.bind(this);
	  this.deleteB =  ec.getFirstElementById("delete");
	  this.deleteB.onclick = this.deleteEventConfirm.bind(this);

	  this.previous = ec.getFirstElementById("previous");
	  this.previous.onclick = this.doPrevious.bind(this);
	  
	 this.peopleSelectTrigger = ec.getFirstElementById("peopleSelectTrigger");
	 this.peopleSelectTrigger.onclick = this.selectPeople.bind(this);
	 
	 this.previewInvitation = ec.getFirstElementById("previewInvitation");
	 this.previewInvitation.onclick = this.doPreview.bind(this);
	 
	 this.eventTaskListContainer = ec.getFirstElementById("eventTaskListContainer");
	 
	// this.inviteesList = ec.getFirstElementById("inviteesList");
	 this.indvslSelectionList = ec.getFirstElementById("indvslSelectionList");
	 this.groupSelectionList = ec.getFirstElementById("groupSelectionList");
	 this.indvslSelectionList.innerHTML = "";
	 this.groupSelectionList.innerHTML = "";


	 this.titleCursor = ec.getFirstElementById("displayName");
	 if(this.titleCursor!=null){
		this.titleCursor.onfocus = this.focusOnNameTextBox.bindAsEventListener(this);
		this.titleCursor.onblur = this.focusLostNameTextBox.bindAsEventListener(this);		
		this.defaultEventName = this.titleCursor.value;
	 }
	 
	 
	 
	  this.editor = new Af.ObjEditor();
	  
	  this.startDTBox = ec.getFirstElementById("startDT");
	  this.nameComp = this.editor.addTextByEC(ec, "displayName");
	  
	  this.scheduleSelect = this.editor.addDynamicSelectByEC(ec, "schedule", new Array(), null, "name", "UUID");
	  this.date1 = this.editor.addDatetByEC(ec, "startDT", "dateTrigger");
	  this.date2 = this.editor.addDatetByEC(ec, "startDT", "startDT");
	  this.date = this.date1;

	  this.date.errorHandler = new this.DateFormatErrorHandler();	  
	  this.dateTrigger = ec.getFirstElementById("dateTrigger");
	  this.dateTrigger.onmouseover = this.datePickerOpened.bindAsEventListener(this);
	  this.startDTBox.onmouseover = this.datePickerOpened.bindAsEventListener(this);

	  this.taskList = this.editor.addDynamicSelectByEC(ec, "taskList", new Array(), null, "name", "UUID");
	  this.editor.addTextByEC(ec, "locationName");
	  this.addressFlag = this.editor.addCheckBoxByEC(ec, "addressFlag");
	  this.city = this.editor.addTextByEC(ec, "city");
	  this.street = this.editor.addTextByEC(ec, "street");
	  this.state = this.editor.addTextByEC(ec, "state");
	  this.zip = this.editor.addTextByEC(ec, "zip");
	  var c1 = this.editor.addCheckBoxByEC(ec, "timeFlag");
	  var c2 = this.editor.addCheckBoxByEC(ec, "noTimeFlag");
	  c1.behavior.addPeer(c2);
	  c2.behavior.addPeer(c1);
	  this.timeFlag = c1;
	  this.noTimeFlag = c2;
	  
	  this.editor.addCheckBoxByEC(ec, "drivingFlag");
	  this.editor.addCheckBoxByEC(ec, "helpAsked");
	  this.driverAssgined = this.editor.addCheckBoxByEC(ec, "driverAssgined");

	  
	  this.taskList.addValueChangeListener(this);
	  this.date.addValueChangeListener(this);
	  this.driverAssgined.element.onclick = this.driverAssginedCheckChanged.bind(this);
	  
	  
	  this.minuteBefore1 = this.editor.addIntByEC(ec, "minuteBefore1");
	  this.minuteBefore2 = this.editor.addIntByEC(ec, "minuteBefore2");
	  
	  this.repeatFlag = this.editor.addCheckBoxByEC(ec, "repeatFlag");

	  this.repeatUntil1 = this.editor.addDatetByEC(ec, "repeatUntil", "repeatUntilTrigger");
	  this.repeatUntil2 = this.editor.addDatetByEC(ec, "repeatUntil", "repeatUntil");

	  this.repeatUntil = this.repeatUntil1;
	  this.repeatUntilBtn = ec.getFirstElementById("repeatUntilTrigger");
	  this.repeatUntilBox = ec.getFirstElementById("repeatUntil");
	  this.repeatUntilBtn.onmouseover = this.datePickerOpened.bindAsEventListener(this);
	  this.repeatUntilBox.onmouseover = this.datePickerOpened.bindAsEventListener(this);
		  

	  
	  this.reminderFlag = this.editor.addCheckBoxByEC(ec, "reminderFlag");
	  
	  this.editor.addIntByEC(ec, "reminderWhen");
	  this.editor.addSelectByEC(ec, "reminderType");
	  
	  this.emails = document.getElementById("emails");
	  this.inviteeEmails = this.editor.addTextAreaByEC(ec, "emails");
	  this.message1 = this.editor.addTextAreaByEC(ec, "message1");
	  this.defaultMessage1 = this.message1.element.value;
	  this.message2 = this.editor.addTextAreaByEC(ec, "message2");
	 
	  this.createNewList = ec.getFirstElementById("createNewList");
	  this.createNewList.onclick = this.doAddNewMyList.bindAsEventListener(this); 
	  
	  this.drivingTab = ec.getFirstElementById("drivingTab");
	  this.selectDriver1 = ec.getFirstElementById("selectDriver1");
	  this.selectDriver2 = ec.getFirstElementById("selectDriver2");
	  this.deleteDriver1 = ec.getFirstElementById("deleteDriver1");
	  this.deleteDriver2 = ec.getFirstElementById("deleteDriver2");
	  this.guestTab = ec.getFirstElementById("guestTab");
	  
	  this.additionalSchedule = ec.getFirstElementById("additionalSchedule");
	  
	  this.additionalScheduleList = ec.getFirstElementById("additionalScheduleList");
	  this.eventSpecialMessage = ec.getFirstElementById("eventSpecialMessage");
	  
	  
	  this.selectDriver1.onclick = this.doSelectDriver1.bind(this);
	  this.selectDriver2.onclick = this.doSelectDriver2.bind(this);

		this.deleteDriver1.onclick = this.doDeleteDriver1.bind(this);
		this.deleteDriver2.onclick = this.doDeleteDriver2.bind(this);


	  
	  this.additionalSchedule.onclick = this.doSelectAddlSchedules.bind(this);
	  
	  this.driver1Name = ec.getFirstElementById("driver1Name");
	  this.driver2Name = ec.getFirstElementById("driver2Name");
	  
	  this.noResponseId = ec.getFirstElementById("noResponseId");
	  this.yesId = ec.getFirstElementById("yesId");
	  this.noId = ec.getFirstElementById("noId");
	  this.totalId = ec.getFirstElementById("totalId");
	  
	  this.listTabEventDetail = ec.getFirstElementById("listTabEventDetail");
	  this.drivingTabEventDtTime = ec.getFirstElementById("drivingTabEventDtTime");
	  
	  this.myOneList = new HJ.MyOneList(ec.getFirstElementById("listTabContent"), this.element);
	  
	  this.inviteesTable = new Af.HtmlTable("inviteesTable", "result, fullName", ec);
	  
	  this.htmlTab = new Af.HtmlTab("tabMenu","basicTab, drivingTab, guestTab, listTab",
						"basicTabContent, drivingTabContent, guestTabContent, listTabContent");
	  
	  this.htmlTab.validityFlags["listTabContent"] = false;
	  this.htmlTab.validityFlags["drivingTabContent"] = false;
	  
	  this.htmlTab.tabSelectionListener = this;
	
	  this.eventTaskListContainer.style.display = "none";
	  
	  this.repeatType = ec.getFirstElementById("repeatType");
	  
	  this.repeatType.onchange = this.repeatTypeChanged.bind(this);
	  
	  this.subTypeTable = ec.getFirstElementById("subTypeTable");
	 
      this.fromTime = new Af.TimeDropDown(ec.getFirstElementById("fromTime"),
		ec.getFirstElementById("fromTimeSelector"), this, ec.getFirstElementById("basicTabContent"), this.element);
		
	  this.toTime = new Af.TimeDropDown(ec.getFirstElementById("toTime"),
		ec.getFirstElementById("toTimeSelector"), this, ec.getFirstElementById("basicTabContent"), this.element);
	
      this.addressFlag.element.checked = false;
	  this.addressFlag.element.onclick = this.doIncludeAddress.bind(this);
	  
	  this.reminderFlag.element.checked = false;
	  this.reminderFlag.element.onclick = this.doReminderFlagChange.bind(this);
	  
	  this.repeatFlag.element.checked = false;
	  this.repeatFlag.element.onclick = this.doRepeatFlagChange.bind(this);
	  
	  this.repeatBlock = ec.getFirstElementById("repeatBlock");
	//  this.reminderBlock = ec.getFirstElementById("reminderBlock");
      
      this.doIncludeAddress();
      this.doReminderFlagChange();
      this.doRepeatFlagChange();
      
      this.defaultEmailMessage = this.emails.value;
	  this.emails.onfocus = this.focusOnTextBox.bindAsEventListener(this);
	  this.emails.onblur = this.focusLostTextBox.bindAsEventListener(this);

	  
	  
	 this.rsvpTabs = [ec.getFirstElementById("allTab"), ec.getFirstElementById("yesTab"), 
		ec.getFirstElementById("noTab"), ec.getFirstElementById("noResponseTab")];
	
	 for (var i=0; i<this.rsvpTabs.length; i++) {
	    this.rsvpTabs[i].onclick = this.rsvpTabSelected.bind(this, i);
	 }
	 
	 this.rsvpIndex = 0;
	 
	 this.rsvpTab0BC = this.rsvpTabs[0].style.backgroundColor;
	 this.rsvpTab1BC = this.rsvpTabs[1].style.backgroundColor;
	 
	 if (this.obj != null) {
	     this.mySetObj();
	  }
   },
   
   DateFormatErrorHandler : function() {
      this.showError = function() {
         showMessageDialog("There is an error in the date format, please try again.", "Excuse us!", 300, 100);
      }
   },
   
	datePickerOpened: function(evt) {
		var e = evt.target ? evt.target : evt.srcElement;		 	  	
		if (e != null) {	
			if("startDT" == e.id){
				this.date = this.date2;					
			}else if("dateTrigger" == e.id){				
				this.date = this.date1;				
			}else if("repeatUntilTrigger" == e.id) {
				 this.repeatUntil = this.repeatUntil1;
			}else if("repeatUntil" == e.id) {
				 this.repeatUntil = this.repeatUntil2;
			}
		}
	},
   setFieldsState: function() {
      var f;	  
	  if (this.index_S_Sch == -1 && this.index_C_Sch == -1) {
		f = false;
	  }
	 else if(this.index != -1) {
		f = false;
	 }
	  else {
	    f = true;
	  }
	  if (f || this.isCreateMode) {
		  this.deleteB.disabled = "true";
		  this.deleteB.style.borderColor = "#888888";
		  this.deleteB.style.color = "#888888";
	  }
	  /* this.nameComp.element.disabled = f;
	  this.date.element.disabled = f;
	  this.dateTrigger.disabled = f;
	  */
   },
   
   setButtonsDisbaled: function(f) {
	  this.save.disabled = f;
	  this.send.disabled = f;
	  this.deleteB.disabled = f || this.isCreateMode;
   },
   
   hide: function() {
	 if (this.element != null) {
	   if (this.visible) {
			var p;
			if (typeof this.container == "string") {
			   p = document.getElementById(this.container);
			} else {
			   p = container;
			}
			p.removeChild(this.element);
		}
		this.showSelectBoxes();
		this.fromTime.hide();
		this.toTime.hide();
	 }
	 this.visible = false;	
   },
  
   doIncludeAddress: function() {
      var s = "none";
      if (this.addressFlag.element.checked) {
         s = "";
      }
      this.city.element.parentNode.style.display = s;
      this.street.element.style.display = s;
      this.state.element.parentNode.style.display = s;
      this.zip.element.parentNode.style.display = s;
   },
   
   doReminderFlagChange: function() {
      var s = "none";
      if (this.reminderFlag.element.checked) {
         s = "none";
      }
     // this.reminderBlock.style.display = s;
   },
   
   doRepeatFlagChange: function() {
      var s = "none";
      if (this.repeatFlag.element.checked) {
         s = "";
		 this.repeatFlag.setValue(true);
         this.obj["repeatFlag"] = true;	
      }
      this.repeatBlock.style.display = s;
   },
  
   timeChanged:function(tdd, newValue, ov) {
      if (tdd == this.fromTime) {
         var newValue = parseInt(newValue);
         var ov = parseInt(ov);
         var tt = parseInt(this.toTime.getValue());
         var tt = newValue + (tt - ov);
         if (tt >= 1440) {
           tt = tt - 1440; // next day
         } else if (tt < 0) {
            tt = 1440 + tt;
         }
         this.toTime.setValue(tt);
      }
   //   this.setStartEnd();

   // Code to check radio button When time selected/entered.
	  if(this.timeFlag != null){
			this.timeFlag.setValue("true");
			this.obj.timeFlag = "true";
			this.noTimeFlag.setValue("false");
			this.obj.noTimeFlag = "false";
			this.timeFlag.element.checked;			
	  }
	  this.setStartEnd();
   },
   
   
   doNext: function() {
      this.htmlTab.next();
   },
   
   doPrevious: function() {
      this.htmlTab.previous();
   },
   
  
   postCreate: function(obj) {
      if (this.timeFlag != null) {
		this.timeFlag.setValue(true);
		this.fromTime.setValue("480");
		this.toTime.setValue("510");
		//this.nameComp.setValue("New Event");
      }
   },
   
   setObj: function(obj, mode, sch, actualDate, scheduleOn, isFocusGuestTab) {
       this.scheduleOn = scheduleOn;
       this.savedRepeatFlag = obj["repeatFlag"];
       this.actualDate = actualDate;
       this.saveStartDate = obj["startDT"];
       if (actualDate != null && actualDate != -1) {
          var t = new Date(actualDate);
          
          obj["startDT"] = actualDate;
       }
       this.isCreateMode = mode;
	   this.obj = obj;	 	 
	   this.originalSch = sch;	  
	   if (this.editor != null) {
	     this.mySetObj(isFocusGuestTab);
	   }
   },
   
   close: function(ev) {
	   if (this.obj != null) {
       		this.obj["startDT"] = this.saveStartDate;
	   }
	    if (this.handler != null && this.closeDialog) {
			   this.handler.closeDialog(this);
		} else {
			   this.hide();
		}
   },
   
   mySetObj: function(isFocusGuestTab) {
	   // this.titleCursor.focus();
	   this.findSelectedScheduleType();
	   this.setFieldsState();
	   var f = true;
	   var dis = "";
	   if (this.index_S_Sch > -1 || this.index_C_Sch > -1) {
	      this.additionalSchedule.style.display = "none";
	      if (this.index_C_Sch > -1) {
	         f = false;
	         dis = "none";
	      }
	   } else {
	      this.additionalSchedule.style.display = "";
	   }
	   
	   this.drivingTab.style.display = dis;
	   this.guestTab.style.display = dis;
	   this.htmlTab.validityFlags["drivingTab"] = f;
	   this.htmlTab.validityFlags["guestTab"] = f;
	   
       var o;
       o = this.obj["addnlSchedules"];
       this.referenceSchedules = new Array();
       if (o != null) {
          this.addlScheduleList = o.split(",");
          for (var i=0; i<this.addlScheduleList.length; i++) {
             this.addlScheduleList[i] = trim(this.addlScheduleList[i]);
             this.referenceSchedules.push(this.addlScheduleList[i]);
          }
       } else {
          this.addlScheduleList = new Array();	  
       }
       
       var s = trim(this.obj["driver1"]);
       if (s != "") {
         this.referenceSchedules.push(s);
       }
       s = trim(this.obj["driver2"]);
       if (s != "") {
         this.referenceSchedules.push(s);
       }
       
       if (this.obj["repeatUntil"] == null) {
           this.obj["repeatUntil"] = this.obj["endDT"];
       }
       
       this.htmlTab.showTab(0);
       
       // Prep data for display within input boxes
       this.obj["displayName"] = inputDisplay(this.obj["displayName"]);
       this.obj["message1"] = inputDisplay(this.obj["message1"]);
       this.obj["locationName"] = inputDisplay(this.obj["locationName"]);

       if (this.isCreateMode && this.obj["displayName"] == null) {
	      this.timeFlag.setValue(true);
		  this.defaultEventName = "New Event";
		  this.nameComp.setValue("New Event");
		  this.obj["displayName"] = this.nameComp.getValue();
		  this.obj["timeFlag"] = true;
	   } else {
	   }
	   
	   if (this.obj["fromTime"] == null) {
		  this.obj["fromTime"] = "480";
       }
       
       if (this.obj["toTime"] == null) {
          this.obj["toTime"] = "510";
       }
       
       var s = trim(this.obj["message1"]);
       
       if (s != null && s == "") {
          this.obj["message1"] = this.defaultMessage1;
          this.message1.setValue(this.defaultMessage1);
       } else if (s != null) {
          s = inputDisplay(s);
          this.obj["message1"] = s;
          this.message1.setValue(s);
       }
       
       s = trim(this.obj["emails"]);
       
       if (s == "" || s == undefined) {		   
		  this.obj["emails"] = this.defaultEmailMessage;					 		 
          this.emails.value = this.defaultEmailMessage;
       } else {
		 //  this.emails.value = "Enter Email addresses separated by commas";
	   }
       
	   
	   this.fromTime.setValue(this.obj["fromTime"]);
	   this.toTime.setValue(this.obj["toTime"]);
	   
	   if (this.obj["people"] == null) {
	     createOneToManyAssoc(this.obj, "people", "Person");
	   }
	   
	   if (this.obj["group"] == null) {
	     createOneToManyAssoc(this.obj, "group", "Group");
	   }
	   
	  
	   this.setMyListsOptions();
	   
	   this.editor.setValueFromObj(this.obj);
	   
	   
	   if (this.originalSch != null) {
	       this.scheduleSelect.setValue(this.originalSch.UUID);
	   }
	 
	   
	   if ((this.obj["driver1"] == null || this.obj["driver1"] == "") && 
	       (this.obj["driver2"] == null || this.obj["driver2"] == "")) {
	      this.driverAssgined.element.checked = false;
	   } else {
	      this.driverAssgined.element.checked = true;
	   }
	  	 
	   
	   s = "";
      
       var obj = this.getDriverObject(this.obj["driver1"]);
       
       if (obj != null) {
           if (obj.__className == "Person") {
             s = getFullName(obj);
           } else {
             s = obj["name"];
           }
       } else {
          s = this.obj["driver1Name"];
          if (s == null) {
            s = "";
          }
       }
       this.driver1Name.innerHTML = s;
       s = ""; 
	   obj = this.getDriverObject(this.obj["driver2"]);
       if (obj != null) {
           if (obj.__className == "Person") {
             s = getFullName(obj);
           } else {
             s = obj["name"];
           }
       } else {
          s = this.obj["driver2Name"];
          if (s == null) {
            s = "";
          }
       }
       this.driver2Name.innerHTML = s;
       
       this.driverAssginedCheckChanged();

	   this.updatePanelState();
	   
	   this.updateRSVPResult();
	   
	   this.doIncludeAddress();
       this.doReminderFlagChange();
       this.doRepeatFlagChange();
	   
	   this.updateDueToStDt();
	   
	   this.updateRepeatStat();
	   
	   this.updateInviteesList();
	   
	   this.updateAddlScheduleList();
	   
	   if (!this.driverAssgined.element.checked) {
	      var s = this.htmlTab.getSelectedTab();
	      if (s == "drivingTab") {
	         this.htmlTab.showTab(0);
	      }
	   }
	   
	   this.saveCurrentValues();
	   
	   s = "";
	   if (this.driver1Name.innerHTML != "") {
	      s = this.driver1Name.innerHTML;
	   }
	   if (this.driver2Name.innerHTML != s) {
	      if (s == "") {
	         s = "schedule " + this.driver2Name.innerHTML;
	      } else {
	         s = "schedules " + s + " & " + this.driver2Name.innerHTML;
	      }
	   } else {
	      if (s == "") {
	         s = "schedule " + s;
	      }
	   }
	   if (this.scheduleOn != null && s != "") {
	      var s = "There is driving time assigned on \"" +  s + "\" for this event.";
	      showMessageDialog(s, "Driving Calendar!", 300, 100);
	   }
       if ((isFocusGuestTab != null) && (isFocusGuestTab == true))
	        this.htmlTab.showTab(2);
   },
   
   
   
   updateRepeatStat: function() {
      if (this.obj["repeatType"] == null) {
         this.obj["repeatType"] = "ED";
      }
      var ec = new Af.ElementCollection(this.element);

      for (var i=0; i<=6; i++) {
           e = ec.getFirstElementById("subTypeDay"+i);
           e.checked = false;
      }
      var rt = this.obj["repeatType"];
      this.repeatType.value = rt;
      
      if (rt == "MORE") {
         var rst = this.obj["repeatSubtype"];
	     if (rst == null) {
	        rst = "";
	     }
	     var e1 = ec.getFirstElementById("subType1Checked");
         var e2 = ec.getFirstElementById("subType2Checked");
         var e;
         e1.checked = false;
         e2.checked = false;
         e = ec.getFirstElementById("subType2Value");
         e.value = "";
	     if (rst.indexOf("REPEAT") == 0) {
	        e = ec.getFirstElementById("subType2");
            e2.checked = true;
            e.value = rst;
            e = ec.getFirstElementById("subType2Value");
            e.value = this.obj["repeatNumber"];
            for (var i=0; i<=6; i++) {
	           e = ec.getFirstElementById("subTypeDay"+i);
	           e.checked = false;
	        }
	     } else if (rst != "None") {
	        e = ec.getFirstElementById("subType1");
	        e1.checked = true;
	        e.value = rst;
	        var n = this.obj["repeatNumber"];
	        if (n == null) {
	           n = 0;
	        }
	        for (var i=0; i<=6; i++) {
	           e = ec.getFirstElementById("subTypeDay"+i);
	           e.checked = (n & (1<<i))!= 0;
	        }
	     }
      }
      
      this.repeatTypeChanged();
      
   },
   
   retrieveRepeatState: function() {
      var rt;
      if (this.index_S_Sch == -1 && this.index_C_Sch == -1) {
         rt = this.repeatType.value;
      } else {
         return;
      }
      this.obj["repeatType"] = rt;
      this.editor.addNV("repeatType", rt);
      
      if (rt == "MORE") {
         var ec = new Af.ElementCollection(this.element);
	     var e1 = ec.getFirstElementById("subType1Checked");
	     var e;
	     if (e1.checked) {
	        e = ec.getFirstElementById("subType1");
	        this.editor.addNV("repeatSubtype", e.value);
	        this.obj["repeatSubtype"] = e.value;
	        var n = 0;
	        for (var i=6; i>=0; i--) {
	           e = ec.getFirstElementById("subTypeDay"+i);
	           if (e.checked) {
	             n = n | (1 << i);
	           }
	          
	        }
	        this.obj["repeatNumber"] = n;
	        this.editor.addNV("repeatNumber", n);
	     } else {
	        var e2 = ec.getFirstElementById("subType2Checked");
	        e = ec.getFirstElementById("subType2");
	        if (e2.checked) {
	           this.obj["repeatSubtype"] = e.value;
	        } else {
	           this.obj["repeatSubtype"] = "None";
	        }
	        this.editor.addNV("repeatSubtype", this.obj["repeatSubtype"]);
	        e = ec.getFirstElementById("subType2Value");
	        var n = 1;
	        try {
	          n = parseInt(e.value);
	          if (isNaN(n)) {
	             n = 1;
	          }
	        } catch (exc) {
	           n = 1;
	        }
	        
	        this.obj["repeatNumber"] = n;
	        this.editor.addNV("repeatNumber", n);
	     }
      }
   },
  
   doPreview: function() {
      if (this.invitationDialog == null) {
         this.invitationDialog = new HJ.EventInvitation("Invitation to:", this, null);
         //this.invitationDialog.width = "370px";
      }
      this.invitationDialog.showHTMLTemplate(basePageURL + "EventInvitation.htm", "MainArea", "eventInvitation");
      this.invitationDialog.setObj(this.obj);

   },
   
   doSend: function() {
	  if(!this.isValidOperation()) {
		return;
	  }
      var t = (new Date()).getTime();
      var t2;
      if (this.obj["repeatFlag"] + "" == "true" && this.index_S_Sch == -1 && this.index_C_Sch == -1) {
         t2 = parseInt(this.obj["repeatUntil"]);
      } else {
         t2 = parseInt(this.obj["startDT"]);
      }	  
	  if(this.obj["noTimeFlag"] + "" == "true") {			
			t2 = new Date(t2);
			t2.setHours(23);
			t2 = t2.getTime();			
	  }
      if (t2 < t) {
         showMessageDialog("You cannot invite guests to this event, as its date has passed.", "Excuse us!", 300, 100);
		 return;
      }

	  var emailsList = "";
	  this.invalidEmails = "";
	  var emailStr = this.emails.value.split(",");
	  if (emailStr.length == 1) {
		  emailStr = emailStr[0].split(';');
	  }
	  if(this.emails.value != this.defaultEmailMessage) {		
		  for(var i=0; i<emailStr.length; i++) {                    
           var s = trim(emailStr[i]);
		   if(!app.emailValidator.validateEmail(s)){
				if (s != "" ) {
					if(this.invalidEmails == "") {
							this.invalidEmails += s;
					}else {
						if(this.invalidEmails.indexOf(s) == -1) {
							this.invalidEmails += "," + s;
						}
					}
				}
			   continue;
		   }		  
           if (s != "") {
        	 s = app.emailValidator.extractEmailAddress(s);
             if (emailsList == "") {
                emailsList += s;
             } else {
				 if(emailsList.indexOf(s) < 0) {
					emailsList += "," + s;
				 }
             }
           }
        }	        
	  }
	//   this.editor.addNV("emails", emailsList);
	   this.inviteeEmails.setValue(emailsList);

      this.doSave("sendInvitation");
	  this.emails.value = this.defaultEmailMessage;    
	  this.obj["emails"] = this.defaultEmailMessage;					 		 
	  GATrackEvent("sendInvitation");
  },
  
  doSaveStep1: function() {
	 if(this.index == -1) {
		var selctedSchID = this.scheduleSelect.getValue();		
		if(this.originalSch != null && selctedSchID == this.originalSch.UUID) {
			this.isValidOperation();			
			return;
		}
	 }
	 if(this.isPastEvent()) {
		  return;
	 }	 
	 //  Write code to check whether repeat flag is true.  
	 // and open dailog to choose operation   RepeatEventDialog.htm 
	
	 if(this.savedRepeatFlag != null){
		 var rflag = this.savedRepeatFlag.toString();
		
		 if(rflag == "true") {
			 this.editor.addNV("repeatFlag", "true");			
			 if(this.obj["UUID"] != null) {
				this.openRepeatEvtDialog();
			 } else {
				 showMessageDialog("Until Date should be greater than current date.<br/>"+
					 "Please select next comming date.", "Request", 350, 120);
			 }
			return;
		 }
	 }
	 
     if (this.resendRequired()) {
		 if(this.isPastEvent()) {
		  return;
		 }
       // showConfirmDialog("Would you like to notify your guests of changes to this event?", "Notify Guests?", 300, 100, this.doSaveStep2.bind(this), this.doSave.bind(this));
	   this.openConfirmDialog();
     } else {
       this.doSave();
     }
  },
	
  openRepeatEvtDialog: function() {
	   if (this.repeatDialog != null) {
		   delete this.repeatDialog;
	   }
        var handler = {
           templateLoaded: function() {
              this.parent.repeatDialogLoaded();
           },
			parent:this
        };
        if ((this.index_S_Sch > -1 || this.index_C_Sch > -1)&& this.index == -1) {
        	this.repeatDialog = new Af.HtmlDialog("Copy Repeat Event", handler, null);
            this.repeatDialog.showHTMLTemplate(basePageURL + "RepeatEventCopyDialog.htm", "MainArea", "repeatEventContent");     
      	  	this.copyRepeatEventAction = true;
        } else {
        	this.repeatDialog = new Af.HtmlDialog("Modify Repeat Event", handler, null);
        	this.repeatDialog.showHTMLTemplate(basePageURL + "RepeatEventDialog.htm", "MainArea", "repeatEventContent");     
      	  	this.copyRepeatEventAction = false;
        }
        this.repeatDialog.centerDialog(350, 350);
  },
	
  repeatDialogLoaded: function() {
	    this.modifyThisOnly = document.getElementById("modifyThisOnly");
		this.modifyThisAndFuture = document.getElementById("modifyThisAndFuture");
		this.modifyAll = document.getElementById("modifyAll");
		this.cancelModBtn = document.getElementById("cancelModBtn");

		this.modifyThisOnly.onclick = this.doModifyThisOnly.bind(this);
		this.modifyThisAndFuture.onclick = this.doModifyThisAndFuture.bind(this);
		this.modifyAll.onclick = this.doModifyAll.bind(this);
		this.cancelModBtn.onclick = this.doCancelModDialog.bind(this);	
  },
	
  doModifyThisOnly: function() {
	  this.repeatDialog.hide();
	  
	  if (this.actualDate != null) {
	     this.doSave("modifyInstance");
	  }
  },
	
  doModifyThisAndFuture: function() {
	  this.repeatDialog.hide();	  
	  if (this.actualDate != null) {
		  this.doSave("modifyThisAndFuture");
	  }
  },  
	
  doModifyAll: function() {
	  this.repeatDialog.hide();
	  this.doSave("modifyAll");
  },
  
  doCancelModDialog: function() {
      this.repeatDialog.hide();
  },
  
  
  openConfirmDialog: function() {
		if (this.confDialog != null) {
			delete this.confDialog;
		}
        var handler = {
           templateLoaded: function() {
              this.parent.confirmDialogLoaded();
           },
			parent:this
        }
        this.confDialog = new Af.HtmlDialog("Notify Guests?", handler, null);
        //this.confDialog.width = "300px";
         this.confDialog.showHTMLTemplate(basePageURL + "ConfirmDialog.htm", "MainArea", "confirmHTMLDailog");     
		 this.confDialog.centerDialog(350, 350);
	},
	confirmDialogLoaded: function() {
		this.messageText = document.getElementById("messageText");
		this.sendButton = document.getElementById("sendButton");
		this.dontSendButton = document.getElementById("dontSendButton");
		this.sendButton.onclick = this.doSendChangeNotification.bind(this);
		this.dontSendButton.onclick = this.doDontSendChangeNotification.bind(this);
		
		this.messageText.innerHTML = "Would you like to notify your guests of changes to this event?";
	},
	doSendChangeNotification: function() {		
		 this.confDialog.hide();
		 this.doSaveStep2();		
	},
	doDontSendChangeNotification: function() {		
		 this.confDialog.hide();		 
		 this.doSave();
	},

  doSaveStep2: function() {
     this.doSave("resendEmail");
  },
  
  saveCurrentValues: function() {
	  this._startDT = this.obj["startDT"];
	  this._endDT = this.obj["endDT"];
	  this._displayName = this.obj["displayName"];
	  this._locationName = this.obj["locationName"];
	  this._city = this.obj["city"];
	  this._state = this.obj["state"];
	  this._zip = this.obj["zip"];
   },
   
   resendRequired: function() {
      var actualRL = this.obj["rsvp"];
      if (actualRL != null && actualRL.length > 0) {
      
         if (this._startDT != this.obj["startDT"] ||
		  this._endDT != this.obj["endDT"] ||
          this._displayName != this.obj["displayName"] ||
		  this._locationName != this.obj["locationName"] ||
		  this._city != this.obj["city"] ||
		  this._state != this.obj["state"] || 
		  this._zip != this.obj["zip"]) {
			 return true;
		  }
      }
      return false;
   },
  
 
  doSave: function(addlAction) {	  
		
	   if(this.obj["repeatFlag"]+"" == "true" && addlAction != "modifyInstance" ){
		   if(parseInt(this.obj["startDT"]) >= parseInt(this.obj["repeatUntil"])){
			   showMessageDialog("The \"Until\" date should be later than the first date of the repeating event."+
									" <BR/> Please select a different date.", "Invalid date selected", 350, 120);
			   return;
		   }
	   }
	   
	   if (this.obj["repeatFlag"]+"" == "true" && 
			addlAction != "doDelete" &&
			(this.obj["people"].length != 0 || this.obj["group"].length != 0 ||
			 this.obj["rsvp"].length != 0 ||
			 this.emails.value != this.defaultEmailMessage)) {
		   showMessageDialog ("You cannot invite guests for a repeating event." +
				   				"<BR />Please uncheck 'Repeat Event' checkbox in 'Basic' tab " +
				   				"before saving or sending this event",
				   				"Invalid Action", 350, 120);
		   return;
	   }
	  this.addlAction = addlAction;
      this.obj.displayName = this.obj["displayName"];
      var title = xmlEncode(this.obj["displayName"]);
      
      title = trim(title);
      
      if (title == "") {
		showMessageDialog("Please enter a title for this event.", "Request", 300, 100);
		return;
      }
      
   /*   if (this.toTime.parseTime() < 0) {
         return;
      }
      
      if (this.fromTime.parseTime() < 0) {
         return;
      }
      */
	  if(addlAction == "sendInvitation") {
		 this.IsInvitationSent = true;
	  }	else {
		 this.IsInvitationSent = false;
	  }
	  
	  if (this.originalSch != null) {
	     app.deleteEventReferences(this.referenceSchedules, this.originalSch, this.obj);
	  }
	  this.referenceSchedules.length = 0;
	  
	  var s = "";
	  
	  for (var i=0; i<this.addlScheduleList.length; i++) {
	     this.referenceSchedules.push(this.addlScheduleList[i]);
	     if (s == "") {
            s = this.addlScheduleList[i];
         } else {
            s += "," + this.addlScheduleList[i];
         }
      }
            
      this.obj["addnlSchedules"] = s;
       
      this.editor.addNV("addnlSchedules", s);
      
      
      s = trim(this.obj["driver1"]);
      if (s != "") {
         this.referenceSchedules.push(s);
      }
      s = trim(this.obj["driver2"]);
      if (s != "") {
         this.referenceSchedules.push(s);
      }
      
      
      s = this.obj["deletedSeqs"];
	  if (s != null) {
	     
		 this.editor.addNV("deletedSeqs", s);
	  } 
      
     
      var sl = this.workspace["schedule"];
      
      if (sl.length == 0) {
				 showMessageDialog("Please add a Calendar in My Calendars", "Request", 300, 100);
         return;
      }
      var sch;
      
      sch = sl[this.scheduleSelect.element.selectedIndex];
     
      if (sch["event"] == null) {
	     createOneToManyAssoc(sch, "event", "Event");
	  }
	  
      if (this.isCreateMode) {
	     initializeCreatedObject(sch["event"], this.obj);
	     sch["event"].push(this.obj);
      } else {
		 if (this.originalSch != null && sch != this.originalSch) {
		    if (this.index_S_Sch == -1 && this.index_C_Sch == -1 &&
				    this.originalSch["event"] != null ) { // private to private change
		      deleteFromArray(this.originalSch["event"], this.obj);
		    }
		    // changed on 18 Oct 07, it was creating duplicate events when we change Parent Shcedule , 
			// initializeCreatedObject function makes UUID = null, and thats why server created new Event because of UUID is null	
			//initializeCreatedObject(sch["event"], this.obj);
	        sch["event"].push(this.obj);
		 }
	  }
      if (addlAction == "sendInvitation") {
         this.obj["inviteStatus"] = "invited";
         app.invitation.invitationSent(this.obj);
      }
      
      if (this.obj["driver1"] != null) {
        this.editor.addNV("driver1", this.obj["driver1"]);
      }
      
      if (this.obj["driver2"] != null) {
        this.editor.addNV("driver2", this.obj["driver2"]);
      }
      
      var t = this.repeatUntil.getValue();
      var dt = new Date(t);
      dt.setHours(23,59,59);
      t = dt.getTime();
      this.editor.addNV("repeatUntil",  "" + t);
      
      this.editor.addNV("timeFlag", this.timeFlag.element.checked);
      this.editor.addNV("noTimeFlag", this.noTimeFlag.element.checked);
	  this.editor.addNV("displayName", this.obj.displayName);     
      this.retrieveRepeatState();
      s = this.obj["minuteBefore1"];
      try {
        var d = parseInt(s);
        if (isNaN(d)) {
          s = "0";
        }
      } catch(e) {
         s = "0";
      }
      this.minuteBefore1.setValue(s);
      
      s = this.obj["minuteBefore2"];
      try {
        var d = parseInt(s);
        if (isNaN(d)) {
          s = "0";
        }
      } catch(e) {
         s = "0";
      }
      this.minuteBefore2.setValue(s);
		
      var assocsXml = this.editor.getChangeXmlForObjList(this.obj["people"], ["name"], "people");
     
      assocsXml += this.editor.getChangeXmlForObjList(this.obj["group"], ["name"], "group");
      
     
      var xmlString = this.editor.getChangeXml(this.isCreateMode, assocsXml);
	 
    
      
      if (xmlString == null) {
         showMessageDialog("Any changes you have made will be saved.", "Informing You", 300, 100);
         return;
      }
      if(this.addlAction != "doDelete") {
		showMessageDialog("Saving ... please wait ...", "Saving", 300, 120);
	  }
      
      //debugA(xmlString);	
      this.hide();	
	  var req = new Af.DataRequest(svcURL, this.saveSuccessful.bind(this), this.saveFailed.bind(this), null, 
				this.saveTimedOut.bind(this));
      req.addService("WorkspaceService", "saveEventDetails"); 
      req.addParameter("parentId", sch.UUID);  
      this.obj["scheduleId"] = sch.UUID;
      if (this.originalSch != null && sch != this.originalSch) { // schedule change, private to private v/s shared/community to private will be handled by the server
    	  req.addParameter("oldParent", this.originalSch.UUID); 
      }
      if (this.obj.UUID != null) {
         req.addParameter("UUID", this.obj.UUID);
      } 
      if (addlAction != null) {
         req.addParameter("addlAction", addlAction);
      }    
      
      if (this.actualDate != null) {
         req.addParameter("actualDate", this.actualDate); 
      } 

	  req.xmlDoc = xmlString;
	  
	  this.prevOriginalSch = this.originalSch;
	  this.originalSch = sch; // change original schedule to new schedule; 

      ajaxEngine.processRequest(req);
   },
   
   doDontSave: function() {
      this.editor.clearChanges();
   },
  
   saveSuccessful: function(response) {
   
      //debugA(response.responseText);      
      var xds = new Af.XMLToDataSet(response.responseXML);
	  var e = xds.data;
	  
	  var sch = this.originalSch;
	  if (this.originalSch.selected) {
		  app.schedule.selectScheduleAndRefresh(this.originalSch);
	  }
	  if (this.prevOriginalSch != null && this.prevOriginalSch.selected) {
		  app.schedule.selectScheduleAndRefresh(this.prevOriginalSch);
	  }
	  
	  if (this.obj.UUID == null && e != null && e != undefined) {
         this.obj.UUID = e.UUID;
      }
      var pl = e["people"];
	  if (pl != null) {
	     var actualPL = this.workspace["myPeople"];
	     for (var i=0; i<pl.length; i++) {
	        var o = pl[i];
	        o.__parent = actualPL.__parent;
	        actualPL.push(o);
	     }
	  }
	  app.updateEventReferences(this.originalSch, this.obj);
	  app.schedule.miniCalendar.updateMiniCalendar(this.obj);
	  if(this.IsInvitationSent && this.addlAction != "doDelete") {
		if(this.invalidEmails!=""){
			showMessageDialog("The event details have been saved and invitations to your guests have been sent and these are the emails to whom emails cannot be sent:<BR/>"+this.invalidEmails, "Success !", 450, 120);
		}else{
			showMessageDialog("The event details have been saved and invitations to your guests have been sent.", "Success !", 300, 120);		
		}	
		
		 this.indvslSelectionList.innerHTML = "";
		 this.groupSelectionList.innerHTML = "";
		 this.emails.value = this.defaultEmailMessage;
		 this.obj["people"].length = 0;
		 this.obj["group"].length = 0;

		 var rl = e["rsvp"];
	  
		 if (rl != null) {
			 if (this.obj["rsvp"] == null) {
				 createOneToManyAssoc(this.obj, "rsvp", "RSVP");
			 }
			 var actualRL = this.obj["rsvp"];
			 for (var i=0; i<rl.length; i++) {
		        
				var r = rl[i];
				r.__parent = actualRL.__parent;
				actualRL.push(r);
			 }
			 this.updateRSVPResult();
		 }
	  } else if(this.addlAction != "doDelete"){
	     if (this.obj["people"].length != 0 || this.obj["group"].length != 0 || this.emails.value != this.defaultEmailMessage) {
			showMessageDialog("Your event details have been saved.<br/>"+
				" However, no invitation has been sent to your newly invited guests.<br/>"+
				"Please click SEND at the bottom of the Guest tab when you would like the invitation sent. ", "Request", 330, 130);
	     } else {
	       if (this.addlAction == "resendEmail") {
	          showMessageDialog("Your event details have been saved.  A notification of the event changes has been sent to your guests.", "Success", 300, 120);
	       } else {
	          showMessageDialog("Your event details have been saved.", "Success", 300, 120);
	       }
	     }
	  }
	  if(this.addlAction == "doDelete") {
		  showMessageDialog("Event deleted successfully.", "Success", 300, 120);
	  }
	  this.IsInvitationSent = false;
      this.editor.clearChanges();
      app.schedule.selectScheduleAndRefresh(this.originalSch);
      this.saveCurrentValues();
      app.schedule.eventChanged(this.obj, false);
      this.obj = null;
   },   
   
   saveFailed: function(dataRequest, msg) {
      showMessageDialog("We are currently unable to save these event details.  Please try again.", "Excuse us!", 400, 130);
   },
   
  saveTimedOut: function(dataRequest) {
      showMessageDialog("A bit of network congestion has caused a delay.  Nonetheless, be assured that"+
						" your notification has been sent.", "Excuse us!", 400, 150);
  },
  
  selectPeople: function() {
		if(!this.isValidOperation()) {
			return false;
		}
		this.pgSelector = getPoepleGroupSelector(this);
		this.pgSelector.element.style.zIndex = "500001";
		this.pgSelector.setDataList(app.workspace["myGroup"], 
		app.workspace["myPeople"], 
		this.obj["group"], 
		this.obj["people"]);
		return false;
  },
  
  setMyListsOptions: function() {
      // make copy of the original array and
	   // add objects that correspond to extra options
	   var l = this.workspace["myList"];
	   l = l.slice(0, l.length);
	   var o = new Object();
	   o["name"] = "------";
	   o["UUID"] = "_separator1";
	   l.unshift(o);
	   o = new Object();
	   o["name"] = "Choose from My Lists";
	   o["UUID"] = "_choose_from_my_lists";
	   l.unshift(o);
	   this.taskList.setData(l);
  },
  
  setDriverOptions: function(driver) {
      // make copy of the original array and
	   // add objects that correspond to extra options
	   var l = this.workspace["schedule"];
	   l = l.slice(0, l.length);
	   var o = new Object();
	   o["name"] = "------";
	   o["__fullId"] = "_separator1";
	   l.unshift(o);
	   o = new Object();
	   o["name"] = "My Schedule";
	   o["__fullId"] = "_choose_from_my_schedule_2";
	   l.unshift(o);
	   o = new Object();
	   o["name"] = "Choose";
	   o["__fullId"] = "_choose_from_my_schedule_1";
	   l.unshift(o);
	   o = new Object();	  
	   o["name"] = "-------------";
	   o["__fullId"] = "_separator2";
	   l.push(o);
	   o = new Object();
	   o["name"] = "Choose from My People";
	   o["__fullId"] = "_choose_from_my_people";
	   l.push(o);
	   o = new Object();	  
	   o["name"] = "------";
	   o["__fullId"] = "_separator3";
	   l.push(o);
	   
	   var l2 = this.workspace["myPeople"];
	   
	   for (var i=0; i<l2.length; i++) {
	      l.push(l2[i]);
	   }
	   
	   driver.setData(l);
  },
  
  setStartEnd: function() {
	 var t =  this.date.getValue();
	 var dt = new Date(t); 
	 dt = this.setTxtBoxEntryDate(dt);

     if (this.timeFlag.getValue() == "false") {        
		dt.setHours(0, 0, 0, 0);
		t = dt.getTime();
		this.obj["startDT"] = t;
		this.editor.addNV("startDT", t);
		dt.setHours(24, 0, 0, 0);
		t = dt.getTime();
        this.obj["endDT"] = t;
        if (this.repeatUntil.getValue() < t) {
			//this.repeatUntil.setValue(t);  // Set repeatUntil date by default to next day 
		}
        this.editor.addNV("endDT", t);
        this.updateAllDateTimes();
        return true;
     }
     
     this.obj["fromTime"] = this.fromTime.getValue();
     this.obj["toTime"] = this.toTime.getValue();
     
     this.editor.addNV("fromTime", this.obj["fromTime"]);
     this.editor.addNV("toTime", this.obj["toTime"]);
          
     var m1 = parseInt(this.fromTime.getValue());
    
     var m2 = parseInt(this.toTime.getValue());
    
    
   /*  
     var t =  this.date.getValue();
     var dt = new Date(t);	  */
     var h = Math.floor(m1/60);
     var m = Math.floor(m1 % 60);
     dt.setHours(h, m, 0, 0);
     var t1 = dt.getTime();
     
     dt = new Date(t);
     h = Math.floor(m2/60);
     m = Math.floor(m2 % 60);
     dt.setHours(h, m, 0, 0);
     var t2 = dt.getTime();
     
     
     if (t2 < t1) {
         t2 = new Date(t2);
         t2.setDate(t2.getDate() + 1);
         t2 = t2.getTime();
     }
     this.obj["startDT"] = t1;
     this.obj["endDT"] = t2;
   
     this.editor.addNV("startDT", t1);
     
     this.editor.addNV("endDT", t2);
     
     if (this.repeatUntil.getValue() < t2) {
        this.repeatUntil.setValue(t2);
     }
     
	  this.updateAllDateTimes();
		 
     
     return true;
  },

  setTxtBoxEntryDate: function(dt) {
		var dtStr = this.startDTBox.value; 
		if(dtStr == null) {
			dtStr = "";
		}
		var dateParts = dtStr.split(" ");
		var year = (new Date()).getYear();
		if(dateParts != null && dateParts.length > 3) {
			year = dateParts[(dateParts.length) - 1];
			dt.setYear(year);
		}
		for(i = 0; i < months.length; i++) {
			if(dtStr.match(months[i]) || dtStr.match(monthsShort[i])) {				
				dt.setMonth(i);
				return dt;
			}
		}
		return dt;
	},
  
  updateAllDateTimes: function() {
      var dt = new Date(this.obj["startDT"]);
	  var s = months[dt.getMonth()] + " " + dt.getDate() + " - ";
	  s += getDisplayTimeFromMins(this.obj["fromTime"]) + " to " + getDisplayTimeFromMins(this.obj["toTime"]);
	  this.drivingTabEventDtTime.innerHTML = s;
	  
	  s = "<strong>" + this.obj["displayName"] + "</strong><br/>";
	  s += "Date: " + months[dt.getMonth()] + " " + dt.getDate() + "<br/>";
	  s += "Time: " + getDisplayTimeFromMins(this.obj["fromTime"]) + " to " + getDisplayTimeFromMins(this.obj["toTime"]) + "<br/>";
	  this.listTabEventDetail.innerHTML = s;
  },
  
  deleteEventConfirm: function() {
    if (this.originalSch == null) {
       this.editor.clearChanges();
       this.hide();
       return;
    }
	if(!this.isValidOperation()) {
		return false;
	}
	
    //showConfirmDialog("Are you sure you want to delete this event?", "Are You Sure?", 300, 100, this.doDeleteEvent.bind(this));

	var t1 = (new Date()).getTime();
	var t2 = parseInt(this.obj["endDT"]);

	if((this.obj["rsvp"] == null || this.obj["rsvp"] == ""))  {
	    var rflag = this.savedRepeatFlag;
	    
	    if (rflag != null) {
	       rflag = rflag.toString();
	    }
		
		if(rflag == "true") {	
			 this.openDelRepeatEvtDialog();
		} else {
			showConfirmDialog("Are you sure you want to delete this event?", "Are You Sure?", 300, 100, this.doDeleteEvent.bind(this));
		}
	}else {
		if (this.deleteCnfrmDialog != null) {
			delete this.deleteCnfrmDialog;
		}
		var handler = {
		   templateLoaded: function() {
			  this.parent.deleteCnfrmDialogLoaded();
		   },
			parent:this
		};
		this.deleteCnfrmDialog = new Af.HtmlDialog("Notify Guests?", handler, null);
		//this.deleteCnfrmDialog.width = "520px";
		 this.deleteCnfrmDialog.showHTMLTemplate(basePageURL + "DeleteEventCnfrmDialog.htm", "MainArea", "DeleteEventCnfrmContent");     	
		 this.deleteCnfrmDialog.centerDialog(100, 100);
		}
	return false;
  },
  
  
  openDelRepeatEvtDialog: function() {
	   if (this.delRepeatDialog != null) {
		   delete this.delRepeatDialog;
	   }
        var handler = {
           templateLoaded: function() {
              this.parent.delRepeatDialogLoaded();
           },
			parent:this
        };
        this.delRepeatDialog = new Af.HtmlDialog("Delete Repeat Event", handler, null);
        //this.delRepeatDialog.width = "400px";
         this.delRepeatDialog.showHTMLTemplate(basePageURL + "DelRepeatEventDialog.htm", "MainArea", "delRepeatEventContent");     
		 this.delRepeatDialog.centerDialog(350, 350);
  },
	
  delRepeatDialogLoaded: function() {
	    this.deleteThisOnly = document.getElementById("deleteThisOnly");
		this.deleteThisAndFuture = document.getElementById("deleteThisAndFuture");
		this.deleteAll = document.getElementById("deleteAll");
		this.cancelDelBtn = document.getElementById("cancelDelBtn");
		

		this.deleteThisOnly.onclick = this.doDeleteThisOnly.bind(this);
		this.deleteThisAndFuture.onclick = this.doDeleteThisAndFuture.bind(this);
		this.deleteAll.onclick = this.doDeleteAll.bind(this);
		this.cancelDelBtn.onclick = this.doCancelDelDialog.bind(this);		
  },
	
  doDeleteThisOnly: function() {
	  this.delRepeatDialog.hide();
	  if (this.actualDate != null) {
	     appendDeleteSeq(this.obj, this.actualDate);
	     this.date.setValue(parseInt(this.saveStartDate));
	     this.obj["startDT"] = this.saveStartDate;
	     this.doSave("doDelete");
	  }
	  
  },
	
  doDeleteThisAndFuture: function() {
	  this.delRepeatDialog.hide();
	  if (this.actualDate != null) {
	     var d = new Date(this.actualDate);
	     d.setDate(d.getDate() - 1);
	     this.obj["repeatUntil"] = d.getTime();
	     this.repeatUntil.setValue(d.getTime());
	     this.date.setValue(parseInt(this.saveStartDate));
	     this.obj["startDT"] = this.saveStartDate;
	     this.doSave("doDelete");
	  }
  },  
	
  doDeleteAll: function() {
      this.delRepeatDialog.hide();
	  deleteFromArray(this.originalSch["event"], this.obj);
	  this.deleteEvent();
  },

  doCancelDelDialog: function() {
	  this.delRepeatDialog.hide();
  },

  deleteCnfrmDialogLoaded : function() {
	  this.dontDeleteBtn = document.getElementById("dontDelete");
	  this.deleteNoNoticeBtn = document.getElementById("deleteNoNotice");
	  this.deleteSendNoticeBtn = document.getElementById("deleteSendNotice");

	  this.dontDeleteBtn.onclick = this.dontDeleteEvent.bind(this);
	  this.deleteNoNoticeBtn.onclick = this.doDelEventNoNotice.bind(this)
	  this.deleteSendNoticeBtn.onclick = this.doDelEventSendNotice.bind(this)
  },
  
  dontDeleteEvent: function() {
	  this.deleteCnfrmDialog.hide();
  },
	
  doDelEventNoNotice: function() {	  
	  this.deleteCnfrmDialog.hide();	  
	  deleteFromArray(this.originalSch["event"], this.obj);
	  this.deleteEvent();
  }, 
   
  doDelEventSendNotice: function() {	  
	  this.deleteCnfrmDialog.hide();	  
	  deleteFromArray(this.originalSch["event"], this.obj);
	  this.deleteEvent("sendNotify");
   },

   doDeleteEvent: function() {	 
	   hideDialogWin();
	   deleteFromArray(this.originalSch["event"], this.obj);
	   this.deleteEvent();
   },

   deleteEvent: function(action) {	   
	   this.hide();
	   if(this.obj.UUID == null || this.originalSch.UUID == null) {
		   return;
	   }
	   var req = new Af.DataRequest(svcURL,
			this.requestDeleteEventCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
	   req.addService("WorkspaceService", "deleteEvent");
	   req.addParameter("parentId", this.originalSch.UUID);
	   req.addParameter("UUID", this.obj.UUID);
	   if(action != null) {
		   req.addParameter("action", action);
	   }
	   ajaxEngine.processRequest(req);
   },

   requestDeleteEventCompleted: function(response) {
	   
	   // Delete event from Invitation List
	    if (this.obj["inviteStatus"] == "invited") {
		  var index = findObjIndex(this.workspace["invitation"], this.obj);
		  if(index > -1) {
			deleteFromArray(this.workspace["invitation"], this.obj);		  
			app.invitation.setDataList(this.workspace["invitation"]);		 
		  }
	  }
	   this.editor.clearChanges();       
       app.schedule.shownScheduleListChanged();
        app.schedule.eventChanged(this.obj, true);
   },
  
   requestFailedCommon: function(dataRequest, msg) {
      showMessageDialog("We are currently unable to delete this event.  Please try again.", "Excuse us!", 350, 100);
   },

   requestTimedoutCommon: function(dataRequest) {
     showMessageDialog("We are currently unable to delete this event.  Please try again.", "Excuse us!", 350, 100);
   },
   
   valueChanged: function(comp, parent, name, val) {
     if (this.taskList == comp) {
	    this.updatePanelState();
	 } else if (this.date == comp) {
	    this.updateDueToStDt();
	 }
   },
   
   driverAssginedCheckChanged: function() {
        if (this.index_C_Sch > -1) {
           return; // for a community calendar don't so anything.
        }
	    if (this.driverAssgined.element.checked) {
	       this.drivingTab.style.display = "";
	       this.htmlTab.validityFlags["drivingTabContent"] = true;
	    } else {
	       this.drivingTab.style.display = "none";
	       this.htmlTab.validityFlags["drivingTabContent"] = false;
	       this.obj["driver1"] = "";
	       this.obj["driver2"] = "";
	    }
   },
   
   updatePanelState: function() {
     var lists = this.workspace["myList"];
     var oneTaskList = findObjById(lists, this.obj["taskList"]);
     if (oneTaskList == null) {
        this.eventTaskListContainer.style.display = "none";
     } else {
        this.eventTaskListContainer.style.display = "";
        this.myOneList.setMyOneList(oneTaskList);
     }
   },
   
   updateDueToStDt: function() {
     var temp = this.repeatType.value;
     removeAll(this.repeatType);
     var dt = this.date.getValue();
     dt = new Date(dt);
     
     var l = this.dateUtil.getRepeatList(dt);
     
     for (var i=0; i<l.length; i++) {
        var option = l[i];
        var oe = document.createElement("option");
		oe.value=option.value;
		oe.label = option.label;
		oe.appendChild(document.createTextNode(option.label));
        this.repeatType.appendChild(oe);
     }
     this.repeatType.value = temp;
     this.setStartEnd();
   },
   
   repeatTypeChanged: function() {
      if (this.repeatType.value == "MORE") {
         this.subTypeTable.style.display = "";
      } else {
         this.subTypeTable.style.display = "none";
      }
   },
   
   doAddNewMyList: function(ev) {
		if(this.dialog == null) {  
			this.dialog = new HJ.AddMyListDialog("New MyList", this, null, "500001");
		}
		this.dialog.showHTMLTemplate(basePageURL + "AddMyList.html", "content", "newMyList");
		this.dialog.centerDialog(400, 280);
		return false;				
   },
   
   myListCreated: function(uuid) {
      this.setMyListsOptions();
      this.taskList.setValue(uuid);
      this.obj["taskList"] = uuid;
      this.updatePanelState();
   },
   
   doSelectDriver1: function() {
      this.selectInfo = 1;
	  this.pSelector = getPoepleScheduleSelector(this);
      this.pSelector.setDataList(app.workspace["schedule"], app.workspace["myPeople"], this.obj["driver1"]);
      return false;
   },
   
   doSelectDriver2: function() {
	  this.selectInfo = 2;
	  this.pSelector = getPoepleScheduleSelector(this);
      this.pSelector.setDataList(app.workspace["schedule"], app.workspace["myPeople"], this.obj["driver2"]);
      return false;
   },

	 doDeleteDriver1:function(){
			 if(this.obj.UUID==null){
				 return;
			 }
			 if(this.obj["driver1"]!= null && this.obj["driver1"]!=""){
				var req = new Af.DataRequest(svcURL, this.deleteDriver1Successful.bind(this), this.deleteDriverFailed.bind(this), null, this.deleteDriverTimedOut.bind(this));
				req.addService("WorkspaceService", "deleteDriver"); 
				if (this.obj.UUID != null) {
					req.addParameter("eventId", this.obj.UUID);
				}
				req.addParameter("driverType","driver1");
				ajaxEngine.processRequest(req);
			}
		},

		setCheckedUncheked:function(){
			if ((this.obj["driver1"] == null || this.obj["driver1"] == "") && 
	       (this.obj["driver2"] == null || this.obj["driver2"] == "")) {
	      this.driverAssgined.element.checked = false;
	   } else {
	      this.driverAssgined.element.checked = true;
	   }
		},


	 deleteDriver1Successful:function(){
		 this.minuteBefore1.setValue("0");
		 this.obj["minuteBefore1"] = "0";
		 this.obj["driver1"] = null;
		 this.driver1Name.innerHTML = "";
		 this.setCheckedUncheked();
		 
		 showMessageDialog("The assigned driver has been successfully deleted.", "Deletion Successful!", 350, 100);
	 },

	 deleteDriverFailed:function(){
		 showMessageDialog("We are currently unable to delete this driver.  Please try again.", "Excuse us!", 350, 100);
	 },

	 deleteDriverTimedOut:function(){
		 showMessageDialog("We are currently unable to delete this driver.  Please try again.", "Excuse us!", 350, 100);
	 },
	 
	 deleteDriver2Successful:function(){
		 this.obj["driver2"] = null;
		 this.minuteBefore2.setValue("0");
		 this.obj["minuteBefore2"] = "0";
		 this.driver2Name.innerHTML = "";
		 this.setCheckedUncheked();
		 showMessageDialog("The assigned driver has been successfully deleted.", "Deletion Successful!", 350, 100);
	 },

	 doDeleteDriver2:function(){
			 if(this.obj.UUID==null){
					 return;
			 }
			 if(this.obj["driver2"]!= null && this.obj["driver2"]!=""){
				var req = new Af.DataRequest(svcURL, this.deleteDriver2Successful.bind(this), this.deleteDriverFailed.bind(this), null, this.deleteDriverTimedOut.bind(this));
				req.addService("WorkspaceService", "deleteDriver"); 
				if (this.obj.UUID != null) {
					req.addParameter("eventId", this.obj.UUID);
				}
				req.addParameter("driverType","driver2");
				ajaxEngine.processRequest(req);
			}

	 },
   
   doSelectAddlSchedules: function() {
	  this.selectInfo = 2;
	  this.scheduleSelector = getScheduleSelector(this);
      this.scheduleSelector.setDataList(app.workspace["schedule"], this.addlScheduleList);
      return false;
   },
   
   getDriverObject: function(d) {
      if (d == null) {
         return null;
      }
      var o = findObjById(app.workspace["schedule"], d);
      if (o == null) {
         o = findObjById(app.workspace["myPeople"], d);
      }
      return o;
   },
   
   selectionDone: function (dialog, obj) {
        if (this.pgSelector == dialog) {
           this.updateInviteesList();
        } else if (this.pSelector == dialog) {
			var s = "";
			var uuid = "";
			if (obj != null) {
			   if (obj.__className == "Person") {
				 s = getFullName(obj);
			   } else {
				 s = obj["name"];
			   }
			   uuid = obj["UUID"];
			}
			if (this.selectInfo == 1) {
			   this.obj["driver1"] = uuid;
			   this.driver1Name.innerHTML = s;
			} else if (this.selectInfo == 2) {
			   this.obj["driver2"] = uuid;
			   this.driver2Name.innerHTML = s;
			}
        } else if (this.scheduleSelector == dialog) {
           this.updateAddlScheduleList();
        }
    },
    
    updateInviteesList: function() {	 
		this.indvslSelectionList.innerHTML = getPeopleNames(this.obj["people"]);
		this.groupSelectionList.innerHTML = getGroupsPeople(this.obj["group"]);		
    },
    
    updateAddlScheduleList: function() {
      s = "";
      var l = app.workspace["schedule"];
      for (var i=0; i<this.addlScheduleList.length; i++) {
        var sch = findObjById(l, this.addlScheduleList[i]);
        if (sch != null) {
          if (s == "") {
            s = sch.name;
          } else {
            s += "<br/>" + sch.name;
          }
        }
      }
      this.additionalScheduleList.innerHTML = s;
    },
    
   rsvpTabSelected: function(p) {
      this.rsvpTabs[this.rsvpIndex].style.backgroundColor = this.rsvpTab1BC;
      this.rsvpIndex = p;
      this.rsvpTabs[this.rsvpIndex].style.backgroundColor = this.rsvpTab0BC;
      this.showRSVPResult();
   },
   
    
    updateRSVPResult: function() {
       if (this.obj["rsvp"] == null) {
	     createOneToManyAssoc(this.obj, "rsvp", "RSVP");
	   }
	   var l = this.obj["rsvp"];
	   
	   var l2 = new Array();
	   
	   var t = 0;
	   var y = 0;
	   var n = 0;
	   var u = 0;
	   if(this.index > -1){
			 for (var i=0; i<l.length; i++) {
					var r = l[i];
					p = findObjById(app.workspace["myPeople"], r["inviteeId"]);
					if (p == null) {
						 continue;
					}
					r["fullName"] = (""==trim(getFullName(p)) ? p["email"] : getFullName(p));
					var res;
					if (r.type == "yes") {
						 res = "(" + r["num"] + ")";
						 y += parseInt(r["num"]);
					} else if (r.type == "no") {
						 res = "(No)";
						 n++;
					} else {
						 res = "(?)";
						 u++;
					}
					r["result"] = res;
					l2.push(r);
					t++;
			 }
		}else {
			 for (var i=0; i<l.length; i++) {
					var r = l[i];
					r["fullName"] = r["PersonName"];
					var res;
					if (r.type == "yes") {
						 res = "(" + r["num"] + ")";
						 y += parseInt(r["num"]);
					} else if (r.type == "no") {
						 res = "(No)";
						 n++;
					} else {
						 res = "(?)";
						 u++;
					}
					r["result"] = res;
					l2.push(r);
					t++;
			 }
		}
	  
	   this.totalId.innerHTML = "" + t;
	   this.noResponseId.innerHTML = "" + u;
	   this.yesId.innerHTML = "" + y;
	   this.noId.innerHTML = "" + n;
	   
	   this["__rsvp"] = l2;
	   this.showRSVPResult();
	   
    },
    
    showRSVPResult: function() {
       var l1 = this["__rsvp"];
       var l2;
       if (this.rsvpIndex == 0) {
          l2 = l1;
       } else {
          l2 = new Array();
          var t = null;
          if (this.rsvpIndex == 1) {
             t = "yes";
          } else if (this.rsvpIndex == 2) {
             t = "no";
          }
          
          for (var i=0; i<l1.length; i++) {
             if (l1[i].type == t) {
                l2.push(l1[i]);
             }
          }
       }
       this.inviteesTable.setDataList(l2);
    },
    
    tabSelected: function(idx, tabName) {	
	  if (idx == 0) {
	     this.previous.style.display = "none";
	  } else {
	     this.previous.style.display = "";
	  }
	  
	
	  if (tabName == "guestTab") {
	     this.send.style.display = "";
	     this.updateRSVPResult();
	     GATrackEvent("selectInviteGuestsTab");
	  } else {
	     this.send.style.display = "none";
	  }
	  if(tabName == "basicTab" && !this.titleCursor.disabled) {
		//this.titleCursor.focus();
		if(this.titleCursor!=null && this.isCreateMode){
			this.titleCursor.onfocus = this.focusOnNameTextBox.bindAsEventListener(this);
			this.titleCursor.onblur = this.focusLostNameTextBox.bindAsEventListener(this);		
			this.defaultEventName = this.titleCursor.value;
		}
	  } else if(tabName == "guestTab") {
		  //this.emails.focus();
	  } 
      
    },
	
	findSelectedScheduleType: function() {		
		/* function to check whether selected schedule is community schedule . 
			 if yes then show my schedule and selectd schedule in drop down list			 
		*/
		if(this.originalSch == null) {
		    this.index_S_Sch = -1;
			this.index_C_Sch = -1;
			this.index = -1;
		} else {
			this.index_S_Sch = findObjIndex(this.workspace["sharedSchedule"], this.originalSch);
			this.index_C_Sch = findObjIndex(this.workspace["communitySchedule"], this.originalSch);
			this.index = findObjIndex(this.workspace["schedule"], this.originalSch);
		}
		
		if(this.scheduleSelect == null) {
			return;
		}
	   
		if(this.index == -1)  {
			var t = new Array();
			var array = this.workspace["schedule"];
			for(var i = 0; i < array.length;i++) {
				t.push(array[i])
			}
			if(this.originalSch != null && findObjIndex(t,this.originalSch) == -1) {
				var s = t.push(this.originalSch);
			}				
			this.scheduleSelect.setData(t);
		} else {
		    this.scheduleSelect.setData(this.workspace["schedule"]);
		}
		if(this.originalSch != null) {
		   this.scheduleSelect.setValue(this.originalSch.UUID);
		}		
	},

	isValidOperation: function() {
		// showMessageDialog("This is community calendar.<br/> Please select schedule to make it private event.","Request", 320, 120);

		if(this.index_S_Sch > -1 && this.index == -1) {
			showMessageDialog("This is an event in a shared calendar. You can't modify it.","Excuse us!", 350, 120);
			return false;
		}
		else if(this.index_C_Sch > -1 && this.index == -1) {
			showMessageDialog("This is an event in a community calendar. You can't modify it.","Excuse us!", 350, 120);
			return false;
		}
		return true;
	},

	isPastEvent: function() {
		if(this.obj == null) {
			return false;
		}	
		var t1 = (new Date()).getTime();
		var t2 = parseInt(this.obj["startDT"]);
		if(this.obj["noTimeFlag"] + "" == "true") {
			t2 = new Date(t2);
			t2.setHours(23);
			t2 = t2.getTime();
	    }
		if(t2 < t1) {
		   if (this.obj["rsvp"] != null && this.obj["rsvp"] != "") {
			   showMessageDialog("You are not allowed to move this event to a past date because you have already invited guests to this event.","Excuse us!", 350, 120);
			   return true;
			} else if (this.obj["people"].length != 0 || this.obj["group"].length != 0 || this.emails.value != this.defaultEmailMessage) {
			   showMessageDialog("You cannot invite guests to this event, as its date has passed.", "Excuse us!", 300, 100); 
			   return true;
			}
		}
		
		return false;
	},

	focusOnTextBox: function(evt) {
		  var s = this.emails.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }		
		  if (s == trim(this.defaultEmailMessage) || s == "") {
			 this.emails.value = "";
			 consumeEvent(evt);
		  }

		  this.emails.focus();
	   },
   
	focusLostTextBox: function(evt) {
		  var s = this.emails.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }
		  if (s == trim(this.defaultEmailMessage) || s == "") {
			 this.emails.value = this.defaultEmailMessage;
			 consumeEvent(evt);
		  }	         
	 },
	 focusOnNameTextBox:function(evt){
		var s = this.titleCursor.value;
		if (s == null) {
			s = "";
		} else {
			s = trim(s);
		}		
		if (s == trim(this.defaultEventName) || s == "") {
			this.titleCursor.value = "";
			consumeEvent(evt);
		}
		this.titleCursor.focus();
	 },
	 
	 focusLostNameTextBox:function(evt){
		var s = this.titleCursor.value;
		if (s == null) {
			s = "";
		} else {
			s = trim(s);
		}
		if (s == trim(this.defaultEventName) || s == "") {
			this.titleCursor.value = this.defaultEventName;
			consumeEvent(evt);
		}	         		
	 }
	
});

