function verifyAgeSelection(id, hidden){ //id of age field, id of form, id of hidden container
	var val = $F(id);
	var errordiv = $(id).up().next('.small_txt');
	var thisForm = $(id).up('form');
	if(val == 1){
		errordiv.update('You must be 13 or older to register.');
		thisForm.disable();
		$(id).enable();
	}else if(val == ''){
		errordiv.update("Please select your age.");
		thisForm.disable();
		$(id).enable();
	}else{
		errordiv.update('&nbsp;');
		$(hidden).show();
		thisForm.enable();
	}
}


function sendTourRegistration(){
	var googleTag = '/Interactions/Tour/TourRegistration/SubmitButton';
	
	var ajax;
	var nameFirst=$F('nameFirst');
	var nameLast=$F('nameLast');
	var fromEmail=$F('fromEmail');
	var city=$F('city');
	var age=$F('age');
	var gender=$F('gender');
	var state=$F('state');
	var tourDate=$F('tourDate');
	var truthUpdates=$('truthUpdates');
	
	
	//do some error checking
	var error = false;
	
	if(checkField('nameFirst')===false){ 
		form_error_focus('nameFirst');  
		error = true;
	}else{
		form_error_remove('nameFirst');
	}
	
	if(checkField('nameLast')===false){ 
		form_error_focus('nameLast');  
		error = true;
	}else{
		form_error_remove('nameLast');
	}
	
	if((checkField('age')===false)||(age==1)){ 
		form_error_focus('age');  
		error = true;
	}else{
		form_error_remove('age');
	}	
		
	if(isValidMultEmails("fromEmail")===false){ 
		form_error_focus('fromEmail');  
		error = true;
	}else{
		form_error_remove('fromEmail');
	}
	
	if(checkField("city")===false){
		form_error_focus('city');  
		error = true;
	}else{
		form_error_remove('city');
	}
	
	if(checkField("state")===false){ 
		form_error_focus('state');  
		error = true;
	}else{
		form_error_remove('state');
	}
	
	if(checkField("gender")===false){ 
		form_error_focus('gender');  
		error = true;
	}else{
		form_error_remove('gender');
	}
	
	if(checkField('tourDate')===false){  
		form_error_focus('tourDate');  
		$('tourDate').up().next('.small_txt').update('You must choose a date for at least one tour.');
		error = true;
	}else{
		form_error_remove('tourDate');  
		$('tourDate').up().next('.small_txt').update('&nbsp;');
	}
	
	
	
	if(error==true){
		return false;
	}else{
		$('error').update("Sending..."); 
	}
	
	
	//send google track tag 
	if(googleTag){
		pageTracker._trackPageview(googleTag);
	}
	
	//spolight tag
	var prd=new Date(),pru=Date.UTC(prd.getUTCFullYear(),prd.getUTCMonth(),prd.getUTCDay(),prd.getUTCHours(),prd.getUTCMinutes(),prd.getUTCSeconds(),prd.getUTCMilliseconds());
	var pr_eid=pru+Math.random();
	var pr_event='';
	var pr_item='';
	var pr_quantity='';
	var pr_value='';
	
	$('tour_registration').insert({ bottom: "<img width='1' height='1' src='http://ev.ads.pointroll.com/event/?ss=85078310-BAC3-4395-A8BF-4D2DFEDF06BD&av=355&eid="+pr_eid+"&ev="+pr_event+"&item="+pr_item+"&q="+pr_quantity+"&val="+pr_value+"&r="+Math.random()+"'>" });

	
	
	ajax = new Ajax.Request('cfm/_emailResponse.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:function(t){ 
							 	$('tour_registration').hide();
								$('error').update("");
								$('registration_form').reset();

								//check if user is already registered at thetruth.com
								var regcheck = t.responseText.replace(/\r|\n|\r\n/g, ""); 
								regcheck = regcheck.replace(/^\s+|\s+$/g, '');
								//alert('['+regcheck+']');
							 	
									
								var responseMessage = '<div>Thank you for submitting your registration information.  You\'ll get another email from us about a week before the tour date.</div><!--<div>Want to sign our petition to change the name of Lung Cancer to Big Tobacco Disease?</div><div style="cursor: pointer; margin:10px 0;"><a onclick=""><img src="/images/btn_clickHere.gif" width="117" height="44" alt="click here" /></a>&nbsp;&nbsp;<span style="vertical-align:top; line-height:44px;">No Thanks</span></div>-->';
/*								if(regcheck != "yes"){
									responseMessage += '<div style="margin:10px 0;">Sweet, you\'re all toured up. But you know what goes great with some tour? A little truth registration. We\'ve got newsletters, downloads, updates, the whole bit. So hit it up: <a href="/register/register.cfm" onclick="googletrack(\'/Interactions/Tour/TourRegistration/RegistrationLink\');">thetruth.com/registration</a>.</div>';	
								}
*/								
								$('response').update('<div class="contentPanel greyDark">'+responseMessage+'</div>'); 
	
								
							 }, 
					         onFailure:function(){ $('error').update('<b>There was a problem, please try again later.</b>'); }, 
					         parameters: '&nameFirst=' + nameFirst + '&nameLast=' + nameLast + '&fromEmail=' + fromEmail + '&age=' + age + '&city=' + city + '&state=' + state + '&gender=' + gender + '&tourDate=' + tourDate + '&truthUpdates=' + truthUpdates.checked + '&emailFormName=tourRegistration&rn=' + Math.random()} 
	                       );
}


function form_error_focus(fieldID){
	$(fieldID).addClassName('error');
	$(fieldID).activate();
	$('error').update("There were errors found, please fix them before submitting.");
}


function form_error_remove(fieldID){
	if($(fieldID).hasClassName('error')){
		$(fieldID).removeClassName('error');
	}
}










//Generic function for all requets to handle error , we can customize this f() for different error messages 

var statusErrFunc = function(t) 
{
  alert('Error setting status: ' + t.status + ' -- ' + t.statusText);
	
}


function googletrack(googleTag){
	if(googleTag){
		pageTracker._trackPageview(googleTag);
	}	
}


function formFieldFocusBlur(id, defValue, action){
	if(action == 'focus'){
		if(defValue == 'password'){ id.type = 'password'; }
		if (id.value == defValue){
			id.clear();
		}
		id.select();
	}else{
		if(checkField(id)===false){ 
			if(defValue == 'password'){ id.type = 'text'; }
			id.value = defValue;
		}
	}
}

loginFields=function(){
	var user = $('mainLogin_username');
	var pass = $('mainLogin_password');
	var submitBut = $('mainLogin_submit');
		
	if(user){
	
		user.observe('focus', function(){ formFieldFocusBlur(user, 'username', 'focus') });
		user.observe('blur', function(){ formFieldFocusBlur(user, 'username', 'blur') });
		
		pass.observe('focus', function(){ formFieldFocusBlur(pass, 'password', 'focus') });
		pass.observe('blur', function(){ formFieldFocusBlur(pass, 'password', 'blur') });
		
		
		submitBut.observe('mouseover', function(){ 
			submitBut.addClassName('FormButtonMO'); 
		});	
		submitBut.observe('mouseout', function(){ 
			submitBut.removeClassName('FormButtonMO'); 
		});	
	}
}

Event.observe(window, 'load', loginFields, false);








function showRegistrationForm(){
	$('response').update('');
	$('error').update('');
	$('registration_form').reset();
	$('tour_registration').show();	
}


function sendTourEmail() 
{   
	
	var googleTag = '/Interactions/Tour/Nav/STAFSubmitButton';

	var ajax;
	var name=$F('STFname');
	var fromEmail=$F('STFfromEmail');
	var toEmail=$F('STFtoEmail');

	
	//do some error checking
	if(checkField('STFname')===false){ 
		$('sendError').update("<b>Please enter your name</b>."); return false; 
	}
	if(isValidMultEmails("STFfromEmail")===false){ 
		$('sendError').update("<b>Please enter a valid email address</b>."); return false; 
	}
	if(isValidMultEmails("STFtoEmail")===false){ 
		$('sendError').update("<b>Please enter a valid email address for your friend</b>."); return false; 
	}
	/*
	if(!$('terms').checked){ 
		$('error').update("<b>You must agree to the terms by checking the box above</b>."); return false; 
	}
	*/
	
	$('sendError').update("Sending..."); 
	
	//send google track tag 
	if(googleTag){
		pageTracker._trackPageview(googleTag);
	}
	
	ajax = new Ajax.Request('cfm/_emailResponse.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:function(){ 
							 	$('email_form_intro').hide();
								$('blog_emailform_container').hide();
								$('sendResponse').update('<div style="margin-top:20px;">Congratulations '+name+', you just spread a little truth. And that\'s twice as cool as spreading a little vomit or some rabies. So thanks.</div>'); 
							 }, 
					         onFailure:function(){ $('sendError').update('<b>There was a problem, please try again later.</b>'); }, 
					         parameters: 'fromEmail=' + fromEmail +  '&name=' + name + '&toEmail=' + toEmail + '&emailFormName=tourStf&rn=' + Math.random()} 
	                       );
}


function sendBlogForm() 
{   

	var googleTag = '/Interactions/Blog/Blog/SubmitMessage';

	var ajax;
	var name=$F('name');
	var city=$F('city');
	var state=$F('state');
	var fromEmail=$F('fromEmail');
	var message=$F('message');
	
	//do some error checking
	if(checkField('name')===false){ 
		$('error').update("<b>Please enter your name</b>."); return false; 
	}
	if(checkField('city')===false){ 
		$('error').update("<b>Please enter a city</b>."); return false; 
	}
	if(isValidMultEmails("fromEmail")===false){ 
		$('error').update("<b>Please enter a valid email address</b>."); return false; 
	}
	if(checkField('message')===false){ 
		$('error').update("<b>Please enter a message</b>."); return false; 
	}
	if(!$('terms').checked){ 
		$('error').update("<b>You must agree to the terms by checking the box above</b>."); return false; 
	}
	
	$('error').update("Sending..."); 
	
	//send google track tag 
	//googleTag = "/Interactions/FactsList/EmailPDF/Submit";
	
	if(googleTag){
		pageTracker._trackPageview(googleTag);
	}
	
	ajax = new Ajax.Request('cfm/_emailResponse.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:function(){ 
							 	$('email_form_intro').update('&nbsp;');
								$('response').update('<div style="margin-top:50px;">Thanks for your email.<br /><br />In our jam-packed schedules, we have approximately three minutes a day devoted to answering fan mail (if you can call it that). So check back on our blog every week or so to see if we&#39;ve finally gotten around to answering yours.<br /><br />And remember, there are no stupid questions. But there may be a few we can&#39;t think of funny answers to.</div>'); 
							 }, 
					         onFailure:function(){ $('error').update('<b>There was a problem, please try again later.</b>'); }, 
					         parameters: 'fromEmail=' + fromEmail +  '&name=' + name + '&city=' + city + '&state=' + state + '&message=' + message + '&rn=' + Math.random()} 
	                       );
}


//start code for facts form pdf emailer
function sendFactForm() 
{   
	var ajax;
	var toEmail=$F('toEmail');
	var fromEmail=$F('fromEmail');
	var message=$F('message');
	var factTemplate=$('factTemplate').value;
	
	//do some error checking
	if((isValidMultEmails("toEmail")===false)||(isValidMultEmails("fromEmail")===false)){ 
		$('response').innerHTML = "Please fix the errors before sending."; return false; 
	}
	
	$('response').innerHTML = "Sending..."; 
	
	//send google track tag 
	//value is based on hidden factTemplate variable passed in form to determine which tag to send
	if(factTemplate == "FactCart"){
		googleTag = "/Interactions/FactsList/EmailPDF/Submit";
	}else if(factTemplate == "MyFavFacts"){
		googleTag = "/Interactions/FavoriteFacts/EmailPDF/Submit";
	}
	if(googleTag){
		pageTracker._trackPageview(googleTag);
	}
	
	ajax = new Ajax.Request('email_response.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:getResponse, // checkuser is the F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'factTemplate=' + factTemplate +  '&fromEmail=' + fromEmail +  '&toEmail=' + toEmail +  '&message=' + message + '&rn=' + Math.random()} 
	                       );
}

var getResponse = function(t) // this Function is for successful completion of Ajax call
{
	//t.responseText is the response from get_users.cfm file
	// "div1" is the div area where we can display the contents after successful completion of login
	if( t.responseText.length )
	{		
		$('response').innerHTML = t.responseText; 
	}
}
//end code for facts form pdf emailer 



//start code for Checking Email Address exits or not in database 
//calling on the page register.cfm

function validateEmailAddress()
{  
	var ajax;
	var Email_address=document.getElementById("Email_address").value;
	ajax = new Ajax.Request('Check_email.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:checkUser1, // checkuser is the F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'Email_address=' + Email_address + '&rn=' + Math.random()} // parameters for action page
	                       );
	
}

var checkUser1 = function(t) // this Function is for successful completion of Ajax call
{
	//t.responseText is the response from get_users.cfm file
	// "div1" is the div area where we can display the contents after successful completion of login
	if( t.responseText.length > 2)
	{		
	
		$('div2').innerHTML = t.responseText; 
	}else{
		
		$('div2').innerHTML = "Email is valid."; 
	}
	
}
//end code for Checking Email Address exits or not in database 


// start code for validating user at the time of logging
//calling on the page login.cfm 
function validateUser() // this F() is called from "validate_user.cfm" for Ajax call
{
	var ajax;
	var User_name=document.getElementById("User_name").value;
	var Password=document.getElementById("Password").value;
	ajax = new Ajax.Request('Validate_user.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:checkUser2, // checkuser is the F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'User_name=' + User_name + '&Password=' + Password + '&rn=' + Math.random()} // parameters for action page
	                       );
	
}

var checkUser2 = function(t) // this Function is for successful completion of Ajax call
{
	//t.responseText is the response from get_users.cfm file
	// "div1" is the div area where we can display the contents after successful completion of login
	
	var loginstatus=t.responseText;
	loginstatus=loginstatus.replace(/\r\n/gi,"");
	loginstatus=loginstatus.replace(/\n/gi,"");
	loginstatus=loginstatus.replace(/\r/gi,"");
	loginstatus=loginstatus.replace(/\t/gi,"");

	if (loginstatus == '')
	{	
		location.href='profile.cfm';
	}
	else
		$('div1').innerHTML = loginstatus; 
	
}
//end code for validating user

//start code for Checking user exits or not in database at the time of editing user
//calling on the page profile.cfm
function validateUsersEdit() 
{   
	var ajax;
	var User_name=document.getElementById("User_name").value;
	var User_id=document.getElementById("User_id").value;

	ajax = new Ajax.Request('Check_user_edit.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:checkUser3, // checkuser is the F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'User_name=' + User_name + '&User_id=' + User_id + '&rn=' + Math.random()} // parameters for action page
	                       );
	
}

var checkUser3 = function(t) // this Function is for successful completion of Ajax call
{
	//t.responseText is the response from get_users.cfm file
	// "div1" is the div area where we can display the contents after successful completion of login
	if( t.responseText.length )
	{		
		$('div1').innerHTML = t.responseText; 
	}
	
}
//start code for Checking user exits or not in database 


//start code for Checking Email Address exits or not in database at the time of editing user
//calling on the page profile.cfm 

function validateEmailAddressEdit()
{  
	var ajax;
	var Email_address=document.getElementById("Email_address").value;
	var User_id=document.getElementById("User_id").value;

	ajax = new Ajax.Request('Check_email_edit.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:checkUser4, // checkuser is the F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'Email_address=' + Email_address + '&User_id=' + User_id + '&rn=' + Math.random()} // parameters for action page
	                       );
	
}

var checkUser4 = function(t) // this Function is for successful completion of Ajax call
{
	//t.responseText is the response from get_users.cfm file
	// "div1" is the div area where we can display the contents after successful completion of login
	if( t.responseText.length )
	{		
		$('div2').innerHTML = t.responseText; 
	}
	
}
//end code for Checking Email Address exits or not in database 


//BgImage switch code
var GSelectedImage=''; // Global variable for request ID 2
function toggleBgImage(obj)
{
	var ajax;
	var SelectedImage=obj; 
	
	//start code to change the value of toggle button 
	if(obj == 'sunnySide')
		document.getElementById('bodyImage').value='darkSide';
	else if(obj == 'darkSide')
		document.getElementById('bodyImage').value='sunnySide';
	//end code to change the value of toggle button 
	ajax = new Ajax.Request('includes/_setBgImage.cfm',
					        {method: 'post',
					         onSuccess:changeImage,
					         onFailure:statusErrFunc,
					         parameters: 'bodyImage=' + SelectedImage + '&rn=' + Math.random()}
	                       );
	GSelectedImage= SelectedImage;
}

var changeImage = function(t) 
{
	var IDmainContainer=document.getElementById('main_container');
	IDmainContainer.className=GSelectedImage;
}
//End for bgImage switch code




//BgImage switch code, revised for simplicity and in use for flash -Joel
function switchBgImage()
{
	var rand = Math.random();
	var url = 'includes/_switchBgImage.cfm?rn='+rand;
	var ajax = new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) {
		  var ajax_response = transport.responseText;
		  var response = ajax_response.replace(/^\s+|\s+$/g, '')
		  $('main_container').className = response;
		  
		  //add switch for tiled bg now also
		  $('home').className = "mainbody_" + response;
		  
	  },
	  onFailure: function() {
		  //$('main_container').className = transport.responseText;
		  return alert('Sorry, there was a problem.  Please try again.');
	  }  
	});
}
//End for bgImage switch code



// Begin functions for the fact cart section
function updateFact (obj)
{
	var sel_value;
	sel_value = obj.value;
	sel_chked_mode= obj.checked;

	var ajax;
	ajax = new Ajax.Request('_updateFacts.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:update_session_fact, //  F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'fact_id=' + sel_value +  '&sel_chked_mode=' + sel_chked_mode + '&rn=' + Math.random()} // parameters for action page
	                       );
}

var update_session_fact = function(t) // this Function is for successful completion of Ajax call
{
	
	// "div10" is the div area where we can display the contents after successful execution
	if( t.responseText.length )
	{		
		
		//$('div110').innerHTML = "Updated..."; 	
		$('div10').innerHTML = t.responseText; 
	}
	
}


// F() to check or uncheck all checkboxes on select of "Select All" checkbox
function chk_all(obj)
{
	sel_chked_mode= obj.checked;
	boxes = document.facts.fact_id.length

	for (i = 0; i < boxes; i++) 
	{
		document.facts.fact_id[i].checked=sel_chked_mode
	}
}
// end function calls for the fact section




/* check all on the page, or uncheck, depending on state of check all checkbox.  check it out. */
function check_all(element){
	if($('checkAll').checked == true){ //all are checked, so uncheck them
		var ret_value = false;
	}else{
		var ret_value = true;	
	}
	
	element = $(element) || document;
	if( element && element.getElementsByTagName ){
		var inputs = element.getElementsByTagName("input");
		for( var i = 0; inputs && i < inputs.length; i++ ){
			if( inputs[i].type == "checkbox" ){
				if(element == document){
					if($('checkAll').checked == true){
						inputs[i].checked = true;
					}else{
						inputs[i].checked = false;
					}
				}else{
					inputs[i].checked = true;	
				}
			}
		}
	}	
}







/*
XMLHttp = function() {
  self = this;
  if (typeof XMLHttpRequest != 'undefined')
  return new XMLHttpRequest();
  else if (window.ActiveXObject) {
    var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0",  "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
    for (var i = avers.length -1; i >= 0; i--) {
      try {httpObj = new ActiveXObject(avers[i]);
      return httpObj;
      } catch(e) {}
    }
  }
  throw new Error('XMLHttp (AJAX) not supported');
}

XMLHttp.prototype.get = function(url) {
  self.open('GET', url, true);
  self.onreadystatechange = function() {
     self.processRequest();}
  self.send(null);
}

XMLHttp.prototype.processRequest = function() {
  if (self.readyState == 4) {
    if (self.status != 200) {
      self.resp = 'Error : Status '+this.status+' returned.';
    } else {
      if (cType == 'text/xml') {
    self.resp = 'xml';
      } else if (cType == 'text/plain') {
    self.resp = 'text';
      } else {
    self.resp = 'unknown content type';
      }
      this.response();
    }
  }
}

ajaxObj = XMLHttp();
ajaxObj.get('myrequest.php');

ajaxObj2 = XMLHttp();
ajaxObj2.get('myrequest.php');

ajaxObj.response = function() {
  if (self.resp == 'xml') {
    alert(self.responseXML);
  } else if (self.resp == 'text') {
    alert(self.responseText);
  } else {
    alert(self.resp);
  }
}
ajaxObj2.response = function() {
  if (self.resp == 'xml') {
    alert(self.responseXML);
  } else if (self.resp == 'text') {
    alert(self.responseText);
  } else {
    alert(self.resp);
  }
}
*/




/* function to fire google tag for every download item checked */
function googletag_checked(){
	
	//fire tag for download button
	pageTracker._trackPageview('/Interactions/Downloads/GetSelectedItems');
	
	
	if( document.getElementsByTagName ){
		/*
		var inputs = document.getElementsByTagName("input");
		
		//if checkAll is selected, just fire the one tag.  otherwise loop through all selected
		//looks at 4th in array of inputs because of login items show up first in page
		if ((inputs[3].name == "checkAll")&&(inputs[3].checked == true)){
			pageTracker._trackPageview('/Interactions/Downloads/GetEverything');	
		}else{
			//alert('name:'+inputs[3].name+' / checked:'+inputs[3].checked);
			var pre_tag = "/Interactions/Downloads/GetIt/";
			for( var i = 0; inputs && i < inputs.length; i++ ){
				if((inputs[i].type == "checkbox")&&(inputs[i].checked == true)){
					
					var section = inputs[i].name;
					pageTracker._trackPageview(pre_tag+section);
					//alert(pre_tag+section);	
				}
			}
		}
		*/
		document.downloads.submit();
	}
}




// Begin functions for the myfavfact cart section
/*
function updateMyFact (obj)
{
	var sel_value;
	sel_value = obj.value;
	sel_chked_mode= obj.checked;

	var ajax;
	ajax = new Ajax.Request('_updateMyFacts.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:update_session_myfact, //  F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'fav_fact_id=' + sel_value +  '&sel_chked_mode=' + sel_chked_mode + '&rn=' + Math.random()} // parameters for action page
	                       );
}
*/



//new one now that checkboxes are changed to hearts
function updateMyFact (obj)
{
	//keep track of status with rel tag.  default: rel="off"
	var a_rel_id = 'fav_fact_'+obj;
	var status = $(a_rel_id).getAttribute('rel');
	//return alert(status);
	
	//change class of fav_fact_#id# to display full color
	if(status == 'off'){
		$(a_rel_id).className = 'heart_on';
		$(a_rel_id).setAttribute('rel', 'on');
		var newstatus = 'on';
	}else{
		$(a_rel_id).className = 'heart_off';
		$(a_rel_id).setAttribute('rel', 'off');
		var newstatus = 'off';
	}

	//make ajax call to add selected ids to session
	var ajax;
	ajax = new Ajax.Request('/facts/_updateMyFacts.cfm',//Action file for ajax call, from where output will come 
					        {method: 'post', // form submission method
					         onSuccess:update_session_myfact, //  F() for successful completion
					         onFailure:statusErrFunc, //error handler F()
					         parameters: 'fav_fact_id=' + obj +  '&status=' + newstatus + '&rn=' + Math.random()} // parameters for action page
	                       );

}


var update_session_myfact = function(t) // this Function is for successful completion of Ajax call
{
	
	// "div10" is the div area where we can display the contents after successful execution
	if( t.responseText.length )
	{		
		
		//$('div110').innerHTML = "Updated..."; 	
		$('div20').innerHTML = t.responseText; 
	}
	
}


// F() to check or uncheck all checkboxes on select of "Select All" checkbox
function chk_all2(obj)
{
	sel_chked_mode= obj.checked;
	boxes = document.facts.fav_fact_id.length

	for (i = 0; i < boxes; i++) 
	{
		document.facts.fav_fact_id[i].checked=sel_chked_mode
	}
}
// end function calls for myfav facts section

function chk_all3(obj)
{
	sel_chked_mode= obj.checked;
	boxes = document.facts.fav_fact_id.length

	for (i = 0; i < boxes; i++) 
	{
		document.facts.fav_fact_id[i].checked=sel_chked_mode
	}
}
// end function calls for myfav facts section






//is email string valid?
function checkEmailValid(address){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(address)){
		return true;
	}else{
		return false;
	}
}



//should consolidate these checking functions but I'll leave it as is for now

//split mult emails by comma, then check they are valid
function isValidMultEmails(thisfield){   //var is the id of the input field
	if(thisfield == 'fromEmail'){
		var errordiv = 'message_fromemail';
	}else if(thisfield=='toEmail'){
		var errordiv = 'message_toemail';
	}else{
		var errordiv = $(thisfield).up().next('.small_txt');
	}

	var form_input = $F(thisfield).replace(/^\s+|\s+$/g, ''); //trim whitespace
	if(form_input.length == 0){
		$(errordiv).innerHTML = 'Please enter an email address.'; 
		return false;
	}
	
	var addresses = form_input.split(",");
	for(i = 0; i < addresses.length; i++){
		var email = addresses[i].replace(/^\s+|\s+$/g, ''); //trim whitespace
		//check email
		if(checkEmailValid(email)){
			//valid
		}else{
			if(i>0){ //lets specify which email is wrong if there are multiple
				var thisnum = i+1;
				$(errordiv).innerHTML = 'Email #'+thisnum+' entered is not a valid email address.';
			}else{
				$(errordiv).innerHTML = 'Please enter a valid email address.';
			}
			return false;
		}
	}
	$(errordiv).innerHTML = '&nbsp;';
	return true;
}	



//code to validate Email Address and User Name at time of Ajax call
function isEmptyEmail(){   
	var email=document.getElementById('Email_address').value.replace(/ /gi,"");
	if(document.getElementById('Email_address').value.length == 0){
		$('div2').innerHTML = '<font class="error_msg">Please enter an email address.</font>'; 
		//document.getElementById('Email_address').focus();
		return false;
	}else if(!checkEmail(email)){// for checking valid email address
		$('div2').innerHTML = '<font class="error_msg">Please provide a valid email address.</font>';
		//document.getElementById('Email_address').focus();
		return false;
	}else{
		validateEmailAddress(); // for ajax call to check Availability fo email address
		return true;
	}
}	




function isEmptyField(id){
	var field = $(id).getValue().replace(/^\s+|\s+$/g, ''); //trim whitespace
	var errordiv = $(id).up().next('.small_txt');
	if(field.length < 1){
		errordiv.update('Please fill out this field.');
	}else{
		errordiv.update('&nbsp;');
	}
}

function checkField(id){
	var field = $(id).getValue().replace(/^\s+|\s+$/g, ''); //trim whitespace
	if(field.length < 1){
		return false;
	}else{
		return true;
	}
}


function validateField(id,errormessage){
	var field = $F(id).replace(/^\s+|\s+$/g, ''); //trim whitespace
	var errordiv = $(id).up().next('.small_txt');
	if(field.length < 1){
		errordiv.update(errormessage);
		return true;
	}else{
		errordiv.update('&nbsp;');
		return false;
	}
}


function checkAgeSelection(id){
	var val = $F(id);
	var errordiv = $(id).up().next('.small_txt');
	if(val == 1){
		errordiv.update('You must be 13 or older to register.');
		$('registration_form').disable();
		$(id).enable();
	}else if(val == ''){
		errordiv.update("Please select your age.");
		$('registration_form').disable();
		$(id).enable();
	}else{
		errordiv.update('&nbsp;');
		$('init_hidden').show();
		$('registration_form').enable();
	}
}


function isEmptyUserName(){
	
	var username = $('User_name_id').getValue().replace(/^\s+|\s+$/g, ''); //trim whitespace
	//if(username){
		//$('User_name').focus();
		//alert(username.length);
		if((username.length < 6)||(username.length > 15)){
			if(username.length < 1){
				$('div1').innerHTML = '<font class="error_msg">Please fill in the User Name.</font>';
			}else{
				$('div1').innerHTML = '<font class="error_msg">Must be 6-15 alpha-numeric characters.</font>';
			}
			return true;
			
		}else if(isAlphaNum(username)===false){
			$('div1').innerHTML = '<font class="error_msg">Must be 6-15 <b>alpha-numeric</b> characters.</font>';
			return true;
		}else{
		

			var ajax = new Ajax.Request('Check_user.cfm',
							{method: 'post', // form submission method
							 onSuccess: function(t){
								if(t.responseText.length > 1){		//this is 1 because of some whitespace char or something being returned from check_user.cfm
									//alert(t.responseText.length);
									$('div1').innerHTML = t.responseText; 
								}else{
									$('div1').innerHTML = 'Username is valid.';
								}								 
							 }, 
							 //onFailure:statusErrFunc, //error handler F()
							 parameters: 'User_name=' + username + '&rn=' + Math.random()} // parameters for action page
						   );

		}
	//}
	return true;
}	



function pass_validate(errordiv){
	
	if(errordiv == "div1"){
		var input_type = 'User Name';
	}else if(errordiv == "div3"){
		var input_type = 'Password';
	}else if(errordiv == "div4"){
		var input_type = 'Confirm Password';
	}

	
	var password = $('Password_id').getValue().replace(/^\s+|\s+$/g, ''); //trim whitespace
	if((password.length < 6)||(password.length > 15)){
		if(password.length < 1){
			$(errordiv).innerHTML = '<font class="error_msg">Please fill in the '+input_type+'.</font>';
		}else{
			$(errordiv).innerHTML = '<font class="error_msg">Must be 6-15 alpha-numeric characters.</font>';
		}
		return true;
		
	}else if(isAlphaNum(password)===false){
		$(errordiv).innerHTML = '<font class="error_msg">Must be 6-15 <b>alpha-numeric</b> characters.</font>';
		return true;
	}else{
		$(errordiv).innerHTML = input_type+' is valid.';
		return true;
	}
	return true;
}	


function confirm_pass_check(errordiv){
	
	var password = $('Password_id').getValue().replace(/^\s+|\s+$/g, '');
	var password1 = $('Password1').getValue().replace(/^\s+|\s+$/g, '');
	if(password != password1){
		$(errordiv).innerHTML = '<font class="error_msg">Passwords do not match.</font>';
	}else{
		$(errordiv).innerHTML = '&nbsp;';
	}
}	




function checkdigits(digits, req_digits){
	var str = digits+"";
	for (var x=0; x<req_digits; x++) {
		var token=str.substr(x,x+1);
		if (!_isInteger(token)) { return false; }
	}	
	return true;
}

function isValidCellField(field, digits)
{
	if($(field).value.length > 0){
		
		//check correct number of digits entered	
		if(field=="cell3"){
			var req_digits = 4;
		}else{
			var req_digits = 3;
		}
		
		if(digits.value.length < req_digits)
		{
			$('cellinfo').innerHTML = '<font class="error_msg">Please enter a valid number.</font>';
			return false;
		}
		
		var digit_str = digits.value+"";
		if(_isInteger(digit_str)===false)
		{
			$('cellinfo').innerHTML = '<font class="error_msg">Please enter numbers only.</font>';
			return false;
		}

	}
	return true;
}	


//need to check all 3 fields and keep error message if one is still not correct

function isValidCellphone()
{
	if(isValidCellField("cell1", $('cell1'))){
		if(isValidCellField("cell2", $('cell2'))){
			if(isValidCellField("cell3", $('cell3'))){
				if($('cellinfo').innerHTML != 'Optional'){
					$('cellinfo').innerHTML = '&nbsp;';
					$('cellphone').value = $('cell1').value + $('cell2').value + $('cell3').value;
				}				
				return true;
			}
		}
	}
	$('cellinfo').innerHTML = '<font class="error_msg">Please enter a valid number.</font>';
	$('cellphone').value = '';
	return false;
}	



//DATE CHECKING FUNCTIONS //////////////////////////

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	
	if (month==2) {
		
		
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			
			if (date > 29){
				return 0; 
			}
		}else { 
		
			if (date > 29) { //leap year check above not working, so just leave check for 29 in all years
				return 0; 
			}
		}
	}
	

	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
		
	//alert("month:"+month+" original date:"+val);
	
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	//alert(newdate.getTime());
	return newdate.getTime();
	}



// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
	}else if (d1 > d2) {
		return 1;
	}
	return 0;
	}



//date checking for min age req
function checkage(){
	if($('Year').value == ""){ //this is just so if they fill out year before month or day
		return false;
	}else{
	
		var currentTime = new Date()
		var month = currentTime.getMonth() + 1; //fix because months start at 0
		var day = currentTime.getDate();
		var year = currentTime.getFullYear() - 13;
		var minage = month + "/" + day + "/" + year;
	
		
		var formdatestr = $('Month').value + '/' + $('Day').value + '/' + $('Year').value;
		var comparedates = compareDates(minage,'M/d/y',formdatestr,'M/d/y');
		
		//alert("comparedates:"+comparedates);
		//check if cookie exists, set that not old enough
		var rand = Math.random();
		var url = '/includes/_coppaCookieCheck.cfm?rn='+rand;
		var ajax = new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
			  var ajax_response = transport.responseText;
			  //return alert(ajax_response);
			  if(ajax_response==0){
			  	//no cookie set
				
					//-1: part of date not entered, push error message to div underneath
					//0: not old enough
					//1: old enough
					if(comparedates == -1){
						$('age_error').innerHTML = "Please select the month, day, and year.";
						$('register_form_elements').style.display = "none";
					}else if(comparedates == 0){
						$('age_error').innerHTML = "We're sorry, you are not old enough to register.";
						$('register_form_elements').style.display = "none";
						
						//set cookie to remember
						var ajax;
						ajax = new Ajax.Request('/includes/_coppaCookie.cfm',
												{method: 'post', // form submission method
												 parameters: 'rn=' + Math.random()} // parameters for action page
											   );			
						
					}else if(comparedates == 1){
						$('age_error').innerHTML = "";
						$('register_form_elements').style.display = "block";
					}
					
			  }else{
				  //there is a cookie set, and so they had previously chosen an underage date.
				$('age_error').innerHTML = "We're sorry, you are not old enough to register.";
				$('register_form_elements').style.display = "none";
			  }
			  
			},
			onFailure: function() {
			  //$('main_container').className = transport.responseText;
			  return alert('Sorry, there was a problem.  Please try again.');
	 		}  
		});
		
	}
}



//Prepopulate any items that needs to be loaded
function prePopulate() {
 document.loginForm.username.value = "email Address";
 document.loginForm.password.value = "password";
}

