// Bind the keydown for login form.If a form element is clicked,hitting 'enter' will submit the form
$('#mloginsection_form').bind('keydown', function(e) {
	if (e.keyCode == '13') {
		$('#loginbtn').click();
	}
});

// Bind events for login form
$('#user_login').focus(function() {
	$('#user_login').addClass('tabindex');
});
$('#user_login').blur(function() {
	$('#user_login').removeClass('tabindex');
});

$('#realpass').focus(function() {
	$('#realpass').addClass('tabindex');
});
$('#realpass').blur(function() {
	$('#realpass').removeClass('tabindex');
});
// Bind the keydown for register form.If a form element is clicked,hitting 'enter' will submit the form
$('#frmRegister').bind('keydown', function(e){
	if (e.keyCode == '13'){
		$('#register_button').click();
	}
});

// Bind click event for #agree checkbox
$("#agree").bind('click', function() {
	is_error('agree');
});

// Bind events for #username
$('#username').focus(function() {
	$('#username').addClass('tabindex');
});
$('#username').blur(function() {
	$('#username').removeClass('tabindex');
});

$('#username').bind('keydown', function(e){
	if (e.keyCode == '13'){
		check_register_form();
		return false;
	}
	is_error('username');
});

// Bind events for dropdowns
$('#day_err').bind('keydown', function(e){
	check_register_form();
	return false;
});
$('#month_err').bind('keydown', function(e){
	check_register_form();
	return false;
});
$('#year_err').bind('keydown', function(e){
	check_register_form();
	return false;
});

$('#day_err').bind('change', function(e){
	check_register_form();
	return false;
});
$('#month_err').bind('change', function(e){
	alert('ssooo');
	check_register_form();
	return false;
});
$('#year_err').bind('change', function(e){
	check_register_form();
	return false;
});


// Bind events for #profile_password
$('#profile_password').focus(function() {
	$('#profile_password').addClass('tabindex');
});
$('#profile_password').blur(function() {
	$('#profile_password').removeClass('tabindex');
});
$('#profile_password').bind('keydown', function(e){
	if (e.keyCode == '13'){
		check_register_form();
		return false;
	}
	is_error('profile_password');

});

// Bind events  for #firstname
$('#firstname').focus(function() {
	$('#firstname').addClass('tabindex');
});
$('#firstname').blur(function() {
	$('#firstname').removeClass('tabindex');
});
$('#firstname').bind('keydown', function(e){
	if (e.keyCode == '13'){
		check_register_form();
		return false;
	}
	is_error('firstname');
});

// Bind events for #email
$('#email').focus(function() {
	$('#email').addClass('tabindex');
});
$('#email').blur(function() {
	$('#email').removeClass('tabindex');
});
$('#email').bind('keydown', function(e){
	if (e.keyCode == '13'){
		check_register_form();
		return false;
	}
	is_error('email');
});

// Function which checks for register errors.It uses a switch for each error type.Argument: id(the error field id)
function is_error(id)
{
	switch (id)
	{
		case 'username':
		// Username errors: 1.empty, 2.length < 4, 3.length > 16
			if($('#username').val().length < 1){
				add_error('username', 'Username is empty');
			}
			else if($('#username').val().length < 4){
				add_error('username', 'Username is too short')
			}
			else if($('#username').val().length > 16){
				add_error('username', 'Username is too long')
			}
			else{
				remove_error('username');
			}
		break;
		case 'profile_password':
		// Password errors: 1.empty, 2.length < 4, 3.length > 16
			if($('#profile_password').val().length < 1){
				add_error('profile_password', 'Password is empty')
			}
			else if($('#profile_password').val().length < 4){
				add_error('profile_password', 'Password is too short')
			}
			else if($('#profile_password').val().length > 16){
				add_error('profile_password', 'Password is too long')
			}
			else{
				remove_error('profile_password');
			}
		break;
		case 'firstname':
		// Firstname errors: 1.empty, 2.length > 25
			if($('#firstname').val().length < 1){
				add_error('firstname', 'First name is empty')
			}
			else if($('#firstname').val().length > 25){
				add_error('firstname', 'Firstname is too long')
			}
			else{
				remove_error('firstname');
			}
		break;
		case 'email':
		// Email errors: 1.empty, 2.length > 60, 3.invalid email
			if($('#email').val().length < 1){
				add_error('email', 'Email is empty')
			}
			else if($('#email').val().length > 60){
				add_error('email', 'Email is too long')
			}
			else if(is_valid_email($('#email').val()) == false){
				add_error('email', 'Email address not valid');
			}
			else{
				remove_error('email');
			}
		break;
		case 'register_date':
		// > 18 years old
			var date_register = $('#month').val() + '/' +  $('#day').val()  + '/' +$('#year').val();
			var date = new Date();
			var year = date.getFullYear() - 18;
			var month = date.getMonth()+1;
			var day = date.getDate();


			var date_past = month + '/' + day + '/'+ year;

			if(Date.parse(date_past) > Date.parse(date_register)){
				remove_error('register_date');

				var pday = $('#day').val();
				var pmonth = $('#month').val();
				var pyear = $('#year').val();
				if (!isDate(pday,pmonth,pyear)) {
					add_error('register_date', 'b-day is incorrect');
				}
				else {
					remove_error('register_date');
				}
			}
			else{
				add_error('register_date', 'You must be at least 18 years old');
			}
		break;

		case 'agree':
			// Agree errors: 1.unckeched
			if($("#agree").is(":checked")){
				remove_error('agree');
			}
			else{
				add_error('agree', 'Please check terms')
			}
		break;

	}
	// If the submit button was clicked, show the errors(if there are any)
	if(sent)
	{
		//alert(error_fields.length);
		// If there are errors,show them
		if (error_fields.length > 0) {
			//Show errors
			show_errors();
			return false;
		}
		// Else hide the errors div
		else {
			$("#err_register").attr('class','error_div');
		}
	}

	return false;
}

//check date functions
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	}
	return this
}
function isDate(tday,tmonth,tyear){
	var day = parseInt(tday, 10);
	var month = parseInt(tmonth, 10);
	var year = parseInt(tyear, 10);
	daysInMonth = new Array();
	for (var i = 1; i <= 12; i++) {
		daysInMonth[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {daysInMonth[i] = 30}
		if (i==2) {daysInMonth[i] = 29}
	}
	if (day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	return true
}

// Function add_error().Adds the error to the errors stack,and adds class 'error' on input field
function add_error(id, msg)
{
	if(sent)
	{
		if(id == "register_date"){
			$('#month_err').addClass('inputerror');
			$('#day_err').addClass('inputerror');
			$('#year_err').addClass('inputerror');
		}
		else
		{
			$('#'+id).addClass('inputerror');
		}
	}
	for (i=0;i<error_fields.length;i++)
	{
		if (error_fields[i] == id)
		{
			errors[i] = msg;
			return;
		}
	}
	error_fields.push(id);
	errors.push(msg);
}

// Function remove_error().Removes the error from the error stack and remove the 'error' class from input field.Also it enables the submit button
function remove_error(id)
{
	if(id == "register_date") {
		$('#month_err').removeClass('inputerror');
		$('#day_err').removeClass('inputerror');
		$('#year_err').removeClass('inputerror');
	}
	else {
		$('#'+id).removeClass('inputerror');
	}
	$("#err_register").attr('class','error_div');

	for (i=0;i<error_fields.length;i++){
		if (error_fields[i] == id){
			error_fields.splice(i, 1);
			errors.splice(i, 1);

			$('.btn4inactive').attr('class', 'btn4 profilecreatebtn');
			$("#err_register").attr('class','error_div');
			return;
		}
	}
}

// Function show_errors().Prints the errors in the errors div.It shows only 2 errors at a time
function show_errors()
{
	$('.btn4').attr('class', 'btn4inactive profilecreatebtn');
	$(".error_div").attr('class','error_div_enabled');
	$(".alert_error").html('');
	var j = 0;

	jQuery.each(errors, function(i, val) {
		if(errors[i]) {
			if(j++ > 0){
				$(".alert_error").append(", ");
			}
			$(".alert_error").append(errors[i]);
			if(j > 1){
				return false;
			}
		}
	});
}

// If the submit button is clicked again while form is submitting, throw an alert for the user to wait until submit is finished
function cancel_message(){
	if (sending){
		alert('Please wait while the data is sent');
		return false;
	}
}

// Define variables for register form submit
var sending = false;
var sent = false;
// error fields
var errors = new Array();
var error_fields = new Array();

// Function which executes when submit button is clicked for register form
function check_register_form()
{
	sent = true;
	// If the submit button is clicked again while form is submitting, throw an alert for the user to wait until submit is finished
	if (sending){
		alert('Please wait while the data is sent');
		return false;
	}

	var msg = "";
	// Checks for form errors
	is_error('username');
	is_error('profile_password');
	is_error('firstname');
	is_error('email');
	is_error('agree');
	is_error('register_date');

	//If there are errors, show them and disable submit button
	if (error_fields.length > 0) {
		$('.btn4').attr('class', 'btn4inactive profilecreatebtn');
		show_errors();
	}
	// If there are no errors,post the data
	else {
		sending = true;
		$.ajax({
			url: 'register_ajax.html',
			type: 'POST',
			data: ({
			'hash' : $('#hash').val(), 'user_login' : $('#username').val(), 'profile_password' : $('#profile_password').val(), 'firstname' : $("#firstname").val(),
			'email' : $('#email').val(), 'user_sex' : $('#user_sex').val(), 'month' : $('#month').val(),
			'day' : $('#day').val(),  'year' : $('#year').val(), 'agree' : $('#agree').is(":checked") ? 1 : 0
			}),
			success: function(response){
				// If the response is empty,submits the form
				if(response == '') {
					$("#err_register").attr('class','error_div');
					$('#frmRegister').submit();
				}
				// Else show the errors
				else{
					if(response.match('username')) {
						$('#username').addClass('inputerror');
					}
					if(response.match('email')) {
						$('#email').addClass('inputerror');
					}
					$(".error_div").attr('class','error_div_enabled');
					$(".alert_error").html('');
					$(".alert_error").html(response);
				}
				sending = false;
			}
		});
	}
	return false;
}

// Function to check validity of email address
function is_valid_email(email) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/;
	return emailPattern.test(email);
}
