// helper function to get the status of a checkbox
function getChecked(checkBoxName) {
  return $('input[name=' + checkBoxName + ']').attr('checked');
}

// helper function to get the value of a radio button group
function getRadioValue(radioName) {
  return $("input[name='" + radioName + "']:checked").val()

}

// helper function to determine if the given sText is numeric
function IsNumeric(sText) {
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }
   return IsNumber;   
}

// helper function to determine if the given sText is a phone number in the format XXX-XXX-XXXX
function IsPhone(sText) {
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   
   if(sText.length != 12)
     return false;
     
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if(i == 3 || i == 7) {
        if(Char != '-')
          IsNumber = false;
      } else {
        if (ValidChars.indexOf(Char) == -1) {
           IsNumber = false;
        }
      }
   }
   return IsNumber;   
}

function IsEmail(sText) {
	state = 0;
	
	for(i = 0; i < sText.length; i++) {
		Char = sText.charAt(i);
		
		if(state == 0 && Char == '@') {
			state = 1;
		} else if(state == 1 && Char == '.') {
			state = 2;
		} else if(state == 2) {
			state = 3;
		}
	}
	
	return state == 3;
}

// Shows the error messages that have accumulated into a colorbox (will be replaced soon)
function showMessage(messages) {
  messages = "<font color=white><p><b>Please resolve the following errors:</b></p>" + messages + "</font><br><input type=button value='OK' class=loginbtn onClick='$.colorbox.close()'>";
  $.colorbox({html:messages});
}

// helper function to assert that the given start date is before the given end date
function helper_EventTime(StartDate, EndDate) {
  slash1 = StartDate.indexOf("/", 0);
  slash2 = StartDate.indexOf("/", slash1+1);
  StartMonth = parseInt(StartDate.substring(0, slash1));
  StartDay = parseInt(StartDate.substring(slash1+1, slash2));
  StartYear = parseInt(StartDate.substring(slash2+1));
  StartHour = parseInt($("#StartHour").val());
  StartMinute = parseInt($("#StartMinute").val());
  StartAMPM = $("#StartAMPM").val();
  
  slash1 = EndDate.indexOf("/", 0);
  slash2 = EndDate.indexOf("/", slash1+1);
  EndMonth = parseInt(EndDate.substring(0, slash1));
  EndDay = parseInt(EndDate.substring(slash1+1, slash2));
  EndYear = parseInt(EndDate.substring(slash2+1));
  EndHour = parseInt($("#EndHour").val());
  EndMinute = parseInt($("#EndMinute").val());
  EndAMPM = $("#EndAMPM").val();
  
  if(EndYear < StartYear) {
    return false;
  } else if(EndYear == StartYear) {
    if(EndMonth < StartMonth) {
      return false;
    } else if(EndMonth == StartMonth) {
      if(EndDay < StartDay) {
        return false;
      } else if(EndDay == StartDay) {
        if(StartAMPM == "AM") {
          if(StartHour == 12)
            StartHour = 0;
        } else {
          if(StartHour != 12)
            StartHour += 12;
        }
        if(EndAMPM == "AM") {
          if(EndHour == 12)
            EndHour = 0;
        } else {
          if(EndHour != 12)
            EndHour += 12;
        }
        if(EndHour < StartHour) {
          return false;
        } else if(EndHour == StartHour) {
          if(EndMinute < StartMinute) {
            return false;
          } else if(EndMinute == StartMinute) {
            return false;
          }
        }
      }
    } 
  } 
  return true;
}

// the rest of these functions do nothing other than return true/false if the form is valid and shows error messages accordingly

function validate_Event() {
  ok = true;
  messages = "";
  if($('#eventList').length) {
    if($("#eventList").val() == "!null") {
      ok = false;
      messages = "Select an event<br>";
      showMessage(messages);
      return ok;
    }
  }
  
  if($("#Title").val() == "") {
    ok = false;
    messages += "Enter an event title<br>";
  }
  if($("#StartDate").val() == "Select") {
    ok = false;
    messages += "Select a start date for the event.<br>";
  } else if($("#EndDate").val() == "Select") {
    StartDate = $("#StartDate").val();
    if(!helper_EventTime(StartDate, StartDate)) {
      ok = false;
      messages += "End date/time must come after start date/time<br>";
    }
  } else {
    StartDate = $("#StartDate").val();
    EndDate = $("#EndDate").val();
    if(!helper_EventTime(StartDate, EndDate)) {
      ok = false;
      messages += "End date/time must come after start date/time<br>";
    }
  }
  
  LocationType = getRadioValue("LocationType");
  if(LocationType == "1") { // member's home
    if($('#LocationHost').val() == "!null") {
      ok = false;
      messages += "Select a member's home to host the event.<br>";
    }
  } else if(LocationType == "2") { // other location
    if($("#LocationName").val() == "") {
      ok = false;
      messages += "Enter the name of the location.<br>";
    }
    if($("#LocationAddress").val() == "") {
      ok = false;
      messages += "Enter the address of the location.<br>";
    }
    if($("#LocationCity").val() == "") {
      ok = false;
      messages += "Enter the city of the location.<br>";
    }
    if($("#LocationState").val() == "") {
      ok = false;
      messages += "Enter the state of the location.<br>";
    } else if($("#LocationState").val().length != 2) {
      ok = false;
      messages += "Enter a valid two-letter state.<br>";
    }
    if($("#LocationZipcode").val() == "") {
      ok = false;
      messages += "Enter the zipcode of the location.<br>";
    } else if($("#LocationZipcode").val().length != 5 || !IsNumeric($("#LocationZipcode").val())) {
      ok = false;
      messages += "Enter 5 digits for the zipcode.<br>";
    }
    if($("#LocationPhone").val() == "") {
      ok = false;
      messages += "Enter the phone number of the location.<br>";
    } else if(!IsPhone($("#LocationPhone").val())) {
      ok = false;
      messages += "Enter the phone number in the format XXX-XXX-XXXX.<br>";
    }
  }
  
  if(!ok) {
    showMessage(messages);
  }
  return ok;
}

function validate_Reminders() {
  ok = true;
  messages = "";

  if($("#eventList").val() == "!null") {
    ok = false;
    messages = "Select an event<br>";
    showMessage(messages);
    return ok;
  }
}

function validate_Link() {
  ok = true;
  messages = "";

  if($("#Label").val() == "") {
    ok = false;
    messages += "Enter a label for the link";
  }

  // TODO
}

function validate_Member() {
  ok = true;
  messages = "";

  if($("#FirstName").val() == "") {
    ok = false;
    messages += "Enter the member's first name.<br>";
  }
  if($("#LastName").val() == "") {
    ok = false;
    messages += "Enter the member's last name.<br>";
  }
  if($("#Email").val() == "") {
    ok = false;
    messages += "Enter the member's e-mail address.<br>";
  }
  if($("#Phone").val() == "") {
    ok = false;
    messages += "Enter the member's phone number.<br>";
  } else if(!IsPhone($("#Phone").val())) {
    ok = false;
    messages += "Enter the phone number in the format XXX-XXX-XXXX.<br>";
  }
  if($("#Address").val() == "") {
    ok = false;
    messages += "Enter the member's address.<br>";
  }
  if($("#City").val() == "") {
    ok = false;
    messages += "Enter the member's city.<br>";
  }
  if($("#State").val() == "") {
    ok = false;
    messages += "Enter the member's state.<br>";
  } else if($("#State").val().length != 2) {
    ok = false;
    messages += "Enter a valid two-letter state.<br>";
  }
  if($("#Zipcode").val() == "") {
    ok = false;
    messages += "Enter the member's zip code.<br>";
  } else if($("#Zipcode").val().length != 5 || !IsNumeric($("#Zipcode").val())) {
    ok = false;
    messages += "Enter 5 digits for the zipcode.<br>";
  }
  if($("#BirthMonth").val() == "") {
    ok = false;
    messages += "Enter the member's birth month.<br>";
  } else if(!IsNumeric($("#BirthMonth").val())) {
    ok = false;
    messages += "Enter a number 1 thru 12 for the birth month.<br>";
  } else if(parseInt($("#BirthMonth").val()) < 1 || parseInt($("#BirthMonth").val()) > 12) {
    ok = false;
    messages += "Enter a number 1 thru 12 for the birth month.<br>";
  }
  if($("#BirthDate").val() == "") {
    ok = false;
    messages += "Enter the member's birth date.<br>";
  } else if(!IsNumeric($("#BirthDate").val())) {
    ok = false;
    messages += "Enter a number 1 thru 12 for the birth month.<br>";
  } else if(parseInt($("#BirthDate").val()) < 1 || parseInt($("#BirthDate").val()) > 31) {
    ok = false;
    messages += "Enter a number 1 thru 31 for the birth date.<br>";
  }

  if(!ok) {
    showMessage(messages);
  }
  return ok;
}

function validate_MemberEdit1() {
  if($("#UserSHA").val() == "!null") {
    ok = false;
    messages = "Select a member.<br>";
    showMessage(messages);
    return ok;
  }
  return true;
}

function validate_Password() {
	ok = true;
	messages = "";
	
	password = $("#password").val();
	repassword = $("#repassword").val();
	
	if(password != repassword) {
		ok = false;
		messages += "Passwords do not match.  Try again.";
		showMessage(messages);
		return ok;
	}
	
	if(password.length < 8) {
		ok = false;
		messages += "Password must be at least 8 characters.";
		showMessage(messages);
		return ok;
	}
	
	numLetters = 0;
	numNumbers = 0;
	numBadSymbols = 0;
	allowedLetters = "pyfgcrlaoeuidhtnsqjkxbmwvzPYFGCRLAOEUIDHTNSQJKXBMWVZ";
	allowedNumbers = "1234567890";
	allowedSymbols = "!@#$%^&,.;:-_/?=+`~<>";
	
	for(i = 0; i < password.length; ++i) {
		isSymbol = true;
		for(j = 0; j < 52; ++j) {
			if(password.charAt(i) == allowedLetters.charAt(j)) {
				numLetters += 1;
				isSymbol = false;
				break;
			}
		}
		
		for(j = 0; j < 10; ++j) {
			if(password.charAt(i) == allowedNumbers.charAt(j)) {
				numNumbers += 1;
				isSymbol = false;
				break;
			}
		}
		
		if(isSymbol) {
			isBadSymbol = true;
			for(j = 0; j < allowedSymbols.length; ++j) {
				if(password.charAt(i) == allowedSymbols.charAt(j)) {
					isBadSymbol = false;
					break;
				}
			}
			if(isBadSymbol)
				numBadSymbols += 1;
		}
	}
	
	if(numLetters == 0) {
		ok = false;
		messages += "Password must contain at least 1 letter.<br>";
	}
	if(numNumbers == 0) {
		ok = false;
		messages += "Password must contain at least 1 number.<br>";
	}
	if(numBadSymbols > 0) {
		ok = false;
		messages += "Password may only contain the following symbols: " + allowedSymbols + "<br>";
	}
	
	if(!ok) {
		showMessage(messages);
	}
	return ok;
}

function validate_MailingList(source) {
	ok = true;
	messages = "";
	
	if($("#FirstName").val() == "") {
		ok = false;
		if(source == 'p')
			messages += "First name is required.  If you do not feel comfortable giving us your name, just use an alias.<br>";
		else
			messages += "First name is required.  If the person did not provide this information, just use the alias in their e-mail address.<br>";
	}
	if($("#Email").val() == "" || !IsEmail($("#Email").val())) {
		ok = false;
		messages += "E-mail address is required.<br>";
	}
	
	if(!ok) {
		showMessage(messages);
	}
	return ok;
}
