function showEULA(country){
	if (country != 'USA')
		$('#eula_iframe').attr('src', '/eula-nonus.html');
	else
		$('#eula_iframe').attr('src', '/eula-us.html');
	$("#eula_popup").fadeIn();
}

function doLogin(){
	var params = new Array();
	params.push('action=logged');
	doAJAXRequest('/login.php', params, loggedCallback);
}

function showMessage(text){
	$("#dynamic_msg").html(text);
    $("#dynamic_msg").css('display', '');
}

function doAJAXRequest(url, params, callback){
	params.push('ajaxrequest=1');
	$.ajax({
		data: params.join('&'),
		type: 'post',
		url: url,
		dataType: 'json',
		beforeSend: function(r){
			$("#dynamic_loading").css('display', '');
            $("#dynamic_msg").css('display', 'none');
		  },
		complete: callback
	});
}

function requestCallback(request, textStatus){
	$("#dynamic_loading").css('display', 'none');
    if(textStatus == 'success'){
        var response = $.parseJSON(request.responseText);
        switch (response.status){
        case 'wronguser':
        	showMessage("<span style='color:red;'>Sorry, but username or password is invalid.</span>");
        	break;
        case 'cantlogin':
        	showMessage("<span style='color:red;'>Sorry, but this user can not login.</span>");
        	break;
        case 'noteula':
            showEULA(response.country);
            break;
        case 'canlogin':
    		if (getComplexity($('#login_password').val()) < 1) {
    			alert('Your password is too weak and does not comply with VirtualX security policy.');
    			changePassword();
    		}
    		else
    			doLogin();
            break;
        default:
        	showMessage("<span style='color:red;'>Sorry, but some strange error just happened. Try again, please.</span>");
            break;
        }
   }else {
	   showMessage("<span style='color:red;'>Cannot connect to the server.</span>");
   }
}

function eulaCallback(request, textStatus){
	$('#eula_popup').fadeOut();
	doLogin();
}

function loggedCallback(request, textStatus){
	if (request.responseText == 'ok') {
		$('#form_action').val('');
		$('#login_form').submit();
	}
	//window.location.href='/login.php';
}

function registerCallBack(request, textStatus){
	$("#dynamic_loading").css('display', 'none');
	showMessage($.parseJSON(request.responseText));
}

function getComplexity(str){
	var numeric = "0123456789";
    var lower = "abcdefghijklmopqrstuvwxyz";
    var upper = "ABCDEFGHIJKLMOPQRSTUVWXYZ";
    var signs = "~`!@#$%^&*+-=_|\\/()[]{}<>,.;:?\"\'";
    
	var numeric_counter = 1;
    var lower_counter = 1;
    var upper_counter = 1;
    var signs_counter = 1;

    if (str.length < 8) return 0;

    for(var i = 0; i < str.length; i++) {
    	if (numeric.indexOf(str.charAt(i)) >= 0) numeric_counter++;
    	if (lower.indexOf(str.charAt(i)) >= 0) lower_counter++;
    	if (upper.indexOf(str.charAt(i)) >= 0) upper_counter++;
    	if (signs.indexOf(str.charAt(i)) >= 0) signs_counter++;
    }
    return (1-1/numeric_counter) + (1-1/lower_counter) + (1-1/upper_counter) + (1-1/signs_counter);
}

function bindLoginListeners() {
	$("#login_button").click(function(){
		var params = new Array();
		$("#login_form input").each(function(){
			if ($(this).attr('type') == 'text' || $(this).attr('type') == 'password' || $(this).attr('type') == 'hidden')
				params.push($(this).attr('name') + '=' + $(this).val())
			else 
				if ($(this).attr('type') == 'checkbox') 
					params.push($(this).attr('name') + '=' + $(this).attr('checked'));
			});
		doAJAXRequest('/login.php', params, requestCallback);
	});
	
	$('#register_button').click(function(){
		var params = new Array();
		$('#form_action').val('register');
		$("#login_form input").each(function(){
			params.push($(this).attr('name') + '=' + $(this).val())
			});
		if (getComplexity($('#login_password').val()) < 1 || $('#login_password').val().length < 8)
			alert('Your password is too weak and does not comply with VirtualX security policy.');
		else
			doAJAXRequest('/login.php', params, registerCallBack);
	});
	
	$("#eula_checkbox").click(function(){
		if ($("#eula_checkbox").attr('checked')) {
			$("#eula_submit").attr('disabled', '');
		}else{
			$("#eula_submit").attr('disabled', 'true');
		}
	});
	
	$('#eula_submit').click(function(){
		if ($("#eula_checkbox").attr('checked'));
		var params = new Array();
		params.push('action=eula');
		params.push('accepted=1');
		doAJAXRequest('/login.php', params, eulaCallback);
	});
	
	$('#eula_decline').click(function(){
		window.location.href = '/login.php';
	});
	
	$("#login_password").keyup(function(){
		complexity_index = getComplexity($("#login_password").val());
	    if (complexity_index < 1) {
	    	$("#complexity").html("Weak");
	    	$("#complexity").css("color", 'red');
	    } else if (complexity_index < 2) {
	    	$("#complexity").html("Medium");
	    	$("#complexity").css("color", 'orange');
	    } else if (complexity_index < 3) {
	    	$("#complexity").html("Good");
	    	$("#complexity").css("color", 'green');
	    } else {
			$("#complexity").html("Great");
	    	$("#complexity").css("color", 'green');
		}
    });
	
	$('#login_form').keyup(function(ev){
		if (ev.keyCode == '13') {
			$("#login_button").click();
		}
	});
}


function forgotPassword()
{
	if(document.getElementById('login_email').value != "")
	{
		var email = document.getElementById('login_email').value;
		location.href='/forgot_password.php?email='+email;
		return true;
	}
	else
	{
		alert('You must enter a valid User E-mail Address to retrieve your password.');
	}
	return false;
}

function changePassword()
{
	if(document.getElementById('login_email').value != "")
	{
		var email = document.getElementById('login_email').value;
		location.href='/change_password.php?email='+email;
		return true;
	}
	else
	{
		alert('You must enter a valid User E-mail Address to change your password.');
	}
	return false;
}
