﻿var fbUser = Object;
var mvc;
var sid;
var userName = "";
var DL_TITLE_LOGIN = "Sign in to your Mota account";
var DL_SUBTITLE_LOGIN = "Use one of the following methods to log-in:";
var DL_TITLE_SIGNUP = "Sign up for a Mota account";
var DL_SUBTITLE_SIGNUP = "";
var rUrl = "http://www.mota.com";
var l_isNew = true;

$(document).bind("formsLoaded", null, function() {
    mvc = getCookie("mvc"); //read mvc cookie
    sid = getCookie("sid");
    $('#msg').html('').hide();
    initLoginForm();
    validateLogin();
    $.validator.messages.required = "";

    $('#tab_fb').click(function(e) {
        $('#msg').html('').hide();
        $('#fb_login_btn_container').hide();
        $('#fb_login_container').show();
        $('#login_container').hide();
        if ($('#dl_title').html() == DL_TITLE_LOGIN)
            $('#mt_login_btn_container').show();
        return false;
    });

    $('#tab_mt').click(function(e) {
        $('#m-bottom').hide();
        $('#msg').html('').hide();
        $('#mt_login_btn_container').hide();
        $('#login_container').show();
        $('#fb_login_btn_container').show();
        $('#fb_login_container').hide();
        $('#m-bottom').show();
        return false;
    });
    $('a.link_login').click(function(e) {
        initLoginForm();
        validateLogin();
        return false;
    });
    $('a.link_signup').click(function(e) {
        initSignupForm();
        validateSignup();
        return false;
    });
    $('a#link_has_account').live("click", function() {
        if ($('a#link_has_account').html() == "Have a Mota account already?") {
            $('#link_account_title').html("Login to your existing Mota account");
            $('.pwd_pnl').hide();
            $("#link_password").val('');
            $('a#link_has_account').html("I don't have a Mota account.");
            l_isNew = false;
            validateLinkAccount();
        } else {
            $('#link_account_title').html("Create your Mota account");
            $('.pwd_pnl').show();
            $("#link_password").val('');
            $('a#link_has_account').html("Have a Mota account already?");
            l_isNew = true;
            validateLinkAccount();
        }
        return false;
    });
});
$(document).ready(function() {
    var F = $('#fb_login');
    $('#msg').html('').hide();
    F.attr("disabled", "disabled").unbind().click(function() {
        FB_RequireFeatures(["Connect"], function() {
            FB.Facebook.init(fb_api_key, "/buy/xd_receiver.htm", null);
            FB.Connect.requireSession();

            FB.Facebook.get_sessionState().waitUntilReady(function(fb_user) {
                fbUser = fb_user;
                $.ajax({
                    type: "POST",
                    url: ws_auth + "/getMotaUserWithFb",
                    data: '{"fbUid":"' + fbUser.uid + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        fbUser.name = msg.d.fbName;
                        fbUser.pic = msg.d.fbPicUrl;
                        userName = msg.d.email;
                        if (msg.d.isAuthed) {
                            if (rUrl.length > 0)
                                window.location.href = rUrl;
                        } else {
                            renderLinkAccounts();
                        }
                    }
                });
            });
        })
    });

    FB_RequireFeatures(["Connect"], function() {
        F.removeAttr("disabled")
    });
    $('#forgot_password_btn').click(function() {
        $('#password').removeClass("required");
        forgotPassword();
        $('#password').addClass("required");
        return false;
    });

})
function validateLogin() {
    $('#form_login').validate({
        rules: {
            accountName: {
                required: "*",
                email: "*"
            },
            password: {
                required: "*",
                minlength: 4
            }
        },
        hightlight: function(e) {
            $(e).addClass("error");
        },
        unhighlight: function(e) {
            $(e).removeClass("error");
        },
        onkeyup: false,
        submitHandler: function() {
            $.ajax({
                type: "POST",
                url: ws_auth + "/Login",
                data: '{ "userName": "' + $("#accountName").val() + '","password": "' + $("#password").val() + '","createPersistentCookie": "false" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    if (msg.d.isAuthed) {
                        if (msg.d.reset) {
                            window.location.href = "/changepwd.htm";
                        } else {
                            fbUser.name = msg.d.fbName;
                            fbUser.pic = msg.d.fbPicUrl;
                            userName = msg.d.email;
                            //$('.fb_square_pic').attr('src', fbUser.pic);
                            if (rUrl.length > 0)
                                window.location.href = rUrl;
                        }
                    } else {
                        $('#msg').html('Login failed.');
                        $('#msg').show();
                    }
                }
            });
        }
    });
}
function validateLinkAccount() {
    $('#form_link').validate({
        messages: {
            link_password2: {
                required: " ",
                equalTo: "Please enter the same password as above"
            }
        },
        rules: {
            link_password: {
                required: true,
                minlength: 4
            }
        },
        hightlight: function(e) {
            $(e).addClass("error");
        },
        unhighlight: function(e) {
            $(e).removeClass("error");
        },
        onkeyup: false,
        submitHandler: function() {
            submitFbMtConnect();

        }
    });
    if (l_isNew) {
        $('#link_password2').rules("add", {
            required: true,
            minlength: 4
        });
    } else {
        $('#link_password2').rules("remove", "required");
    }

}
function validateSignup() {
    $('#form_register').validate({
        messages: {
            reg_password2: {
                required: " ",
                equalTo: "Please enter the same password as above"
            }
        },
        rules: {
            reg_password: {
                required: true,
                minlength: 4
            },
            reg_zip: {
                required: true,
                minlength: 5,
                maxlength: 5,
                digits: true
            }
        },
        hightlight: function(e) {
            $(e).addClass("error");
        },
        unhighlight: function(e) {
            $(e).removeClass("error");
        },
        onkeyup: false,
        submitHandler: function() {
            registerUser();
        }
    });
}
function initLoginForm() {
    $('#m-bottom').hide();
    $('#msg').html('').hide();
    $('#dl_title').html(DL_TITLE_LOGIN);
    $('#dl_subtitle').html(DL_SUBTITLE_LOGIN);
    $('#fb_login_btn_container').show();
    $('#fb_login_container').hide();
    $('#mt_login_btn_container').show();
    $('#login_container').hide();
    $('#register_container').hide();
    $('#l_s').html("Don't have an account yet?");
    $('a#dl_signup2').show();
    $('a#dl_login2').hide();
    $('#m-bottom').show();
}
function initSignupForm() {
    $('#m-bottom').hide();
    $('#msg').html('').hide();
    $('#dl_title').html(DL_TITLE_SIGNUP);
    $('#dl_subtitle').html(DL_SUBTITLE_SIGNUP);
    $('#login_container').hide();
    $('#fb_login_btn_container').hide();
    $('#fb_login_container').show();
    $('#mt_login_btn_container').hide();

    $('#register_container').show();
    $('#l_s').html("Already a Mota user?");
    $('a#dl_signup2').hide();
    $('a#dl_login2').show();
    $('#m-bottom').show();
}
function renderLinkAccounts() {
    $('#m-bottom').hide();
    $('#dl_title').html("Link to a Mota account");
    $('#dl_subtitle').html("A few more things...");
    if (fbUser.pic.length > 0)
        $('.fb_square_pic').show();
    $('#fb_login_container').hide();
    $('#mt_login_btn_container').hide();
    $('#fb_connect_container').show();
    $('#link_account_container').show();
    $('#login_container').hide();
    $('#register_container').hide();
    $('#dl_bottom').hide();
    validateLinkAccount();
    $('#m-bottom').show();
}
function facebook_onlogin() {
    renderLoggedInHeader();
    if (rUrl.length > 0)
        window.location.href = rUrl;
}
function submitFbMtConnect() {
    $.ajax({
        type: "POST",
        url: ws_auth + "/betaFbMtConnect",
        data: '{ "mvc":"' + mvc + '", "fbUid":"' + fbUser.uid + '","userName": "' + $("#link_userName").val() + '","password": "' + $("#link_password").val()
            + '","followFriends": "' + $("input#follow_friend").attr('checked') + '","useFbData":"' + $("input#use_fb_data").attr('checked') + '","isNew":"' + l_isNew + '","betaCode":"' + $("#link_betaCode").val() + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d.isAuthed) {
                fbUser.name = msg.d.fbName;
                fbUser.pic = msg.d.fbPicUrl;
                userName = msg.d.email;
                $('.fb_square_pic').attr('src', msg.d.fbPicUrl);
                if (rUrl.length > 0)
                    window.location.href = rUrl;
            } else {
                switch (msg.d.message) {
                    case "user_exist":
                        $('#msg').html('This email is already registered with Mota. Please check your input and try again.');
                        $('#msg').show();
                        break;
                    default:
                        $('#msg').html(msg.d.message);
                        $('#msg').show();
                        break;
                }
            }
        }
    });
}

function registerUser() {
    var email = $('#reg_email').val();
    var firstName = $('#reg_first_name').val();
    var lastName = $('#reg_last_name').val();
    var password = $('#reg_password').val();
    var zip = $('#reg_zip').val();
    var betaCode = $('#reg_betaCode').val();
    $.ajax({
        type: "POST",
        url: ws_auth + "/registerBetaUser",
        data: '{ "sid":"' + sid + '", "mvc":"' + mvc + '", "email":"' + email + '","password": "' + password + '","firstName": "' + firstName
            + '","lastName": "' + lastName + '","zip":"' + zip + '","betaCode":"' + betaCode + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d.isAuthed) {
                fbUser.name = msg.d.fbName;
                fbUser.pic = msg.d.fbPicUrl;
                userName = msg.d.email;
                $('.fb_square_pic').attr('src', msg.d.fbPicUrl);
                if (rUrl.length > 0)
                    window.location.href = rUrl;
            } else {
                switch (msg.d.message) {
                    case "user_exist":
                        $('#msg').html('This email is already registered with Mota. Please check your input and try again.');
                        $('#msg').show();
                        break;
                    default:
                        $('#msg').html(msg.d.message);
                        $('#msg').show();
                        break;
                }
            }
        }
    });
}
function forgotPassword() {
    $.ajax({
        type: "POST",
        url: ws_auth + "/resetPassword",
        data: '{"emailid":"' + $('#accountName').val() + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $('#msg').html(msg.d.message);
            $('#msg').show();
        }
    });
}