// social-sharing.js
// Adds a checkbox for social sharing to the Echo Submit client

(function($) {

    var streamItems = {};

    // Returns true if we are in a test environment
    var isTest = function() {
        var isTest;
        return function() {
            if (isTest === undefined) {
                isTest = /^test/.test(window.location.host) || /^localhost/.test(window.location.host);
            }
            return isTest;
        };
    }();
    
    var plugin = Echo.createPlugin({
        "name": "SocialSharing",
        "applications": ["Submit", "Stream"],
        "init": function(plugin, application) {
            plugin.extendRenderer("Submit", "socialsharing", plugin.socialsharingRenderer, "SocialSharing");
            plugin.extendTemplate("Submit", '<div class="echo-submit-socialsharing"></div>', "insertAfter", "echo-submit-post-container", "SocialSharing");
            plugin.extendRenderer("Item", "content", plugin.streamItemRenderer, "SocialSharing");

            if (application.namespace === "Submit") {
                Echo.Broadcast.subscribe("Submit.onPostComplete", plugin.postCompleteHandler(application));
            }
            else if (application.namespace === "Stream" && !isTest()) {
                Echo.Broadcast.subscribe("Stream.Plugins.Like.onLikeComplete", plugin.likeCompleteHandler(application));
            }
        }
    });

    plugin.addCss(".echo-submit-socialsharing {float: right; margin-right: 5px;}");

    var unique = 0;
    plugin.generateUniqueId = function() {
        unique++;
        return "ss" + unique;
    }

    plugin.socialsharingRenderer = function(element, dom) {
        var id = plugin.generateUniqueId();
        var application = this;
        if (application.user.account.accounts.length > 0) {
            if (isTest()) {
                plugin.config.set(application, "share", false);
            }
            else {
                plugin.config.set(application, "share", true);
            }
            
            $('<label for="' + id + '">Share with your friends</label>').appendTo(element);
            $('<input type="checkbox"' + (plugin.config.get(application, "share") ? ' checked="checked" ' : '') + 'id="' + id + '" />').click(function() {
                plugin.config.set(application, "share", this.checked);
            }).appendTo(element);
            element.addClass("echo-primaryFont");
        }
    };

    plugin.postCompleteHandler = function(application) {
        return function(topic, args) {
            if (application.config.get("targetURL") === args.targetURL && plugin.config.get(application, "share")) {
                var item = streamItems[args.data.unique];
                publish_rpx(args.postData.content, args.postData.target, item, "commented on this");
            }
        };
    };

    plugin.likeCompleteHandler = function(application) {
        return function(topic, args) {
            if ($.inArray(args.target, application.config.get("target")) !== -1 && application.user.account.accounts.length > 0 && args.item.data.object.permalink) {
                publish_rpx(undefined, args.item.data.object.permalink, args.item, "likes this");
            }
        };
    };

    plugin.streamItemRenderer = function(topic, args) {
        this.parentRenderer("content", arguments);
        streamItems[this.data.unique] = this;
    };

    function publish_rpx(msg, targetURL, item, action) {
        var image;
        var activity = {
            url: targetURL,
            action: action,
            user_generated_content: msg
        };
        if (item) {
            // if item is defined, then we're dealing with a river object and the comment
            // is not specific to this page.

            if (getDomain(targetURL) !== getDomain(window.location.href)) {
                activity.url = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search + "#!p=" + targetURL;
            }
            activity.title = strip(item.data.object.title);
            activity.description = strip(item.data.object.content);
            image = item.data.actor.avatar;
        }
        else {
            // if item is not defined, we are commenting on a stream that is specific to this page, so we can safely grab
            // metadata from the page itself.

            activity.title = $("meta[property='og:title']").attr("content") || $("title").text().replace(/(^\s+)|(\s+$)/g, "");
            activity.description = $("meta[property='og:description']").attr("content");
            image = $("meta[property='og:image']").attr("content");
        }

        if (image) {
            activity.media = [{
                type: "image", 
                src: image,
                href: targetURL
            }];
        }

        if (typeof Capture !== 'undefined') {
            $.ajax({
                url: Capture.urlHelpers.getAccessTokenUrl(),
                success: function(data) {
                    if (data.statusCode === 200) {
                        $.ajax({
                            url: window.location.protocol + "//" + window.location.host + "/_global/rpxproxy.ashx", 
                            data: {
                                token: data.accessToken,
                                activity: JSON.stringify(activity),
                                backplaneChannelId: Backplane.getChannelID()
                            },
                            dataType: "json",
                            type: "POST"
                        });
                    }
                },
                dataType: 'json',
                type: 'GET'
            });
        }
    }

    function strip(html) {
        if (html) {
            return $('<div></div>').html(html).text();
        }
        else {
            return html;
        }
    }

    function getDomain(url) {
        var matches;
        if (matches = /^https?:\/\/(?:[a-z0-9-]+\.)*([a-z0-9-]+\.[a-z0-9-]+)(?:\/|$)/.exec(url)) {
            return matches[1];
        }
        return "";
    }
    
}(jQuery));
