HJ.MyListEmail = Class.create();

HJ.MyListEmail.prototype = Object.extend(new Af.HtmlDialog(), {
      
	initialize: function(title, handler, content) {
		 this._initializeDialog(title, handler, content);
		 this.obj = null;
		// this.editor = new Af.ObjEditor();
		 this.requestType = "simpleList";
		 this.groupSelectedList = new Array();
		 this.peopleSelectedList = new Array();
		 this.messageList = null;
		 this.messageHelp = null;
		 this.defaultValue = "";
		 this.invalidEmails = "";
	},
      
      
   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.listDisplayDivArea =  ec.getFirstElementById("listDisplayDivArea");
	  
	 this.selectionTrigger = ec.getFirstElementById("selectionTrigger");
	 this.selectionTrigger.onclick = this.selectPeopleGroup.bind(this);

	 this.emailsElement = ec.getFirstElementById("emails");
	 //this.emailsElement.onchange = this.doShowEnteredEmails.bind(this);
	 this.emailsElement.onfocus = this.focusOnTextBox.bindAsEventListener(this);
	 this.emailsElement.onblur = this.focusLostTextBox.bindAsEventListener(this);
	 
	 // Use Prototype
	 Element.extend(this.emailsElement);
	 Event.observe(this.emailsElement, 'keypress', this.processKeyPress.bindAsEventListener(this));
	 
	 this.defaultValue = this.emailsElement.value;
	 
	 this.subject = ec.getFirstElementById("subject");
	 Element.extend(this.subject);
	 Event.observe(this.subject, 'keypress', this.processKeyPress.bindAsEventListener(this));

	 if(this.requestType == "simpleList") {
		this.messageList = ec.getFirstElementById("messageList");
	 }
	 else {
		this.messageHelp = ec.getFirstElementById("messageHelp");
	 }
	 
	 this.emailsDefaultValue = this.emailsElement.value;
	 
	// this.title1 = ec.getFirstElementById("listTitle");
	 this.title2 = ec.getFirstElementById("listTitle2");
	 this.listTitleDueDate = ec.getFirstElementById("listTitleDueDate");
	 
	 
	 this.indvslSelectionList = ec.getFirstElementById("indvslSelectionList");
	 this.groupSelectionList = ec.getFirstElementById("groupSelectionList");

	 this.indvslSelectionList.innerHTML = "";
	 this.groupSelectionList.innerHTML = "";

	 this.taskList = new Af.HtmlTable("taskList", "description,dueDate", ec);
	 this.taskList.listener = this;	
	 
	 this.myListLink = ec.getFirstElementById("myListLink");	 
	 
	 
	 this.sendBy = ec.getFirstElementById("sendBy");
 
	 if (this.obj != null) {
		 this.mySetObj();
	 }
   },

	processKeyPress: function(event) {
		Event.extend(event);
	   	if (event.keyCode == Event.KEY_RETURN) {
	   	  	Event.stop(event); // ignore pressing of Enter key
	    }
	},

   cellSelected: function(row, col) {
		  this.taskList.normalBackcolor = "#f6f6f6";
		  this.taskList.selectRow(row, "#c2c2c2");		
   },
      
   doSend: function(event) {
      var emails = "";
      this.invalidEmails = ""; // initialize invalid email list
  
      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)){
							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(emails == "") {
								emails += s;
							}else {
								if(emails.indexOf(s) == -1) {
									emails += "," + s;
								}
							}
						}
					}
			}
      var l = this.peopleSelectedList;
      for(var i=0; i<l.length; i++) {
           var a = l[i];
           debugA(a["email"]);
           var s = trim(a["email"]);
           if (s != "") {
             if (emails == "") {
                emails += s;
             } else {
                if(emails.indexOf(s) == -1) {
						emails += "," + s;
				 }
             }
           }
        }
        
		l = this.groupSelectedList;
        for(var i=0; i<l.length; i++){
          var a = l[i];
		  if(a["people"] != undefined || a["people"] != null)  {
			  for (var j=0; j<a["people"].length; j++ ){
					  var b = a["people"][j];
					  var s = trim(b["email"]);
					  if (s != "") {
						 if (emails == "") {
							emails += s;
						 } else {
							if(emails.indexOf(s) == -1) {
									emails += "," + s;
							 }
						 }
					  }
			   }
			}
        }
        
        if (this.invalidEmails != "") {
        	showMessageDialog("You must enter valid email addresses such as xxx@yyy.com", "Request", 400, 150);
        	return;
        }
        
        if (emails == "") {
           showMessageDialog("Please enter emails for, or click-select, the people or groups you would like to receive this list.", "Request", 400, 150);
           return;
        }
        
        
	  var m1 = "";
	  if(this.messageList != null) {
		  m1 = xmlEncode(this.messageList.value);
	  } else  if (this.messageHelp != null) {
		  m1 = xmlEncode(this.messageHelp.value);
	   }
	   
	  if (this.requestType == "askForHelp") {
	  	// track help request with google analytics
	  	// Use logical name instead of name of the destination page
	  	GATrackAction("/dashboard/request-signup");
	  }

	  var req = new Af.DataRequest(svcURL,this.requestSendMyListCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
         
      req.addService("WorkspaceService", "sendMyList");
      req.addParameter("UUID", this.obj.UUID);
      req.addParameter("requestType", this.requestType);   

	  var s = "<messages>";
	  s += "<message>" + m1 + "</message>";	
	  s +=  "<subject>" + xmlEncode(this.subject.value) + "</subject>";
	  s +=  "<emails>" + emails + "</emails>";
	  s += "</messages>";
		
	  req.xmlDoc = s;
	  ajaxEngine.processRequest(req);
	  this.hide();
	  this.clearData();
   },
   
   requestSendMyListCompleted: function(response)	{		
	     if(response.responseText == "<response><message>ListSent</message></response>") {
			if(this.invalidEmails!=""){
				showMessageDialog("Your list has been successfully sent.and here are invalid emails to which list cannot be sent: <BR/>"+this.invalidEmails, "Success!", 420, 100);
			}else {
				showMessageDialog("Your list has been successfully sent.", "Success!", 300, 100);
			} 
		 } else {
			 if(this.invalidEmails!=""){	
				showMessageDialog("Your request for help with items on this list has been sent and here are invalid emails to which list cannot be sent: <BR/>"+this.invalidEmails, "Informing You", 420, 100);
			}else{
				showMessageDialog("Your request for help with items on this list has been sent.", "Informing You", 300, 100);
			} 
		 }
		 this.clearData();
   },
	requestFailedCommon: function(dataRequest, msg) {
	    showMessageDialog("We are currently unable to send the list Please try again.", "Excuse us!", 300, 100);
   },
	requestTimedoutCommon: function () {
	    showMessageDialog("We are currently unable to send the list Please try again.", "Excuse us!", 300, 100);
   },
   
   doDontSend: function() {
		this.hide();
		this.clearData();
   },
   
   setObj: function(obj) {
       this.obj = obj;
       if (this.send) {
          this.mySetObj();
       }
	  if(this.indvslSelectionList != null && this.groupSelectionList != null) {
		 this.indvslSelectionList.innerHTML = "";
		 this.groupSelectionList.innerHTML = "";
	  }
	  if(this.messageList !=null){
	        if (this.obj.lastEmailNote !=null)
	        	this.messageList.value = this.obj.lastEmailNote;
		else
			this.messageList.value = "I hope you enjoy this list I am sending you.";
	  }
	  if(this.messageHelp !=null){
	        if (this.obj.lastEmailNote !=null)
	        	this.messageHelp.value = this.obj.lastEmailNote;
	        else
			this.messageHelp.value = "I'm using Jooners to help organize my busy life, and I'd love to have your help with:";
	  }	
   },
   
   mySetObj: function() {	   
	  // this.title1.innerHTML = this.obj.name;
	   this.title2.innerHTML = this.obj.name;
	   if (this.emailsElement != null)
		   if (this.obj.lastEmailString != null) this.emailsElement.value = this.obj.lastEmailString;
	   if (this.subject != null)
	   	   if (this.obj.lastEmailSubject != null) this.subject.value = this.obj.lastEmailSubject;
	   if (this.messageList != null)
		   if (this.obj.lastEmailNote != null) this.messageList.value = this.obj.lastEmailNote;
	   if (this.messageHelp != null)
		   if (this.obj.lastEmailNote != null) this.messageHelp.value = this.obj.lastEmailNote;
	   //this.emailsElement.value = "Enter email addresses separated by commas";
	   if(this.listTitleDueDate != null) {
		   this.listTitleDueDate.innerHTML = "";
		   for(Id = 0 ; Id < this.obj["item"].length ; Id++) {		  
			   if(this.obj["item"][Id].dueDate != null && "" != trim(this.obj["item"][Id].dueDate)) {
					this.listTitleDueDate.innerHTML = "";				
					this.listTitleDueDate.innerHTML = "Due";
			   }
		   }
	   }
	 
	   if (this.myListLink != null) {
	      this.myListLink.innerHTML = this.obj.name;
	   }
	   this.sendBy.innerHTML = login.userFullName;
    
	   this.selectedPeople = getPeopleNames(this.peopleSelectedList);
	   this.selectedGroup = getGroupsPeople(this.groupSelectedList);
		
	   this.doShowEnteredEmails();
	   
       var l = this.obj["item"];
	  
	   var r = this.taskList.templateRow;	
	   var childNodes = r.getElementsByTagName("TD");  
	   childNodes[0].style.width = "270px";			   
	   
	   
	   this.taskList.setDataList(l);
	   if(l != null && l.length > 15){		 
		   this.listDisplayDivArea.style.height = "250px";
		   this.listDisplayDivArea.style.overflow = "auto";		   
	   }else{
		    this.listDisplayDivArea.style.height = "";
	   }
       
      // this.editor.setValueFromObj(this.obj);	  

	 //  this.emailsElement.focus();
	   
   },
   
   selectPeopleGroup: function() {
	 //this.groupSelectedList = new Array();
	 //this.peopleSelectedList = new Array();

	 var pgSelector = getPoepleGroupSelector(this);
     pgSelector.setDataList(app.workspace["myGroup"], 
      app.workspace["myPeople"], 
      this.groupSelectedList, 
      this.peopleSelectedList);
     return false;
    },    


     selectionDone:function(child){
        this.mySetObj(); 		
     },

		doShowEnteredEmails:function(){
			this.indvslSelectionList.innerHTML = "";
			this.groupSelectionList.innerHTML = "";
			
			this.indvslSelectionList.innerHTML+="<br/>"+this.selectedPeople;
			this.groupSelectionList.innerHTML +="<br/>"+this.selectedGroup;
			return;
		},

		clearData:function(){
			this.emailsElement.value = "";			
			this.emailsElement.value = "Enter email addresses separated by commas";
			this.subject.value = "";
			if(this.requestType == "simpleList") {
				this.subject.value = "A List for You";
			}
			else {
				this.subject.value = "Would love your help !";
			 }
			
			this.indvslSelectionList.innerHTML = "";
			this.groupSelectionList.innerHTML = "";
			this.groupSelectedList = new Array();
			this.peopleSelectedList = new Array();
			if(this.listTitleDueDate != null) {
				this.listTitleDueDate.innerHTML = "";
			}
		},

	   focusOnTextBox: function(evt) {
		 // this.emailsElement.value = "";
		  var s = this.emailsElement.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }		
		  if (s == trim(this.defaultValue) || 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.defaultValue) || s == "") {
			 this.emailsElement.value = this.defaultValue;
			 consumeEvent(evt);
		  }	         
	 }

});

