function goto_register(){
    $('login').set('html', '');
    add_template('register_form.xml', 'login');
}

function goto_login(message){
    $('login').set('html', '');
    add_template('login_form.xml', 'login', {'message': message});
}

function register(){
    //data validation
    if ($('password').get('value') != $('password_again').get('value')) 
        return Notification('your passwords don\'t match', false);
    if ($('password').get('value').length < 5) 
        return  Notification('Your password must be at least 5 characters', false);
    if (!$('email').get('value').test(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) 
        return  Notification('You must enter a valid e-mail address', false);
    if ($('nickname').get('value').clean().test(/\W/)) 
        return  Notification('Your nickname must only contain alphanumeric characters', false);
    if ($('nickname').get('value').clean() == '' || $('nickname').get('value').clean().length < 5) 
        return  Notification('Your nickname must be at least 5 characters', false); 
    
    var fields = ['email', 'nickname', 'password', 'user_key'];
    var values = [$('email').get('value'), $('nickname').get('value'), $('password').get('value'), newKey()]; 
    var results = new Model('users').Insert(fields, values).Eval();
    
    if (results.toString().test(/Duplicate/g)){
        var badKey = results.split(' ');
        if (badKey[badKey.length - 1] == 2)
            return Notification('E-mail address is taken', false);
        if (badKey[badKey.length - 1] == 3)
            return Notification('Nickname address is taken', false);
    } else {
        goto_login('Thank you for registering. Log in an start blogging away.');
    }
}

function login(user, pass){
    user = user || $('email').get('value');
    pass = pass || $('password').get('value');
    var result = new Model('users').Select(['*'], "email='" + user + "' AND password='" + pass + "'").Eval();
    if (result.length == 1){
        $('login').set('html', '');
        add_template('welcome.xml', 'login', result[0]);
    }
    //replace with more secure system
    Cookie.write('user', result[0]['email'] + '&' + result[0]['password'], {'duration': 1});
}

function show_secret_plans_hahaha(){
    $('home_page').hide();
    add_template('plans.xml', 'right', {'email': 'hobberwickey@gmail.com'});
}

function hide_plans(){
    $('plans').dispose();
    $('home_page').show();
}