HJ.TellAFriendPage = Class.create();

HJ.TellAFriendPage.prototype = {

	initialize: function() {
		this.url = basePageURL + "tellafriend_general.html";
		this.sourceContainerId = "tellafriend_form_wrapper";
		this.targetContainerId = "tellafriend_form_wrapper";
		this.data = null;
		this.tl = null;
		this.emailValidator = new HJ.EmailValidator();
		this.thankYouNote = new HJ.ThankYouNote();
		this.showThankYou = false;
	},
	
	cleanup:function() {
	},
	
	init: function(targetContainerId) {
		if (targetContainerId != null) {
			this.targetContainerId = targetContainerId;
			this.sourceContainerId = "tellAFriendFormContent";
		}
		if(this.tl == null) {
			this.tl = new Af.TemplateLoader(this.url, this.targetContainerId, this.sourceContainerId);
			this.tl.listener = this;
			this.tl.loadTemplate();
		} else {
			this.tl.reAttachElement();
		}
		this.isCommunityResource = false;
		this.emails = "";		
		ajaxEngine.commFailureHandler = commFailure;
		ajaxEngine.timoutHandler = commTimedout;
		
	},
	
   templateLoaded: function() {
  
  	 if (this.showThankYou) {
  	 	return;
  	 }
     var ec = new Af.ElementCollection(this.tl.element);

	if (login != null) {
		var logo = document.getElementById("tellAFriendHeaderImage");
		if (logo) {
			logo.style.display = 'none';
		}
	}
	 this.subjectElem = ec.getFirstElementById("subject");
     this.sendButtonElem = ec.getFirstElementById("send");
     this.armedButton = this.sendButtonElem;
	 this.dontSendButtonElem =  ec.getFirstElementById("dontSend");
	 this.sendButtonElem.onclick = this.doSendEmail.bind(this);
	 this.dontSendButtonElem.onclick = this.doDontSend.bind(this);
	 this.toEmailListErrorMsgElem = ec.getFirstElementById("toEmailListErrorMsg");
	 this.subjectErrorMsgElem = ec.getFirstElementById("subjectErrorMsg");

	 this.toEmailListElem = ec.getFirstElementById("toEmailList");
	 this.personalNote = ec.getFirstElementById("personalNote");
	 
	 // subject of the email cannot be modified by user
	 this.subjectDefaultValue = "Be a \"Jooner\" like me!";

	 this.toEmailListElem.onfocus = this.focusOnToEmailListElem.bindAsEventListener(this);
	 this.toEmailListElem.onblur = this.focusLostToEmailListElem.bindAsEventListener(this);
	 this.emailsDefaultValue = this.toEmailListElem.value;
	 	 	  
	 this.mySetObj();
   },
   	
   
   requestTellAFriendCompleted: function(response)	{
	 if(this.invalidEmails!=""){	
		alert("We are unable to send email to the following email addresses:<BR/> "+this.invalidEmails);
	 }
	 alert("Email sent to your friends ", "Email Sent", 300, 100);

	// track help request with google analytics
  	// Use logical name instead of name of the destination page
  	GATrackAction(GA_ACTION_SUCCESSFUL_TELL_A_FRIEND);
	 
	 if (app != null && app.db != null) {
		app.db.displayCurrentTab();
	 }
	 else {
	 	window.location = basePageURL;
	 }
   },
	   
	requestFailedCommon: function(dataRequest,msg) {
		 alert("We are currently unable to process this tell a friend request. <br/> Please try again.");
	},
	
	requestTimedoutCommon: function(dataRequest) {
		 alert("We are currently unable to process this tell a friend request. <br/> Please try again.");
	},
   
   doDontSend: function() {
	 if (app != null) {
		app.db.displayCurrentTab();
	 }
	 else {
	 	window.location = basePageURL;
	 }
	 return false;
   },
   
   mySetObj: function() {
	    if(this.toEmailListElem!=null){
			this.toEmailListElem.value = "Enter email addresses separated by commas";
			this.emailsDefaultValue = this.toEmailListElem.value;  
		}		
   },   

	focusOnToEmailListElem: function(evt) {	 			 
		  var s = this.toEmailListElem.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }		
		  if (s == trim(this.emailsDefaultValue) || s == "") {
			 this.toEmailListElem.value = "";
			 consumeEvent(evt);
		  }

		  this.toEmailListElem.focus();
	   },
   
	 validateToEmailListElem: function() {
      this.emails = "";
	  this.invalidEmails = "";
      
      if ((this.toEmailListElem.value != this.emailsDefaultValue)) {
            var s = trim(this.toEmailListElem.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(this.emailValidator.validateEmail(s)==false){
				if (s != "" ) {
					if(this.invalidEmails == "") {
							this.invalidEmails += s;
						}else {
							if(this.invalidEmails.indexOf(s) == -1) {
								this.invalidEmails += "," + s;
							}
					}
				}
			   continue;
			  }
			  
			  s = this.emailValidator.extractEmailAddress(s);
               if (s != "") {
                 if (this.emails == "") {
					this.emails += s;
				 } else {
					 if(this.emails.indexOf(s) < 0) {
						this.emails += "," + s;
					 }
				 }
               }
            }
       }
	          
      if (this.emails == "" || this.invalidEmails != "") {
      	this.toEmailListErrorMsgElem.style.display = "block";
        return false;
      }
	  this.toEmailListErrorMsgElem.style.display = "none";
      return true;
	 },

	focusLostToEmailListElem: function(evt) {
		  var s = this.toEmailListElem.value;
		  if (s == null) {
			s = "";
		  } else {
			s = trim(s);
		  }
		  if (s == trim(this.emailsDefaultValue) || s == "") {
			this.toEmailListElem.value = this.emailsDefaultValue;
		  }
		  if (!this.validateToEmailListElem()) {
		  	this.toEmailListElem.focus();
		  	return false;
		  }
		  this.toEmailListErrorMsgElem.style.display = "none";
		  return true;
	 },
	 
   doSendEmail: function(evt) {
	   	// invoke focusLost<element name>Elem method to validate all elements
	   	var validateFields = this.validateToEmailListElem(evt);
		if (!validateFields)
		{
			alert("Please correct the errors shown");
			consumeEvent(evt);
			return false;
		}
	    var req = new Af.DataRequest(svcURL,this.requestTellAFriendCompleted.bind(this), this.requestFailedCommon.bind(this), null, this.requestTimedoutCommon.bind(this));
		req.addService("CommunityResourceService", "tellAFriend");		   
		req.addParameter("emails", xmlEncode(this.emails));
		var s = "<messages>";
		s +=  "<subject>" + xmlEncode(this.subjectDefaultValue) + "</subject>";
		s += "<senderName>" + xmlEncode(login.userData.fName + ' ' + login.userData.lName)+ "</senderName>";
		s += "<senderEmailAddress>" + xmlEncode(login.userData.email)+ "</senderEmailAddress>";
		s += "<personalNote>" + xmlEncode(this.personalNote.value)+ "</personalNote>";
		s += "</messages>";
		req.xmlDoc = s;
		ajaxEngine.processRequest(req);
		return false;
   }
};


