﻿

function getRecipientEmail() {
	return document.getElementById('recipientemail').value;  
}

function getInviteSenderID() {
	var id = '';
	var sender = document.getElementById('hInviteSender');
	if (sender) {
		id = sender.value;
	}
	return id;
}

function validateRecipientEmail() {
	
	var strEmail = getRecipientEmail();
	var confirmspan = document.getElementById('spnInviteFriendFeedback');
	confirmspan.innerHTML = '';

	if ((strEmail==null)||(strEmail=='')){
		confirmspan.innerHTML = 'Please enter an email address.';
		return false;
	}
	if (checkEmail(strEmail)==false){
		return false;
	}
	//Otherwise, the email address was valid...invoke handler call.
	InvokeAshxInviteExternalFriend();
	//return true;
}

//Tests the email address. Regex is also used elsewhere in the site.
function isValidEmailAddressExtFriend(value) {
	if (value.length == 0) { return true; }
	//4/22/09: Updated to include all top-level domains, such as
	//.travel, .museum, .xn--hgbk6aj7f53bba, .xn--11b5bs3a9aj6gs, .xn--hlcj6aya9esc7a
	//NEW:
	re = /^[a-zA-Z0-9\-\._]+\@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2,18})$/; 
	//OLD:
	//re = /^[a-zA-Z0-9\-\._]+\@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9]{2,4})$/;
	return re.test(value);
}

function checkEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	var strErrorInvalidEmail = 'Did you enter a valid e-mail address? Please check your friend’s e-mail address and enter it again.';
	
	var confirmspan = document.getElementById('spnInviteFriendFeedback');
	confirmspan.innerHTML = '';
	
	//Invite external friend email validation.
	//Use the regex that the rest of the site uses.
	var bIsValidEmail = isValidEmailAddressExtFriend(str);
	if (bIsValidEmail) { return true; } 
	else { confirmspan.innerHTML = strErrorInvalidEmail; return false; }
	
//	if (str.indexOf(at)==-1){
//	   confirmspan.innerHTML = strErrorInvalidEmail;
//	   return false;
//	}
//	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
//	   confirmspan.innerHTML = strErrorInvalidEmail;
//	   return false;
//	}
//	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
//	   confirmspan.innerHTML = strErrorInvalidEmail;
//	   return false;
//	}
//	if (str.indexOf(at,(lat+1))!=-1){
//		alert(strErrorInvalidEmail);
//		return false;
//	}
//	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
//		confirmspan.innerHTML = strErrorInvalidEmail;
//		return false;
//	}
//	if (str.indexOf(dot,(lat+2))==-1){
//		confirmspan.innerHTML = strErrorInvalidEmail;
//		return false;
//	}
//	if (str.indexOf(" ")!=-1){
//		confirmspan.innerHTML = strErrorInvalidEmail;
//		return false;
//	}
//	return true;				
}


function resetInviteExternalFriend() {
	document.getElementById('recipientemail').value = 'Enter text';
	document.getElementById('recipientmessage').selectedIndex = 0;
	document.getElementById('spnInviteFriendFeedback').innerHTML = '';
	//$("#inviteFriendContainer").hide();
}

////////////////////////////////////////////////////////
/* Invite External Friend AJAX functions */
////////////////////////////////////////////////////////

var fInviteExternalFriendCallback = function() {
	var intMaxResponseLength = 300;			
	var bCatchConnectionErrors = false;					
	var bExistingUser = false;
	//Custom error message in the event of failure.
	var errormsgHTML = 'InviteExternalFriend: An error occurred while processing the request.';
	var confirmspan = document.getElementById('spnInviteFriendFeedback');
	var strRedirectLink = '<a class="resettext" onclick="resetInviteExternalFriend();">Invite another friend</a>';
	//var msgHTML = 'Success! Your message has been sent. ' + strRedirectLink;
	
	if (xmlhttp.readyState==4) {	//If OK...
		try {
			////////////////////////////////////////////////////////
			var strResponse = xmlhttp.responseText; //Do something with the response.
			////////////////////////////////////////////////////////
			
			if (strResponse.length > intMaxResponseLength && bCatchConnectionErrors) {
				//If the length of the response exceeds the max, it's an error. Probably a 404 error.
				//Don't populate the callback div with this error. Instead, show a message.
				confirmspan.innerHTML = errormsgHTML;
			}
			else {
				//The response length is good. Proceed with the callback execution.
				//confirmspan.innerHTML = msgHTML;
				//hide panel 1 and show confirm panel
				
				//See if the email recipient already existed...
				var intExists = Number(strResponse.split('|')[1]);
				if (intExists == 1) { 
					//alert('User already existed!'); 
					//Need to populate message...
					confirmspan.innerHTML = 'You have already invited this recipient!';
				}
				else { //User did not exist previously.
				
					//Show success div and bottom success div.
					showInviteFriendSuccess();
					
					//Set success flag, so we can reset the div.
					setMessageSentFlag('1');
				}
			}
		}
		catch (e) {
		
			//Put any error handling here.
			var strErrorExplanation = 'There was a problem handling the response. \n'
			var strStatusText = 'Status Text: ' + xmlhttp.statusText + '\n'
			var strError = 'Error: ' + e.toString();
			//alert(strErrorExplanation + strStatusText + strError);
			//Display friendly failure message.
			confirmspan.innerHTML = errormsgHTML;
		}
	}
}

function InvokeAshxInviteExternalFriend() {

	//Retrieve params
	var strSenderID = getInviteSenderID();
	var strSenderEmail = document.getElementById('hidIEFSenderEmail').value;
	var strSenderDN = document.getElementById('hidIEFSenderDN').value;
	var strSenderFN = document.getElementById('hidIEFSenderFN').value;
	var strRecipientEmail = document.getElementById('recipientemail').value;  
	var intOptionalMessageID = document.getElementById('recipientmessage').selectedIndex; 

	var confirmspan = document.getElementById('spnInviteFriendFeedback');

	//Abort send if user is not logged in.
	if (strSenderEmail == 'ANONYMOUS' || strSenderDN == 'ANONYMOUS') {
		confirmspan.innerHTML = 'You must be logged in to use this resource.';
		return;
	}

	//If we do not have the sender's and recipient's email address, exit.
	if ((!strSenderEmail.length > 0) || (!strRecipientEmail.length > 0)) { return; }

	var strHttpCommandType = 'GET';
	var strHandlerPath = '/mycorner/handlers/EmailHandler.ashx';
	strHandlerPath += '?semail=' + strSenderEmail;
	strHandlerPath += '&sfn=' + strSenderFN;
	strHandlerPath += '&suid=' + strSenderID;
	strHandlerPath += '&remail=' + strRecipientEmail;
	strHandlerPath += '&optmsgid=' + intOptionalMessageID;
	strHandlerPath += '&m=inviteexternalfriend';
	
	//If asynchronous, set to true. Prevents page from hanging during ashx error.
	var bAsynch = true;	

	//////////////////////////////////////////////////////////////
	//Initialize the XmlHttpRequest, Set the callback function, make the request.
	//////////////////////////////////////////////////////////////
	InitXmlHttp();
	xmlhttp.onreadystatechange = fInviteExternalFriendCallback;
	xmlhttp.open(strHttpCommandType, strHandlerPath, bAsynch);
	xmlhttp.send(null);	//If command is GET, set to 'null'.
	//////////////////////////////////////////////////////////////
	
}