/*global window, document, Image, $, pcaLookupStatus: true, pcaCompleteAddress, pcaSwitch, pcaInterceptKeystroke, submitted: true */

/*jslint sloppy: true */

window.onload = function () {
	if (document.images) {
		submitted = new Image(179, 29);
		submitted.src = "/images/please-wait.gif";
	}
};

/**
 * check_email()
 * Checks that an email address is well-formed
 * @param {String} emailAddress
 * @returns {Boolean} whether the email address is well-formed or not.
 */
function check_email(emailAddress) {
	/*jslint regexp: true */
	var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.+@-_QWERTYUIOPASDFGHJKLZXCVBNM",
		i,
		re,
		re_two;
	for (i = 0; i < emailAddress.length; i++) {
		if (ok.indexOf(emailAddress.charAt(i)) < 0) {
			return false;
		}
	}
	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!emailAddress.match(re) && emailAddress.match(re_two)) {
			return -1;
		}
	}
}

function isCardnumber(sText) {
	var validChars = "0123456789 ",
		isNumber = true,
		character,
		i;
	for (i = 0; i < sText.length && isNumber === true; i++) {
		character = sText.charAt(i);
		if (validChars.indexOf(character) === -1) {
			isNumber = false;
		}
	}
	return isNumber;
}

function luhn_check(number) {
	number = number.replace(/\D/g, '');
	var parity = number.length % 2,
		total = 0,
		i,
		digit;

	for (i = 0; i < number.length; i++) {
	    digit = number.charAt(i);
		if (i % 2 === parity) {
			digit = digit * 2;
			if (digit > 9) {
				digit = digit - 9;
			}
		}
		total = total + parseInt(digit, 10);
	}
	if (total % 10 === 0) {
		return true;
	} else {
		return false;
	}
}

function isChecked(butts) {
	var buttlength = butts.length,
		i;
	for (i = 0; i < buttlength; i++) {
		if (butts[i].checked) {
			return true;
		}
	}
	return false;
}

function fieldInError(field) {
	try {
		field.focus();
	}
	catch (ex) { }
	field.style.backgroundColor = 'yellow';
}

function showValidationMsg(msg) {
	if (typeof msg !== 'undefined' && msg !== '') {
		window.alert("Sorry, something's not quite right.\n\n" + msg);
	}
}

function getSelectedAddressId(theform) {
	var address_id = -1,
		i;

	if (!theform.choose_address || theform.choose_address.value === '0') {
		address_id = 0;
	}
	else {
		for (i = 0; i < theform.choose_address.length; i++) {
			if (theform.choose_address[i].checked === true) {
				address_id = theform.choose_address[i].value;
				break;
			}
		}
	}
	return 0;
}

function step1(theform) {
	var okToContinue = false,
		msg = '';

	if (!check_email(theform.email.value.replace(/^\s+|\s+$/g, ""))) {
		msg = 'Please can you check that your e-mail address is right.\n\n' +
			'You might have missed a dot or an @ sign.';
		fieldInError(theform.email);
		okToContinue = false;
	}
	else if (theform.existing_account[1].checked && !theform.password.value.length) {
		msg = "Please enter your password, or select the option to continue without a password.";
		theform.email.style.backgroundColor = '';
		fieldInError(theform.password);
		okToContinue = false;
	}
	else {
		okToContinue = true;
	}

	showValidationMsg(msg);
	return okToContinue;
}

function step1a(theform) {
	if (theform.phone && theform.phone.value === '') {
		showValidationMsg('Please can you enter your contact phone number.');
		fieldInError(theform.phone);
		return false;
	} else {
		return true;
	}
}

function step1b(theform, existingcards) {
	if (existingcards === '1') {
		if (!isChecked(theform.paytype)) {
			showValidationMsg('Please can you choose an existing card or payment method.');
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
}

function validateStep2and3(theform, step, currency, paymentType) {
	var address_id = getSelectedAddressId(theform),
		okToContinue = false,
		msg = '',
		usdMsg,
		person = step === 2 ? 'recipient' : 'cardholder';
	if (address_id === -1) {
		msg = "Please can you choose an existing address, or enter a new address.";
		okToContinue = false;
	} else if (address_id === 0) {
		if (theform.firstname.value === '') {
			msg = "Please can you enter the " + person + "'s first name.";
			fieldInError(theform.firstname);
			okToContinue = false;
		} else if (theform.lastname.value === '') {
			msg = "Please can you enter the " + person + "'s last name.";
			fieldInError(theform.lastname);
			okToContinue = false;
		} else if (step === 2 && theform.country.value !== '13' && theform.phone.value === '') {
			msg = "Please can you enter a contact phone number.";
			fieldInError(theform.phone);
			okToContinue = false;
		} else if (theform.address1.value === '') {
			msg = "Please can you enter the delivery address.";
			//if (typeof pcaSwitch == 'function') pcaSwitch('manual');
			fieldInError(theform.address1);
			okToContinue = false;
		} else if (theform.city.value === '') {
			msg = "Please can you enter the delivery town or city name.";
			//if (typeof pcaSwitch == 'function') pcaSwitch('manual');
			fieldInError(theform.city);
			okToContinue = false;
		} else if (step === 2 && theform.country.value === '21' && theform.state.value === '') {
			msg = "Please can you enter the state.";
			fieldInError(theform.state);
			okToContinue = false;
		} else if (theform.country.value !== '8' && theform.postcode.value === '') {
			msg = "Please can you enter the delivery postcode.";
			//if (typeof pcaSwitch == 'function') pcaSwitch('manual');
			fieldInError(theform.postcode);
			okToContinue = false;
		} else if (step === 2 && paymentType === 'cc' && theform.cardholder && !theform.cardholder[0].checked && !theform.cardholder[1].checked) {
			msg = "Please can you tell us if this is also the cardholder's address.";
			theform.cardholder[0].focus();
			okToContinue = false;
		} else if (step === 2 && theform.country.value === '21' && currency !== 'USD') {
			usdMsg = "This is a really important message for US citizens.\n\n" +
				"Lovehoney is a United Kingdom Web site. The prices shown on the site " +
				"are in UK pounds sterling unless you choose US dollars or Euros.\n\n" +
				"You have chosen the USA as a billing address, but have not chosen to " +
				"be billed in US dollars.\n\nIf you would like to be billed in US dollars, " +
				"please click Cancel and click 'back' to return to Lovehoney to select " +
				"US dollars.\n\nOtherwise, please click OK and continue with your order.";
			okToContinue = window.confirm(usdMsg);
		} else {
			okToContinue = true;
		}
	} else if (step === 2 && paymentType === 'cc' && theform.cardholder && !theform.cardholder[0].checked && !theform.cardholder[1].checked) {
		msg = "Please can you tell us if this is also the cardholder's address.";
		theform.cardholder[0].focus();
		okToContinue = false;
	}
	showValidationMsg(msg);
	return okToContinue;
}

function changeSubmitButtonState(state) {
	if (state === 'address') {
		$('#address_submit_button')
			.val('Find the address');
	}
	else {
		$('#address_submit_button')
			.val('Click to continue');
	}
}

function checkLookupStatus() {
	var lookupInterval = window.setInterval(function () {
		if (pcaLookupStatus !== 'init') {
			// If we have a non-init status, stop the interval timer
			window.clearInterval(lookupInterval);
			if (pcaLookupStatus === 'success') {
				changeSubmitButtonState('continue');
			}
		}
	}, 500);
}

function step2and3(theform, step, currency, paymentType) {
	var okToContinue = false,
		div_address = document.getElementById('div_address'),
		lookupInterval;
	if (typeof paymentType === 'undefined') {
		paymentType = 'cc';
	}
	if (typeof currency === 'undefined') {
		currency = 'GBP';
	}
	// As long as UK, and name fields filled in, and empty address1 OR hidden div_address,
	// use PCA to complete address
	if (theform.country.value === '13' && $('#find_address').is(':visible') &&
		theform.firstname.value !== '' && theform.lastname.value !== '' &&
		(theform.address1.value === '' || div_address.style.display !== 'block')) {
		// Reset the lookup status, for multiple lookups within one page request
		pcaLookupStatus = 'init';
		pcaCompleteAddress();
		lookupInterval = window.setInterval(function () {
			if (pcaLookupStatus !== 'init') {
				// If we have a non-init status, stop the interval timer
				window.clearInterval(lookupInterval);
				if (pcaLookupStatus === 'success') {
					okToContinue = validateStep2and3(theform, step, currency, paymentType);
					changeSubmitButtonState('continue');
				}
			}
		}, 500);
	}
	// Otherwise, validate the form
	else {
		okToContinue = validateStep2and3(theform, step, currency, paymentType);
	}
	return okToContinue;
}

function step2(theform, currency) {
	return step2and3(theform, 2, currency, 'cc');
}

function step2cheque(theform, currency) {
	return step2and3(theform, 2, currency, 'cq');
}

function step3(theform) {
	return step2and3(theform, 3);
}

function step4(theform) {
	var requestSubmitted = false,
		okToContinue = false,
		msg = '';
	if (document.images) {
		submitted = new Image(179, 29);
		submitted.src = "/images/please-wait.gif";
	}
	if (theform.card_name.value === '') {
		msg = "Please can you enter the card holder's name.";
		fieldInError(theform.card_name);
		okToContinue = false;
	} else if (theform.card_number.value === '' || !isCardnumber(theform.card_number.value) || !luhn_check(theform.card_number.value)) {
		msg = "Please can you enter a valid card number.";
		fieldInError(theform.card_number);
		okToContinue = false;
	} else if (theform.cv2.value === '') {
		msg = "Please can you enter the 3-digit security code from the back of your card.";
		fieldInError(theform.cv2);
		okToContinue = false;
	} else {
		document.getElementById('place').src = '/images/please-wait.gif';
		document.getElementById('place-order').blur();
		document.getElementById('place-order').disabled = true;
		if (!requestSubmitted) {
			requestSubmitted = true;
			okToContinue = true;
		}
	}
	showValidationMsg(msg);
	return okToContinue;
}

function confirmCard(theform) {
	var requestSubmitted = false;
	if (document.images) {
		submitted = new Image(179, 29);
		submitted.src = "/images/please-wait.gif";
	}
	document.getElementById('place').src = '/images/please-wait.gif';
	document.getElementById('place-order').blur();
	document.getElementById('place-order').disabled = true;
	if (!requestSubmitted) {
		requestSubmitted = true;
		return true;
	}
	return false;
}

function confirmPayPal(theform) {
	var requestSubmitted = false;
	if (document.images) {
		submitted = new Image(179, 29);
		submitted.src = "/images/please-wait.gif";
	}
	document.getElementById('place').src = '/images/please-wait.gif';
	document.getElementById('place-order').blur();
	document.getElementById('place-order').disabled = true;
	if (!requestSubmitted) {
		requestSubmitted = true;
		return true;
	}
	return false;
}

function stepconfirm(theform) {
	var requestSubmitted = false;
	if (document.images) {
		submitted = new Image(179, 29);
		submitted.src = "/images/please-wait.gif";
	}
	document.getElementById('place').src = '/images/please-wait.gif';
	document.getElementById('place-order').blur();
	document.getElementById('place-order').disabled = true;
	if (!requestSubmitted) {
		requestSubmitted = true;
		return true;
	}
	return false;
}

function confirmEmail(theform) {
	if (!check_email(theform.email.value.replace(/^\s+|\s+$/g, "")))	{
		//alert('Sorry, something\'s not quite right.\n\nPlease can you check that your e-mail address is right.\n\nYou might have missed a dot or an @ sign.');
		fieldInError(theform.email);
		return false;
	} else {
		return true;
	}
}

$(document).ready(function () {
	// Change submit button
	$('#pcaSelect').change(function () {
		changeSubmitButtonState('continue');
	});

	$('#pca_switch_another,#pca_switch_idontknow,#pca_switch_manual').click(function () {
		var mode = this.id.replace('pca_switch_', ''),
			buttonState = mode === 'manual' ? 'continue' : 'address';
		changeSubmitButtonState(buttonState);
		return pcaSwitch(mode);
	});

	$('#find_address').click(function () {
		pcaCompleteAddress();
		checkLookupStatus();
	});

	if ($('#address1').is(':visible')) {
		changeSubmitButtonState('continue');
	}

	$('#housename_1,#streetname_1,#postcode_1').keypress(function (event) {
		return pcaInterceptKeystroke(event);
	});

	$('select[name=country]').change(function (e) {
		changeSubmitButtonState($(e.target).val() === '13' && $('#find_address').is(':visible') ? 'address' : 'continue');
	});

});

