var InviteLinkValid = true;
var EmailAddressValid = true;

function validateString(str, minlength)
{
	if(!str)
		return false;

	str = new String(str);
	if(str.replace(/ /g, '').length<minlength)
		return false;

	return true;
}

function validateEmail(str)
{
	var emailRegEx = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
	if(str.match(emailRegEx))
		return true;
	else
		return false;
}

function validateInvite(str)
{
	var inviteRegEx = /[a-zA-Z0-9\-\_]{3,50}/;
	if(str.match(inviteRegEx))
		return true;
	return false;
}

function validateRequest()
{
	var fname = gEl('firstName-input').value;
	var lname = gEl('lastName-input').value;
	var address = gEl('address-input').value;
	var city = gEl('city-input').value;
	var postal = gEl('postal-input').value;
	var countryId = gEl('countryId').value;
	
	var errors = new Array();
	var i=0;
	var div = gEl('errorDiv');

	if(!validateString(fname, 2))
		errors[i++]="Enter First Name";
	
	if(!validateString(lname, 2))
		errors[i++]="Enter Last Name";
	
	if(!validateString(address, 2))
		errors[i++]="Enter Address";
	
	if(!validateString(city, 2))
		errors[i++]="Enter City";

	
	if ((countryId == 230 && gEl('USStateId').value == '') || (countryId == 39 && gEl('CanadaStateId').value == '') || (countryId != 230 && countryId != 39 && gEl('NonUSState').value == ''))
		errors[i++]="Select State";
	
	if(!validateString(postal, 3))
		errors[i++]="Enter Phone";
	
	if (countryId == '' || countryId == 0)	
		errors[i++]="Select Country";
	
	
	var errorContent = 'Please correct the following:<ul>';
	for(i=0;i<errors.length;i++)
	{
		errorContent += ('<li>'+errors[i]+'</li>');
	}
	errorContent += '</ul>';
	div.innerHTML = errorContent;

	if(errors.length>0)
	{
		gEl("errorDivContainer").style.visibility = "visible";
		window.scroll(0,0);
		return false;
	}
	else
	{
		gEl("errorDivContainer").style.visibility = "hidden";
		return true;
	}
	
	
}
function validateAccount()
{
	var email = gEl('email-input').value;
	var password = gEl('password-input').value;
	var securityQuestionId = document.getElementById('securityQuestionId').value;
	var answer = document.getElementById('answer-input').value;
	var zip = document.getElementById('postal-input').value;
	var countryId = document.getElementById('countryId').value;
	
	var ethnicityId = (gEl('ethnicityId')) ? gEl('ethnicityId').value : 1;
	var maritalId = gEl('maritalId').value;
	var incomeId = gEl('incomeId').value;
	var genderId = (gEl('genderId')) ? gEl('genderId').value : 1;
	var homeId = gEl('homeId').value;
	
	var alcoholId = gEl('alcoholId').value;
	var smokerId = gEl('smokerId').value;
	
	var errors = new Array();
	var i=0;

	if(!validateString(email, 1))
		errors[i++]="Enter Email";
	else if(!validateEmail(email))
		errors[i++] = "Enter a valid Email";
	
	if(!validateString(password, 4))
		errors[i++]='Enter Password. Minimum 4 characters';
	
	
	if(!validateString(securityQuestionId, 1))
		errors[i++]='Select Security Question';
	if(!validateString(answer, 3))
		errors[i++]='Enter Answer. Minimum 3 characters';
	if (!InviteLinkValid)
		errors[i++] = "Invalid Invite Link";
	
	if(!validateString(zip, 3))
		errors[i++]='Enter zip/postal code';
	if(!validateString(countryId, 1))
		errors[i++]='Select Country';
	
	if ((countryId == 230 && gEl('USStateId').value == '') || (countryId == 39 && gEl('CanadaStateId').value == '') || (countryId != 230 && countryId != 39 && gEl('NonUSState').value == ''))
		errors[i++]="Select State";
	
	
	if(!validateString(ethnicityId, 1))
		errors[i++]='Select Ethnicity';
	if(!validateString(maritalId, 1))
		errors[i++]='Select Marital Status';
	if(!validateString(incomeId, 1))
		errors[i++]='Select Income';
	if(!genderId)
		errors[i++]='Select Gender';
	if(!homeId)
		errors[i++]='Select Homeowner';
	if(!alcoholId)
		errors[i++]='Select Alcohol';
	if(!smokerId)
		errors[i++]='Select Tobacco';
	if (gEl('monthId') && gEl('dayId') && gEl('yearId'))
	{
		var month = document.getElementById('monthId').value;
		var year = document.getElementById('yearId').value; 
		var day = document.getElementById('dayId').value;
		if(!validateString(day, 1) && !validateString(month, 1) && !validateString(year, 1))
			errors[i++]='Select Birthday';
		else if (!validateDateN(month + '/' + day + '/' + year))
			errors[i++]='Select correct Birthday';
	}
		
	var div = gEl('errorDiv');
	var errorContent = 'Please correct the following:<ul>';
	for(i=0;i<errors.length;i++)
		errorContent += ('<li>'+errors[i]+'</li>');
	errorContent += '</ul>';
	div.innerHTML = errorContent;

	if(errors.length>0)
	{
		gEl("errorDivContainer").style.visibility = "visible";
		window.scroll(0,0);
		return false;
	}
	else
	{
		gEl("errorDivContainer").style.visibility = "hidden";
		return true;
	}
}

/* --------------- registr form ------------------------------------------------*/

var regInviteCheckedInDB_History = new Array();
/*
regInviteCheckedInDB_History[(str)invateLink] = (bool)result;
*/

var regLastInvLinkCheckedInDB_History = ''; // last state of invite link

/*
* @param (obj) o_invOBJ - is object of invite link field
* @return (bool)
*/
function CheckInviteLinkInDB(o_invOBJ)
{
  InviteLinkValid = false;
  gEl('InviteEr').style.visibility = 'hidden';
  gEl('InviteErM').innerHTML = '';
  var errorStr = '';

  if (typeof(o_invOBJ) == 'object')
  {
     var o_vl = o_invOBJ.value;
     regLastInvLinkCheckedInDB_History = o_vl;

     if (o_vl.length > 0)
     {
        if (validateInvite(o_vl))
        {
           var RegEx1 = /^\d{5,6}\w{2,3}$/;
           var RegEx2 = /^\w{3}\d{1}$/;

           if(!o_vl.match(RegEx1) && !o_vl.match(RegEx2))
           {
              if (typeof(regInviteCheckedInDB_History) != 'undefined')
              {
                 if (typeof(regInviteCheckedInDB_History[ o_vl ]) != 'undefined')
                 {
                        if (!regInviteCheckedInDB_History[ o_vl ])
                        {
                            InviteLinkValid = true;
                        }
                        else
                        {
                            errorStr = 'That one is taken. Try again!';
                        }
                 }
                 else
                 {
                    //alert("Active AJAX!");
                    AjaxAfterLoadCall = 'CheckInvLinkAfterPost';
                   	AjaxRequestPost('/ajax/', 'get=v_invite&s=' + o_vl, 'null');
                 }
              }
           }
           else errorStr = 'Invalid Invite Link';
        }
        else errorStr = 'Invalid Invite Link';
     }
  }

  if (errorStr.length > 0 )
  {
    gEl('InviteEr').style.visibility = 'visible';
    gEl('InviteErM').innerHTML = errorStr;
  }

  return false;
}

function CheckInvLinkAfterPost()
{
  if (AjaxRequestResult != '')
 	{
    		if (typeof(regInviteCheckedInDB_History) != 'undefined' && typeof(regLastInvLinkCheckedInDB_History) != 'undefined')
      {
         if (regLastInvLinkCheckedInDB_History.length > 0)
            regInviteCheckedInDB_History[ regLastInvLinkCheckedInDB_History ] = (AjaxRequestResult == 'ok' ? false : true);
      }

      InviteLinkValid = (AjaxRequestResult == 'ok' ? false : true);

      if (AjaxRequestResult != 'ok')
      {
         gEl('InviteEr').style.visibility = 'visible';
         gEl('InviteErM').innerHTML = AjaxRequestResult;
      }
 	}
  else InviteLinkValid = false;
}


function validateForm(formId)
{
     tErrors = new Array();
    	tErrors1 = new Array();
    	tErrors2 = new Array();
    	tErrors3 = new Array();

     var email = gEl('email').value;
    	var emailRetype = gEl('emailRetype').value;
    	var password = gEl('registerPassword').value;
    	var passwordRetype = gEl('registerPasswordRetype').value;
    	var securityQuestion = gEl('securityQuestion').value;
    	var securityAnswer = gEl('securityAnswer').value;
    	var securityAnswerRetype = gEl('answerRetype').value;

     var invite_link = gEl('invite_link').value;

    	var FirstName = gEl('FirstName').value;
    	var LastName = gEl('LastName').value;

    	var zip = gEl('zip').value;
    	var country = gEl('countrySelect').value;
    	var month, year, day, agree;

    	month = gEl('month').value;
    	year = gEl('year').value;
    	day = gEl('day').value;

    	var ethnicity = gEl('Ethnicity').value;
    	var maritalStatus = gEl('MaritalStatus').value;
    	var income = gEl('IncomeRange').value;
    	var gender = gEl('Gender').value;
    	var homeOwner = gEl('OwnHome').value;
    	var alcohol = gEl('Alcohol').value;
    	var smoker = gEl('Smoker').value;

    	var errors = new Array();
    	var i=0;

    	if(!validateString(email, 1))
    	{
     		errors[i]="Enter Email";
       tErrors1[tErrors1.length] = "Email Address";
     		i++;
    	}
    	else if(!validateEmail(email))
    	{
     		errors[i] = "Enter a valid Email";
       tErrors1[tErrors1.length] = "Email Address";
     		i++;
    	}
    	else if (!EmailAddressValid)
    	{
     		errors[i] = "Enter a valid Email";
       tErrors1[tErrors1.length] = "Email Address";
     		i++;
    	}
     else if(email!=emailRetype)
    	{
     		errors[i]='The Email you entered do not match';
       tErrors1[tErrors1.length] = "Email Address";
     		i++;
    	}

    	if (!InviteLinkValid || invite_link == '')
    	{
     		errors[i] = "Invalid Invite Link";
       tErrors2[tErrors2.length] = "Invite Link";
     		i++;
    	}

    	if(!validateString(password, 4))
    	{
     		errors[i]='Enter Password. Minimum 4 characters';
       tErrors1[tErrors1.length] = "Password";
     		i++;
    	}
     else if(password!=passwordRetype)
    	{
     		errors[i]='The passwords you entered do not match';
       tErrors1[tErrors1.length] = "Password";
     		i++;
    	}

    	if(!validateString(securityQuestion, 1))
    	{
     		errors[i]='Select Security Question';
       tErrors1[tErrors1.length] = "Question";
     		i++;
    	}

    	if(!validateString(securityAnswer, 3))
    	{
     		errors[i]='Enter Answer. Minimum 3 characters';
       tErrors1[tErrors1.length] = "Answer";
     		i++;
    	}
     else if(securityAnswer!=securityAnswerRetype)
    	{
     		errors[i]='The Answers you entered do not match';
       tErrors1[tErrors1.length] = "Answer";
     		i++;
    	}

    	if (!validateString(FirstName, 1))
    	{
     		errors[i]='Enter First Name';
       tErrors3[tErrors3.length] = "First Name";
     		i++;
    	}

    	if (!validateString(LastName, 1))
    	{
     		errors[i]='Enter Last Name';
       tErrors3[tErrors3.length] = "Last Name";
     		i++;
    	}

    	if(!validateString(zip, 3))
    	{
     		errors[i]='Enter zip/postal code';
       tErrors3[tErrors3.length] = "Postal Code";
     		i++;
    	}

    	if(!validateString(country, 1))
    	{
     		errors[i]='Select Country';
       tErrors3[tErrors3.length] = "Country";
     		i++;
    	}

    	if(!validateString(day, 1) && !validateString(month, 1) && !validateString(year, 1))
    	{
     		errors[i]='Select Birthday';
       tErrors3[tErrors3.length] = "Birthday";
     		i++;
    	}

    	if(!validateString(ethnicity, 1))
    	{
     		errors[i]='Select Ethnicity';
       tErrors3[tErrors3.length] = "Ethnicity";
     		i++;
    	}

    	if(!validateString(maritalStatus, 1))
    	{
     		errors[i]='Select Marital Status';
       tErrors3[tErrors3.length] = "Marital Status";
     		i++;
    	}

    	if(!validateString(income, 1))
    	{
     		errors[i]='Select Income';
       tErrors3[tErrors3.length] = "Income";
     		i++;
    	}

    	if(!validateString(gender,1))
    	{
    		 errors[i]='Select Gender';
       tErrors3[tErrors3.length] = "Gender";
    		 i++;
    	}

    	if(!validateString(homeOwner, 1))
    	{
     		errors[i]='Select Homeowner';
       tErrors3[tErrors3.length] = "Homeowner";
     		i++;
    	}

    	if(!validateString(alcohol, 1))
    	{
     		errors[i]='Select Alcohol';
       tErrors3[tErrors3.length] = "Alcohol";
     		i++;
    	}

    	if(!validateString(smoker,1))
    	{
     		errors[i]='Select Tobacco';
       tErrors3[tErrors3.length] = "Tobacco";
     		i++;
    	}

    	if (tErrors1.length > 0 || tErrors2.length > 0 || tErrors3.length > 0)
     {
		      showValidationAlertEx();
    		  return false;
    	}
    	else
    	{
    		  return true;
    	}
}


function showValidationAlertEx()
{
   	window.scroll(0,0);

   	e = '';
   	if (tErrors1.length > 0)
   	{
     		for (var i = 0; i < tErrors1.length; i++)
     			e =  e + "<span>" + tErrors1[i] + "</span>";
   	}
   	gEl('erError1').innerHTML = e;

   	e = '';
   	if (tErrors2.length > 0)
   	{
     		for (var i = 0; i < tErrors2.length; i++)
     			e =  e + "<span>" + tErrors2[i] + "</span>";
   	}
   	gEl('erError2').innerHTML = e;

   	e = '';
   	if (tErrors3.length > 0)
   	{
      		for (var i = 0; i < tErrors3.length; i++)
      			e =  e + "<span>" + tErrors3[i] + "</span>";
   	}
   	gEl('erError3').innerHTML = e;

   	show('errorEx');
}


var re_dt = /^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/;
function validateDateN(s_date)
{
	// check format
	if (!re_dt.test(s_date))
		return false;

	// check allowed ranges	
	if (RegExp.$1 > 12 || RegExp.$2 > 31 || RegExp.$3 < 1900 )
		return false;

	// check number of day in month
	var dt_test = new Date(RegExp.$3, Number(RegExp.$1-1), RegExp.$2);

	if (dt_test.getMonth() != Number(RegExp.$1-1))
		return false;

	return true;
}

function stateSet(countryId)
{
	if (gEl('state-edit'))
		setField('state');
		
	gEl('NonUSState').style.display = (countryId != 230 && countryId != 39) ? 'block' : 'none';
	gEl('USStateId').style.display = (countryId == 230) ? 'block' : 'none';
	gEl('CanadaStateId').style.display = (countryId == 39) ? 'block' : 'none';
}