HJ.ShareComResourcesToFriend = Class.create();

HJ.ShareComResourcesToFriend.prototype = Object.extend(new Af.HtmlDialog(), {
      
	initialize: function(title, handler, content) {
		 this._initializeDialog(title, handler, content);
		 this.obj = null;
		 this.handler = handler;	
		 this.isCommunityResource = false;
		 this.emails = "";		
	},
      
      
   templateLoaded: function() {
  
     var ec = new Af.ElementCollection(this.element);

     this.send = ec.getFirstElementById("send");
     this.armedButton = this.send;
	 this.dontSend =  ec.getFirstElementById("dontSend");
	 this.send.onclick = this.doSend.bind(this);
	 this.dontSend.onclick = this.doDontSend.bind(this);
	 this.resourceInfo =  ec.getFirstElementById("resourceInfo");
	 this.resourceInfoDiscription =  ec.getFirstElementById("resourceInfoDiscription");
	 this.businessName = ec.getFirstElementById("businessName");  
	 this.selectionTrigger = ec.getFirstElementById("selectionTrigger");
	 this.selectionTrigger.onclick = this.selectPeopleGroup.bind(this);

	 this.emailsElement = ec.getFirstElementById("emails");
	 this.message = ec.getFirstElementById("message");	
	 this.subjectElement = ec.getFirstElementById("subject");
	 this.subjectDefaultValue = this.subjectElement.value;
	 

	 this.emailsElement.onfocus = this.focusOnTextBox.bindAsEventListener(this);
	 this.emailsElement.onblur = this.focusLostTextBox.bindAsEventListener(this);
	 
	 this.emailsDefaultValue = this.emailsElement.value;   	 	 
	 
	// this.selectionList = ec.getFirstElementById("selectionList");	
	 this.indvslSelectionList = ec.getFirstElementById("indvslSelectionList");
	 this.groupSelectionList = ec.getFirstElementById("groupSelectionList");

	 this.indvslSelectionList.innerHTML = "";
	 this.groupSelectionList.innerHTML = "";

	 
	 this.sendBy = ec.getFirstElementById("sendBy");
 
	 if (this.obj != null) {
		 this.mySetObj();
	 }
   },
   
   
   doSend: function() {
      this.emails = "";
	  this.invalidEmails = "";
      
      if ((this.emailsElement.value != this.emailsDefaultValue)) {
            var s = trim(this.emailsElement.value);				              
            var sl = s.split(",");								              
		    if (sl.length == 1) {
		    	sl = sl[0].split(';');
		    }
		    for (var i=0; i<sl.length; i++) {
               s = trim(sl[i]);			  
			  if(app.emailValidator.validateEmail(s)==false){
				if (s != "" ) {
					if(this.invalidEmails == "") {
							this.invalidEmails += s;
						}else {
							if(this.invalidEmails.indexOf(s) == -1) {
								this.invalidEmails += "," + s;
							}
					}
				}
			   continue;
			  }
			  s = app.emailValidator.extractEmailAddress(s);
               if (s != "") {
                 if (this.emails == "") {
					this.emails += s;
				 } else {
					 if(this.emails.indexOf(s) < 0) {
						this.emails += "," + s;
					 }
				 }
               }
            }
       }
	  
      var l = this.obj["people"];
      for(var i=0; i<l.length; i++) {
           var a = l[i];
           debugA(a["email"]);
           var s = trim(a["email"]);
           if (s != "") {
             if (this.emails == "") {
                this.emails += s;
             } else {
				 if(this.emails.indexOf(s) < 0) {
					this.emails += "," + s;
				 }
             }
           }
        }		
        
		l = this.obj["group"];
        for(var i=0; i<l.length; i++){
          var a = l[i];
		  if(a["people"] != null && a["people"] != undefined) {
			  for (var j=0; j<a["people"].length; j++ ){
					  var b = a["people"][j];
					  var s = trim(b["email"]);
					  if (s != "") {
						 if (this.emails == "") {
							this.emails += s;
						 } else {
							 if(this.emails.indexOf(s) < 0) {
								this.emails += "," + s;
							 }
						 }
					  }
			   }
		  }
        }	  		
        
        if (this.emails == "") {
           showMessageDialog("Please select the people or group or specify valid email addresses", "Request", 300, 100);
           return;
        }
	  this.m1 = this.message.value;	
	  this.m2 = this.resourceInfoDiscription.innerHTML;	 
	  this.hide();
	  if(this.isCommunityResource) {
		   this.doSendEmail();
	  } 
	  else {
		  this.handler.sendEmailsToFriends = true;
		  this.handler.doSave();
	  }
	  return;

   },
	
   doSendEmail: function() {
	   
	    var req = new Af.DataRequest(svcURL,this.requestSendMyListCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
		  req.addService("CommunityResourceService", "shareResourceToFriends");		   
		  req.addParameter("resourceUUID", this.handler.resourceUUID);
		  req.addParameter("emails", xmlEncode(this.emails));
		  var s = "<messages>";
		  s += "<editableMessage>" + xmlEncode(this.m1) + "</editableMessage>";
		  s += "<staticMessage>" + xmlEncode(this.m2) + "</staticMessage>";
		  s +=  "<subject>" + xmlEncode(this.subjectElement.value) + "</subject>";
		  s += "</messages>";
		  if(this.isCommunityResource) {
			  this.isCommunityResource = false;
			  req.addParameter("isCommResource", "true");
		  }
		  req.xmlDoc = s;
		  ajaxEngine.processRequest(req);
		  this.clearData();
   },
   
   requestSendMyListCompleted: function(response)	{
	 // showMessageDialog("Email sent to your friends ", "Email Sent", 300, 100);
	// this.emailsElement.value = "Enter email addresses separated by commas";
	 if(this.invalidEmails!=""){	
		showMessageDialog("These are the emails to which we are unable to share this resource:<BR/> "+this.invalidEmails, "Excuse Us!", 450, 100);
	 }
	 app.thankYouNote.doOpenThankYouDialog(response.responseText);
   },
	   
	requestFailedCommon: function(dataRequest,msg) {
		 showMessageDialog("We are currently unable to process this email request. <br/> Please try again.", "Excuse Us!", 300, 100);
	},
	
	requestTimedoutCommon: function(dataRequest) {
		 showMessageDialog("We are currently unable to process this email request. <br/> Please try again.", "Excuse Us!", 300, 100);
	},
   
   doDontSend: function() {
	   this.handler.sendEmailsToFriends = false;
	 //  this.emailsElement.value = "Enter email addresses separated by commas";
      this.hide();
   },
   
   setObj: function(obj) {
       this.obj = obj;
       if (this.send) {
          this.mySetObj();
       }	 
	   if (this.obj["people"] == null) {
            createOneToManyAssoc(this.obj, "people", "Person");
       }
	   if (this.obj["group"] == null) {
            createOneToManyAssoc(this.obj, "group", "Group");
       }	   
   },
   
   mySetObj: function() {	
	    if(this.emailsElement!=null){
			this.emailsElement.value = "Enter email addresses separated by commas";
			this.emailsDefaultValue = this.emailsElement.value;  
		}		
	   if(this.resourceInfo != null) {
		   this.resourceInfo.innerHTML = this.handler.resourceInfo;
	   }
	   if(this.businessName != null) {
		   this.businessName.innerHTML = this.handler.businessName;		   
	   }	  
	   this.sendBy.innerHTML = login.userFullName;
	   /*
       var s = "";	   
       var l = this.obj["group"]; 
       if (l != null) {
		   for (var i=0; i<l.length; i++) {
			  if (s == "") {
				s = l[i].name;
			  } else {
				s += ", " + l[i].name;
			  }
		   }
	   } else {
	       this.obj["group"] = new Array();
	   }
       l = this.obj["people"]; 
       if (l != null) {
		   for (var i=0; i<l.length; i++) {
			  if (s == "") {
				s = l[i]["name"];
			  } else {
				s += ", " + l[i]["name"];
			  }
		   }
       } else {
	       this.obj["people"] = new Array();
	   }
	  
	   */

	   this.indvslSelectionList.innerHTML = getPeopleNames(this.obj["people"]);
	   this.groupSelectionList.innerHTML = getGroupsPeople(this.obj["group"]);
   },
   
   selectPeopleGroup: function() {	
	 var pgSelector = getPoepleGroupSelector(this);
     pgSelector.setDataList(app.workspace["myGroup"],app.workspace["myPeople"],this.obj["group"],this.obj["people"]);
     return false;
    },	    
   
     selectionDone:function(child){		
        this.mySetObj(); 
     },
     
     hideSelectBoxes: function() {
          if (is_ie && !is_ie7 && this.handler != null && this.handler.state != null) {
              this.handler.state.element.style.visibility = "hidden";
		  }
	  },
	  
	  showSelectBoxes: function() {
	      if (is_ie && !is_ie7 && this.handler != null && this.handler.state != null) {
              this.handler.state.element.style.visibility = "visible";
		  }
	  },

	 focusOnTextBox: function(evt) {		 
		  var s = this.emailsElement.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }		
		  if (s == trim(this.emailsDefaultValue) || s == "") {
			 this.emailsElement.value = "";
			 consumeEvent(evt);
		  }

		  this.emailsElement.focus();
	   },
   
	focusLostTextBox: function(evt) {    		
		  var s = this.emailsElement.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }
		  if (s == trim(this.emailsDefaultValue) || s == "") {
			 this.emailsElement.value = this.emailsDefaultValue;
			 consumeEvent(evt);
		  }	         
	 },
	 clearData:function(){
		if(this.subjectElement!=null){
			this.subjectElement.value = "";
			this.subjectElement.value = "Have I got something for you !";			
		 }
	 }
	 

     
});

