$(document).ready(function() {
    $('#protectSignUpForm .button').click(function() {
        register();
    });

    $('#protectSignUpForm form').submit(function(e) {
        //register();
        e.preventDefault();
        //return false;
    });

    $('#protectSignUpBtn').click(function() {
        error(0, '');
        $('#protectSignUpForm').jqmShow();
        return false;
    });

    $('#protectSignOutBtn').click(function() {
        $.ajax({
            type: "POST",
            url: "protect.php?a=signout",
            data: {post: 1},
            dataType: "json",
            success: function(msg) {
                window.location.reload()
            }
        });
        
        return false;
    });

    $('.jqmWindow').keydown(function(e) {
        if (e == null) { // ie
            keycode = event.keyCode;
        } else { // mozilla
            keycode = e.which;
        }

        if (keycode == 27) { // escape, close box
            $('.jqmWindow').jqmHide();
        }
    });
    
    $('#protectSignUpForm').jqm({overlay: 45});
});


function register() {
    hideshow('#protectSignUpForm .loading', 1);
    error(0);

    $.ajax({
        type: "POST",
        url: "protect.php?a=register",
        data: $('#protectSignUpForm form').serialize(),
        dataType: "json",
        success: function(msg) {
            if (parseInt(msg.status) == 1){
                $('#protectSignUpForm form').hide();
                $('#protectSignUpForm .error').hide();
                $('#protectSignUpForm .title').html("Registration success");
                $('#protectSignUpForm .message').html("You can click on the " +
                                          "<a href=\"" + window.location.href + "\">link</a> " +
                                          "or wait to be automatically redirected in just a few seconds");
                clearForm('#protectSignUpForm form');
                setTimeout(function(){
                    window.location.reload()        
                }, 2000)
            }else if (parseInt(msg.status) == 0){
                error(1, msg.txt);
            }
            hideshow('#protectSignUpForm .loading', 0);
        }
    });
}

function error(act, txt) {
    hideshow('#protectSignUpForm .error', act);
    if (txt) $('#protectSignUpForm .error').html(txt);
}

function hideshow(el, act) {
    if (act) $(el).css('visibility', 'visible');
    else $(el).css('visibility', 'hidden');
}

function clearForm(el) {
    $(el).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}


