HJ.SendScribbleEmail = Class.create();

HJ.SendScribbleEmail.prototype = Object.extend(new Af.HtmlDialog(), {
      
      initialize: function(title, handler, content) {
         this._initializeDialog(title, handler, content);
         
         this.selectedPeopleList = new Array();
         this.selectedGroupList = new Array();
         
         this.receiverText = "";
        
      },
      
      templateLoaded: function() {
         var ec = new Af.ElementCollection(this.element);
         this.showPeopleGroupList = ec.getFirstElementById("showPeopleGroupList");
         this.showPeopleGroupList.onclick = this.doPeopleSelection.bind(this);
         this.receiver = ec.getFirstElementById("receivers");
         this.receiver.onfocus = this.focusOnTextBox.bindAsEventListener(this);
         this.receiver.onblur = this.focusLostTextBox.bindAsEventListener(this);
         this.receiverText = this.receiver.value;
         this.btnSendScribble = ec.getFirstElementById("btnSendEmail");
         this.armedButton = this.btnSendScribble;
         this.btnSendScribble.onclick = this.doSendEmail.bind(this);
         this.dontSend = ec.getFirstElementById("dontSend");
         this.dontSend.onclick = this.doDontSend.bind(this);
         this.scribbleTextElement = ec.getFirstElementById("scribbleText");
         this.groupTable = new Af.HtmlTable("sendScribbleGroupTable", "isCellSelected,isSelected,name");
         this.peopleTable = new Af.HtmlTable("sendScribblePeopleTable", "isCellSelected,isSelected,name");
         this.initState();
      },
      
      initState: function() {
      
         this.selectedPeopleList = new Array();
         this.selectedGroupList = new Array();
         
         this.emails = "";
         this.cellPhones = "";
         if (this.receiver != null) {
             this.showPeopleList();
             this.showGroupList();
			 this.receiver.value = this.receiverText;
			 if(this.handler.currentRow !=-1 ){
			    this.scribbleText = this.handler.dataTable.getDataList()[this.handler.currentRow].text;
				this.scribbleTextElement.innerHTML	= this.scribbleText;
			 }
         }
      },
      
      doPeopleSelection: function() {
         var pgSelector = getPeopleGroupSelector2(this);
         pgSelector.setDataList(app.workspace["myGroup"], app.workspace["myPeople"],
			this.selectedGroupList, this.selectedPeopleList);
         
         
         return false;
      },
      
      doSendEmail: function() {
        this.invalidEmails = "";
		this.invalidPhones = "";
         if (this.receiver.value != this.receiverText) {
            
            var s = trim(this.receiver.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]);
			   var invalidEmail = false;
			   if(!app.emailValidator.validateEmail(s) && s.indexOf("@") != -1){
			   		invalidEmail = true;
					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(!app.validator.validatePhone(s) && s.indexOf("@") == -1){
					if (s != "" ) {
						if(this.invalidPhones == "") {
								this.invalidPhones += s;
							}else {
								if(this.invalidPhones.indexOf(s) == -1) {
									this.invalidPhones += "," + s;
								}
							}
					}
					continue;
				}			
			   
               if (s != "") {
                  if (s.indexOf("@") > -1) {
                     if (this.emails == "") {
						this.emails += s;
					 } else {							
							if(this.emails.indexOf(s) < 0){
								this.emails += "," + s;
							}
					 }
                  } else {
                     if (this.cellPhones == "") {
						this.cellPhones += s;
					 } else {
						this.cellPhones += "," + s;
					 }
                  }
               }
            }
         }	     
		 debugA("Selected emails: " + this.emails);
         debugA("Selected cell phones: " + this.cellPhones);
         
         if ((this.emails == "" && this.cellPhones == "") && (this.invalidPhones=="" || this.invalidEmails=="")) {
			showMessageDialog("Please click the emails and/or cell phone numbers of"+
				" the people you would like to receive this Scribble.", "Request", 300, 100);
            return;
         }
         this.hide();
         var req = new Af.DataRequest(svcURL,this.requestSendScribbleCompleted.bind(this),this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
         
         req.addService("EmailSvc", "emailSMSScribble");
		 
		  var s = "<messages>";
		   s += "<sender>" +  login.userFullName + "</sender>";
		  s += "<content>" +  xmlEncode(this.scribbleText) + "</content>";
		  s += "<subject>" +  xmlEncode(this.scribbleText) + "</subject>";
		  s += "<emails>" +  this.emails + "</emails>";
		  s += "<cellPhones>" +  this.cellPhones + "</cellPhones>";
		  s += "</messages>";
		  req.xmlDoc = s;
         
         ajaxEngine.processRequest(req);
      },
      
      requestSendScribbleCompleted: function(response)	{
		if(this.invalidEmails!=""){
			showMessageDialog("Your Scribble has been successfully sent to valid emails and these are the emails found invalid:<br/>"+this.invalidEmails, "Success!", 300, 100);
		 }else{
			showMessageDialog("Your Scribble has been successfully sent." , "Success!", 300, 100);        
		 }
      },
      
      requestFailedCommon: function(dataRequest, msg) {
         showMessageDialog("We are currently unable to send this Scribble. <br/>Please try again.", "Excuse us!", 300, 100);
      },
      
      requestTimedoutCommon: function() {
         showMessageDialog( "We are currently unable to send this Scribble. <br/>Please try again.", "Excuse us!", 300, 100);
      },
      
      doDontSend:function(){
         this.hide();
      },
      
      showPeopleList: function() {
        if (this.selectedPeopleList.length > 0) {
           this.peopleTable.tableElement.style.display = "";
        } else {
           this.peopleTable.tableElement.style.display = "none";
        }
        this.peopleTable.setDataList(this.selectedPeopleList);
      },
      
      showGroupList: function() {
        if (this.selectedGroupList.length > 0) {
           this.groupTable.tableElement.style.display = "";
        } else {
           this.groupTable.tableElement.style.display = "none";
        }
        this.groupTable.setDataList(this.selectedGroupList);
      },
      
      selectionDone:function(child){
        this.emails = "";
        this.cellPhones = "";
        
        this.showPeopleList();
        this.showGroupList();
        
        for(var index=0; index<this.selectedPeopleList.length; index++) {
           var a = this.selectedPeopleList[index];
           if(a.isSelected){
              var s = trim(a["email"]);
              if (s != "") {
                 if (this.emails == "") {
                    this.emails += s;
                 } else {
						if(this.emails.indexOf(s)<0){	
							this.emails += "," + s;
						}
                 }
              }
           }
           
           if(a.isCellSelected){
              var s = trim(this.getCellPhone(a));
              if (s != "") {
                 if (this.cellPhones == "") {
                    this.cellPhones += s;
                 } else {
                    this.cellPhones += "," + s;
                 }
              }
           }
        }
 
        for(var index=0;index<this.selectedGroupList.length;index++){
           var a = this.selectedGroupList[index];
           if(a.isSelected){
			   if(this.selectedGroupList[index]["people"] != null){
				   for (var peopleId=0; peopleId<this.selectedGroupList[index]["people"].length; peopleId++ ){
					  var b = this.selectedGroupList[index]["people"][peopleId];
					  var s = trim(b["email"]);
					  if (s != "") {
						 if (this.emails == "") {
							this.emails += s;
						 } else {
								if(this.emails.indexOf(s) < 0){
									this.emails += "," + s;
								}	
						}
					  }
				   }  
			   }
           }
           
           if(a.isCellSelected){
			   if(this.selectedGroupList[index]["people"]){
				   for (var peopleId=0; peopleId<this.selectedGroupList[index]["people"].length; peopleId++ ){
					  var b = this.selectedGroupList[index]["people"][peopleId];
					  var s = trim(this.getCellPhone(b));
					  if (s != "") {
						 if (this.cellPhones == "") {
							this.cellPhones += s;
						 } else {
							this.cellPhones += "," + s;
						 }
					  }
				   }  
			   }
           }
        }
        debugA("Selected emails: " + this.emails);
        debugA("Selected cell phones: " + this.cellPhones);
         
      },
      
      getCellPhone: function(a) {
         if (a["phoneType1"] == "Mobile") {
            var s = trim(a["phone1"]);
            if (s != "") {
               return s;
            }
         }
         if (a["phoneType2"] == "Mobile") {
            var s = trim(a["phone2"]);
            if (s != "") {
               return s;
            }
         }
         if (a["phoneType3"] == "Mobile") {
            var s = trim(a["phone3"]);
            if (s != "") {
               return s;
            }
         }
         
         return "";
      },


	focusOnTextBox: function(evt) {
		var s = trim(this.receiver.value);
		if (s == this.receiverText) {
			this.receiver.value = "";
		}
    },
	focusLostTextBox: function(evt) {
      var s = this.receiver.value;
      if (s == null) {
        s = "";
      } else {
        s = trim(s);
      }
      if (s == this.receiverText || s == "") {
         this.receiver.value = this.receiverText;
         consumeEvent(evt);
      }
   }
});

