/**
 *
 * Author: Michael Kinkaid
 * Version 1
 * 
 * The following functions are used within the login and registration page.
 * 
 * All form validation is done prior to sending the values to the server
 * for processing.  Ajax has been used to verify that a user name is available
 * and that an email address has not already been associated with an account
 **/

//Global variables
var xmlHttp;
var nameAvailable	= true; 
var emailAvailable	= true;
var dateValid		= true;

/**
 * Handles the creation of the XMLHTTP object for use with AJAX
 * communication between the client and the server.
 */
function GetXmlHttpObject()
{ 
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var aVersions = [ "MSXML2.XMLHttp.5.0",
        "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
        "MSXML2.XMLHttp","Microsoft.XMLHttp"
      ];

      for (var i = 0; i < aVersions.length; i++) {
        try {
            var oXmlHttp = new ActiveXObject(aVersions[i]);
            return oXmlHttp;
        } catch (oError) {
            //Do nothing
        }
      }
    }
    throw new Error("XMLHttp object could be created.");
} 

/**
 * checkUserName makes an XMLHTTP object to check the name entered 
 * by the user against those in the Members table.   checkUserNameResponse
 * is set as the function to handle the response from the XMLHTTP object.
 *
 * @param	str_requestName		Requested username to check 
 *
 */
function checkUserName(str_requestName)
{
	if (str_requestName.length < 4)
	{ 
		document.getElementById("nameErrorPrompt").innerHTML="Used to identify you.";
		document.getElementById("nameErrorPrompt").style.color = "#a1a0a0";
		return;
	}
	else
	{
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null)
		{
			alert ("Browser does not support HTTP Request");
			return;
		} 
		
		var url = "../checkUserName.asp";
		url = url + "?q=" + str_requestName;
		url = url + "&sid=" + Math.random();
		xmlHttp.onreadystatechange = checkUserNameResponse;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);	
	}
} 

/**
 * checkEmailAddress makes an XMLHTTP object to check the email entered 
 * by the user has not already been registered with another account.
 * checkEmailAddressResponse is set as the function to handle the response
 * from the XMLHTTP object.
 *
 * @param	str_requestEmail		Requested email address to validate 
 *
 */
function checkEmailAddress(str_requestEmail)
{
	if (str_requestEmail.length == 0)
	{ 
		document.getElementById("emailErrorPrompt").innerHTML="Must be a valid address.";
		document.getElementById("emailErrorPrompt").style.color = "#a1a0a0";
		return;
	}
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	} 
	var url = "../checkEmailAddress.asp";
	url = url + "?q=" + str_requestEmail;
	url = url + "&sid=" + Math.random();
	xmlHttp.onreadystatechange = checkEmailAddressResponse;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

/**
 * checkDatemakes an XMLHTTP object to check that the date entered 
 * by the user is actually valid i.e. November 31st is not valid.
 *
 */
function checkDate()
{
	//Get values from date select boxes
	var birthMonth			= document.getElementById('monthSelect');
	var birthDay			= document.getElementById('daySelect');
	var birthYear			= document.getElementById('yearSelect');
	
	var str_monthValue		= birthMonth.value;
	var str_dayValue		= birthDay.value;
	var str_yearValue		= birthYear.value;
	
	//Only check when all select boxes have a value
	if((str_dayValue != "Select")&&(str_dayValue != ""))
	{
		if((str_monthValue != "Select")&&(str_monthValue != ""))
		{
			if((str_yearValue != "Select")&&(str_yearValue != ""))
			{
				//Check the date
				xmlHttp = GetXmlHttpObject();
				if (xmlHttp == null)
				{
					alert ("Browser does not support HTTP Request");
					return;
				} 
				var url = "../checkValidDate.asp";
				url = url + "?day="		+ str_dayValue;
				url = url + "&month="	+ str_monthValue;
				url = url + "&year="	+ str_yearValue;
				url = url + "&sid="		+ Math.random();
				xmlHttp.onreadystatechange = checkDateResponse;
				xmlHttp.open("GET", url, true);
				xmlHttp.send(null);				
			}
		}
	}
}

/**
 * checkUserNameResponse handles the XMLHTTP response from checkUserName.asp 
 */
function checkUserNameResponse() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById("nameErrorPrompt").innerHTML=xmlHttp.responseText;
		
		if(xmlHttp.responseText == "User Name Already Taken")
		{
			document.getElementById("nameErrorPrompt").style.color = "#FF0000";
			nameAvailable = false;
		}
		else
		{
			document.getElementById("nameErrorPrompt").style.color = "#328DC8";
			nameAvailable = true;		
		}
	} 
} 

/**
 * checkEmailAddressResponse handles the XMLHTTP response from checkEmailAddress.asp 
 */
function checkEmailAddressResponse() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		
		if(xmlHttp.responseText == "Email Address Already Registered")
		{
			document.getElementById("emailErrorPrompt").innerHTML="Already taken.";
			document.getElementById("emailErrorPrompt").style.color = "#FF0000";
			emailAvailable = false;
		}
		else
		{
			document.getElementById("emailErrorPrompt").innerHTML="Must be a valid address.";
			document.getElementById("emailErrorPrompt").style.color = "#a1a0a0";
			emailAvailable = true;	
		}
	} 
} 

/**
 * checkDateResponse handles the XMLHTTP response from checkValidDate.asp 
 */
function checkDateResponse() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById("dateErrorPrompt").innerHTML=xmlHttp.responseText;
		
		if(xmlHttp.responseText == "Invalid date.")
		{
			document.getElementById("dateErrorPrompt").style.color = "#FF0000";
			dateValid = false;
		}
		else
		{
			document.getElementById("dateErrorPrompt").innerHTML= xmlHttp.responseText;
			document.getElementById("dateErrorPrompt").style.color = "#a1a0a0";
			dateValid = true;	
		}
	} 
} 

/**
 * Validates the fields from the login form
 */
function validateLoginForm()
{	
	//Get reference to form objects
	var userName	= document.getElementById('loginNameTextBox');
	var password 	= document.getElementById('loginPasswordTextBox');
	var errorPrompt = document.getElementById('loginErrorPrompt');
	
	//Starting with first form element, validate fields.
	if(checkLength(userName, "Username is too short.", "", 0, 255, errorPrompt))
	{
		if(checkLength(password, "Password is too short", "", 6, 255, errorPrompt))
		{
			//Validation successful, clear error and process login
			errorPrompt.innerHTML = "";
			return true;
		}
	}

	//Validation not successful
	return false;	
}

/**
 * Validates the fields from the registration form
 */
function validateRegistrationForm()
{
	//Get reference to form objects
	var emailAddress		= document.getElementById('emailTextBox');
	var confirmEmail		= document.getElementById('confirmEmailTextBox');	
	var userName			= document.getElementById('userNameTextBox');
	var password			= document.getElementById('passwordTextBox');
	var verifyPassword		= document.getElementById('passwordVerifyTextBox');
	var firstName			= document.getElementById('firstNameTextBox');
	var lastName			= document.getElementById('lastNameTextBox');
	var birthMonth			= document.getElementById('monthSelect');
	var birthDay			= document.getElementById('daySelect');
	var birthYear			= document.getElementById('yearSelect');
	var agreementCheckBox	= document.getElementById('agreementCheckBox');

	//Get reference to error prompts
	var confirmAddressPrompt	= document.getElementById('confirmEmailErrorPrompt');	
	var namePrompt				= document.getElementById('nameErrorPrompt');
	var passwordPrompt			= document.getElementById('passwordErrorPrompt');
	var verifyPrompt			= document.getElementById('verifyErrorPrompt');
	var emailPrompt				= document.getElementById('emailErrorPrompt');
	var datePrompt				= document.getElementById('dateErrorPrompt');
	var registerPrompt			= document.getElementById('RegisterErrorPrompt');
	var AgreeErrorPrompt		= document.getElementById('AgreeErrorPrompt');
	var firstNameErrorPrompt	= document.getElementById('firstNameErrorPrompt');
	var lastNameErrorPrompt		= document.getElementById('lastNameErrorPrompt');
	
	//Check AJAX response and then standard form validation
	if(nameAvailable)
	{
		if(emailAvailable)
		{
			if(dateValid)
			{	
				if(isLegal(userName, "* Unallowed character.  The following characters are not permitted: ( * | < > # ' \\ / \" ? : ;)", "Used to identify you.", namePrompt))
				{
					if(checkLength(userName, "* Username is too short.", "Used to identify you.", 4, 255, namePrompt))
					{
						if(isAlphanumeric(userName, "* Only letters and numbers please.", "Used to identify you.", namePrompt))
						{
							if(isEmpty(firstName, "* Required.", "", firstNameErrorPrompt))
							{
								if(isEmpty(lastName, "* Required.", "", lastNameErrorPrompt))
								{
									if(checkLength(password, "* Password is too short", "Must be at least 6 characters.", 6, 255, passwordPrompt))
									{
										if(checkPassword(password, verifyPassword, "* Passwords do not match", "Retype your password.", verifyPrompt))
										{
											if(emailValidator(emailAddress, "* Not a valid address.", "Must be a valid address.", emailPrompt))
											{
												if(emailAddress.value != confirmEmail.value)
												{
													registerPrompt.style.color = "#FF0000";
													registerPrompt.innerHTML = " * Please address the items in red.";					
												
													confirmAddressPrompt.style.color = "#FF0000";
													confirmAddressPrompt.innerHTML = "* Please match above email."
													confirmEmail.focus();	
													return false;
												}
												else
												{
													confirmAddressPrompt.style.color = "#a1a0a0";
													confirmAddressPrompt.innerHTML = "Retype your address."
												}
											
												if(madeSelection(birthMonth, "* Please select a month.", "", datePrompt))
												{
													if(madeSelection(birthDay, "* Please select a day.", "", datePrompt))
													{
														if(agreementCheckBox.checked == true)
														{	
															AgreeErrorPrompt.innerHTML = "";

															if(madeSelection(birthYear, "* Please select a year.", "", datePrompt))
															{
																//Final check for age
																var thisDate	= new Date();
																var thisDay		= thisDate.getDate();
																var thisMonth	= thisDate.getMonth() + 1;
																var thisYear	= thisDate.getYear();
																
																var userDay		= birthDay.value;
																var userMonth	= birthMonth.value;
																var userYear	= birthYear.value - 1900;
																
						
																//Compare dates
																if((thisYear - userYear) > 13)
																{
																	return true;
																}
																else if((thisYear - userYear) == 13)
																{
																	if(thisMonth > userMonth)
																	{
																		return true
																	}
																	else
																	{
																		if(thisMonth == userMonth)
																		{
																			if(thisDay == userDay)
																			{
																				alert("HAPPY BIRTHDAY from everyone here at T-shirt Monster!!");
																				return true;
																			}
																			else if(thisDay > userDay)
																			{
																				return true;
																			}
																			else
																			{
																				alert("Sorry but you are too young to register.");
																				return false;		
																			}
																		}
																		else
																		{
																			alert("Sorry but you are too young to register.");
																			return false;
																		}
																	}
																}
																else
																{
																	alert("Sorry but you are too young to register.");
																	return false;
																}
															}
														}
														else
														{
															registerPrompt.style.color = "#FF0000";
															registerPrompt.innerHTML = " * Please address the items in red.";				
															
															AgreeErrorPrompt.style.color = "#FF0000";
															AgreeErrorPrompt.innerHTML = "* Please read.";
															return false;
														}									
													}							
												}
											}
										}
									}
								}
							}
						}					
					}	
				}
			}
		}
	}
	
	registerPrompt.style.color = "#FF0000";
	registerPrompt.innerHTML = " * Please address the items in red.";
	return false;
}

/**
 * Checks to see if a string entered by the user is a legal 
 * name for a folder.
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function isLegal(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	var num1;
	var num2;
	var num3;
	var num4;
	var num5;
	var num6;
	var num7;
	var num8;
	var num9;
	var num10;
	var num11;
	var num12;	
	var checkString;
	
	checkString = obj_input.value;	
		
	num1 = checkString.indexOf("\\");
	num2 = checkString.indexOf("\"");
	num3 = checkString.indexOf("*");
	num4 = checkString.indexOf("/");
	num5 = checkString.indexOf(":");
	num6 = checkString.indexOf("<");
	num7 = checkString.indexOf(">");
	num8 = checkString.indexOf("?");
	num9 = checkString.indexOf("|");
	num10 = checkString.indexOf("'");
	num11 = checkString.indexOf("&");
	num12 = checkString.indexOf("#");
	num13 = checkString.indexOf(";");
	
	//Validate
	if((num1 == -1)&&(num2 == -1)&&(num3 == -1)&&(num4 == -1)&&(num5 == -1)&&(num6 == -1)&&(num7 == -1)&&(num8 == -1)&&(num9 == -1)&&(num10 == -1)&&(num11 == -1)&&(num12 == -1)&&(num13 == -1))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;
	}
}


/**
 * Checks to see if a string entered by the user is of a valid 
 * length.
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	n_minLength				Minimum length for string to be valid
 * @param	n_maxLength				Maximum length for string to be valid
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function checkLength(obj_input, str_helperMessage, str_hint, n_minLength, n_maxLength, obj_errorMsg)
{
	var inputLength = obj_input.value.length;
	
	if((inputLength  >= n_minLength)&&(inputLength  <= n_maxLength))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;	
	}
}

/**
 * Checks to see if a string entered by the user is of a valid 
 * content.  In this case - letters
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function isAlphabet(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	var alphaExp = /^[a-zA-Z]+$/;
	if(obj_input.value.match(alphaExp))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;
	}
}

/**
 * Checks to see if a string entered by the user is of a valid 
 * content.  In this case - letter and numbers
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function isAlphanumeric(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(obj_input.value.match(alphaExp))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;
	}
}

/**
 * Checks to see if a string entered by the user is empty
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function isEmpty(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	if(obj_input.value.length != 0)
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;	
	}
}

/**
 * Checks to see if a password entered by a user matches the 
 * verification string that they entered
 *
 * @param	obj_password			Form element containing password
 * @param	obj_verify				Form element containing verification string 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function checkPassword(obj_password, obj_verify, str_helperMessage, str_hint, obj_errorMsg)
{
	var str_password;
	var str_verify;
	str_password = obj_password.value;
	str_verify = obj_verify.value;
	
	if(str_password == str_verify)
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_verify.focus();
		return false;	
	}
}

/**
 * Checks to see if an email address entered by the user is valid.
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function emailValidator(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	
	if(obj_input.value.match(emailExp))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;
	}
}

/**
 * Checks to see if a combo box has been used.
 *
 * @param	obj_input				Form element that we are checking 
 * @param	str_helperMessage		Message displayed on error
 * @param	str_hint				Message displayed to discribe validation
 * @param	obj_errorMsg			Form element to display all messages 
 *
 */
function madeSelection(obj_input, str_helperMessage, str_hint, obj_errorMsg)
{
	if((obj_input.value != "Select")&&(obj_input.value != ""))
	{
		obj_errorMsg.style.color = "#a1a0a0";
		obj_errorMsg.innerHTML = str_hint;
		return true;
	}
	else
	{
		obj_errorMsg.style.color = "#FF0000";
		obj_errorMsg.innerHTML = str_helperMessage;
		obj_input.focus();
		return false;
	}
}

/**
 * Send email to user 
 */
function emailDetails()
{
	var emailDetails = document.getElementById("emailDetails");
	var getDetailsErrorPrompt = document.getElementById("getDetailsErrorPrompt");
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	
	if(emailDetails.value == "")
	{
		getDetailsErrorPrompt.innerHTML = "* Please enter an address."
	}
	else
	{
		if(emailDetails.value.match(emailExp))
		{
			xmlHttp = GetXmlHttpObject();
			if (xmlHttp == null)
			{
				alert ("Browser does not support HTTP Request");
				return;
			} 
			var url = "../getUserDetails.asp";
			url = url + "?emailAddress=" + encodeURI(emailDetails.value);
			url = url + "&sid="		+ Math.random();
			xmlHttp.onreadystatechange = emailDetailsResponse;
			xmlHttp.open("GET", url, true);
			xmlHttp.send(null);			
		}
		else
		{
			getDetailsErrorPrompt.innerHTML = "* Invalid address."
		}		
	}
}

/**
 * Response for emailDetails HTTP Request 
 */
function emailDetailsResponse()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		
		//Successful login
		var updateResponse = xmlHttp.responseText;
		var getDetailsErrorPrompt = document.getElementById("getDetailsErrorPrompt");
		
		if(updateResponse == "Not Found")
		{
			getDetailsErrorPrompt.innerHTML = "* Address not found."
		}
		else if(updateResponse == "Found")
		{
			getDetailsErrorPrompt.style.color = "#FFAA00";
			getDetailsErrorPrompt.innerHTML = "* Password sent!";
		}
		else
		{
			getDetailsErrorPrompt.innerHTML = "Please try again.";
		}
	}
}

/**
 * show/hide get password information 
 */
function toggleGetPassword()
{
	var getPasswordTable = document.getElementById("getPasswordTable");
	
	if(getPasswordTable.style.visibility == "visible")
	{
		getPasswordTable.style.visibility = "hidden"
	}
	else
	{
		var getDetailsErrorPrompt 			= document.getElementById("getDetailsErrorPrompt");
		var emailDetails 					= document.getElementById("emailDetails");
		
		getDetailsErrorPrompt.innerHTML 	= "";
		emailDetails.value 					= "";
		
		getPasswordTable.style.visibility 	= "visible"
	}
}

/**
 * showLicense - opens the license.
 */
function showLicense()
{
	var theTop	= (screen.height/2)-(400/2);
	var theLeft	= (screen.width/2)-(600/2);
	var features = "height=400,width=600,top=" + theTop + ",left=" + theLeft + ",status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
	window.open("userAgreement.htm", "_blank", features);
}