/*  The first three functions are from Head First Javascript */
    
function writeCookie(name, value, days)
{
	// By default, there is no expiration, so the cookie is temporary
	var expires = "";
	
	// Specifying a number of days makes the cookie persistent
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	
	// Set cookie to the name, value, and expiration date
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
	// Find the specified cookie and return its value
	var searchName = name + "=";
	var cookies = document.cookie.split(';');
	for (var i = 0; i < cookies.length; i++) {
		var c = cookies[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(searchName) == 0)
			return c.substring(searchName.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	// Erase the specified cookie
	writeCookie(name, "", -1);
}

/* Make sure the user can access this page */

var confirmAccess = function(origin) {
    /*  Description: Controlls user access to a particular page through the 
            use of cookies. Sets the cookie if appropriate. Otherwise, checks
            for the presence of the cookie.
        Input: The referring document
        Output: None. Redirects the user on authentication failure
    */
    if (!(readCookie("registered"))) {
        window.location.assign(origin);
    }
};

/* Form validation */

var validateName = function(input, nameType, nagList) {
    /*  Description: Validates a basic name
        Input: The input object containing the name, the type of name ('first'
            or 'last') and a <ul> element to append the error message to
        Output: true if the name is valid, false if it isn't
    */
    var regex = /[^0-9A-Za-z-.\s]/;
    var name = input.attr("name");
    var val = input.val();

    $("#" + name + "-nag").remove();
    if (val === "" || val === null) {
        $(nagList).append('<li id="' + name + '-nag">Please enter your ' +
            nameType + ' name</li>');
        return false;
    } else if (val.match(regex)) {
        $(nagList).append('<li id="' + name + '-nag">Invalid ' + nameType + 
            ' name</li>');
        return false;
    } else {
        return true;
    }
};

var validateEmail = function(input, nagList) {
    /*  Description: Validates a basic email address
        Input: The input object containing the address, the <ul> element to
            append the error message to 
        Output: true if the email is valid, false if it isn't
    */
    var regex = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/;
    var name = input.attr("name");
    var val = input.val();
    
    $("#" + name + "-nag").remove();
    if (val == "" || val === null) {
        $(nagList).append('<li id="' + name + 
            '-nag">Please enter your email address</li>');
        return false;
    } else if (!val.match(regex)) {
        $(nagList).append('<li id="' + name + 
            '-nag">Please enter a valid email address</li>');
        return false;
    } else {
        return true;
    }
};

var validateAllFilled = function(form, nagList) {
    /*  Description: Makes sure all form elememnts contain some sort of text
            Does not validate the text itself
        Input: The form object, the <ul> element to append the error message to
        Output: true if everything has been filled out, false if it hasn't 
    */
    var complete = true;
    $(form).children().children("input[type!='image'], textarea").each(function(index, value) {
        if ($(value).val() == "" || $(value).val() == null) {
            complete = false;
        }
    });
    if (complete) {
        return true;
    } else {
        $(nagList).append('<li id="completion-nag">Please fill in all fields</li>');
        return false;
    }
};

var validateForm = function(form, nagDiv, fName, lName, email) {
    var firstNameRes, lastNameRes, emailRes;
    var nagList = nagDiv + " ul";
    
    $(nagList).empty();
    $(nagDiv + " p").remove();
    firstNameRes = validateName($("#" + fName), "first", nagList);
    lastNameRes = validateName($("#" + lName), "last", nagList);
    emailRes = validateEmail($("#" + email), nagList);
    
    if (validateAllFilled(form, nagList)) {
        if (firstNameRes && lastNameRes && emailRes) {
            writeCookie("registered", 1, 500);
            $(form).submit();
        }
    } else {
        $("#nag").prepend('<p style="color:#f00; font-weight:bold">Your form could not be submitted for the following reasons:</p>');
    }
};

