var verify = getHTTPObject(); 
var verifyWorking = false;
var fcweb_userid = false;

function checkPublicName(nickname)
{
	var regexAccount = /^[a-z0-9\-\_]{4,15}$/i;  // alphanumeric, dashes, and underscores, min length 4, max length 15
	if (regexAccount.test(nickname))
	{
		return true;
	}
	return false;
}


function CheckTeamName(thename)
{
   if (trim(thename.value).length < 1) 
	{
		alert ('Please enter a name for your new entry.');
		thename.focus();
		return false;
	} 
   if (trim(thename.value).length < 3 || trim(thename.value).length > 30) 
	{
		alert ('Your entry name must be between 3 and 30 characters long.');
		thename.focus();
		return false;
	} 

	var regexAccount = /^[a-z0-9\-\_\ \!\$\(\)\*\+\.\?\"\'\@]{3,30}$/i;  // alphanumeric, dashes, and underscores, and spaces min length 3, max length 30
	if (!regexAccount.test(thename.value)) {
		alert ('Your entry name may only contain letters, numbers, dashes and spaces.');
		thename.focus();
		return false;
	} 

   return true;
}

function CheckLeagueName(thename)
{
	if (trim(thename.value).length < 1) 
	{
		alert ('Please enter a name for your new league.');
		thename.focus();
		return false;
	} 
   if (trim(thename.value).length < 3 || trim(thename.value).length > 50 ) 
	{
		alert ('The name for your new league must be between 3 and 50 characters long.');
		thename.focus();
		return false;
	} 
	var regexAccount = /^[a-z0-9\-\_\ \!\$\(\)\*\+\.\?\"\'\@]{3,50}$/i;  // alphanumeric, dashes, and underscores, and spaces min length 3, max length 50
	if (!regexAccount.test(thename.value)) {
		alert ('Your league name may only contain letters, numbers, dashes and spaces.');
		thename.focus();
		return false;
	} 
   return true;
}

function SubmitVerification(params,handler)
{
   EnableCheckingMsg();
   verifyWorking = true;
   verify.open("POST", "/php/check-exists.php", true);
   verify.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   verify.setRequestHeader("Content-length", params.length);
   verify.setRequestHeader("Connection", "close");
   verify.onreadystatechange = handler;
   verify.send(params);	
}
function EnableCheckingMsg()
{
   var signupStatusDiv = document.getElementById('SIGNUPSTATUS');				
   signupStatusDiv.innerHTML = 'Checking...';
}
function EnableCheckAccountButton()
{
   var signupStatusDiv = document.getElementById('SIGNUPSTATUS');				
   signupStatusDiv.innerHTML = '<a href=\"javascript:VerifyAccount(document.SIGNUP)\"><img border=0 alt=Go src=http://www.rtsports.com/img/go.gif></a>';
}


//-----    Call AJAX and Check for an Existing Account  -----

function ValidateAccountID(theform,strong)
{
	theform.ACCOUNTID.value = trim(theform.ACCOUNTID.value);
	if (theform.ACCOUNTID.length < 1 || theform.ACCOUNTID.value == '') {
		alert ('Please enter your email address.');
		theform.ACCOUNTID.focus();
		theform.ACCOUNTID.select();
		return false;
	} 
	
   if (strong) {
      var validemail = checkEmail(theform.ACCOUNTID.value);
      if (validemail != 0) {
         alert ('Email not valid. Please enter your email address.');
         theform.ACCOUNTID.focus();
         theform.ACCOUNTID.select();
         return false;
      }
   }

	return true;
}

function VerifyAccount(theform)
{
   if (!ValidateAccountID(theform,theform.ACCOUNTID.value.indexOf("@") > 0)) return;
   if (!verifyWorking && verify) SubmitVerification("AID=" + escape(theform.ACCOUNTID.value), VerifyAccountHandler);
}

function VerifyAccountHandler() 
{
	if (verify.readyState == 4) {
		if (verify.responseText.indexOf('invalid') == -1) {
			//try {
				var newAccountDiv = document.getElementById('NewAccountDiv');
    	      var passwdDiv 		= document.getElementById('PasswdDiv');
				var xmlDocument   = verify.responseXML; 
	         var status        = xmlDocument.getElementsByTagName('check').item(0);  
				var acctStatus    = status.getAttribute('account');
				var fcwebStatus   = status.getAttribute('fcweb');
				
            if (fcwebStatus == 'Yes') {
               fcweb_userid = true;
            } else {
               fcweb_userid = false;
            }

            if (acctStatus == 'EXISTS')	{	

					passwdDiv.style.display = '';
               newAccountDiv.style.display = 'none';
               window.location.hash = "ACCOUNTFOUND";  // move to the correct location on the page

				} else {
               
               //
               //  New accounts must be email addresses
               //
               if (ValidateAccountID(document.SIGNUP,true)) {             

                  passwdDiv.style.display 	= 'none';
                  newAccountDiv.style.display = '';
      
                  var accountID = document.getElementById('ACCOUNTID');
                  var email = document.getElementById('EMAIL');
                  email.value = accountID.value;
                  email = document.getElementById('EMAILREF');
                  email.innerHTML = '<b>' + accountID.value + '</b>';
                  window.location.hash = "ACCOUNTNOTFOUND";  // move to the correct location on the page

               } else { 
                  passwdDiv.style.display 	 = 'none';
                  newAccountDiv.style.display = 'none';
               }
            }

            EnableCheckAccountButton();
            verifyWorking = false;    

			//}
			//catch (e)
			{
				;
			}

		} else {
         ;
      }
	}
}

//-----    Verify Information for Existing Account is Present and Submit  -----

function VerifyExistingInfo(theform)
{
   if (!ValidateAccountID(theform,!fcweb_userid)) return false;

	if (trim(theform.PASSWORD.value).length == 0)
	{
      alert ("You must enter a password.  Please try again.");
	   theform.PASSWORD.select();
  	   return false;
	}

   if (theform.ENTRYNICK1 && !CheckTeamName(theform.ENTRYNICK1)) return false;
  
   if (theform.ENTRYNICK2 && trim(theform.ENTRYNICK2.value).length > 0 && !CheckTeamName(theform.ENTRYNICK2)) return false;

   if (theform.LGNAME && !CheckLeagueName(theform.LGNAME)) return false;
   
   if (theform.REFERRER && trim(theform.REFERRER.value).length > 0 && !checkNatural(theform.REFERRER.value, theform.REFERRER.value.length))
   {
	   alert("You must enter a valid referring league ID.  If you were not referred to us by another RTSports league then leave this field blank.");
	   return false;
   }

   theform.submit();
}

//-----    Call AJAX and Check Nickname and Referrer  -----

function ValidateNewInfo()
{
   var eMailElement = document.REGISTER.EMAIL;
	eMailElement.value = trim(eMailElement.value);
	if (eMailElement.value.length == 0)
	{
		alert('Your account ID must be a valid e-mail address.');
		document.REGISTER.EMAIL.select();
		return false;
	}
	var eMailValid = checkEmail(eMailElement.value);
	if (eMailValid == 2)  // bad email
	{
		alert ('The e-mail address ' + eMailElement.value + ' is not valid.  Please re-enter a valid e-mail address and try again.');
		document.REGISTER.EMAIL.select();
		return false;
	}
	if (eMailValid == 1)	// Close to good e-mail
	{
		alert('The e-mail address ' + eMailElement.value + ' does not appear to be valid.  Please re-enter a valid e-mail address and try again.');
		document.REGISTER.EMAIL.select();
		return false;
	}


    if (document.REGISTER.EMAIL.value != document.REGISTER.EMAILVERIFY.value)
    {
        alert ("Email verification error.  Re-enter and verify the email and try again.")
		document.REGISTER.EMAIL.select();
    	return false;
    }


	if (!checkPassword(trim(document.REGISTER.PASSWORD.value)))
	{
        alert ('Your password must be 6 characters long and contain only printable characters.  Re-enter the password and try again.')
		document.REGISTER.PASSWORD.select();
    	return false;
	}

	if (checkEasyPassword(trim(document.REGISTER.PASSWORD.value)))
	{
       alert ("That password is too easy to guess try again.  Please try again.");
	   document.REGISTER.PASSWORD.select();
  	   return false;
	}

    if (document.REGISTER.PASSWORD.value != document.REGISTER.VERIFY.value)
    {
        alert ("Password verification error.  Re-enter and verify the password and try again.")
		document.REGISTER.PASSWORD.select();
    	return false;
    }

    if (!document.REGISTER.DISCLAIMER.checked)
    {
        alert("You must check the box agreeing to the terms and conditions of use before registering.")
        return false;
    }

	if (document.REGISTER.QUESTION.value == "NONE")
	{
        alert ('Please select a secret question, you will need it if you forget your password.')
    	return false;
	}

	if (trim(document.REGISTER.ANSWER.value).length < 1)
	{
        alert ('Please provide a secret answer, you will need it if you forget your password.')
		document.REGISTER.ANSWER.select();
    	return false;
	}

	if (trim(document.REGISTER.FIRSTNAME.value).length < 1)
	{
        alert ('Please enter your first name.')
		document.REGISTER.FIRSTNAME.select();
    	return false;
	}

	if (trim(document.REGISTER.LASTNAME.value).length < 1)
	{
        alert ('Please enter your last name.')
		document.REGISTER.LASTNAME.select();
    	return false;
	}

	if (trim(document.REGISTER.STREETADDRESS.value).length < 1)
	{
        alert ('Please enter your address of residence.')
		document.REGISTER.STREETADDRESS.select();
    	return false;
	}

	if (trim(document.REGISTER.CITY.value).length < 1)
	{
        alert ('Please enter your city of residence.')
		document.REGISTER.CITY.select();
    	return false;
	}

	if (document.REGISTER.STATE.value == "INVALID")
	{
        alert ('Please enter your state/province of residence.')
		document.REGISTER.STATE.select();
    	return false;
	}

	if (trim(document.REGISTER.ZIP.value).length < 1)
	{
        alert ('Please enter your zip/postal code.')
		document.REGISTER.ZIP.select();
    	return false;
	}

	if (document.REGISTER.COUNTRY.value == "INVALID")
	{
      	alert ('Please enter your country of residence.')
    	return false;
	}

	if (trim(document.REGISTER.AGE.value).length < 1)
	{
        alert ('Please enter your age.')
		document.REGISTER.AGE.select();
    	return false;
	}
	else if (!checkNatural(document.REGISTER.AGE.value, document.REGISTER.AGE.value.length))
	{
        alert ('Please enter a valid age.')
		document.REGISTER.AGE.select();
    	return false;
	}
	else if (parseInt(document.REGISTER.AGE.value) <= 13)
	{
        alert ('You must be at least 14 years of age to register.')
		document.REGISTER.AGE.select();
    	return false;
	}

   if (document.REGISTER.ENTRYNICK1 && !CheckTeamName(document.REGISTER.ENTRYNICK1)) return false;
   
   if (document.REGISTER.ENTRYNICK2 && document.REGISTER.ENTRYNICK2.value.length > 0 && !CheckTeamName(document.REGISTER.ENTRYNICK2)) return false;

   if (document.REGISTER.LGNAME && !CheckLeagueName(document.REGISTER.LGNAME)) return false;
   
   if (document.REFERRER && trim(document.REFERRER.value).length > 0 && !checkNatural(document.REFERRER.value, document.REFERRER.value.length))
   {
	   alert("You must enter a valid referring league ID.  If you were not referred to us by another RTSports league then leave this field blank.");
	   return false; 
   }

	if (document.REGISTER.FIND[0])
	{
		if (!(document.REGISTER.FIND[0].checked || document.REGISTER.FIND[1].checked || 
			   document.REGISTER.FIND[2].checked || document.REGISTER.FIND[3].checked || 
			   document.REGISTER.FIND[4].checked || document.REGISTER.FIND[5].checked))
		{
			alert ("You must select how you found out about our service.\n" +
				   "Please select the appropriate button claiming how you discovered our site and try again.")
			return false;
		}
		if (document.REGISTER.FIND[0].checked && document.REGISTER.Magazine_Source.selectedIndex == 0)
		{
			alert ("You specified that you discovered our site from a magazine, but you did not specify the magazine. " +
				   "Please select a magazine and try again.")
			return false;
		}

		if (document.REGISTER.FIND[1].checked && document.REGISTER.Engine_Source.selectedIndex == 0)
		{
			alert ("You specified that you discovered our site using a search engine, but you did not specify which one. " +
				   "Please select a search engine and try again.")
			return false;
		}

		if (document.REGISTER.FIND[2].checked && document.REGISTER.Website_Source.selectedIndex == 0)
		{
			alert ("You specified that you discovered our site from a website or message board, but you did not specify which one. " +
				   "Please select a website or message board and try again.")
			return false;
		}

		if (document.REGISTER.FIND[3].checked && trim(document.REGISTER.Account.value).length == 0)
		{
			alert ("You specified that you are a returning customer or were referred by an existing customer, but you did not " +
				   "specify the referring account ID or league name.  Please enter this information and try again.")
			return false;
		}

		if (document.REGISTER.FIND[4].checked && trim(document.REGISTER.Banner.value).length == 0)
		{
			alert ("You specified that you found out about our service from a banner or link on a web page, but you did not " +
				   "specify which page.  Please enter the web page and try again.")
			return false;
		}

		if (document.REGISTER.FIND[5].checked && trim(document.REGISTER.Other_Source.value).length == 0)
		{
			alert ("You specified that you found out about our service from a source not listed, but you did not " +
				   "specify the source.  Please enter the source and try again.")
			return false;
		}
	}
	
	if (trim(document.REGISTER.NICKNAME.value).length < 1) 
	{
		alert ('Please enter a nickname to be used as your name in our forums.');
		document.REGISTER.NICKNAME.focus();
		document.REGISTER.NICKNAME.select();
		return false;
	} 

	if (!checkNickname(document.REGISTER.NICKNAME.value)) 
	{
      alert ('Your forum nickname must be at least 4 characters long and can contain letters, numbers and underscores.  Re-enter the nickname and try again.')
		document.REGISTER.NICKNAME.select();
		return false;
    }
	
	return true;
}

function VerifyNewInfo(theform)
{
   if (!ValidateNewInfo()) return;
   if (!verifyWorking && verify) {
      var params = "NICK=" + escape(theform.NICKNAME.value);
      if (theform.REFERRER) params += "&REF=" + escape(theform.REFERRER.value);
      SubmitVerification(params, VerifyNewAccountHandler);
   }
}

function VerifyNewAccountHandler() 
{
	if (verify.readyState == 4) {
		if (verify.responseText.indexOf('invalid') == -1)	{
			//try {
            var SubmitForm = true;
				var nickStatusDiv = document.getElementById('nicknameStatus');
				var refStatusDiv 	= document.getElementById('referrerStatus');
				var xmlDocument   = verify.responseXML; 
	         var status        = xmlDocument.getElementsByTagName('check').item(0);  
				var refStatus     = status.getAttribute('referrer');
				var nickStatus    = status.getAttribute('nickname');
				
            if (refStatusDiv){
               if (refStatus == 'NOTEXISTS') {				
                  refStatusDiv.innerHTML = '<b>&lt;&lt; INVALID LEAGUE ID</b>';
                  alert ('The referring league ID you entered does not match a valid RTSports.com league ID.');
                  document.REGISTER.REFERRER.select();
                  SubmitForm = false;
               } else {
                  refStatusDiv.innerHTML = '&nbsp;';
               }
            }

            if (nickStatus == 'EXISTS') {
               nickStatusDiv.innerHTML = '<b>&lt;&lt; NICKNAME TAKEN</b>';
               alert ('The forum nickname ' + document.REGISTER.NICKNAME.value + ' has been taken.');
               document.REGISTER.NICKNAME.select();
               SubmitForm = false;
			   } else {
               nickStatusDiv.innerHTML = '&nbsp;';
            }

            if (SubmitForm) {
               document.REGISTER.submit();
            } else {
               EnableCheckAccountButton();
               verifyWorking = false;    
            }
			//}
			//catch (e)
			//{
         //   document.REGISTER.submit();
			//}
		} else {
			document.REGISTER.submit();
      }
	}
}
