﻿(function ($) {

    function setupDialog(lnk) {
        var landing = lnk.attr("data-landing"),
            cssClass = lnk.attr("data-dialog-class"),
            width = 350,
            height = 450,
            padding,
            popup = $("<div></div>").appendTo("body").attr("id", "SignIn-Dialog")
                    .append("<iframe src='about:blank' width='" + width + "' height='" + height +
                            "' name='SignInWindow' id='SignInWindow' frameborder='0' marginheight='0' marginwidth='0' scrolling='no'></iframe>");

        padding = { top: parseInt(popup.css("padding-top"), 10), right: parseInt(popup.css("padding-right"), 10),
            bottom: parseFloat(popup.css("padding-bottom"), 10), left: parseInt(popup.css("padding-left"), 10)
        };

        height += ((isNaN(padding.top) ? 0 : padding.top) + (isNaN(padding.bottom) ? 0 : padding.bottom));
        width += ((isNaN(padding.left) ? 0 : padding.left) + (isNaN(padding.right) ? 0 : padding.right));

        return popup.dialog({
            autoOpen: false,
            bgiframe: true,
            modal: true,
            title: "Sign In",
            closeOnEscape: true,
            width: width + 30, // TODO: Refactor to account for padding and border
            minHeight: height,
            position: "center",
            dialogClass: cssClass,
            zIndex: 2000000 // So ads can be hidden
        });
    }

    function setupLoginDialog(lnk) {
        var url = lnk.attr("href"),
            popupUrl = lnk.attr("data-popup-url");

        if (popupUrl) {
            url = popupUrl;
        }

        if (url) {
            lnk.removeAttr("href").css("cursor", "pointer").click(function () {
                var popup = $("#SignIn-Dialog"), iframe, iframeSrc;
                if (!popup.length) {
                    popup = setupDialog(lnk);
                }

                iframe = popup.find('iframe');
                iframeSrc = iframe.attr("src");

                // Make sure iframe is blank so user doesn't see previous page
                iframe.attr("src", '');

                // Delay to ensure IFRAME is ready to load
                setTimeout(function () {
                    iframe.attr("src", url);
                    popup.dialog("open");
                    $('.ui-widget-overlay').click(function () { popup.dialog('close'); });
                }, 50);
            });
        }
    }

    function setupMemberCentreOptions(mbrLnk) {
        var options = mbrLnk.parents(".signed-in").find("ul"),
            hoverHandler = function (state) {
                return function (ev) {
                    var t = $(ev.target), rt = $(ev.relatedTarget);

                    if (state === "show") {
                        options.show();
                    } else {
                        if (!t.is(options) && !rt.is(mbrLnk)) {
                            options.hide();
                        }
                    }
                };
            };
        mbrLnk.hover(hoverHandler("show"), hoverHandler("hide"));
        options.hover(hoverHandler("show"), hoverHandler("hide"));
    }

    function setGreetingName(mbrLnk, serviceUrl) {
        var c = $(mbrLnk);
        var url = serviceUrl;

        if (url.length == 0) {
            return;
        }

        url = url + "&t=" + (new Date()).getTime();

        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'jsonp',
            contentType: 'application/json; charset=utf-8',

            success: function (result) {
                if (result != null && result.length > 0) {
                    // temporary thing: remove <span class=""signed-in-arrow"">&nbsp;</span> from the greeting name
                    // it needs to be removed when A/B testing on login modules (i.e. new and old top nav) is done
                    var index = (result).indexOf(" <span");
                    if (index > 0) // no need to check for 0 here because the it would mean 
                    // the greeting name is empty and we don't want to update the control in this case
                    {
                        result = result.substring(0, index);
                    }
                    c.html(result);
                }
            }
        });
    }

    $.extend({
        csn_login: function (args) {
            var signinLink = $(args.signInLink),
                joinLink = $(args.joinLink),
                mbrLnk = $(args.memberCentreLink),
                memberCentreGreetingCtrl = $(args.memberCentreGreetingCtrl),
                memberNameAjaxCallUrl = args.memberNameAjaxCallUrl,
                ignoreSignInVisibility = args.ignoreSignInVisibility;

            if ((signinLink.is(":visible") || ignoreSignInVisibility) && signinLink.length) {
                setupLoginDialog(signinLink);
            }
            if (joinLink.is(":visible") && joinLink.length) {
                setupLoginDialog(joinLink);
            }
            if (memberCentreGreetingCtrl.is(":visible")) {
                if (mbrLnk) setupMemberCentreOptions(mbrLnk);
                setGreetingName(memberCentreGreetingCtrl, memberNameAjaxCallUrl);
            }
        }
    });

} (jQuery));
