﻿(function ($) {

    var plugin = Echo.createPlugin({
        "name": "LMKStreamSubscription",
        "applications": ["Stream"],
        "init": function (plugin, application) {
            plugin.extendTemplate("Stream", plugin.subscribeResponseTemplate, "insertAfter", "echo-stream-header");
            plugin.extendTemplate("Stream", plugin.subscribeFormTemplate, "insertAfter", "echo-stream-header");
            plugin.extendTemplate("Stream", plugin.subscribeLinkTemplate, "insertAfter", "echo-stream-header");
            plugin.extendRenderer("Stream", "subscribeResponseWrapper", plugin.subscribeResponseWrapperRenderer);
            plugin.extendRenderer("Stream", "subscribeLink", plugin.subscribeLinkRenderer);
            plugin.extendRenderer("Stream", "subscribeFormWrapper", plugin.subscribeFormWrapperRenderer);
            plugin.extendRenderer("Stream", "subscribeFormButton", plugin.subscribeFormButtonRenderer);
            plugin.extendRenderer("Stream", "subscribeFormEmail", plugin.subscribeFormEmailRenderer);
            plugin.vars = plugin.vars || {}; // init the plugin vars
            plugin.set(plugin, "appkey", application.config.get("appkey"));
            if (plugin.config.get(application, "subscribeQuery")) {
                // use the custom query
                plugin.set(plugin, "query", plugin.config.get(application, "subscribeQuery"));
            }
            else {
                // use the stream query
                plugin.set(plugin, "query", application.config.get("query"));
            }
            if (plugin.config.get(application, "subscribeEmail")) {
                // use the pres param
                plugin.set(plugin, "email", plugin.config.get(application, "subscribeEmail"));
            }
            else {
                // init to blank
                plugin.set(plugin, "email", "");
            }
        }
    });

    plugin.addLabels({
        "subscribeLink": "Subscribe to updates",
        "actionString": "Email address..."
    });

    plugin.subscribeLinkTemplate =
        '<div class="echo-stream-subscribeLinkWrapper echo-primaryFont">' +
                '<span class="echo-primaryFont echo-stream-subscribeLink echo-linkColor echo-clickable" style="font-weight:bold;font-size: 14px;" ><hr/>' +
                            plugin.label("subscribeLink") +
                    '<hr/></span>' +
        '</div>';

    plugin.subscribeFormTemplate =
        '<div class="echo-stream-subscribeFormWrapper echo-primaryFont">' +
                '<input type="text" class="echo-stream-subscribeFormEmail">&nbsp;' +
                '<button class="echo-stream-subscribeFormButton">Subscribe</button>' +
                '&nbsp;<span class="echo-stream-subscribeFormEmailLabel"></span>' +
        '</div>';

    plugin.subscribeResponseTemplate =
        '<div class="echo-stream-subscribeResponseWrapper echo-primaryFont">' +
                '<span>You have been subscribed</span>' +
        '</div>';

    plugin.subscribeFormWrapperRenderer = function (element, dom) {
        var application = this;

        // call the parent rendered
        application.parentRenderer("subscribeFormWrapper", arguments);

        // initialize the form to hidden
        element.hide();
    };

    plugin.subscribeResponseWrapperRenderer = function (element, dom) {
        var application = this;

        // call the parent rendered
        application.parentRenderer("subscribeResponseWrapper", arguments);

        // initialize the form to hidden
        element.hide();
    };

    plugin.subscribeLinkRenderer = function (element, dom) {
        var application = this;

        // call the parent rendered
        application.parentRenderer("subscribeLink", arguments);

        // bind to the click event
        element.bind("click", function () {
            // check to see if a user object exists first
            var user = new Echo.User({ "appkey": plugin.get(plugin, "appkey") });
            user.init();
            var account = user.getActiveAccounts();
            // hide the link
            $(this).hide();
            // determine whether to show the textbox or label for email
            var haveEmail = false;
            var email = plugin.get(plugin, "email");
            if (email == "") {
                // see if a user has an email address
                if (account.length && account[0].emails) {
                    $.each(account[0].emails, function (id, data) {
                        if (data.primary == "true") {
                            email = data.value;
                            plugin.set(plugin, "email", email);
                            haveEmail = true;
                        }
                    });
                }
            }
            else {
                haveEmail = true;
            }
            if (haveEmail == true) {
                //show the label
                $(document).find(".echo-stream-subscribeFormEmailLabel").show();
                $(document).find(".echo-stream-subscribeFormEmailLabel").text(email);
                $(document).find(".echo-stream-subscribeFormEmail").hide();
            }
            else {
                // show the textbox
                $(document).find(".echo-stream-subscribeFormEmailLabel").hide();
                $(document).find(".echo-stream-subscribeFormEmail").show();
            }
            // show the form
            $(document).find(".echo-stream-subscribeFormWrapper").show();
        });
    };

    plugin.subscribeFormEmailRenderer = function (element, dom) {
        var application = this;
        element.iHint({
            "text": plugin.label("actionString"),
            "className": "echo-secondaryColor"
        });
    };

    plugin.subscribeFormButtonRenderer = function (element, dom) {
        var application = this;

        // we should call existing renderer so as not to break things
        application.parentRenderer("subscribeFormButton", arguments);

        element.bind("click", function () {
            var query = plugin.get(plugin, "query");

            if (!query) return;

            // Setup the params object
            var email = plugin.get(plugin, "email");
            if (email == "") {
                email = $(document).find(".echo-stream-subscribeFormEmail");
            }
            else {
                email = $(document).find(".echo-stream-subscribeFormEmailLabel");
            }
            // check to see the email is valid
            var rxEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            if (rxEmail.test(email.val())) {
                var hurl = $(location).attr("href");
                var hname = $(document).attr("title");
                var cmd = "subscribe";
                var params = {
                    "query": query,
                    "appkey": application.config.get("appkey"),
                    "email": email.val(),
                    "cmd": cmd,
                    "hurl": hurl,
                    "hname": hname
                };
                // $.get function will send the HTTP GET request to the URL
                // specified in the first argument, the "params" object contains
                // the necessary GET parameters
                $.get("http://api.yotify.com/echo", params, function (data) {
                    // HTTP request callback function,
                    // which can be used for example to close the subscription form
                }, "jsonp");
                // close the form
                $(document).find(".echo-stream-subscribeFormWrapper").hide();
                // show the confirmation
                $(document).find(".echo-stream-subscribeResponseWrapper").show();

                // This function will be called as soon as the visitor clicks
                // on the notification preferences control.
                // You should extend this function and insert the necessary logics here
            }
            else {
                alert("Please enter a valid email address");
            }
        });
    };

})(jQuery);

