
var OK_MESSAGE_COLOR = "green";
var ERROR_MESSAGE_COLOR = "red";
var resendMode = "";
var checkDepositIntervalId;


$(document).ready(function() {

	$.ajaxSetup({ cache: false });
	
	// Create event handlers
	$("a#login_link").click(function() { if($("div#login_div").length > 0) { showLogin(); } return false; });
	$("a#register_link").click(function() { if($("div#reg_div").length > 0) { showRegister(); } return false; });
	$("a#forgot_password").click(function() { showForgot(); return false; });
	$("a#reg_captcha_refresh").click(function(){ refreshRegCaptcha(); return false; });
	$("a#forgot_captcha_refresh").click(function(){ refreshForgotCaptcha(); return false; });
	$("img#hide_dialog").click(function() { hideDialog(); return false; });
	$("div.dialog_black_wrapper").click(function() { hideDialog(); return false; });
	
	$("form#login_form").submit(function(e) {
		e.preventDefault();
		
		var email = $.trim($("input#login_email").val());
		var password = $.trim($("input#login_password").val());
		var remmember_me = $("input#login_remmember_me").attr('checked') ? 1 : 0;
		
		hideInfo();
		if((email == "") || (password == "")) {
			setLoginMessage('Please fill all fields.', ERROR_MESSAGE_COLOR);
		} else {
		
			setBusy("input#login_submitbutton", true);
			var requestString = {email: email, password: password, remmember_me: remmember_me};
			$.post("/actions/login.php", requestString, afterLogin, "text");
		}		
	});

	$("form#reg_form").submit(function(e) {
		e.preventDefault();
	
		var email = $.trim($("input#reg_email").val());
		var password = $("input#reg_password").val();
		var re_password = $("input#reg_re_password").val();
		var nickname = $.trim($("input#reg_nickname").val());
		var captcha = $("input#reg_captcha").val();
		var terms = $("input#reg_terms").attr('checked') ? 1 : 0;

		hideInfo();
		if((email == "") || ($.trim(password) == "") || (nickname == "") || (re_password == "")) {
			setRegisterMessage('Please fill all fields.', ERROR_MESSAGE_COLOR);
		} else {
			if(terms == 0) {
				setRegisterMessage('You need to agree to our Terms and Conditions.', ERROR_MESSAGE_COLOR);
			} else if(password != re_password) {
				setRegisterMessage('The password is not identical in both fields.', ERROR_MESSAGE_COLOR);
			} else {
			
				setBusy("input#reg_submitbutton", true);
				var requestString = {email: email, password: password, nickname: nickname, captcha: captcha};
				$.post("/actions/register_user_new.php", requestString, afterReg, "text");
			}
		}
	});
	
	$("form#forgot_form").submit(function(e) {
		// Prevent default behavior
		e.preventDefault();

		var email = $.trim($("input#forgot_email").val());
		var captcha = $("input#forgot_captcha").val();
		
		hideInfo();
		if($.trim(email) == "") {
			setForgotMessage('Please type the email address you registered with.', ERROR_MESSAGE_COLOR);
		} else {

			setBusy("input#forgot_submitbutton", true);
			$.post("/actions/reset_password.php", {email : email, captcha: captcha }, afterForgot);
		}
	});
	
	//if($("div.online").length > 0) {
		//} else {
		$("a#play_now_btn").click(function(){
			showRegister();
			return false;
		});	
		//}

});


//check if getTransactionId() function defined 
if (typeof getTransactionId == 'function')
	waitForDepositTx(getTransactionId());


/*
function startGame() {
	pauseIntroMovie();
	window.open('/upgrading.html', 'SkillogicClient', 'top=' + ((screen.height - 600)/2) + ',left=' + ((screen.width - 800)/2) + ',width=800,height=600,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}
*/

function pauseIntroMovie() {
	try {
		if($f()) {
			$f().pause();
		}
	} catch(err) {}
}

function startGame() {
	pauseIntroMovie();
	window.open('/resources/client/SkillogicClient.php', 'SkillogicClient', 'top=' + ((screen.height - 600)/2) + ',left=' + ((screen.width - 800)/2) + ',width=800,height=605,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function hideAll() {
	$("div#reg_div").hide();
	$("form#reg_form").hide();
	$("form#forgot_form").hide();
	$("form#login_form").hide();
	$("div#login_div").hide();
	$("div#deposit_success").hide();
	$(".footnote").hide();
}

function showDialog() {
	pauseIntroMovie();
	$("div.dialog_black_wrapper").show();
	$("div.dialog").fadeIn("fast");
}


function showRegister() {
	hideAll();
	refreshRegCaptcha();
	$("div#reg_div").show();
	$("form#reg_form").show();
	$("input#reg_submitbutton").attr("disabled", "");
	showDialog();
	$("input#reg_email").focus();
}


function showLogin() {
	hideAll();
	$("div#login_div").show();
	$("form#login_form").show();
	showDialog();
	$("input#login_email").focus();
}


function showForgot() {
	hideAll();
	refreshForgotCaptcha();
	$("div#login_div").show();
	$("form#forgot_form").show();
	showDialog();
	$("input#forgot_email").focus();
}


function showDeposit() {
	hideAll();
	$("div#deposit_div").show();
	showDialog();
}


function waitForDepositTx(transactionId) {
	checkDepositIntervalId = setInterval("checkDepositTx()", 1000);
}


function checkDepositTx() {
	var transactionId = getTransactionId();
	var requestString = {transactionId: transactionId};
	$.post("/actions/check_deposit_tx.php", requestString, checkDepositTxResult, "text");
}


function checkDepositTxResult(result) {
	switch (result) {
		case "DepositSuccessPaymentTransaction":
			clearInterval(checkDepositIntervalId);
			$("div#deposit_waiting").hide();
			$("div#deposit_success").show();
			break;
		default:
			break;
	}
}


function hideDialog() {
	$("div.dialog").fadeOut("fast");
	$("div.dialog_black_wrapper").hide();
}


function afterLogin(result) {
	var message;
	
	switch(result) {
		case "UserAccountDoesNotExists":
			setBusy("input#login_submitbutton", false);
			message = 'Incorrect email or password.';
			break;
		case "UserAccountNotActivated":
			setBusy("input#login_submitbutton", false);
			message = 'Your account needs to be activated first. Please check your e-mail inbox for the activation link we sent you.<br><a href="javascript: sendActivationMail(\'login\');">Click here</a> to resend the activation link.';
			break;
		case "UserAccountDisabled":
			setBusy("input#login_submitbutton", false);
			message = 'Your account is disabled. Please contact Customer Support.';
			break;
		case "error":
			setBusy("input#login_submitbutton", false);
			message = "Please try again soon. We're experiencing technical difficulties. We apologize for the inconvenience!";
			break;
		default:
			window.location = '/home.php';
			return;
	}

	setLoginMessage(message, ERROR_MESSAGE_COLOR);
}


function afterReg(result) {
	var message;
	var color = ERROR_MESSAGE_COLOR;

	setBusy("input#reg_submitbutton", false);
	switch(result) {
		case "success":
			sendActivationMail("reg1");
			message = 'Thank you for signing up! Before you can log in, please check your e-mail inbox and click the activation link we sent you.';
			color = OK_MESSAGE_COLOR;
			$("input#reg_submitbutton").attr("disabled", "disabled");
			break;
		case "UserAccountEmailInUse":
			message = 'The email address you entered is already associated with a Trade2Race account.';
			refreshRegCaptcha();
			break;
		case "UserAccountNicknameInUse":
			message = 'The nickname you chose is already taken.<br>Please choose a different one.';
			refreshRegCaptcha();
			break;
		case "UserAccountEmailInUseAndNotActivated":
			message = 'Your account needs to be activated first. Please check your email inbox for the activation link we sent you.<br/><a href="javascript: sendActivationMail(\'reg2\');">Click here</a> to resend the activation link.'
			refreshRegCaptcha();
			break;
		case "EmailValidationFailed":
			message = 'Please type your correct email address';
			refreshRegCaptcha();
			break;
		case "PasswordValidationFailed":
			message = 'Please follow the password instructions.';
			refreshRegCaptcha();
			break;
		case "NicknameValidationFailed":
			message = 'Please follow the nickname instructions.';
			refreshRegCaptcha();
			break;
		case "IncorrectCaptcha":
			message = 'The combination of letters you typed is incorrect. Please try again.';
			refreshRegCaptcha();
			break;
		case "UserAccountDisabled":
			message = 'Your account is disabled. Please contact Customer Support.';
			refreshRegCaptcha();
			break;
		case "error":
			message = "Please try again soon. We're experiencing technical difficulties. We apologise for the inconvenience!";
			refreshRegCaptcha();
			break;
	}
	
	setRegisterMessage(message, color);
}

function afterForgot(result) {
	var message;
	var color = ERROR_MESSAGE_COLOR;

	setBusy("input#forgot_submitbutton", false);
	switch(result) {
		case "UserAccountDoesNotExists":
			message = 'The email address you typed isn\'t associated with a Trade2Race account.';
			refreshForgotCaptcha();
			break;
		case "IncorrectCaptcha":
			message = 'The combination of letters you typed is incorrect. Please try again.';
			refreshForgotCaptcha();
			break;
		case 'error':
			message = "Please try again soon. We're experiencing technical difficulties. We apologize for the inconvenience!";
			refreshForgotCaptcha();
			break;
		case "success":
			message = 'Your password has been reset. Please check your email to proceed.';
			color = OK_MESSAGE_COLOR;
			break;
	}
	
	setForgotMessage(message, color);
}
		
		
function setLoginMessage(message, color) {
	$("div#login_info").hide();
	$(".footnote").css("border-top", "1px dotted " + color);
	$("div#login_info").css("color", color);
	$("div#login_info").html(message).fadeIn("fast");
}


function setRegisterMessage(message, color) {
	$("div#reg_info").hide();
	$(".footnote").css("border-top", "1px dotted " + color);
	$("div#reg_info").css("color", color);
	//$("div#reg_info").show();
	$("div#reg_info").html(message).fadeIn("fast");
}


function setForgotMessage(message, color) {
	$("div#forgot_info").hide();
	$("div#forgot_info").css("color", color);
	$(".footnote").css("border-top", "1px dotted " + color);
	$("div#forgot_info").html(message).fadeIn("fast");
}


function refreshRegCaptcha() {
	$("input#reg_captcha").val("");
	$("img#reg_captcha_image").attr("src", "/securimage/securimage_show.php?sid=" + Math.random());
	$("input#reg_captcha").val("");
}


function refreshForgotCaptcha() {
	$("input#forgot_captcha").val("");
	$("img#forgot_captcha_image").attr("src", "/securimage/securimage_show.php?sid=" + Math.random());
	$("input#forgot_captcha").val("");
}


function sendActivationMail(mode) {
	var email;
	var password;
	resendMode = mode;	

	if(mode == "login") {
		email = $("input#login_email").val();
		password = $("input#login_password").val();
	} else if(mode == "reg1" || mode == "reg2") {
		email = $("input#reg_email").val();
		password = $("input#reg_password").val();
	}
	
	var requestString = {email: email, password: password};

	$.post("/actions/get_user_activation_token.php", requestString, sendActivationMailForReal, "text");
}


function sendActivationMailForReal(userActivationToken) {
	if(userActivationToken != "error") {
		var email;
		
		if(resendMode == "login") {
			email = $("input#login_email").val();
			setLoginMessage('The activation link was successfully sent to your email account.', OK_MESSAGE_COLOR);
		} else if(resendMode == "reg1" || resendMode == "reg2") {
			email = $("input#reg_email").val();
			
			if(resendMode == "reg2") {
				setRegisterMessage('The activation link was successfully sent to your email.', OK_MESSAGE_COLOR);
			}
		}
		
		var requestString = {email: email, userActivationToken: userActivationToken};

		$.post("/actions/send_activation_mail.php", requestString);
	}
}


function setBusy(selector, isBusy) {
	if(isBusy) {
		$(selector).attr('disabled', true);
		$(selector).attr('value', 'Please wait...');
	} else {
		$(selector).removeAttr('disabled');
		$(selector).attr('value', $(selector).attr('alt'));
	}
}


function validateNumber(input) {
    var digitsOnly = /^\d+$/;
    return (digitsOnly.test(input));
}


function isValidDate(year, month, day) {
	dummyDate = new Date(Date.UTC(year, month, day));
	
	if(dummyDate.getFullYear() != year || dummyDate.getMonth() != month || dummyDate.getDate() != day) {
		return false;
	}
	
	return true;
}


function hideInfo() {
	$("div#forgot_info.footnote").hide();
	$("div#login_info.footnote").hide();
	$("div#reg_info.footnote").hide();
}