/* care2 facebook connect libs */

var re = /^(.*\-)?.*/;
var fb_www_stage = document.domain.replace(re, "$1");
var C2FBConnect={
    connectApiKey:             'XXX', // prod
    connectApiSecret:          'XXX', // prod
    TEMPLATE_ID_COMMENT:       'XXX', // prod

    init:function() {
        switch (fb_www_stage) {
            case 'smith-':
            case 'smith2-':
                C2FBConnect.connectApiKey = 'afb06647a06a2c58a0439367c80efbc7';
                C2FBConnect.connectApiSecret = 'ebce2492b2f3a65958cd7ed31bbaa419';
                C2FBConnect.TEMPLATE_ID_COMMENT = '185564410493';
                C2FBConnect.TEMPLATE_ID_PETITION_SIG = '205441300493';
                C2FBConnect.TEMPLATE_ID_DAILY_ACTION = '214474895493';
                break;
            case 'beta-':
            case 'beta2-':
                C2FBConnect.connectApiKey = '3090772ce1ad56fb2476b04bb4623192';
                C2FBConnect.connectApiSecret = 'db0f0abaf41d932b1f48b538b10c1145';
                C2FBConnect.TEMPLATE_ID_COMMENT = '83475674450';
                C2FBConnect.TEMPLATE_ID_PETITION_SIG = '97212379450';
                C2FBConnect.TEMPLATE_ID_DAILY_ACTION = '103476614450';
                break;
            case 'alex2-':
            case 'test1-':
            case 'prerelease2-':
                C2FBConnect.connectApiKey = 'd215b9d6f95ff825cf65d625971d6b59';
                C2FBConnect.connectApiSecret = '79192d9a1a4b62017acf00f27904a1b2';
                C2FBConnect.TEMPLATE_ID_COMMENT = '282335365444';
                C2FBConnect.TEMPLATE_ID_PETITION_SIG = '282335365444';
                //C2FBConnect.TEMPLATE_ID_DAILY_ACTION = '103476614450';
                break;
            default:
                C2FBConnect.connectApiKey = 'dfc27a7e48d90111634fd0bbe8eb73d7';
                C2FBConnect.connectApiSecret = '290e5d9575b53fb1ea749c8310853f9b';
                C2FBConnect.TEMPLATE_ID_COMMENT = '87686042959';
                C2FBConnect.TEMPLATE_ID_PETITION_SIG = '97229442959';
                C2FBConnect.TEMPLATE_ID_DAILY_ACTION = '111696202959';
        }
    },


    onConnectWithoutMerge: function(pg) {
        // rumor has it "publish_stream" is coming REAL SOON. Then we will uncomment the showPermissions
        //var continuation = function() {
        //  // redirect to the onconnect script and have it come back here (to comment anchor if possible)
            var requrl = "/fb/onlogin.php";
            if (pg) {
                requrl += "?pg=" + encodeURIComponent(pg);
            }
            window.location = requrl;
        //};
        //FB.Connect.showPermissionDialog("publish_stream", continuation);
    },

    recordAnalyticsPageView: function(page, script) {
        //void(s.t());
        s.pageName = "Facebook Connect : " + page;
        s.channel = "Facebook Connect";
        s.eVar3 = s.pageName; 
        s.eVar4 = s.channel;
        s.eVar6 = "Facebook Connect : " + script;
        s.events = "";
        s.prop3 = s.eVar6;
        s.prop37 = s.pageName;
        void(s.t());
    },

    //onConnectWithMerge: function(pg) {
    onConnect: function(pg) {

        // fake pageview for traccking a page view
        C2FBConnect.recordAnalyticsPageView("Connected Check", "Connected.html");

        // first check if already connected
        var floatContent = '<div style="padding:10px">One Moment Please!!!</div>';
        var floatOptions = {"width":400, "height":200, "branding":"care2", "disableOverlay":true, "disableClose":true};
        var theFloater = CARE2.floater(floatContent, floatOptions);

        // ajax query
        var callback = {
            success: function(o) {
                theFloater.hide();


                var json = o.responseText.replace(/(<([^>]+)>)/ig,'').trim();
                var ret = eval('(' + json + ')');
                //console.log(ret);

                if (ret.connected) {
                    // all good
                    C2FBConnect.recordAnalyticsPageView("Logging In", "LoggingIn.html");
                    window.location = "/fb/onlogin.php?pg="  + encodeURIComponent(pg);
                } else {
                    FB.ensureInit(function() {
                        // ask for publish_stream permission then ack them to merge a possible Care2 acct
                        var continuation = function() {

                            // fake pageview for tracking a page view
                            C2FBConnect.recordAnalyticsPageView("Merge Account", "MergeAccount.html");

                            var url_conn_new = "/fb/onlogin.php?pg="  + encodeURIComponent(pg);
                            var url_conn_existing = "/accounts/login.html?fbconnect=1&pg=" + encodeURIComponent(pg);
                            floatContent = '<div style="padding:10px">'
                                         + '<b>Do you already have a Care2 account?</b><br />'
                                         + '<br />'
                                         + '<ul>'
                                         + ' <li><input onclick="window.location=\'' + url_conn_new + '\'; return false;" type="button" value="No" style="font-weight:bold" class="care2_button_light_medium"></a> (Just login with Facebook)</li>'
                                         + ' <li><input onclick="window.location=\'' + url_conn_existing + '\'; return false;" type="button" value="Yes" style="font-weight:bold" class="care2_button_light_medium"></a> (Connect my Care2 and Facebook accounts)</li>'
                                         + '</ul>'
                                         + '<br />'
                                         + 'If you have a Care2 account, we recommend you connect that account to your Facebook account '
                                         + 'to avoid confusion in the future.' 
                                         + '</div>';
                            floatOptions = {"width":400, "height":200, "branding":"care2", "disableOverlay":true, "disableClose":true};
                            theFloater = CARE2.floater(floatContent, floatOptions);
                        };
                        FB.Connect.showPermissionDialog("publish_stream", continuation); 
                    });
                }
            },
            failure: function(o) {
            },
            timeout: 15000
        }
        var request = YAHOO.util.Connect.asyncRequest('POST', '/fb/servlet_isconnected.php', callback); 
    },

    reshowPublishStreamPermission: function(continuation) {
        FB.ensureInit(function() {
            FB.Connect.showPermissionDialog("publish_stream", continuation); 
        });

    },


    onSubmitHAGLComment: function(continuation, theTextArea, system) {

        var article_title = $('article_title').innerHTML;
        var article_url = String(window.location);
        var article_image = $('article_image');
        if (article_image) {
            article_image = article_image.src;
        } else {
            article_image = "http://" + CARE2.stage + "dingo.care2.com/c2/media_room/care2-full-color.gif";
        }
        var article_comment = theTextArea.value.substring(0,200) + "...";

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            article_url = new String(article_url); article_url = article_url.replace(/\:\/\/.*?\-/, "://");
            article_image = article_image.replace(/\:\/\/.*?\-/, "://");
            //article_url = "http://www.care2.com/causes/womens-rights/blog/show-your-ass-are-we-still-talking-about-this/";   
            //article_image = "http://dingo.care2.com/pictures/c2c/share/11/113/342/1134287_431.jpg";
        }

        var template_data = {
            "story_title":       article_title,
            "story_url":         article_url,
            "story_comment_url": article_url + "#comments",
            "story_comment":     article_comment,
            "images": [{"src": article_image, "href": article_url}]
        }
        switch (system) {
            case 2:
                template_data.story_system = "Care2 Healthy & Green Living";
                break;
            case 25:
                template_data.story_system = "Care2 Causes";
                break;
            default:
                template_data.story_system = "Care2";
                break;
        }
        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_COMMENT, template_data, null, continuation, true);

        // swallow the event
        return false;
    },

    onSubmitPollComment: function(continuation, theTextArea) {

        var article_title = $('article_title').innerHTML;
        var article_url = String(window.location);
        var article_image = $('article_image');
        if (article_image) {
            article_image = article_image.src;
        } else {
            article_image = "http://dingo.care2.com/c2/media_room/care2-full-color.gif";
        }
        var article_comment = theTextArea.value.substring(0,200) + "...";

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            article_url = new String(article_url); article_url = article_url.replace(/\:\/\/.*?\-/, "://");
            //article_image = article_image.replace(/\:\/\/.*?\-/, "://");
            //article_url = "http://www.care2.com/causes/womens-rights/blog/show-your-ass-are-we-still-talking-about-this/";   
            //article_image = "http://dingo.care2.com/pictures/c2c/share/11/113/342/1134287_431.jpg";
        }

        var template_data = {
            "story_title":       article_title,
            "story_url":         article_url,
            "story_comment_url": article_url + "#comment_form",
            "story_comment":     article_comment,
            "story_system":      "Care2 Polls",
            "images": [{"src": article_image, "href": article_url}]
        }

        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_COMMENT, template_data, null, continuation, true);

        // swallow the event
        return false;

    },

    onSubmitCauseComment: function() {
        // actually handled by the HAGL function above.
    },

    onSubmitC2NNComment: function(continuation, theTextArea) {
        
        var article_title = $('article_title').innerHTML;
        var article_url = String(window.location);
        var article_image = $('article_image');
        if (article_image) {
            article_image = article_image.src;
        } else {
            article_image = "http://" + CARE2.stage + "dingo.care2.com/c2/media_room/care2-full-color.gif";
        }
        var article_comment = theTextArea.value.substring(0,200) + "...";

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            article_url = new String(article_url); article_url = article_url.replace(/\:\/\/.*?\-/, "://");
            article_image = article_image.replace(/\:\/\/.*?\-/, "://");
            //article_url = "http://www.care2.com/causes/womens-rights/blog/show-your-ass-are-we-still-talking-about-this/";   
            //article_image = "http://dingo.care2.com/pictures/c2c/share/11/113/342/1134287_431.jpg";
        }

        var template_data = {
            "story_title":       article_title,
            "story_url":         article_url,
            "story_comment_url": article_url + "#comments",
            "story_comment":     article_comment,
            "story_system":      "Care2 News Network", // XXX - needs to be customized per system
            "images": [{"src": article_image, "href": article_url}]
        }
        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_COMMENT, template_data, null, continuation, true);

        // swallow the event
        return false;
    },

    onSubmitShareComment: function(continuation, theTextArea) {
        
        var article_title = $('article_title').innerHTML;
        var article_url = String(window.location);
        var article_image = $('article_image');
        if (article_image) {
            article_image = article_image.src;
        } else {
            article_image = "http://" + CARE2.stage + "dingo.care2.com/c2/media_room/care2-full-color.gif";
        }
        var article_comment = theTextArea.value.substring(0,200) + "...";

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            article_url = new String(article_url); article_url = article_url.replace(/\:\/\/.*?\-/, "://");
            article_image = article_image.replace(/\:\/\/.*?\-/, "://");
            //article_url = "http://www.care2.com/causes/womens-rights/blog/show-your-ass-are-we-still-talking-about-this/";   
            //article_image = "http://dingo.care2.com/pictures/c2c/share/11/113/342/1134287_431.jpg";
        }

        var template_data = {
            "story_title":       article_title,
            "story_url":         article_url,
            "story_comment_url": article_url + "#comments",
            "story_comment":     article_comment,
            "story_system":      "Care2 Share", // XXX - needs to be customized per system
            "images": [{"src": article_image, "href": article_url}]
        }
        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_COMMENT, template_data, null, continuation, true);

        // swallow the event
        return false;
    },

    onSubmitDailyAction: function(continuation, title, description) {
        
        var article_title = title
        var article_url = String(window.location);
        var article_image = "http://dingo.care2.com/facebook/dailyaction_fb.jpg";
        var article_summary = description.substring(0,200) + "...";

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            article_url = new String(article_url); article_url = article_url.replace(/\:\/\/.*?\-/, "://");
        }

        var template_data = {
            "story_title":       article_title,
            "story_url":         article_url,
            "story_summary":     article_summary,
            "images": [{"src": article_image, "href": article_url}]
        }
        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_DAILY_ACTION, template_data, null, continuation, true);

        // swallow the event
        return false;
    },

    hasAppPermission : function(thePermission, continuation) {
        FB.ensureInit(function() {
            FB.Facebook.apiClient.users_hasAppPermission(thePermission, continuation);
        });
    },

    publishStory : function(templateID, template_data, user_message, continuation, promptIfNotAuto) {
        FB.ensureInit(function() {
            // do we have publishstream permission? If not, showFeedDialog
            FB.Facebook.apiClient.users_hasAppPermission("publish_stream", 
                function (result) {
                    if (result != 0) {
                        var ret = FB.Facebook.apiClient.feed_publishUserAction(templateID, template_data, 
                                    [], "", FB.FeedStorySize.shortStory, user_message, continuation);
                    } else if (promptIfNotAuto) {
                        if (!user_message) {
                            user_message = "Write a note for your Facebook friends...";
                        }
                        var ret = FB.Connect.showFeedDialog(templateID, template_data, null, null, null, 
                                FB.RequireConnect.promptConnect, continuation,
                                user_message, null);
                    }
                });
        });
    },

    onSignPetition: function(petition_data) {
        if ( (!petition_data.image_url) || (petition_data.image_url == '') ) {
            petition_data.image_url = "http://" + CARE2.stage + "dingo.care2.com/c2/media_room/care2-full-color.gif";
        }

        // Facebook does not accept our dev urls because it cannot see them. This hack lets us
        // test on articles that are inproduction too (stripping out stage-)
        if (CARE2.stage) {
            petition_data.url = new String(petition_data.url); petition_data.url = petition_data.url.replace(/\:\/\/.*?\-/, "://");
            petition_data.image_url = petition_data.image_url.replace(/\:\/\/.*?\-/, "://");
            //article_url = "http://www.care2.com/causes/womens-rights/blog/show-your-ass-are-we-still-talking-about-this/";   
            //article_image = "http://dingo.care2.com/pictures/c2c/share/11/113/342/1134287_431.jpg";
        }

        var template_data = {
            "story_title":       petition_data.title,
            "story_url":         petition_data.url,
            "story_summary":     petition_data.summary,
            "signature_count":   petition_data.signature_count,
            "images": [{"src":   petition_data.image_url, "href": petition_data.url}]
        }
        var user_message = "I just signed this petition!";
        var continuation = function() { };

        C2FBConnect.publishStory(C2FBConnect.TEMPLATE_ID_PETITION_SIG, template_data, user_message, continuation, false);
    },

    
    // Strip stage strings out of URLs, since Facebook doesn't accept them
    cleanUrl: function(url) {
        if (CARE2.stage) {
            url = new String(url);
            return url.replace(/\:\/\/[^\/]*?\-/, "://");
        } else {
            return url;
        }
    }

};


C2FBConnect.init();
