// variable declarations
var http = RealAge.Utils.CreateXmlHttp(); // We create the HTTP Object
// bD is for  bad domain, gd is for good domain returned by webservice
var bD = "";
var gD = "";
// the variables for tracking webservice vary by web site. 
var impressionID = "186"; //for user typed in bad email
var itemID = "199"; // for user clicks yes
var clientID = "2"; // for all tracking
// names of email text box may vary slightly site to site, change here to cascade to rest of functions
var emailTextBoxID = 'EmailAddress';
var emailErrorLabelID = 'EmailAddressError';
// change value of below to match location of webservice.
var localHost = urlConstructor();
var url = window.document.location.protocol + "//" + localHost + "/emailValidator/emailValidation.asmx/validateUsersEmail?emailAddress="; // The server-side script
var trackingURL = window.document.location.protocol + "//" + localHost + "/emailvalidator/emailValidation.asmx/trackYesClicks?"; //itemID=string&clientID=string";
var globalUName; //for passing around user name
var globalDomain; //for passing around domain

//comment out the checkEmail function calls in the two below to deactivate 
//web service call.
function verifyEmailAJAX()
{
	//return true;
	return checkEmail();
	
}
function verifyEmailNonStandardPage(emailTextBoxToValidate,errorLabelIDToCheck)
{
    
	//return true;
	emailTextBoxID = emailTextBoxToValidate;
	emailErrorLabelID = errorLabelIDToCheck;
	return checkEmail();
}


function urlConstructor()
{
	if (document.location.host.toLowerCase() != "www.realage.com" &&
	    document.location.host.toLowerCase() != "clsproto1.realage.com" &&
	    document.location.host.toLowerCase() != "cls.realage.com")
	{
		return window.document.location.host + "/RealAge20";
	}
	else
	{
		return window.document.location.host;
	}
}
// add in additional client validations if wanted.
function ValidateEmail(){
	//var emailID=document.getElementById(emailTextBoxID).value;
	return true
 }
 
// handles response from remote webservice (on same machine / farm). 
function handleHttpResponse() {
if ( ValidateEmail()  )
{
  if (http.readyState == 4) {
		if (http.status == 200){
		   	results = http.responseXML.documentElement;
			if (results.getElementsByTagName('invalidDomain')[0] != null)
			{
			    var badDomain = results.getElementsByTagName('invalidDomain')[0].firstChild.data;
			    var goodDomain = results.getElementsByTagName('validDomain')[0].firstChild.data;
			    var uName = results.getElementsByTagName('userName')[0].firstChild.data;
			    if ((results.getElementsByTagName('isValid')[0].firstChild.data == "false") && (results.getElementsByTagName('undeliverable')[0].firstChild.data == "false")) 
			    {
				    clearUserNotification();
    				
				    bD = badDomain;
				    gD = goodDomain;
				    showUserNotification(badDomain,goodDomain,uName);
			    }
			    else
			    {
    			    
				    clearText();
				    if (results.getElementsByTagName('undeliverable')[0].firstChild.data == "true")
				    {
				        showUndeliverable(badDomain,goodDomain,uName);
				    }
			    }
			}
		}
  }
}
}

function clearText()
{
	if ( document.getElementById('misSpellBox').hasChildNodes() )
				{
					while(document.getElementById('misSpellBox').hasChildNodes() == true)
					{
						document.getElementById('misSpellBox').removeChild(document.getElementById('misSpellBox').childNodes[0]);
					}	
				}
}

function showUndeliverable(badDomain,goodDomain,uName)
{
		trackYesClicks('undelivimpression');
	    var mBox = document.getElementById('misSpellBox');
		mBox.className = "FontLarge"
		mBox.appendChild(document.createElement("br"));
		var newDiv = document.createElement("div");
		//newDiv.setAttribute("style", "font-size:100%;")
		newDiv.className = "errorMessage"; 
		var txt = document.createTextNode("Important Account Information!");
		var spacer = document.createTextNode(" ");
		newDiv.appendChild(txt);		
		mBox.appendChild(newDiv);
		mBox.appendChild(document.createElement("br"));
		
		newDiv = document.createElement("div");
		//newDiv.setAttribute("style", "font-size:100%;")
		//newDiv.className = "FontMediumHover";
		
		txt = document.createTextNode("RealAge has detected ")
		newDiv.appendChild(txt);		
		var redSpan = document.createElement("div");
		redSpan.className = "errorMessage"
		txt = document.createTextNode(uName + "@" + goodDomain)
		redSpan.appendChild(txt);
		newDiv.appendChild(redSpan);		
		
		txt = document.createTextNode(" as an invalid address that is no longer receiving messages.");
		newDiv.appendChild(txt);	
		mBox.appendChild(newDiv);
		mBox.appendChild(document.createElement("br"));
		
		newDiv = document.createElement("div");
		//newDiv.setAttribute("style", "font-size:100%;")
		//newDiv.className = "FontMediumHover";
		var nLink = document.createElement("a");
		nLink.setAttribute("href", "javascript:trackYesClicks('undeliverable');");
		//nLink.setAttribute("onClick", "javascript:trackYesClicks('undeliverable');");
		//nLink.setAttribute("style", "color:blue;font-decoration:underline;");
		var linkText=document.createTextNode("Click here");
		nLink.appendChild(linkText);		
		newDiv.appendChild(nLink);		
		
		txt = document.createTextNode(" to update your RealAge account with your new e-mail address. If you know your e-mail is valid, skip this step and continue below.")
		newDiv.appendChild(txt);
		
		mBox.appendChild(newDiv);
		globalUName = uName;
		globalDomain = goodDomain;
}
// creates yes/no radio buttons using DOM, Javascript
// yes/no radio buttons call other functions using onClick event
function showUserNotification(badDomain,goodDomain,uName)
{
	    trackYesClicks( "impression" );
	    var lineBreak = document.createElement("br");
		var mBox = document.getElementById('misSpellBox');
		mBox.appendChild(document.createElement("br"));
		var txt = document.createTextNode("Did you mean " + uName + "@" + goodDomain + "?");
		var spacer = document.createTextNode(" ");
		mBox.appendChild(txt);		
		var newDiv = document.createElement("div");
		newDiv.className = "Verd_Black_12_pad"; 
		
		var yBtn = document.createElement("input");
		yBtn.type = "radio";
		yBtn.onclick = fixEmailDomain;
		newDiv.appendChild(yBtn);
		newDiv.appendChild(document.createTextNode(" Yes "));
		
		newDiv.appendChild(document.createElement("br"));
		
		var nBtn = document.createElement("input");
		nBtn.type = "radio";
		nBtn.onclick = clickedNo;
		newDiv.appendChild(nBtn);
		newDiv.appendChild(document.createTextNode(" No "));
		mBox.appendChild(newDiv);
}

// handles no click event, runs through tracking function, clears user notification
function clickedNo()
{
	trackYesClicks('no');
	clearUserNotification();
}

// recursively eliminates all nodes built in DOM construction of user interface area
function clearUserNotification()
{
	if ( document.getElementById('misSpellBox').hasChildNodes() )
	{
		while(document.getElementById('misSpellBox').hasChildNodes() == true)
		{
			document.getElementById('misSpellBox').removeChild(document.getElementById('misSpellBox').childNodes[0]);
		}
	}
	if ( document.getElementById(emailErrorLabelID)!= null )
	{
		while(document.getElementById(emailErrorLabelID).hasChildNodes() == true)
		{
			document.getElementById(emailErrorLabelID).removeChild(document.getElementById(emailErrorLabelID).childNodes[0]);
		}
	}
}

// replaces poorly spelled domain name with correct domain name from webservice
function fixEmailDomain( )
{
	document.getElementById(emailTextBoxID).value = document.getElementById(emailTextBoxID).value.toLowerCase().replace( bD, gD );
	clearUserNotification();
	trackYesClicks("yes");
}

// actual function doing bulk of work
// checks for DOM enabled browsers, AJAX enabled broswers
// if both are present, runs the email validation using remote webservice
function checkEmail() {
	if ( document.getElementById ) 
	{
	//alert('has document.getElementById');
	
		var emailValue = document.getElementById(emailTextBoxID);
		// uncomment for indow location window.location = url + emailValue.value;
		if (emailValue.value)
		{
			if (http)
			{
				http.open("GET", url + emailValue.value, true);
				http.onreadystatechange = handleHttpResponse;
				http.send(null);
			}
		}
	}

 }
 
 // tracking function, feeds info into new tracking object
function trackYesClicks(userRepsonse) {
	if (userRepsonse == "impression" )
	{
		// uncomment the alert to view the URL data ---- 
		//alert(trackingURL + "itemID=" + impressionID + "&clientID=" + clientID + "&answer=impression&pageURL=" + thisPageURL);
		http.open("GET", trackingURL + "itemID=" + impressionID + "&clientID=" + clientID + "&answer=impression&pageURL=" + thisPageURL, true);
		http.onreadystatechange = handleTrackingResponse;
		http.send(null);
	}
	if (userRepsonse == "yes" )
	{
		http.open("GET", trackingURL + "itemID=" + itemID + "&clientID=" + clientID + "&answer=yes&pageURL=" + thisPageURL, true);
		http.onreadystatechange = handleTrackingResponse;
		http.send(null);
	}
	if (userRepsonse == "no" )
	{
		http.open("GET", trackingURL + "itemID=" + itemID + "&clientID=" + clientID + "&answer=no&pageURL=" + thisPageURL, true);
		http.onreadystatechange = handleTrackingResponse;
		http.send(null);
	}
	if (userRepsonse == "undeliverable" )
	{
		http.open("GET", trackingURL + "itemID=" + itemID + "&clientID=" + clientID + "&answer=undeliverable&pageURL=" + thisPageURL, true);
		http.onreadystatechange = handleUndeliverableTrackingResponse;
		http.send(null);
		//alert( userRepsonse );
		//document.location = window.document.location.protocol + "//" + localHost + "/reg/MyAcnt.aspx?mat=100&userEmail=" + globalUName + "@" + globalDomain +"&destURL=" + toUrl + "&mod=" + pageModKey;
	}
	if (userRepsonse == "undelivimpression" )
	{
		http.open("GET", trackingURL + "itemID=" + itemID + "&clientID=" + clientID + "&answer=undelivimpression&pageURL=" + thisPageURL, true);
		http.onreadystatechange = handleTrackingResponse;
		http.send(null);
	}
 }

// essentially does nothing, but needed for Firefox support (return function). 
// you can uncomment some lines for debugging webservice 
function handleTrackingResponse() {
if (http.readyState == 4) {
		if (http.status == 200){
			// do nothing, or uncomment to see pop up of tracking (0=failed, 1=success).
			//var trackResults = http.responseXML.documentElement;
			//alert( trackResults.firstChild.data );
		}
	}
}

// for handling click tracking on undeliverable tracking
function handleUndeliverableTrackingResponse() {
if (http.readyState == 4) {
		if (http.status == 200){
			// uncomment to see pop up of tracking (0=failed, 1=success).
			var trackResults = http.responseXML.documentElement;
			//alert( trackResults.firstChild.data );
			//alert(window.document.location.protocol + "//" + localHost + "/reg/MyAcnt.aspx?mat=100&userEmail=" + globalUName + "@" + globalDomain +"&destURL=" + toUrl + "&mod=" + pageModKey);
			document.location = window.document.location.protocol + "//" + localHost + "/reg/MyAcnt.aspx?mat=100&userEmail=" + globalUName + "@" + globalDomain +"&destURL=" + toUrl + "&mod=" + pageModKey;
		}
	}
}

