﻿var Facebook = new function () {
    var debug = false;

    var self = this;

    this.access_token = null;
    this.id = null;
    this.isUserFound = false;
    this.isAuthedWithDTD = false;
    this.autoReconnect = false;

    this.fb_appId = "";
    this.overrideId = null;

    this.locationKeys = "";

    this.fb_uid = function () {
        if (this.overrideId) {
            return this.overrideId;
        }
        else {
            return this.id;
        }
    };

    this.setLocationKeys = function (keys) {
        self.locationKeys = keys;
    };

    this.showFacebookLogin = function () {
        self.access_token = null;
        self.id = null;
        self.overrideId = null;
        self.isUserFound = false;
        self.autoReconnect = false;
        self.isAuthedWithDTD = false;

        FB.init({
            appId: self.fb_appId,
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });

        FB.login(function (response) {
            if (response.authResponse) {
                //user successfully logged in
                var m_url = window.location.href;
                self.access_token = response.authResponse.accessToken;
                self.id = response.authResponse.userID;
                if (!self.isAuthedWithDTD) {
                    if (m_url.indexOf("Login") < 0 && m_url.indexOf("access_token") < 0) {
                        $.cookie("firstUse", "false", { path: "/", expires: 365 });
                        var locKeys = "";
                        if (self.locationKeys != "") {
                            locKeys = "&locKeys=" + encodeURIComponent(self.locationKeys);
                        }
                        window.location.href = "/Login?access_token=" + self.access_token + "&expires_in=" + response.authResponse.expiresIn + "&fb_uid=" + self.id + "&ReturnUrl=" + encodeURIComponent(window.location.href) + locKeys;
                    }
                }
            }
        }, { scope: 'publish_stream,email,user_location,offline_access' });

    };

    this.showDTDLogin = function (access_token, id) {
        if (!access_token) {
            access_token = self.access_token;
        }
        if (!id) {
            id = self.fb_uid();
        }
        if (window.location.href.indexOf("Login") < 0 && window.location.href.indexOf("access_token") < 0) {
            window.location.href = '/Login?access_token=' + access_token + '&fb_uid=' + id + '&ReturnUrl=' + encodeURI(window.location.href);
        }
    };

    this.showShareScreen = function (data) {
        // message: data.message,
        data.method = 'feed';

        if (data.picture) {
            var rdm = Math.random();
            data.picture += "?v=" + rdm;
        }
        data.message = "";
        FB.ui(data,
			function (response) {
			    if (self.debug) {
			        if (response && response.post_id) {
			            alert('Post was published.');
			        } else {
			            alert('Post was not published.');
			        }
			    }
			}
		);
    };

    this.isLoggedIn = function () {
        return (self.isAuthedWithDTD && self.isUserFound);
        $('.profile-image').css('display', 'inline-block');
    };

    this.init = function (overrideFBId, appId) {
        if (overrideFBId) {
            self.overrideId = overrideFBId;
        }

        if (appId) {
            self.fb_appId = appId;
        }
        else {
            self.fb_appId = '161014790590908';
        }
        self.addConnectButton(function () {
            //            if (profileImgId && self.isLoggedIn()) {
            //                if (window.location.href.indexOf("buynow") > 0) {
            //                    $("#" + profileImgId).attr("src", "https://graph.facebook.com/" + self.fb_uid() + "/picture?access_token=" + self.access_token + "&type=small&return_ssl_resources=1");
            //                }
            //                else {
            //                    $("#" + profileImgId).attr("src", "https://graph.facebook.com/" + self.fb_uid() + "/picture?access_token=" + self.access_token + "&type=small");
            //                }
            //                $("#" + profileImgId).height(32);
            //            }
        });

    };

    this.initFacebook = function (callback) {
        if (typeof (FB) == 'undefined' || FB == null) {
            $('div#l-share a.facebook').hide();
            $('div#l-share a.twitter').css('margin-left', '27px');
            $('div.shareLinks a.facebook-subscribe').hide();
            $('div.shareLinks a.facebook-register').hide();
            $('div.shareLinks a.facebook-purchase').hide();
            $('div.signin-fb').hide();
            return;
        }

        FB.init({
            appId: self.fb_appId,
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });
        self.checkConnectionStatus(function () {
            if (self.isUserFound && !self.isAuthedWithDTD && self.autoReconnect && window.location.href.indexOf("login") < 0) {
                self.showDTDLogin(self.access_token, self.fb_uid());
            }

            if (callback) {
                callback();
            }
        });
    };
    /// Expects container to be on the page and a valid jQuery div object.
    this.addConnectButton = function (callback) {
        self.initFacebook(function () {
            var btnConnect = "";
            if (window.location.pathname.indexOf("buynow" > -1)) { 
                btnConnect = $('<a href="javascript:validateCheckFacebook();"><img src="/Content/Images/Dtd2/ButtonsCommon/button_connect_w_fb.png" alt="Sign In With Facebook" style="cursor:pointer;" /></a>');
            } else {
                btnConnect = $('<a href="javascript:Facebook.showFacebookLogin();"><img src="/Content/Images/Dtd2/ButtonsCommon/button_connect_w_fb.png" alt="Sign In With Facebook" style="cursor:pointer;" /></a>');
           
            }

             $(".facebookConnectButton").append(btnConnect);

            if (callback) {
                callback();
            }
        });
    };

    this.checkConnectionStatus = function (callback) {

        $.ajax({
            url: '/WebServices/CheckFacebook.aspx',
            dataType: 'json',
            type: 'POST',
            data: {
                op: "1"
            },
            success: function (json) {
                self.id = json.fb_uid;
                self.access_token = json.access_token;
                self.isAuthedWithDTD = (self.fb_uid != null && self.access_token != null);
                self.isUserFound = (self.fb_uid != null && self.access_token != null);
                self.autoReconnect = json.autoReconnect;

                if (!self.isUserFound) {
                    FB.getLoginStatus(function (response) {
                        if (response.session) {
                            $.ajax({
                                url: '/WebServices/CheckFacebook.aspx',
                                dataType: 'json',
                                type: 'POST',
                                data: {
                                    access_token: response.session.access_token,
                                    fb_uid: response.session.uid
                                },
                                success: function (json) {
                                    //self.isAuthedWithFacebook = json.isAuthed;
                                    self.isAuthedWithDTD = json.isLoggedIn;
                                    self.isUserFound = json.isFound;
                                    self.autoReconnect = json.autoReconnect;
                                    self.access_token = json.access_token;
                                    self.id = json.fb_uid;

                                    if (callback) {
                                        callback();
                                    }
                                }
                            });
                        }
                        else if (callback) {
                            callback();
                        }
                    });
                }
                else if (callback) {
                    callback();
                }
            }
        });
    };
    this.connect = function () {
        self.initFacebook();
        if (self.isLoggedIn()) {
            return;
        }
        else if (!self.isAuthedWithDTD) {
            // account linked and signed into facebook, sign into dtd now
            self.showDTDLogin();
        }
        else {
            // need to link accounts
            self.showFacebookLogin();
        }
    };
    // data is json object in following structure:
    /*  
    {
    picture: "",
    link: "",
    name: "",
    caption: "",
    description: "",
    source: ""
    }
    */
    this.postToWall = function (data) {
        self.initFacebook(function () {
            self.showShareScreen(data);
        });
    };
};
