﻿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 = "";
var l_isNew = true;

$(document).bind("formsLoaded", null, function() {
    mvc = getCookie("mvc"); //read mvc cookie
    sid = getCookie("sid");
    $('#msg').html('').hide();
    var _a = getKeyFromQueryStr("ReturnUrl");
    _a = decodeURIComponent(_a.replace(/\+/g, " "));
    if (_a.length > 0)
        rUrl = location.protocol + "//" + location.host + _a;
    else
        rUrl = location.protocol + "//" + location.host;

    if (location.pathname.toLowerCase() == "/login") {
        initLoginForm();
        validateLogin();
    } else {
        initSignupForm();
        validateSignup();
    }
    $.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) {
        $('#msg').html('').hide();
        $('#mt_login_btn_container').hide();
        $('#login_container').show();
        $('#fb_login_btn_container').show();
        $('#fb_login_container').hide();
        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;
                        //$('.fb_square_pic').attr('src', fbUser.pic);
                        if (msg.d.isAuthed) {
                            renderLoggedInHeader(msg.d.fbName.length > 0 ? msg.d.fbName : msg.d.firstName + " " + msg.d.lastName, msg.d.useFbData, msg.d.userType);
                            if (rUrl.length > 0)
                                window.location.href = rUrl;
                        } else {
                            renderLinkAccounts();
                        }
                    }
                });
            });
        })
    });

    FB_RequireFeatures(["Connect"], function() {
        F.removeAttr("disabled")
    });
    //    $('#fb_mt_connect_btn').click(function(e) {
    //        //e.preventDefault();
    //        submitFbMtConnect();
    //    });
    $('#dl_logout').click(function() { logoutUser(); return false; });
    $('#forgot_password_btn').click(function() {
        $('#password').removeClass("required");
        forgotPassword();
        $('#password').addClass("required");
        return false;
    });

    //loadProfileData(sid);
})
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?e="+ msg.d.email + "&reset=1&r=" + rUrl;
                        } else {
                            fbUser.name = msg.d.fbName;
                            fbUser.pic = msg.d.fbPicUrl;
                            userName = msg.d.email;
                            //$('.fb_square_pic').attr('src', fbUser.pic);
                            renderLoggedInHeader(msg.d.fbName.length > 0 ? msg.d.fbName : msg.d.firstName + " " + msg.d.lastName, msg.d.useFbData, msg.d.userType);
                            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() {
            $.ajax({
                type: "POST",
                url: ws_auth + "/isValidRecaptcha",
                data: '{ "challengeVal":"' + Recaptcha.get_challenge() + '", "responseVal":"' + Recaptcha.get_response() + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    if (msg.d) {
                        registerUser();
                    } else {
                        Recaptcha.reload();
                        $('#recaptcha_response_field').addClass('error');
                    }
                }
            });
        }
    });
}
function initLoginForm() {
    $('#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();
    //$('#login_container').show();
    $('#register_container').hide();
    $('#l_s').html("Don't have an account yet?");
    $('a#dl_signup2').show();
    $('a#dl_login2').hide();
    //$('#form_login').validate().resetForm();
    //validateLogin();
}
function initSignupForm() {
    $('#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();

    showRecaptcha('reg_recaptcha', 'white', 7);
    $('#register_container').show();
    $('#l_s').html("Already a Mota user?");
    $('a#dl_signup2').hide();
    $('a#dl_login2').show();
}
function renderLoggedInHeader(greeting, show_fb_img, user_type) {
    $('span#greeting').html(greeting);
    $('#fbPanel').show();
    $('#dl_myaccount').next().show();
    if (show_fb_img)
        $('.fb_square_pic').show();
    $('a#dl_signup').hide();
    $('a#dl_login').hide();
    $('a#dl_login').prev().hide();
    $('a#dl_logout').show();
    //    if (user_type == "seller") {
    //        $('#dl_myaccount').show();
    //        $('#dl_myaccount').prev().show();
    //    } else {
    //        $('#dl_myaccount').hide();
    //        $('#dl_myaccount').prev().hide();
    //    }
}
function renderLoggedOutHeader() {
    $('span#greeting').html('');
    $('#fbPanel').hide();
    $('.fb_square_pic').hide();
    $('a#dl_signup').show();
    $('a#dl_login').show();
    $('a#dl_login').prev().show();
    $('a#dl_logout').hide();
    $('#dl_myaccount').hide();
    $('#dl_myaccount').prev().hide();
    $('#dl_myaccount').next().hide();
}
function renderLinkAccounts() {
    $('#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();
}
function facebook_onlogin() {
    renderLoggedInHeader();
    if (rUrl.length > 0)
        window.location.href = rUrl;
}
function submitFbMtConnect() {
    $.ajax({
        type: "POST",
        url: ws_auth + "/submitFbMtConnect",
        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 + '"}',
        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);
                renderLoggedInHeader(msg.d.fbName.length > 0 ? msg.d.fbName : msg.d.firstName + " " + msg.d.lastName, msg.d.useFbData, msg.d.userType);
                if (rUrl.length > 0)
                    window.location.href = rUrl;
            } else {
                switch (msg.d.message) {
                    case "user_exist":
                        alert('This email is already registered with Mota. Please check your input and try again.');
                        $('#msg').show();
                        break;
                    default:
                        alert('Cannot create/link your mota account, please check your input and try again.');
                        $('#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 buyerid = '';
    var newsOptIn = $('#chkNewsOptIn').is(':checked');
    if (bid)
        buyerid = bid;

    $.ajax({
        type: "POST",
        url: ws_auth + "/registerUser",
        data: '{ "sid":"' + sid + '", "mvc":"' + mvc + '", "email":"' + email + '","password": "' + password + '","firstName": "' + firstName
            + '","lastName": "' + lastName + '","zip":"' + zip + '","bid":"' + buyerid + '","newsOptIn":"'+newsOptIn+'"}',
        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);
                renderLoggedInHeader(msg.d.fbName.length > 0 ? msg.d.fbName : msg.d.firstName + " " + msg.d.lastName, msg.d.useFbData, msg.d.userType);
                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 logoutUser() {
    $.ajax({
        type: "POST",
        url: ws_auth + "/Logout",
        data: '{"userName":"' + userName + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            renderLoggedOutHeader();
            FB.Connect.logout();
        }
    });
}
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();
        }
    });
}
function loadProfileData(_sid) {
    $.ajax({
        type: "POST",
        url: ws_profile + "/getsearchhistory",
        data: '{"sid":"' + _sid + '","count":"10"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $('#msg').html(msg.d.message);
            $('#msg').show();
        }
    });
}