
/**
 * Error Handling File, Fontshop.com
 *
 * This file handles all of the newer in-line error messages by validating
 * them and displaying the appropriate confirmation or error messages inline.
 *
 * Author: Nick Fehr <nick@fontshop.com>
 */


var LOGIN_FORM;

/**
* This function simply gets an element by ID. I used it to consolidate my code.
* Return: HTMLelement
*/
function getById(id){
	return document.getElementById(id);
}	

// Instantiates Dataset. Redundant, since each field is reset in each function
// but I'm trying to work within the class created in addresses.js. Fehr 6/23/08
if (getById("create_account")){
	LOGIN_FORM = new Dataset(getById("create_account"));
} 

/*
	This function will make a red background flash and then fade
	It's used to hightlight information in the form that hasn'y been filled out yet. 
*/		
	function redFade(el) {
	  var b = 100;
	  function f() {
	    el.style.background = 'rgb(255,' + (b+=4) + ',' + (b+=4) + ')';
	    if (b < 255) {
	      setTimeout(f, 40);
	    } else {
			el.style.background = ''; 
		}	
	  };
	 f();
	}
/*
* This function returns true if the argument is a string
*/	
function isString(a) {
    return typeof a == 'string';
}

/**
* This function validates the first name and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkName (input) {
	LOGIN_FORM.firstname = input.value; //necessary in case value is changed
	var inputParent = input.parentNode;
	var markHolder = inputParent.getElementsByTagName("span")[0];
	if(LOGIN_FORM.validateName()){
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; required';
		return false;
	}
}


/**
* This function validates the first name and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkLastName (input) {
	LOGIN_FORM.lastname = input.value; //necessary in case value is changed
	var inputParent = input.parentNode;
	var markHolder = inputParent.getElementsByTagName("span")[0];
	if(LOGIN_FORM.validateLastName()){
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; required';
		return false;
	}
}



/**
* This function validates email using validateEmailAddress in addresses.js 
* and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkEmail(input) {
	LOGIN_FORM.email_address = input.value; //necessary in case value is changed
	var markHolder = getById("emailSpan");
	if (LOGIN_FORM.validateEmailAddress()) {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; must be valid';
		return false;
	}
}

/**
* This function validates email using a different regular expression and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkEmail2(input) {
	// var valid_email= "^[A-Za-z0-9\+\_\.]+@[A-Za-z0-9\+\_\.]+\.[A-Za-z]{2,}$";
	// var email = new RegExp(valid_email);
	// if (email.test(input.value)) {
		// return true;
	// } else {
		// return false;
	// }
	if (input.value)
		return true;
}

/**
* This function validates phone numbers using validateTelephone() from addresses.js and 
* displays appropriate messages.
* Parameters: input element
* Return: boolean
*/
function checkPhoneNumber(input) {
	LOGIN_FORM.telephone = input.value; //necessary in case value is changed
	var markHolder = getById("phoneSpan");
	if (LOGIN_FORM.validateTelephone()) {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; must be valid';
		return false;
	}
}

/**
* This function validates the street address using validateStreetAddress() in addresses.js 
* and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkStreetAddress(input) {
	LOGIN_FORM.street_address = input.value; //necessary in case value is changed
	var markHolder = getById("addSpan");
	if (LOGIN_FORM.validateStreetAddress()) {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; must be valid';
		return false;
	}
}

/**
* This function validates city using validateCity() in addresses.js and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkCity(input) {
	LOGIN_FORM.city = input.value; //necessary in case value is changed
	var markHolder = getById("citySpan");
	if (LOGIN_FORM.validateCity() && isString(input.value)) {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; must be valid';
		return false;
	}
}

/**
* This function displays the state dropdown/ input field
*/
function showState(){
	updateCountry(this);
	LOGIN_FORM.showState();
}

/**
* This function updates the country element when selected
* Parameters: input element
*/
function updateCountry(input) {
	LOGIN_FORM.country = input.value;
	LOGIN_FORM.setCountryId();
}


function checkCountry(input) {
	var markHolder = getById("countrySpan");
	if (LOGIN_FORM.validateCountryId()){
		
		markHolder.innerHTML = '&nbsp;<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&nbsp;&#9664; please select';
		return false;
	}
}

/**
* This function validates Postal Code using validatePostcode() in addresses.js and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function checkPostCode(input) {
	if (getById("country").value != 130) { //Ireland: The Edge Case
		LOGIN_FORM.postcode = input.value; //necessary in case value is changed
		var markHolder = getById("postSpan");
	
		if (LOGIN_FORM.validatePostcode()) {
			markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
			return true;
		} else {
			markHolder.innerHTML = '&#9664; must be valid';
			return false;
		}
	}
}


/**
* This function checks to see if the password has enough characters with validateLength() from addresses.js
* and displays appropriate messages
* Parameters: input element
* Return: boolean
*/
function passwordValid(input) {
	LOGIN_FORM.password = input.value; //necessary in case value is changed
	var markHolder = getById("passVSpan");
	if (!LOGIN_FORM.validateLength()) {
		markHolder.innerHTML = '&#9664; minimum of 5 characters';	
		return false;
	} else {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	}
}



/**
* This function validates the password using validatePassword() in addresses.js and displays appropriate 
* messages. It checks to see if the two passwords match.
* Parameters: input element
* Return: boolean
*/
function checkPassword(input) {
	LOGIN_FORM.confirmation = input.value; //necessary in case value is changed
	var markHolder = getById("passSpan");
	if (LOGIN_FORM.validatePassword()) {
		markHolder.innerHTML = '<img src="images/errors/bg-fieldset-welldone.gif" />';
		return true;
	} else {
		markHolder.innerHTML = '&#9664; must match';
		return false;
	}
}


/**
* Error message function. Displays red error message with unicode arrow pointing left.
* Takes the ID of the empty element to place the message in as a parameter.
* Parameters: elementId, messsage
*/
function redErrorMessage(elementId, message){
	var markHolder = getById(elementId);
	markHolder.style.color="red";
	markHolder.innerHTML = '&#9664; ' + message;
}

//Validates the entire registration form. Returns true if valid. 
if (document.getElementById("submitRegister")) {
	IS_VALID_REG = false;
}

/**
* This function validates the entire registration form and displays messages.
* Return: boolean
*/
function checkRegistrationForm() {
	IS_VALID_REG = true;
	var submitButton = getById("submitRegister");
	
	if (!checkName(getById("firstname"))){
			redErrorMessage("firstnameSpan", "required");
			IS_VALID_REG = false;
	}
	if (!checkLastName (getById("lastname"))){
			redErrorMessage("lastnameSpan", "required");
			IS_VALID_REG = false;
	}
	if (!checkEmail(getById("email_address_registration"))){
			redErrorMessage("emailSpan", "must be valid");
			IS_VALID_REG = false;
	}
	if (!checkPhoneNumber(getById("telephone"))){
			redErrorMessage("phoneSpan", "must be valid");
			IS_VALID_REG = false;
	}
	if (!checkStreetAddress(getById("street_address"))){
			redErrorMessage("addSpan", "must be valid");
			IS_VALID_REG = false;
	}
	if (!checkCity(getById("city"))){
			redErrorMessage("citySpan", "must be valid");
			IS_VALID_REG = false;
	}

	if (!checkCountry()){
			getById("countrySpan").innerHTML =  "&nbsp;&#9664; please select"; 
			IS_VALID_REG = false;
	}
	
	if (!checkPostCode(getById("postcode"))){
		if (getById("country").value != 130) {
			redErrorMessage("postSpan", "must be valid");
			IS_VALID_REG = false;
		} else if (getById("country")=='130') { // Jacob: can be ELSe
			IS_VALID_REG = true;
		}			
	}

	LOGIN_FORM.password = getById("password_registration"); //necessary in case value is changed
	if (!passwordValid(getById("password_registration"))) {
			redErrorMessage("passVSpan", "minimum of 5 characters");
			IS_VALID_REG = false;
	}
	
	if (!checkPassword(getById("confirmation"))) {
			redErrorMessage("passSpan", "must match");
			IS_VALID_REG = false;
	}	
	
	//submits the form if valid
	if (IS_VALID_REG == true){
		submitButton.setAttribute('src', "/images/icons/loader.gif");
		submitButton.style.width="71px";
		submitButton.style.height="20px";
	}	
	
	// alert (IS_VALID_REG);
	
	return IS_VALID_REG;
}

/**
* This function checks the contact form and returns true if 
* all fields are correct. Appropriate error messages are displayed
* and the form can then be submitted.
* Return: boolean
*/
function checkContactForm() {

	IS_VALID_CONTACT = true;
	var markHolder = getById("submitDiv");
	
	if (!getById("recipient").value) {
		redErrorMessage("queryTypeSpan", "required");
		IS_VALID_CONTACT = false;
	} else {
		getById("queryTypeSpan").innerHTML = '';
	}
	
	if (!getById("name").value) {
		redErrorMessage("nameSpan", "required");
		IS_VALID_CONTACT = false;
	} else {
		getById("nameSpan").innerHTML = '';
	}
	
	if (!checkEmail2(getById("email"))) {
		redErrorMessage("emailSpan", "must be valid");
		IS_VALID_CONTACT = false;
	} else {
		getById("emailSpan").innerHTML = '';
	}
	
	if (!getById("comments").value) {
		redErrorMessage("commentSpan", "required");
		IS_VALID_CONTACT = false;
	} else {
		getById("commentSpan").innerHTML = '';
	}
	
	if (IS_VALID_CONTACT == false){
			markHolder.style.color="red";
			markHolder.innerHTML = "There are errors in your form submission. Please review above.";
	} else if (IS_VALID_CONTACT == true) {
			getById("submitDiv").innerHTML = '';
			markHolder.innerHTML = "";
			getById("submitContact").setAttribute('src', "/images/icons/loader.gif");
	}
	
	return IS_VALID_CONTACT;
}

/** 
* This function validates the Login process. There are multiple 
* <span>s that are used to hold error messages and unicode arrows
* which get set depending on the field's validity.
* Return: boolean
*/
function checkLogin() {
	IS_VALID_LOGIN = true; //global
	var loginButton = getById("loginSubmitButton");

	if (!checkEmail2(getById("email_address_login"))){
		getById("incorrectPasswordSpan").innerHTML="";
		redErrorMessage("emailLoginSpan", "");
			var markHolder = getById("emailLoginSpanMessage");
			markHolder.style.color="red";
			markHolder.innerHTML = "must be valid";
		IS_VALID_LOGIN = false;
	} else {
		getById("incorrectPasswordSpan").innerHTML="";
		getById("emailLoginSpanMessage").innerHTML="";
		getById("emailLoginSpan").innerHTML="";
	}
	
	if (!getById("password").value && checkEmail2(getById("email_address_login"))) {
		getById("incorrectPasswordSpan").innerHTML="";
		redErrorMessage("passwordLoginSpan", "");
			var markHolder = getById("passwordLoginSpanMessage");
			markHolder.style.color="red";
			markHolder.innerHTML = "required";
		IS_VALID_LOGIN = false;
	} else {
		getById("incorrectPasswordSpan").innerHTML="";
		getById("passwordLoginSpanMessage").innerHTML="";
		getById("passwordLoginSpan").innerHTML="";
	}
	
	if (IS_VALID_LOGIN) {
		loginButton.setAttribute('src', "/images/icons/loader.gif");
		loginButton.style.width="69px";
		loginButton.style.height="20px";
	}
	
	return IS_VALID_LOGIN;
}

/** 
* Validation for credit card in cart checkout.
* Functions to check each field and one that 
* checks whole form to prevent submission
* when there are errors. Fehr 7/1/08 
* Return: boolean
*/
if (getById("wordBubbleCode") || getById("wordBubbleDeclined")){
	showSecurityCode();
}

/**
* Returns true if a card type is selected
* Return: boolean
*/

IS_VALID_CARD_TYPE = false;
function checkCardType() {
	cc_swap_submit_button();
	cc_select_card();
	
	if (getById("cardTypeSelect").value != "none") {
		getById("cardTypeSpan").innerHTML = "";
		IS_VALID_CARD_TYPE = true;
		cc_swap_submit_button();
	} else {
		getById("cardTypeSpan").innerHTML = "&#9664; Please&nbsp;select"; 
		IS_VALID_CARD_TYPE = false;
		cc_swap_submit_button();
	}

	if (getById("cc_number").value != "" && !checkCardNumber()) {
		getById("cardNumberSpan").innerHTML =  "&nbsp;&#9664; must&nbsp;be&nbsp;valid"; //extra space needed
		getById("cardNumberSpan").style.color="grey";
	}
	
	if (getById("cc_ccv").value != "" && !checkCardCode()) {
		getById("cardCodeSpan").innerHTML = "&#9664; must be valid";
		getById("cardCodeSpan").style.color = "grey";
	} else {
		getById("cardCodeSpan").innerHTML = "";
	}
	cc_swap_submit_button();
}

/**
* Checks if the card number is valid (16 characters long - beginning with a 3 if Amex, 
* 4 => Visa, 5=> Mastercard, 6=> Discover). Outputs error message
* 
* UPDATE: adding validation from cc_validation...
*/

IS_VALID_CARD_NUMBER = false;
function checkCardNumber() {
	cc_swap_submit_button();
	cc_select_card();

	var cardType = getById("cardTypeSelect").value;
	var cardNum = getById("cc_number").value;
	var numSpan = getById("cardNumberSpan");
	
	var regex_amex = new RegExp("^3[47][0-9]{13}$");
	var regex_visa = new RegExp("^4[0-9]{12}([0-9]{3})?$");
	var regex_mcard = new RegExp("^5[1-5][0-9]{14}$");
	var regex_discover = new RegExp("^6011[0-9]{12}$");

	if(cardNum == "") {
		IS_VALID_CARD_NUMBER = false;
		cc_swap_submit_button();
		numSpan.innerHTML = '&nbsp;&#9664; Please&nbsp;enter'; 
		numSpan.style.color="grey";
	} else if (cardType == "amex" && regex_amex.test(cardNum)) {
		IS_VALID_CARD_NUMBER = true;
		cc_swap_submit_button();
	} else if (cardType == "visa" && regex_visa.test(cardNum)) {
		IS_VALID_CARD_NUMBER = true;
		cc_swap_submit_button();
	} else if (cardType == "mcard" && regex_mcard.test(cardNum)) {
		IS_VALID_CARD_NUMBER = true;
		cc_swap_submit_button();
	} else if (cardType == "discover" && regex_discover.test(cardNum)) {
		IS_VALID_CARD_NUMBER = true;
		cc_swap_submit_button();
	} else {
		IS_VALID_CARD_NUMBER = false;
		cc_swap_submit_button();
		numSpan.innerHTML = " &#9664; must&nbsp;be&nbsp;valid"; 
		numSpan.style.color="grey";
	}
	
	if (IS_VALID_CARD_NUMBER){
		numSpan.innerHTML = "";
	}
	
	cc_swap_submit_button();
	
	return IS_VALID_CARD_NUMBER;
}


/**
* Checks if the credit card date is valid by checking it against the current date. prints error message
*/

IS_VALID_DATE = false;
function checkCardDate() {
	cc_swap_submit_button();
	
	var now = new Date();
	var dateErrorSpan2 = getById("cardDateSpan2");

	if (parseInt(getById("cc_expires_year").value, 10) < (now.getFullYear() - 2000)) {
		IS_VALID_DATE = false;
		cc_swap_submit_button();
	} else if (parseInt(getById("cc_expires_year").value, 10) == (now.getFullYear() - 2000) && 
			  (getById("cc_expires_month").value < (now.getMonth() + 1))) {
		IS_VALID_DATE = false;
		cc_swap_submit_button();
	} else {
		dateErrorSpan2.innerHTML = ""
		IS_VALID_DATE = true;
		cc_swap_submit_button();
	}
	
	if (!IS_VALID_DATE){
		dateErrorSpan2.innerHTML = "&nbsp;&nbsp;&#9664; must&nbsp;be&nbsp;valid"; //extra space needed
		dateErrorSpan2.style.color="grey";
	}
	
	cc_swap_submit_button();
}

/**
* Checks if the code is not 3 numbers long (4 if Amex). outputs error message
*/

IS_VALID_CODE = false;

function checkCardCode() {
	var codeSpan = getById("cardCodeSpan");
	var isInt = /^\d+$/.test(getById("cc_ccv").value);
	
	
	if (getById("cc_ccv").value.length == 3 && isInt){
		if (getById("cardTypeSelect").value == "amex"){
			IS_VALID_CODE = false;
		} else {
			IS_VALID_CODE = true;
		}
		cc_swap_submit_button();

	} else if (getById("cc_ccv").value.length == 4 && isInt){
		if (getById("cardTypeSelect").value == "amex"){
			IS_VALID_CODE = true;
		} else {
			IS_VALID_CODE = false;
		}
		cc_swap_submit_button();
	} else if (isInt){
		IS_VALID_CODE = false;
		cc_swap_submit_button();
	}
	
	if (IS_VALID_CODE) {
		codeSpan.innerHTML = "";
	} else {
		codeSpan.innerHTML = "&#9664; must be valid";
		codeSpan.style.color = "grey";
	}
	
	return IS_VALID_CODE;
}

IS_VALID_INVOICE = false;

function checkPayByInvoice(){
    if (getById('paymentinvoice')) {
	if(getById('paymentinvoice').checked){
		IS_VALID_INVOICE = true;
	} else {
		IS_VALID_INVOICE = false;
	}
	cc_swap_submit_button();
    }
}

/**
* Validates whole credit card form. Returns true if completely valid. 

*/

function checkCreditCard() {
	checkPayByInvoice();

	if (!IS_VALID_INVOICE){ 
		checkCardType();
		if (IS_VALID_CARD_TYPE){
			checkCardNumber();
			if (IS_VALID_CARD_NUMBER){
				checkCardDate();
				if (IS_VALID_DATE){
					checkCardCode();
				}
			}
		}	
		cc_swap_submit_button();
		return (IS_VALID_CARD_TYPE && IS_VALID_CARD_NUMBER && IS_VALID_DATE && IS_VALID_CODE);
		
	} else {
		return IS_VALID_INVOICE;
	}
}

function cc_select_card(){
	if (getById("paymentcybersource")){
		getById("paymentcybersource").checked = true;
	}
}

function cc_swap_submit_button() {
	var checkoutButton = getById("checkout_submit_button"); //grey
	var checkoutButton2 = getById("checkout_submit_button_good"); //green
	
	//for debugging:
	//getById("todebug").innerHTML = "<br />" + IS_VALID_CARD_TYPE + IS_VALID_CARD_NUMBER + IS_VALID_DATE + IS_VALID_CODE;
	if (!IS_VALID_INVOICE && IS_VALID_CARD_TYPE && IS_VALID_CARD_NUMBER && IS_VALID_DATE && IS_VALID_CODE){
			checkoutButton2.style.display= "";
			checkoutButton.style.display="none";
	} else if (IS_VALID_INVOICE){
			checkoutButton2.style.display= "";
			checkoutButton.style.display="none";
	} else {
			checkoutButton.style.display="";
			checkoutButton2.style.display="none";
	}
}

function redFades() {
	redFade(getById("cardNumberSpan"));
	redFade(getById("cardTypeSpan"));
	redFade(getById("cardCodeSpan"));
	redFade(getById("cardDateSpan2"));
	
	if(getById("billingAddressError")){
		redFade(getById("billingAddressError"));
	}
}

/**
* Validates the EULA agreement page. Returns true if all EULA boxes are checked	
* Return: boolean
*/
function checkEULA() {
	IS_VALID_EULA = true;	
	
	var errorButton = getById("eulaSubmitButton");
		errorButton.src=  "includes/languages/english/images/buttons/button_submit_off.gif";
		
	var eulaArray = new Array(); //array for checkbox objects
	var eulaCounter = 0;
	
	while(getById("eula_agreed" + eulaCounter)) {
		eulaArray[eulaCounter] = getById("eula_agreed" + eulaCounter);
		eulaCounter++;
	}
	var numChecked = 0;	
	
	for (var i=0; i<eulaArray.length; i++) {
		if (eulaArray[i].checked == false) {
			redErrorMessage("eulaErrorSpan" + i, "This item must be checked to continue");
			getById("eulaErrorBottom").innerHTML = "You must agree to each foundry's user license to continue";
			errorButton.src= "includes/languages/english/images/buttons/button_submit_grey.gif";
			errorButton.style.cursor="default";	
		} else {
			getById("eulaErrorSpan" + i).innerHTML = "";
			numChecked++;
		}
	}
	
	if (numChecked == eulaArray.length && numChecked > 0) {
		getById("eulaErrorBottom").innerHTML = "";
		errorButton.src= "includes/languages/english/images/buttons/button_submit_off.gif";
		errorButton.style.cursor="pointer";
		IS_VALID_EULA = true;
	} else {
		IS_VALID_EULA = false;
	}
	return IS_VALID_EULA;
}

/*
Research page
*/


function checkResearch(){
	IS_VALID_RESEARCH = false;
	
	
	
	if (getById("appearance").value != ""){
		IS_VALID_RESEARCH = true;
	}
	
	if (!IS_VALID_RESEARCH){
		getById("appearance_span_error").innerHTML = "must enter description &#9650;";
	} else {
		getById("appearance_span_error").innerHTML = "";
	}
	
	return IS_VALID_RESEARCH;
}