/**
 * @author Rich
 */
var _100_WEEKS = 60480000000;

$(document).ready(function(){
    keyRing.initKeys("join");
});

function forceSignin(signinParams, successCallback, cancelCallback, formState){
    pushOverlay("layer_sign_in_up", "/signin/ajax_overlay?" + signinParams, successCallback, cancelCallback, function(){
        showForm(formState);
    });
}

function showForm(formState){
    if (typeof formState == "undefined") 
        formState = ["#signInPart", "#signUpPart"];
    $(formState[0]).show(0);
    $(formState[1]).hide(0);
	setFormFocus(formState[0])	
}

function join(form_id, confirmPwd, next){
	return join(form_id, confirmPwd, next,false)
}

function join(form_id, confirmPwd, next,isPopup){
    if (confirmPwd == null) 
        confirmPwd = false;
    var form = $("#" + form_id)[0];
    if (checkSignUp(form, confirmPwd) && keyRing.acquireKey("join")) {
        $.ajax({
            url: "/signin/ajax_join/",
            data: form.phone ? {
                "phone": form.phone.value,
                "email": form.username.value,
				"usernameCheck":encode64(form.username.value + ":"),
                "firstName": form.first_name.value,
                "lastName": form.last_name.value,
                "password": MD5(form.password.value),
                "authenticity_token": $("#authenticity_token").val()
            } : {
                "email": form.username.value,
				"usernameCheck":encode64(form.username.value + ":"),
                "firstName": form.first_name.value,
                "lastName": form.last_name.value,
                "password": MD5(form.password.value),
                "authenticity_token": $("#authenticity_token").val()
            },
            cache: false,
            timeout: TIMEOUT_LIMIT,
            type: "POST",
            success: function(data){
                signIn(form_id, next);
            },
            error: function(xhr, type, error){
                showMessage("error", xhr.responseText,isPopup,"join",xhr.responseText);
                if (DEBUG) 
                    showMessage("error", xhr.status+" "+ xhr.responseText+" "+ type+" "+ error,false,"join");
            },
            complete: function(){
                keyRing.releaseKey("join");
            }
        });
    }
    return false;
}

function signIn(form_id, next){
    var form = $("#" + form_id)[0];
    var expire = (form.remember!=null && form.remember.checked) ? (new Date((new Date()).getTime() + _100_WEEKS)).toUTCString() : '';
    setAuthKey(form.username.value, MD5(form.password.value), expire);
    document.cookie = "email=" + form.username.value + "; path=/;";
    if (typeof next == "string") 
        window.location = next;
    else 
        popOverlay();
    return false;
}

function setAuthKey(username, passwordMD5ed, expire){
    document.cookie = "authKey=" + encode64(username + ":" + passwordMD5ed) + "; path=/; expires=" + ((typeof expire == "undefined") ? '' : expire);
}

function signOut(){
	FB_RequireFeatures(["Connect"], function() {
	  FB.ensureInit (function(){ 
	    FB.Connect.logout();
	  }); 
	});
    clearCookies();
    startLoading("Signing out...");
    setTimeout(function(){
        window.location = "/";
    }, 500);
}

function lookupEmail(form){
    $.ajax({
        url: "/signin/ajax_email_lookup/",
        data: {
            "email": form.signin_username.value
        },
        cache: false,
        timeout: TIMEOUT_LIMIT,
        dataType: "json",
        beforeSend: function(xhr){
            startLoading("continue-btn");
        },
        success: function(data){
            if ((data[0] == "return_user") && ($("#return_user").css("display") == "none")) {
                $("#emailTakenMessage").show();
                $("#emailUnknownMessage").hide();
            }
            else 
                if ((data[0] == "new_user") && ($("#new_user").css("display") == "none")) {
                    $("#emailUnknownMessage").show();
                    $("#emailTakenMessage").hide();
                }
                else {
                    $("#emailUnknownMessage").hide();
                    $("#emailTakenMessage").hide();
                }
        },
        error: function(xhr, type, error){
            showMessage("error", "The server encountered an error.  Please try again later.",false,"lookupEmail",xhr.responseText);
            if (DEBUG) 
                showMessage("error", xhr.status+" "+ xhr.responseText+" "+ type+" "+ error,false,"lookupEmail");
        }
    });
}

function checkSignUp(form, confirmPwd){
    var isValid = true;
    var errorMessage = "";
    if (form.first_name.value == "") {
        errorMessage += "Please enter your first name.\n";
        isValid = false;
    }
    if (form.last_name.value == "") {
        errorMessage += "Please enter your last name.\n";
        isValid = false;
    }
    if ((form.username.value == "") || (form.username.value.indexOf("@") == -1) || (form.username.value.indexOf(".") == -1)) {
        errorMessage += "Please enter a valid email.\n";
        isValid = false;
    }
    if ((confirmPwd) && (form.password.value != form.confirm.value)) {
        errorMessage += "The passwords you entered do not match.\n";
        isValid = false;
    }
    if ((form.password.value == "") && ((!confirmPwd) || (form.confirm.value == ""))) {
        errorMessage += "Please enter a password.\n";
        isValid = false;
    }
    if ((isValid) && (form.password.value.length < 6)) {
        errorMessage += "Please enter a valid password (at least 6 characters).\n";
        isValid = false;
    }
    if (!isValid) 
        alert(errorMessage);
    return isValid;
}
