﻿var AsyncUserID = "";
var AsyncLoginType="";
function FBConnect(IsFirstTime) {
    var PrivateVariables = {
        Context: {
            ValidateUser: "ValidateUser",
            NotConfirmeduser: "NotConfirmeduser",
            CreateUser: "CreateUser",
            UpdateUser: "UpdateUser"
        },
        Validations: {
            EmailAddress: "^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",
            MobileNumber: "^[789]\\d{9}$"
        },
        ServerValidationMessage: {
            CreateUserSuccess: "Confirmed",
            NotConfirmed: "NotConfirmed"
        },
        fbUser: {
            "first_name": "",
            "last_name": "",
            "gender": "",
            "id": "",
            "logintype":""
        },
        Path: "",
        pagePath: "",
        ServicePath: "App_Handlers/FBConnect.ashx",
        Pathpage: "socialoauth.aspx"
    };

    var PrivateMethods = {
        Init: function () {
            if (IsFirstTime) {
                $("#" + fbRegistration).dialog({
                    bgiframe: false,
                    modal: true,
                    width: 900,
                    autoOpen: false,
                    resizable: false,
                    draggable: true,
                    position: ['center', 50],
                    height: 600,
                    title: ""
                });
            }
            $("#rbtnMobile,#rbtnFBEmail").attr("checked", "checked");
            PrivateMethods.AttachEvents();
            PrivateVariables.Path = siteBase + PrivateVariables.ServicePath;
            PrivateVariables.pagePath = siteBase + PrivateVariables.Pathpage;
        },
        AttachEvents: function () {
            try {
                $(".fbConnectLoginButton").bind('click', function () {
                    //FB.login(PrivateMethods.handleSessionResponse);
                    PrivateMethods.loadpopup('facebook');
                    return false;
                });
               // $("#g_login").bind('click', function () { PrivateMethods.loadpopup('google'); return false });
            }
            catch (Error)
            { }
        },
        loadpopup: function (a) {
            var popuppath = PrivateVariables.pagePath + "?reqpage=" + a;
            window.open(popuppath, '', 'location=1,status=1,scrollbars=1,width=700,height=450');
        },
        handleSessionResponse: function (PrmResponse,PrmLoginType) {
            try {
                if (PrmResponse) {
                    var PostServerData = {
                        "ID": PrmResponse,
                        "LoginType":LoginType,
                        "Context": PrivateVariables.Context.ValidateUser,
                        "CurrentCustomerID": CurrentCustomerID
                    };

                    PrivateMethods.PostDataToServer(PrivateVariables.Path, PostServerData, true);
                }
                return false;
            } catch (e) {
                return false;
            }
        },
        NotConfirmeduser: function () {
            try {

                var PostServerData = {
                    "Context": PrivateVariables.Context.NotConfirmeduser
                };
                var strPath = window.location.href.replace(window.location.protocol + "//" + window.location.host + "/", "");
                strPath = strPath.split("/");
                var path = window.location.protocol + "//" + window.location.host + "/" + strPath[0] + "/fbConnect.aspx";
                PrivateMethods.PostDataToServer(path, PostServerData, true);
            }
            catch (e)
            { }
        },
        SetEmail: function (PrmValue) {
            try {
                $("#txt_fb_Email").val(PrmValue);
            }
            catch (e)
            { }
        },
        GetfbValueAndSet: function () {
            try {
                FB.getLoginStatus(function (response) {
                    if (response.session) {
                        FB.api('/me', function (fbUserInfo) {
                            if (fbUserInfo.email) {
                                PrivateMethods.SetEmail(fbUserInfo.email);
                            }
                            else {
                                FB.ui({
                                    method: 'permissions.request',
                                    perms: 'email'
                                }, function (PermissionStatus) {
                                    if (PermissionStatus) {
                                        FB.api('/me', function (fbUserInfo) {
                                            if (fbUserInfo.email) {
                                                PrivateMethods.SetEmail(fbUserInfo.email);
                                            }
                                        });
                                    }
                                });
                            }
                        });

                    }
                    else {
                        alert("You are logged out, and the cookie has been cleared");
                        location.href = "signout.aspx";
                    }
                });
            } catch (e) { }
            return false;
        },
        VarifyfbInputs: function () {
            try {
                var boolVarified = true;
                $("#spn_fb_Email,#spn_fb_User_Mobile").hide();
                if ($("#rbtnMobile").attr("checked")) {
                    if ($("#txt_fb_User_Mobile").val().trim() !== "") {
                        var MobilePattern = new RegExp(PrivateVariables.Validations.MobileNumber);
                        if (!MobilePattern.test($("#txt_fb_User_Mobile").val())) {
                            $("#txt_fb_User_Mobile").val("").focus();
                            $("#spn_fb_User_Mobile").show();
                            boolVarified = false;
                        }
                        else {
                            $("#spn_fb_User_Mobile").hide();
                            boolVarified = true;
                        }
                    }
                    else {
                        $("#txt_fb_User_Mobile").val("").focus();
                        $("#spn_fb_User_Mobile").show();
                        boolVarified = false;
                    }

                }
                if ($("#rbtnFBEmail").attr("checked")) {
                    if ($("#txt_fb_Email").val().trim() !== "") {
                        var EmailPattern = new RegExp(PrivateVariables.Validations.EmailAddress);
                        if (!EmailPattern.test($("#txt_fb_Email").val())) {
                            $("#txt_fb_Email").focus();
                            $("#spn_fb_Email").show();
                            boolVarified = false;
                        } else {
                            $("#spn_fb_Email").hide();
                            boolVarified = true;
                        }
                    }
                    else {
                        $("#txt_fb_Email").focus();
                        $("#spn_fb_Email").show();
                        boolVarified = false;
                    }
                }
            } catch (e) {

            }
            return boolVarified;
        },
        AttachRunTimeElementsEvents: function () {
            try {
                $("#rbtnFBEmail").bind("click", function () {

                    $(this).attr("checked") ? $("#ul_rbtnFBEmail").show() : $("#ul_rbtnFBEmail").hide();
                });

                $("#img_fb_email").bind("click", PrivateMethods.GetfbValueAndSet);

                $("#rbtnMobile").bind("change", function () {
                    try {
                        if ($("#rbtnMobile").attr("checked")) {
                            $("#ul_Mobile").show();
                        }
                        else {
                            $("#ul_Mobile").hide();
                        }
                    }
                    catch (Error)
                    { }
                    return false;
                });
                $("#btn_fbReg").bind("click", function () {

                    if (PrivateMethods.VarifyfbInputs()) {
                        $("#spn_fb_Email,#spn_fb_User_Mobile").hide();
                        var PostServerData = {
                            "ID": PrivateVariables.fbUser.id,
                            "CurrentCustomerID": CurrentCustomerID,
                            "First_Name": PrivateVariables.fbUser.first_name,
                            "Last_Name": PrivateVariables.fbUser.last_name,
                            "Gender": PrivateVariables.fbUser.gender,
                            "LoginType":PrivateVariables.fb.logintype,
                            "Context": PrivateVariables.Context.CreateUser,
                            "EMail": $("#txt_fb_Email").val().trim() !== "" && $("#rbtnFBEmail").attr("checked") ? $("#txt_fb_Email").val().trim() : "",
                            "Mobile": $("#txt_fb_User_Mobile").val().trim() !== "" && $("#rbtnMobile").attr("checked") ? $("#txt_fb_User_Mobile").val().trim() : ""
                        };

                        PrivateMethods.PostDataToServer(PrivateVariables.Path, PostServerData, true);
                    }
                    return false;
                });
                $("#btn_BBReg").bind("click", function () {
                    var PostServerData = {
                        "ID": FB.getSession().uid,
                        "Name": fbUser.name,
                        "Context": PrivateVariables.Context.UpdateUser
                    };
                    //PrivateMethods.PostDataToServer(PrivateVariables.Path, PostServerData, true);
                    return false;
                });
                $("#a_DWC").bind("click", function () {
                    $(">div", $("#" + Content)).empty();
                });
            } catch (e) { }
        },
        PostDataToServer: function (PrmStrPath, PrmData, PrmAsync) {
            try {
                $.ajax({
                    url: PrmStrPath,
                    type: "POST",
                    data: PrmData,
                    error: function (response) { },
                    success: function (response) {
                        PrivateMethods.ReceiveServerData(response, PrmData.Context);
                    },
                    async: PrmAsync
                });
            } catch (e) {

            }
        },
        ReceiveServerData: function (PrmResponse, PrmContext) {
            try {
                if (PrivateMethods.ValidateServerData(PrmResponse, PrmContext)) {
                    switch (PrmContext) {
                        case PrivateVariables.Context.ValidateUser:
                            if (PrmResponse.toUpperCase() === PrivateVariables.ServerValidationMessage.NotConfirmed.toUpperCase()) {
                                PrivateMethods.NotConfirmeduser();
                            }
                            else {
                                window.location.href = window.location.href;
                            }
                            break;
                        case PrivateVariables.Context.NotConfirmeduser:
                            if (PrmResponse.trim() !== "") {
                                $("#" + Content).html(PrmResponse);
                                PrivateMethods.AttachRunTimeElementsEvents();
                                $("#" + fbRegistration).dialog('open');
                            }
                            break;
                        case PrivateVariables.Context.CreateUser:
                        case PrivateVariables.Context.UpdateUser:
                            if (PrmResponse.toUpperCase() === PrivateVariables.ServerValidationMessage.CreateUserSuccess.toUpperCase()) {
                                $("#" + fbRegistration).dialog('close');
                                window.location.href = window.location.href;
                            }
                            else {
                                alert("Please try again!");
                            }
                            break;
                        default:
                            break;
                    }
                }
                else {
                }
            } catch (e) {

            }
        },
        ValidateServerData: function (PrmResponse, PrmContext) {
            try {
                var boolReturnValue = false;
                switch (PrmContext) {
                    case PrivateVariables.Context.ValidateUser:
                        boolReturnValue = true;
                        break;
                    case PrivateVariables.Context.CreateUser:
                        boolReturnValue = true;
                        break;
                    case PrivateVariables.Context.UpdateUser:
                        boolReturnValue = true;
                        break;
                    case PrivateVariables.Context.NotConfirmeduser:
                        boolReturnValue = true;
                        break;
                    default:
                        break;
                }
            } catch (e) {

            }
            return boolReturnValue;
        }
    };

    this.PublicMethod = {
        CallhandleSessionResponse: function (LoginType, FBID, ObjFBInfo) {
            PrivateVariables.fbUser = ObjFBInfo;
            PrivateMethods.handleSessionResponse(FBID, LoginType);
        }

    };
    PrivateMethods.Init();
}


function ValidateUser(LoginType,ID, ObjUserInfo) {
    try {

        var objFBConnect1 = new FBConnect(false);
        objFBConnect1.PublicMethod.CallhandleSessionResponse(LoginType, ID, ObjUserInfo);
        AsyncUserID = ID;
        AsyncLoginType = LoginType;

    } catch (e) {
        alert(e.Message);
    }
}




var Message = '';
var TitleName = '';
var ImagePicture = '';
var TopicURLLink = 'http://www.bindaasbargain.com/';

function loginResponse(response) {
    if (response.status == "connected") {
        postToFeed();
    }
};
function postToFeed() {
    FB.getLoginStatus(function (response) {
        if (response.session) {
            FB.api({ method: 'users.hasAppPermission', ext_perm: 'publish_stream' }, function (resp) {
                var params = {};
                params['message'] = Message;
                params['name'] = TitleName;
                //params['description'] = 'D';
                params['link'] = TopicURLLink;
                params['picture'] = ImagePicture;
                //params['caption'] = 'C';
                if (resp === "1") {
                    FB.api('/me/feed', 'post', params, function (response) {
                        if (!response || response.error) {
                            alert('Error occured. Not posted on facebook wall');
                        } else {
                        }
                    });
                } else {
                    FB.ui({
                        method: 'permissions.request',
                        perms: 'publish_stream'
                    }, function (PermissionStatus) {
                        if (PermissionStatus.perms == "publish_stream") {
                            FB.api('/me/feed', 'post', params, function (response) {
                                if (!response || response.error) {
                                    alert('Error occured. Not posted on facebook wall');
                                } else {
                                }
                            });
                        }
                    });
                }
            });
        }
        else {
            FB.login(loginResponse);
        }
    });
};


