HJ.MyGroup = Class.create();

HJ.MyGroup.prototype = {
   
   initialize: function() {
      
      //global var for the myListId
      
      this.targetContainerId = "content";
      
      this.myGroupTable = new Af.HtmlTable("myGroupTable", ",,name");
      this.myGroupTable.listener = this;
      this.currentRow = -1;
      
      this.myGroupTitleLink = new Af.HtmlTitlePane2("myGroupTable", "myGroupTitle", "boxLink open", "boxLink closed");
      this.myGroupTitleLink.listener = this;
      this.tl = null;
      
      this.url = basePageURL + "MyGroup.html";
      this.url2 = basePageURL + "GroupDetails.html";
      this.tl = null;
      
      this.leftList = null;
      this.rightList = null;
      this.myPeopleList = null;
      this.dataTable = null;
   },
   
   cleanup: function() {
	  this.myGroupTable.cleanup();
   },
   
   setDataList: function(dlist, myPeopleList) {
      this.myPeopleList = myPeopleList;   
      this.dataTable = new Af.DataTable(dlist);
	  if(dlist != null && dlist.length > 0){
		 dlist.sort(sortGroups);
	  }
	  this.myGroupTable.setDataList(dlist);
      this.setAllLists();
   },
   
	viewSelected: function(invoker) {		
   //  HIDE CALENDAR'S HEADER
	  if(calenderTop == null){
		calenderTop = document.getElementById("calenderTop");
	  }
	  calenderTop.style.display = "none";

      this.loadMyGroupTemplate();
    },
   
   setAllLists: function(groupRow) {
      if (this.leftList == null || this.myPeopleList  == null) {
         return false;
      }
    
      if (this.currentRow < 0 || this.currentRow >= this.dataTable.getDataList().length) {
          this.currentRow = 0;
      }

      // the following order is important
      this.setGroupSelectorList(this.currentRow);
      this.setPeopleGroupSelectorList();
      this.setRightList();
      this.setLeftList();
   },
   
   
   setGroupSelectorList: function(groupRow) {
      this.groupSelector.setDataList(this.dataTable.getDataList(), groupRow);
   },
   
   setPeopleGroupSelectorList: function() {
		var l = new Array();
		l = l.slice(0, l.length);
		var o = new Object();
		o["name"] = "MY PEOPLE";
		l.push(o);
		o = new Object();
		o["name"] = "-------------";
		l.push(o);

		var l2 = this.dataTable.getDataList();

		for (var i=0; i<l2.length; i++) {
			l.push(l2[i]);
		}

		this.peopleGroupSelector.setDataList(l);
	},

   setLeftList: function() {
	   var leftSelected = this.leftList.selectElement.selectedIndex;
	   var idx = this.peopleGroupListSelector.selectedIndex;
	   if (idx == 1) {
         this.leftList.setDataList(new Array());
         return;
      }
      
      var l;
      
      if (idx == 0) {
         l = this.myPeopleList;
      } else {
         var g = this.dataTable.getDataList()[idx-2];
         l = g["people"];
         if (l == null) {
           l = new Array();
         }
      }
	  	  
	  var peopleLl;
	  var obj = this.groupSelector.getSelectedObj();
      if (obj == null) {
		  peopleLl = new Array();         
		  for (var i=0; i<l.length; i++) {
		      var p = l[i];
			  if(""!=trim(getFullName(p))){
				p["name"] = getFullName(p);
			  }else{
				p["name"] = p["email"];
			  }
			  peopleLl.push(p);		  
          }
				 
      } else {
         
         var l2 = obj["people"];
         if (l2 == null) {
            createOneToManyAssoc(obj, "people", "Person");
            peopleLl = l;
         } else {
            peopleLl = new Array();
            for (var i=0; i<l.length; i++) {
               var p = l[i];
               if (findObjIndex(l2, p) < 0) {
				  if(""!=trim(getFullName(p))){
					p["name"] = getFullName(p);
				  }else{
					p["name"] = p["email"];
				  }
			                      
                  peopleLl.push(p);
               }
            }
         }
      }

	  this.leftList.setDataList(peopleLl.sort(sortByLastName));	 
	  if (peopleLl.length > 0) {
		  try{	
			  if(this.leftList.selectElement.options.length > leftSelected){
				this.leftList.selectElement.options[leftSelected].selected = true;		
			  }else{
				  this.leftList.selectElement.options[0].selected = true;		
			  }
		  }catch(errs) {
		  }
      } else {
        this.leftList.selectElement.selectedIndex  = -1;
      }
	
	// Setting references to null
		idx = null;
		peopleLl = null;
		l = null;

   },
   
   setRightList: function() {
		var obj = this.groupSelector.getSelectedObj();
		if (obj == null) {
			this.rightList.setDataList(new Array());
			this.groupListSelector.selectedIndex = -1;
		return;
		}
		
		if (obj["people"] == null) {
			createOneToManyAssoc(obj, "people", "Person");
		}
		var l = obj["people"];
		if(this.rightList==null){
			return;
		}
		for(var i=0;i<l.length;i++){
			if(""==trim(getFullName(l[i]))){				
				l[i]["name"] = l[i]["email"];
			}			
		}
		if(l!=null){
			this.rightList.setDataList(l.sort(sortByLastName));
		}
	},
   
   
   cellSelected: function(row, col, reselected) {
	
	 //  HIDE CALENDAR'S HEADER
	  if(calenderTop == null){
		calenderTop = document.getElementById("calenderTop");
	  }
	  calenderTop.style.display = "none";

	  refreshWidget();   

      this.currentRow = row;    
	  if (!reselected) {
         this.myGroupTable.selectRow(row);
      }
      this.loadMyGroupTemplate2();
   },
   
   paneStateChanged: function(comp) {
      this.loadMyGroupTemplate();
   },
   
   showGroupDetails: function() {
	   if(this.currentRow == -1 || this.dataTable.getDataList().length == 0) {
		 showMessageDialog("please select Group name.", "Request!", 300, 100);
		 return;
	  }	  
	  this.loadMyGroupTemplate2();
   },

   loadMyGroupTemplate: function () {
      if (this.tl == null) {
         this.tl = new Af.TemplateLoader(this.url, this.targetContainerId, "MyGroupContent");
         this.tl.listener = this;
         this.tl.loadTemplate();
      } else {
         this.tl.reAttachElement();
         app.setCurrentView(this);
         this.setAllLists();
      }
   },
	
    loadMyGroupTemplate2: function () {
      if (this.tl2 == null) {
         this.tl2 = new Af.TemplateLoader(this.url2, this.targetContainerId, "GroupDetails");
         this.tl2.listener = this;
         this.tl2.loadTemplate();
      } else {
         this.tl2.reAttachElement();
         app.setCurrentView(this);
         this.setGroupDetails();
      }
    },
   
   templateLoaded: function(tl) {
     if (tl == this.tl) {
         this.templateLoaded1();
      } else if (tl == this.tl2) {
         this.templateLoaded2();
      }
   },
   
   templateLoaded1: function() {

      this.leftList = new Af.HtmlMultiSelect("MyGroupSubscribed", "name");
      this.rightList = new Af.HtmlMultiSelect("available", "name");
      
      this.addGroup = document.getElementById("addGroup");
      this.addGroup.onclick = this.doAddGroup.bind(this);
      var button = document.getElementById("shareGroup");
      button.onclick = this.shareGroupClicked.bind(this);
	  this.renameGroup = document.getElementById("renameGroup");
      this.renameGroup.onclick = this.doRenameGroup.bind(this);
	  
      this.addPerson = document.getElementById("addPerson");
      this.addPerson.onclick = this.doAddPerson.bind(this);
      this.editPerson = document.getElementById("editPerson");
      this.editPerson.onclick = this.doEditPerson.bind(this);
      this.deleteGroup = document.getElementById("deleteGroup");
      this.deleteGroup.onclick = this.deleteGroupConfirm.bind(this);
      
      this.addToGroup = document.getElementById("addToGroup");
      this.addToGroup.onclick = this.doAddToGroup.bind(this);

	  this.doneGroup = document.getElementById("doneGroup");
      this.doneGroup.onclick = this.showGroupDetails.bind(this);

      
      this.removeFromGroup = document.getElementById("removeFromGroup");
      this.removeFromGroup.onclick = this.doRemoveFromGroup.bind(this);
      
      this.peopleGroupSelector = new Af.HtmlSingleSelect("peopleGroupSelector", "name");
      this.peopleGroupListSelector = document.getElementById("peopleGroupSelector");
      this.peopleGroupListSelector.onchange = this.leftListTypeChanged.bind(this);
      
      this.groupSelector = new Af.HtmlSingleSelect("myGroupList", "name");
      this.groupListSelector = document.getElementById("myGroupList");
      this.groupListSelector.onchange = this.rightListTypeChanged.bind(this);
     
      this.setAllLists();
      app.setCurrentView(this);
      
   },   
  
   templateLoaded2: function() {
		var ec = new Af.ElementCollection(this.tl2.element);
		this.addPersonGroupDetails = ec.getFirstElementById("addPersonGroupDetails");
		this.groupDetailsTitle = ec.getFirstElementById("groupDetailsTitle");
		this.addPersonGroupDetails.onclick = this.doAddPerson.bind(this);
		this.printGroupDetails = ec.getFirstElementById("printGroupDetails");
		this.printGroupDetails.onclick = this.doPrintGroupDetails.bind(this);

	  
	    var te = ec.getFirstElementById("groupDetailsTable");
	    this.tableElement  = te;
	    if (te == null) {
	       return;
	    }
	    
	    if (te.tBodies.length == 0) {
	       return;
	    }
	    
	    var tb = te.tBodies[0];
	    
	    if (tb.rows.length == 0) {
	       return;
	    }
	    
	    this.templateRow = this.tableElement.rows[0].cloneNode(true);
	    removeAll(tb);
	    
	    this.setGroupDetails();
   },
   
   setGroupDetails: function() {
   
      if ( this.dataTable.getDataList().length == 0) {
         return;
      }
      
      if (this.currentRow < 0 || this.currentRow >= this.dataTable.getDataList().length) {
          this.currentRow = 0;
      }
      
      var g = this.dataTable.getDataList()[this.currentRow];
      
      this.groupDetailsTitle.innerHTML = g.name;
      
       var tb = this.tableElement.tBodies[0];
	   removeAll(tb);
	   
	   var dlist = g["people"];
	   
	   if (dlist == null) {
	      return;
	   }
	   dlist.sort(sortByLastName);
	   for (var i=0; i<dlist.length; i++) {
	      var data = dlist[i];
	      var row = this.templateRow.cloneNode(true);
	      row.id = "" + i;
	      
	      tb.appendChild(row);
	   
	      if(data.fName != null){
			   row.cells[0].innerHTML = data.fName;
		  }
		  if(data.lName != null){
			   row.cells[1].innerHTML = data.lName;
		  }	     
		  
	      var s = data["phonePrimary"];
	      if (s == null) {
	         s = "";
	      }
	      row.cells[2].innerHTML = s;
	      
	      var t = "";
	      s = data["email"];
	      if (s == null) {
	         s = "";
	      }	 
	      
	      row.cells[3].innerHTML = s;
	   
	   }
   },

	shareGroupClicked: function(evt) {
		if (this.shareGroupDisplayed || login == null || app == null) {
			// stop multiple dialogs from being shown
			return false;
		}
		// XXX: uncomment after debug this.shareGroupDisplayed = true;

	   	this.shareGroupDialog = new HJ.ShareGroup(this);
	   	this.shareGroupDialog.loadTemplate();

	 	return false;
	},

   // Called from ShareGroup.js
   shareGroupDialogClosed: function(dialog) {
       this.shareGroupDisplayed = false;
       // allow garbage collection
       this.shareGroupDialog = null;
   },

   doAddToGroup: function() {
       var obj = this.groupSelector.getSelectedObj();
      if (obj == null) {
         return;
      }
      var l = this.leftList.getSelectedObjs();
      if (l.length > 0) {
         for (var i=0; i<l.length; i++) {
					if(this.rightList.dlist!=null){
						this.rightList.dlist.push(l[i]);
					}
         }
         this.setAllLists();
      } else {
         return;
      }
      app.groupUpdated(obj, this.myPeopleList);
      this.saveGroup(obj);
   },
   
   doRemoveFromGroup: function() {
      var obj = this.groupSelector.getSelectedObj();
      if (obj == null) {
         return;
      }
      var l = this.rightList.getSelectedObjs();
      if (l.length > 0) {
         for (var i=0; i<l.length; i++) {
					 if(this.rightList.dlist!=null && this.rightList.dlist.length > 0){
						deleteFromArray(this.rightList.dlist, l[i]);
					 }
         }
         this.setAllLists();
      } else {
        return;
      }
      app.groupUpdated(obj, this.myPeopleList);
      this.saveGroup(obj);
   },
   
   
   leftListTypeChanged: function() {
      this.setLeftList();
   },
   
   rightListTypeChanged: function() {	   
	  this.currentRow = this.groupSelector.getSelectedIndex();   
      this.setRightList();
      this.setLeftList();
   },
   
   
   doAddGroup: function() {
      if (this.dialog != null) {
    	  delete this.dialog;
      }
	  this.dialog = new HJ.GroupDialog("Add Group", this, null);		
      this.dialog.showHTMLTemplate(basePageURL + "AddGroup.html", "content", "newGroup");
	  this.dialog.centerDialog(400, 250);
	  this.dialog.setDataObject(null, "Type the name of a new group.");
      return false;
   },
	
   doRenameGroup: function() {	   
	  if(this.currentRow == -1 || this.dataTable.getDataList().length == 0) {
		 showMessageDialog("please select Group name.", "Request!", 300, 100);
		 return;
	  }
      if (this.renamedialog != null) {
    	  delete this.renamedialog;
      }
	  this.renamedialog = new HJ.GroupDialog("Rename Group", this, null);			
      this.renamedialog.showHTMLTemplate(basePageURL + "AddGroup.html", "content", "newGroup");
	  this.renamedialog.centerDialog(400, 250);
	  this.renamedialog.setDataObject(this.dataTable.getDataList()[this.currentRow], "Type new group name.");
      return false;
   },
   
   doAddPerson: function(){
      app.myPeople.doAddPerson();
      return false;
   },
   
   deleteGroupConfirm: function() {
      if(this.currentRow >= 0 && this.dataTable.getDataList()[this.currentRow] != null)
      {
         var obj = this.dataTable.getDataList()[this.currentRow];	
	     showConfirmDialog("Are you sure you want to delete this group? <br/> All people in the group will remain in My People.", "Are You Sure?", 300, 120, this.doDeleteGroup.bind(this));
	  } else {
	     showMessageDialog("Please select a group to delete." , "Request", 300, 80);
	  }
   },
   
   doDeleteGroup: function(){
      hideDialogWin();
      if(this.currentRow >= 0)
      {
         var obj = this.dataTable.deleteObjectByIndex(this.currentRow);      
		 this.myGroupTable.setDataList(this.dataTable.getDataList());
         app.groupDeleted(obj, this.myPeopleList);
         this.currentRow = -1;
         this.deleteGroupName(obj);
      }
      else {
         showMessageDialog("Please select group to delete." , "Request", 300, 80);
      }
      
   },
   
   deleteGroupName: function(obj) {
      var req = new Af.DataRequest(svcURL, this.requestDeleteGroupCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
      req.addService("WorkspaceService", "deleteGroupName");
      req.addParameter("UUID", obj.UUID);
      ajaxEngine.processRequest(req);
   },
   
   requestDeleteGroupCompleted: function(response)	{
      this.setAllLists();
   },
   
   requestFailedCommon: function(dataRequest, msg) {
      showMessageDialog("We are currently unable to delete this group.  Please try again.", "Excuse us!", 350, 100);
   },
   
   requestTimedoutCommon: function() {
      showMessageDialog("We are currently unable to delete this group.  Please try again.", "Excuse us!", 350, 100);
   },
   
   saveGroup: function(obj) {
      var editor = new Af.ObjEditor();
	  var nestedXml = editor.getChangeXmlForObjList(obj["people"], ["name", "fName", "lName"], "people");
	  var xmlString = editor.getChangeXmlForObj(obj, ["name"], "ObjModify", nestedXml);
 
      var req = new Af.DataRequest(svcURL,this.requestSaveGroupCompletedCommon.bind(this), 
		this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
      req.addService("WorkspaceService", "saveGroupDetails");
      req.addParameter("UUID", obj.UUID);
      req.xmlDoc = xmlString;
      ajaxEngine.processRequest(req);
   },
  
   requestSaveGroupCompletedCommon: function(response){
   },

		doPrintGroupDetails:function(){
				var groupData = this.dataTable.getDataList()[this.currentRow];
				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", "myGroups");
				req.addParameter("xlstFile","MyGroups.xsl");
				req.addParameter("UUID",groupData.UUID);
				ajaxEngine.processRequest(req);
				return false;
		},

		printCompleted: function(response)	{
			var p = new Af.PrintUtil();
			p.showPrintView(response);
		},

		printFailed: function() {
				showMessageDialog("<br/>Printing is currently unavailable.Please try again.", "Printing Unavailable", 350, 100);
		},

		requestTimedout: function() {
				showMessageDialog("<br/>Printing is currently unavailable.Please try again.", "Printing Unavailable", 350, 100);
		},

	 doEditPerson:function(){
		 var selectedPerson =  this.leftList.getSelectedObjs();
		 if(selectedPerson.length==1){
			if (this.editPersonDialog1 != null) {
				delete this.editPersonDialog1;
			}
			this.editPersonDialog1 =  new HJ.MyPeopleDetail("Person Details", app.myPeople, null);
			this.editPersonDialog1.width = "520px";
			this.editPersonDialog1.showHTMLTemplate(basePageURL + "MyPeopleDetail.html", "content", "peopleDetail");
			this.editPersonDialog1.centerDialog(520, 250);
			
			var selectedPerson = selectedPerson[0];
			this.editPersonDialog1.setObj(selectedPerson);
			this.editPersonDialog1.personHandlerIs = "myGroup";
		 }else{
			 showMessageDialog("Please choose one person's record to edit.", "Request", 350, 100);
		 }
		 return false;
	 },

	 refresh: function() {		 
		 this.setDataList(app.workspace["myGroup"],app.workspace["myPeople"]);		 
		 if(this.groupDetailsTitle != null) {
			this.setGroupDetails();
		 }
	  return;
   }

}

