///////////////////////////////////////////////////////////////////////
// This function will visually display the inut element.
//////////////////////////////////////////////////////////////////////
function ShowElement(ElementId)
{ 
	// make sure the element exists
	if (document.getElementById(ElementId) != null)
	{
		// hide "update in progress" text and display
		document.getElementById(ElementId).style.display="";
		document.getElementById(ElementId).style.visibility="visible";
	}
}

///////////////////////////////////////////////////////////////////////
// Trims leading/trailing spaces
//////////////////////////////////////////////////////////////////////
function trim(str) 
{ 
  str = str.replace( /^\s+/g, "" ); // strip leading 
  str = str.replace( /\s+$/g, "" ); // strip trailing 

  return str; 
} 

///////////////////////////////////////////////////////////////////////
// This function will visually hide the inut element.
//////////////////////////////////////////////////////////////////////
function HideElement(ElementId)
{ 
	// make sure the element exists
	if (document.getElementById(ElementId) != null)
	{
		// hide "update in progress" text and display
		document.getElementById(ElementId).style.display="none";
		document.getElementById(ElementId).style.visibility="hidden";
	}
}

//////////////////////////////////////////////////////////////////
// returns true if the input string ends with a letter.
//////////////////////////////////////////////////////////////////
function endsWithletter(s) 
{
	if (s.length == 0)
	{
		return false;
	}
	
	if ( (s.toLowerCase().charAt(s.length - 1) >= 'a') && (s.toLowerCase().charAt(s.length - 1) <= 'z') )
	{
		return true;
	}
	
	return false;
}

//////////////////////////////////////////////////////////////////
// Determines if the input string represents a syntactically correct
// email address.
//////////////////////////////////////////////////////////////////
function isValidEmail(addr) {
   if ((addr.indexOf("@")  == -1) 
   ||  (addr.indexOf(".")  == -1) 
   ||  (addr.indexOf(" ")  != -1) 
   ||  (addr.indexOf(",")  != -1) 
   ||  (addr.indexOf(";")  != -1) 
   ||  (addr.indexOf(":")  != -1) 
   ||  (addr.indexOf("/")  != -1) 
   ||  (addr.indexOf("\\") != -1) 
   ||  (addr.indexOf("!")  != -1) 
   ||  (addr.indexOf("@@") != -1) 
   ||  (addr.indexOf("..") != -1) 
   ||  (addr.indexOf("@.") != -1) 
   ||  (addr.indexOf(")")  != -1) 
   ||  (addr.indexOf("(")  != -1) 
   ||  (addr.indexOf("#")  != -1) 
   ||  (endsWithletter(addr)  == false) 
      ) 
   {
      return false;
   } 
   else 
   {
		return true;
   }
}

//////////////////////////////////////////////////////////////////////
// This function will determine the number of checkboxes with their
// value checked.
//////////////////////////////////////////////////////////////////////
function NumberOfBoxesChecked(CheckboxObject)
{ 
	var NumChecked = 0;

	// loop thru all options
   	for (var i = 0; i < CheckboxObject.length; i++) 
	{
	   // if this option is checked
	   if (CheckboxObject[i].checked)
	   {
		NumChecked++;
	   }
	}
	return NumChecked;
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clicks
//////////////////////////////////////////////////////////////////
function unsubscribeValid(inForm)
{
	if (!inForm.editionNames.length)
	{
		if (!inForm.editionNames.checked)
		{
			alert ('please select the edition from which you want to unsubscribe.');
			return false;
		}
	}
	else
	{
		if (NumberOfBoxesChecked(inForm.editionNames) == 0)
		{
			alert ('please select the edition(s) from which you want to unsubscribe.');
			return false;
		}
	}
	
	return true;
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clicks
//////////////////////////////////////////////////////////////////
function Unsubscribe(inForm)
{ 
	// if the form is NOT invalid
	if ( !unsubscribeValid(inForm) )
	{
		return false;
	}

	$('idUnsubscribe').value = "Processing...";
	$('idUnsubscribe').disabled = true;
	
	inForm.submit();
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clicks
//////////////////////////////////////////////////////////////////
function signinValid(inForm)
{
	inForm.emailAddress.value = trim(inForm.emailAddress.value);
	
	if (!isValidEmail(inForm.emailAddress.value))
	{
		alert ('a valid email address is required.');
		return false;
	}
	return true;
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clicks
//////////////////////////////////////////////////////////////////
function Signin(inForm)
{ 
	// if the form is NOT invalid
	if ( !signinValid(inForm) )
	{
		return false;
	}

	inForm.submit();
}

//////////////////////////////////////////////////////////////////
// Determines if the input string contains only whitespace.
//////////////////////////////////////////////////////////////////
function isBlank(s) {
   if (s == "") return true
   for (var i = 0; i < s.length; i++) {
      var c = s.charAt(i);
      if ((c != " ") && (c != '\n') && (c != '\t')) return false;
   }
   return true; 
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clickes
//////////////////////////////////////////////////////////////////
function submitEmailAddress(inForm, editionName)
{
	var popup = document.getElementById("popup");
	var fader = document.getElementById("fader");
	
	if (!$('policy').checked)
	{
		alert ('Please indicate you accept the terms and privacy statement by checking the box near the Subscribe button');
		return;
	}
	
	document.getElementById("emailAddress").value = trim(document.getElementById("emailAddress").value);
	if (!isValidEmail(document.getElementById("emailAddress").value))
	{
		alert ('a valid email address is required.');
		return;
	}
	
	if (editionName)
	{
//		alert('edition');
	}
	else
	{
		if (NumberOfBoxesChecked(inForm.editionNames) == 0)
		{
			alert ('please select at least 1 edition.');
			return;
		}
	}
	
	submitViaAjaxMoo(inForm, editionName);
	
	fader.style.display = "block";
	popup.style.display = "block";
	fader.style.height = document.documentElement.scrollHeight+'px';
	popup.style.marginLeft = -popup.clientWidth/2 + 'px';

/*	
	ShowElement("popup");
	popup.style.left = document.documentElement.clientWidth/2 + 40 - 443/2 + 'px';
	popup.style.top = document.documentElement.clientWidth/2 + 40 - 1043/2 + 'px';
	if(fader)
	{
		fader.style.display = "block";
		fader.style.width = document.documentElement.scrollWidth+'px';
		fader.style.height = document.documentElement.scrollHeight+'px';
	}
	*/
}

//////////////////////////////////////////////////////////////////
// submitViaAjax - submits just the email address
//////////////////////////////////////////////////////////////////
function submitViaAjaxMoo(inForm, editionName)
{ 
	// this only works if we are the root application...
	var url = $('subscribe_url').value;
	
	// hang onto the email address they entered so it can be re-submitted with the additional information
	$('emailAddress2').value = document.getElementById("emailAddress").value;

	var editions  = "";
	var separator = "";
	
	if (editionName)
	{
		editions = editionName;
	}
	else
	{
	   	for (var i = 0; i < inForm.editionNames.length; i++) 
		{
			// if this one is selected
			if (inForm.editionNames[i].checked == true)
			{
				editions += separator + inForm.editionNames[i].value;
				separator = ",";
			}
		}
	}
	
	var jsonRequest = new Request.JSON(
						{
							url: 		url, 
							onComplete: parseJsonResultMoo
						}).post(
							{
								'emailAddress'   		: document.getElementById("emailAddress").value, 
								'referrer'       		: document.getElementById("referrer").value, 
								'editionNamesComposite' : editions,
								'processingStage'		: '1'
							});
	
	$('emailAddress').value = "";
}
//////////////////////////////////////////////////////////////////
// Parse the JSON result into an object
//////////////////////////////////////////////////////////////////
function parseJsonResultMoo(commandBean)
{ 
	// sometimes we use a tracer graphic to acknowledge a visitor just subscribed.  If we do, we will
	// have an image placeholder (idTi1) and a hidden field that holds the tracer url (idTid1Url)  to be supplied as the img src
	if ( (document.getElementById("idTi1")) && (document.getElementById("idTid1Url")) )
	{
		var urlTracker1 = document.getElementById("idTid1Url").value.replace("emailAddress", document.getElementById("emailAddress2").value);
		// retrieve the tracer image (so the recipient can bookkeep))
		document.getElementById("idTi1").src = urlTracker1;
	}
	
	if ( (document.getElementById("idTi2")) && (document.getElementById("idTid2Url")) )
	{
		var urlTracker2 = document.getElementById("idTid2Url").value.replace("emailAddress", document.getElementById("emailAddress2").value);
		urlTracker2 = urlTracker2.replace("visitorId",commandBean.visitorId);
		// retrieve the tracer image (so the recipient can bookkeep))
		document.getElementById("idTi2").src = urlTracker2;
	}
	
	// now that we have submitted the email address, we will see if there are any 
	// Cost Per Acquition (CPA) tracer graphics (or more sophisticated tracking code) we need to include.  
	// Usually, these graphics would just  be included on a "Thanks" page, but since we just AJAX'ed
	// the email address, I will programatically create an iframe(s) and use the tracer
	// graphic as the iframe's source

	if (document.getElementById("iframeCpaTracker1"))
	{
		urlTracker1 = document.getElementById("iframeCpaTracker1").value.replace("visitorId",commandBean.visitorId);
		iframeCpaTracker = document.createElement("IFRAME"); 
		iframeCpaTracker.setAttribute("src", urlTracker1); 
		iframeCpaTracker.style.width = 1+"px"; 
		iframeCpaTracker.style.height = 1+"px"; 
		document.body.appendChild(iframeCpaTracker); 
	}
	
}

//////////////////////////////////////////////////////////////////
// submitViaAjax - submits just the email address
//////////////////////////////////////////////////////////////////
function submitViaAjax2Moo()
{ 
	// this only works if we are the root application...
	var url = $('subscribe_url').value;
	
	var jsonRequest = new Request.JSON(
						{
							url: 		url, 
							onComplete: parseJsonResult2Moo
						}).post(
							{
								'emailAddress': 	document.getElementById("emailAddress2").value, 
								'zip': 				document.getElementById("zip").value, 
								'gender': 			RadioButtonValue(document.emailForm2.gender,""), 
								'age': 				document.getElementById("age").value, 
								'income': 			document.getElementById("income").value, 
								'mobilePhone': 		document.getElementById("mobilePhone").value, 
								'processingStage': 	'2'
							});
}
//////////////////////////////////////////////////////////////////
// Parse the JSON result into an object
//////////////////////////////////////////////////////////////////
function parseJsonResult2Moo(commandBean)
{ 
	// reset the values
	$('zip').value 			= "";
	$('income').value 		= "-1";
	$('mobilePhone').value 	= "";
}

//////////////////////////////////////////////////////////////////
// Submits the other vitals via a normal post so we can show  Thanks paage.
//////////////////////////////////////////////////////////////////
function submitViaThanksPost(inProcessingStage)
{ 
	$('processingStage').value 	= inProcessingStage;
	$('emailForm2').action = $('thanks_url').value;
	$('emailForm2').method = "post";
	$('emailForm2').submit();
}

//////////////////////////////////////////////////////////////////
// Called when the submit button is clickes
//////////////////////////////////////////////////////////////////
function submitOtherVitals()
{
	var popup = document.getElementById("popup");
	var fader = document.getElementById("fader");
	
	submitViaThanksPost("2");
	return true;

}
