var hasSubmitted = false;
var onBlurError = 0;
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
var getForm = '';
var isEmailExist    = false;
var isUserNameExist = false;
var isPasswordGood  = true;

// error framework
errorOpen = "<div class='reg_error'>";
errorClose = "</div>";

// validation error messages
requiredMsg = "Oops, you forgot to fill this in and it's required.";
noEmailMatchMsg = "Oops! The email addresses you entered do not match. Try again.";
invalidEmail = "<div id='invalidEmail'>Something is incorrect with the format of the email address you entered.<br \/> Here is an example of a valid email format: martha@marthastewart.com.</div>";
noPasswordMatchMsg = "Oops! The passwords you entered do not match. Try again.";
passwordNotStrong = "To provide optimum security, we require your password be between six and fifteen characters. It is case sensitive. Please try again.";
userNameNotFit = "Username cannot include special characters and spaces, and must be between three and twenty three characters. Please try again.";
errorMsgUserName = "Unfortunately, that user name has already been chosen by another contributor - - great minds really do think alike! Please try another.";
errorMsgEmail = "Sorry, a contributor - - maybe even you - - already registered with that email address. Please choose another.";

// field confirmed
confirmedField = "<img src='/images/assets/module/registration/reg_confirmed_field.gif' alt='confirmed' \/>";

// hint framework
hintOpen = "<div class='reg_hint'><div class='reg_message_outer'><div class='reg_message_inner'><div>";
hintClose = "</div></div></div></div>";

// field hint messages

email_address_hint = "Type in your email address. Example: martha@marthastewart.com";
confirm_email_address_hint = "Type in your email address again, just to make sure we have it right.";
reg_password_hint = "Your password must be at least six characters long.";
reg_confirm_password_hint = "Type in your password again.";
reg_username_hint = "This is what you'll be known as!";
reg_first_name_hint = "Type in your first name.";
reg_last_name_hint = "Type in your last name.";
reg_street_hint = "You won't get lots of extra mail, and this will help Martha Stewart serve you more efficiently.";
reg_city_hint = "Type in your city.";
reg_state_hint = "Type in your state or province.";
reg_zip_code_hint = "Type in your ZIP or postal code.";
reg_bday_hint = "We're big on birthdays - - tell us yours!";
username_hint = "This is what you'll be known as!";
reg_year_of_birth_hint = "Select your birth year.";
male_hint="";
female_hint="";


function createAccountValidation() {
	if($('registration')) {
		getForm = 'registration_form';
	} else if($('account_settings_wrapper')) {
		getForm = 'account_settings_form';
	}
	var getAllRequired = document.getElementsByClassName("required");
	for(i=0; i<getAllRequired.length; i++) {
		getAllRequired[i].onblur = function() {
			var getId = this.getAttribute("id");
			if(this.value == 0) {
				$(getId + "-M").innerHTML = errorOpen + requiredMsg + errorClose;
				$(getId).style.background = "#FBEEE8";
				//return false;
			} else {
				$(getId + "-M").innerHTML = "";
				$(getId).style.background = "";
				if(getId == "email_address") { 
					validateEmail(); 
				} 
				if(getId == "confirm_email_address") { 
					validateEmail(1); 
				}
				if(getId == "reg_password") { 
					validatePassword(0); 
				}
				if(getId == "reg_confirm_password") { 
					validatePassword(1);
				}
				if(getId == "reg_username") {
					validateUsername();
				}
			}
		}
	}
}

function validateEmail(confirm) {	
	var email = $('email_address').value;
	//alert("passEmailFormatCheck="+passEmailFormatCheck(email) );
	
	if(!passEmailFormatCheck(email)) 
      {
		if(confirm == 1) {
			$("confirm_email_address-M").innerHTML = errorOpen + invalidEmail + errorClose;
			$("confirm_email_address").style.background = "#FBEEE8";            
			onBlurError = 1;
			return false;
		} else {
			$("email_address-M").innerHTML = errorOpen + invalidEmail + errorClose;
			$("email_address").style.background = "#FBEEE8";           
			onBlurError = 1;
			return false;
			}
	} 
	
    	
          if(confirm == 1) 
          { 
		     checkEmailMatch();
	      }
          else
          { 
             fCheckEmail(email);
          }
}

function passEmailFormatCheck(email)
{ 
  if (email=='')
  { 
       return false;  
  }
  else if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(email)== false)
  { 
       return false;  
  }
  else
  {
      return true;
  }
} 

function checkEmailMatch() {
	var emailAddress = $('email_address');
	var confirmEmailAddress = $('confirm_email_address');
	if(emailAddress.value != confirmEmailAddress.value) {
		$("confirm_email_address-M").innerHTML = errorOpen + noEmailMatchMsg + errorClose;
		$("confirm_email_address").style.background = "#FBEEE8";
            //$(getForm).confirm_email_address.focus();
		onBlurError = 1;
		return false;
	} 
	else 
	{  // no error and match, show confirm image
		onBlurError = 0;        
		document.getElementById("confirm_email_address-M").innerHTML = confirmedField;		
	}
}


// for email backend validation
function fCheckEmail(email)
{   //alert('before calling ajax, validate email='+email);
	if(email!='')
		RegistrationValidationService.checkEmail(email,handleEmailCheck);
}
function handleEmailCheck(exists) {
    //alert('after calling ajax, exists='+exists);
	if(exists=='true')
        {   isEmailExist = true;
		    document.getElementById("email_address-M").innerHTML = errorOpen + errorMsgEmail +errorClose ; 
            onBlurError = 1;
            return false;
            //$(getForm).propID_email.focus();
        }
	else
	   { //show a check, not confirm 
		 //document.getElementById("email_address-M").innerHTML = confirmedField;
		 isEmailExist = false;
	   }
}

function fCheckUserName(userName)
{
	if(userName!='')
		RegistrationValidationService.checkUserName(userName,handleUserNameCheck);
}

function handleUserNameCheck(exists) {
if(exists=='true')
{ isUserNameExist=true;
 document.getElementById("reg_username-M").innerHTML = errorOpen + errorMsgUserName +errorClose;
 $("reg_username").style.background = "#FBEEE8";
 onBlurError = 1;
 return false;
 //$(getForm).propID_screen_name.focus();  
}	
else
{ isUserNameExist=false;
  document.getElementById("reg_username-M").innerHTML = confirmedField;
 }
}

function validatePassword(confirm) {
	var regPassword = $('reg_password');
	var regConfirmPassword = $('reg_confirm_password');
	if(confirm == 0) 
        { 
		if(regPassword.value.length < 6) 
        {   isPasswordGood = false;      
			$("reg_password-M").innerHTML = errorOpen + passwordNotStrong + errorClose;
			$("reg_password").style.background = "#FBEEE8";
		}
        else 
        {
			//$("reg_password-M").innerHTML = confirmedField;
			isPasswordGood = true;  
			onBlurError = 0;
		}
	} else {
		if(regConfirmPassword.value.length < 6) {
			$("reg_confirm_password-M").innerHTML = errorOpen + passwordNotStrong + errorClose;
			$("reg_confirm_password").style.background = "#FBEEE8";
			onBlurError = 1;
			isPasswordGood = false;  
			return false;
		} 
		else 
		{
			if(regPassword.value != regConfirmPassword.value) 
			{
				$("reg_confirm_password-M").innerHTML = errorOpen + noPasswordMatchMsg + errorClose;
				$("reg_confirm_password").style.background = "#FBEEE8";
				onBlurError = 1;
				isPasswordGood = false;  
				return false;
			} 
			else
			{   onBlurError = 0; 
			    isPasswordGood = true;  
			    $("reg_confirm_password-M").innerHTML = confirmedField;
			}
		}	
	}
}

function validatePasswordForMyAccount() {
  //alert('validatePasswrodForMyAccount 1');
  if (($(getForm).propID_pass1!=null) && ($(getForm).propID_pass1.value.length>0))
   {  
      //alert('validatePasswrodForMyAccount 2 user typed in sth new password='+ $(getForm).propID_pass1.value  );
	var regPassword = $('reg_password');
	var regConfirmPassword = $('reg_confirm_password');
     

        if(regPassword.value.length < 6) 
         { //alert('validatePasswrodForMyAccount 2.1');
          	$("reg_password-M").innerHTML = errorOpen + passwordNotStrong + errorClose;
			$("reg_password").style.background = "#FBEEE8";                      
             onBlurError = 1;
			 return false;
		}             
		else if(regConfirmPassword.value.length < 6) 
                { //alert('validatePasswrodForMyAccount 2.2');
			$("reg_confirm_password-M").innerHTML = errorOpen + passwordNotStrong + errorClose;
			$("reg_confirm_password").style.background = "#FBEEE8";
             onBlurError = 1;
			 return false;
		} 
		else if (regPassword.value != regConfirmPassword.value) 
		{     //alert('validatePasswrodForMyAccount 2.3');
			$("reg_confirm_password-M").innerHTML = errorOpen + noPasswordMatchMsg + errorClose;
			$("reg_confirm_password").style.background = "#FBEEE8";
                   onBlurError = 1;
                   return false;
		} 
		else
		{      onBlurError = 0; 
			$("reg_confirm_password-M").innerHTML = confirmedField;
                  return true;
		}
  }
  else			  
  {  //do not do validate if user not type in anything  
     //alert('validatePasswrodForMyAccount 3 no need to validate');  
     return true;
  }
}

function validateUsername() {
	    	
     var userName = $('reg_username');
     var succ1 = true;  // need local var because this is re-called by the same user
    
     //alert("validateUsername 1  succ1="+succ1);
     
    succ1 = isValidUserName(userName.value);
    
     //alert("validateUsername 2  succ1="+succ1);
     
     if( !succ1 ) 
      {         
				$("reg_username-M").innerHTML = errorOpen + userNameNotFit + errorClose;
				$("reg_username").style.background = "#FBEEE8";
				onBlurError = 1;
				return succ1;
                                //$(getForm).propID_screen_name.focus();
                                
	   } 
       else 
       {             
              //alert("validateUsername 3 run the ajax call for server side check on username ="+userName.value);             
              fCheckUserName(userName.value);
       }


}
	

function isValidUserName(s){
    // this is to conform KA's rule.
    if (s.length<3 || s.length>23) return false;
    
    var list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
    var i;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        
        if (list.indexOf(c)<0)  return false;
    }
   
    return true;
}


function fieldHint() {
	var getAllHints = document.getElementsByClassName("hintBubble");
	for(var i=0; i<getAllHints.length; i++) {
		getAllHints[i].onfocus = function() {
			var getId = this.getAttribute("id");
        this.style.backgroundColor = '#EDF7F7';
			$(getId + "-M").innerHTML =  hintOpen + eval(getId + "_hint") + hintClose;
			if(!$(getId).hasClassName("required")) {
				$(getId).onblur = function() {
					$(getId + "-M").innerHTML = "";
					$(getId).style.background = "";
				}
			}
		}	
	}
}

function onSubmitValidate(page) {
      
//alert("onSubmitValidate 1 page="+page +" hasSubmitted="+hasSubmitted); 
 
 if (page=="1") 
 {
		validateEmail(); 
		validateEmail(1); 
		validatePassword(0); 
		validatePassword(1);
		validateUsername();		
 }

//alert("onSubmitValidate 2 isEmailExist="+isEmailExist); 
//alert("onSubmitValidate 3 isUserNameExist="+isUserNameExist); 

  var error = 'false'; 
  var firstErrorField;
  var getAllRequired = document.getElementsByClassName("required");
      
	
       for(var i=0; i<getAllRequired.length; i++) 
        {   
           //alert("onSubmitValidate.validation 1 getAllRequired[i]="+getAllRequired[i].name);
           //alert("onSubmitValidate.validation 2 getAllRequired[i]="+getAllRequired[i].value.length);
           //alert("onSubmitValidate.validation 3 getAllRequired[i]="+getAllRequired[i].type);
     	    
           if (getAllRequired[i].name=='propID_gender')
             {  
               // gender is radion button, need to check if it is checked
               gender_choice = false;
               for (counter = 0; counter < $(getForm).propID_gender.length; counter++)
                {
                  if ($(getForm).propID_gender[counter].checked)
                  gender_choice = true; 
                }                   
               
               if(!gender_choice) 
                {			
			                   
                        if(error=='false')
                        	firstErrorField = getAllRequired[i];                                          
                        error = 'true';                                            
			      $("reg_gender-M").innerHTML = errorOpen + requiredMsg + errorClose;   

		}
            }           
           else
            {  // for text fields     
               
               if(getAllRequired[i].value.length == 0 || onBlurError == 1) 
                {			
                        if(error=='false')
                        	firstErrorField = getAllRequired[i];
                        // this focus is needed for showing all error bf submit
                        //getAllRequired[i].focus();
                        getAllRequired[i].blur();
                        error = 'true';

		}
            }
          
           
        } // end for


  if (page=="2")
   {  
      //alert("onSubmitValidate 3 validatePasswordForMyAccount");
      if ( !validatePasswordForMyAccount())
      return false;
   }

	
	
   if(error=='true')
   {
   	//if (page=="1") firstErrorField.focus();   // page2 has different tag, focus will cause js error.
   	return false; 	
   }
   
   // verify birthday
   // after weddingwire, birthday is optional, but yyyy is required.
        //mm = $(getForm).propID_dob_mm.value;
        //dd = $(getForm).propID_dob_dd.value;
        mm = '01';
        dd = '01';
        //yyyy = $(getForm).propID_dob_yyyy.value;
        yyyy = $(getForm).propID_year_of_birth.value;
        dob = mm +'/'+dd+'/'+yyyy ;  
        
        //alert('dob='+dob);
  
       if (isDate(dob)==false)
       {  // not a valid date	
       	  error = 'true';
		  return false;
       }
       else if (isAgeValid(yyyy, mm, dd, 13)==false)
       {  // not older than 13        
          error = 'true';
		  return false;
       }
       else
       {   // need to setup 2 more hidden params
          $(getForm).propID_dob.value = dob ;
          //$(getForm).propID_year_of_birth.value = yyyy;    
       }
  
  // verify accept terms and conditions
 
  accept = $(getForm).propID_status.value;   
 
  //alert('accept='+accept);
  
  if ( !(   (accept=="1") 
         || ($(getForm).propID_status.checked)) 
     )
  {    alert ('You need to acknowledge our Privacy Policy and agree to our Terms and Conditions before creating an account.');
       return false;  
  }
  else
  {   $(getForm).propID_status.value="1";
  }   
    
 
  if (!isCookieOn())
  {    alert ('You need to enable cookies on your browser.');
       return false;  
  }
      
 //replace the username with confirmed email + date to bypass some Account issues, this is called by register only:
   if ((page==1)&&($(getForm).propID_email.value.length>0))
   {  
      var today = new Date();
            var month = today.getMonth()+1;
            var year = today.getYear();
            var day = today.getDate();
            if(day<10) day = "0" + day;
            if(month<10) month= "0" + month;
            if(year<1000) year+=1900;
            var yyyymmdd = "_"+year+month+day ; 
     $(getForm).propID_username.value=$(getForm).propID_email.value+yyyymmdd;
     
     //alert("username="+$(getForm).propID_username.value );

   } 

  if (($(getForm).optout!=null) && ($(getForm).optout.checked==true))
  {   $(getForm).propID_optout.value="1";}
  else
  {   $(getForm).propID_optout.value="0";}
      
  
  //alert("onSubmitValidate before submit 1 onBlurError =" +onBlurError);
  if (onBlurError==1)
  { //alert("onSubmitValidate before submit 1 onBlurError =" +onBlurError);
    return false;
  } 
 
  //add these final checks in case onBlurError check failure
  if (!isPasswordGood)
  {  //alert ('Sorry, password is bad.');   
     return false;
  }
 
  if (isEmailExist==true)
  {    alert ('Sorry, a contributor - - maybe even you - - already registered with that email address. Please choose another.');    
       //do not use the focus which causes more trouble  
       //$(getForm).propID_email_address.focus();
       return false;  
  }
  
  if (isUserNameExist==true)
  {    alert ('Unfortunately, that user name has already been chosen by another contributor - - great minds really do think alike! Please try another.');
       //do not use the focus which causes more trouble 
       //$(getForm).propID_screen_name.focus();
       return false;  
  }
  
 //alert("onSubmitValidate before submit 2");
 
// the following code to avoid duplicate submit
if (hasSubmitted == false) 
{ 
   hasSubmitted = true; 
   $(getForm).submit();
 }
 else 
{ 
   alert("Be patient, please wait...");
} 


}

function checkAcceptTerms()
{
  accept = $(getForm).propID_status.value;    

  if ( !(   (accept=="1") 
         || ($(getForm).propID_status.checked)) 
     )
  {    alert ('You need to acknowledge our Privacy Policy and agree to our Terms and Conditions.');
       //$(getForm).propID_status.focus(); 
       return false;  
  } 
  else
  {    return true;
  }
}

function isCookieOn(){
var d = new Date();
         chkcookie2 = (d.getTime() + '');
         document.cookie = "chkcookie2=" + chkcookie2 + "; path=/";
         if (document.cookie.indexOf(chkcookie2,0) < 0) 
         {      
           return false;
         }   
         else 
         { return true;
         }
}

function isInteger(s){
   var i;
    for (i = 0; i < s.length; i++){  
     // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
//alert('isDate, str='+dtStr);
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	
	if (pos1==-1 || pos2==-1)
	{
		alert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12)
	{
		alert("Please enter a valid month");
		//$(getForm).propID_dob_mm.focus();
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		alert("Please enter a valid day");
		//$(getForm).propID_dob_dd.focus();
		return false;
	}
	
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);		
		$(getForm).propID_year_of_birth.focus();
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date");
		return false;
	}
return true;
} 
 
function isAgeValid(y, m, d, minYear)
{
	var millennium =new Date(y, m-1, d) //Month is 0-11 in JavaScript
        var today=new Date()
        //Get 1 day in milliseconds
        var one_day=1000*60*60*24

        var diff = (today.getTime()-millennium.getTime())/one_day/365 - minYear;


	if (diff < 0)
        {
		alert("We admire your passion, but you must be 13 or older to join.");
		//$(getForm).propID_dob_yyyy.focus();
		$(getForm).propID_year_of_birth.focus();
		return false;
	}
	
return true;
} 

addLoadEvent(createAccountValidation);
addLoadEvent(fieldHint);