$(function() {initPage()});

/* 	-----------------------------------------------------------
		Form initialisation
		----------------------------------------------------------- */
		
function initPage() {
		
		//$(".popUp").pngFix();
		
		//Hide the 'No can haz JS' message:
		$('#noJavascript').remove()
		
		$('a.popper').click(function(){showPopup(this.id);return false;});
		$('.closeWidget').click(function(){hidePopup(this.parentNode);return false;});
		
		// Initialise the forms with some extra polish 
	  $("form[class!=errorCheck] .formStructure input, #quickLogin input, #quickSubscribe input").toggleVal({changedClass: "dirty"});
		
		// add validation on submit
		$("form#signUpPanel").submit(function(){return rValidate(this)});
		
		//Add a class to simulate :focus in IE
		$("input").focus(function(){$(this).addClass('focus')}).blur(function(){$(this).removeClass('focus')});
		
		$("form#signUpPanel input").focus(function(){$(this).siblings('label.extraHelp').show()}).blur(function(){$(this).siblings('label.extraHelp').hide()});
		
		$('.extraHelp').hide();
		
		 //we want to check emails on the fly
		$("#signUpPanel input.email").blur(function(){if($(this).hasClass('dirty')){if(rCheckEmail(this)) {rShowFormNotification(this, "ok", "looks good");}else{rShowFormNotification(this, "error", "Please check this.");}}});
		
		//Quick check that the name field contains two names at least
		$("#signUpPanel #realName").blur(function(){if($(this).hasClass('dirty')){if(rCheckName(this)) {rShowFormNotification(this, "ok", "cool.");}else{rShowFormNotification(this, "error", "Both names please?");}}});

		//Check that the password has a minimum length
		$("#signUpPanel .password").blur(function(){if($(this).hasClass('dirty')){if(rCheckPassword(this)) {rShowFormNotification(this, "ok", "great.");}else{rShowFormNotification(this, "error", "6-12 characters.");}}});

		$("input#userName").keyup(function(){
			if($(this).hasClass('dirty')){false} else {
				switch (rCheckUserName(this)) {
					case -1 : 
						//For length = 0, don't show any validations
						break;
					case 0 :
						rShowFormNotification(this, "ok", "available.");
						break;
					case 1 :
						rShowFormNotification(this, "error", "Too short");
						break;
					case 2 :
						rShowFormNotification(this, "error", "Too long!");
						break;
					case 3 :
					case 4 :
					case 5 :
						rShowFormNotification(this, "error", "Unavailable");
						break;
				}
				//Update the URL preview in the extraHelp
				$(this).siblings('.extraHelp').children('strong').children('.username').html(this.value);
			}
		});
		
		/* Removed until we've got time to get it sorted in IE
		 
		// switch .password inputs to true type="password"'s when typing starts
		// There's a dirty shortcut here in the hard-coded default value, best to fix this for production 
		$(".formStructure input.password").keyup(function(){if (this.value.length==0||this.value=='Choose your password') {
				$(this.parentNode).removeClass().children('.validation').remove();
					$(".inputHelper").show();
				} else {
					$(".inputHelper").hide();
					$(this).focus();
				}
			});
		
		//IE doesn't allow dynamic switching between input types - hack around this here:
		$(".formStructure input.password").focus(function(){hideHelpers()}).parent().append('<span class="inputHelper">Choose your password</span>');
		
		$(".inputHelper").click(function(){hideHelpers(this)});
		$(".formStructure input.password").keydown(function(){hideHelpers()});
		
		*/

		//add a highlight class to the selected radio label {
			$("#signUpPanel .radio").click(function(){
				$("label[for=" + this.id + "]").addClass('radioCurrent');
				$("label[for!=" + this.id + "]").removeClass('radioCurrent');
			});
		
		//Quick hack: if the form is classed with ErrorCheck, show the validation message by default:
		$('form.errorCheck .buttonBar').before('<p class="formValidationError">We couldn’t process your sign up. Please check for highlighted fields.</p>')
		
		// Show extra fields on quick login while it has focus
		$('form#quickLogin input, form#quickLogin button').focus(function(){
				return $(this.parentNode.parentNode).hasClass('compacted') ? showLoginForm(this.parentNode.parentNode) : false;
		});

		//prevent propagation to the document from the quickLogin form
		$('form#quickLogin').click(function(evt){evt.stopPropagation();}).focus(function(evt){evt.stopPropagation();});
		
		//When clicking on a label with a nested input, give focus to the input
		$('form#quickLogin label').click(function(){alert(this);$(this).children('input').focus();})
		
		//re-collapse the form when anything else in the doc gains focus or is clicked
		$(document).click(function(){quickLoginExpanded ? hideLoginForm('#quickLogin') : false;}).focus(function(){quickLoginExpanded ? hideLoginForm('#quickLogin') : false;});

		//Default easing for animations
		jQuery.easing.def = "easeOutExpo";
	
		$('ol#quickWalkThrough').cycle({ 
			fx:     'fade', 
			pager: '.slideControls',
			speed: 400,
			pause: 1,
			timeout:6500,
			easing:'easeInQuad'
		}); 
		
		//On pages with tourSteps slideshows, initialise the first slide and controls:
		$('.tourSteps li:first').show();
		$('.tourControls li').click(function(){
		
			var target = $(this.parentNode);
			var step = target.children().index(this);
			
			//Update the controls
			 $(this).addClass('current').siblings('li').removeClass('current');
			
			//Perform the switch:
			switchTourSteps(target.parentNode, step);

			return false;
		});
	
}

/* 	-----------------------------------------------------------
		Global variables - mostly flags for performance on often-used ops
		----------------------------------------------------------- */
		
		var quickLoginExpanded = false; //remember the last state of the form

/* 	-----------------------------------------------------------
		Form helpers are clear text labels which can sit over a password field
		to workaround IE's shortcomings
		----------------------------------------------------------- */

function toggleHelpers(helper) {
				$(helper).toggle();
				$(".formStructure input.password").focus()
}
function hideHelpers(helper) {
				$(helper).hide();
				$(".formStructure input.password").focus()
}

/* Two helper functions for the collapsible login form: */
function showLoginForm(form) {$(form).addClass('expanded').children('fieldset.extraFields').slideDown('fast').end().removeClass('compacted');quickLoginExpanded = true;return false;}	
function hideLoginForm(form) {$(form).removeClass('expanded').children('fieldset.extraFields').slideUp('fast', function(){$(this.parentNode).addClass('compacted')}).end();quickLoginExpanded = false;return false;}	

/* 	-----------------------------------------------------------
		Run validation on all inputs in a form
		----------------------------------------------------------- */

function rValidate(form) {
	var validFlag = true;
	$("input.required", form).each(function(){
		rValidateField(this) ? validFlag = validFlag : validFlag = false; 
	})
	
	if (!validFlag) {$('#' + form.id + ' .buttonBar').before('<p class="formValidationError">We couldn’t process your sign up. Please check for highlighted fields.</p>')};
	return validFlag;
}

/* 	-----------------------------------------------------------
		Run validation on a single field
		----------------------------------------------------------- */

function rValidateField(target) {
	var validFlag = false;
	
	if ($(target).hasClass('required')) { //This field is required to have a value
		
		if ($(target).hasClass('dirty')) { //This value has changed
			
			if (target.value.length ==0) {	//The field is empty
				rShowFormNotification(target, "error", "required");
			} else { //All the simple cases are out the way - validate by type:
				if ($(target).hasClass('email')) {
					if (rCheckEmail(target)) {
						validFlag = true;
					} else {
						rShowFormNotification(target, "error", "please check.");
					};
				} else {
					validFlag = true;
				}
			}
		} else { 	//The field hasn't been changed - reject it
			rShowFormNotification(target, "error", "please check.");
		}
	}
	return validFlag;
}

/* 	-----------------------------------------------------------
		Check email address for valid-looking format
		----------------------------------------------------------- */

function rCheckEmail(target) {
	if (target.value.length == 0) {return false;}
	//$(target).unbind('keyup');
	
	if (/(^[a-z0-9]([a-z0-9_\+\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z0-9]([a-z0-9_\.]*)@([a-z0-9_\.]*)(\.[a-z0-9]{2,})(\.[a-z0-9]{2,})*$)/i.test(target.value)) {
		$(target).unbind('keyup');
		return true;
	} else {
		//Switch to eager validation if the test fails for easier revision feedback
		//$(target).keyup(function(){if(rCheckEmail(this)) {rShowFormNotification(this, "ok", "looks good!");}});
		return false;
	}
}

/* 	-----------------------------------------------------------
		Check a name for at least two words
		----------------------------------------------------------- */

function rCheckName(target) {
	return( /((\w+)\s+(\w+))/.test(target.value));
}

/* 	-----------------------------------------------------------
		Check a password for minimum length
		----------------------------------------------------------- */

function rCheckPassword(target) {
		return(target.value.length > 5 && target.value.length < 13);
}

/* 	-----------------------------------------------------------
		Display a notification message alongside the targeted input
		----------------------------------------------------------- */

function rShowFormNotification(target, type, message) {
	
	var notifier = '<label class="validation" for="' + target.id + '"><span>' + message + '</span></label>'
	
	//Select the parent element and add a class to it
	$(target.parentNode).removeClass('ok error').addClass(type).children(".validation").remove().end().append(notifier);
}

/* 	-----------------------------------------------------------
		Ping the server to determine if the selected username is taken
		----------------------------------------------------------- */
var userCheckResult;
function rCheckUserName(field) {
		var checkValue = field.value;
		switch (true) { //Some basic validation first, to cut excess server calls
			case (checkValue.length == 0) :
				return -1;
				break;
			case (checkValue.length < 4) :
				return 1;
				break;
			case (checkValue.length > 12) :
				return 2;
				break;
			default:
				//Check with the server if this is OK
				$.get("http://pt1.arachsys.com/users/check_username.jsp", {username: checkValue},
				function(data){
					 userCheckResult = parseInt(data.slice(-1));
				});
				return userCheckResult;
		}
}

/* 	-----------------------------------------------------------
	 Switch panels on .tourSteps slideShows
		----------------------------------------------------------- */
function switchTourSteps(tourBox, step) {
	//This version fades out the selected slide before fading in the new one:
	$('.tourSteps li:visible', tourBox).fadeOut('fast', function() {$(this.parentNode).children('li').eq(step).fadeIn('fast')});
	
	//This version does a simultaneous in/out transition - not used as it requires a fixed height and/or abs positioning on all slides
	//$('.tourSteps li:visible', tourBox).fadeOut('slow').parent().children('li').eq(step).fadeIn('fast');
}

function showPopup(trigger) {
	$('.popUp#' + trigger + 'Panel').fadeIn('fast');
	//Scroll to the top of the displayed panel (when not using position:fixed popUps 

	//Scroll to the top of the panel -15px doesn't work in IE6.
	//$.scrollTo('.popUp#' + trigger + 'Panel', {duration:250, offset:-15});

	//Use scroll to 0 instead for now:
	$.scrollTo(0, {duration:250, offset:30});
		

}

function hidePopup(box) {
	$(box).fadeOut('fast');
}