function showRegErrorPanel(form){
	var errPanel = $(form + ' .error');
	errPanel.empty();
	errPanel.append('<p>Sorry, there seems to be a problem</p><ul>'+errorMessages);
	var errPanelHeight = errPanel.height();
	if(errPanel.css('display') == 'none'){
		if($.browser.msie && $.browser.version == 6){
			errPanel.css('display','block');
		}else{
			errPanel.css({'display':'block', 'height':0, 'overflow':'hidden'}).animate({'height':errPanelHeight},"medium");
		}
	}else{
		errPanel.css({'backgroundColor':'#ffffff', 'height':'auto'}).animate({'backgroundColor':'#f2bfbf'}, "medium");
	}
	//errPanel.css('display','block');
}

/* Registration */
	$(".call-registration").click(function(event){
		event.preventDefault();
	}); 

var icon_info = '<img src="/assets/images/misc/info.gif" alt="" width="14" height="14" />';
var icon_tick = '<img src="/assets/images/misc/tick.gif" alt="" width="14" height="14" />';
var errorMessages;

var currentForm = '';

$("body").append('<div id="registration_form_wrapper"></div>');

String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

function hidePassA() { 
$("input.text-a").hide();
$("input.pw-a").show().focus();
}

function checkPass(field){
	var elem = $(field);
	if(elem.val() == ''){
		if(elem.attr('id') == 'signup_password'){
			elem.hide();
			$('input.text-a').show();
		}
		if(elem.attr('id') == 'signup_confirm_password'){;
			elem.hide();
			$('input.text-b').show();
		}
	}
}

function hidePassB() {
$("input.text-b").hide()
$("input.pw-b").show().focus();
}

function showForm(form) {
	if (currentForm) {
		$("div#"+currentForm).hide();
	}
	$("div#"+form).show(); 
	var topPos = parseInt($(window).height() / 2 + $(window).scrollTop() - $('.inner').height() / 2); 
 	var leftPos = parseInt($(document).width() / 2 - $('.inner').width() / 2); 
 	if(form == 'settings'){
 	$('.inner').css({'top': 60, 'left': leftPos}); // this may need to be reworked to account for the module manager.
 	}else{
 	$('.inner').css({'top': topPos, 'left': leftPos}); // this may need to be reworked to account for the module manager.
 	}
	
	$('.overlay').unbind().click(function(){
		close_registration();
	});
	
	$('#form_register').unbind().submit(function(event){
		event.preventDefault();
		validateForm('signup', 'submit');
	});
	
	$('#form_signin').unbind().submit(function(event){
		event.preventDefault();
		validateForm('signin', 'submit');
	});
	
	$('#settings-form').unbind().submit(function(event){
		event.preventDefault();
		validateForm('settings', 'submit');
	});

	$('#form_reminder').unbind().submit(function(event){
		event.preventDefault();
		validateForm('reminder', 'submit');
	});
	
	$('a.form-submit').unbind().each(function(i, elem){
		$(this).click(function(event){
			event.preventDefault();
			$(this).parents('form').triggerHandler('submit');
		});
	});
	
	currentForm = form;
	return false;
}
// NOTE: we could use the jQuery Form plugin's ajaxSubmit() function here, and really streamline this. TBC.

function validateForm(form, trigger) {
	
	if (form == 'signin') {
		email_address =  $("#signin_email_address").val();
		password = $("#signin_password").val();
		$.post("/ajax/signin.php",{
			trigger: trigger,
			email_address: email_address,
			password: password
		}, function(xml) {
				if($("form_status",xml).text() == "1") {
				window.location = '/';			
			}
			else if($("form_status",xml).text() == "0"){	
				field_error = false; // Is there an error with an individual field?
				errorMessages = '';
				$("field", xml).each(function() {
					field 	= $(this).attr('id');
					status  = $("status", this).text();
					message = "<li>"+$("message", this).text()+"</li>";		 
					if (status == 0) {
						$("div#validation_icon_"+field).html(icon_info);
						errorMessages += message;
						field_error = true;
						return false;
					}	
				});
			
				if(errorMessages){
					showRegErrorPanel('#signin');
				}
			
			}else if($("form_status",xml).text() == "2"){
				errorMessages = '<li>Your username/password is incorrect.</li>';
				showRegErrorPanel('#signin');
			}
			

			
		});
	}
	else if (form == 'signup') {
		// We may be able to merge the individual clauses of this loop with each other, to an extent...
		// but let's get it working "as is", and then optimise it if possible
		email_address =  $("#signup_email_address").val();
		password = $("#signup_password").val();
		confirm_password = $("#signup_confirm_password").val();
		$.post("/ajax/signup.php",{
			trigger: trigger,
			email_address: email_address,
			password: password,
			confirm_password: confirm_password
		}, function(xml) {
			if($("form_status",xml).text() == "1") {
				$('.settings-thanks').css('display','block');
				showForm('settings'); //was thanks
				switchControls();				
			}
			else {		
				field_error = false; // Is there an error with an individual field?
				errorMessages = '';
				
				$("field", xml).each(function() {
					field 	= $(this).attr('id');
					var status = $(this).children('status').text();
					message = '<li>' + $("message", this).text() + "</li>";		
					if (status == 0) {
						$("div#validation_icon_"+field).html(icon_info);
						errorMessages += message;
						field_error = true;
						//return false; // This breaks out of the loop; if we want to highlight multiple fields, we'll need to remove this
					}
					else {
						$("div#validation_icon_"+field).html('');
					}
					
				});
				
				if (!field_error) {
					// If we haven't found an individual field error, the entire form doesn't validate; EG, the username/password combination is incorrect:
					//$("#error_signup").html($("form_message",xml).text());
				}
				
				if(errorMessages){
					showRegErrorPanel('#registernow');
				}	
				
			}
		});
	}
	else if (form == 'settings') {
		// Note: trigger will always be "submit" for this form, as we don't validate individual fields as far as I know
		// However, this may change in the future, so it's left in place...
		var theName = $('#settings-form #name');
		var theCompany = $('#settings-form #company');
		if(theName.val() == 'your name') theName.val('');
		if(theCompany.val() == 'your company') theCompany.val(''); 
		var data = $('#settings-form').formSerialize(); //formSerialize()
		
		data += '&trigger='+trigger;
		
		$.post("/ajax/settings.php",data, function(xml) {
			errorMessages = '';																					 
			if($("form_status",xml).text() == "1") {
				close_registration(); // Surely we should have a second "thanks" page...? 					
			}
			else {
				// This form should always validate OK, we don't technically run any validation on it						
			}
		});
	}
	else if(form == 'reminder') {
		var email_address =  $("#reminder_email_address").val();
		errorMessages = '';
		$.post("/ajax/reminder.php",{
			trigger: trigger,
			email_address: email_address
		}, function(xml) {
			if($("form_status",xml).text() == "1") {				
				$(".error:visible").hide();
				$('#reminder>form,#reminder>p').hide();
				$('#reminder .completemessage').show();
			}
			else {
				errorMessages = '<li>' + $("form_message",xml).text() + '</li>';
				showRegErrorPanel('#reminder');
				$("div#validation_icon_reminder").html(icon_info);					
			}
		});
	}
				
	return false;
}

function rememberMe(t) {
	// All the work here is done within the Ajax script itself
	$.post("/ajax/remember-me.php",{
		 checkbox: t.checked
	 });
}	

/* Exposes functions to MSIE - I'll rewrite this some time... */

if ($.browser.msie){
	$("a.open_registration").click(function(event){
		event.preventDefault();
		open_registration(event);
	});
	}
	
	if ($.browser.msie){
	$("a.open_settings").click(function(event){
		event.preventDefault();
		open_settings(event);
	});
	}
	
	if ($.browser.msie){
	$("a.open_signup").click(function(event){
		event.preventDefault();
		open_signup(event);
	});
	}
	
	if ($.browser.msie){
	$("a.open_reminder").click(function(event){
		event.preventDefault();
		open_reminder(event);
	});
}

/* Functions for each form */

function open_registration(event) {
	
	if (!$.browser.msie){
		event.preventDefault();
	}
	
	$.get("/public/registration_form.php", function(data){
		$("#registration_form_wrapper").html(data);		
		$("select").css('visibility','hidden');
		overlay(); // this is a function in core.js
			showForm('signin');		
		$("div#registration_form_wrapper").css("display","block");
	//	$("#signin_email_address").focus()
	});
	
}

function open_signup(event) {
	if (!$.browser.msie){
		event.preventDefault();
	}
	
	$.get("/public/registration_form.php", function(data){
		$("#registration_form_wrapper").html(data);		
		$("select").css('visibility','hidden');
		overlay();
			showForm('registernow');		
		$("div#registration_form_wrapper").css("display","block");
	//	$("#signup_email_address").focus()
	});
}

function open_settings(event) {
	if (!$.browser.msie){
		event.preventDefault();
	}	
		
	$.get("/public/registration_form.php", function(data){
		$("select").css('visibility','hidden');
		$("#registration_form_wrapper").html(data);		
		overlay();
		showForm('settings');		

	});
}

function open_reminder(event) {
	if (!$.browser.msie){
		event.preventDefault();
	}	
		
	$.get("/public/registration_form.php", function(data){
		$("#registration_form_wrapper").html(data);		
		overlay();
		showForm('reminder');		
	});
	
}

function close_registration() {
	$(".overlay").fadeTo("slow",0,removeOverlay).removeClass("active") ; // SC
	$(".inner").css({'left': -9999});
}

function removeOverlay(){  // SC
	if(!$.browser.safari){
		$('body').removeClass('withOverlay');
	}
	$('.overlay').hide();
	$("select").css('visibility','visible');
}

function switchControls(){ // Switches 'Login/register' to 'Settings/logout'
			$("#admin-links").append("<span id='controls_logout'><li><a href='/settings'  id='settings_link' class='call-registration open_settings' onclick='open_settings(event);return false;'>Settings</a> </li><li> <a id='log_out' href='/?logout'  class='open_logout'>Log out</a></li><li><a id='contact_us' href='/contact/' class='open_contact'>Contact us</a></li></span>");
			$("span#controls_login").remove();
}

/* // for debugging
$(document).ready(function() {
	open_settings();
//	open_signup();
//	open_registration();
});
*/