// <<:: Form and Cookie javascript functions ::>> //

// ---- COOKIE RELATED FUNCTIONS ----->>

function getCookie(Name){
     var search = Name + "=";
	if (document.cookie.length > 0) {
	   var offset = document.cookie.indexOf(search);
	   if (offset != -1) {
		offset += search.length;
		var end = document.cookie.indexOf(";", offset);
	     	if (end == -1) {
			end = document.cookie.length;
			}
		return unescape(document.cookie.substring(offset, end));
	    }
	}
	return "";
}

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + value +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) 
	document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) + 
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
	


//****************************************************************************//
// --- FORM RELATED FUNCTIONS ----->>

function focusKey(e, fieldObj, formName, validationName)
{
    eval('var theForm = document.'+ formName +';');
    if(( e && e.which && e.which == 13 ) || ( e && e.keyCode && e.keyCode == 13 )) 
    {
	fieldObj.blur(); 
	eval ('if (valid'+ validationName +'FormEntry() == true) theForm.submit();');
	return true;
    }
}

function validEmail(emailaddress)
{
	var email = emailaddress;
	var filter  = /^([-\w\.])+\@(([-\w])+\.)+([\w]{2,4})$/;
	if (filter.test(email)) 
		return true;
	else 
		return false;
}

function validName(nametext)
{
	var name = nametext;
	var filter  = /^([-\w\.]){2,128}$/;
	if (filter.test(name)) 
		return true;
	else 
		return false;
}

function validPwd(pwd1, pwd2)
{
	var p1 = pwd1;
	var p2 = pwd2;
	var filter  = /^([-\w\.]){6,32}$/;
	if (filter.test(p1) && filter.test(p2)) 
	{
	    if (p1 == p2)
		return "pass";
	    else
		return "fail_confirm";
	}
	else 
	    return "fail_regex";
}

function validPostalCode(postal_code)
{
	var code = postal_code;
	var filter  = /^([-\w\.\s]){5,20}$/;
	if (filter.test(code)) 
		return true;
	else 
		return false;
}

function validGeneralText(textstr)
{
	var filter  = /^([-\w\s\.\,\'\~!@#$%^&*\(\)\+=\;:?\/])+$/;
	if (filter.test(textstr)) 
		return true;
	else 
		return false;
}

function validDate(day, month, year)
{
    /* Using form values, create a new date object using the setFullYear function */

    var myDate = new Date();
    myDate.setFullYear( year, (month-1), day );

    if ( myDate.getMonth() != (month-1) ) {
	return false;
    } else {
	return true;
    }
}

// :::::: Quick "GetElementById" scripting shortcut function. ::::::
function $(id) {
	return document.getElementById(id);
}


//****************************************************************************//
// --> Stores the hash array containing the HTML strings of every possible
// error message and instruction message that would pop up on the form while
// the user is filling it out, and before it gets submitted for processing.
// This array is used in the (validFormEntry) functions. <-- //

function get_display_message_array()
{
	var message_display = new Array();
	message_display["instructions"] = "These are the instructions you should see first.";
	message_display["required_field"] = "Please fill in all fields to proceed.";
	message_display["invalid_name"] = "The username must be at least two characters long. Only letters, digits, dashes, periods and underscores allowed.";
	message_display["invalid_email"] = "Please make sure you have entered a valid email address.";
	message_display["invalid_pwd"] = "Password must be at least 6 characters long, and contain only numbers, letters, dots, underscores or dashes.";
	message_display["invalid_pwd_confirm"] = "The password has not been confirmed!";
	message_display["invalid_zip"] = "The Postal code can only have numbers, letters, dashes and/or periods in it. It must be at least 5 characters long.";
	message_display["invalid_date"] = "The date you chose does not exist.";

	return message_display;
}



//****************************************************************************//
//****************************************************************************//
// --> Sign Up Form Validation Function.
// This function does a javascript check to make sure that the form 
// was completed by the user, and that all the field entries are valid 
// (using above regex check funcs). <-- //
function validSignUpFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var userNm = document.sign_up.username.value;
	var email = document.sign_up.email.value;
	var pwd1 = document.sign_up.password1.value;
	var pwd2 = document.sign_up.password2.value;
	var gender = document.sign_up.gender.value;
	var b_day = document.sign_up.birth_day.value;
	var b_mo = document.sign_up.birth_month.value;
	var b_yr = document.sign_up.birth_year.value;
	var cntry = document.sign_up.country.value;

	// Checkbox value not used here. It only matters whether the box was clicked or not.
	var tandc = document.sign_up.tandc_verify;
	var zip = document.sign_up.postal_code.value;
	// POSTAL CODE SPECIAL CASE OP: Delete surrounding spaces, replace inner space with '-'.
	document.sign_up.postal_code.value = (zip.replace(/^\s*(.*?)\s*$/,"$1")).replace(" ", "-");
	zip = document.sign_up.postal_code.value;

	var MessageArray = get_display_message_array(); //array of display and error messages
	$("formtop").innerHTML= '';


	// UN-HIGHLIGHT ANY HIGHLIGHTED TEXT FIELDS
	$("input_item3").style.border='0';
	$("input_item4").style.border='0';
	$("input_item5").style.border='0';
	$("input_item6").style.border='0';
	$("input_item7").style.border='0';
	$("input_item8").style.border='0';


	// *** FIRST CHECK TO SEE IF THE FORM HAS BEEN COMPLETED ***
	if (userNm == '' || email == '' || pwd1 == '' || pwd2 == ''
		|| gender == 'x' || b_day == 0 || b_mo == '' || b_yr == 1900 
		|| cntry == 'ZZ' || zip == '' || !(tandc.checked))
	{
		// alert the user to enter a name
		$("formtop").innerHTML=MessageArray["required_field"];
		$("formtop").style.display='block';
		return false;
	}

	// *** VALIDATE EACH FIELD IN ORDER ON THE FORM ***
	if(!validName(userNm))
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_name"];
		$("formtop").style.display='block';
		$("input_item3").style.border='thin solid red';
		return false;
	}
	if(!validEmail(email))
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML+=MessageArray["invalid_email"];
		$("formtop").style.display='block';
		$("input_item4").style.border='thin solid red';
		return false;
	}
	var pw_check = validPwd(pwd1, pwd2);
	if (pw_check == "fail_regex")
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_pwd"];
		$("formtop").style.display='block';
		$("input_item5").style.border='thin solid red';
		$("input_item6").style.border='thin solid red';
		return false;
	}
	if (pw_check == "fail_confirm")
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_pwd_confirm"];
		$("formtop").style.display='block';
		$("input_item6").style.border='thin solid red';
		return false;
	}
	if (!validDate(b_day, b_mo, b_yr))
	{
		// alert the user to enter a date
		$("formtop").innerHTML=MessageArray["invalid_date"];
		$("formtop").style.display='block';
		$("input_item7").style.border='thin solid red';
		return false;
	}
	if (!validPostalCode(zip))
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_zip"];
		$("formtop").style.display='block';
		$("input_item8").style.border='thin solid red';
		return false;
	}

	return true;

} 
//End Of Sign Up Form Validation Function


//****************************************************************************//
// --> Profile Form Validation Function. This function does a quick js check
// to make sure the form text entries are valid, using the funcs above. <-- //
function validProfileFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var fav_bk = document.profile.fav_book.value;
	var fav_mv = document.profile.fav_movie.value;
	var fav_sg = document.profile.fav_song.value;
	var fav_qt = document.profile.fav_quote.value;
	var pd = document.profile.personal_desc.value;
	var im_nm = document.profile.im_name.value;

	$("formtop").innerHTML= '';

	if (	(fav_bk == '' || validGeneralText(fav_bk)) &&
		(fav_mv == '' || validGeneralText(fav_mv)) &&
		(fav_sg == '' || validGeneralText(fav_sg)) &&
		(fav_qt == '' || validGeneralText(fav_qt)) &&
		(pd == '' || validGeneralText(pd)) &&
		(im_nm == '' || validName(im_nm)))
	    return true;
	else
	{
	    $("formtop").innerHTML= '<div style=\"text-align:center;\"><b>'
				+'There are invalid characters in the text'
	   			+' fields. Please remove them to continue.'
				+'</b></div><br/><br/>';
	    $("formtop").style.display='block';
	    return false;
	}

}
//End Of Profile Form Validation Function


//****************************************************************************//
// --> Log In Form Validation Function.
// This function does a javascript check to make sure that the form was
// completed by the user, and that both field entries are valid (using 
// regex funcs above). <-- //
function validLogInFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var userNm = document.log_in.username.value;
	var pwd = document.log_in.password.value;

	var MessageArray = get_display_message_array(); //array of display and error messages

	// UN-HIGHLIGHT ANY HIGHLIGHTED TEXT FIELDS
	$("input_item1").style.border='0';
	$("input_item2").style.border='0';

	// *** FIRST CHECK TO SEE IF THE FORM HAS BEEN COMPLETED ***
	if (userNm == '' || pwd == '')
		return false;

	// *** VALIDATE EACH FIELD IN ORDER ON THE FORM ***
	if(!validName(userNm))
	{
		$("input_item1").style.border='thin solid red';
		return false;
	}
	var pw_check = validPwd(pwd, pwd);	// validates the password text only
	if (pw_check == "fail_regex")
	{
		$("input_item2").style.border='thin solid red';
		return false;
	}
	return true;

} 
//End Of Log In Form Validation Function


//****************************************************************************//
// --> Log Out Function 
// Quick func to delete the session cookies which kept the user logged in. <--
function log_out_user()
{
	deleteCookie('UserID', '/');
	deleteCookie('icon_email', '/');
	deleteCookie('TimeOut', '/');
}


//****************************************************************************//
// --> Password Change Form Validation Function.
// Does a js validation check on the pw entries(using pw regex func above). <-- //
function validChangePwFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var old_pw = document.change_pw.curr_pw.value;
	var pwd1 = document.change_pw.new_pw1.value;
	var pwd2 = document.change_pw.new_pw2.value;

	var MessageArray = get_display_message_array(); //display&error messages
	$("formtop").innerHTML= '';

	// UN-HIGHLIGHT ANY HIGHLIGHTED TEXT FIELDS
	$("input_item1").style.border='0';
	$("input_item2").style.border='0';
	$("input_item3").style.border='0';

	// *** FIRST CHECK TO SEE IF THE FORM HAS BEEN COMPLETED ***
	if ( old_pw == '' || pwd1 == '' || pwd2 == '')
	{
		// alert the user to enter a name
		$("formtop").innerHTML=MessageArray["required_field"];
		$("formtop").style.display='block';
		return false;
	}

	// *** VALIDATE EACH FIELD IN ORDER ON THE FORM ***
	var old_pw_check = validPwd(old_pw, old_pw);
	if (old_pw_check == "fail_regex")
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_pwd"];
		$("formtop").style.display='block';
		$("input_item1").style.border='thin solid red';
		return false;
	}
	var new_pw_check = validPwd(pwd1, pwd2);
	if (new_pw_check == "fail_regex")
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_pwd"];
		$("formtop").style.display='block';
		$("input_item2").style.border='thin solid red';
		$("input_item3").style.border='thin solid red';
		return false;
	}
	if (new_pw_check == "fail_confirm")
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_pwd_confirm"];
		$("formtop").style.display='block';
		$("input_item3").style.border='thin solid red';
		return false;
	}
	return true;

}
//End Of Change Password Form Validation Function


//****************************************************************************//
// --> Change Email Form Validation Function. 
// This function does a quick javascript check to make sure first 
// that the form was completed by the user, and then that the new
// email address is valid (using validEmail func above). <-- //
function validChangeEmailFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var email = document.change_email.new_email.value;

	var MessageArray = get_display_message_array(); //display&error messages
	$("formtop").innerHTML= '';

	// UN-HIGHLIGHT ANY HIGHLIGHTED TEXT FIELDS
	$("input_item2").style.border='0';

	// EMAIL DOESN'T HAVE TO BE ALTERED (IT CAN BE NULL ON THIS FORM)
	if (email == '' )
		return true;
	if(!validEmail(email))
	{
		// alert the user to enter a valid name
		$("formtop").innerHTML=MessageArray["invalid_email"];
		$("formtop").style.display='block';
		$("input_item2").style.border='thin solid red';
		return false;
	}
	return true;

} 
//End Of Change Email Form Validation Function



//****************************************************************************//
// --> Forgot Password Form Validation Function.
// This function does a javascript check on the username given
// by the user requesting that their password be reset. <-- //
function validForgotPwFormEntry()
{
	// ASSIGN FORM DATA TO VARS
	var email = document.forgot_pw.email.value;

	var MessageArray = get_display_message_array(); //array of display and error messages

	// UN-HIGHLIGHT ANY HIGHLIGHTED TEXT FIELDS
	$("input_item_1").style.border='0';

	if (email == '')
	{
		// alert the user to enter a name
		$("input_item_1").style.border='thin solid red';
		$("formtop").innerHTML=MessageArray["required_field"];
		$("formtop").style.display='block';
		return false;
	}
	if(!validEmail(email))
	{
		$("formtop").innerHTML=MessageArray["invalid_email"];
		$("formtop").style.display='block';
		$("input_item_1").style.border='thin solid red';
		return false;
	}
	return true;

} 
//End Of Log In Form Validation Function


//****************************************************************************//

function ToggleSubgameList(gameTitle)
{
    // check if currently + or - shown, change accordingly
    // check if display is 'none' or 'block', toggle accordingly

    if ($(gameTitle+'_sublevels').style.display == 'block')
    {
	$(gameTitle+'_sublevels').style.display = 'none';
	$(gameTitle+'_plus_minus').innerHTML = '[+]';
    }
    else
    {
	$(gameTitle+'_sublevels').style.display = 'block';
	$(gameTitle+'_plus_minus').innerHTML = '[&#8211;]';
    }
}

//*************************************************************************//

