var timeoutId = -1;
var timeoutId2 = -1;
var validation = null;
var lastUsername = "";
var lastEmail = "";
var usernameTaken = false;
var emailTaken = false;
var msie = $.browser.msie === true;
if (msie) {
    if (parseInt($.browser.version.substr(0, 1)) >= 9)
        msie = false;
}

function checkUsername() {
    lastUsername = $("#reg-username").val();
    invokeJsonRequest("requests/account/checkUsername.php", {
        data: {
            username: lastUsername
        }
    });
}

function checkEmail() {
    lastEmail = $("#reg-email").val();
    /*
    invokeJsonRequest("requests/account/checkEmail.php", {
        data: {
            email: lastEmail
        }
    });
    */
}

function initiateCheckUsername() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout("checkUsername()", 400);
}

function initiateCheckEmail() {
    //clearTimeout(timeoutId2);
    //timeoutId2 = setTimeout("checkEmail()", 400);
}

function usernameResult(json) {
    if (isUndefined(json)) {
        validation.fields["username"].masterValidate(null, false);
    }
    else {
        usernameTaken = json[0] != 1;
        validation.fields["username"].masterValidate(null, json[0] == 1);
    }
}

function emailResult(json) {
    if (isUndefined(json)) {
        validation.fields["email"].masterValidate(null, false);
    }
    else {
        emailTaken = json[0] != 1;
        validation.fields["email"].masterValidate(null, json[0] == 1);
    }
}

function loggedOutResult(json) {
    loginFailure(json);
}

function accountResult(json) {
    location.href = "enter.php";
}

function loginFailure(json) {
    //hideLoadingDialog();
    $("#logging-in").hide();
    jsonRequestFailure({
        responseText: json[1][2]
    });
}

function registeredResult(json) {
    if (msie) {
        blockIE();
        return false;
    }
    invokeJsonRequest("requests/account/login.php", {
        data: {
            username: window.username,
            password: window.password
        }
    });
    window.password = "";
}

function blockIE(s) {
    var e = $("#no-ie-text").clone().removeAttr("id");
    e.find(".ie-version").text($.browser.version);
    showError(e, s, {
        height: 220,
        width: 300
    });
    return false;
}

function login(e) {
    // Check for IE
    if (msie) {
        //blockIE(getLanguageString("Texts", "Login"));
        //return false;
    }

    var data = serializeFormToObject($("#login-form"));
    if (!('password' in data) || data.password == "" || !('username' in data) || data.username == "") {
        jsonRequestFailure({
            responseText: "Invalid login information. Please provide both a username and password."
        });
        e.preventDefault();
        return;
    }
    //showLoadingDialog();
    $("#logging-in").center().show();
    invokeJsonRequest("requests/account/login.php", {
        data: data
    });
    e.preventDefault();
}

function register() {
    // Check for IE
    if (msie) {
        blockIE(getLanguageString("Texts", "Register"));
        return false;
    }
    var data = $("#register-form").formToHash();
    //if (validation.validateAll()) {
        if (!('tac' in data && data.tac == "on")) {
            jsonRequestFailure({
                responseText:"You must agree to the Terms of Conditions."
            });
        }
        else {
            window.password = $("#reg-password").val();
            window.username = $("#reg-username").val();
            showLoadingDialog();
            invokeJsonRequest("requests/account/register.php", {
                data: data
            });
        }
    //}
    /*
    else {
        jsonRequestFailure({
            responseText:"Some of the information you have entered is invalid."
        });
    }
    */
    return false;
}

function verifyCode(e) {
    var data = serializeFormToObject($("#code-form"));
    closeDialog("PreReg");
    showLoadingDialog();
    invokeJsonRequest("requests/account/verifyCode.php", {
        data: data
    });
}

function registerFailure(json) {
    hideLoadingDialog();
    window.password = "";
    jsonRequestFailure({
        responseText: json[1][2]
    });
}

function jsonRequestFailure(t) {
    hideLoadingDialog();
    console.log(t);
    var errorString = t.responseText;
    errorString = errorString.replace(/<br \/>/, "\n");
    showError("<p>" + errorString + "</p>", "Error", {
        width: 300,
        height: 200
    });
}

function jsonRequestError(json) {
    console.log(json);
    jsonRequestFailure({
        responseText: json[1][2]
    });
}

function passwordResetResult(json) {
    closeDialog("ForgotPassword");
    hideLoadingDialog();
    showError("<p>An email has now been sent to <strong>" + json[0] + "</strong> with instructions on how to create a new password.</p>", "Ok", {
        width: 300,
        height: 200
    });
}

function initiateNewPasswordFailure(json) {
    closeDialog("ForgotPassword");
    hideLoadingDialog();
    jsonRequestFailure({
        responseText: json[1][2]
    });
}

function recoverPassword(e) {
    var data = serializeFormToObject($("#forgotpassword-form"));
    if (!('email' in data) || data.email == "") {
        jsonRequestFailure({
            responseText: "Please provide an email address."
        });
        return false;
    }
    showLoadingDialog();
    invokeJsonRequest("requests/account/initiateNewPassword.php", {
        data: data
    });
    return false;
}

//$(document).ready(function() {
documentReadyList.push(function() {
    $("#no-ie-text").toggle(msie);

    $("#register-content input[name=link]").val(getUrlParam("link") == null ? getUrlParam("l") : getUrlParam("link"));
    var ref = getUrlParam("ref");
    var r = getUrlParam("r");
    if (r != null)
        ref = r;
    $("#register-content input[name=ref]").val(ref);

    /*
    var pattern = /#(.+)$/;
    var extraFlag = pattern.exec(top.location.href);
    if (extraFlag != null) {
        top.location.href = top.location.href.replace(pattern, "");
        switch (extraFlag[1]) {
            case "nosession":
                alert("no session");
                break;
            case "invalidsession":
                alert("invalid session");
        }
    }
    */
   /*
   if (getUrlParam("nosession") == "1") {
       alert("We are currently experiencing some problems with the login system. This applies to some browsers and only to some users. If you are receiving this message it means that you are currently affected and are therefor not able to login at the moment.\n\nWe are working to fix this problem and we hope to solve it as quick as possible! Be sure to check out the news to the right or check out our Facebook page for updates on the issue.");
   }
    */

    prepareDialogNameSpace("Register", {
        resizable: false,
        draggable: false,
        width: 350,
        height: msie ? 380 : 280,
        modal: true,
        closeButton: true,
        onAfterShow: function() {
            Aloriah.Dialog.Register.elementDialog.find(".popup-dialog-container").css("max-height", "");//.find("input:text:first").focus();
        }
    });

    prepareDialogNameSpace("Message", {
        resizable: false,
        draggable: false,
        width: 350,
        height: 300,
        modal: true,
        closeButton: true,
        buttons: {
            "Ok" : function() {
                closeDialog("Message");
            }
        }
    });

    prepareDialogNameSpace("ForgotPassword", {
        resizable: false,
        draggable: false,
        width: 350,
        height: 150,
        modal: true,
        closeButton: true,
        onAfterShow: function() {
            Aloriah.Dialog.ForgotPassword.elementDialog.find(".popup-dialog-container").css("max-height", "");//.find("input:text").focus();
        }
    });

    prepareDialogNameSpace("GameTour", {
        resizable: false,
        draggable: false,
        width: 828,
        noTitleBar: true,
        height: 477,
        modalExtraClasses: "gametour",
        modal: true,
        closeButton: true
    });

    prepareDialogNameSpace("PreReg", {
        resizable: false,
        draggable: false,
        width: 400,
        height: 200,
        modal: true,
        closeButton: true
    });

    var s = ".question img";
    $(s).live("mouseover", function(ev) {
        showTooltip(ev, $(this), true);
        return false;
    })
    $(s).live("mouseout", function(ev) {
        showTooltip(ev, $(this), false);
        return false;
    });

    var elementValid = $($.IMG({
        src: "images/icons/checkmark.png",
        alt: "Valid"
    }));
    var elementInvalid = $($.IMG({
        src: "images/icons/crossmark.png",
        alt: "Invalid"
    }));
    var elementQuestion = $($.IMG({
        src: "images/icons/questionmark.png"
    }));
    var s = getLanguageString("Texts", "ValueIsInvalid");

    validation = {
        elementValid: elementValid,
        elementInvalid: elementInvalid,
        elementQuestion: elementQuestion,
        required: ['username', 'password', 'passwordConfirm', 'email'],
        fields: {
            username: {
                expr: Aloriah.patterns.username,
                msg: createFormInvalidTooltip("username", s, [getLanguageString("Texts", "UsernameReq1"),getLanguageString("Texts", "UsernameReq2"),getLanguageString("Texts", "UsernameReq3")]),
                validate: function(t, config, fields) {
                    if (usernameTaken) {
                        return false;
                    }
                    else {
                        return t.val().match(fields["username"].expr) != null;
                    }
                }
            },
            password: {
                expr: Aloriah.patterns.password,
                msg: createFormInvalidTooltip("password", s, [getLanguageString("Texts", "PasswordReq1")])
            },
            passwordConfirm: {
                msg: createFormInvalidTooltip("passwordConfirm", s, [getLanguageString("Texts", "PasswordReq1"), getLanguageString("Texts", "PasswordConfirmReq1")]),
                validate: function(t, config, fields) {
                    return t.val().match(fields["password"].expr) && $($("#register-form").find('input[name="password"]')).val() == t.val();
                }
            },
            email: {
                expr: Aloriah.patterns.email,
                msg: createFormInvalidTooltip("email", s, [getLanguageString("Texts", "EmailReq1"),getLanguageString("Texts", "EmailReq2")])
            }
        },
        onInvalid: function(element, config, fields) {
            var key = element.attr("name");
            var e = $(element.parent().parent());
            var q = config.elementQuestion.clone();
            e.find(".validation").empty().append(config.elementInvalid.clone());
            e.find(".question").empty().append(q);
            assignTooltipTo(fields[key].msg, q);
            //$("#register-form input:submit").attr("disabled", "disabled").addClass("disabled");
        },
        onValid: function(element, config, fields) {
            var key = element.attr("name");
            var e = $(element.parent().parent());
            e.find(".validation").empty().append(config.elementValid.clone());
            $("#" + e.find(".question img").attr("rel")).hide();
            e.find(".question").empty();

            e = $("#register-form");
            if (e.find(".invalid").length == 0) {
                e.find("input:submit").removeAttr("disabled").removeClass("disabled");
            }
        },
        onSubmit: function() {
        }
    };
    //$("#register-form").liveValidation(validation);
    //$("#reg-username").keyup(initiateCheckUsername);
    //$("#reg-email").keyup(initiateCheckEmail);
    $("#register-form input:submit").removeAttr("disabled");

    $("#forgotpassword-link").click(function(e) {
        showDialog("ForgotPassword", $("#forgotpassword").show(), "forgot");
        $("#forgotpassword-form").submit(function(e) {
            recoverPassword(e);
            e.preventDefault();
        });
        //.find("input:first").trigger("focues").select();
        e.preventDefault();
    });
    $("#register-button, #big-button").click(function(e) {
        // Check for IE
        if (msie) {
            blockIE(getLanguageString("Texts", "Register"));
            return false;
        }
        showDialog("Register", $("#registration").show(), getLanguageString("Texts", "RegisterAccount"));
        $("#register-form").unbind("submit").submit(register).find("input:text").trigger("focus").select();
        e.preventDefault();
    });
    $("#login-form").submit(function(e) {
        login(e);
        e.preventDefault();
    });
    $("#beta-form").submit(function(e) {
        signUpBeta(e);
        e.preventDefault();
    });
    //$("#features-button").click(openSlideshow);

    $("#username input").trigger("focus").select();
    $("#test1").mouseover(function() {
        $("#contest-banner").fadeIn("slow");
    });
});

$(window).load(function() {
    // Check if default action
    var action = getUrlParam("action");
    if (action == null) action = "";
    if (action != "") {
        switch (action) {
            case "gametour":
                $("#features-button").click();
                break;
            case "registration":
                $("#register-button").click();
                break;
        }
    }
});

function codeVerifiedResult(json) {
    hideLoadingDialog();
    var e = $("#registration");
    e.find("input[name='code']").val(json[0]);
    showDialog("Register", e.show(), getLanguageString("Texts", "RegisterAlpha"));
}

function verifyCodeFailure(json) {
    hideLoadingDialog();
    showError("<p>The code you have entered is invalid. This means you are not able to register an account in the alpha version of the game.</p><p>However you can still sign up for the beta in the upper left corner.</p>", "Invalid code");
}

function signUpBeta(e) {
    var data = serializeFormToObject($("#beta-form"));
    $("#beta-form").find("input:submit").hide().next().show();
    $("#beta-form").find("input:text").val("");
    invokeJsonRequest("requests/account/signUpBeta.php", {
        data: data
    });
}

function signUpBetaFailure(json) {
    $("#beta-form").find("input:submit").show().next().hide();
    var s = "<p>We are sorry to tell you that your request to sign up for the beta could not be completed due to the following reason(s):</p><p><strong>" + json[1][2] + "</strong></p>";
    showError(s, "Error");
}

function betaRegisteredResult(json) {
    $("#beta-form").find("input:submit").show().next().hide();
    var s = "<p>Your email address has been successfully registered in our system. We will contact you when the beta is closing in!</p>";
    showError(s, "Thank you!");
}
