/* ---------------------------------------------------------------------

MemberToMember User Info Popup Functionality
Written by SusQtech
www.susqtech.com

* requires jQuery 1.3.2 or later
* http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js

--------------------------------------------------------------------- */

// Attach popup to links with this string in the HREF attribute
var userInfoLinkBase = "/_layouts/community/profile/default.aspx?accountname=";
// Also attach popup to this link. This could be done with an array to allow multiple values, but this quick fix just uses a second variable.
var userInfoLinkBase2 = "/Profile/Pages/default.aspx?accountname=";

// Web services URL
var userInfoPopupWebService = "/_layouts/community/readonlywebservices/PeoplePickerService.asmx/GetPeopleByLoginName";

// Distance (in pixels) box appears from mouse cursor (X-axis movement)
var distanceFromMouseCursor = 10;

// Time it takes to show/hide the popup (on hover/leave)
var timeBeforeUserPopupAppears = 500;
var timeBeforeUserPopupDisappears = 500;
var popProfileShowTimer = setTimeout('void(0);', 0);
var popProfileHideTimer = setTimeout('void(0);', 0);

// Is profile popup currently displayed?
var isPopProfileDisplayed = false;

// Default image paths
var defaultProfileImage = "/SQTComm_Images/profile-default.png";
var loadingProfilePath = "/_layouts/community/profile/scripts/images/loading.gif";

// Details Visibility
var socialDistanceVisibility = "true";
var myColleaguesVisibility = "false";
var reputationVisibility = "false";

$(document).ready(function() {
    // add place holder div for the popup
    if ($("form:eq(0)") != null) {
        $("form:eq(0)").prepend("<div class=\"UserProfilePopupWrapper\"><div class=\"UserProfilePopup\"></div><div class=\"UserProfilePopupWrapperBottom\"></div></div>");

        $('.UserProfilePopupWrapper').mouseover(function() {
            clearTimeout(popProfileHideTimer);
        });
        $('.UserProfilePopupWrapper').mouseout(function() {
            popProfileHideTimer = setTimeout('hideProfilePopup();', timeBeforeUserPopupDisappears);
        });

        // Add popup to each user profile link
        // This could be done more expandible by using an array of links instead of these 2 variables, but this is the quick fix.
        $("a[href*='" + userInfoLinkBase + "']").each(function() {
            wirePopup($(this), userInfoLinkBase);
        });
        $("a[href*='" + userInfoLinkBase2 + "']").each(function() {
            wirePopup($(this), userInfoLinkBase2);
        });
    }
});

// function to wire up the hover-over user info popup to an href that includes the given userLink string
function wirePopup(el, userLink) {
    el.attr('title', '');
    el.mouseover(function(e) {
        clearTimeout(popProfileHideTimer);
        var mouseX = e.pageX;
        var mouseY = e.pageY;
        // changed for links with full url, not relatvie to the base
        var baseIndex = el.attr("href").indexOf(userLink);
        // if the base has text to the left then remove it
        var userName = "";
        if (baseIndex > 0) {
            userName = el.attr("href").replace(el.attr("href").substring(0, baseIndex + userLink.length), "");
        }
        else {
            userName = el.attr("href").replace(userLink, "");
        }

        if (userName.toLowerCase() != mtmCurrentUserName.toLowerCase()) // only show the popup for other profiles
        {
            userName = userName.replace("\\", "\\\\"); // replace \ with \\ for NT accounts
            popProfileShowTimer = setTimeout(function() { showProfilePopup(userName, mouseX, mouseY); }, timeBeforeUserPopupAppears);
        }
    });  // end .mouseover function
    el.mouseout(function() {
        clearTimeout(popProfileShowTimer);
        popProfileHideTimer = setTimeout(hideProfilePopup, timeBeforeUserPopupDisappears);
    }); // end .mouseout function

}

var showProfilePopup = (function() {
    var cache = {};
    return function(username, posX, posY) {
        var success = function(data) {
            cache[username] = data;
            $('.UserProfilePopupWrapper .UserProfilePopup').empty();
            $(data).find('Person').each(function() {
                var Username = $(this).find('Username').text();
                var DisplayName = $(this).find('DisplayName').text();
                var Title = $(this).find('Title').text();
                Title = jQuery.trim(Title);
                var Location = $(this).find('Location').text();
                Location = jQuery.trim(Location);
                var ImageUrl = $(this).find('ImageURL').text();
                var IsColleague = $(this).find('IsColleague').text();
                var Organization = $(this).find('Organization').text();
                Organization = jQuery.trim(Organization);
                var ColleagueCount = $(this).find('ColleagueCount').text();
                var SocialDistance = $(this).find('SocialDistance').text();
                var ReputationTitle = $(this).find('ReputationTitle').text();
                var ReputationImgUrl = $(this).find('ReputationImgUrl').text();

                var profilePopNameDiv = $('<div class="UserProfileName">' + DisplayName + '</div>');
                var titleOrgText = "";
                if (Title != "") {
                    titleOrgText += Title;
                }
                if (Organization != "" && Title != "") {
                    titleOrgText += ", ";
                }
                if (Organization != "") {
                    titleOrgText += Organization;
                }

                var profilePopTitleDiv = $('<div class="UserProfileTitle">' + titleOrgText + '</div>');

                // show default or users profile image
                var profilePopImgDiv = $('<div class="UserProfileImage"/>');
                if (ImageUrl == "") {
                    var profilePopImg = $('<img src="' + defaultProfileImage + '" alt="' + DisplayName + '" />');
                }
                else {
                    var profilePopImg = $('<img src="' + ImageUrl + '" alt="' + DisplayName + '" />');
                }
                $(profilePopImg).appendTo(profilePopImgDiv);

                var profilePopLinksDiv = $('<div class="UserProfileShortcuts"/>');

                if (mtmCurrentUserName != "") {
                    var profilePopContactLink = $('<a href="javascript:void(0);" onclick="mtmShowDialog(\'message\', \'' + Username + '\', \'' + DisplayName + '\')" >Contact</a>');
                    $(profilePopContactLink).appendTo(profilePopLinksDiv);


                    // conditionally show add as colleague
                    if (IsColleague != "true") {
                        $(profilePopLinksDiv).html($(profilePopLinksDiv).html() + '&nbsp;|&nbsp;<a href="javascript:void(0);" onclick="mtmShowDialog(\'colleague\', \'' + Username + '\', \'' + DisplayName + '\')" >Add Colleague</a>');
                    }
                }
                else {
                    $(profilePopLinksDiv).html($(profilePopLinksDiv).html() + '<br>');
                }

                // display/don't display social distance
                if (socialDistanceVisibility == "true") {
                    var socialDistanceDiv = $('<div class="socialDistance-' + SocialDistance + '" title="How we\'re connected"></div>');
                }
                else {
                    var socialDistanceDiv = '';
                }

                // display/don't display myColleagues
                if (myColleaguesVisibility == "true") {
                    var myColleaguesDiv = $('<div class="UserProfileColleagueCount"><img src="/SQTComm_Images/icon_colleagues.png" border="0" title="How many colleagues I have" /><a href="/_layouts/community/profile/colleagues.aspx?accountname=' + Username + '" >' + ColleagueCount.toString() + '</a></div>');
                }
                else {
                    var myColleaguesDiv = '';
                }

                // display/don't display user Reputation
                if (reputationVisibility == "true" && ReputationImgUrl != '') {
                    var reputationDiv = $('<div class="reputation"><img src="' + ReputationImgUrl + '" title="' + ReputationTitle + '" /></div>');
                }
                else {
                    var reputationDiv = '';
                }

                // add to popup container
                $('.UserProfilePopupWrapper .UserProfilePopup').append(profilePopImgDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(profilePopNameDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(profilePopTitleDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(profilePopLinksDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(socialDistanceDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(myColleaguesDiv);
                $('.UserProfilePopupWrapper .UserProfilePopup').append(reputationDiv);
            });

            var popupHeight = $('.UserProfilePopupWrapper').height();
            var newYPos = Math.floor(posY - (popupHeight / 2));
            $('.UserProfilePopupWrapper').css('top', newYPos + 'px').css('left', (posX + distanceFromMouseCursor) + 'px');
            $('.UserProfilePopupWrapper').show();
            isPopProfileDisplayed = true;
        };

        try {
            if (cache[username])
                success(cache[username]);
            else {
                $.ajax({
                    url: userInfoPopupWebService,
                    type: "POST",
                    data: { 'loginName': username },
                    success: success,
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if (window.console && window.console.error) {
                            console.log('An Ajax error was thrown for ' + userInfoPopupWebService);
                            console.log("XMLHttpRequest.status=" + XMLHttpRequest.status);
                            console.log("textStatus=" + textStatus);
                            console.log("errorThrown=" + errorThrown);
                        }
                    }
                });
            }
        }
        catch (err) {
            if (window.console && window.console.error) {
                console.log("Error loading user info popup : " + err);
            }
        }
    };
})();

function hideProfilePopup() {
    $('.UserProfilePopupWrapper').hide();
    isPopupProfileDisplayed = false;
}

// Displays any ajax errors in the Firebug console instead of hiding them
$(document).ajaxError(function() {
    if (window.console && window.console.error) {
        console.error(arguments);
    }
});

