HJ.MyPeopleDetail = Class.create();

HJ.MyPeopleDetail.prototype = Object.extend(new Af.HtmlDialog(), {

   initialize: function(title, handler, content) {
	    this._initializeDialog(title, handler, content);
		this.isCallFromMyLovedOne = false;		
		this.handler = handler;
		this.personHandlerIs = null;
   },
	
	
   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

	  this.fNameCursor = document.getElementById("fName");
      var ec = new Af.ElementCollection(this.element);
	  this.save = ec.getFirstElementById("save");
	  this.armedButton = this.save;
	  this.dontSave =  ec.getFirstElementById("dontSave");	
	  this.save.onclick = this.doSave.bind(this);
	  this.dontSave.onclick = this.doDontSave.bind(this);
	  this.groupSelector = ec.getFirstElementById("groupSelector");
	  this.groupSelector.onclick = this.doGroupSelection.bindAsEventListener(this);
	  this.deletePersonLink = ec.getFirstElementById("deletePerson");
		this.deletePersonLink.onclick = this.deletePeopleConfirm.bind(this);
		this.printPersonDetails =  ec.getFirstElementById("printDetails");
		this.printPersonDetails.onclick = this.doPrintDetails.bind(this);

	  this.editor = new Af.ObjEditor();
	  
	  this.fName = this.editor.addTextByEC(ec, "fName");
	  this.editor.addTextByEC(ec, "lName");
	  this.phone1 = this.editor.addTextByEC(ec, "phone1");
	  this.phone2 = this.editor.addTextByEC(ec, "phone2");
	  this.phone3 = this.editor.addTextByEC(ec, "phone3");
	  this.email = this.editor.addTextByEC(ec, "email");
	  this.editor.addTextByEC(ec, "alternateEmail");
	  this.editor.addTextByEC(ec, "myNotes");
	  this.address = this.editor.addTextByEC(ec, "address");
	  this.editor.addTextByEC(ec, "city");
	  this.editor.addSelectByEC(ec, "state");
	  this.zip = this.editor.addTextByEC(ec, "zip");
	  this.phoneType1 = this.editor.addSelectByEC(ec,"phoneType1");
	  this.phoneType2 = this.editor.addSelectByEC(ec,"phoneType2");
	  this.phoneType3 = this.editor.addSelectByEC(ec,"phoneType3");	  
	  
	  this.phonePrimary = this.editor.addTextByEC(ec, "phonePrimary");
	  this.primaryRadio = new Array(3);
	  this.primaryRadio[0] = ec.getFirstElementById("phonePrimary1");
	  this.primaryRadio[1] = ec.getFirstElementById("phonePrimary2");
	  this.primaryRadio[2] = ec.getFirstElementById("phonePrimary3");

	  this.zip.element.onkeypress = this.doValidateZipCode.bindAsEventListener(this);
	 
	  if (this.obj != null) {
	     this.editor.clearChanges();		 
	     this.editor.setValueFromObj(this.obj);
	  }
	  this.showDeleteAndPrintLink();	  
	  this.showPrimaryNumber();
   },
   
   setObj: function(obj, mode) {
       this.isCreateMode = mode;	
	   this.cloneObj = new Object();
	   this.cloneObj = cloneObject(obj);
	   this.obj = (obj);	
	  
	   if (this.obj["group"] == null) {
         createOneToManyAssoc(this.obj, "group", "Group");
       } 
	   if (this.editor != null) {
	     this.editor.clearChanges();		 
	     this.editor.setValueFromObj(this.obj);
	   }
	   this.showDeleteAndPrintLink();
	   this.showPrimaryNumber();
   },

   showDeleteAndPrintLink: function() {
	   if(this.deletePersonLink != null && this.printPersonDetails != null) {
			if(this.handler.IsNewPerson != null && this.handler.IsNewPerson == true)  {
				this.deletePersonLink.style.display = "none";		
				this.printPersonDetails.style.display = "none";				
				this.handler.IsNewPerson = false;
			}
			else {
				this.deletePersonLink.style.display = "";		
				this.printPersonDetails.style.display = "";
			}
	   }
	   if(this.phone1 != null && this.phone2 != null && this.phone3 != null && this.obj != null) {					 
		    var obj = cloneObject(this.obj);
			app.formatPhone.setListenerOnPhonesId("phone1,phone2,phone3",this.obj); 
	   }
	   if(this.fNameCursor != null) {
		  // this.fNameCursor.focus();
	   }
   },

	showPrimaryNumber: function() {		  
		 // To keep selected radio button corresponding to  primary phone number
		 if(this.obj == null || this.primaryRadio == null) {
			 return;
		 }
		for(var index =0; index < this.primaryRadio.length; index++){	
			var phone = this.obj["phone"+(index+1)];
			if(this.obj["phonePrimary"] == phone && phone != "") {
				this.primaryRadio[index].checked = true;	
				break;							
			}
		}
	},
   
   doSave: function() {
	     if(this.isEmailIDExist()) {
			 return;
		 }
		 if(this.obj["address"] != null){
			 this.obj["address"] = this.obj["address"];
		 }
		 var fObject = app.formatPhone.getFormattedObject();
		
		 if(fObject["phone1"] != undefined && fObject["phone1"] != null)
			this.obj["phone1"] = fObject["phone1"];
		 if(fObject["phone2"] != undefined && fObject["phone2"] != null)
			this.obj["phone2"] = fObject["phone2"];
		 if(fObject["phone3"] != undefined && fObject["phone3"] != null)
			this.obj["phone3"] = fObject["phone3"];
		
		 this.editor.addNV("phone1", this.obj["phone1"]);						
		 this.editor.addNV("phone2", this.obj["phone2"]);						
		 this.editor.addNV("phone3", this.obj["phone3"]);
		
		 // set primary phone number here based on the radio button selected	
		var array = this.primaryRadio;
		var phone1 = this.obj["phone1"];
		var phone2 = this.obj["phone2"];
		var phone3 = this.obj["phone3"];
		if(phone1==null)
		 phone1 = "";		 
		 if(phone2==null)		 
		 phone2 = "";
		 if(phone3==null)
		 phone3 = "";
		 
		if(phone1!="" && (phone2=="" && phone3=="")){
			array[0].checked = true;			
			this.phonePrimary.setValue(phone1);
			this.obj["phonePrimary"] = phone1;			
		}else if(phone2!="" && (phone1=="" && phone3=="")){
			array[1].checked = true;		
			this.phonePrimary.setValue(phone2);			
			this.obj["phonePrimary"] = phone2;
		}
		else if(phone3!="" && (phone1=="" && phone2=="")){
			array[2].checked = true;			
			this.phonePrimary.setValue(phone3);			
			this.obj["phonePrimary"] = phone3;
		}
		else{
			for(var index =0;index <array.length; index++){	
				var phone = this.obj["phone"+(index+1)];		
				if(array[index].checked && phone!=null && phone!=undefined){
					var s = phone;
					if (s == null) {
					   s = "";
					}
					this.phonePrimary.setValue(s);
					this.obj["phonePrimary"] = s;
				}
			}
		}
		
		 if(this.phoneType1.value ==undefined){
					this.phoneType1.setValue("Home");
		 }
		if(this.phoneType2.value ==undefined){
					this.phoneType2.setValue("Office");
		 }
		 if(this.phoneType3.value ==undefined){
					this.phoneType3.setValue("Mobile");
		 }
				
		if(this.fName.getValue() == "" || this.fName.getValue() == undefined) {
			showMessageDialog("Please enter first name of person.","Request",300,100,null, true);
			return;			
		}
		 if(this.email.getValue() != "" && this.email.getValue() != undefined) {
			if(app.emailValidator.validateEmail(trim(this.email.value))==false){
					 showMessageDialog("Please enter a valid email address.","Request",300,100,null, true);
					return;
			}
		}
		this.email.value = app.emailValidator.extractEmailAddress(this.email.value);
		
		 if(this.address.value != undefined && this.address.value.length > 100 ) {
			showMessageDialog("The address you have entered is too long. Please enter a shorter version.","Request",300,100,null, true);
			 return;
		 }

		if(this.zip.value != undefined &&this.zip.value != "" ) {
			if(app.validator.validateZip(this.zip.value) == false) {
				showMessageDialog("<br/>Please enter a valid zip code.","Request", 300, 100,null, true);
				return;
			}
		 }		 		
		app.peopleUpdated(this.obj, app.workspace["myGroup"]);   		
		var assocsXml = this.editor.getChangeXmlForObjList(this.obj["group"], ["name"], "group");	
		var xmlString = this.editor.getChangeXml(this.isCreateMode, assocsXml);
	
		if (xmlString == null) {
			showMessageDialog("Any changes made have been saved.", "Informing You", 300, 100,null, true);
			return;
		}		
		this.obj["name"] = getFullName(this.obj);
		if (this.isCreateMode) {			
			this.handler.dataTable.addObject(this.obj); // this sets id of the object		 
		}

		 var req = new Af.DataRequest(svcURL, this.saveSuccessful.bind(this), this.saveFailed.bind(this), null, 
					this.saveTimedOut.bind(this));
		 req.addService("WorkspaceService", "savePersonDetails"); 
		 
		 if (this.obj.UUID != null) {
			req.addParameter("UUID", this.obj.UUID); 
		 }
		 req.xmlDoc = xmlString;
	
		ajaxEngine.processRequest(req);
		this.hide();
		return true;
   },
   
   doDontSave: function() {	 
		this.editor.clearChanges();
		this.hide();
		if(this.isCallFromMyLovedOne) {
		  this.isCallFromMyLovedOne = false;
		  app.myLovedOne.showInfo = 0;
	   }	
	   if(this.handler.myPeopleDetailsTable != null && this.personHandlerIs == "myPeople") {
			var currentRow = this.handler.myPeopleDetailsTable.selectedRowNumber;								
			if(currentRow >= 0) {
				this.handler.dataTable.getDataList()[currentRow] = this.cloneObj;				
			}			   
	   }else if(this.personHandlerIs == "myGroup"){
		    var o = findObjIndex(app.myPeople.dataTable.getDataList(), this.cloneObj);						
			if(o != -1) {
				app.myPeople.dataTable.getDataList()[o] = this.cloneObj;				
			}
	   }
   },
   
   doGroupSelection: function(ev) {
	  var gSelector = getGroupSelector(this);
      gSelector.setGroupDataList(app.workspace["myGroup"],
         this.obj["group"]);
   },

	
   saveSuccessful: function(response) {		  
		if(this.handler.myPeopleDetailsTable != null && this.personHandlerIs == "myPeople" && 
			!this.isCreateMode) {		
			var currentRow = this.handler.myPeopleDetailsTable.selectedRowNumber;			
			if(currentRow >= 0) {
				this.handler.dataTable.getDataList()[currentRow] = this.obj;				
			}			   
	   }else if(this.personHandlerIs == "myGroup"){
		    var o = findObjIndex(app.myPeople.dataTable.getDataList(), this.obj);			
			if(o != -1) {
				app.myPeople.dataTable.getDataList()[o] = this.obj;				
			}
	   }

		if (this.obj.UUID == null) {
			this.obj.UUID = response.responseText;
		}

		this.editor.clearChanges();		
		

		//if(app.myGroups.groupDetailsTitle!=null){
			app.myGroups.refresh();
		//}	
		if(this.isCallFromMyLovedOne) {
			this.isCallFromMyLovedOne = false;	
			if(app.myLovedOne.createNewObjectOfType != "") {
				app.myLovedOne.obj[app.myLovedOne.createNewObjectOfType][0] = this.obj;
				app.myLovedOne.createNewObjectOfType = "";
			}
			app.myLovedOne.showContactInformation(this.obj);
		}else{
			this.handler.refresh();
		}
   },
   
   saveFailed: function(dataRequest, msg) {
		showMessageDialog(msg + "<br/>We are currently unable to save this record. Please try again.", "Excuse us!", 400, 150,null, true);
   },
   
  saveTimedOut: function(dataRequest) {
		showMessageDialog(msg + "<br/>We are currently unable to save this record. Please try again.", "Excuse us!", 400, 150,null, true);
   },
   
   setGroupListSelected: function() {     
	  this.groupSelectorDialog.setDataList(this.selectedGroups);	 
   },
   
   deletePeopleConfirm: function() {
	   showConfirmDialog("Are you sure you want to delete this person from My People?", "Are You Sure?",300, 100, this.doDeletePerson.bind(this));
		return false;
   },
	   
   doDeletePerson: function(){
	   if(this.personHandlerIs == "myGroup"){
		    var o = findObjIndex(app.myPeople.dataTable.getDataList(), this.obj);			
			if(o != -1) {
				var obj =   this.handler.dataTable.deleteObjectByIndex(o);				
				app.peopleDeleted(obj, app.workspace["myGroup"]);  				
				app.myGroups.refresh();
				this.deletePerson(obj);
			}
	   }
	   else if(this.personHandlerIs == "myPeople"){
			var currentRow = this.handler.myPeopleDetailsTable.selectedRowNumber;
			if(currentRow >= 0) {
			var obj =   this.handler.dataTable.deleteObjectByIndex(currentRow);
			this.handler.myPeopleDetailsTable.setDataList(this.handler.dataTable.getDataList());			
			app.peopleDeleted(obj, app.workspace["myGroup"]);  
			currentRow = -1;
			this.deletePerson(obj);
		}
      }
      else {
         showMessageDialog("Please select a person's record to delete." , "Request", 300, 80,null, true);
      }
      return false;
   },
	   
   deletePerson: function(obj) {	
         hideDialogWin(); 
		var req = new Af.DataRequest(svcURL, this.requestDeletePersonCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
		req.addService("WorkspaceService", "deletePerson");
		req.addParameter("UUID", this.obj.UUID);
		ajaxEngine.processRequest(req);
		return false;
   },
   
   requestDeletePersonCompleted: function(response){
	  this.hide();
	  showMessageDialog("This person's record was successfully deleted." , "Deletion Successful", 300, 80,null, true);
   },
   
   requestFailedCommon: function() {
		showMessageDialog("<br/>We are currently unable to delete this record. Please try again.", "Excuse us!", 400, 150,null, true);
   },
   
   requestTimedoutCommon: function() {
		showMessageDialog("<br/>We are currently unable to delete this record. Please try again.", "Excuse us!", 400, 150,null, true);
   },
	
   doPrintDetails: function() {
		if(this.doSave()) {
			this.printDetails();
		}
		return false;
   },

	printDetails:function(){
			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", "personDetails");
			req.addParameter("xlstFile","personDetail.xsl");
			req.addParameter("id",this.obj.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", 400, 150,null, true);
   },
   
   requestTimedout: function() {
		showMessageDialog("<br/>Printing is currently unavailable. Please try again.", "Printing Unavailable", 400, 150,null, true);
   },

	isEmailIDExist: function(evt) { 
		var email = this.email.getValue();
		if(email == null || email == "") {
			return false;
		}
		email = trim(email);
		
		var pList = this.handler.dataTable.getDataList();
		var objIndex = findObjIndex(pList, this.obj);

		for(var idx = 0; idx < pList.length; idx++) {					
			if(this.obj["UUID"] == null) {
				if(email == pList[idx]["email"]) {
					showMessageDialog("Person with email ID "+email +" already exists. Please try again.", "Excuse us!", 330, 120,null, true);			
					//this.obj["email"] = "";
					return true;
				}
			} else if(email == pList[idx]["email"] && objIndex != idx) {
				showMessageDialog("Person with email ID "+ email+" already exists. Please try again.", "Excuse us!", 330, 120,null, true);			
				//this.obj["email"] = "";
				return true;
			}
		}
		return false;
	 },

	doValidateZipCode: function(evt) {
		return app.validator.doValidateZipCode(evt);
	}

});

