(function() {

var MESSAGES = {
	ERR_EMPTY_USER:        "Member Name can not be empty",
	ERR_USER:              "Your member name must be between 5 and 25 characters in length, and can only contain letters and numbers.",
	ERR_PASS:              "Your password must be at least 5 letters or numbers and cannot contain any spaces or non-alphanumeric characters, such as !@#$%&*()_+:\"?.",
	ERR_PASS_MISMATCH:     "Your passwords do not match.",
	ERR_EMAIL:             "Your email address does not appear to be a valid address in the form yourname@yourdomain.com.",
	ERR_COLLEGELIVE_EMAIL: "College Live signup e-mails must end in '.edu'.",
	ERR_FIRSTNAME:         "Please enter your first name.",
	ERR_COUNTRY:           "Please choose your country.",
	ERR_BIRTH_YEAR:        "Your year of birth does not appear valid.",
	ERR_UNDERAGE:          "We're sorry, but we are unable to register you at this time. Please continue to enjoy Webshots without registering.",
	ERR_GENDER:            "Please choose your gender.",

	CHECKNAME_AVAILABLE:   "Available!",
	CHECKNAME_UNAVAILABLE: "Unavailable",
	CHECKNAME_ERROR:       "Try again",
	CHECKNAME_QUERY:       "Check Availability",

	NEWSLETTER1_HELP: "Keep tabs on the popularity of your photos (views and downloads)�plus, read your new comments and see who's given you a thumbs up!",
	NEWSLETTER3_HELP: "Bringing you the best of the best that's featured on Webshots each week as well as news and updates about the site.",
	NEWSLETTER4_HELP: "This roundup includes the week's latest Pro Shots photos. Now you'll never miss one!",
	NEWSLETTER5_HELP: "You'll be the first to know when your friends and favorite members upload new images to Webshots!"
};

var FormElements = $(
	'signup_username', 'signup_password', 'password_again', 'email_address',
	'firstname', 'country_code', 'birth_month', 'birth_day', 'birth_year',
	'gender', 'zip_code'
);

function showSuggestions(user, suggestions, delay) {
	var opts = '';
	for (var names = suggestions.split(' '), i = 0, l = names.length; i < l; i++) {
		opts += '<option value="' + names[i] + '">' + names[i] + '</option>';
	}

	var input = $('signup_username');

	var info = new PopupInfo;
	info.html = '\
		<div style="width: ' + input.offsetWidth + 'px">\
			<p>Sorry, the member name <strong>' + user + '</strong> is already taken.</p>\
			<p>Please try a different member name.  Some suggestions are listed below.</p>\
			<p>\
				<select onchange="var input = parent.$(\'signup_username\'); input.value = this.value; input.focus();">\
				<option value="0">Select one of these...</option>' + opts + '\
				</select>\
			</p>\
			<p id="login-prompt">If you <em>are</em> ' + user + ', <a href="login" target="_top">log in</a>.</p>\
		</div>';
	info.css = 'http://p.webshots.net/css/chromeCheckName.css';
	info.origin = 'element';
	info.position = 'bottom-right';
	info.showDelay = 0;
	info.hideDelay = -1;
	info.offset = [input.offsetWidth, -16];
	setTimeout(function() { showSuggestions.popup.create(input, null, info, true) }, delay || 500);
}
showSuggestions.popup = new Popup;
window.showSuggestions = showSuggestions;

function infoToolTip(el, evt, html) {
	var info = new PopupInfo;
	info.html = '<div class="smallToolTip"><div class="text">' + html + '<div class="tail"></div></div></div>';
	info.css = 'http://p.webshots.net/css/toolTip.css';
	info.origin = 'element';
	info.position = 'top';
	info.showDelay = 100;
	info.fadeOutDuration = 300;
	info.keepInView = false;
	infoToolTip.popup.create(el, evt, info);
}
infoToolTip.popup = new Popup;

function setCheckUserBtn(state) {
	var btn = $('check-availability');

	var states = ['available', 'unavailable', 'tryagain', 'hover'];
	for (var i = states.length; i--; delClass(btn, states[i]));
	addClass(btn, state);

	switch (state) {
		case 'tryagain': btn.innerHTML = MESSAGES.CHECKNAME_ERROR; break;
		case 'available': btn.innerHTML = MESSAGES.CHECKNAME_AVAILABLE; break;
		case 'unavailable': btn.innerHTML = MESSAGES.CHECKNAME_UNAVAILABLE; break;
		default: btn.innerHTML = MESSAGES.CHECKNAME_QUERY; break;
	}
}

function userChecker(user) {
	var me = this;

	function handler() {
		var xhr = me.xhr;
		if (!xhr || xhr.readyState != 4) return;
		var s = xhr.responseText;

		if (xhr.status != 200) {
			setCheckUserBtn('tryagain');
		} else if (s.indexOf('Congratulations!') != -1) {
			setCheckUserBtn('available');
		} else {
			setCheckUserBtn('unavailable');

			var names = [];
			var re = /<div[^>]*>\s*(\S+)\s*<\/div>/gi;
			for (var suggestions = re.exec(s); suggestions; suggestions = re.exec(s)) {
				names.push(suggestions[1]);
			}
			showSuggestions(user, names.join(' '), 1);
		}
	}

	this.xhr = XHR.open('/signup', 'action=check_username&signup_username=' + encodeURIComponent(user), handler);
}

function validateField(el, force) {
	var val = el.value;
	if (!val && el.tagName == 'INPUT' && !force) return;
	var errors = 0;

	switch (el.id) {
		case 'signup_username':
			if (!/^\w{5,25}$/.test(val)) {
				setError(MESSAGES.ERR_USER, $('check-availability')), errors++;
			}
			break;
		case 'signup_password':
			if (!/^[a-z\d]{5,}$/i.test(val)) {
				setError(MESSAGES.ERR_PASS, el), errors++;
			}
			break;
		case 'password_again':
			if (val != $('signup_password').value) {
				setError(MESSAGES.ERR_PASS_MISMATCH, el), errors++;
			}
			break;
		case 'email_address':
			if (!/^[^@ ]+@[^@. ]+\.[^@ ]+$/.test(val)) {
				setError(MESSAGES.ERR_EMAIL, el), errors++;
			} else if (hasClass(document.body, 'college_live') && !/\.edu$|@cnet\.com$/i.test(val)) {
				setError(MESSAGES.ERR_COLLEGELIVE_EMAIL, el), errors++;
			}
			break;
		case 'firstname':
			if (!/^\w{1,32}$/.test(val)) {
				setError(MESSAGES.ERR_FIRSTNAME, el), errors++;
			}
			break;
		case 'country_code':
			if (el.selectedIndex < 1) {
				setError(MESSAGES.ERR_COUNTRY, el), errors++;
			}
			break;
		case 'birth_year':
			if (!/^\d\d$/.test(val)) {
				setError(MESSAGES.ERR_BIRTH_YEAR, el), errors++;
			} else if (((new Date - new Date($('birth_month').value + '/' + $('birth_day').value + '/19' + $('birth_year').value)) / (1000 * 60 * 60 * 24 * 365)) < 13) {
				setError(MESSAGES.ERR_UNDERAGE, el), errors++;
			}
			break;
		case 'gender':
			if (el.selectedIndex < 1) {
				setError(MESSAGES.ERR_GENDER, el), errors++;
			}
			break;
	}

	return errors;
}

function validateForm(e) {
	var errors = 0;

	for (var i = FormElements.length; i--;) {
		errors += validateField(FormElements[i], true);
	}

	if (errors) {
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
	}
}

function init() {
	// quick temporary hack to replace inputs with buttons for Safari until new signup.jsp is pushed
	//if (navigator.userAgent.indexOf('Safari') != -1) {
	//	for (var inputs = $('join-free', 'join-free2', 'join-premium', 'continue','join-prem'), i = inputs.length, btn, input; i--;) {
	//		input = inputs[i];
	//		if (input.tagName != 'INPUT') continue;
	//		btn = document.createElement('button');
	//		btn.id = input.id;
	//		btn.type = input.type;
	//		btn.name = input.name;
	//		btn.value = input.value;
	//		btn.innerHTML = (input.id == 'join-premium') ? 'Join Premium!' : 'Join FREE';
	//		input.parentNode.replaceChild(btn, input);
	//	}
	//}

	addEvent($('signup'), 'submit', validateForm);

	for (var i = FormElements.length; i--;) {
		addEvent(FormElements[i], 'focus', function(e) { addClass(e.srcElement || e.target, 'focus') });
		addEvent(FormElements[i], 'blur', function(e) { delClass(e.srcElement || e.target, 'focus') });
		addEvent(FormElements[i], 'mouseover', function(e) { addClass(e.srcElement || e.target, 'hover') });
		addEvent(FormElements[i], 'mouseout', function(e) { delClass(e.srcElement || e.target, 'hover') });
	}

	var inputs = FormElements.concat($('check-availability'));
	for (var i = inputs.length, input; i--;) {
		input = inputs[i];
		addEvent(input, 'focus', function(e) { unsetMessage(e.srcElement || e.target) });
		addEvent(input, 'blur', function(e) { validateField(e.srcElement || e.target) });
		if (input.nextSibling && input.nextSibling.className == 'error') {
			input.msgbox = input.nextSibling;
			setMessage.messages.push(input);
		}
	}

	var input = $('signup_username');
	var btn = $('check-availability');

	addEvent(input, 'focus', function() {
		unsetMessage(btn);
		setCheckUserBtn();
		showSuggestions.popup.destroy();
	});

	addEvent(btn, 'click', function() {
		if (/\S/.test(input.value)) {
			userChecker.checker = new userChecker(input.value);
		} else {
			showSuggestions.popup.destroy();
			setError(MESSAGES.ERR_EMPTY_USER, btn);
		}
	});

	var features = $('features');
	features.slideDir = hasClass(features.parentNode, 'collapsed') ? -1 : 1;
	addEvent($('free-details-btn'), 'click', function() { slide(features, 5, 1000, [1, 1, 1, 0], features.slideDir *= -1) });
	addEvent($('premium-details-btn'), 'click', function() { slide(features, 5, 1000, [1, 1, 1, 0], features.slideDir *= -1) });

	addEvent($('newsletter1-help'), 'click', function(e) { infoToolTip(e.srcElement || e.target, e, MESSAGES.NEWSLETTER1_HELP) });
	addEvent($('newsletter3-help'), 'click', function(e) { infoToolTip(e.srcElement || e.target, e, MESSAGES.NEWSLETTER3_HELP) });
	addEvent($('newsletter4-help'), 'click', function(e) { infoToolTip(e.srcElement || e.target, e, MESSAGES.NEWSLETTER4_HELP) });
	addEvent($('newsletter5-help'), 'click', function(e) { infoToolTip(e.srcElement || e.target, e, MESSAGES.NEWSLETTER5_HELP) });
	addEvent($('join-free2'), 'click', function() {
		setTimeout(function() {
			var errors = 0;
			for (var i = FormElements.length; i--;) { errors += validateField(FormElements[i], true); }
			if (errors) { location.href = '#'; }
		}, 100);
	});
	
	var buttons = {
		list:		[$('free-details-btn'), $('premium-details-btn')],
		details:	function(button) { if (hasClass(button, 'hide') == false) { for (var i = buttons.list.length; i--; addClass(buttons.list[i], 'hide')); } else { for (var i = buttons.list.length; i--; delClass(buttons.list[i], 'hide')); } }
	};
	for (var i = buttons.list.length; i--; addEvent(buttons.list[i], 'click', function(e) { var el = e.srcElement || e.target; buttons.details(el); }));
}
init();

})()