var signinInitialized = false;
var signupInitialized = false;

function nativeSignout() {
    jQuery.cookie("hgm__user", null, {expires: -1, path:'/'});
    Smooth_Reload.lout();
    return window.setTimeout(initSigninDialog,3000)
}

function loginCallback(data) {
    if(!data.success) {
        $("#errorBox").html('Login Failed').show();
    } else {
        closeSigninDialog();
        $("#dialogSingin").remove();
        signinInitialized = false;
        if('undefined' !== typeof Smooth_Reload) {
            Smooth_Reload.lin();
        }
    }
}

function signinCallback(data) {
    if(!data.success) {
        for(error in data.errors) {
            if(data.errors.hasOwnProperty(error)) {
                if('general' === error) {
                    $("#errorBoxSignup").html(data.errors[error]).show();
                } else {
                    $('#'+error).html(data.errors[error]).show();
                }
            }
        }
    } else {
        closeSignupDialog();
        $("#dialogSingup").remove();
        signupInitialized = false;
        if('undefined' !== typeof Smooth_Reload) {
            Smooth_Reload.refresh(1);
        }
        $.get(
            "/blocks/member-dialogs/"
            , {'mode':'local','dialogs':'congrats'}
            , function (responseText, textStatus, req) {
                $("#dialog-container").html(responseText);
                $("#dialogCongrats").dialog({
                        autoOpen: false
                    ,   bgiframe: true
                    ,   resizable: false
                });
                $('#dialogCongrats').dialog('open');
            }
        );
    }
}

function openSigninDialog() {
    if($("#dialogSingup").length) {
        closeSignupDialog();
    }
    if(!signinInitialized) {
        $.get(
            "/blocks/member-dialogs/"
            , {'mode':'local','dialogs':'signin'}
            , function (responseText, textStatus, req) {
                $("#dialog-container").html(responseText);
                initSigninDialog();
                $('#dialogSingin').dialog('open');
            }
        );
    } else {
        $('#dialogSingin').dialog('open');
    }
}

function openSignupDialog() {
    if($("#dialogSingin").length) {
        closeSigninDialog();
    }
    if(!signupInitialized) {
        $.get(
            "/blocks/member-dialogs/"
            , {'mode':'local','dialogs':'signup'}
            , function (responseText, textStatus, req) {
                $("#dialog-container").html(responseText);
                initSignupDialog();
                $('#dialogSingup').dialog('open');
            }
        );
    } else {
        $('#dialogSingup').dialog('open');
    }
}

function closeSigninDialog() {
    $('#dialogSingin').dialog('close');
    $("#errorBox").hide();
    $("#member-pass").val('');
    $("#member-email").val('');
}

function closeSignupDialog() {
    $('#dialogSingup').dialog('close');
    $(".signup-error").hide();
    $("#errorBoxSignup").hide();
    $("#member-pass").val('');
    $("#member-email").val('');
    $("#member-pass").val('');
    $("#member-pass2").val('');
    $("#member-nick").val('');
    $("#member-fname").val('');
    $("#member-lname").val('');
}

function initSigninDialog() {
    if($("#dialogSingin").length) {
        try {
            $("#dialogSingin").dialog({
                    autoOpen: false
                ,   bgiframe: true
                ,   resizable: false
            });
            $("#errorBox").html("");

            $("#dialogSingin input").keypress(function (e) {
               if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                   $("#login").click();
                   return false;
               } else {
                   return true;
               }
            });
            
            $("#login").click(function() {
                if($("input#member-nick-login").val().length < 4) {
                    $("#errorBox").html('Login Failed').show();
                    return;
                }
                if($("input#member-pass-login").val().length < 6) {
                    $("#errorBox").html('Login Failed').show();
                    return;
                }
                $("#errorBox").hide();
                $.post("/blocks/member-dialogs/login", {
                        nick: $("#member-nick-login").val(),
                        pass: $("#member-pass-login").val()
                    }
                    , loginCallback
                    , 'json'
                )
            });
            signinInitialized = true;
        } catch(e) {
            console.log("Sign In Exception: " + e.message);
        }
    }
}

function initSignupDialog() {
    if($("#dialogSingup").length) {
        try {
            $("#dialogSingup").dialog({
                    autoOpen: false
                ,   bgiframe: true
                ,   resizable: false
                ,   width: 338
            });
            $("#dialogSingup input").keypress(function (e) {
               if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                   $("#signup").click();
                   return false;
               } else {
                   return true;
               }
            });
            $("#signup").click(function() {
                var wasError = false;
                $(".signup-error").hide();
                if(!$("input#member-email").val().length || !validEmail($("input#member-email").val())) {
                    $("#errorEmail").html('Please insert valid email').show();
                    wasError = true;
                }
                if($("input#member-nick").val().length < 4) {
                    $("#errorNick").html('Username should be at least 4 characters length').show();
                    wasError = true;
                }
                if($("input#member-pass").val().length < 6) {
                    $("#errorPass").html('Password should be at least 6 characters length').show();
                    wasError = true;
                }
                if($("input#member-pass").val() !== $("input#member-pass2").val()) {
                    $("#errorPass2").html('Password confirmation failed').show();
                    wasError = true;
                }
                if(!$("input#member-fname").val().length) {
                    $("#errorFname").html('Please insert first name').show();
                    wasError = true;
                }
                if(!$("input#member-lname").val().length) {
                    $("#errorLname").html('Please insert last name').show();
                    wasError = true;
                }
                if(!$("#member-agree:checked").length) {
                    $("#errorAgree").html('Please agree to the Terms of Service').show();
                    wasError = true;
                }
                if(!wasError) {
                    $("#errorBoxSignup").hide();
                    $(".signup-error").hide();
                    $.post("/blocks/member-dialogs/signup", {
                            email: $("#member-email").val(),
                            pass: $("#member-pass").val(),
                            nick: $("#member-nick").val(),
                            fname: $("#member-fname").val(),
                            lname: $("#member-lname").val()
                        }
                        , signinCallback
                        , 'json'
                    )
                }
            });
            signupInitialized = true;
        } catch(e) {
            console.log("Sign Up Exception: " + e.message);
        }
    }
}

function validEmail(src) {
     var emailReg = "^[\\s]*[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w][\\s]*$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
}
