//This check is incase miniprofile.js gets loaded twice things won't be reset
if ($MP == undefined) {
    //Create MiniProfile Namespace
    var $MP = TGN.namespace("TGN.Ancestry.Community.MiniProfile");
    if ('undefined' == typeof _YDom) _YDom = YAHOO.util.Dom;

    //This is a global reference to the instance of MiniProfile and the container for the mini-profile
    $MP.miniProfile = null;
    $MP.miniProfileContainer = null;
    $MP.miniProfileBody = null;
    $MP.knub = null;

    $MP.Init = function() {
        this.isFireFox = false;
        this.height = 280;
        this.width = 370;
        if (navigator.userAgent.indexOf("Firefox") != -1) {
            this.isFireFox = true;
            this.height = 260;
        }
    };

    //$MP.timeout = null;
    //I keep an array of below profile objects so that I can cache them on the page
    $MP.profiles = null;

    $MP.Profile = function(ucdmid, miniProfile) {
        this.ucdmid = ucdmid;
        this.miniProfile = miniProfile;
    };

    //custom events
    $MP.miniProfileLoaded = new YAHOO.util.CustomEvent("miniProfileLoaded");
    $MP.miniProfileClosed = new YAHOO.util.CustomEvent("miniProfileClosed");

    $MP.currentRequest = null;
    $MP.currentRequestId;
    //The required data for this function is ucdmid, and unique id used for the DOM
    //It would be nice to have the photoId but not required
    //Object: ucdmid, bcontextType, contextValue, id
    $MP.showMiniProfile = function(obj) {
        var contextValue = "";
        var contextType = 0;
        var showContactModal = true;
        if (undefined != obj.contextType)
            contextType = obj.contextType;
        if (undefined != obj.contextValue)
            contextValue = obj.contextValue;
        if (undefined != obj.showContactModal)
            showContactModal = obj.showContactModal;

        $MP.currentRequestId = obj.id;
        if ($MP.miniProfile == null) {
            $MP.miniProfile = new $MP.Init();
            if ($MP.profiles == null)
                $MP.profiles = new Array();
        }

        YAHOO.util.Event.addListener(document, "click", $MP.close);

        var loading = '<div class="un_content" style="background:white;height:50px;padding:25px 30px 25px 100px;"><img src="http://c.mfcreative.com/lib/TGN/Ancestry/Community/i/loading.gif"/></div>';
        $MP.showPanel(loading);

        //check to see if the current userHandle is already on the client if not then make an ajax request to get the profile information
        for (i = 0; i < $MP.profiles.length; i++) {
            if ($MP.profiles[i].ucdmid == obj.ucdmid) {
                $MP.showPanel($MP.profiles[i].miniProfile, obj.id);
                return;
            }
        }

        var scopeOjbect = function(p1, p2) {
            this.ucdmid = p1;
            this.id = p2;
        };

        // report any tracking context to omniture
        var ufc = $MP.getContextValue(contextValue, "o_ufc");
        var cvc = $MP.getContextValue(contextValue, "o_cvc");
        if (ufc != null || cvc != null) {
            var s = s_gi(s_account, 1);
            if (ufc != null) s.prop20 = ufc;
            if (cvc != null) s.prop21 = cvc;
            s.tl();
        }

        //
        $MP.currentRequest = new TGN.Util.AjaxRequest("POST", "/community.ashx", "", { success: $MP.success, failure: $MP.failure, scope: new scopeOjbect(obj.ucdmid, obj.id), timeout: 20000 }, "f=GetMiniProfile&rurl=" + escape(window.location) + "&uid=" + obj.ucdmid + "&ctxT=" + contextType + "&ctxV=" + escape(contextValue) + "&showContactModal=" + showContactModal);
        $MP.currentRequest.invoke();
    };

    $MP.getContextValue = function(ctv, key) {
        var re = new RegExp("(^|[&])" + key + "=([^&]*)", "i");
        var results = re.exec(ctv);
        if (results == null) return null;
        return unescape(results[2]);
    };

    $MP.cacheDomain = "http://c.mfcreative.com";
    $MP.userDocDomain = "http://userdoc.ancestry.com";

    $MP.GetUserLink = function(obj) {
        var userLink = "";

        var ucdmid = "";
        if (obj.ucdmid != undefined)
            ucdmid = obj.ucdmid;
        var displayName = "";
        if (obj.displayName != undefined)
            displayName = obj.displayName;
        var id = "";
        if (obj.id != undefined)
            id = obj.id;
        var photoId = "";
        if (obj.photoId != undefined)
            photoId = obj.photoId;
        var macId = "";
        if (obj.macId != undefined)
            macId = obj.macId;
        var showAvatar = true;
        if (obj.showAvatar != undefined)
            showAvatar = obj.showAvatar;
        if (obj.userDocDomain != undefined)
            $MP.userDocDomain = obj.userDocDomain;
        var context = "";
        if (obj.contextType != undefined)
            context += ",contextType:" + obj.contextType;
        if (obj.contextValue != undefined)
            context += ",contextValue:'" + obj.contextValue + "'";

        if (ucdmid.length > 0 && displayName.length > 0 && id.length > 0) {
            var config = "{type:'miniprofile',onSuccess:function(config){$MP.showMiniProfile(config);},ucdmid:'" + ucdmid + "',id:'" + id + "'" + context + "}";
            userLink = "<a id=\"ul_" + id + "\" class=\"uLink\" href=\"javascript:$Anc.load(" + config + ");\">";
            if (showAvatar) {
                if (photoId.length > 0 && macId.length > 0 && photoId != "ffffffff-ffff-ffff-ffff-ffffffffffff")
                    userLink += "<img height=\"20\" width=\"15\" src=\"" + $MP.userDocDomain + "/userdocstore/download.ashx?fileid=" + photoId + "&mac=" + macId + "\"/>";
                else
                    userLink += "<img height=\"20\" width=\"15\" src=\"" + $MP.cacheDomain + "/lib/TGN/shared/assets/images/usericon_small.gif\"/>";
                userLink += "&nbsp;";
            }
            userLink += "<span>" + displayName + "</span>";
            userLink += "</a>";
        }
        return userLink;
    };

    $MP.showPanel = function(content) {
        //if this is the first time then load miniprofile in the DOM
        if (null == $MP.miniProfileContainer)
            $MP.loadMiniProfileInDOM();

        $MP.miniProfileContainer.style.display = "block";

        $MP.miniProfileBody.innerHTML = content;
        //Make sure display attribute is set to "block" before any positioning is assigned,
        //Positioning doesn't seem to apply correctly until this attribute is set
        //$MP.miniProfile.width = $MP.miniProfileContainer.clientWidth;
        //_YDom.setStyle($MP.miniProfileContainer, "width", $MP.miniProfile.width + "px");
        $MP.SetPosition();

        //$MP.myLink.panel.show();

        //fire event stating that the mini-profile has been displayed
        $MP.miniProfileLoaded.fire();
    };

    $MP.loadMiniProfileInDOM = function() {
        //Create the div for the miniprofile and add it to the DOM
        $MP.miniProfileContainer = document.createElement("div");
        $MP.miniProfileContainer.id = "miniProfile";
        _YDom.setStyle($MP.miniProfileContainer, "width", $MP.miniProfile.width + "px");
        //_YDom.setStyle($MP.miniProfileContainer, "width", "auto");
        _YDom.setStyle($MP.miniProfileContainer, "height", "auto");
        _YDom.setStyle($MP.miniProfileContainer, "position", "absolute");
        //Add the children to container
        var div = document.createElement("div");
        div.id = "mp_knub";
        $MP.miniProfileContainer.appendChild(div);
        div = document.createElement("div");
        div.id = "mp_knub_r";
        $MP.miniProfileContainer.appendChild(div);
        var el = document.createElement("a");
        el.id = "un_close";
        _YDom.setAttribute(el, "href", "javascript:$MP.captureClick();");
        var img = document.createElement("img");
        img.id = "close_button";
        _YDom.setAttribute(img, "src", "http://c.mfcreative.com/lib/TGN/Ancestry/Community/i/close.gif");
        el.appendChild(img);
        $MP.miniProfileContainer.appendChild(el);
        $MP.miniProfileBody = document.createElement("div");
        $MP.miniProfileContainer.appendChild($MP.miniProfileBody);
        document.body.appendChild($MP.miniProfileContainer);
    };

    $MP.success = function(o, scope) {
        $MP.currentRequest = null;

        var i;
        var found = false;
        for (i = 0; i < $MP.profiles.length; i++) {
            if ($MP.profiles[i].ucdmid == scope.ucdmid)
                found = true;
        }
        //add it to the array if it's not already in there
        if (!found)
            $MP.profiles[$MP.profiles.length] = new $MP.Profile(scope.ucdmid, o.responseText);

        //If another request has been fired off since this one then still add it to the cache but don't display it
        if (scope.id == $MP.currentRequestId)
            $MP.showPanel(o.responseText);
    };

    $MP.failure = function(o, scope) {
        $MP.currentRequest = null;

        //If another request has been fired off since this one then ignore this request and return
        if (scope.id != $MP.currentRequestId) return;
        var errorText = "We're sorry. We were unable to retrieve the requested profile.<br>Please click the close button and try again.";
        var html = '<div class="un_content" style="background:white;padding:25px 10px 25px 10px;">' + errorText + '</div>';
        $MP.showPanel(html);
    };

    $MP.SetPosition = function() {
        //This is the element in which to align the mini-profile to
        var el = _YDom.get("ul_" + $MP.currentRequestId);
        var xy = _YDom.getXY(el);
        var documentHeight = _YDom.getViewportHeight();
        var documentWidth = _YDom.getViewportWidth();
        //We need to get the space above and below x in order to decide how to position
        //the mini-profile
        var scrollTopOffset = _YDom.getDocumentScrollTop(document);
        var topSpace = xy[1] - scrollTopOffset;
        var bottomSpace = documentHeight - topSpace;
        //Decide if the mini-profile will go left or right of the element
        var leftSpace = xy[0];
        var rightSpace = documentWidth - (leftSpace + el.clientWidth);
        var knubWidth = 20;
        if (topSpace > bottomSpace) {
            _YDom.setY($MP.miniProfileContainer, xy[1] - ($MP.miniProfileContainer.clientHeight - 40));
        }
        else {
            _YDom.setY($MP.miniProfileContainer, xy[1] - 30);
        }
        //If the mini-profile won't fit on either the right or left space then just put it to the right
        var showRight = false;
        if (rightSpace > $MP.miniProfile.width)
            showRight = true;
        else if (leftSpace > $MP.miniProfile.width) {
            _YDom.setStyle(_YDom.get("mp_knub"), "display", "none");
            $MP.knub = _YDom.get("mp_knub_r");
            _YDom.setStyle($MP.knub, "display", "block");
            _YDom.setX($MP.miniProfileContainer, xy[0] - ($MP.miniProfile.width + knubWidth + 3));
            _YDom.setX($MP.knub, _YDom.getX($MP.miniProfileContainer) + $MP.miniProfile.width + 3);
            _YDom.setStyle($MP.knub, "top", "20px");
        }
        else
            showRight = true;

        if (showRight) {
            _YDom.setStyle(_YDom.get("mp_knub_r"), "display", "none");
            $MP.knub = _YDom.get("mp_knub");
            _YDom.setStyle($MP.knub, "display", "block");
            _YDom.setX($MP.miniProfileContainer, xy[0] + el.offsetWidth + (knubWidth - 5));
            _YDom.setX($MP.knub, xy[0] + el.offsetWidth);
        }
        _YDom.setY($MP.knub, xy[1] - 5);
        /*  Animation code that we are holding off on right now
        if (!$MP.miniProfile.isFireFox) {
        _YDom.setStyle(_YDom.get("un_close"), "display", "block");
        }
        var anim = new YAHOO.util.Anim($MP.miniProfileContainer, { opacity: { to: 1} }, 1.5, YAHOO.util.Easing.easeOutStrong);
        anim.animate();
        */
    };

    $MP.captureClick = function(o) {
        //This is basically a function that does nothing. I just needed a dead end for when the close button is clicked,
        //the close button will pick up the event and close the panel
    };

    $MP.close = function(o) {
        var browser = navigator.userAgent;
        var panelXY = _YDom.getXY($MP.miniProfileContainer);
        var minX = panelXY[0];
        var maxX = panelXY[0] + $MP.miniProfileContainer.clientWidth;
        var minY = panelXY[1];
        var maxY = panelXY[1] + $MP.miniProfileContainer.clientHeight;

        var elX;
        var elY;
        //Use page property for firefox
        if ($MP.miniProfile.isFireFox) {
            elX = o.pageX;
            elY = o.pageY;
        }
        else {
            elX = o.clientX;
            elY = o.clientY;
        }

        var userLinkClicked = false;
        var target;
        if ($MP.miniProfile.isFireFox)
            target = o.target;
        else
            target = o.srcElement;
        if (!userLinkClicked) {
            if ((elY >= maxY || elY <= minY) || (elX >= maxX || elX <= minX) || target.id == "close_button" || target.className == "contactLink") {
                $MP.miniProfileContainer.style.display = "none";
                /*  Animation code that we are holding off on right now
                var anim = new YAHOO.util.Anim($MP.miniProfileContainer, { opacity: { to: 0} }, 1.5, YAHOO.util.Easing.easeOutStrong);
                anim.onComplete.subscribe($MP.hideContainer);
                We need to hide the knub and the close button because in IE the images don't fade away
                if (!$MP.miniProfile.isFireFox) {
                _YDom.setStyle($MP.knub, "display", "none");
                _YDom.setStyle(_YDom.get("un_close"), "display", "none");
                }
                anim.animate();
                */
                YAHOO.util.Event.removeListener(document, "click", $MP.close);
                //fire event stating the miniprofile has been closed
                $MP.miniProfileClosed.fire();
                //abort the request if use has closed the panel before the request has come back
                if (null != $MP.currentRequest)
                    $MP.currentRequest.abort(false);
            }
        }
    };

    $MP.hideContainer = function() {
        $MP.miniProfileContainer.style.display = "none";
    };

    $MP.flushProfile = function(ucdmid) {
        try {
            if ($MP.profiles != null) {
                var i;
                var profile;
                for (i = 0; i < $MP.profiles.length; i++) {
                    profile = $MP.profiles[i];
                    if (profile.ucdmid == ucdmid) {
                        profile.ucdmid = "";
                        profile.miniProfile = "";
                    }
                }
            }
        }
        catch (e) { }
    };

    $MP.onBlockUser = new YAHOO.util.CustomEvent("onBlockUser");
    $MP.onUnBlockUser = new YAHOO.util.CustomEvent("onBlockUser");
    $MP.blockUser = function(params) {
        var f;
        if (params.block)
            f = "BlockUser";
        else
            f = "UnBlockUser";
        var scope = { block:params.block, blockLinkContainerId: params.blockLinkContainerId, contactLinkContainerId: params.contactLinkContainerId };
        var request = new TGN.Util.AjaxRequest("GET", "/community.ashx", "f=" + f + "&bId=" + params.bid + "&bcId=" + params.blockLinkContainerId + "&ccId=" + params.contactLinkContainerId + "&view=" + params.view + "&uid=" + params.ucdmid, { success: $MP.BlockUser_Success, failure: $MP.fail, scope: scope }, "");
        request.invoke();
    };
    $MP.BlockUser_Success = function(o, scope) {
        var json;
        try {
            json = eval("(" + o.responseText + ")");
            if (json.success) {
                var otherText = "";
                if (json.otherText != undefined)
                    otherText = json.otherText + " ";
                _YDom.get(scope.blockLinkContainerId).innerHTML = otherText + "<a href=\"" + json.linkUrl + "\">" + json.linkText + "</a>";
                if (json.hideContactLink)
                    _YDom.setStyle(scope.contactLinkContainerId, "display", "none");
                else
                    _YDom.setStyle(scope.contactLinkContainerId, "display", "block");
                $MP.flushProfile(json.blockedId);
                if (scope.block)
                    $MP.onBlockUser.fire({});
                else
                    $MP.onUnBlockUser.fire({});
            }
        }
        catch (e) {
            alert(e);
        }
    };

    $MP.Callback_BlockUser = {
        success: $MP.BlockUser_Success,
        failure: $MP.fail
    };
}
