HJ.ScheduleDetail = Class.create();
HJ.ScheduleDetail.prototype = {
   
   initialize: function() {
      this.table = document.getElementById("myScheduleListTable");
      this.tableContainer = document.getElementById("myScheduleListContainer");
      this.emails = "";
      this.schDetail = null;
   },
   
   setSchedules: function(dlist, sch) {
      this.schedules = dlist;
      
      if (this.schDetail == null) {
         this.schDetail = new HJ.OneScheduleDetail(this, this.tableContainer, this.table);
      } 
      
      if (sch == null) {
         var sch = new Object();
         initializeCreatedObject(this.schedules, sch);
         this.sch = sch;
         this.sch["name"] = "New Calendar";
         this.schDetail.setSchedule(this.sch);
         this.schDetail.doSave();
      } else {
         this.sch = sch;
         this.schDetail.setSchedule(this.sch);
      }
   },
   
  
   doDeleteSchedule: function(sch, osd) {
      deleteFromArray(this.schedules, sch);
      app.schedule.selectedScheduleDeleted();
      app.schedule.removeFromShownList(sch);
      app.schedule.myScheduleListChanged(true);
      this.deleteSchedule(sch);
   },
   
   deleteSchedule: function(obj) {
      var req = new Af.DataRequest(svcURL,
      this.requestDeleteScheduleCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
      req.addService("WorkspaceService", "deleteSchedule");
      req.addParameter("UUID", obj.UUID);
      ajaxEngine.processRequest(req);
   },
   
   requestDeleteScheduleCompleted: function(response) {
      this.table.style.display = "none";
   },
   
   requestFailedCommon: function(dataRequest, msg) {
      showMessageDialog("We are currently unable to delete this Calendar. Please try again.", "Excuse us!", 350, 100);
   },
   
   requestTimedoutCommon: function(dataRequest) {
      showMessageDialog("We are currently unable to delete this Calendar. Please try again.", "Excuse us!", 350, 100);
   }
   
}

HJ.OneScheduleDetail = Class.create();
HJ.OneScheduleDetail.prototype = {
   
   initialize: function(parent, tableContainer, table, sch) {
      this.parent = parent;
      this.table = table;
      this.tableContainer = tableContainer;
     
      this.table.style.display = "";
      
      var ec = new Af.ElementCollection(this.table);
      this.showFreeTimeTrigger = ec.getFirstElementById("showFreeTimeTrigger");
      this.showAllTrigger =  ec.getFirstElementById("showAllTrigger");
      this.showFreeTimeTrigger.onclick = this.doShowFree.bind(this);
      this.showAllTrigger.onclick = this.doShowAll.bind(this);
      this.deleteButton = ec.getFirstElementById("deleteButton");
      this.deleteButton.onclick = this.deleteScheduleConfirm.bind(this);
			this.stopAllTrigger = ec.getFirstElementById("stopAllTrigger");
			this.stopAllTrigger.onclick = this.doShowUnSelectedAll.bind(this);
			this.stopFreeTimeTrigger = ec.getFirstElementById("stopFreeTimeTrigger");
			this.stopFreeTimeTrigger.onclick = this.doShowUnSelectedFree.bind(this);




     
      this.nameComp = ec.getFirstElementById("name");
      this.sharing = ec.getFirstElementById("sharing");     
      this.published = ec.getFirstElementById("publishRemoveTrigger");
      this.color = ec.getFirstElementById("color");
      
      if (is_ie) {
         this.textChanger = new Af.TextChanger(this.nameComp);
      }
      
      this.publishMessage = ec.getFirstElementById("publishMessage");
      
     // this.nameComp.onchange = this.nameChanged.bind(this);

	  this.nameComp.onfocus = this.focusOnTextBox.bindAsEventListener(this);
	  this.nameComp.onblur = this.focusLostTextBox.bindAsEventListener(this);

      this.sharing.onchange = this.sharingChanged.bind(this);    
      this.published.onclick = this.publishedClicked.bindAsEventListener(this);

      this.color.onclick = this.pickColor.bind(this);
      
      this.allTimeList = ec.getFirstElementById("allTimeList");
      this.allTimeListGList = ec.getFirstElementById("allTimeListGList");
      this.freeTimeList = ec.getFirstElementById("freeTimeList");
	  this.freeTimeListGList = ec.getFirstElementById("freeTimeListGList");
	  
      
      this.removeMessageText = "This Calendar has been published to Jooners Community Calendars.<br/>To remove it from Community Calendars, Click:"
      this.publishMessageText = "To publish to Jooners Community Calendars, Click:"
      this.removeLabel = "Remove";
      this.publishLabel = "Publish";
   },
 
   setSchedule: function(sch) {
      this.table.style.display = "";
      this.sch = sch;
      if (sch["people"] == null) {
         createOneToManyAssoc(sch, "people", "Person");
      }
      
      if (sch["group"] == null) {
         createOneToManyAssoc(sch, "group", "Group");
      }
      
      if (sch["people2"] == null) {
         createOneToManyAssoc(sch, "people2", "Person");
      }
      
      if (sch["group2"] == null) {
         createOneToManyAssoc(sch, "group2", "Group");
      }
      
      this.sch = sch;
      
      var t = this.sch["name"]
      if (t == null) {
         t = "New Calendar";
         this.sch["name"] = t;
      }
      this.nameComp.value = t;
      t = this.sch["sharing"];
      if (t == null) {
         t = "private";
         this.sch["sharing"] = t;
      }
      this.sharing.value = t;
      t = this.sch["published"];
      if (t == null) {
         t = false;
         this.sch["published"] = "" + t;
      }   
     
      t = this.sch["color"];
      if (t == null) {
         t = "green";
         this.sch["color"] = t;
      }
      this.color.style.background = getBackground(t);
      this.updateSharingState();
      this.showPeopleGroups();
   },
   
   doShowFree: function() {
      this.showNotifyDialog(false);
      GATrackEvent("share");
      return false;
   },
   
   doShowAll: function() {
      this.showNotifyDialog(true);
      try {
    	  GATrackEvent("share");
      } catch (ex) {
      }
      return false;
   },

		doShowUnSelectedAll:function() {
			this.allDetails = "ALL_TIME";
			this.doShowUnSelectedAllPeople(true);
	 },

	 doShowUnSelectedAllPeople:function(bShowAll){
		 if(bShowAll){
				this.originalGrList = this.sch["group2"];
				this.originalPplList = this.sch["people2"];
	    } else {
				this.originalGrList = this.sch["group"];
				this.originalPplList = this.sch["people"];
			}
	   	
			this.pplList = this.originalPplList.slice(0, this.originalPplList.length);
			this.grpList = this.originalGrList.slice(0, this.originalGrList.length);
		 if (this.pgSelector == null) {
					this.pgSelector = new HJ.PeopleGroupSelector("Choose to unshare Calendar", this, null);
					this.pgSelector.centerDialog(400, 300);
					this.pgSelector.displayTextMessage = "Please choose group and people with whom you want to unshare Calendar. <BR/><BR/>";
		 }
	  	this.pgSelector.showHTMLTemplate(basePageURL + "PeopleGroupSelector.htm", "MainArea", "peopleSelector");
			this.pgSelector.centerDialog(400, 300);			
			this.pgSelector.setDataList(this.grpList,this.pplList,new Array(), new Array());			
			
			return false;
	 },

	 doShowUnSelectedFree:function() {
		 this.allDetails = "FREE_TIME";
		 this.doShowUnSelectedAllPeople(false);
	 },

	 selectionDone: function(child) {
	  
		var selectedPersonList = child.myPeopleDataList;
	
		this.personIdArr = new Array();
		this.groupIdArr = new Array();

		
		for(var idx=0;idx<selectedPersonList.length;idx++){
			if(selectedPersonList[idx]["isSelected"]==true){
				 this.personIdArr.push(selectedPersonList[idx].UUID);
			}
		}

		for(var grIndex=0;grIndex<this.originalGrList.length;grIndex++){
			if(this.originalGrList[grIndex]["isSelected"]==true){
				 this.groupIdArr.push(this.originalGrList[grIndex].UUID);
			}
		}
		if(this.personIdArr.length > 0 || this.groupIdArr.length > 0){
			showConfirmDialog("Are you sure you want to unshare this Calendar ?", "Are You Sure?", 300, 100, this.unshareSharedSch.bind(this),this.sharingChangedCancel.bind(this));
		}
	},

	 unshareSharedSch: function(){
		 hideDialogWin();
		 if(this.personIdArr.length > 0 || this.groupIdArr.length > 0){
			this.unShareSharedSchedule(this.sch,this.personIdArr,this.groupIdArr);
		 }
	 },

	unShareSharedSchedule:function(obj,personIds,groupIds){
			var req = new Af.DataRequest(svcURL,this.reqDeleteSharedScheduleCompleted.bind(this), this.reqFailedDeleteShaSch.bind(this), null, this.reqTimedoutDeleteShaSch.bind(this));
			req.addService("WorkspaceService", "deleteSharing");
			req.addParameter("sharedSchId", obj.UUID);
			if(personIds.length > 0){
				req.addParameter("personIds", personIds);
			}
			if(groupIds.length > 0){
				req.addParameter("groupIds", groupIds);
			}
			if(this.allDetails!=null){
				req.addParameter("allDetails", this.allDetails);
			}
			ajaxEngine.processRequest(req);
	 },

	reqDeleteSharedScheduleCompleted:function(response){
			var res = response.responseText;
			
			if(res == "SUCCESS") {
				
				showMessageDialog("Your shared Calendar has been successfully unshared.", "Unshare Successful", 300, 100);
					if(this.allDetails=="ALL_TIME" && this.sch["people2"].length > 0) {
						var size = this.sch["people2"].length;
						if(size > 0){
								for(var arrIndex=0;arrIndex < size;arrIndex++){
										if(this.sch["people2"][0]["isSelected"]==true){
											deleteFromArray(this.sch["people2"],this.sch["people2"][0]);
										}
								}
						}
					}

					if(this.allDetails=="ALL_TIME" && this.sch["group2"].length > 0) {
						var size3 = this.sch["group2"].length;
						if(size3 > 0){
								for(var arrIndex=0;arrIndex < size3;arrIndex++){
										if(this.sch["group2"][0]["isSelected"]==true){
											deleteFromArray(this.sch["group2"],this.sch["group2"][0]);
										}
								}
						}
					}


					if(this.allDetails=="FREE_TIME" && this.sch["people"].length > 0) {
						var size1 = this.sch["people"].length;
						if(size1 > 0){
								for(var arrIndex=0;arrIndex < size1;arrIndex++){
										if(this.sch["people"][0]["isSelected"]==true){
											deleteFromArray(this.sch["people"],this.sch["people"][0]);
										}
								}
						}
					}

					if(this.allDetails=="FREE_TIME" && this.sch["group"].length > 0) {
						var size4 = this.sch["group"].length;
						if(size4 > 0){
								for(var arrIndex=0;arrIndex < size4;arrIndex++){
										if(this.sch["group"][0]["isSelected"]==true){
											deleteFromArray(this.sch["group"],this.sch["group"][0]);
										}
								}
						}
					}
					this.doSave();
			}
		},

	 reqFailedDeleteShaSch:function(){
		 showMessageDialog("We are currently unable to delete this shared Calendar. <br/> Please try again.", "Excuse us!", 300, 100);
	 },

	 reqTimedoutDeleteShaSch:function(){
		 showMessageDialog("We are currently unable to delete this shared Calendar. <br/> Please try again.", "Excuse us!", 300, 100);
	 },

   
   nameChanged: function() {	  
      this.sch["name"] = this.nameComp.value;
      this.doSave();
   },
   
   sharingChanged: function() {
      if (this.sharing.value == "private") {
         showConfirmDialog("Are you sure you want to change this Calendar to be private?", "Are You Sure?", 300, 100, this.sharingChangedOK.bind(this),
         this.sharingChangedCancel.bind(this));
      } else {
         this.sch["sharing"] = this.sharing.value;
         this.doSave();
      }
      return false;
   },
   
   sharingChangedOK: function() {
      hideDialogWin();
      this.sch["sharing"] = this.sharing.value;
      if (this.sharing.value == "private") {
         this.sch["people"].length = 0;
         this.sch["group"].length = 0;
         this.sch["people2"].length = 0;
         this.sch["group2"].length = 0;
      }
      this.doSave();
   },
   
   sharingChangedCancel: function() {
      hideDialogWin();
      this.sharing.value = this.sch["sharing"];
   },
   
   pickColor: function() {
      var p = RicoUtil.toDocumentPosition(this.color);
      var x = p.x;
      var y = p.y  + this.color.offsetHeight;
      app.colorPicker.handler = this;
      app.colorPicker.show("content", x, y);
   },
   
   colorSelected: function(color) {
      this.sch["color"] = color;
      this.color.style.background = getBackground(color);
      this.doSave();
   },
   
   updateSharingState: function() {
      
      if (this.sharing.value == "shared") {
         this.table.rows[3].style.display = "";
         this.table.rows[4].style.display = "";
         this.table.rows[5].style.display = "";  
      } else {
         this.table.rows[3].style.display = "none";
         this.table.rows[4].style.display = "none";
         this.table.rows[5].style.display = "none";  
      }
      
      if (this.sch["published"] == "true") {
         this.publishMessage.innerHTML  = this.removeMessageText;
         this.published.value = this.removeLabel;
      } else {
         this.publishMessage.innerHTML  = this.publishMessageText
         this.published.value = this.publishLabel;
      }
   },   
   
  
   deleteScheduleConfirm: function() {
	    showConfirmDialog("Are you sure you want to delete this Calendar?", "Are You Sure?", 300, 110, this.doDeleteSchedule.bind(this));
	 /*  if (this.sch != null && this.sch["published"] == "true") {
	      showConfirmDialog("Are you sure you want to delete this Calendar? <br/>It is currently being shared with other people.", "Are You Sure?", 320, 130, this.doDeleteSchedule.bind(this));
	   }else{
		   showConfirmDialog("Are you sure you want to delete this Calendar?", "Are You Sure?", 300, 110, this.doDeleteSchedule.bind(this));
	   }*/
   },
   
   
   doDeleteSchedule: function() {
      hideDialogWin();
      this.parent.doDeleteSchedule(this.sch, this);
   },
   
   
   doSave: function() {
      app.schedule.myScheduleListChanged(true);		  
	  app.schedule.shownScheduleListChanged();
      this.save();
   },
   
   save: function(addlAction, emailsText, sendNotifyMailTo, allDetails) {
	  this.invalidEmails = "";	
      
      var editor = new Af.ObjEditor();
      
      var nestedXml = editor.getChangeXmlForObjList(this.sch["people"], ["name"], "people");
      
      nestedXml += editor.getChangeXmlForObjList(this.sch["group"], ["name"], "group");
      
      nestedXml += editor.getChangeXmlForObjList(this.sch["people2"], ["name"], "people2");
      
      nestedXml += editor.getChangeXmlForObjList(this.sch["group2"], ["name"], "group2");
      
      var xmlString = editor.getChangeXmlForObj(this.sch, ["name", "sharing", "published", "color", "category", "notifMessage","communityTitle", "city", "state", "description"], "ObjModify", nestedXml);
      
      var req = new Af.DataRequest(svcURL, this.saveSuccessful.bind(this), this.saveFailed.bind(this), null,
      this.saveTimedOut.bind(this));
      req.addService("WorkspaceService", "saveScheduleDetails");
      if (this.sch.UUID != null) {
		req.addParameter("UUID", this.sch.UUID);
      }
      
      this.addlAction = addlAction;
     
      if (addlAction != null) {
         req.addParameter("addlAction", addlAction);
      }
      if (emailsText != null) {
				var emailArr = emailsText.split(",");				
				this.emailsArray = new Array();
				for(var emailIndex=0;emailIndex < emailArr.length;emailIndex++){
					if(!app.emailValidator.validateEmail(emailArr[emailIndex])){
						if (emailArr[emailIndex] != "") {
							if(this.invalidEmails == "") {
								this.invalidEmails += emailArr[emailIndex];
							}
							else {
								if(this.invalidEmails.indexOf(emailArr[emailIndex]) == -1) {
									this.invalidEmails += "," + emailArr[emailIndex];
								}
							}
						}
						 continue;
					}
					emailArr[emailIndex] = app.emailValidator.extractEmailAddress(emailArr[emailIndex]);
					if(emailArr[emailIndex] != ""){
						this.emailsArray.push(emailArr[emailIndex]);
					}
				}
				req.addParameter("emails", xmlEncode(emailsText));
      }
      if (sendNotifyMailTo != null) {
         req.addParameter("sendNotifyMailTo", sendNotifyMailTo);
      }
      if (allDetails != null) {
         req.addParameter("allDetails", ""+allDetails);
      }
	  if (this.sharing.value == "private") {
		  req.addParameter("isPrivate", "Yes");
	  }
			req.xmlDoc = xmlString;
      
      ajaxEngine.processRequest(req);
   },
   
   saveSuccessful: function(response) {
      
      
      var xds = new Af.XMLToDataSet(response.responseXML);
	  var e = xds.data;
	 
      if (this.sch.UUID == null) {
		 this.sch.UUID = e.UUID;
		 this.parent.schedules.unshift(this.sch);
		 app.schedule.myScheduleListChanged(true);
		 app.db.workspace["schedule"].push(this.sch);
      }
      
	  var pl = e["people"];
	  var schpl = this.sch["people"]
	  if (pl != null  && pl.length > 0) {
	     var actualPL = app.workspace["myPeople"];
	     for (var i=0; i<pl.length; i++) {
	        var o;
	        o = findObjById(actualPL, pl[i]["UUID"]);
	        if (o == null) {
	           o = pl[i];
	           o.__parent = actualPL.__parent;
	           actualPL.push(o);
	        }
	        if (findObjById(schpl,o["UUID"]) == null) {
	           schpl.push(o);
	        }
	     }
	     app.myPeople.myPeopleListChanged();
	  }
	  
	  pl = e["people2"];
	  schpl = this.sch["people2"]
	  if (pl != null && pl.length > 0) {
	     var actualPL = app.workspace["myPeople"];
	     for (var i=0; i<pl.length; i++) {
	        var o;
	        o = findObjById(actualPL, pl[i]["UUID"]);
	        if (o == null) {
	           o = pl[i];
	           o.__parent = actualPL.__parent;
	           actualPL.push(o);
	        }
	        if (findObjById(schpl,o["UUID"]) == null) {
	           schpl.push(o);
	        }
	     }
	     app.myPeople.myPeopleListChanged();
	  }
	  this.showPeopleGroups();
      this.updateSharingState();
      if (this.addlAction == "notify") {
		 if(this.invalidEmails!=""){
			showMessageDialog("Your email notification has been sent and these are the invalid emails to which we are unable to send notification.<BR/>"+this.invalidEmails, "Email Delivered", 450, 150);
		 }
		 else{
			showMessageDialog("Your email notification has been sent.", "Email Delivered", 400, 150);
		 }
      }
   },
   
   saveFailed: function(dataRequest, msg) {
	  if (this.addlAction == "notify") {        
		 showMessageDialog("We are currently unable to share this Calendar.<br/> Please try again.", "Excuse us!", 350, 130);
      }else{
		showMessageDialog("We are currently unable to save this Calendar.<br/> Please try again.", "Excuse us!", 350, 130);
	  }
   },
   
   saveTimedOut: function(dataRequest) {
      showMessageDialog("We are currently unable to save this Calendar.<br/> Please try again.", "Excuse us!", 400, 150);
   },
   
   showNotifyDialog: function(all) {
    
      if (this.shareNotificationEmailDialog == null) {
         this.shareNotificationEmailDialog = new HJ.ShareNotificationEmail("Calendar Sharing Email", this, null);
         this.shareNotificationEmailDialog.width = "370px";         
      }
      this.shareNotificationEmailDialog.showHTMLTemplate(basePageURL + "ShareNotificationEmail.htm", "MainArea", "shareNotificationEmail");
	  this.shareNotificationEmailDialog.centerDialog(350, 350);
      this.shareNotificationEmailDialog.setObj(this.sch, all);
   },
   
   publishedClicked:function(evt){
	
		var f = this.sch["published"];	
		
		if (f == "false") {
			if (this.dialog == null) {
					this.dialog = new HJ.PublishCalender("Publish Your Calendar", this, null);
			}						
			var obj = new Object();
			obj["city"] = "City";
			this.dialog.showHTMLTemplate(basePageURL + "PublishYourCalendar.htm", "content", "publishCalDiv");
			this.dialog.centerDialog(300, 300);
			this.dialog.setObj(obj, true);
			return true;
		} else {
		    showConfirmDialog("Are you sure you want to unpublish this Calendar? Unpublishing it will make it unavailable to the Jooners community.", "Are You Sure?", 400, 150, this.doUnpublishCalendar.bind(this));
		    return false;
		}
		
    },
	
	doUnpublishCalendar: function() {
	  hideDialogWin();	
	  this.sch["published"] = "false";
	  this.sch["category"] = "";
	  this.sch["communityTitle"] = "";
	  this.sch["description"] = "";
	  this.sch["city"] = "";
	  this.sch["state"] = "";
	  this.save();
	},
	
	showPeopleGroups: function() {
      var s = "";
	  var g = "";
      var l = this.sch["people"];
      for (var i=0; i<l.length; i++) {        
		 if(s == ""){
			  s += '<b><strong>'+"Individuals"+'</b></strong>' +"<br/>" + (""==trim(getFullName(l[i])) ? l[i]["email"] : getFullName(l[i]));
		  }else{
	          s += "<br/>" + (""==trim(getFullName(l[i])) ? l[i]["email"] : getFullName(l[i]));
		  }
      }
      l = this.sch["group"];
      for (var i=0; i<l.length; i++) {
          if(g == ""){
			  g += '<b><strong>'+"Groups"+'</b></strong>'+"<br/>" + l[i].name;
		  }else{
	         g += "<br/>" + l[i].name;
		  }
      }
      this.freeTimeList.innerHTML = s;
	  this.freeTimeListGList.innerHTML = g;
      
      s = "";
	  g = "";
      var l = this.sch["people2"];
      for (var i=0; i<l.length; i++) {
         if(s == ""){
			   s += '<b><strong>'+"Individuals"+'</b></strong>' +"<br/>" + (""==trim(getFullName(l[i])) ? l[i]["email"] : getFullName(l[i]));
		  }else{
	          s += "<br/>" + (""==trim(getFullName(l[i])) ? l[i]["email"] : getFullName(l[i]));
		  }
      }
      l = this.sch["group2"];
      for (var i=0; i<l.length; i++) {
		  if(g == ""){
			   g += '<b><strong>'+"Groups"+'</b></strong>'+"<br/>" + l[i].name;
		  }else{
	         g += "<br/>" + l[i].name;
		  }
      }
      this.allTimeList.innerHTML = s;
	  this.allTimeListGList.innerHTML = g;
   },

	focusOnTextBox: function(evt) {
	  if("New Calendar" == this.nameComp.value){
		this.nameComp.value = "";
	  }
	  this.nameComp.focus();
   },
   
   focusLostTextBox: function(evt) {      
	    var s = this.nameComp.value;
		if(s == null) {
			s= "";
		}
		else {
			s = trim(s);
		}
		
		var s1 = trim("New Calendar");
		if(s == s1 || s == "") {
			this.nameComp.value = this.sch["name"];
		}
		else {
			this.sch["name"] = this.nameComp.value ;
			this.doSave();			
			GATrackEvent("changeName");
		}
         consumeEvent(evt);	      
   }
  
}


