/*------------------- Constants -------------------*/

var VALIDATE_WHITESPACE              = " \t\n\r";
var VALIDATE_REQUIRED_INDICATOR      = '<img src="../images/required.gif" width="7" height="9" alt="required information">';
var VALIDATE_TEXTFIELD_NORMAL_CLASS  = 'textField';
var VALIDATE_TEXTFIELD_INVALID_CLASS = 'textFieldError';
var VALIDATE_TEXT_AREA_NORMAL_CLASS  = 'textArea';
var VALIDATE_TEXT_AREA_INVALID_CLASS = 'textAreaError';
var VALIDATE_LIST_NORMAL_CLASS       = 'selectNormal';
var VALIDATE_LIST_INVALID_CLASS      = 'selectError';
var VALIDATE_COOKIE_KEY              = 'validationCookie';
var VALIDATE_EXPIRATION_WEEKS        = 3;
var VALIDATE_EXPIRATION_DATE         = new Date((new Date()).getTime() + VALIDATE_EXPIRATION_WEEKS * 7 * 24 * 60 * 60 * 1000);
var VALIDATE_WAY_BACK_WHEN           = new Date((new Date()).getTime() - 500 * 7 * 24 * 60 * 60 * 1000);
var VALIDATE_MIN_PHONE_CHARACTERS    = 7;

var debug = false;

/*------------------- Common validation functions -------------------*/

function isEmpty(value)
{
	return (value == null) || (value.length == 0);
}

function isNotEmpty(value)
{
	return !isEmpty(value);
}

function isWhitespace(s)
{
    if (isEmpty(s))
	{
		return true;
	}

    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (VALIDATE_WHITESPACE.indexOf(c) == -1)
		{
			return false;
		}
    }

    return true;
}

function isLetter(c)
{
	return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) );
}

function isDigit(c)
{
	return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit(c)
{
	return (isLetter(c) || isDigit(c))
}

function isInteger(s)
{
	if (isEmpty(s))
	{
		return false;
	}

    for (var i = 0; i < s.length; i++)
    {
		var c = s.charAt(i);
		if (!isDigit(c))
		{
			return false;
		}
    }

    return true;
}

function isEmailCharacters(s)
{
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) || (c=='@') || (c=='.') || (c=='_') || (c=='-') || (c=='+')) )
		{
       		return false;
		}
    }

    return true;
}

function isEmail(s)
{
	if (isEmpty(s) || isWhitespace(s) || !isEmailCharacters(s))
	{
		return false;
	}

    atOffset = s.lastIndexOf('@');

    if (atOffset < 1)
	{
        return false;
	}
    else
	{
 		dotOffset = s.indexOf('.', atOffset);

		if (dotOffset < atOffset + 2 || dotOffset > s.length - 2)
		{
			return false;
		}
	}

	return true;
}

function isEmailAddress(s)
{
	return isEmail(s);
}

function isPhoneNumberCharacters(s)
{
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (! (isDigit(c) || (c=='.') || (c=='-') || (c=='+') || (c=='(') || (c==')') || (c==' ')) )
		{
       		return false;
		}
    }

    return true;
}

function isPhoneNumber(s)
{
	if (isEmpty(s) || isWhitespace(s) || !isPhoneNumberCharacters(s) || s.length < VALIDATE_MIN_PHONE_CHARACTERS)
	{
		return false;
	}
	else
	{
		return true;
	}
}

/*------------------- The object ValidateObject -------------------*/

function ValidateObject(id, label, required, validate, validateFunction, clarification)
{
	this.id = id;
	this.label = label;
	this.required = required;
	this.validate = validate;
	this.validateFunction = validateFunction;
	this.clarification = clarification;
	if (arguments[6] != null)
	{
		this.value = arguments[6];
	}
	else
	{
		this.value = null;
	}
	
	this.isValid            = ValidateObject_isValid;
	this.showLabel          = ValidateObject_showLabel;
	this.showRequired       = ValidateObject_showRequired;
	this.createTextfield    = ValidateObject_createTextfield;
	this.createTextArea     = ValidateObject_createTextArea;
	this.createRadioButton  = ValidateObject_createRadioButton;
	this.createCheckbox     = ValidateObject_createCheckbox;
	this.createList         = ValidateObject_createList;
	
	return this;
}

function ValidateObject_isValid()
{
	if (this.validateFunction == null)
	{
		return true;
	}
	else
	{
		if (this.value == null)
		{
			return eval(this.validateFunction + '(null)');
		}
		else
		{
			return eval(this.validateFunction + '("' + escape(this.value) + '")');
		}
	}
}

function ValidateObject_showRequired()
{
	if (this.required)
	{
		document.write(VALIDATE_REQUIRED_INDICATOR);
	}
}

function ValidateObject_showLabel()
{
	document.write(this.label);
}

function ValidateObject_createTextfield(size, maxLength)
{
	var html = '<input type="text" name="' + this.id + '" id="' + this.id + '" ';
	if (size != null && size > 0)
	{
		html += 'size="' + size + '" ';
	}
	if (maxLength != null && maxLength > 0)
	{
		html += 'maxlength="' + maxLength + '" ';
	}
	
	if (this.validate)
	{
		if (this.isValid())
		{
			html += 'class="' + VALIDATE_TEXTFIELD_NORMAL_CLASS + '" ';
		}
		else
		{
			html += 'class="' + VALIDATE_TEXTFIELD_INVALID_CLASS + '" ';
		}
	}
	else
	{
		html += 'class="' + VALIDATE_TEXTFIELD_NORMAL_CLASS + '" ';
	}
	
	if (isEmpty(this.value))
	{
		html += 'value="">';
	}
	else
	{
		html += 'value="' + this.value + '">';
	}
	
	document.write(html);
}

function ValidateObject_createTextArea(cols, rows)
{
	var html = '<textarea name="' + this.id + '" id="' + this.id + '" ';
	if (cols != null && cols > 0)
	{
		html += 'cols="' + cols + '" ';
	}
	if (rows != null && rows > 0)
	{
		html += 'rows="' + rows + '" ';
	}
	
	if (this.validate)
	{
		if (this.isValid())
		{
			html += 'class="' + VALIDATE_TEXT_AREA_NORMAL_CLASS + '">';
		}
		else
		{
			html += 'class="' + VALIDATE_TEXT_AREA_INVALID_CLASS + '">';
		}
	}
	else
	{
		html += 'class="' + VALIDATE_TEXT_AREA_NORMAL_CLASS + '">';
	}
	
	if (!isEmpty(this.value))
	{
		html += this.value;
	}
	
	html += '</textarea>';
	
	document.write(html);
}

function ValidateObject_createRadioButton(value)
{
	var html = '<input type="radio" name="' + this.id + '" id="' + this.id + '" ';
	
	html += 'value="' + value + '"';
	
	if (value == this.value)
	{
		html += ' checked>';
	}
	else
	{
		html += '>';
	}

	document.write(html);
}

function ValidateObject_createCheckbox(value)
{
	var html = '<input type="checkbox" name="' + this.id + '" id="' + this.id + '" ';
	
	html += 'value="' + value + '"';
	
	if (value == this.value)
	{
		html += ' checked>';
	}
	else
	{
		html += '>';
	}

	document.write(html);
}

function ValidateObject_createList(opts)
{
	var size = null;
	if (arguments[1] != null)
	{
		size = arguments[1];
	}
	
	var multiple = false;
	if (arguments[2] != null)
	{
		multiple = arguments[2];
	}
	
	var extras = null;
	if (arguments[3] != null)
	{
		extras = arguments[3];
	}
	
	var html = '<select name="' + this.id + '" id="' + this.id + '"';
	if (size != null)
	{
		html += ' size="' + size + '"';
	}
	
	if (multiple)
	{
		html += ' multiple';
	}
	
	if (this.validate)
	{
		if (this.isValid())
		{
			html += ' class="' + VALIDATE_LIST_NORMAL_CLASS + '"';
		}
		else
		{
			html += ' class="' + VALIDATE_LIST_INVALID_CLASS + '"';
		}
	}
	else
	{
		html += ' class="' + VALIDATE_LIST_NORMAL_CLASS + '"';
	}
	
	if (extras != null)
	{
		html += ' ' + extras;
	}
	
	html += '>';
	
	for (var i = 0; i < opts.length; i++)
	{
		html += '<option';
		if (opts[i].value == this.value || opts[i].defaultSelected || opts[i].selected)
		{
			html += ' selected="selected"';
		}
		
		html += ' value="' + opts[i].value + '">';
		
		html += opts[i].text;
		
		html += '</option>';
	}
	
	html += '</select>'

	document.write(html);
}

/*------------------- Convenience functions -------------------*/

function validateArray(array)
{
	for (var i = 0; i < array.length; i++)
	{
		if (array[i].validate)
		{
			if (array[i].required)
			{
				if (!array[i].isValid())
				{
					return false;
				}
			}
			else
			{
				if (!isEmpty(array[i].value))
				{
					if (!array[i].isValid())
					{
						return false;
					}
				}
			}
		}
	}
	
	return true;
}

function findValidateObject(array, id)
{
	for (var i = 0; i < array.length; i++)
	{
		if (array[i].id == id)
		{
			return array[i];
		}
	}
	
	return null;
}

function showValidationErrors(array)
{
	if (!validateArray(array))
	{
		document.write('<tr>');
              document.write('<td class="errorBox"><table width="700" border="0" cellspacing="0" cellpadding="0">');
                document.write('<tr>');
                  document.write('<td style="vertical-align:top" width="1%"><img src="../images/iconErrorSmall.gif" width="31" height="31"></td>');
                  document.write('<td style="vertical-align:top"><table width="100%" border="0" cellspacing="0" cellpadding="0">');
                      document.write('<tr>');
                        document.write('<td class="errorTitle">Important Message</td>');
                      document.write('</tr>');
                      document.write('<tr>');
                        document.write('<td class="errorExplanation">The following information needs to be specified or corrected:</td>');
                      document.write('</tr>');
					  for (var i = 0; i < array.length; i++)
					  {
					  	if (array[i].validate)
						{
							if (!array[i].isValid())
							{
		                      document.write('<tr>');
							  document.write('<td class="errorFieldCell"><span class="errorFieldLabel">' +
							  	array[i].label +
								'</span> - ' +
								array[i].clarification +
								'.</td>');
		                      document.write('</tr>');
							}
						}
					  }
                    document.write('</table>');
                  document.write('</td>');
                document.write('</tr>');
              document.write('</table></td>');
            document.write('</tr>');
            document.write('<tr>');
              document.write('<td height="20">&nbsp;</td>');
            document.write('</tr>');
	}
}

function retrieveValidationArray()
{
	var key = VALIDATE_COOKIE_KEY;
	if (arguments[1] != null)
	{
		key = arguments[1];
	}
	
    var rawInfo = getCookie(key);
	if (rawInfo == null)
	{
	    return null;
	}
    
    // Parse out the information
	var infoArray = rawInfo.split('-->');
	var info = new Array(infoArray.length);
	for (var i = 0; i < infoArray.length; i++)
	{
	    var items = infoArray[i].split('::');
		if (debug)
		{
			for (var j = 0; j < items.length; j++) alert("Item[" + j + "] = <" + items[j] + ">");
		}
		info[i] = new ValidateObject(
							items[0],
							items[1],
							items[2] == "true" ? true : false,
							items[3] == "true" ? true : false,
							((isEmpty(items[4]) || items[4] == "null") ? null : items[4]),
							((isEmpty(items[5]) || items[5] == "null") ? null : items[5]),
							((isEmpty(items[6]) || items[6] == "null") ? null : items[6]));
	}
	
	return info;
}

function persistValidationArray(array)
{
	var key = VALIDATE_COOKIE_KEY;
	if (arguments[1] != null)
	{
		key = arguments[1];
	}
	
    // Create a string containing the customer's billing information
    var rawInfo = '';
    for (var i = 0; i < array.length; i++)
	{
        if (array[i] != null)
		{
            rawInfo += array[i].id +
                           "::" +
                           array[i].label +
                           "::" +
                           (array[i].required ? "true" : "false") +
                           "::" +
                           (array[i].validate ? "true" : "false") +
                           "::" +
                           (isEmpty(array[i].validateFunction) ? "" : array[i].validateFunction) +
                           "::" +
                           (isEmpty(array[i].clarification) ? "" : array[i].clarification) +
                           "::" +
                           (isEmpty(array[i].value) ? "" : array[i].value) +
                           "-->";
		}
	}
    
    // Trim off the last "-->"
    if (rawInfo.length > 0)
	{
        rawInfo = rawInfo.substring(0, rawInfo.length - 3);
	}
        
    // Track the information via a cookie
    setCookie(key, rawInfo, VALIDATE_EXPIRATION_DATE, "/");
}

function deleteValidationCookie()
{
	var key = VALIDATE_COOKIE_KEY;
	if (arguments[0] != null)
	{
		key = arguments[0];
	}
	
	setCookie(key, null, VALIDATE_WAY_BACK_WHEN, "/");
}
